From ad111bcc22d439c4bc6d40333aa0db9f6c8e0d64 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Tue, 2 Jun 2026 14:51:20 +0100 Subject: [PATCH 01/78] ci: Patch binaries in nix-based images and test in every distro (#7376) Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- docker/check-tool-versions.sh | 24 +++++++ docker/install-sanitizer-libs.sh | 89 ++++++++++++++++++++++++ docker/nix.Dockerfile | 66 ++++++++++-------- docker/test_files/compile-cpp-sources.sh | 17 +++-- docker/test_files/run-test-binaries.sh | 44 +++++++++--- nix/packages.nix | 1 + 6 files changed, 196 insertions(+), 45 deletions(-) create mode 100755 docker/check-tool-versions.sh create mode 100755 docker/install-sanitizer-libs.sh diff --git a/docker/check-tool-versions.sh b/docker/check-tool-versions.sh new file mode 100755 index 0000000000..db20be45e4 --- /dev/null +++ b/docker/check-tool-versions.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# Verify that every tool expected in the Nix CI env is present and runnable. +set -euo pipefail + +ccache --version +clang --version +clang++ --version +clang-format --version +cmake --version +conan --version +g++ --version +gcc --version +gcovr --version +git --version +less --version +make --version +mold --version +ninja --version +perl --version +pkg-config --version +pre-commit --version +python3 --version +run-clang-tidy --help +vim --version diff --git a/docker/install-sanitizer-libs.sh b/docker/install-sanitizer-libs.sh new file mode 100755 index 0000000000..a28efeab3f --- /dev/null +++ b/docker/install-sanitizer-libs.sh @@ -0,0 +1,89 @@ +#!/bin/bash +# Install sanitizer runtime libraries required to run binaries compiled with: +# -fsanitize=address → libasan.so.8 +# -fsanitize=thread → libtsan.so.2 +# -fsanitize=undefined → libubsan.so.1 +# +# The exact SONAMEs required depend on the compiler toolchain used to build the +# test binaries (see nix/ci-env.nix). If the toolchain is bumped and SONAMEs +# change, update the list below (or detect them from the binaries). +# +# Supported base images: +# debian:bookworm +# ubuntu:20.04 +# rhel:9 +# nixos/nix — tests are skipped; this script is not called + +set -euo pipefail + +if [ ! -f /etc/os-release ]; then + echo "ERROR: /etc/os-release not found; cannot detect OS" >&2 + exit 1 +fi + +# shellcheck source=/dev/null +. /etc/os-release + +echo "Detected OS: ${ID} ${VERSION_ID:-}" + +case "${ID}" in + debian) + apt-get update -y + apt-get install -y --no-install-recommends \ + libasan8 \ + libtsan2 \ + libubsan1 + + apt-get clean + rm -rf /var/lib/apt/lists/* + ;; + + ubuntu) + apt-get update -y + apt-get install -y --no-install-recommends \ + gnupg \ + software-properties-common + add-apt-repository -y ppa:ubuntu-toolchain-r/test + apt-get update -y + apt-get install -y --no-install-recommends \ + libasan8 \ + libtsan2 \ + libubsan1 + + apt-get clean + rm -rf /var/lib/apt/lists/* + ;; + + rhel | centos | rocky | almalinux) + dnf install -y \ + libasan8 \ + libtsan2 \ + libubsan + + dnf clean -y all + rm -rf /var/cache/dnf/* + ;; + + *) + echo "ERROR: unsupported OS '${ID}'. Supported: debian, ubuntu, rhel-family" >&2 + exit 1 + ;; +esac + +# Verify that every expected library is now resolvable by the dynamic linker. +missing=0 +for lib in libasan.so.8 libtsan.so.2 libubsan.so.1; do + if ldconfig -p | grep -q "${lib}"; then + echo "OK: ${lib} found" + else + echo "ERROR: ${lib} not found after installation" >&2 + missing=$((missing + 1)) + fi +done + +if [ "${missing}" -ne 0 ]; then + echo "ERROR: ${missing} library/libraries missing" >&2 + exit 1 +fi + +echo "All sanitizer runtime libraries installed successfully." diff --git a/docker/nix.Dockerfile b/docker/nix.Dockerfile index 3c5dbcb734..a0eab31769 100644 --- a/docker/nix.Dockerfile +++ b/docker/nix.Dockerfile @@ -32,7 +32,7 @@ FROM ${BASE_IMAGE} AS final ARG BASE_IMAGE # bash is not located at /bin/bash in nixos/nix, so we need to create a symlink to it. -RUN if [ -d /nix ]; then \ +RUN if echo "${BASE_IMAGE}" | grep -qiE 'nixos'; then \ ln -s /root/.nix-profile/bin/bash /bin/bash; \ fi @@ -65,38 +65,44 @@ if [ ! -e "${target}" ]; then fi EOF -RUN < function run() { @@ -18,27 +20,34 @@ function run() { out_file="$(mktemp)" echo "=== Run ${binary} ===" - local rc=0 - "${binary}" >"${out_file}" 2>&1 || rc=$? + set +e + "${binary}" >"${out_file}" 2>&1 + local rc=$? + set -e cat "${out_file}" + local failed=0 if [ "${expected_rc}" = "nonzero" ]; then if [ "${rc}" -eq 0 ]; then echo "ERROR: expected non-zero exit code from ${binary}, got ${rc}" >&2 - exit 1 + failed=1 fi elif [ "${rc}" -ne "${expected_rc}" ]; then echo "ERROR: expected exit code ${expected_rc} from ${binary}, got ${rc}" >&2 - exit 1 + failed=1 fi - grep -q "${expected_output}" "${out_file}" || - { - echo "ERROR: expected '${expected_output}' from ${binary}" >&2 - exit 1 - } - echo "OK: '${expected_output}' detected" + if ! grep -q "${expected_output}" "${out_file}"; then + echo "ERROR: expected '${expected_output}' from ${binary}" >&2 + failed=1 + fi + + if [ "${failed}" -eq 0 ]; then + echo "OK: '${expected_output}' detected" + else + failed_binaries+=("${binary}") + fi } declare -A expect=( @@ -52,6 +61,15 @@ declare -A expect=( for compiler in g++ clang++; do for name in regular asan tsan ubsan; do binary="${bins_dir}/${name}-${compiler}" + + if [ "${name}" = "tsan" ] && [ "${compiler}" = "g++" ] && + grep -qi 'debian' /etc/os-release 2>/dev/null && + [ "$(uname -m)" = "aarch64" ]; then + echo "=== Skipping ${binary} (tsan-g++ unsupported on Debian ARM64) ===" + echo " NOTE: to enable it, add --security-opt seccomp=unconfined to your docker run command" + continue + fi + if [ "${name}" = "regular" ]; then expected_rc=0 else @@ -60,3 +78,9 @@ for compiler in g++ clang++; do run "${binary}" "${expect[$name]}" "${expected_rc}" done done + +if [ "${#failed_binaries[@]}" -gt 0 ]; then + echo "ERROR: the following binaries failed:" >&2 + printf ' %s\n' "${failed_binaries[@]}" >&2 + exit 1 +fi diff --git a/nix/packages.nix b/nix/packages.nix index d209620a68..3d92fedb4b 100644 --- a/nix/packages.nix +++ b/nix/packages.nix @@ -15,6 +15,7 @@ in git gnumake llvmPackages_22.clang-tools + less # needed for git diff mold ninja patchelf From 225ed204ad101527c19f1f3c9a32fda1bd28761b Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Tue, 2 Jun 2026 19:12:09 +0200 Subject: [PATCH 02/78] test: Suppress invariant-failure logs in Vault and LoanBroker bug-regression tests (#7379) --- src/test/app/LoanBroker_test.cpp | 5 ++++- src/test/app/Vault_test.cpp | 26 ++++++++++++++++++-------- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/src/test/app/LoanBroker_test.cpp b/src/test/app/LoanBroker_test.cpp index 92949256fd..0edb955b90 100644 --- a/src/test/app/LoanBroker_test.cpp +++ b/src/test/app/LoanBroker_test.cpp @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -52,6 +53,7 @@ #include #include #include +#include #include #include #include @@ -1708,7 +1710,8 @@ class LoanBroker_test : public beast::unit_test::Suite Account const alice("alice"); auto const withFix = features[fixCleanup3_2_0]; - Env env(*this, features); + std::string logs; + Env env(*this, features, std::make_unique(&logs)); env.fund(XRP(100'000), issuer, alice); env.close(); diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index bf707afae9..2c83ad91ec 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -60,6 +61,7 @@ #include #include #include +#include #include #include #include @@ -6630,7 +6632,8 @@ class Vault_test : public beast::unit_test::Suite "fixed-asset amount with impaired loan"} + (withFix ? " (fixCleanup3_2_0)" : " (pre-fix)")); - Env env(*this, features); + std::string logs; + Env env(*this, features, std::make_unique(&logs)); auto const f = setupStuckDepositor(env); if (!f.vaultKeylet || !f.asset || f.sharesLender == 0) { @@ -6748,7 +6751,8 @@ class Vault_test : public beast::unit_test::Suite "burn is rejected while loss outstanding"} + (withFix ? " (fixCleanup3_2_0)" : " (pre-fix)")); - Env env(*this, features); + std::string logs; + Env env(*this, features, std::make_unique(&logs)); auto const f = setupStuckDepositor(env); if (!f.vaultKeylet || f.sharesLender == 0) { @@ -7074,7 +7078,8 @@ class Vault_test : public beast::unit_test::Suite using namespace test::jtx; auto runScenario = [this](FeatureBitset features, TER expected) { - Env env(*this, features); + std::string logs; + Env env(*this, features, std::make_unique(&logs)); Account const issuer{"issuer"}; Account const alice{"alice"}; @@ -7150,7 +7155,8 @@ class Vault_test : public beast::unit_test::Suite using namespace test::jtx; auto runScenario = [this](FeatureBitset features, TER expected) { - Env env(*this, features); + std::string logs; + Env env(*this, features, std::make_unique(&logs)); Account const issuer{"issuer"}; Account const alice{"alice"}; @@ -7226,7 +7232,8 @@ class Vault_test : public beast::unit_test::Suite enum class DestKind : bool { ThirdParty = false, Self = true }; auto runScenario = [this](FeatureBitset features, DestKind destKind, TER expected) { - Env env(*this, features); + std::string logs; + Env env(*this, features, std::make_unique(&logs)); Account const issuer{"issuer"}; Account const alice{"alice"}; @@ -7331,7 +7338,8 @@ class Vault_test : public beast::unit_test::Suite using namespace test::jtx; auto runScenario = [this](FeatureBitset features, TER expected) { - Env env(*this, features); + std::string logs; + Env env(*this, features, std::make_unique(&logs)); Account const issuer{"issuer"}; Account const alice{"alice"}; @@ -7414,7 +7422,8 @@ class Vault_test : public beast::unit_test::Suite { using namespace test::jtx; auto runScenario = [this](FeatureBitset features, TER expected) { - Env env(*this, features); + std::string logs; + Env env(*this, features, std::make_unique(&logs)); Account const issuer{"issuer"}; Account const alice{"alice"}; @@ -7489,7 +7498,8 @@ class Vault_test : public beast::unit_test::Suite using namespace test::jtx; auto runScenario = [this](FeatureBitset features, TER expected) { - Env env(*this, features); + std::string logs; + Env env(*this, features, std::make_unique(&logs)); Account const issuer{"issuer"}; Account const owner{"owner"}; From 1441d4690d91cf047704af27cca0381269c8b17e Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 3 Jun 2026 01:16:02 +0100 Subject: [PATCH 03/78] chore: Update flake.lock to allow conan with clang-22 support (#7390) --- flake.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/flake.lock b/flake.lock index 3149f3feed..2013cfabd4 100644 --- a/flake.lock +++ b/flake.lock @@ -2,11 +2,11 @@ "nodes": { "nixpkgs": { "locked": { - "lastModified": 1777954456, - "narHash": "sha256-hGdgeU2Nk87RAuZyYjyDjFL6LK7dAZN5RE9+hrDTkDU=", + "lastModified": 1780243769, + "narHash": "sha256-x5UQuRsH3MqI0U9afaXSNqzTPSeZlRLvFAav2Ux1pNw=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "549bd84d6279f9852cae6225e372cc67fb91a4c1", + "rev": "331800de5053fcebacf6813adb5db9c9dca22a0c", "type": "github" }, "original": { From 96b2c0964f0d19f48853fd3fcec362e9bfba5d60 Mon Sep 17 00:00:00 2001 From: Bart Date: Wed, 3 Jun 2026 11:34:19 -0400 Subject: [PATCH 04/78] refactor: Replace `intr_ptr::SharedPtr` by `SHAMapTreeNodePtr` (#7396) Co-authored-by: Bart <11445373+bthomee@users.noreply.github.com> --- include/xrpl/shamap/SHAMap.h | 57 ++++++++----------- .../xrpl/shamap/SHAMapAccountStateLeafNode.h | 2 +- include/xrpl/shamap/SHAMapInnerNode.h | 16 +++--- include/xrpl/shamap/SHAMapTreeNode.h | 15 +++-- include/xrpl/shamap/SHAMapTxLeafNode.h | 2 +- .../xrpl/shamap/SHAMapTxPlusMetaLeafNode.h | 2 +- include/xrpl/shamap/TreeNodeCache.h | 2 +- include/xrpl/shamap/detail/TaggedPointer.h | 4 +- include/xrpl/shamap/detail/TaggedPointer.ipp | 38 ++++++------- src/libxrpl/shamap/SHAMap.cpp | 57 ++++++++----------- src/libxrpl/shamap/SHAMapDelta.cpp | 7 +-- src/libxrpl/shamap/SHAMapInnerNode.cpp | 26 +++++---- src/libxrpl/shamap/SHAMapSync.cpp | 8 +-- src/libxrpl/shamap/SHAMapTreeNode.cpp | 10 ++-- 14 files changed, 115 insertions(+), 131 deletions(-) diff --git a/include/xrpl/shamap/SHAMap.h b/include/xrpl/shamap/SHAMap.h index f63fc95b27..32e87b64c6 100644 --- a/include/xrpl/shamap/SHAMap.h +++ b/include/xrpl/shamap/SHAMap.h @@ -85,7 +85,7 @@ private: /** The sequence of the ledger that this map references, if any. */ std::uint32_t ledgerSeq_ = 0; - intr_ptr::SharedPtr root_; + SHAMapTreeNodePtr root_; mutable SHAMapState state_; SHAMapType const type_; bool backed_ = true; // Map is backed by the database @@ -326,36 +326,32 @@ public: invariants() const; private: - using SharedPtrNodeStack = - std::stack, SHAMapNodeID>>; + using SharedPtrNodeStack = std::stack>; using DeltaRef = std::pair, boost::intrusive_ptr>; // tree node cache operations - intr_ptr::SharedPtr + SHAMapTreeNodePtr cacheLookup(SHAMapHash const& hash) const; void - canonicalize(SHAMapHash const& hash, intr_ptr::SharedPtr&) const; + canonicalize(SHAMapHash const& hash, SHAMapTreeNodePtr&) const; // database operations - intr_ptr::SharedPtr + SHAMapTreeNodePtr fetchNodeFromDB(SHAMapHash const& hash) const; - intr_ptr::SharedPtr + SHAMapTreeNodePtr fetchNodeNT(SHAMapHash const& hash) const; - intr_ptr::SharedPtr + SHAMapTreeNodePtr fetchNodeNT(SHAMapHash const& hash, SHAMapSyncFilter* filter) const; - intr_ptr::SharedPtr + SHAMapTreeNodePtr fetchNode(SHAMapHash const& hash) const; - intr_ptr::SharedPtr + SHAMapTreeNodePtr checkFilter(SHAMapHash const& hash, SHAMapSyncFilter* filter) const; /** Update hashes up to the root */ void - dirtyUp( - SharedPtrNodeStack& stack, - uint256 const& target, - intr_ptr::SharedPtr terminal); + dirtyUp(SharedPtrNodeStack& stack, uint256 const& target, SHAMapTreeNodePtr terminal); /** Walk towards the specified id, returning the node. Caller must check if the return is nullptr, and if not, if the node->peekItem()->key() == @@ -377,25 +373,21 @@ private: preFlushNode(intr_ptr::SharedPtr node) const; /** write and canonicalize modified node */ - intr_ptr::SharedPtr - writeNode(NodeObjectType t, intr_ptr::SharedPtr node) const; + SHAMapTreeNodePtr + writeNode(NodeObjectType t, SHAMapTreeNodePtr node) const; // returns the first item at or below this node SHAMapLeafNode* - firstBelow(intr_ptr::SharedPtr, SharedPtrNodeStack& stack, int branch = 0) - const; + firstBelow(SHAMapTreeNodePtr node, SharedPtrNodeStack& stack, int branch = 0) const; // returns the last item at or below this node SHAMapLeafNode* - lastBelow( - intr_ptr::SharedPtr node, - SharedPtrNodeStack& stack, - int branch = kBranchFactor) const; + lastBelow(SHAMapTreeNodePtr node, SharedPtrNodeStack& stack, int branch = kBranchFactor) const; // helper function for firstBelow and lastBelow SHAMapLeafNode* belowHelper( - intr_ptr::SharedPtr node, + SHAMapTreeNodePtr node, SharedPtrNodeStack& stack, int branch, std::tuple, std::function> const& loopParams) @@ -407,15 +399,14 @@ private: descend(SHAMapInnerNode*, int branch) const; SHAMapTreeNode* descendThrow(SHAMapInnerNode*, int branch) const; - intr_ptr::SharedPtr + SHAMapTreeNodePtr descend(SHAMapInnerNode&, int branch) const; - intr_ptr::SharedPtr + SHAMapTreeNodePtr descendThrow(SHAMapInnerNode&, int branch) const; // Descend with filter // If pending, callback is called as if it called fetchNodeNT - using descendCallback = - std::function, SHAMapHash const&)>; + using descendCallback = std::function; SHAMapTreeNode* descendAsync( SHAMapInnerNode* parent, @@ -433,7 +424,7 @@ private: // Non-storing // Does not hook the returned node to its parent - intr_ptr::SharedPtr + SHAMapTreeNodePtr descendNoStore(SHAMapInnerNode&, int branch) const; /** If there is only one leaf below this node, get its contents */ @@ -495,10 +486,10 @@ private: // nodes we may have acquired from deferred reads using DeferredNode = std::tuple< - SHAMapInnerNode*, // parent node - SHAMapNodeID, // parent node ID - int, // branch - intr_ptr::SharedPtr>; // node + SHAMapInnerNode*, // parent node + SHAMapNodeID, // parent node ID + int, // branch + SHAMapTreeNodePtr>; // node int deferred; std::mutex deferLock; @@ -524,7 +515,7 @@ private: gmnProcessDeferredReads(MissingNodes&); // fetch from DB helper function - intr_ptr::SharedPtr + SHAMapTreeNodePtr finishFetch(SHAMapHash const& hash, std::shared_ptr const& object) const; }; diff --git a/include/xrpl/shamap/SHAMapAccountStateLeafNode.h b/include/xrpl/shamap/SHAMapAccountStateLeafNode.h index c67b32d4e7..e388d205d1 100644 --- a/include/xrpl/shamap/SHAMapAccountStateLeafNode.h +++ b/include/xrpl/shamap/SHAMapAccountStateLeafNode.h @@ -27,7 +27,7 @@ public: { } - intr_ptr::SharedPtr + SHAMapTreeNodePtr clone(std::uint32_t cowid) const final { return intr_ptr::makeShared(item_, cowid, hash_); diff --git a/include/xrpl/shamap/SHAMapInnerNode.h b/include/xrpl/shamap/SHAMapInnerNode.h index 48416a93e6..cafb498218 100644 --- a/include/xrpl/shamap/SHAMapInnerNode.h +++ b/include/xrpl/shamap/SHAMapInnerNode.h @@ -87,7 +87,7 @@ public: void partialDestructor() override; - intr_ptr::SharedPtr + SHAMapTreeNodePtr clone(std::uint32_t cowid) const override; SHAMapNodeType @@ -121,19 +121,19 @@ public: getChildHash(int m) const; void - setChild(int m, intr_ptr::SharedPtr child); + setChild(int m, SHAMapTreeNodePtr child); void - shareChild(int m, intr_ptr::SharedPtr const& child); + shareChild(int m, SHAMapTreeNodePtr const& child); SHAMapTreeNode* getChildPointer(int branch); - intr_ptr::SharedPtr + SHAMapTreeNodePtr getChild(int branch); - intr_ptr::SharedPtr - canonicalizeChild(int branch, intr_ptr::SharedPtr node); + SHAMapTreeNodePtr + canonicalizeChild(int branch, SHAMapTreeNodePtr node); // sync functions bool @@ -161,10 +161,10 @@ public: void invariants(bool isRoot = false) const override; - static intr_ptr::SharedPtr + static SHAMapTreeNodePtr makeFullInner(Slice data, SHAMapHash const& hash, bool hashValid); - static intr_ptr::SharedPtr + static SHAMapTreeNodePtr makeCompressedInner(Slice data); }; diff --git a/include/xrpl/shamap/SHAMapTreeNode.h b/include/xrpl/shamap/SHAMapTreeNode.h index ee74155ac4..5cca2ea41a 100644 --- a/include/xrpl/shamap/SHAMapTreeNode.h +++ b/include/xrpl/shamap/SHAMapTreeNode.h @@ -13,6 +13,9 @@ namespace xrpl { +class SHAMapTreeNode; +using SHAMapTreeNodePtr = intr_ptr::SharedPtr; + // These are wire-protocol identifiers used during serialization to encode the // type of a node. They should not be arbitrarily be changed. static constexpr unsigned char const kWireTypeTransaction = 0; @@ -112,7 +115,7 @@ public: } /** Make a copy of this node, setting the owner. */ - virtual intr_ptr::SharedPtr + virtual SHAMapTreeNodePtr clone(std::uint32_t cowid) const = 0; /** @} */ @@ -153,20 +156,20 @@ public: virtual void invariants(bool isRoot = false) const = 0; - static intr_ptr::SharedPtr + static SHAMapTreeNodePtr makeFromPrefix(Slice rawNode, SHAMapHash const& hash); - static intr_ptr::SharedPtr + static SHAMapTreeNodePtr makeFromWire(Slice rawNode); private: - static intr_ptr::SharedPtr + static SHAMapTreeNodePtr makeTransaction(Slice data, SHAMapHash const& hash, bool hashValid); - static intr_ptr::SharedPtr + static SHAMapTreeNodePtr makeAccountState(Slice data, SHAMapHash const& hash, bool hashValid); - static intr_ptr::SharedPtr + static SHAMapTreeNodePtr makeTransactionWithMeta(Slice data, SHAMapHash const& hash, bool hashValid); }; diff --git a/include/xrpl/shamap/SHAMapTxLeafNode.h b/include/xrpl/shamap/SHAMapTxLeafNode.h index 72be5b1962..49f4f90906 100644 --- a/include/xrpl/shamap/SHAMapTxLeafNode.h +++ b/include/xrpl/shamap/SHAMapTxLeafNode.h @@ -26,7 +26,7 @@ public: { } - intr_ptr::SharedPtr + SHAMapTreeNodePtr clone(std::uint32_t cowid) const final { return intr_ptr::makeShared(item_, cowid, hash_); diff --git a/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h b/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h index 44562aeaba..3f4163ac41 100644 --- a/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h +++ b/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h @@ -27,7 +27,7 @@ public: { } - intr_ptr::SharedPtr + SHAMapTreeNodePtr clone(std::uint32_t cowid) const override { return intr_ptr::makeShared(item_, cowid, hash_); diff --git a/include/xrpl/shamap/TreeNodeCache.h b/include/xrpl/shamap/TreeNodeCache.h index 4edb6348ec..2d5782c7e9 100644 --- a/include/xrpl/shamap/TreeNodeCache.h +++ b/include/xrpl/shamap/TreeNodeCache.h @@ -11,5 +11,5 @@ using TreeNodeCache = TaggedCache< SHAMapTreeNode, /*IsKeyCache*/ false, intr_ptr::SharedWeakUnionPtr, - intr_ptr::SharedPtr>; + SHAMapTreeNodePtr>; } // namespace xrpl diff --git a/include/xrpl/shamap/detail/TaggedPointer.h b/include/xrpl/shamap/detail/TaggedPointer.h index 94dbe95284..5eb3863de0 100644 --- a/include/xrpl/shamap/detail/TaggedPointer.h +++ b/include/xrpl/shamap/detail/TaggedPointer.h @@ -148,7 +148,7 @@ public: /** Get the number of elements in each array and a pointer to the start of each array. */ - [[nodiscard]] std::tuple*> + [[nodiscard]] std::tuple getHashesAndChildren() const; /** Get the `hashes` array */ @@ -156,7 +156,7 @@ public: getHashes() const; /** Get the `children` array */ - [[nodiscard]] intr_ptr::SharedPtr* + [[nodiscard]] SHAMapTreeNodePtr* getChildren() const; /** Call the `f` callback for all 16 (branchFactor) branches - even if diff --git a/include/xrpl/shamap/detail/TaggedPointer.ipp b/include/xrpl/shamap/detail/TaggedPointer.ipp index 2e6e31fed8..6606c49a6b 100644 --- a/include/xrpl/shamap/detail/TaggedPointer.ipp +++ b/include/xrpl/shamap/detail/TaggedPointer.ipp @@ -26,8 +26,7 @@ static_assert( // Terminology: A chunk is the memory being allocated from a block. A block // contains multiple chunks. This is the terminology the boost documentation // uses. Pools use "Simple Segregated Storage" as their storage format. -constexpr size_t kElementSizeBytes = - (sizeof(SHAMapHash) + sizeof(intr_ptr::SharedPtr)); +constexpr size_t kElementSizeBytes = sizeof(SHAMapHash) + sizeof(SHAMapTreeNodePtr); constexpr size_t kBlockSizeBytes = kilobytes(512); @@ -364,8 +363,7 @@ inline TaggedPointer::TaggedPointer( // keep new (&dstHashes[dstIndex]) SHAMapHash{srcHashes[srcIndex]}; - new (&dstChildren[dstIndex]) - intr_ptr::SharedPtr{std::move(srcChildren[srcIndex])}; + new (&dstChildren[dstIndex]) SHAMapTreeNodePtr{std::move(srcChildren[srcIndex])}; ++dstIndex; ++srcIndex; } @@ -376,7 +374,7 @@ inline TaggedPointer::TaggedPointer( if (dstIsDense) { new (&dstHashes[dstIndex]) SHAMapHash{}; - new (&dstChildren[dstIndex]) intr_ptr::SharedPtr{}; + new (&dstChildren[dstIndex]) SHAMapTreeNodePtr{}; ++dstIndex; } } @@ -384,7 +382,7 @@ inline TaggedPointer::TaggedPointer( { // add new (&dstHashes[dstIndex]) SHAMapHash{}; - new (&dstChildren[dstIndex]) intr_ptr::SharedPtr{}; + new (&dstChildren[dstIndex]) SHAMapTreeNodePtr{}; ++dstIndex; if (srcIsDense) { @@ -397,7 +395,7 @@ inline TaggedPointer::TaggedPointer( if (dstIsDense) { new (&dstHashes[dstIndex]) SHAMapHash{}; - new (&dstChildren[dstIndex]) intr_ptr::SharedPtr{}; + new (&dstChildren[dstIndex]) SHAMapTreeNodePtr{}; ++dstIndex; } if (srcIsDense) @@ -414,7 +412,7 @@ inline TaggedPointer::TaggedPointer( for (int i = dstIndex; i < dstNumAllocated; ++i) { new (&dstHashes[i]) SHAMapHash{}; - new (&dstChildren[i]) intr_ptr::SharedPtr{}; + new (&dstChildren[i]) SHAMapTreeNodePtr{}; } *this = std::move(dst); } @@ -433,8 +431,10 @@ inline TaggedPointer::TaggedPointer( // allocate hashes and children, but do not run constructors TaggedPointer newHashesAndChildren{RawAllocateTag{}, toAllocate}; - SHAMapHash *newHashes = nullptr, *oldHashes = nullptr; - intr_ptr::SharedPtr*newChildren = nullptr, *oldChildren = nullptr; + SHAMapHash* newHashes = nullptr; + SHAMapHash* oldHashes = nullptr; + SHAMapTreeNodePtr* newChildren = nullptr; + SHAMapTreeNodePtr* oldChildren = nullptr; std::uint8_t newNumAllocated = 0; // structured bindings can't be captured in c++ 17; use tie instead std::tie(newNumAllocated, newHashes, newChildren) = newHashesAndChildren.getHashesAndChildren(); @@ -445,8 +445,7 @@ inline TaggedPointer::TaggedPointer( // new arrays are dense, old arrays are sparse iterNonEmptyChildIndexes(isBranch, [&](auto branchNum, auto indexNum) { new (&newHashes[branchNum]) SHAMapHash{oldHashes[indexNum]}; - new (&newChildren[branchNum]) - intr_ptr::SharedPtr{std::move(oldChildren[indexNum])}; + new (&newChildren[branchNum]) SHAMapTreeNodePtr{std::move(oldChildren[indexNum])}; }); // Run the constructors for the remaining elements for (int i = 0; i < SHAMapInnerNode::kBranchFactor; ++i) @@ -454,7 +453,7 @@ inline TaggedPointer::TaggedPointer( if (((1 << i) & isBranch) != 0) continue; new (&newHashes[i]) SHAMapHash{}; - new (&newChildren[i]) intr_ptr::SharedPtr{}; + new (&newChildren[i]) SHAMapTreeNodePtr{}; } } else @@ -464,14 +463,14 @@ inline TaggedPointer::TaggedPointer( iterNonEmptyChildIndexes(isBranch, [&](auto branchNum, auto indexNum) { new (&newHashes[curCompressedIndex]) SHAMapHash{oldHashes[indexNum]}; new (&newChildren[curCompressedIndex]) - intr_ptr::SharedPtr{std::move(oldChildren[indexNum])}; + SHAMapTreeNodePtr{std::move(oldChildren[indexNum])}; ++curCompressedIndex; }); // Run the constructors for the remaining elements for (int i = curCompressedIndex; i < newNumAllocated; ++i) { new (&newHashes[i]) SHAMapHash{}; - new (&newChildren[i]) intr_ptr::SharedPtr{}; + new (&newChildren[i]) SHAMapTreeNodePtr{}; } } @@ -485,7 +484,7 @@ inline TaggedPointer::TaggedPointer(std::uint8_t numChildren) for (std::size_t i = 0; i < numAllocated; ++i) { new (&hashes[i]) SHAMapHash{}; - new (&children[i]) intr_ptr::SharedPtr{}; + new (&children[i]) SHAMapTreeNodePtr{}; } } @@ -523,14 +522,13 @@ TaggedPointer::isDense() const return (tp_ & kTagMask) == kBoundaries.size() - 1; } -[[nodiscard]] inline std::tuple*> +[[nodiscard]] inline std::tuple TaggedPointer::getHashesAndChildren() const { auto const [tag, ptr] = decode(); auto const hashes = reinterpret_cast(ptr); std::uint8_t const numAllocated = kBoundaries[tag]; - auto const children = - reinterpret_cast*>(hashes + numAllocated); + auto const children = reinterpret_cast(hashes + numAllocated); return {numAllocated, hashes, children}; }; @@ -540,7 +538,7 @@ TaggedPointer::getHashes() const return reinterpret_cast(tp_ & kPtrMask); }; -[[nodiscard]] inline intr_ptr::SharedPtr* +[[nodiscard]] inline SHAMapTreeNodePtr* TaggedPointer::getChildren() const { auto [unused1, unused2, result] = getHashesAndChildren(); diff --git a/src/libxrpl/shamap/SHAMap.cpp b/src/libxrpl/shamap/SHAMap.cpp index d3a7d49da6..4aad255d81 100644 --- a/src/libxrpl/shamap/SHAMap.cpp +++ b/src/libxrpl/shamap/SHAMap.cpp @@ -97,10 +97,7 @@ SHAMap::snapShot(bool isMutable) const } void -SHAMap::dirtyUp( - SharedPtrNodeStack& stack, - uint256 const& target, - intr_ptr::SharedPtr child) +SHAMap::dirtyUp(SharedPtrNodeStack& stack, uint256 const& target, SHAMapTreeNodePtr child) { // walk the tree up from through the inner nodes to the root_ // update hashes and links @@ -165,7 +162,7 @@ SHAMap::findKey(uint256 const& id) const return leaf; } -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMap::fetchNodeFromDB(SHAMapHash const& hash) const { XRPL_ASSERT(backed_, "xrpl::SHAMap::fetchNodeFromDB : is backed"); @@ -173,7 +170,7 @@ SHAMap::fetchNodeFromDB(SHAMapHash const& hash) const return finishFetch(hash, obj); } -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMap::finishFetch(SHAMapHash const& hash, std::shared_ptr const& object) const { XRPL_ASSERT(backed_, "xrpl::SHAMap::finishFetch : is backed"); @@ -208,7 +205,7 @@ SHAMap::finishFetch(SHAMapHash const& hash, std::shared_ptr const& o } // See if a sync filter has a node -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMap::checkFilter(SHAMapHash const& hash, SHAMapSyncFilter* filter) const { if (auto nodeData = filter->getNode(hash)) @@ -234,7 +231,7 @@ SHAMap::checkFilter(SHAMapHash const& hash, SHAMapSyncFilter* filter) const // Get a node without throwing // Used on maps where missing nodes are expected -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMap::fetchNodeNT(SHAMapHash const& hash, SHAMapSyncFilter* filter) const { auto node = cacheLookup(hash); @@ -257,7 +254,7 @@ SHAMap::fetchNodeNT(SHAMapHash const& hash, SHAMapSyncFilter* filter) const return node; } -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMap::fetchNodeNT(SHAMapHash const& hash) const { auto node = cacheLookup(hash); @@ -269,7 +266,7 @@ SHAMap::fetchNodeNT(SHAMapHash const& hash) const } // Throw if the node is missing -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMap::fetchNode(SHAMapHash const& hash) const { auto node = fetchNodeNT(hash); @@ -291,10 +288,10 @@ SHAMap::descendThrow(SHAMapInnerNode* parent, int branch) const return ret; } -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMap::descendThrow(SHAMapInnerNode& parent, int branch) const { - intr_ptr::SharedPtr ret = descend(parent, branch); + SHAMapTreeNodePtr ret = descend(parent, branch); if (!ret && !parent.isEmptyBranch(branch)) Throw(type_, parent.getChildHash(branch)); @@ -309,7 +306,7 @@ SHAMap::descend(SHAMapInnerNode* parent, int branch) const if ((ret != nullptr) || !backed_) return ret; - intr_ptr::SharedPtr node = fetchNodeNT(parent->getChildHash(branch)); + SHAMapTreeNodePtr node = fetchNodeNT(parent->getChildHash(branch)); if (!node) return nullptr; @@ -317,10 +314,10 @@ SHAMap::descend(SHAMapInnerNode* parent, int branch) const return node.get(); } -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMap::descend(SHAMapInnerNode& parent, int branch) const { - intr_ptr::SharedPtr node = parent.getChild(branch); + SHAMapTreeNodePtr node = parent.getChild(branch); if (node || !backed_) return node; @@ -334,10 +331,10 @@ SHAMap::descend(SHAMapInnerNode& parent, int branch) const // Gets the node that would be hooked to this branch, // but doesn't hook it up. -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMap::descendNoStore(SHAMapInnerNode& parent, int branch) const { - intr_ptr::SharedPtr ret = parent.getChild(branch); + SHAMapTreeNodePtr ret = parent.getChild(branch); if (!ret && backed_) ret = fetchNode(parent.getChildHash(branch)); return ret; @@ -361,7 +358,7 @@ SHAMap::descend( if (child == nullptr) { auto const& childHash = parent->getChildHash(branch); - intr_ptr::SharedPtr childNode = fetchNodeNT(childHash, filter); + SHAMapTreeNodePtr childNode = fetchNodeNT(childHash, filter); if (childNode) { @@ -434,7 +431,7 @@ SHAMap::unshareNode(intr_ptr::SharedPtr node, SHAMapNodeID const& nodeID) SHAMapLeafNode* SHAMap::belowHelper( - intr_ptr::SharedPtr node, + SHAMapTreeNodePtr node, SharedPtrNodeStack& stack, int branch, std::tuple, std::function> const& loopParams) const @@ -479,8 +476,7 @@ SHAMap::belowHelper( return nullptr; } SHAMapLeafNode* -SHAMap::lastBelow(intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, int branch) - const +SHAMap::lastBelow(SHAMapTreeNodePtr node, SharedPtrNodeStack& stack, int branch) const { auto init = kBranchFactor - 1; auto cmp = [](int i) { return i >= 0; }; @@ -489,8 +485,7 @@ SHAMap::lastBelow(intr_ptr::SharedPtr node, SharedPtrNodeStack& return belowHelper(node, stack, branch, {init, cmp, incr}); } SHAMapLeafNode* -SHAMap::firstBelow(intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, int branch) - const +SHAMap::firstBelow(SHAMapTreeNodePtr node, SharedPtrNodeStack& stack, int branch) const { auto init = 0; auto cmp = [](int i) { return i <= kBranchFactor; }; @@ -699,10 +694,8 @@ SHAMap::delItem(uint256 const& id) SHAMapNodeType const type = leaf->getType(); - using TreeNodeType = intr_ptr::SharedPtr; - // What gets attached to the end of the chain (For now, nothing, since we deleted the leaf) - TreeNodeType prevNode; + SHAMapTreeNodePtr prevNode; while (!stack.empty()) { @@ -728,7 +721,7 @@ SHAMap::delItem(uint256 const& id) // no children below this branch // // Note: This is unnecessary due to the std::move above but left here for safety - prevNode = TreeNodeType{}; + prevNode = SHAMapTreeNodePtr{}; } else if (bc == 1) { @@ -741,7 +734,7 @@ SHAMap::delItem(uint256 const& id) { if (!node->isEmptyBranch(i)) { - node->setChild(i, TreeNodeType{}); + node->setChild(i, SHAMapTreeNodePtr{}); break; } } @@ -937,8 +930,8 @@ SHAMap::fetchRoot(SHAMapHash const& hash, SHAMapSyncFilter* filter) @note The node must have already been unshared by having the caller first call SHAMapTreeNode::unshare(). */ -intr_ptr::SharedPtr -SHAMap::writeNode(NodeObjectType t, intr_ptr::SharedPtr node) const +SHAMapTreeNodePtr +SHAMap::writeNode(NodeObjectType t, SHAMapTreeNodePtr node) const { XRPL_ASSERT(node->cowid() == 0, "xrpl::SHAMap::writeNode : valid input node"); XRPL_ASSERT(backed_, "xrpl::SHAMap::writeNode : is backed"); @@ -1155,7 +1148,7 @@ SHAMap::dump(bool hash) const JLOG(journal_.info()) << leafCount << " resident leaves"; } -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMap::cacheLookup(SHAMapHash const& hash) const { auto ret = f_.getTreeNodeCache()->fetch(hash.asUInt256()); @@ -1164,7 +1157,7 @@ SHAMap::cacheLookup(SHAMapHash const& hash) const } void -SHAMap::canonicalize(SHAMapHash const& hash, intr_ptr::SharedPtr& node) const +SHAMap::canonicalize(SHAMapHash const& hash, SHAMapTreeNodePtr& node) const { XRPL_ASSERT(backed_, "xrpl::SHAMap::canonicalize : is backed"); XRPL_ASSERT(node->cowid() == 0, "xrpl::SHAMap::canonicalize : valid node input"); diff --git a/src/libxrpl/shamap/SHAMapDelta.cpp b/src/libxrpl/shamap/SHAMapDelta.cpp index b1aeac18e8..8336ce5481 100644 --- a/src/libxrpl/shamap/SHAMapDelta.cpp +++ b/src/libxrpl/shamap/SHAMapDelta.cpp @@ -261,7 +261,7 @@ SHAMap::walkMap(std::vector& missingNodes, int maxMissing) co { if (!node->isEmptyBranch(i)) { - intr_ptr::SharedPtr const nextNode = descendNoStore(*node, i); + SHAMapTreeNodePtr const nextNode = descendNoStore(*node, i); if (nextNode) { @@ -286,7 +286,7 @@ SHAMap::walkMapParallel(std::vector& missingNodes, int maxMis return false; using StackEntry = intr_ptr::SharedPtr; - std::array, 16> topChildren; + std::array topChildren; { auto const& innerRoot = intr_ptr::staticPointerCast(root_); for (int i = 0; i < 16; ++i) @@ -331,8 +331,7 @@ SHAMap::walkMapParallel(std::vector& missingNodes, int maxMis { if (node->isEmptyBranch(i)) continue; - intr_ptr::SharedPtr const nextNode = - descendNoStore(*node, i); + SHAMapTreeNodePtr const nextNode = descendNoStore(*node, i); if (nextNode) { diff --git a/src/libxrpl/shamap/SHAMapInnerNode.cpp b/src/libxrpl/shamap/SHAMapInnerNode.cpp index f31b75ad39..ee6ebf7f3f 100644 --- a/src/libxrpl/shamap/SHAMapInnerNode.cpp +++ b/src/libxrpl/shamap/SHAMapInnerNode.cpp @@ -37,7 +37,7 @@ SHAMapInnerNode::~SHAMapInnerNode() = default; void SHAMapInnerNode::partialDestructor() { - intr_ptr::SharedPtr* children = nullptr; + SHAMapTreeNodePtr* children = nullptr; // structured bindings can't be captured in c++ 17; use tie instead std::tie(std::ignore, std::ignore, children) = hashesAndChildren_.getHashesAndChildren(); iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { children[indexNum].reset(); }); @@ -69,7 +69,7 @@ SHAMapInnerNode::getChildIndex(int i) const return hashesAndChildren_.getChildIndex(isBranch_, i); } -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMapInnerNode::clone(std::uint32_t cowid) const { auto const branchCount = getBranchCount(); @@ -78,8 +78,10 @@ SHAMapInnerNode::clone(std::uint32_t cowid) const p->hash_ = hash_; p->isBranch_ = isBranch_; p->fullBelowGen_ = fullBelowGen_; - SHAMapHash *cloneHashes = nullptr, *thisHashes = nullptr; - intr_ptr::SharedPtr*cloneChildren = nullptr, *thisChildren = nullptr; + SHAMapHash* cloneHashes = nullptr; + SHAMapHash* thisHashes = nullptr; + SHAMapTreeNodePtr* cloneChildren = nullptr; + SHAMapTreeNodePtr* thisChildren = nullptr; // structured bindings can't be captured in c++ 17; use tie instead std::tie(std::ignore, cloneHashes, cloneChildren) = p->hashesAndChildren_.getHashesAndChildren(); @@ -118,7 +120,7 @@ SHAMapInnerNode::clone(std::uint32_t cowid) const return p; } -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMapInnerNode::makeFullInner(Slice data, SHAMapHash const& hash, bool hashValid) { // A full inner node is serialized as 16 256-bit hashes, back to back: @@ -153,7 +155,7 @@ SHAMapInnerNode::makeFullInner(Slice data, SHAMapHash const& hash, bool hashVali return ret; } -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMapInnerNode::makeCompressedInner(Slice data) { // A compressed inner node is serialized as a series of 33 byte chunks, @@ -207,7 +209,7 @@ void SHAMapInnerNode::updateHashDeep() { SHAMapHash* hashes = nullptr; - intr_ptr::SharedPtr* children = nullptr; + SHAMapTreeNodePtr* children = nullptr; // structured bindings can't be captured in c++ 17; use tie instead std::tie(std::ignore, hashes, children) = hashesAndChildren_.getHashesAndChildren(); iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { @@ -265,7 +267,7 @@ SHAMapInnerNode::getString(SHAMapNodeID const& id) const // We are modifying an inner node void -SHAMapInnerNode::setChild(int m, intr_ptr::SharedPtr child) +SHAMapInnerNode::setChild(int m, SHAMapTreeNodePtr child) { XRPL_ASSERT( (m >= 0) && (m < kBranchFactor), "xrpl::SHAMapInnerNode::setChild : valid branch input"); @@ -307,7 +309,7 @@ SHAMapInnerNode::setChild(int m, intr_ptr::SharedPtr child) // finished modifying, now make shareable void -SHAMapInnerNode::shareChild(int m, intr_ptr::SharedPtr const& child) +SHAMapInnerNode::shareChild(int m, SHAMapTreeNodePtr const& child) { XRPL_ASSERT( (m >= 0) && (m < kBranchFactor), "xrpl::SHAMapInnerNode::shareChild : valid branch input"); @@ -337,7 +339,7 @@ SHAMapInnerNode::getChildPointer(int branch) return hashesAndChildren_.getChildren()[index].get(); } -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMapInnerNode::getChild(int branch) { XRPL_ASSERT( @@ -365,8 +367,8 @@ SHAMapInnerNode::getChildHash(int m) const return kZeroShaMapHash; } -intr_ptr::SharedPtr -SHAMapInnerNode::canonicalizeChild(int branch, intr_ptr::SharedPtr node) +SHAMapTreeNodePtr +SHAMapInnerNode::canonicalizeChild(int branch, SHAMapTreeNodePtr node) { XRPL_ASSERT( branch >= 0 && branch < kBranchFactor, diff --git a/src/libxrpl/shamap/SHAMapSync.cpp b/src/libxrpl/shamap/SHAMapSync.cpp index cd2654c603..0601bfefda 100644 --- a/src/libxrpl/shamap/SHAMapSync.cpp +++ b/src/libxrpl/shamap/SHAMapSync.cpp @@ -66,7 +66,7 @@ SHAMap::visitNodes(std::function const& function) const { if (!node->isEmptyBranch(pos)) { - intr_ptr::SharedPtr const child = descendNoStore(*node, pos); + SHAMapTreeNodePtr const child = descendNoStore(*node, pos); if (!function(*child)) return; @@ -204,8 +204,7 @@ SHAMap::gmnProcessNodes(MissingNodes& mn, MissingNodes::StackEntry& se) branch, mn.filter, pending, - [node, nodeID, branch, &mn]( - intr_ptr::SharedPtr found, SHAMapHash const&) { + [node, nodeID, branch, &mn](SHAMapTreeNodePtr found, SHAMapHash const&) { // a read completed asynchronously std::unique_lock const lock{mn.deferLock}; mn.finishedReads.emplace_back(node, nodeID, branch, std::move(found)); @@ -266,8 +265,7 @@ SHAMap::gmnProcessDeferredReads(MissingNodes& mn) int complete = 0; while (complete != mn.deferred) { - std::tuple> - deferredNode; + std::tuple deferredNode; { std::unique_lock lock{mn.deferLock}; diff --git a/src/libxrpl/shamap/SHAMapTreeNode.cpp b/src/libxrpl/shamap/SHAMapTreeNode.cpp index 3b8d976c69..1ae7cf18af 100644 --- a/src/libxrpl/shamap/SHAMapTreeNode.cpp +++ b/src/libxrpl/shamap/SHAMapTreeNode.cpp @@ -25,7 +25,7 @@ namespace xrpl { -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMapTreeNode::makeTransaction(Slice data, SHAMapHash const& hash, bool hashValid) { if (data.size() < kMinShaMapItemBytes) @@ -43,7 +43,7 @@ SHAMapTreeNode::makeTransaction(Slice data, SHAMapHash const& hash, bool hashVal return intr_ptr::makeShared(std::move(item), 0); } -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMapTreeNode::makeTransactionWithMeta(Slice data, SHAMapHash const& hash, bool hashValid) { Serializer s(data.data(), data.size()); @@ -83,7 +83,7 @@ SHAMapTreeNode::makeTransactionWithMeta(Slice data, SHAMapHash const& hash, bool return intr_ptr::makeShared(std::move(item), 0); } -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMapTreeNode::makeAccountState(Slice data, SHAMapHash const& hash, bool hashValid) { Serializer s(data.data(), data.size()); @@ -124,7 +124,7 @@ SHAMapTreeNode::makeAccountState(Slice data, SHAMapHash const& hash, bool hashVa return intr_ptr::makeShared(std::move(item), 0); } -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMapTreeNode::makeFromWire(Slice rawNode) { if (rawNode.empty()) @@ -155,7 +155,7 @@ SHAMapTreeNode::makeFromWire(Slice rawNode) Throw("wire: Unknown type (" + std::to_string(type) + ")"); } -intr_ptr::SharedPtr +SHAMapTreeNodePtr SHAMapTreeNode::makeFromPrefix(Slice rawNode, SHAMapHash const& hash) { if (rawNode.size() < 4) From 023bdaeeedc6ebcff3a2eef136d0f2bdac4a8296 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 3 Jun 2026 20:14:17 +0100 Subject: [PATCH 05/78] ci: Install gcov, nettools, cacert in nix images (#7398) --- docker/{check-tool-versions.sh => check-tools.sh} | 8 ++++++++ docker/nix.Dockerfile | 10 ++++++++-- nix/ci-env.nix | 14 ++++++++++++++ nix/packages.nix | 1 + 4 files changed, 31 insertions(+), 2 deletions(-) rename docker/{check-tool-versions.sh => check-tools.sh} (59%) diff --git a/docker/check-tool-versions.sh b/docker/check-tools.sh similarity index 59% rename from docker/check-tool-versions.sh rename to docker/check-tools.sh index db20be45e4..faa4586832 100755 --- a/docker/check-tool-versions.sh +++ b/docker/check-tools.sh @@ -10,11 +10,13 @@ cmake --version conan --version g++ --version gcc --version +gcov --version gcovr --version git --version less --version make --version mold --version +netstat --version ninja --version perl --version pkg-config --version @@ -22,3 +24,9 @@ pre-commit --version python3 --version run-clang-tidy --help vim --version + +# A simple test to verify that git can clone a repository over HTTPS +# (i.e. the CA bundle is wired up). Clone to a temp dir and clean up. +tmp_clone="$(mktemp -d)" +git clone --depth 1 https://github.com/XRPLF/actions.git "${tmp_clone}/actions" +rm -rf "${tmp_clone}" diff --git a/docker/nix.Dockerfile b/docker/nix.Dockerfile index a0eab31769..6248708417 100644 --- a/docker/nix.Dockerfile +++ b/docker/nix.Dockerfile @@ -47,6 +47,12 @@ COPY --from=builder /tmp/build/result /nix/ci-env ENV PATH="/nix/ci-env/bin:${PATH}" +# Point HTTPS clients (git, curl, conan, ...) at the CA bundle shipped in the +# Nix CI environment, so TLS verification works without ca-certificates being +# installed in the system. +ENV SSL_CERT_FILE="/nix/ci-env/etc/ssl/certs/ca-bundle.crt" +ENV GIT_SSL_CAINFO="/nix/ci-env/etc/ssl/certs/ca-bundle.crt" + # Externally-built dynamically-linked ELF binaries hard-code the loader path # (e.g. /lib64/ld-linux-x86-64.so.2) in their PT_INTERP header. Install it # from the Nix store when the base image doesn't already provide one. @@ -65,8 +71,8 @@ if [ ! -e "${target}" ]; then fi EOF -COPY docker/check-tool-versions.sh /tmp/check-tool-versions.sh -RUN /tmp/check-tool-versions.sh +COPY docker/check-tools.sh /tmp/check-tools.sh +RUN /tmp/check-tools.sh # Sanity-check that the g++/clang++ are able to build binaries, including sanitizer-instrumented ones. COPY docker/test_files/cpp_sources/ /tmp/cpp_sources/ diff --git a/nix/ci-env.nix b/nix/ci-env.nix index 0d617913d9..0ef7410250 100644 --- a/nix/ci-env.nix +++ b/nix/ci-env.nix @@ -43,6 +43,15 @@ let bintools = customBinutils; }; + # gcov ships in gcc's `cc` output, but the cc-wrapper doesn't expose it. + # Surface the gcov from our rebuilt gcc (linked against the custom glibc, so + # it runs under the loader installed in the image) and matching the exact + # compiler version, so gcovr can produce coverage reports in the CI env. + customGcov = pkgs.runCommand "gcov-custom-for-ci-env" { } '' + mkdir -p "$out/bin" + ln -s "${customGccCc}/bin/gcov" "$out/bin/gcov" + ''; + # stdenv built around the rebuilt gcc / custom glibc. Used to rebuild # compiler-rt below so its sanitizer runtimes see the custom glibc # headers. @@ -105,11 +114,16 @@ in name = "xrpld-ci-env"; paths = commonPackages ++ [ customGcc + customGcov customClangForCiEnv customBinutils + # CA certificate bundle so HTTPS clients (git, curl, conan) can verify + # TLS connections without ca-certificates being installed in the system. + pkgs.cacert ]; pathsToLink = [ "/bin" + "/etc/ssl/certs" "/lib" "/include" "/share" diff --git a/nix/packages.nix b/nix/packages.nix index 3d92fedb4b..b608677aea 100644 --- a/nix/packages.nix +++ b/nix/packages.nix @@ -17,6 +17,7 @@ in llvmPackages_22.clang-tools less # needed for git diff mold + nettools # provides netstat, used to debug failures in CI ninja patchelf perl # needed for openssl From e5cf1a0985ee27e5519fa5de1d0a664c57b73d1a Mon Sep 17 00:00:00 2001 From: yinyiqian1 Date: Wed, 3 Jun 2026 15:30:20 -0400 Subject: [PATCH 06/78] fix: Add zero NFT Offer ID check for NFTokenCancelOffer (#7391) --- .../tx/transactors/nft/NFTokenCancelOffer.cpp | 11 +++++++++-- src/test/app/NFToken_test.cpp | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/libxrpl/tx/transactors/nft/NFTokenCancelOffer.cpp b/src/libxrpl/tx/transactors/nft/NFTokenCancelOffer.cpp index 1614f90202..d04714907e 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenCancelOffer.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenCancelOffer.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -21,8 +22,14 @@ namespace xrpl { NotTEC NFTokenCancelOffer::preflight(PreflightContext const& ctx) { - if (auto const& ids = ctx.tx[sfNFTokenOffers]; - ids.empty() || (ids.size() > kMaxTokenOfferCancelCount)) + auto const& offerIds = ctx.tx[sfNFTokenOffers]; + + if (offerIds.empty() || (offerIds.size() > kMaxTokenOfferCancelCount)) + return temMALFORMED; + + // Zero offer IDs cannot be passed as ledger entry keys. + if (ctx.rules.enabled(fixCleanup3_2_0) && + std::ranges::any_of(offerIds, [](uint256 const& id) { return id.isZero(); })) return temMALFORMED; // In order to prevent unnecessarily overlarge transactions, we diff --git a/src/test/app/NFToken_test.cpp b/src/test/app/NFToken_test.cpp index ebd470ec92..269bc72c53 100644 --- a/src/test/app/NFToken_test.cpp +++ b/src/test/app/NFToken_test.cpp @@ -892,6 +892,25 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite BEAST_EXPECT(ownerCount(env, buyer) == 1); } + // Only test this with fixCleanup3_2_0 enabled. Without the fix, + // an assert-enabled build can crash when Ledger::read() receives + // a zero-key offer ID. + if (features[fixCleanup3_2_0]) + { + // Zero is not a valid offer ID. + env(token::cancelOffer(buyer, {uint256{}}), Ter(temMALFORMED)); + env.close(); + BEAST_EXPECT(ownerCount(env, buyer) == 1); + + // List of offer IDs containing zero is invalid. + // craftedIndex is not a valid offer index but it is not zero. + auto const craftedIndex = keylet::nftoffer(gw, env.seq(gw)).key; + env(token::cancelOffer(buyer, {buyerOfferIndex, uint256{}, craftedIndex}), + Ter(temMALFORMED)); + env.close(); + BEAST_EXPECT(ownerCount(env, buyer) == 1); + } + // List of tokens to delete is too long. { std::vector const offers(kMaxTokenOfferCancelCount + 1, buyerOfferIndex); From 6c543426c3461f98d62146a445dada2f47516a93 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 3 Jun 2026 23:19:15 +0100 Subject: [PATCH 07/78] ci: Fix clang asan include dirs in nix images, add curl & gnupg (#7400) --- cspell.config.yaml | 1 + docker/check-tools.sh | 2 ++ docker/test_files/cpp_sources/asan.cpp | 7 +++++++ nix/ci-env.nix | 8 ++++++++ nix/packages.nix | 2 ++ 5 files changed, 20 insertions(+) diff --git a/cspell.config.yaml b/cspell.config.yaml index ed936941e4..da5dc9b072 100644 --- a/cspell.config.yaml +++ b/cspell.config.yaml @@ -134,6 +134,7 @@ words: - iou - ious - isrdc + - isystem - itype - jemalloc - jlog diff --git a/docker/check-tools.sh b/docker/check-tools.sh index faa4586832..eb72e8f357 100755 --- a/docker/check-tools.sh +++ b/docker/check-tools.sh @@ -8,11 +8,13 @@ clang++ --version clang-format --version cmake --version conan --version +curl --version g++ --version gcc --version gcov --version gcovr --version git --version +gpg --version less --version make --version mold --version diff --git a/docker/test_files/cpp_sources/asan.cpp b/docker/test_files/cpp_sources/asan.cpp index 8347f58d37..deefdec79a 100644 --- a/docker/test_files/cpp_sources/asan.cpp +++ b/docker/test_files/cpp_sources/asan.cpp @@ -2,6 +2,13 @@ #include #include +// Regression test: the compiler-rt sanitizer interface headers must be on the +// include path. A bare on-PATH clang in the Nix CI env doesn't get them +// propagated automatically, so this include would fail to compile with clang++ +// if the env isn't wired up correctly. abseil hits the same include during +// sanitizer builds. LeakSanitizer ships with AddressSanitizer. +#include + #if defined(__clang__) || defined(__GNUC__) __attribute__((noinline)) #elif defined(_MSC_VER) diff --git a/nix/ci-env.nix b/nix/ci-env.nix index 0ef7410250..f823f71de0 100644 --- a/nix/ci-env.nix +++ b/nix/ci-env.nix @@ -94,6 +94,14 @@ let ln -s "${customCompilerRt.out}/lib" "$rsrc/lib" ln -s "${customCompilerRt.out}/share" "$rsrc/share" || true echo "-resource-dir=$rsrc" >> $out/nix-support/cc-cflags + # compiler-rt ships the sanitizer/profile/xray interface headers (e.g. + # ) in its `dev` output. In a normal Nix + # build these reach the include path because compiler-rt is propagated + # via depsTargetTargetPropagated and stdenv's setup hooks add its + # dev/include. The CI image runs clang outside a Nix stdenv (binaries + # on PATH, no setup hooks), so that never happens; add the headers + # explicitly. gcc ships its own copy, which is why this is clang-only. + echo "-isystem ${customCompilerRt.dev}/include" >> $out/nix-support/cc-cflags ''; }; diff --git a/nix/packages.nix b/nix/packages.nix index b608677aea..f282c15df9 100644 --- a/nix/packages.nix +++ b/nix/packages.nix @@ -11,9 +11,11 @@ in ccache cmake conan + curlMinimal # needed for codecov/codecov-action gcovr git gnumake + gnupg # needed for signing commits & codecov/codecov-action llvmPackages_22.clang-tools less # needed for git diff mold From 12e81abef3aa4c05bc2f21ea1be49644cb7d478a Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Thu, 4 Jun 2026 15:52:42 +0100 Subject: [PATCH 08/78] ci: Improve sanitizer-libs, add doxygen, dpkg, rpm in nix (#7403) --- docker/check-tools.sh | 3 + docker/install-sanitizer-libs.sh | 124 ++++++++++++++++++------------- nix/packages.nix | 3 + 3 files changed, 80 insertions(+), 50 deletions(-) diff --git a/docker/check-tools.sh b/docker/check-tools.sh index eb72e8f357..c446dc1b4a 100755 --- a/docker/check-tools.sh +++ b/docker/check-tools.sh @@ -9,6 +9,8 @@ clang-format --version cmake --version conan --version curl --version +doxygen --version +dpkg-buildpackage --version g++ --version gcc --version gcov --version @@ -24,6 +26,7 @@ perl --version pkg-config --version pre-commit --version python3 --version +rpmbuild --version run-clang-tidy --help vim --version diff --git a/docker/install-sanitizer-libs.sh b/docker/install-sanitizer-libs.sh index a28efeab3f..dc1ba1b350 100755 --- a/docker/install-sanitizer-libs.sh +++ b/docker/install-sanitizer-libs.sh @@ -27,63 +27,87 @@ fi echo "Detected OS: ${ID} ${VERSION_ID:-}" case "${ID}" in - debian) - apt-get update -y - apt-get install -y --no-install-recommends \ - libasan8 \ - libtsan2 \ - libubsan1 - - apt-get clean - rm -rf /var/lib/apt/lists/* + ubuntu | debian | rhel | centos | rocky | almalinux) + echo "Supported OS detected: ${ID}" ;; - - ubuntu) - apt-get update -y - apt-get install -y --no-install-recommends \ - gnupg \ - software-properties-common - add-apt-repository -y ppa:ubuntu-toolchain-r/test - apt-get update -y - apt-get install -y --no-install-recommends \ - libasan8 \ - libtsan2 \ - libubsan1 - - apt-get clean - rm -rf /var/lib/apt/lists/* - ;; - - rhel | centos | rocky | almalinux) - dnf install -y \ - libasan8 \ - libtsan2 \ - libubsan - - dnf clean -y all - rm -rf /var/cache/dnf/* - ;; - *) echo "ERROR: unsupported OS '${ID}'. Supported: debian, ubuntu, rhel-family" >&2 exit 1 ;; esac -# Verify that every expected library is now resolvable by the dynamic linker. -missing=0 -for lib in libasan.so.8 libtsan.so.2 libubsan.so.1; do - if ldconfig -p | grep -q "${lib}"; then - echo "OK: ${lib} found" - else - echo "ERROR: ${lib} not found after installation" >&2 - missing=$((missing + 1)) - fi -done +function preinstall() { + case "${ID}" in + ubuntu) + apt-get update -y + apt-get install -y --no-install-recommends \ + gnupg \ + software-properties-common + add-apt-repository -y ppa:ubuntu-toolchain-r/test + ;; + esac +} -if [ "${missing}" -ne 0 ]; then - echo "ERROR: ${missing} library/libraries missing" >&2 - exit 1 -fi +function install() { + case "${ID}" in + debian | ubuntu) + apt-get update -y + apt-get install -y --no-install-recommends \ + libasan8 \ + libtsan2 \ + libubsan1 + ;; + + rhel | centos | rocky | almalinux) + dnf install -y \ + libasan8 \ + libtsan2 \ + libubsan + ;; + esac +} + +function postinstall() { + # Don't clear cache in non-CI environments + if [ -z "${CI:-}" ]; then + echo "Not running in CI environment; skipping cache cleanup" + return + fi + + case "${ID}" in + debian | ubuntu) + apt-get clean + rm -rf /var/lib/apt/lists/* + ;; + + rhel | centos | rocky | almalinux) + dnf clean -y all + rm -rf /var/cache/dnf/* + ;; + esac +} + +function verify() { + # Verify that every expected library is now resolvable by the dynamic linker. + missing=0 + for lib in libasan.so.8 libtsan.so.2 libubsan.so.1; do + if ldconfig -p | grep -q "${lib}"; then + echo "OK: ${lib} found" + else + echo "ERROR: ${lib} not found after installation" >&2 + missing=$((missing + 1)) + fi + done + + if [ "${missing}" -ne 0 ]; then + echo "ERROR: ${missing} library/libraries missing" >&2 + exit 1 + fi +} + +preinstall +install +postinstall +verify echo "All sanitizer runtime libraries installed successfully." diff --git a/nix/packages.nix b/nix/packages.nix index f282c15df9..c51077367e 100644 --- a/nix/packages.nix +++ b/nix/packages.nix @@ -12,6 +12,8 @@ in cmake conan curlMinimal # needed for codecov/codecov-action + doxygen + dpkg # needed for dpkg-buildpackage gcovr git gnumake @@ -26,6 +28,7 @@ in pkg-config pre-commit python3 + rpm # needed for rpmbuild runClangTidy vim ]; From 5b8e6cd1dd6796c94cf471c223028d817cbc3906 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Thu, 4 Jun 2026 20:35:36 +0100 Subject: [PATCH 09/78] test: Fix LCOV_EXCL_END -> LCOV_EXCL_STOP (#7407) --- src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp index cfcf79fdba..05dcfea506 100644 --- a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp @@ -300,7 +300,7 @@ VaultWithdraw::doApply() << "VaultWithdraw: " // "Cannot burn all outstanding shares while unrealized loss is non-zero"; return tefINTERNAL; - // LCOV_EXCL_END + // LCOV_EXCL_STOP } STAmount const allAvailable{vaultAsset, *assetsAvailable}; From 8abe82eefa2357777af075d252ea8613f2948ae6 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Thu, 4 Jun 2026 21:02:59 +0100 Subject: [PATCH 10/78] ci: Redesign matrix configuration based on Nix images (#7385) Co-authored-by: semgrep-companion-app[bot] <218312740+semgrep-companion-app[bot]@users.noreply.github.com> --- .github/actions/build-deps/action.yml | 3 +- .github/actions/set-compiler-env/action.yml | 34 + .github/actions/setup-conan/action.yml | 25 +- .github/scripts/strategy-matrix/generate.py | 579 +++++++----------- .github/scripts/strategy-matrix/linux.json | 300 +++------ .github/scripts/strategy-matrix/macos.json | 24 +- .github/scripts/strategy-matrix/windows.json | 23 +- .github/workflows/on-tag.yml | 1 - .github/workflows/on-trigger.yml | 1 - .../workflows/reusable-build-test-config.yml | 49 +- .github/workflows/reusable-build-test.yml | 12 +- .github/workflows/reusable-package.yml | 39 +- .../workflows/reusable-strategy-matrix.yml | 15 +- .github/workflows/upload-conan-deps.yml | 11 +- cmake/XrplCompiler.cmake | 32 +- conan/profiles/ci | 7 + cspell.config.yaml | 1 + docker/check-tools.sh | 2 - nix/packages.nix | 2 - 19 files changed, 512 insertions(+), 648 deletions(-) create mode 100644 .github/actions/set-compiler-env/action.yml diff --git a/.github/actions/build-deps/action.yml b/.github/actions/build-deps/action.yml index 0891d56dfa..044c264ef0 100644 --- a/.github/actions/build-deps/action.yml +++ b/.github/actions/build-deps/action.yml @@ -35,9 +35,8 @@ runs: LOG_VERBOSITY: ${{ inputs.log_verbosity }} SANITIZERS: ${{ inputs.sanitizers }} run: | - echo 'Installing dependencies.' conan install \ - --profile ci \ + --profile:all ci \ --build="${BUILD_OPTION}" \ --options:host='&:tests=True' \ --options:host='&:xrpld=True' \ diff --git a/.github/actions/set-compiler-env/action.yml b/.github/actions/set-compiler-env/action.yml new file mode 100644 index 0000000000..a16dde2b30 --- /dev/null +++ b/.github/actions/set-compiler-env/action.yml @@ -0,0 +1,34 @@ +name: Set compiler environment +description: "Set CC and CXX environment variables for the given compiler." + +inputs: + compiler: + description: 'The compiler to use ("gcc" or "clang").' + required: true + +runs: + using: composite + + steps: + - name: Set CC and CXX for gcc + if: ${{ inputs.compiler == 'gcc' }} + shell: bash + run: | + echo "CC=gcc" >>"${GITHUB_ENV}" + echo "CXX=g++" >>"${GITHUB_ENV}" + + - name: Set CC and CXX for clang + if: ${{ inputs.compiler == 'clang' }} + shell: bash + run: | + echo "CC=clang" >>"${GITHUB_ENV}" + echo "CXX=clang++" >>"${GITHUB_ENV}" + + - name: Fail on unknown compiler + if: ${{ inputs.compiler != 'gcc' && inputs.compiler != 'clang' }} + shell: bash + env: + COMPILER: ${{ inputs.compiler }} + run: | + echo "Unknown compiler: $COMPILER" >&2 + exit 1 diff --git a/.github/actions/setup-conan/action.yml b/.github/actions/setup-conan/action.yml index 9d834884d2..0dd22f0d92 100644 --- a/.github/actions/setup-conan/action.yml +++ b/.github/actions/setup-conan/action.yml @@ -15,32 +15,35 @@ runs: using: composite steps: - - name: Set up Conan configuration + - name: Apply custom configuration to global.conf shell: bash run: | - echo 'Installing configuration.' cat conan/global.conf ${{ runner.os == 'Linux' && '>>' || '>' }} $(conan config home)/global.conf - echo 'Conan configuration:' - conan config show '*' - - - name: Set up Conan profile + - name: Show global configuration + shell: bash + run: | + conan config show '*' + + - name: Install profiles shell: bash run: | - echo 'Installing profile.' conan config install conan/profiles/ -tf $(conan config home)/profiles/ - echo 'Conan profile:' + - name: Show CI profile + shell: bash + run: | conan profile show --profile ci - - name: Set up Conan remote + - name: Add a remote shell: bash env: REMOTE_NAME: ${{ inputs.remote_name }} REMOTE_URL: ${{ inputs.remote_url }} run: | - echo "Adding Conan remote '${REMOTE_NAME}' at '${REMOTE_URL}'." conan remote add --index 0 --force "${REMOTE_NAME}" "${REMOTE_URL}" - echo 'Listing Conan remotes.' + - name: List remotes + shell: bash + run: | conan remote list diff --git a/.github/scripts/strategy-matrix/generate.py b/.github/scripts/strategy-matrix/generate.py index 6eccfcc6be..aaf84a51d0 100755 --- a/.github/scripts/strategy-matrix/generate.py +++ b/.github/scripts/strategy-matrix/generate.py @@ -1,384 +1,281 @@ #!/usr/bin/env python3 import argparse +import dataclasses import itertools import json -from dataclasses import dataclass from pathlib import Path THIS_DIR = Path(__file__).parent.resolve() +_BASE_CMAKE_ARGS = ["-Dtests=ON", "-Dwerr=ON", "-Dxrpld=ON", "-Dwextra=ON"] -@dataclass -class Config: - architecture: list[dict] - os: list[dict] +# Maps sanitizer names (as used in cmake) to short config-name suffixes. +_SANITIZER_SUFFIX: dict[str, str] = { + "address": "asan", + "undefinedbehavior": "ubsan", + "thread": "tsan", +} + + +def get_cmake_args(build_type: str, extra_args: str) -> str: + """Get the full list of CMake arguments for a config.""" + args = _BASE_CMAKE_ARGS.copy() + if build_type == "Release": + args.append("-Dassert=ON") + if extra_args: + args.extend(extra_args.split()) + return " ".join(args) + + +# --------------------------------------------------------------------------- +# Input types — shapes of the JSON config files +# --------------------------------------------------------------------------- + + +@dataclasses.dataclass +class LinuxConfig: + """One entry in linux.json's 'configs' or 'package_configs' arrays.""" + + compiler: list[str] build_type: list[str] - cmake_args: list[str] + arch: list[str] + sanitizers: list[str] = dataclasses.field(default_factory=list) + suffix: str = "" + extra_cmake_args: str = "" + image: str = "" # only used by package_configs entries -""" -Generate a strategy matrix for GitHub Actions CI. +@dataclasses.dataclass +class LinuxFile: + """Shape of linux.json.""" -On each PR commit we will build a selection of Debian, RHEL, Ubuntu, MacOS, and -Windows configurations, while upon merge into the develop or release branches, -we will build all configurations, and test most of them. + image_tag: str + configs: dict[str, list[LinuxConfig]] # distro → configs + package_configs: dict[str, list[LinuxConfig]] # distro → packaging configs -We will further set additional CMake arguments as follows: -- All builds will have the `tests`, `werr`, and `xrpld` options. -- All builds will have the `wextra` option except for GCC 12 and Clang 16. -- All release builds will have the `assert` option. -- Certain Debian Bookworm configurations will change the reference fee, enable - codecov, and enable voidstar in PRs. -""" + @classmethod + def load(cls, path: Path) -> "LinuxFile": + data = json.loads(path.read_text()) + + def parse(section: dict) -> dict[str, list[LinuxConfig]]: + return { + distro: [LinuxConfig(**c) for c in cfgs] + for distro, cfgs in section.items() + } + + return cls( + image_tag=data["image_tag"], + configs=parse(data["configs"]), + package_configs=parse(data.get("package_configs", {})), + ) -def build_config_name(os_entry: dict[str, str], platform: str, build_type: str) -> str: - parts = [os_entry["distro_name"]] - for key in ("distro_version", "compiler_name", "compiler_version"): - if value := os_entry[key]: - parts.append(value) - parts.append("arm64" if "arm64" in platform else "amd64") - parts.append(build_type.lower()) - return "-".join(parts) +@dataclasses.dataclass +class PlatformConfig: + """One entry in macos.json's or windows.json's 'configs' array.""" + + build_type: list[str] + build_only: bool = False # if true, skip tests (e.g. macos/Windows Debug) + extra_cmake_args: str = "" + + def __post_init__(self) -> None: + if isinstance(self.build_type, str): + self.build_type = [self.build_type] -def generate_packaging_matrix(config: Config) -> list[dict]: - """Emit one entry per os entry with `package: true`. Architecture is - hardcoded to linux/amd64 here (and the runner is hardcoded at the - workflow level) until arm64 packaging is ready. +@dataclasses.dataclass +class PlatformFile: + """Shape of macos.json and windows.json.""" + + platform: str # e.g. "macos/arm64" or "windows/amd64" + runner: list[str] # GitHub Actions runner labels + configs: list[PlatformConfig] + + @classmethod + def load(cls, path: Path) -> "PlatformFile": + data = json.loads(path.read_text()) + return cls( + platform=data["platform"], + runner=data["runner"], + configs=[PlatformConfig(**c) for c in data["configs"]], + ) + + +# --------------------------------------------------------------------------- +# Output types — shapes of the generated GitHub Actions matrix entries +# --------------------------------------------------------------------------- + + +@dataclasses.dataclass +class Architecture: + platform: str + runner: list[str] + + +@dataclasses.dataclass +class MatrixEntry: + """One entry in the generated build/test strategy matrix.""" + + config_name: str + cmake_args: str + cmake_target: str + build_only: bool + build_type: str + architecture: Architecture + sanitizers: str + image: str = "" # container image; empty for macOS/Windows (runs natively) + compiler: str = "" # compiler name ("gcc" or "clang"); empty for macOS/Windows + + +@dataclasses.dataclass +class PackagingEntry: + """One entry in the generated packaging strategy matrix.""" + + artifact_name: str + image: str + distro: str # e.g. "debian" or "rhel"; drives package-format-specific steps + + +# --------------------------------------------------------------------------- +# Matrix expansion +# --------------------------------------------------------------------------- + +_ARCHS: dict[str, Architecture] = { + "amd64": Architecture( + platform="linux/amd64", runner=["self-hosted", "Linux", "X64", "heavy"] + ), + "arm64": Architecture( + platform="linux/arm64", + runner=["self-hosted", "Linux", "ARM64", "heavy-arm64"], + ), +} + + +def expand_linux_matrix(linux: LinuxFile) -> list[MatrixEntry]: + """Expand a LinuxFile into a flat list of matrix entries. + + Each config entry is expanded over the cross-product of its + compiler, build_type, sanitizers, and architecture lists. """ - return [ - { - "artifact_name": f"xrpld-{build_config_name(os, 'linux/amd64', 'Release')}", - "os": os, - } - for os in config.os - if os.get("package", False) - ] + entries: list[MatrixEntry] = [] + for distro, configs in linux.configs.items(): + for cfg in configs: + # An empty sanitizers list means "one entry with no sanitizer". + effective_sanitizers = cfg.sanitizers or [""] + effective_archs = {arch: _ARCHS[arch] for arch in cfg.arch} -def generate_strategy_matrix(all: bool, config: Config) -> list[dict]: - configurations = [] - for architecture, os, build_type, cmake_args in itertools.product( - config.architecture, config.os, config.build_type, config.cmake_args - ): - # The default CMake target is 'all' for Linux and MacOS and 'install' - # for Windows, but it can get overridden for certain configurations. - cmake_target = "install" if os["distro_name"] == "windows" else "all" - - # We build and test all configurations by default, except for Windows in - # Debug, because it is too slow, as well as when code coverage is - # enabled as that mode already runs the tests. - build_only = False - if os["distro_name"] == "windows" and build_type == "Debug": - build_only = True - - # Only generate a subset of configurations in PRs. - if not all: - # Debian: - # - Bookworm using GCC 13: Debug on linux/amd64, set the reference - # fee to 500 and enable code coverage (which will be done below). - # - Bookworm using GCC 15: Debug on linux/amd64, enable Address and - # UB sanitizers (which will be done below). - # - Bookworm using Clang 16: Debug on linux/amd64, enable voidstar. - # - Bookworm using Clang 17: Release on linux/amd64, set the - # reference fee to 1000. - # - Bookworm using Clang 20: Debug on linux/amd64, enable Address - # and UB sanitizers (which will be done below). - if os["distro_name"] == "debian": - skip = True - if os["distro_version"] == "bookworm": - if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-13" - and build_type == "Debug" - and architecture["platform"] == "linux/amd64" - ): - cmake_args = f"-DUNIT_TEST_REFERENCE_FEE=500 {cmake_args}" - skip = False - if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-15" - and build_type == "Release" - and architecture["platform"] == "linux/amd64" - ): - skip = False - if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "clang-16" - and build_type == "Debug" - and architecture["platform"] == "linux/amd64" - ): - cmake_args = f"-Dvoidstar=ON {cmake_args}" - skip = False - if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "clang-17" - and build_type == "Release" - and architecture["platform"] == "linux/amd64" - ): - cmake_args = f"-DUNIT_TEST_REFERENCE_FEE=1000 {cmake_args}" - skip = False - elif os["distro_version"] == "trixie": - if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "clang-22" - and build_type == "Debug" - and architecture["platform"] == "linux/amd64" - ): - skip = False - if skip: - continue - - # RHEL: - # - 9 using GCC 12: Debug and Release on linux/amd64 - # (Release is required for RPM packaging). - # - 10 using Clang: Release on linux/amd64. - if os["distro_name"] == "rhel": - skip = True - if os["distro_version"] == "9": - if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-12" - and build_type in ["Debug", "Release"] - and architecture["platform"] == "linux/amd64" - ): - skip = False - elif os["distro_version"] == "10": - if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "clang-any" - and build_type == "Release" - and architecture["platform"] == "linux/amd64" - ): - skip = False - if skip: - continue - - # Ubuntu: - # - Jammy using GCC 12: Debug on linux/arm64, Release on - # linux/amd64 (Release is required for DEB packaging). - # - Noble using GCC 14: Release on linux/amd64. - # - Noble using Clang 18: Debug on linux/amd64. - # - Noble using Clang 19: Release on linux/arm64. - if os["distro_name"] == "ubuntu": - skip = True - if os["distro_version"] == "jammy": - if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-12" - and build_type == "Debug" - and architecture["platform"] == "linux/arm64" - ): - skip = False - if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-12" - and build_type == "Release" - and architecture["platform"] == "linux/amd64" - ): - skip = False - elif os["distro_version"] == "noble": - if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-14" - and build_type == "Release" - and architecture["platform"] == "linux/amd64" - ): - skip = False - if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "clang-18" - and build_type == "Debug" - and architecture["platform"] == "linux/amd64" - ): - skip = False - if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "clang-19" - and build_type == "Release" - and architecture["platform"] == "linux/arm64" - ): - skip = False - if skip: - continue - - # MacOS: - # - Debug on macos/arm64. - if os["distro_name"] == "macos" and not ( - build_type == "Debug" and architecture["platform"] == "macos/arm64" + for compiler, build_type, sanitizer, (arch, arch_info) in itertools.product( + cfg.compiler, + cfg.build_type, + effective_sanitizers, + effective_archs.items(), ): - continue + name = f"{distro}-{compiler}-{build_type.lower()}-{arch}" + suffix_parts = [ + s for s in [cfg.suffix, _SANITIZER_SUFFIX.get(sanitizer, "")] if s + ] + if suffix_parts: + name += "-" + "-".join(suffix_parts) - # Windows: - # - Release on windows/amd64. - if os["distro_name"] == "windows" and not ( - build_type == "Release" and architecture["platform"] == "windows/amd64" - ): - continue - - # Additional CMake arguments. - cmake_args = f"{cmake_args} -Dtests=ON -Dwerr=ON -Dxrpld=ON" - if not f"{os['compiler_name']}-{os['compiler_version']}" in [ - "gcc-12", - "clang-16", - ]: - cmake_args = f"{cmake_args} -Dwextra=ON" - if build_type == "Release": - cmake_args = f"{cmake_args} -Dassert=ON" - - # We skip all RHEL on arm64 due to a build failure that needs further - # investigation. - if os["distro_name"] == "rhel" and architecture["platform"] == "linux/arm64": - continue - - # We skip all clang 20+ on arm64 due to Boost build error. - if ( - os["compiler_name"] == "clang" - and os["compiler_version"].isdigit() - and int(os["compiler_version"]) >= 20 - and architecture["platform"] == "linux/arm64" - ): - continue - - # Enable code coverage for Debian Bookworm using GCC 13 in Debug on - # linux/amd64. - if ( - f"{os['distro_name']}-{os['distro_version']}" == "debian-bookworm" - and f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-13" - and build_type == "Debug" - and architecture["platform"] == "linux/amd64" - ): - cmake_args = f"{cmake_args} -Dcoverage=ON -Dcoverage_format=xml -DCODE_COVERAGE_VERBOSE=ON -DCMAKE_C_FLAGS=-O0 -DCMAKE_CXX_FLAGS=-O0" - - # Enable unity build for Ubuntu Jammy using GCC 12 in Debug on - # linux/amd64. - if ( - f"{os['distro_name']}-{os['distro_version']}" == "ubuntu-jammy" - and f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-12" - and build_type == "Debug" - and architecture["platform"] == "linux/amd64" - ): - cmake_args = f"{cmake_args} -Dunity=ON" - - # Generate a unique name for the configuration, e.g. macos-arm64-debug - # or debian-bookworm-gcc-12-amd64-release. - config_name = build_config_name(os, architecture["platform"], build_type) - if "-Dcoverage=ON" in cmake_args: - config_name += "-coverage" - if "-Dunity=ON" in cmake_args: - config_name += "-unity" - - # Add the configuration to the list, with the most unique fields first, - # so that they are easier to identify in the GitHub Actions UI, as long - # names get truncated. - # Add Address and UB sanitizers as separate configurations for specific - # bookworm distros. Thread sanitizer is currently disabled (see below). - # GCC-Asan xrpld-embedded tests are failing because of https://github.com/google/sanitizers/issues/856 - if ( - os["distro_version"] == "bookworm" - and f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-15" - ) or ( - os["distro_version"] == "trixie" - and f"{os['compiler_name']}-{os['compiler_version']}" == "clang-22" - ): - # Add ASAN and UBSAN configurations for both gcc-15 and clang-22 - configurations.append( - { - "config_name": config_name + "-asan", - "cmake_args": cmake_args, - "cmake_target": cmake_target, - "build_only": build_only, - "build_type": build_type, - "os": os, - "architecture": architecture, - "sanitizers": "address", - } - ) - configurations.append( - { - "config_name": config_name + "-ubsan", - "cmake_args": cmake_args, - "cmake_target": cmake_target, - "build_only": build_only, - "build_type": build_type, - "os": os, - "architecture": architecture, - "sanitizers": "undefinedbehavior", - } - ) - # TSAN is deactivated due to seg faults with latest compilers. - activate_tsan = False - if activate_tsan: - configurations.append( - { - "config_name": config_name + "-tsan-ubsan", - "cmake_args": cmake_args, - "cmake_target": cmake_target, - "build_only": build_only, - "build_type": build_type, - "os": os, - "architecture": architecture, - "sanitizers": "thread,undefinedbehavior", - } + entries.append( + MatrixEntry( + config_name=name, + image=f"ghcr.io/xrplf/xrpld/nix-{distro}:{linux.image_tag}", + cmake_args=get_cmake_args(build_type, cfg.extra_cmake_args), + cmake_target="all", + build_only=False, + build_type=build_type, + architecture=arch_info, + sanitizers=sanitizer, + compiler=compiler, + ) + ) + + return entries + + +def expand_linux_packaging(linux: LinuxFile) -> list[PackagingEntry]: + """Generate the packaging matrix from a LinuxFile's package_configs section. + + Packaging uses vanilla distro images (debian:bookworm, ubi9, …) instead of + the nix-based build images, because deb/rpm tooling (debhelper, rpm-build) + is taken from the distro's archive rather than from nixpkgs. Each config + entry carries its own 'image'. + """ + entries = [] + for distro, configs in linux.package_configs.items(): + for cfg in configs: + for compiler, build_type in itertools.product(cfg.compiler, cfg.build_type): + entries.append( + PackagingEntry( + artifact_name=f"xrpld-{distro}-{compiler}-{build_type.lower()}-amd64", + image=cfg.image, + distro=distro, + ) + ) + + return entries + + +def expand_platform_matrix(pf: PlatformFile) -> list[MatrixEntry]: + """Expand a PlatformFile (macOS or Windows) into matrix entries.""" + platform_name, arch = pf.platform.split("/") + is_windows = platform_name == "windows" + + entries: list[MatrixEntry] = [] + for cfg in pf.configs: + for build_type in cfg.build_type: + entries.append( + MatrixEntry( + config_name=f"{platform_name}-{arch}-{build_type.lower()}", + cmake_args=get_cmake_args(build_type, cfg.extra_cmake_args), + cmake_target="install" if is_windows else "all", + build_only=cfg.build_only, + build_type=build_type, + architecture=Architecture(platform=pf.platform, runner=pf.runner), + sanitizers="", ) - else: - configurations.append( - { - "config_name": config_name, - "cmake_args": cmake_args, - "cmake_target": cmake_target, - "build_only": build_only, - "build_type": build_type, - "os": os, - "architecture": architecture, - "sanitizers": "", - } ) - - return configurations + return entries -def read_config(file: Path) -> Config: - config = json.loads(file.read_text()) - if ( - config["architecture"] is None - or config["os"] is None - or config["build_type"] is None - or config["cmake_args"] is None - ): - raise Exception("Invalid configuration file.") - - return Config(**config) +# --------------------------------------------------------------------------- +# Entry point +# --------------------------------------------------------------------------- if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument( - "-a", - "--all", - help="Set to generate all configurations (generally used when merging a PR) or leave unset to generate a subset of configurations (generally used when committing to a PR).", - action="store_true", + parser = argparse.ArgumentParser( + description="Generate a CI strategy matrix for all platforms or a specific one." ) parser.add_argument( "-c", "--config", - help="Path to the JSON file containing the strategy matrix configurations.", - required=False, - type=Path, + help="Platform to generate for ('linux', 'macos', or 'windows'). Defaults to all platforms.", + choices=["linux", "macos", "windows"], + default=None, ) parser.add_argument( "-p", "--packaging", - help="Emit the packaging matrix (derived from the 'package' field on os entries) instead of the build/test matrix.", + help="Emit the Linux packaging matrix instead of the build/test matrix.", action="store_true", ) args = parser.parse_args() - matrix = [] - if args.packaging: - config_path = args.config if args.config else THIS_DIR / "linux.json" - matrix += generate_packaging_matrix(read_config(config_path)) - elif args.config is None or args.config == "": - matrix += generate_strategy_matrix( - args.all, read_config(THIS_DIR / "linux.json") - ) - matrix += generate_strategy_matrix( - args.all, read_config(THIS_DIR / "macos.json") - ) - matrix += generate_strategy_matrix( - args.all, read_config(THIS_DIR / "windows.json") - ) - else: - matrix += generate_strategy_matrix(args.all, read_config(args.config)) + matrix: list[MatrixEntry] | list[PackagingEntry] = [] - # Generate the strategy matrix. - print(f"matrix={json.dumps({'include': matrix})}") + if args.packaging: + matrix = expand_linux_packaging(LinuxFile.load(THIS_DIR / "linux.json")) + else: + if args.config in ("linux", None): + matrix += expand_linux_matrix(LinuxFile.load(THIS_DIR / "linux.json")) + if args.config in ("macos", None): + matrix += expand_platform_matrix(PlatformFile.load(THIS_DIR / "macos.json")) + if args.config in ("windows", None): + matrix += expand_platform_matrix( + PlatformFile.load(THIS_DIR / "windows.json") + ) + + print(f"matrix={json.dumps({'include': [dataclasses.asdict(e) for e in matrix]})}") diff --git a/.github/scripts/strategy-matrix/linux.json b/.github/scripts/strategy-matrix/linux.json index 4f090a81a3..3070b8d9f4 100644 --- a/.github/scripts/strategy-matrix/linux.json +++ b/.github/scripts/strategy-matrix/linux.json @@ -1,221 +1,83 @@ { - "architecture": [ - { - "platform": "linux/amd64", - "runner": ["self-hosted", "Linux", "X64", "heavy"] - }, - { - "platform": "linux/arm64", - "runner": ["self-hosted", "Linux", "ARM64", "heavy-arm64"] - } - ], - "os": [ - { - "distro_name": "debian", - "distro_version": "bookworm", - "compiler_name": "gcc", - "compiler_version": "12", - "image_sha": "4c086b9" - }, - { - "distro_name": "debian", - "distro_version": "bookworm", - "compiler_name": "gcc", - "compiler_version": "13", - "image_sha": "4c086b9" - }, - { - "distro_name": "debian", - "distro_version": "bookworm", - "compiler_name": "gcc", - "compiler_version": "14", - "image_sha": "4c086b9" - }, - { - "distro_name": "debian", - "distro_version": "bookworm", - "compiler_name": "gcc", - "compiler_version": "15", - "image_sha": "4c086b9" - }, - { - "distro_name": "debian", - "distro_version": "bookworm", - "compiler_name": "clang", - "compiler_version": "16", - "image_sha": "4c086b9" - }, - { - "distro_name": "debian", - "distro_version": "bookworm", - "compiler_name": "clang", - "compiler_version": "17", - "image_sha": "4c086b9" - }, - { - "distro_name": "debian", - "distro_version": "bookworm", - "compiler_name": "clang", - "compiler_version": "18", - "image_sha": "4c086b9" - }, - { - "distro_name": "debian", - "distro_version": "bookworm", - "compiler_name": "clang", - "compiler_version": "19", - "image_sha": "4c086b9" - }, - { - "distro_name": "debian", - "distro_version": "bookworm", - "compiler_name": "clang", - "compiler_version": "20", - "image_sha": "4c086b9" - }, - { - "distro_name": "debian", - "distro_version": "trixie", - "compiler_name": "gcc", - "compiler_version": "14", - "image_sha": "4c086b9" - }, - { - "distro_name": "debian", - "distro_version": "trixie", - "compiler_name": "gcc", - "compiler_version": "15", - "image_sha": "4c086b9" - }, - { - "distro_name": "debian", - "distro_version": "trixie", - "compiler_name": "clang", - "compiler_version": "20", - "image_sha": "4c086b9" - }, - { - "distro_name": "debian", - "distro_version": "trixie", - "compiler_name": "clang", - "compiler_version": "21", - "image_sha": "4c086b9" - }, - { - "distro_name": "debian", - "distro_version": "trixie", - "compiler_name": "clang", - "compiler_version": "22", - "image_sha": "4c086b9" - }, - { - "distro_name": "rhel", - "distro_version": "8", - "compiler_name": "gcc", - "compiler_version": "14", - "image_sha": "4c086b9" - }, - { - "distro_name": "rhel", - "distro_version": "8", - "compiler_name": "clang", - "compiler_version": "any", - "image_sha": "4c086b9" - }, - { - "distro_name": "rhel", - "distro_version": "9", - "compiler_name": "gcc", - "compiler_version": "12", - "image_sha": "4c086b9", - "package": true - }, - { - "distro_name": "rhel", - "distro_version": "9", - "compiler_name": "gcc", - "compiler_version": "13", - "image_sha": "4c086b9" - }, - { - "distro_name": "rhel", - "distro_version": "9", - "compiler_name": "gcc", - "compiler_version": "14", - "image_sha": "4c086b9" - }, - { - "distro_name": "rhel", - "distro_version": "9", - "compiler_name": "clang", - "compiler_version": "any", - "image_sha": "4c086b9" - }, - { - "distro_name": "rhel", - "distro_version": "10", - "compiler_name": "gcc", - "compiler_version": "14", - "image_sha": "4c086b9" - }, - { - "distro_name": "rhel", - "distro_version": "10", - "compiler_name": "clang", - "compiler_version": "any", - "image_sha": "4c086b9" - }, - { - "distro_name": "ubuntu", - "distro_version": "jammy", - "compiler_name": "gcc", - "compiler_version": "12", - "image_sha": "4c086b9", - "package": true - }, - { - "distro_name": "ubuntu", - "distro_version": "noble", - "compiler_name": "gcc", - "compiler_version": "13", - "image_sha": "4c086b9" - }, - { - "distro_name": "ubuntu", - "distro_version": "noble", - "compiler_name": "gcc", - "compiler_version": "14", - "image_sha": "4c086b9" - }, - { - "distro_name": "ubuntu", - "distro_version": "noble", - "compiler_name": "clang", - "compiler_version": "16", - "image_sha": "4c086b9" - }, - { - "distro_name": "ubuntu", - "distro_version": "noble", - "compiler_name": "clang", - "compiler_version": "17", - "image_sha": "4c086b9" - }, - { - "distro_name": "ubuntu", - "distro_version": "noble", - "compiler_name": "clang", - "compiler_version": "18", - "image_sha": "4c086b9" - }, - { - "distro_name": "ubuntu", - "distro_version": "noble", - "compiler_name": "clang", - "compiler_version": "19", - "image_sha": "4c086b9" - } - ], - "build_type": ["Debug", "Release"], - "cmake_args": [""] + "image_tag": "sha-6c54342", + "configs": { + "ubuntu": [ + { + "compiler": ["gcc", "clang"], + "build_type": ["Debug", "Release"], + "arch": ["amd64", "arm64"] + }, + + { + "compiler": ["gcc", "clang"], + "build_type": ["Debug"], + "arch": ["amd64"], + "sanitizers": ["address", "undefinedbehavior"] + }, + + { + "compiler": ["gcc"], + "build_type": ["Debug"], + "arch": ["amd64"], + "suffix": "coverage", + "extra_cmake_args": "-DUNIT_TEST_REFERENCE_FEE=500 -Dcoverage=ON -Dcoverage_format=xml -DCODE_COVERAGE_VERBOSE=ON -DCMAKE_C_FLAGS=-O0 -DCMAKE_CXX_FLAGS=-O0" + }, + { + "compiler": ["clang"], + "build_type": ["Debug"], + "arch": ["amd64"], + "suffix": "voidstar", + "extra_cmake_args": "-Dvoidstar=ON" + }, + { + "compiler": ["clang"], + "build_type": ["Release"], + "arch": ["amd64"], + "suffix": "reffee", + "extra_cmake_args": "-DUNIT_TEST_REFERENCE_FEE=1000" + }, + { + "compiler": ["gcc"], + "build_type": ["Debug"], + "arch": ["amd64"], + "suffix": "unity", + "extra_cmake_args": "-Dunity=ON" + } + ], + + "debian": [ + { + "compiler": ["gcc"], + "build_type": ["Release"], + "arch": ["amd64"] + } + ], + + "rhel": [ + { + "compiler": ["gcc"], + "build_type": ["Release"], + "arch": ["amd64"] + } + ] + }, + "package_configs": { + "debian": [ + { + "compiler": ["gcc"], + "build_type": ["Release"], + "arch": ["amd64"], + "image": "debian:bookworm" + } + ], + + "rhel": [ + { + "compiler": ["gcc"], + "build_type": ["Release"], + "arch": ["amd64"], + "image": "registry.access.redhat.com/ubi9/ubi:latest" + } + ] + } } diff --git a/.github/scripts/strategy-matrix/macos.json b/.github/scripts/strategy-matrix/macos.json index 6fc44d0f80..5b9e32f88e 100644 --- a/.github/scripts/strategy-matrix/macos.json +++ b/.github/scripts/strategy-matrix/macos.json @@ -1,19 +1,15 @@ { - "architecture": [ + "platform": "macos/arm64", + "runner": ["self-hosted", "macOS", "ARM64", "mac-runner-m1"], + "configs": [ { - "platform": "macos/arm64", - "runner": ["self-hosted", "macOS", "ARM64", "mac-runner-m1"] - } - ], - "os": [ + "build_type": "Release", + "extra_cmake_args": "-DCMAKE_POLICY_VERSION_MINIMUM=3.5" + }, { - "distro_name": "macos", - "distro_version": "", - "compiler_name": "", - "compiler_version": "", - "image_sha": "" + "build_type": "Debug", + "extra_cmake_args": "-DCMAKE_POLICY_VERSION_MINIMUM=3.5", + "build_only": true } - ], - "build_type": ["Debug", "Release"], - "cmake_args": ["-DCMAKE_POLICY_VERSION_MINIMUM=3.5"] + ] } diff --git a/.github/scripts/strategy-matrix/windows.json b/.github/scripts/strategy-matrix/windows.json index 8c536c70f2..e4678b60db 100644 --- a/.github/scripts/strategy-matrix/windows.json +++ b/.github/scripts/strategy-matrix/windows.json @@ -1,19 +1,8 @@ { - "architecture": [ - { - "platform": "windows/amd64", - "runner": ["self-hosted", "Windows", "devbox"] - } - ], - "os": [ - { - "distro_name": "windows", - "distro_version": "", - "compiler_name": "", - "compiler_version": "", - "image_sha": "" - } - ], - "build_type": ["Debug", "Release"], - "cmake_args": [""] + "platform": "windows/amd64", + "runner": ["self-hosted", "Windows", "devbox"], + "configs": [ + { "build_type": "Release" }, + { "build_type": "Debug", "build_only": true } + ] } diff --git a/.github/workflows/on-tag.yml b/.github/workflows/on-tag.yml index b7517ccf11..42d5827cab 100644 --- a/.github/workflows/on-tag.yml +++ b/.github/workflows/on-tag.yml @@ -33,7 +33,6 @@ jobs: with: ccache_enabled: false os: ${{ matrix.os }} - strategy_matrix: minimal secrets: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/on-trigger.yml b/.github/workflows/on-trigger.yml index 803ba3c87b..74bca82019 100644 --- a/.github/workflows/on-trigger.yml +++ b/.github/workflows/on-trigger.yml @@ -88,7 +88,6 @@ jobs: # not identical to a regular compilation. ccache_enabled: ${{ github.repository_owner == 'XRPLF' && !startsWith(github.ref, 'refs/heads/release') }} os: ${{ matrix.os }} - strategy_matrix: ${{ github.event_name == 'schedule' && 'all' || 'minimal' }} secrets: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index 31457bb892..e1154f74be 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -57,6 +57,12 @@ on: type: string default: "" + compiler: + description: 'The compiler to use ("gcc" or "clang"). Leave empty for macOS/Windows (uses system default).' + required: false + type: string + default: "" + secrets: CODECOV_TOKEN: description: "The Codecov token to use for uploading coverage reports." @@ -124,6 +130,12 @@ jobs: with: subtract: ${{ inputs.nproc_subtract }} + - name: Set compiler environment (Linux) + if: ${{ runner.os == 'Linux' }} + uses: ./.github/actions/set-compiler-env + with: + compiler: ${{ inputs.compiler }} + - name: Setup Conan env: SANITIZERS: ${{ inputs.sanitizers }} @@ -191,6 +203,21 @@ jobs: --parallel "${BUILD_NPROC}" \ --target "${CMAKE_TARGET}" + # This step is needed to allow running in non-Nix environments + - name: Patch binary to use default loader and remove rpath (Linux) + if: ${{ runner.os == 'Linux' && env.SANITIZERS_ENABLED == 'false' }} + run: | + loader="$(/tmp/loader-path.sh)" + patchelf --set-interpreter "${loader}" --remove-rpath "${{ env.BUILD_DIR }}/xrpld" + + # We're only running aarch64 Linux builds in Ubuntu-based images, so this is kept simple + - name: Install libatomic (Linux aarch64) + if: ${{ runner.os == 'Linux' && runner.arch == 'ARM64' }} + run: | + apt update --yes + apt install -y --no-install-recommends \ + libatomic1 + - name: Show ccache statistics if: ${{ inputs.ccache_enabled }} run: | @@ -217,7 +244,7 @@ jobs: ./xrpld --definitions | python3 -m json.tool >server_definitions.json - name: Upload server definitions - if: ${{ github.event.repository.visibility == 'public' && inputs.config_name == 'debian-bookworm-gcc-13-amd64-release' }} + if: ${{ github.event.repository.visibility == 'public' && inputs.config_name == 'debian-gcc-release-amd64' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: server-definitions @@ -279,7 +306,25 @@ jobs: set -o pipefail # Coverage builds are slower due to instrumentation; use fewer parallel jobs to avoid flakiness [ "$COVERAGE_ENABLED" = "true" ] && BUILD_NPROC=$((BUILD_NPROC - 2)) - ./xrpld --unittest --unittest-jobs "${BUILD_NPROC}" 2>&1 | tee unittest.log + + # The resolver/preload workaround is only correct for the ASan build: + # a regular build doesn't hit the __dn_expand interceptor bug, and must + # NOT have libasan injected. So only preload when xrpld is ASan-built. + # + # libresolv hosts getaddrinfo's resolver helpers (dn_expand, res_*). Under ASan + # these are intercepted via dlsym(RTLD_NEXT, ...), which yields a NULL pointer + # and crashes DNS resolution if libresolv isn't loaded. Linking it guarantees + # the symbols are present; it's a harmless no-op on glibc >= 2.34 (merged into + # libc) and is what the compiler driver already does for sanitizer builds. + # https://github.com/llvm/llvm-project/issues/59007 + # https://github.com/google/sanitizers/issues/1592 + if ldd ./xrpld | grep -q libasan; then + PRELOAD="$(gcc -print-file-name=libasan.so):/usr/lib/x86_64-linux-gnu/libresolv.so.2" + else + PRELOAD="" + fi + + LD_PRELOAD="$PRELOAD" ./xrpld --unittest --unittest-jobs "${BUILD_NPROC}" 2>&1 | tee unittest.log - name: Show test failure summary if: ${{ failure() && !inputs.build_only }} diff --git a/.github/workflows/reusable-build-test.yml b/.github/workflows/reusable-build-test.yml index 0086cbbfb5..4b64c53521 100644 --- a/.github/workflows/reusable-build-test.yml +++ b/.github/workflows/reusable-build-test.yml @@ -19,13 +19,6 @@ on: required: true type: string - strategy_matrix: - # TODO: Support additional strategies, e.g. "ubuntu" for generating all Ubuntu configurations. - description: 'The strategy matrix to use for generating the configurations ("minimal", "all").' - required: false - type: string - default: "minimal" - secrets: CODECOV_TOKEN: description: "The Codecov token to use for uploading coverage reports." @@ -37,7 +30,6 @@ jobs: uses: ./.github/workflows/reusable-strategy-matrix.yml with: os: ${{ inputs.os }} - strategy_matrix: ${{ inputs.strategy_matrix }} # Build and test the binary for each configuration. build-test-config: @@ -47,7 +39,6 @@ jobs: strategy: fail-fast: ${{ github.event_name == 'merge_group' }} matrix: ${{ fromJson(needs.generate-matrix.outputs.matrix) }} - max-parallel: 10 with: build_only: ${{ matrix.build_only }} build_type: ${{ matrix.build_type }} @@ -55,8 +46,9 @@ jobs: cmake_args: ${{ matrix.cmake_args }} cmake_target: ${{ matrix.cmake_target }} runs_on: ${{ toJSON(matrix.architecture.runner) }} - image: ${{ contains(matrix.architecture.platform, 'linux') && format('ghcr.io/xrplf/ci/{0}-{1}:{2}-{3}-sha-{4}', matrix.os.distro_name, matrix.os.distro_version, matrix.os.compiler_name, matrix.os.compiler_version, matrix.os.image_sha) || '' }} + image: ${{ matrix.image || '' }} config_name: ${{ matrix.config_name }} sanitizers: ${{ matrix.sanitizers }} + compiler: ${{ matrix.compiler || '' }} secrets: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/reusable-package.yml b/.github/workflows/reusable-package.yml index 2a3ed8a33e..670c01733e 100644 --- a/.github/workflows/reusable-package.yml +++ b/.github/workflows/reusable-package.yml @@ -1,8 +1,7 @@ # Build Linux packages (DEB and RPM) from pre-built binary artifacts. -# Discovers which configurations to package from linux.json (os entries -# with "package": true) and fans out one job per entry. Today only -# linux/amd64 is emitted; the architecture is hardcoded both here -# (runner) and in generate.py. +# Discovers which configurations to package from linux.json (configs in +# "package_configs") and fans out one job per distro. Only linux/amd64 is +# supported; the runner is hardcoded in the job below. name: Package on: @@ -33,13 +32,12 @@ jobs: - name: Set up Python uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 with: - python-version: 3.13 + python-version: "3.13" - name: Generate packaging matrix id: generate working-directory: .github/scripts/strategy-matrix - run: | - ./generate.py --packaging --config=linux.json >>"${GITHUB_OUTPUT}" + run: ./generate.py --packaging >>"${GITHUB_OUTPUT}" generate-version: runs-on: ubuntu-latest @@ -66,10 +64,35 @@ jobs: permissions: contents: read runs-on: ["self-hosted", "Linux", "X64", "heavy"] - container: ${{ format('ghcr.io/xrplf/ci/{0}-{1}:{2}-{3}-sha-{4}', matrix.os.distro_name, matrix.os.distro_version, matrix.os.compiler_name, matrix.os.compiler_version, matrix.os.image_sha) }} + container: ${{ matrix.image }} timeout-minutes: 30 steps: + # Packaging runs in a vanilla distro image, so the tooling has to come + # from the distro's archive: debhelper for deb, rpm-build (and the + # systemd / find-debuginfo macros it depends on) for rpm. Run this + # before actions/checkout so the latter can use git (real history) for + # build_pkg.sh's SOURCE_DATE_EPOCH; otherwise it falls back to a tarball + # download and the timestamp comes from wall-clock time. + - name: Install packaging tooling (deb) + if: ${{ matrix.distro == 'debian' }} + run: | + export DEBIAN_FRONTEND=noninteractive + apt-get update + apt-get install -y --no-install-recommends \ + ca-certificates \ + debhelper \ + git + + - name: Install packaging tooling (rpm) + if: ${{ matrix.distro == 'rhel' }} + run: | + dnf install -y --setopt=install_weak_deps=False \ + git \ + rpm-build \ + redhat-rpm-config \ + systemd-rpm-macros + - name: Checkout repository uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 diff --git a/.github/workflows/reusable-strategy-matrix.yml b/.github/workflows/reusable-strategy-matrix.yml index 62d65ad3fa..16a2b4e336 100644 --- a/.github/workflows/reusable-strategy-matrix.yml +++ b/.github/workflows/reusable-strategy-matrix.yml @@ -4,15 +4,9 @@ on: workflow_call: inputs: os: - description: 'The operating system to use for the build ("linux", "macos", "windows").' + description: 'The operating system to use for the build ("linux", "macos", "windows", or empty for all).' required: false type: string - strategy_matrix: - # TODO: Support additional strategies, e.g. "ubuntu" for generating all Ubuntu configurations. - description: 'The strategy matrix to use for generating the configurations ("minimal", "all").' - required: false - type: string - default: "minimal" outputs: matrix: description: "The generated strategy matrix." @@ -34,12 +28,11 @@ jobs: - name: Set up Python uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 with: - python-version: 3.13 + python-version: "3.13" - name: Generate strategy matrix working-directory: .github/scripts/strategy-matrix id: generate env: - GENERATE_CONFIG: ${{ inputs.os != '' && format('--config={0}.json', inputs.os) || '' }} - GENERATE_OPTION: ${{ inputs.strategy_matrix == 'all' && '--all' || '' }} - run: ./generate.py ${GENERATE_OPTION} ${GENERATE_CONFIG} >>"${GITHUB_OUTPUT}" + GENERATE_CONFIG: ${{ inputs.os != '' && format('--config={0}', inputs.os) || '' }} + run: ./generate.py ${GENERATE_CONFIG} >>"${GITHUB_OUTPUT}" diff --git a/.github/workflows/upload-conan-deps.yml b/.github/workflows/upload-conan-deps.yml index 34dce28334..87465b4d3d 100644 --- a/.github/workflows/upload-conan-deps.yml +++ b/.github/workflows/upload-conan-deps.yml @@ -48,8 +48,6 @@ jobs: # Generate the strategy matrix to be used by the following job. generate-matrix: uses: ./.github/workflows/reusable-strategy-matrix.yml - with: - strategy_matrix: ${{ github.event_name == 'pull_request' && 'minimal' || 'all' }} # Build and upload the dependencies for each configuration. run-upload-conan-deps: @@ -58,9 +56,8 @@ jobs: strategy: fail-fast: false matrix: ${{ fromJson(needs.generate-matrix.outputs.matrix) }} - max-parallel: 10 runs-on: ${{ matrix.architecture.runner }} - container: ${{ contains(matrix.architecture.platform, 'linux') && format('ghcr.io/xrplf/ci/{0}-{1}:{2}-{3}-sha-{4}', matrix.os.distro_name, matrix.os.distro_version, matrix.os.compiler_name, matrix.os.compiler_version, matrix.os.image_sha) || null }} + container: ${{ matrix.image || null }} steps: - name: Cleanup workspace (macOS and Windows) if: ${{ runner.os == 'macOS' || runner.os == 'Windows' }} @@ -83,6 +80,12 @@ jobs: with: subtract: ${{ env.NPROC_SUBTRACT }} + - name: Set compiler environment (Linux) + if: ${{ runner.os == 'Linux' }} + uses: ./.github/actions/set-compiler-env + with: + compiler: ${{ matrix.compiler }} + - name: Setup Conan env: SANITIZERS: ${{ matrix.sanitizers }} diff --git a/cmake/XrplCompiler.cmake b/cmake/XrplCompiler.cmake index 0b77ff3525..9af8e962d0 100644 --- a/cmake/XrplCompiler.cmake +++ b/cmake/XrplCompiler.cmake @@ -145,13 +145,39 @@ else() INTERFACE -rdynamic $<$:-Wl,-z,relro,-z,now,--build-id> - # link to static libc/c++ iff: * static option set and * NOT APPLE (AppleClang does not support static - # libc/c++) and * NOT SANITIZERS (sanitizers typically don't work with static libc/c++) - $<$,$>,$>>: + # link to static libc/c++ if: + # * static option set and + # * NOT APPLE (AppleClang does not support static libc/c++) + $<$,$>>: -static-libstdc++ -static-libgcc > ) + + # Keep -stdlib=libstdc++ off the compile commands, but preserve it for linking. + # + # Conan turns `compiler.libcxx=libstdc++` into `-stdlib=libstdc++` and puts it in + # CMAKE_CXX_FLAGS, which CMake passes to BOTH compile and link steps. On a normal Clang + # the compile step consumes it while choosing the C++ stdlib include paths. The Nixpkgs + # Clang wrapper supplies those paths itself (via -nostdinc++), so at compile time the + # flag is unused -> Clang errors under our -Werror. At link time the flag IS consumed + # (it selects the C++ runtime), so we move it there instead of dropping it entirely. + get_filename_component(_cxx_real "${CMAKE_CXX_COMPILER}" REALPATH) + if( + _cxx_real MATCHES "^/nix/store/" + AND is_linux + AND is_clang + AND CMAKE_CXX_FLAGS MATCHES "stdlib=libstdc" + ) + string( + REPLACE "-stdlib=libstdc++" + "" + CMAKE_CXX_FLAGS + "${CMAKE_CXX_FLAGS}" + ) + string(STRIP "${CMAKE_CXX_FLAGS}" CMAKE_CXX_FLAGS) + add_link_options($<$:-stdlib=libstdc++>) + endif() endif() # Antithesis instrumentation will only be built and deployed using machines running Linux. diff --git a/conan/profiles/ci b/conan/profiles/ci index ae93187026..9422addfe3 100644 --- a/conan/profiles/ci +++ b/conan/profiles/ci @@ -1 +1,8 @@ +{% set os = detect_api.detect_os() %} include(sanitizers) + +[conf] +{% if os == "Linux" %} +user.package:libc_version=2.31 +tools.info.package_id:confs+=["user.package:libc_version"] +{% endif %} diff --git a/cspell.config.yaml b/cspell.config.yaml index da5dc9b072..cab2fc3da6 100644 --- a/cspell.config.yaml +++ b/cspell.config.yaml @@ -50,6 +50,7 @@ words: - AMMXRP - amt - amts + - archs - asnode - asynchrony - attestation diff --git a/docker/check-tools.sh b/docker/check-tools.sh index c446dc1b4a..faa6520678 100755 --- a/docker/check-tools.sh +++ b/docker/check-tools.sh @@ -10,7 +10,6 @@ cmake --version conan --version curl --version doxygen --version -dpkg-buildpackage --version g++ --version gcc --version gcov --version @@ -26,7 +25,6 @@ perl --version pkg-config --version pre-commit --version python3 --version -rpmbuild --version run-clang-tidy --help vim --version diff --git a/nix/packages.nix b/nix/packages.nix index c51077367e..6a83446d88 100644 --- a/nix/packages.nix +++ b/nix/packages.nix @@ -13,7 +13,6 @@ in conan curlMinimal # needed for codecov/codecov-action doxygen - dpkg # needed for dpkg-buildpackage gcovr git gnumake @@ -28,7 +27,6 @@ in pkg-config pre-commit python3 - rpm # needed for rpmbuild runClangTidy vim ]; From 2111bb4b9593a5c4f4a43ad1a27cde310159bdf5 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Fri, 5 Jun 2026 15:11:47 +0100 Subject: [PATCH 11/78] ci: Update clang-tidy to nix-based v22 (#7412) --- .clang-tidy | 2 +- .github/workflows/reusable-clang-tidy.yml | 7 +- include/xrpl/nodestore/detail/varint.h | 2 +- src/libxrpl/basics/Log.cpp | 3 +- src/libxrpl/basics/Number.cpp | 8 +- src/libxrpl/beast/core/CurrentThreadName.cpp | 1 - src/libxrpl/server/Port.cpp | 4 +- src/test/app/AccountDelete_test.cpp | 2 +- src/test/app/Batch_test.cpp | 972 +++++++++++++++--- src/test/app/Credentials_test.cpp | 4 +- src/test/app/CrossingLimitsMPT_test.cpp | 4 +- src/test/app/CrossingLimits_test.cpp | 4 +- src/test/app/DepositAuth_test.cpp | 87 +- src/test/app/Escrow_test.cpp | 4 +- src/test/app/LedgerReplay_test.cpp | 2 +- src/test/app/PayStrand_test.cpp | 28 +- src/test/app/PermissionedDEX_test.cpp | 6 +- src/test/app/PermissionedDomains_test.cpp | 98 +- src/test/app/TxQ_test.cpp | 2 +- src/test/app/ValidatorList_test.cpp | 87 +- src/test/app/ValidatorSite_test.cpp | 391 ++++--- src/test/basics/PerfLog_test.cpp | 2 +- .../beast/aged_associative_container_test.cpp | 6 +- src/test/core/Config_test.cpp | 16 +- src/test/jtx/impl/WSClient.cpp | 2 +- src/test/jtx/impl/permissioned_dex.cpp | 2 +- src/test/jtx/impl/permissioned_domains.cpp | 4 +- src/test/nodestore/import_test.cpp | 6 +- src/test/rpc/AccountObjects_test.cpp | 4 +- src/test/rpc/DepositAuthorized_test.cpp | 4 +- src/test/rpc/LedgerEntry_test.cpp | 49 +- src/xrpld/app/misc/detail/ValidatorList.cpp | 2 +- .../peerfinder/detail/PeerfinderConfig.cpp | 3 +- src/xrpld/rpc/detail/Pathfinder.cpp | 84 +- src/xrpld/rpc/detail/ServerHandler.cpp | 18 +- 35 files changed, 1392 insertions(+), 528 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index b23d7ccbff..2d72eae701 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -154,7 +154,7 @@ Checks: "-*, " # --- # readability-inconsistent-declaration-parameter-name, # in this codebase this check will break a lot of arg names -# readability-static-accessed-through-instance, # this check is probably unnecessary. it makes the code less readable +# readability-static-accessed-through-instance, # this check is probably unnecessary. It makes the code less readable # --- CheckOptions: diff --git a/.github/workflows/reusable-clang-tidy.yml b/.github/workflows/reusable-clang-tidy.yml index 8be1db5fb2..cfbd8af963 100644 --- a/.github/workflows/reusable-clang-tidy.yml +++ b/.github/workflows/reusable-clang-tidy.yml @@ -36,7 +36,7 @@ jobs: needs: [determine-files] if: ${{ always() && !cancelled() && (!inputs.check_only_changed || needs.determine-files.outputs.cpp_changed_files != '' || needs.determine-files.outputs.clang_tidy_config_changed == 'true') }} runs-on: ["self-hosted", "Linux", "X64", "heavy"] - container: "ghcr.io/xrplf/ci/debian-trixie:clang-21-sha-53033a2" + container: "ghcr.io/xrplf/xrpld/nix-debian:sha-8abe82e" permissions: contents: read issues: write @@ -56,6 +56,11 @@ jobs: uses: XRPLF/actions/get-nproc@cf0433aa74563aead044a1e395610c96d65a37cf id: nproc + - name: Set compiler environment + uses: ./.github/actions/set-compiler-env + with: + compiler: clang + - name: Setup Conan uses: ./.github/actions/setup-conan diff --git a/include/xrpl/nodestore/detail/varint.h b/include/xrpl/nodestore/detail/varint.h index e6b78fcf08..0c49274d70 100644 --- a/include/xrpl/nodestore/detail/varint.h +++ b/include/xrpl/nodestore/detail/varint.h @@ -25,7 +25,7 @@ struct varint_traits { explicit varint_traits() = default; - static constexpr std::size_t kMax = (8 * sizeof(T) + 6) / 7; + static constexpr std::size_t kMax = ((8 * sizeof(T)) + 6) / 7; }; // Returns: Number of bytes consumed or 0 on error, diff --git a/src/libxrpl/basics/Log.cpp b/src/libxrpl/basics/Log.cpp index 1079f91280..d1e54a515f 100644 --- a/src/libxrpl/basics/Log.cpp +++ b/src/libxrpl/basics/Log.cpp @@ -61,7 +61,8 @@ Logs::File::open(boost::filesystem::path const& path) bool wasOpened = false; // VFALCO TODO Make this work with Unicode file paths - std::unique_ptr stream(new std::ofstream(path.c_str(), std::fstream::app)); + std::unique_ptr stream = + std::make_unique(path.c_str(), std::fstream::app); if (stream->good()) { diff --git a/src/libxrpl/basics/Number.cpp b/src/libxrpl/basics/Number.cpp index 275d82d8c9..23e913bbdc 100644 --- a/src/libxrpl/basics/Number.cpp +++ b/src/libxrpl/basics/Number.cpp @@ -1241,9 +1241,11 @@ root(Number f, unsigned d) } // Quadratic least squares curve fit of f^(1/d) in the range [0, 1] - auto const D = (((6 * di + 11) * di + 6) * di) + 1; // NOLINT(readability-identifier-naming) - auto const a0 = 3 * di * ((2 * di - 3) * di + 1); - auto const a1 = 24 * di * (2 * di - 1); + + // NOLINTNEXTLINE(readability-identifier-naming) + auto const D = (((((6 * di) + 11) * di) + 6) * di) + 1; + auto const a0 = 3 * di * ((((2 * di) - 3) * di) + 1); + auto const a1 = 24 * di * ((2 * di) - 1); auto const a2 = -30 * (di - 1) * di; Number r = ((Number{a2} * f + Number{a1}) * f + Number{a0}) / Number{D}; if (neg) diff --git a/src/libxrpl/beast/core/CurrentThreadName.cpp b/src/libxrpl/beast/core/CurrentThreadName.cpp index 52d9063179..628fec5b7a 100644 --- a/src/libxrpl/beast/core/CurrentThreadName.cpp +++ b/src/libxrpl/beast/core/CurrentThreadName.cpp @@ -71,7 +71,6 @@ setCurrentThreadNameImpl(std::string_view name) #if BOOST_OS_LINUX #include -#include #include // IWYU pragma: keep namespace beast::detail { diff --git a/src/libxrpl/server/Port.cpp b/src/libxrpl/server/Port.cpp index 00c10b2b55..b3fd7a1526 100644 --- a/src/libxrpl/server/Port.cpp +++ b/src/libxrpl/server/Port.cpp @@ -26,8 +26,8 @@ namespace xrpl { bool Port::secure() const { - return protocol.count("peer") > 0 || protocol.count("https") > 0 || protocol.count("wss") > 0 || - protocol.count("wss2") > 0; + return protocol.contains("peer") || protocol.contains("https") || protocol.contains("wss") || + protocol.contains("wss2"); } std::string diff --git a/src/test/app/AccountDelete_test.cpp b/src/test/app/AccountDelete_test.cpp index 951f99919b..65ff9ed839 100644 --- a/src/test/app/AccountDelete_test.cpp +++ b/src/test/app/AccountDelete_test.cpp @@ -813,7 +813,7 @@ public: env.close(); // alice create DepositPreauth Object - env(deposit::authCredentials(alice, {{carol, credType}})); + env(deposit::authCredentials(alice, {{.issuer = carol, .credType = credType}})); env.close(); // becky attempts to delete her account, but alice won't take her diff --git a/src/test/app/Batch_test.cpp b/src/test/app/Batch_test.cpp index 8755fe9f9c..791bb5a4d6 100644 --- a/src/test/app/Batch_test.cpp +++ b/src/test/app/Batch_test.cpp @@ -1017,7 +1017,11 @@ class Batch_test : public beast::unit_test::Suite env.close(); { std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, }; validateClosedLedger(env, testCases); } @@ -1059,7 +1063,11 @@ class Batch_test : public beast::unit_test::Suite env.close(); { std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, }; validateClosedLedger(env, testCases); } @@ -1101,7 +1109,11 @@ class Batch_test : public beast::unit_test::Suite env.close(); { std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, }; validateClosedLedger(env, testCases); } @@ -1143,7 +1155,11 @@ class Batch_test : public beast::unit_test::Suite env.close(); { std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, }; validateClosedLedger(env, testCases); } @@ -1185,7 +1201,11 @@ class Batch_test : public beast::unit_test::Suite env.close(); { std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, }; validateClosedLedger(env, testCases); } @@ -1520,9 +1540,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -1552,7 +1584,11 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, }; validateClosedLedger(env, testCases); @@ -1581,7 +1617,11 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, }; validateClosedLedger(env, testCases); @@ -1610,7 +1650,11 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, }; validateClosedLedger(env, testCases); @@ -1662,10 +1706,26 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tecUNFUNDED_PAYMENT", txIDs[0], batchID}, - {2, "Payment", "tecUNFUNDED_PAYMENT", txIDs[1], batchID}, - {3, "Payment", "tecUNFUNDED_PAYMENT", txIDs[2], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tecUNFUNDED_PAYMENT", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tecUNFUNDED_PAYMENT", + .txHash = txIDs[1], + .batchID = batchID}, + {.index = 3, + .txType = "Payment", + .result = "tecUNFUNDED_PAYMENT", + .txHash = txIDs[2], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -1695,9 +1755,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tecUNFUNDED_PAYMENT", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tecUNFUNDED_PAYMENT", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -1727,8 +1799,16 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -1758,8 +1838,16 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -1789,8 +1877,16 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -1826,11 +1922,31 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "OfferCreate", "tecKILLED", txIDs[0], batchID}, - {2, "OfferCreate", "tecKILLED", txIDs[1], batchID}, - {3, "OfferCreate", "tecKILLED", txIDs[2], batchID}, - {4, "Payment", "tesSUCCESS", txIDs[3], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "OfferCreate", + .result = "tecKILLED", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "OfferCreate", + .result = "tecKILLED", + .txHash = txIDs[1], + .batchID = batchID}, + {.index = 3, + .txType = "OfferCreate", + .result = "tecKILLED", + .txHash = txIDs[2], + .batchID = batchID}, + {.index = 4, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[3], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -1878,8 +1994,16 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tecUNFUNDED_PAYMENT", txIDs[0], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tecUNFUNDED_PAYMENT", + .txHash = txIDs[0], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -1909,11 +2033,31 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, - {3, "Payment", "tesSUCCESS", txIDs[2], batchID}, - {4, "Payment", "tesSUCCESS", txIDs[3], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, + {.index = 3, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[2], + .batchID = batchID}, + {.index = 4, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[3], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -1944,10 +2088,26 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, - {3, "Payment", "tecUNFUNDED_PAYMENT", txIDs[2], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, + {.index = 3, + .txType = "Payment", + .result = "tecUNFUNDED_PAYMENT", + .txHash = txIDs[2], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -1978,9 +2138,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -2011,9 +2183,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -2044,10 +2228,26 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, - {3, "OfferCreate", "tecKILLED", txIDs[2], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, + {.index = 3, + .txType = "OfferCreate", + .result = "tecKILLED", + .txHash = txIDs[2], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -2095,11 +2295,31 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tecUNFUNDED_PAYMENT", txIDs[1], batchID}, - {3, "Payment", "tecUNFUNDED_PAYMENT", txIDs[2], batchID}, - {4, "Payment", "tesSUCCESS", txIDs[3], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tecUNFUNDED_PAYMENT", + .txHash = txIDs[1], + .batchID = batchID}, + {.index = 3, + .txType = "Payment", + .result = "tecUNFUNDED_PAYMENT", + .txHash = txIDs[2], + .batchID = batchID}, + {.index = 4, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[3], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -2130,11 +2350,31 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, - {3, "Payment", "tecUNFUNDED_PAYMENT", txIDs[2], batchID}, - {4, "Payment", "tesSUCCESS", txIDs[3], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, + {.index = 3, + .txType = "Payment", + .result = "tecUNFUNDED_PAYMENT", + .txHash = txIDs[2], + .batchID = batchID}, + {.index = 4, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[3], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -2165,10 +2405,26 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, - {3, "Payment", "tesSUCCESS", txIDs[3], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, + {.index = 3, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[3], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -2199,10 +2455,26 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, - {3, "Payment", "tesSUCCESS", txIDs[3], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, + {.index = 3, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[3], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -2232,10 +2504,26 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, - {3, "OfferCreate", "tecKILLED", txIDs[2], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, + {.index = 3, + .txType = "OfferCreate", + .result = "tecKILLED", + .txHash = txIDs[2], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -2454,9 +2742,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "AccountSet", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "AccountSet", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -2503,9 +2803,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "AccountSet", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "AccountSet", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -2558,9 +2870,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "AccountDelete", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "AccountDelete", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -2601,10 +2925,26 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "AccountDelete", "tecHAS_OBLIGATIONS", txIDs[1], batchID}, - {3, "Payment", "tesSUCCESS", txIDs[2], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "AccountDelete", + .result = "tecHAS_OBLIGATIONS", + .txHash = txIDs[1], + .batchID = batchID}, + {.index = 3, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[2], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -2642,7 +2982,11 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, }; validateClosedLedger(env, testCases); @@ -2876,9 +3220,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "CheckCreate", "tesSUCCESS", txIDs[0], batchID}, - {2, "CheckCash", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "CheckCreate", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "CheckCash", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -2922,9 +3278,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "CheckCreate", "tecDST_TAG_NEEDED", txIDs[0], batchID}, - {2, "CheckCash", "tecNO_ENTRY", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "CheckCreate", + .result = "tecDST_TAG_NEEDED", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "CheckCash", + .result = "tecNO_ENTRY", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -2987,10 +3355,26 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "TicketCreate", "tesSUCCESS", txIDs[0], batchID}, - {2, "CheckCreate", "tesSUCCESS", txIDs[1], batchID}, - {3, "CheckCash", "tesSUCCESS", txIDs[2], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "TicketCreate", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "CheckCreate", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, + {.index = 3, + .txType = "CheckCash", + .result = "tesSUCCESS", + .txHash = txIDs[2], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -3047,9 +3431,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "CheckCreate", "tesSUCCESS", txIDs[0], batchID}, - {2, "CheckCash", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "CheckCreate", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "CheckCash", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -3099,9 +3495,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -3147,9 +3555,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -3196,9 +3616,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -3257,9 +3689,21 @@ class Batch_test : public beast::unit_test::Suite { std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); } @@ -3268,7 +3712,11 @@ class Batch_test : public beast::unit_test::Suite { // next ledger contains noop txn std::vector const testCases = { - {0, "AccountSet", "tesSUCCESS", noopTxnID, std::nullopt}, + {.index = 0, + .txType = "AccountSet", + .result = "tesSUCCESS", + .txHash = noopTxnID, + .batchID = std::nullopt}, }; validateClosedLedger(env, testCases); } @@ -3301,9 +3749,21 @@ class Batch_test : public beast::unit_test::Suite { std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); } @@ -3340,9 +3800,21 @@ class Batch_test : public beast::unit_test::Suite { std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); } @@ -3382,10 +3854,26 @@ class Batch_test : public beast::unit_test::Suite { std::vector const testCases = { - {0, "AccountSet", "tesSUCCESS", noopTxnID, std::nullopt}, - {1, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {2, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {3, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "AccountSet", + .result = "tesSUCCESS", + .txHash = noopTxnID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 3, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); } @@ -3442,9 +3930,21 @@ class Batch_test : public beast::unit_test::Suite { std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); } @@ -3489,9 +3989,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); { std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); } @@ -3552,10 +4064,26 @@ class Batch_test : public beast::unit_test::Suite env.close(); { std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "CheckCreate", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, - {3, "CheckCash", "tesSUCCESS", objTxnID, std::nullopt}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "CheckCreate", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, + {.index = 3, + .txType = "CheckCash", + .result = "tesSUCCESS", + .txHash = objTxnID, + .batchID = std::nullopt}, }; validateClosedLedger(env, testCases); } @@ -3601,10 +4129,26 @@ class Batch_test : public beast::unit_test::Suite env.close(); { std::vector const testCases = { - {0, "CheckCreate", "tesSUCCESS", objTxnID, std::nullopt}, - {1, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {2, "CheckCash", "tesSUCCESS", txIDs[0], batchID}, - {3, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "CheckCreate", + .result = "tesSUCCESS", + .txHash = objTxnID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 2, + .txType = "CheckCash", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 3, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); } @@ -3646,10 +4190,26 @@ class Batch_test : public beast::unit_test::Suite env.close(); { std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "CheckCreate", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, - {3, "CheckCash", "tesSUCCESS", objTxnID, std::nullopt}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "CheckCreate", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, + {.index = 3, + .txType = "CheckCash", + .result = "tesSUCCESS", + .txHash = objTxnID, + .batchID = std::nullopt}, }; validateClosedLedger(env, testCases); } @@ -3742,10 +4302,26 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Payment", "tesSUCCESS", payTxn1ID, std::nullopt}, - {1, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {2, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {3, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = payTxn1ID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 3, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -3753,7 +4329,11 @@ class Batch_test : public beast::unit_test::Suite { // next ledger includes the payment txn std::vector const testCases = { - {0, "Payment", "tesSUCCESS", payTxn2ID, std::nullopt}, + {.index = 0, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = payTxn2ID, + .batchID = std::nullopt}, }; validateClosedLedger(env, testCases); } @@ -3965,9 +4545,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -4014,9 +4606,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -4064,9 +4668,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "AccountSet", "tesSUCCESS", txIDs[0], batchID}, - {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "AccountSet", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "Payment", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); @@ -4126,9 +4742,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "MPTokenIssuanceSet", "tesSUCCESS", txIDs[0], batchID}, - {2, "MPTokenIssuanceSet", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "MPTokenIssuanceSet", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "MPTokenIssuanceSet", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); } @@ -4167,9 +4795,21 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "TrustSet", "tesSUCCESS", txIDs[0], batchID}, - {2, "TrustSet", "tesSUCCESS", txIDs[1], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "TrustSet", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, + {.index = 2, + .txType = "TrustSet", + .result = "tesSUCCESS", + .txHash = txIDs[1], + .batchID = batchID}, }; validateClosedLedger(env, testCases); } @@ -4207,8 +4847,16 @@ class Batch_test : public beast::unit_test::Suite env.close(); std::vector const testCases = { - {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, - {1, "TrustSet", "tesSUCCESS", txIDs[0], batchID}, + {.index = 0, + .txType = "Batch", + .result = "tesSUCCESS", + .txHash = batchID, + .batchID = std::nullopt}, + {.index = 1, + .txType = "TrustSet", + .result = "tesSUCCESS", + .txHash = txIDs[0], + .batchID = batchID}, // jv2 fails with terNO_DELEGATE_PERMISSION. }; validateClosedLedger(env, testCases); diff --git a/src/test/app/Credentials_test.cpp b/src/test/app/Credentials_test.cpp index 9416ca222f..456a53bc01 100644 --- a/src/test/app/Credentials_test.cpp +++ b/src/test/app/Credentials_test.cpp @@ -1078,7 +1078,7 @@ struct Credentials_test : public beast::unit_test::Suite } // Create DepositPreauth - env(deposit::authCredentials(becky, {{subject, credType}})); + env(deposit::authCredentials(becky, {{.issuer = subject, .credType = credType}})); env.close(); // env(); auto jtx = env.jt(pay(subject, becky, XRP(100)), credentials::Ids({credIdx})); @@ -1087,7 +1087,7 @@ struct Credentials_test : public beast::unit_test::Suite auto const stx = std::make_shared(*jtx.stx); // Create PermissionedDomain - env(pdomain::setTx(becky, {{issuer, credType}})); + env(pdomain::setTx(becky, {{.issuer = issuer, .credType = credType}})); env.close(); auto const objects = pdomain::getObjects(becky, env); if (!BEAST_EXPECT(!objects.empty())) diff --git a/src/test/app/CrossingLimitsMPT_test.cpp b/src/test/app/CrossingLimitsMPT_test.cpp index 4a016f31dc..8bd0c767f7 100644 --- a/src/test/app/CrossingLimitsMPT_test.cpp +++ b/src/test/app/CrossingLimitsMPT_test.cpp @@ -270,7 +270,7 @@ public: env.require(Balance(alice, usd(2'503))); env.require(Balance(alice, eur(1'100))); - auto const numAOffers = 2'000 + 100 + 1'000 + 1 - (2 * 100 + 2 * 199 + 1 + 1); + auto const numAOffers = 2'000 + 100 + 1'000 + 1 - ((2 * 100) + (2 * 199) + 1 + 1); env.require(offers(alice, numAOffers)); env.require(Owners(alice, numAOffers + 2)); @@ -358,7 +358,7 @@ public: env.require(Balance(alice, usd(2'494))); env.require(Balance(alice, eur(1'100))); auto const numAOffers = - 1 + 2'000 + 100 + 1'000 + 1 - (1 + 2 * 100 + 2 * 199 + 1 + 1); + 1 + 2'000 + 100 + 1'000 + 1 - (1 + (2 * 100) + (2 * 199) + 1 + 1); env.require(offers(alice, numAOffers)); env.require(Owners(alice, numAOffers + 2)); diff --git a/src/test/app/CrossingLimits_test.cpp b/src/test/app/CrossingLimits_test.cpp index 3cf8f50990..c48892f04e 100644 --- a/src/test/app/CrossingLimits_test.cpp +++ b/src/test/app/CrossingLimits_test.cpp @@ -258,7 +258,7 @@ public: env.require(Balance(alice, usd(2503))); env.require(Balance(alice, eur(1100))); - auto const numAOffers = 2000 + 100 + 1000 + 1 - (2 * 100 + 2 * 199 + 1 + 1); + auto const numAOffers = 2000 + 100 + 1000 + 1 - ((2 * 100) + (2 * 199) + 1 + 1); env.require(offers(alice, numAOffers)); env.require(Owners(alice, numAOffers + 2)); @@ -329,7 +329,7 @@ public: env.require(Balance(alice, usd(2494))); env.require(Balance(alice, eur(1100))); - auto const numAOffers = 1 + 2000 + 100 + 1000 + 1 - (1 + 2 * 100 + 2 * 199 + 1 + 1); + auto const numAOffers = 1 + 2000 + 100 + 1000 + 1 - (1 + (2 * 100) + (2 * 199) + 1 + 1); env.require(offers(alice, numAOffers)); env.require(Owners(alice, numAOffers + 2)); diff --git a/src/test/app/DepositAuth_test.cpp b/src/test/app/DepositAuth_test.cpp index 98597a175f..3496e67b54 100644 --- a/src/test/app/DepositAuth_test.cpp +++ b/src/test/app/DepositAuth_test.cpp @@ -614,7 +614,8 @@ struct DepositPreauth_test : public beast::unit_test::Suite TER const expectTer(!supportsCredentials ? TER(temDISABLED) : TER(tesSUCCESS)); - env(deposit::authCredentials(becky, {{carol, credType}}), Ter(expectTer)); + env(deposit::authCredentials(becky, {{.issuer = carol, .credType = credType}}), + Ter(expectTer)); env.close(); // gw accept credentials @@ -744,7 +745,8 @@ struct DepositPreauth_test : public beast::unit_test::Suite env.close(); // Setup DepositPreauth object failed - amendent is not supported - env(deposit::authCredentials(bob, {{issuer, credType}}), Ter(temDISABLED)); + env(deposit::authCredentials(bob, {{.issuer = issuer, .credType = credType}}), + Ter(temDISABLED)); env.close(); // But can create old DepositPreauth @@ -782,10 +784,11 @@ struct DepositPreauth_test : public beast::unit_test::Suite // Bob will accept payments from accounts with credentials signed // by 'issuer' - env(deposit::authCredentials(bob, {{issuer, credType}})); + env(deposit::authCredentials(bob, {{.issuer = issuer, .credType = credType}})); env.close(); - auto const jDP = ledgerEntryDepositPreauth(env, bob, {{issuer, credType}}); + auto const jDP = + ledgerEntryDepositPreauth(env, bob, {{.issuer = issuer, .credType = credType}}); BEAST_EXPECT( jDP.isObject() && jDP.isMember(jss::result) && !jDP[jss::result].isMember(jss::error) && jDP[jss::result].isMember(jss::node) && @@ -858,11 +861,14 @@ struct DepositPreauth_test : public beast::unit_test::Suite } // Bob setup DepositPreauth object, duplicates is not allowed - env(deposit::authCredentials(bob, {{issuer, credType}, {issuer, credType}}), + env(deposit::authCredentials( + bob, + {{.issuer = issuer, .credType = credType}, + {.issuer = issuer, .credType = credType}}), Ter(temMALFORMED)); // Bob setup DepositPreauth object - env(deposit::authCredentials(bob, {{issuer, credType}})); + env(deposit::authCredentials(bob, {{.issuer = issuer, .credType = credType}})); env.close(); { @@ -928,35 +934,37 @@ struct DepositPreauth_test : public beast::unit_test::Suite { // both included [AuthorizeCredentials UnauthorizeCredentials] - auto jv = deposit::authCredentials(bob, {{issuer, credType}}); + auto jv = deposit::authCredentials(bob, {{.issuer = issuer, .credType = credType}}); jv[sfUnauthorizeCredentials.jsonName] = json::ValueType::Array; env(jv, Ter(temMALFORMED)); } { // both included [Unauthorize, AuthorizeCredentials] - auto jv = deposit::authCredentials(bob, {{issuer, credType}}); + auto jv = deposit::authCredentials(bob, {{.issuer = issuer, .credType = credType}}); jv[sfUnauthorize.jsonName] = issuer.human(); env(jv, Ter(temMALFORMED)); } { // both included [Authorize, AuthorizeCredentials] - auto jv = deposit::authCredentials(bob, {{issuer, credType}}); + auto jv = deposit::authCredentials(bob, {{.issuer = issuer, .credType = credType}}); jv[sfAuthorize.jsonName] = issuer.human(); env(jv, Ter(temMALFORMED)); } { // both included [Unauthorize, UnauthorizeCredentials] - auto jv = deposit::unauthCredentials(bob, {{issuer, credType}}); + auto jv = + deposit::unauthCredentials(bob, {{.issuer = issuer, .credType = credType}}); jv[sfUnauthorize.jsonName] = issuer.human(); env(jv, Ter(temMALFORMED)); } { // both included [Authorize, UnauthorizeCredentials] - auto jv = deposit::unauthCredentials(bob, {{issuer, credType}}); + auto jv = + deposit::unauthCredentials(bob, {{.issuer = issuer, .credType = credType}}); jv[sfAuthorize.jsonName] = issuer.human(); env(jv, Ter(temMALFORMED)); } @@ -983,7 +991,7 @@ struct DepositPreauth_test : public beast::unit_test::Suite { // empty credential type - auto jv = deposit::authCredentials(bob, {{issuer, {}}}); + auto jv = deposit::authCredentials(bob, {{.issuer = issuer, .credType = {}}}); env(jv, Ter(temMALFORMED)); } @@ -993,14 +1001,23 @@ struct DepositPreauth_test : public beast::unit_test::Suite i("i"); auto const& z = credType; auto jv = deposit::authCredentials( - bob, {{a, z}, {b, z}, {c, z}, {d, z}, {e, z}, {f, z}, {g, z}, {h, z}, {i, z}}); + bob, + {{.issuer = a, .credType = z}, + {.issuer = b, .credType = z}, + {.issuer = c, .credType = z}, + {.issuer = d, .credType = z}, + {.issuer = e, .credType = z}, + {.issuer = f, .credType = z}, + {.issuer = g, .credType = z}, + {.issuer = h, .credType = z}, + {.issuer = i, .credType = z}}); env(jv, Ter(temARRAY_TOO_LARGE)); } { // Can't create with non-existing issuer Account const rick{"rick"}; - auto jv = deposit::authCredentials(bob, {{rick, credType}}); + auto jv = deposit::authCredentials(bob, {{.issuer = rick, .credType = credType}}); env(jv, Ter(tecNO_ISSUER)); env.close(); } @@ -1010,21 +1027,24 @@ struct DepositPreauth_test : public beast::unit_test::Suite Account const john{"john"}; env.fund(env.current()->fees().accountReserve(0), john); env.close(); - auto jv = deposit::authCredentials(john, {{issuer, credType}}); + auto jv = + deposit::authCredentials(john, {{.issuer = issuer, .credType = credType}}); env(jv, Ter(tecINSUFFICIENT_RESERVE)); } { // NO deposit object exists - env(deposit::unauthCredentials(bob, {{issuer, credType}}), Ter(tecNO_ENTRY)); + env(deposit::unauthCredentials(bob, {{.issuer = issuer, .credType = credType}}), + Ter(tecNO_ENTRY)); } // Create DepositPreauth object { - env(deposit::authCredentials(bob, {{issuer, credType}})); + env(deposit::authCredentials(bob, {{.issuer = issuer, .credType = credType}})); env.close(); - auto const jDP = ledgerEntryDepositPreauth(env, bob, {{issuer, credType}}); + auto const jDP = + ledgerEntryDepositPreauth(env, bob, {{.issuer = issuer, .credType = credType}}); BEAST_EXPECT( jDP.isObject() && jDP.isMember(jss::result) && !jDP[jss::result].isMember(jss::error) && @@ -1045,14 +1065,16 @@ struct DepositPreauth_test : public beast::unit_test::Suite } // can't create duplicate - env(deposit::authCredentials(bob, {{issuer, credType}}), Ter(tecDUPLICATE)); + env(deposit::authCredentials(bob, {{.issuer = issuer, .credType = credType}}), + Ter(tecDUPLICATE)); } // Delete DepositPreauth object { - env(deposit::unauthCredentials(bob, {{issuer, credType}})); + env(deposit::unauthCredentials(bob, {{.issuer = issuer, .credType = credType}})); env.close(); - auto const jDP = ledgerEntryDepositPreauth(env, bob, {{issuer, credType}}); + auto const jDP = + ledgerEntryDepositPreauth(env, bob, {{.issuer = issuer, .credType = credType}}); BEAST_EXPECT( jDP.isObject() && jDP.isMember(jss::result) && jDP[jss::result].isMember(jss::error) && @@ -1119,7 +1141,10 @@ struct DepositPreauth_test : public beast::unit_test::Suite env(fset(bob, asfDepositAuth)); env.close(); // Bob setup DepositPreauth object - env(deposit::authCredentials(bob, {{issuer, credType}, {issuer, credType2}})); + env(deposit::authCredentials( + bob, + {{.issuer = issuer, .credType = credType}, + {.issuer = issuer, .credType = credType2}})); env.close(); { @@ -1228,7 +1253,7 @@ struct DepositPreauth_test : public beast::unit_test::Suite env(fset(bob, asfDepositAuth)); env.close(); // Bob setup DepositPreauth object - env(deposit::authCredentials(bob, {{issuer, credType}})); + env(deposit::authCredentials(bob, {{.issuer = issuer, .credType = credType}})); env.close(); auto const seq = env.seq(alice); @@ -1286,14 +1311,14 @@ struct DepositPreauth_test : public beast::unit_test::Suite env.fund(XRP(5000), stock, alice, bob); std::vector credentials = { - {"a", "a"}, - {"b", "b"}, - {"c", "c"}, - {"d", "d"}, - {"e", "e"}, - {"f", "f"}, - {"g", "g"}, - {"h", "h"}}; + {.issuer = "a", .credType = "a"}, + {.issuer = "b", .credType = "b"}, + {.issuer = "c", .credType = "c"}, + {.issuer = "d", .credType = "d"}, + {.issuer = "e", .credType = "e"}, + {.issuer = "f", .credType = "f"}, + {.issuer = "g", .credType = "g"}, + {.issuer = "h", .credType = "h"}}; for (auto const& c : credentials) env.fund(XRP(5000), c.issuer); diff --git a/src/test/app/Escrow_test.cpp b/src/test/app/Escrow_test.cpp index 3e76524cf1..5623bc4443 100644 --- a/src/test/app/Escrow_test.cpp +++ b/src/test/app/Escrow_test.cpp @@ -1544,7 +1544,7 @@ struct Escrow_test : public beast::unit_test::Suite credentials::Ids({credIdx}), Ter(tecNO_PERMISSION)); - env(deposit::authCredentials(bob, {{zelda, credType}})); + env(deposit::authCredentials(bob, {{.issuer = zelda, .credType = credType}})); env.close(); // Success @@ -1601,7 +1601,7 @@ struct Escrow_test : public beast::unit_test::Suite // Bob require pre-authorization env(fset(bob, asfDepositAuth)); env.close(); - env(deposit::authCredentials(bob, {{zelda, credType}})); + env(deposit::authCredentials(bob, {{.issuer = zelda, .credType = credType}})); env.close(); // Use any valid credentials if account == dst diff --git a/src/test/app/LedgerReplay_test.cpp b/src/test/app/LedgerReplay_test.cpp index 1978d04fe1..810d93e6e1 100644 --- a/src/test/app/LedgerReplay_test.cpp +++ b/src/test/app/LedgerReplay_test.cpp @@ -549,7 +549,7 @@ struct LedgerServer while (senders.contains(fromIdx)) fromIdx = (fromIdx + 1) % fundedAccounts; senders.insert(fromIdx); - toIdx = (toIdx + r * 2) % fundedAccounts; + toIdx = (toIdx + (r * 2)) % fundedAccounts; if (toIdx == fromIdx) toIdx = (toIdx + 1) % fundedAccounts; }; diff --git a/src/test/app/PayStrand_test.cpp b/src/test/app/PayStrand_test.cpp index 67a37833b2..471c641f36 100644 --- a/src/test/app/PayStrand_test.cpp +++ b/src/test/app/PayStrand_test.cpp @@ -632,7 +632,13 @@ struct PayStrand_test : public beast::unit_test::Suite // Insert implied account test( - env, usd, std::nullopt, STPath(), tesSUCCESS, D{alice, gw, usdC}, D{gw, bob, usdC}); + env, + usd, + std::nullopt, + STPath(), + tesSUCCESS, + D{.src = alice, .dst = gw, .currency = usdC}, + D{.src = gw, .dst = bob, .currency = usdC}); env.trust(eur(1000), alice, bob); // Insert implied offer @@ -642,9 +648,9 @@ struct PayStrand_test : public beast::unit_test::Suite usd, STPath(), tesSUCCESS, - D{alice, gw, usdC}, + D{.src = alice, .dst = gw, .currency = usdC}, B{usd, eur, std::nullopt}, - D{gw, bob, eurC}); + D{.src = gw, .dst = bob, .currency = eurC}); // Path with explicit offer test( @@ -653,9 +659,9 @@ struct PayStrand_test : public beast::unit_test::Suite usd, STPath({ipe(eur)}), tesSUCCESS, - D{alice, gw, usdC}, + D{.src = alice, .dst = gw, .currency = usdC}, B{usd, eur, std::nullopt}, - D{gw, bob, eurC}); + D{.src = gw, .dst = bob, .currency = eurC}); // Path with offer that changes issuer only env.trust(carol["USD"](1000), bob); @@ -665,9 +671,9 @@ struct PayStrand_test : public beast::unit_test::Suite usd, STPath({iape(carol)}), tesSUCCESS, - D{alice, gw, usdC}, + D{.src = alice, .dst = gw, .currency = usdC}, B{usd, carol["USD"], std::nullopt}, - D{carol, bob, usdC}); + D{.src = carol, .dst = bob, .currency = usdC}); // Path with XRP src currency test( @@ -678,7 +684,7 @@ struct PayStrand_test : public beast::unit_test::Suite tesSUCCESS, XRPS{alice}, B{XRP, usd, std::nullopt}, - D{gw, bob, usdC}); + D{.src = gw, .dst = bob, .currency = usdC}); // Path with XRP dst currency. test( @@ -688,7 +694,7 @@ struct PayStrand_test : public beast::unit_test::Suite STPath({STPathElement{ STPathElement::TypeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()}}), tesSUCCESS, - D{alice, gw, usdC}, + D{.src = alice, .dst = gw, .currency = usdC}, B{usd, XRP, std::nullopt}, XRPS{bob}); @@ -699,10 +705,10 @@ struct PayStrand_test : public beast::unit_test::Suite usd, STPath({cpe(xrpCurrency())}), tesSUCCESS, - D{alice, gw, usdC}, + D{.src = alice, .dst = gw, .currency = usdC}, B{usd, XRP, std::nullopt}, B{XRP, eur, std::nullopt}, - D{gw, bob, eurC}); + D{.src = gw, .dst = bob, .currency = eurC}); // XRP -> XRP transaction can't include a path test(env, XRP, std::nullopt, STPath({ape(carol)}), temBAD_PATH); diff --git a/src/test/app/PermissionedDEX_test.cpp b/src/test/app/PermissionedDEX_test.cpp index a88cbaa868..d534f20248 100644 --- a/src/test/app/PermissionedDEX_test.cpp +++ b/src/test/app/PermissionedDEX_test.cpp @@ -704,7 +704,8 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); auto const badCredType = "badCred"; - pdomain::Credentials const credentials{{badDomainOwner, badCredType}}; + pdomain::Credentials const credentials{ + {.issuer = badDomainOwner, .credType = badCredType}}; env(pdomain::setTx(badDomainOwner, credentials)); auto objects = pdomain::getObjects(badDomainOwner, env); @@ -1222,7 +1223,8 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); auto const badCredType = "badCred"; - pdomain::Credentials const credentials{{badDomainOwner, badCredType}}; + pdomain::Credentials const credentials{ + {.issuer = badDomainOwner, .credType = badCredType}}; env(pdomain::setTx(badDomainOwner, credentials)); auto objects = pdomain::getObjects(badDomainOwner, env); diff --git a/src/test/app/PermissionedDomains_test.cpp b/src/test/app/PermissionedDomains_test.cpp index 0857a4bdef..f2d7bce152 100644 --- a/src/test/app/PermissionedDomains_test.cpp +++ b/src/test/app/PermissionedDomains_test.cpp @@ -62,7 +62,7 @@ class PermissionedDomains_test : public beast::unit_test::Suite Account const alice("alice"); Env env(*this, features); env.fund(XRP(1000), alice); - pdomain::Credentials const credentials{{alice, "first credential"}}; + pdomain::Credentials const credentials{{.issuer = alice, .credType = "first credential"}}; env(pdomain::setTx(alice, credentials)); BEAST_EXPECT(env.ownerCount(alice) == 1); auto objects = pdomain::getObjects(alice, env); @@ -84,7 +84,7 @@ class PermissionedDomains_test : public beast::unit_test::Suite Account const alice("alice"); Env env(*this, amendments); env.fund(XRP(1000), alice); - pdomain::Credentials const credentials{{alice, "first credential"}}; + pdomain::Credentials const credentials{{.issuer = alice, .credType = "first credential"}}; env(pdomain::setTx(alice, credentials), Ter(temDISABLED)); } @@ -96,7 +96,7 @@ class PermissionedDomains_test : public beast::unit_test::Suite Account const alice("alice"); Env env(*this, testableAmendments() - featurePermissionedDomains); env.fund(XRP(1000), alice); - pdomain::Credentials const credentials{{alice, "first credential"}}; + pdomain::Credentials const credentials{{.issuer = alice, .credType = "first credential"}}; env(pdomain::setTx(alice, credentials), Ter(temDISABLED)); env(pdomain::deleteTx(alice, uint256(75)), Ter(temDISABLED)); } @@ -124,40 +124,40 @@ class PermissionedDomains_test : public beast::unit_test::Suite // Test 11 credentials. pdomain::Credentials const credentials11{ - {alice2, "credential1"}, - {alice3, "credential2"}, - {alice4, "credential3"}, - {alice5, "credential4"}, - {alice6, "credential5"}, - {alice7, "credential6"}, - {alice8, "credential7"}, - {alice9, "credential8"}, - {alice10, "credential9"}, - {alice11, "credential10"}, - {alice12, "credential11"}}; + {.issuer = alice2, .credType = "credential1"}, + {.issuer = alice3, .credType = "credential2"}, + {.issuer = alice4, .credType = "credential3"}, + {.issuer = alice5, .credType = "credential4"}, + {.issuer = alice6, .credType = "credential5"}, + {.issuer = alice7, .credType = "credential6"}, + {.issuer = alice8, .credType = "credential7"}, + {.issuer = alice9, .credType = "credential8"}, + {.issuer = alice10, .credType = "credential9"}, + {.issuer = alice11, .credType = "credential10"}, + {.issuer = alice12, .credType = "credential11"}}; BEAST_EXPECT(credentials11.size() == kMaxPermissionedDomainCredentialsArraySize + 1); env(pdomain::setTx(account, credentials11, domain), Ter(temARRAY_TOO_LARGE)); // Test credentials including non-existent issuer. Account const nobody("nobody"); pdomain::Credentials const credentialsNon{ - {alice2, "credential1"}, - {alice3, "credential2"}, - {alice4, "credential3"}, - {nobody, "credential4"}, - {alice5, "credential5"}, - {alice6, "credential6"}, - {alice7, "credential7"}}; + {.issuer = alice2, .credType = "credential1"}, + {.issuer = alice3, .credType = "credential2"}, + {.issuer = alice4, .credType = "credential3"}, + {.issuer = nobody, .credType = "credential4"}, + {.issuer = alice5, .credType = "credential5"}, + {.issuer = alice6, .credType = "credential6"}, + {.issuer = alice7, .credType = "credential7"}}; env(pdomain::setTx(account, credentialsNon, domain), Ter(tecNO_ISSUER)); // Test bad fee env(pdomain::setTx(account, credentials11, domain), Fee(1, true), Ter(temBAD_FEE)); pdomain::Credentials const credentials4{ - {alice2, "credential1"}, - {alice3, "credential2"}, - {alice4, "credential3"}, - {alice5, "credential4"}, + {.issuer = alice2, .credType = "credential1"}, + {.issuer = alice3, .credType = "credential2"}, + {.issuer = alice4, .credType = "credential3"}, + {.issuer = alice5, .credType = "credential4"}, }; auto txJsonMutable = pdomain::setTx(account, credentials4, domain); auto const credentialOrig = txJsonMutable["AcceptedCredentials"][2u]; @@ -192,11 +192,11 @@ class PermissionedDomains_test : public beast::unit_test::Suite // permissioned domains, so transactions should return errors { pdomain::Credentials const credentialsDup{ - {alice7, "credential6"}, - {alice2, "credential1"}, - {alice3, "credential2"}, - {alice2, "credential1"}, - {alice5, "credential4"}, + {.issuer = alice7, .credType = "credential6"}, + {.issuer = alice2, .credType = "credential1"}, + {.issuer = alice3, .credType = "credential2"}, + {.issuer = alice2, .credType = "credential1"}, + {.issuer = alice5, .credType = "credential4"}, }; std::unordered_map human2Acc; @@ -230,11 +230,11 @@ class PermissionedDomains_test : public beast::unit_test::Suite // sort correctly. { pdomain::Credentials const credentialsSame{ - {alice2, "credential3"}, - {alice3, "credential2"}, - {alice2, "credential9"}, - {alice5, "credential4"}, - {alice2, "credential6"}, + {.issuer = alice2, .credType = "credential3"}, + {.issuer = alice3, .credType = "credential2"}, + {.issuer = alice2, .credType = "credential9"}, + {.issuer = alice5, .credType = "credential4"}, + {.issuer = alice2, .credType = "credential6"}, }; std::unordered_map human2Acc; for (auto const& c : credentialsSame) @@ -290,7 +290,7 @@ class PermissionedDomains_test : public beast::unit_test::Suite env.fund(XRP(1000), alice[i]); // Create new from existing account with a single credential. - pdomain::Credentials const credentials1{{alice[2], "credential1"}}; + pdomain::Credentials const credentials1{{.issuer = alice[2], .credType = "credential1"}}; { env(pdomain::setTx(alice[0], credentials1)); BEAST_EXPECT(env.ownerCount(alice[0]) == 1); @@ -314,7 +314,7 @@ class PermissionedDomains_test : public beast::unit_test::Suite "89"; static_assert(kLongCredentialType.size() == kMaxCredentialTypeLength); pdomain::Credentials const longCredentials{ - {alice[1], std::string(kLongCredentialType)}}; + {.issuer = alice[1], .credType = std::string(kLongCredentialType)}}; env(pdomain::setTx(alice[0], longCredentials)); @@ -345,16 +345,16 @@ class PermissionedDomains_test : public beast::unit_test::Suite // Create new from existing account with 10 credentials. // Last credential describe domain owner itself pdomain::Credentials const credentials10{ - {alice[2], "credential1"}, - {alice[3], "credential2"}, - {alice[4], "credential3"}, - {alice[5], "credential4"}, - {alice[6], "credential5"}, - {alice[7], "credential6"}, - {alice[8], "credential7"}, - {alice[9], "credential8"}, - {alice[10], "credential9"}, - {alice[0], "credential10"}, + {.issuer = alice[2], .credType = "credential1"}, + {.issuer = alice[3], .credType = "credential2"}, + {.issuer = alice[4], .credType = "credential3"}, + {.issuer = alice[5], .credType = "credential4"}, + {.issuer = alice[6], .credType = "credential5"}, + {.issuer = alice[7], .credType = "credential6"}, + {.issuer = alice[8], .credType = "credential7"}, + {.issuer = alice[9], .credType = "credential8"}, + {.issuer = alice[10], .credType = "credential9"}, + {.issuer = alice[0], .credType = "credential10"}, }; uint256 domain2; { @@ -434,7 +434,7 @@ class PermissionedDomains_test : public beast::unit_test::Suite env.fund(XRP(1000), alice); auto const setFee(drops(env.current()->fees().increment)); - pdomain::Credentials const credentials{{alice, "first credential"}}; + pdomain::Credentials const credentials{{.issuer = alice, .credType = "first credential"}}; env(pdomain::setTx(alice, credentials)); env.close(); @@ -498,7 +498,7 @@ class PermissionedDomains_test : public beast::unit_test::Suite BEAST_EXPECT(env.ownerCount(alice) == 0); // alice does not have enough XRP to cover the reserve. - pdomain::Credentials const credentials{{alice, "first credential"}}; + pdomain::Credentials const credentials{{.issuer = alice, .credType = "first credential"}}; env(pdomain::setTx(alice, credentials), Ter(tecINSUFFICIENT_RESERVE)); BEAST_EXPECT(env.ownerCount(alice) == 0); BEAST_EXPECT(pdomain::getObjects(alice, env).empty()); diff --git a/src/test/app/TxQ_test.cpp b/src/test/app/TxQ_test.cpp index 8333fce3b3..dc28388de4 100644 --- a/src/test/app/TxQ_test.cpp +++ b/src/test/app/TxQ_test.cpp @@ -1228,7 +1228,7 @@ public: // Try to replace a middle item in the queue // with enough fee to bankrupt bob and make the // later transactions unable to pay their fees - std::int64_t bobFee = env.le(bob)->getFieldAmount(sfBalance).xrp().drops() - (9 * 10 - 1); + std::int64_t bobFee = env.le(bob)->getFieldAmount(sfBalance).xrp().drops() - ((9 * 10) - 1); env(noop(bob), Seq(bobSeq + 5), Fee(bobFee), Ter(telCAN_NOT_QUEUE_BALANCE)); checkMetrics(*this, env, 10, 12, 7, 6); diff --git a/src/test/app/ValidatorList_test.cpp b/src/test/app/ValidatorList_test.cpp index 20a3557db5..80483446a2 100644 --- a/src/test/app/ValidatorList_test.cpp +++ b/src/test/app/ValidatorList_test.cpp @@ -632,7 +632,11 @@ private: checkResult( trustedKeys->applyLists( - manifest1, version, {{expiredblob, expiredSig, {}}, {blob2, sig2, {}}}, siteUri), + manifest1, + version, + {{.blob = expiredblob, .signature = expiredSig, .manifest = {}}, + {.blob = blob2, .signature = sig2, .manifest = {}}}, + siteUri), publisherPublic, ListDisposition::Expired, ListDisposition::Accepted); @@ -665,7 +669,11 @@ private: checkResult( trustedKeys->applyLists( - manifest1, version2, {{blob7, sig7, {}}, {blob8, sig8, {}}}, siteUri), + manifest1, + version2, + {{.blob = blob7, .signature = sig7, .manifest = {}}, + {.blob = blob8, .signature = sig8, .manifest = {}}}, + siteUri), publisherPublic, ListDisposition::Pending, ListDisposition::Pending); @@ -697,7 +705,11 @@ private: checkResult( trustedKeys->applyLists( - manifest1, version, {{blob6a, sig6a, {}}, {blob6, sig6, {}}}, siteUri), + manifest1, + version, + {{.blob = blob6a, .signature = sig6a, .manifest = {}}, + {.blob = blob6, .signature = sig6, .manifest = {}}}, + siteUri), publisherPublic, ListDisposition::Pending, ListDisposition::Pending); @@ -709,7 +721,11 @@ private: checkResult( trustedKeys->applyLists( - manifest1, version, {{blob7, sig7, {}}, {blob6, sig6, {}}}, siteUri), + manifest1, + version, + {{.blob = blob7, .signature = sig7, .manifest = {}}, + {.blob = blob6, .signature = sig6, .manifest = {}}}, + siteUri), publisherPublic, ListDisposition::KnownSequence, ListDisposition::KnownSequence); @@ -720,7 +736,12 @@ private: // try empty or mangled manifest checkResult( - trustedKeys->applyLists("", version, {{blob7, sig7, {}}, {blob6, sig6, {}}}, siteUri), + trustedKeys->applyLists( + "", + version, + {{.blob = blob7, .signature = sig7, .manifest = {}}, + {.blob = blob6, .signature = sig6, .manifest = {}}}, + siteUri), publisherPublic, ListDisposition::Invalid, ListDisposition::Invalid); @@ -729,7 +750,8 @@ private: trustedKeys->applyLists( base64Encode("not a manifest"), version, - {{blob7, sig7, {}}, {blob6, sig6, {}}}, + {{.blob = blob7, .signature = sig7, .manifest = {}}, + {.blob = blob6, .signature = sig6, .manifest = {}}}, siteUri), publisherPublic, ListDisposition::Invalid, @@ -740,7 +762,11 @@ private: randomMasterKey(), publisherSecret, pubSigningKeys1.first, pubSigningKeys1.second, 1)); checkResult( - trustedKeys->applyLists(untrustedManifest, version, {{blob2, sig2, {}}}, siteUri), + trustedKeys->applyLists( + untrustedManifest, + version, + {{.blob = blob2, .signature = sig2, .manifest = {}}}, + siteUri), publisherPublic, ListDisposition::Untrusted, ListDisposition::Untrusted); @@ -748,7 +774,11 @@ private: // do not use list with unhandled version auto const badVersion = 666; checkResult( - trustedKeys->applyLists(manifest1, badVersion, {{blob2, sig2, {}}}, siteUri), + trustedKeys->applyLists( + manifest1, + badVersion, + {{.blob = blob2, .signature = sig2, .manifest = {}}}, + siteUri), publisherPublic, ListDisposition::UnsupportedVersion, ListDisposition::UnsupportedVersion); @@ -759,7 +789,8 @@ private: auto const sig3 = signList(blob3, pubSigningKeys1); checkResult( - trustedKeys->applyLists(manifest1, version, {{blob3, sig3, {}}}, siteUri), + trustedKeys->applyLists( + manifest1, version, {{.blob = blob3, .signature = sig3, .manifest = {}}}, siteUri), publisherPublic, ListDisposition::Accepted, ListDisposition::Accepted); @@ -780,7 +811,11 @@ private: // do not re-apply lists with past or current sequence numbers checkResult( trustedKeys->applyLists( - manifest1, version, {{blob2, sig2, {}}, {blob3, sig3, {}}}, siteUri), + manifest1, + version, + {{.blob = blob2, .signature = sig2, .manifest = {}}, + {.blob = blob3, .signature = sig3, .manifest = {}}}, + siteUri), publisherPublic, ListDisposition::Stale, ListDisposition::SameSequence); @@ -799,7 +834,9 @@ private: trustedKeys->applyLists( manifest2, version, - {{blob2, sig2, manifest1}, {blob3, sig3, manifest1}, {blob4, sig4, {}}}, + {{.blob = blob2, .signature = sig2, .manifest = manifest1}, + {.blob = blob3, .signature = sig3, .manifest = manifest1}, + {.blob = blob4, .signature = sig4, .manifest = {}}}, siteUri), publisherPublic, ListDisposition::Stale, @@ -820,7 +857,11 @@ private: auto const blob5 = makeList(lists.at(5), sequence5, validUntil.time_since_epoch().count()); auto const badSig = signList(blob5, pubSigningKeys1); checkResult( - trustedKeys->applyLists(manifest1, version, {{blob5, badSig, {}}}, siteUri), + trustedKeys->applyLists( + manifest1, + version, + {{.blob = blob5, .signature = badSig, .manifest = {}}}, + siteUri), publisherPublic, ListDisposition::Invalid, ListDisposition::Invalid); @@ -833,7 +874,11 @@ private: // Reprocess the pending list, but the signature is no longer valid checkResult( trustedKeys->applyLists( - manifest1, version, {{blob7, sig7, {}}, {blob8, sig8, {}}}, siteUri), + manifest1, + version, + {{.blob = blob7, .signature = sig7, .manifest = {}}, + {.blob = blob8, .signature = sig8, .manifest = {}}}, + siteUri), publisherPublic, ListDisposition::Invalid, ListDisposition::Invalid); @@ -884,7 +929,11 @@ private: checkResult( trustedKeys->applyLists( - manifest2, version, {{blob8, sig8, manifest1}, {blob8, sig82, {}}}, siteUri), + manifest2, + version, + {{.blob = blob8, .signature = sig8, .manifest = manifest1}, + {.blob = blob8, .signature = sig82, .manifest = {}}}, + siteUri), publisherPublic, ListDisposition::Invalid, ListDisposition::SameSequence); @@ -903,7 +952,11 @@ private: auto const sig9 = signList(blob9, signingKeysMax); checkResult( - trustedKeys->applyLists(maxManifest, version, {{blob9, sig9, {}}}, siteUri), + trustedKeys->applyLists( + maxManifest, + version, + {{.blob = blob9, .signature = sig9, .manifest = {}}}, + siteUri), publisherPublic, ListDisposition::Untrusted, ListDisposition::Untrusted); @@ -1900,7 +1953,9 @@ private: return PreparedList{ .publisherPublic = publisherPublic, .manifest = manifest, - .blobs = {{blob1, sig1, {}}, {blob2, sig2, {}}}, + .blobs = + {{.blob = blob1, .signature = sig1, .manifest = {}}, + {.blob = blob2, .signature = sig2, .manifest = {}}}, .version = version, .expirations = {expiration1, expiration2}}; }; diff --git a/src/test/app/ValidatorSite_test.cpp b/src/test/app/ValidatorSite_test.cpp index f7f805faa2..e3e3ec27df 100644 --- a/src/test/app/ValidatorSite_test.cpp +++ b/src/test/app/ValidatorSite_test.cpp @@ -380,226 +380,333 @@ public: for (auto ssl : {true, false}) { // fetch single site - testFetchList(good, {{"/validators", "", ssl}}); - testFetchList(good, {{"/validators2", "", ssl}}); + testFetchList(good, {{.path = "/validators", .msg = "", .ssl = ssl}}); + testFetchList(good, {{.path = "/validators2", .msg = "", .ssl = ssl}}); // fetch multiple sites - testFetchList(good, {{"/validators", "", ssl}, {"/validators", "", ssl}}); - testFetchList(good, {{"/validators", "", ssl}, {"/validators2", "", ssl}}); - testFetchList(good, {{"/validators2", "", ssl}, {"/validators", "", ssl}}); - testFetchList(good, {{"/validators2", "", ssl}, {"/validators2", "", ssl}}); + testFetchList( + good, + {{.path = "/validators", .msg = "", .ssl = ssl}, + {.path = "/validators", .msg = "", .ssl = ssl}}); + testFetchList( + good, + {{.path = "/validators", .msg = "", .ssl = ssl}, + {.path = "/validators2", .msg = "", .ssl = ssl}}); + testFetchList( + good, + {{.path = "/validators2", .msg = "", .ssl = ssl}, + {.path = "/validators", .msg = "", .ssl = ssl}}); + testFetchList( + good, + {{.path = "/validators2", .msg = "", .ssl = ssl}, + {.path = "/validators2", .msg = "", .ssl = ssl}}); // fetch single site with single redirects - testFetchList(good, {{"/redirect_once/301", "", ssl}}); - testFetchList(good, {{"/redirect_once/302", "", ssl}}); - testFetchList(good, {{"/redirect_once/307", "", ssl}}); - testFetchList(good, {{"/redirect_once/308", "", ssl}}); + testFetchList(good, {{.path = "/redirect_once/301", .msg = "", .ssl = ssl}}); + testFetchList(good, {{.path = "/redirect_once/302", .msg = "", .ssl = ssl}}); + testFetchList(good, {{.path = "/redirect_once/307", .msg = "", .ssl = ssl}}); + testFetchList(good, {{.path = "/redirect_once/308", .msg = "", .ssl = ssl}}); // one redirect, one not - testFetchList(good, {{"/validators", "", ssl}, {"/redirect_once/302", "", ssl}}); - testFetchList(good, {{"/validators2", "", ssl}, {"/redirect_once/302", "", ssl}}); + testFetchList( + good, + {{.path = "/validators", .msg = "", .ssl = ssl}, + {.path = "/redirect_once/302", .msg = "", .ssl = ssl}}); + testFetchList( + good, + {{.path = "/validators2", .msg = "", .ssl = ssl}, + {.path = "/redirect_once/302", .msg = "", .ssl = ssl}}); // UNLs with a "gap" between validUntil of one and validFrom of the // next testFetchList( good, - {{"/validators2", - "", - ssl, - false, - false, - 1, - detail::kDefaultExpires, - std::chrono::seconds{-90}}}); + {{.path = "/validators2", + .msg = "", + .ssl = ssl, + .failFetch = false, + .failApply = false, + .serverVersion = 1, + .expiresFromNow = detail::kDefaultExpires, + .effectiveOverlap = std::chrono::seconds{-90}}}); // fetch single site with unending redirect (fails to load) testFetchList( - good, {{"/redirect_forever/301", "Exceeded max redirects", ssl, true, true}}); + good, + {{.path = "/redirect_forever/301", + .msg = "Exceeded max redirects", + .ssl = ssl, + .failFetch = true, + .failApply = true}}); // two that redirect forever testFetchList( good, - {{"/redirect_forever/307", "Exceeded max redirects", ssl, true, true}, - {"/redirect_forever/308", "Exceeded max redirects", ssl, true, true}}); + {{.path = "/redirect_forever/307", + .msg = "Exceeded max redirects", + .ssl = ssl, + .failFetch = true, + .failApply = true}, + {.path = "/redirect_forever/308", + .msg = "Exceeded max redirects", + .ssl = ssl, + .failFetch = true, + .failApply = true}}); // one unending redirect, one not testFetchList( good, - {{"/validators", "", ssl}, - {"/redirect_forever/302", "Exceeded max redirects", ssl, true, true}}); + {{.path = "/validators", .msg = "", .ssl = ssl}, + {.path = "/redirect_forever/302", + .msg = "Exceeded max redirects", + .ssl = ssl, + .failFetch = true, + .failApply = true}}); // one unending redirect, one not testFetchList( good, - {{"/validators2", "", ssl}, - {"/redirect_forever/302", "Exceeded max redirects", ssl, true, true}}); + {{.path = "/validators2", .msg = "", .ssl = ssl}, + {.path = "/redirect_forever/302", + .msg = "Exceeded max redirects", + .ssl = ssl, + .failFetch = true, + .failApply = true}}); // invalid redir Location testFetchList( good, - {{"/redirect_to/ftp://invalid-url/302", - "Invalid redirect location", - ssl, - true, - true}}); + {{.path = "/redirect_to/ftp://invalid-url/302", + .msg = "Invalid redirect location", + .ssl = ssl, + .failFetch = true, + .failApply = true}}); testFetchList( good, - {{"/redirect_to/file://invalid-url/302", - "Invalid redirect location", - ssl, - true, - true}}); + {{.path = "/redirect_to/file://invalid-url/302", + .msg = "Invalid redirect location", + .ssl = ssl, + .failFetch = true, + .failApply = true}}); // invalid json testFetchList( - good, {{"/validators/bad", "Unable to parse JSON response", ssl, true, true}}); + good, + {{.path = "/validators/bad", + .msg = "Unable to parse JSON response", + .ssl = ssl, + .failFetch = true, + .failApply = true}}); testFetchList( - good, {{"/validators2/bad", "Unable to parse JSON response", ssl, true, true}}); + good, + {{.path = "/validators2/bad", + .msg = "Unable to parse JSON response", + .ssl = ssl, + .failFetch = true, + .failApply = true}}); // error status returned - testFetchList(good, {{"/bad-resource", "returned bad status", ssl, true, true}}); + testFetchList( + good, + {{.path = "/bad-resource", + .msg = "returned bad status", + .ssl = ssl, + .failFetch = true, + .failApply = true}}); // location field missing testFetchList( good, - {{"/redirect_nolo/308", "returned a redirect with no Location", ssl, true, true}}); + {{.path = "/redirect_nolo/308", + .msg = "returned a redirect with no Location", + .ssl = ssl, + .failFetch = true, + .failApply = true}}); // json fields missing testFetchList( good, - {{"/validators/missing", "Missing fields in JSON response", ssl, true, true}}); + {{.path = "/validators/missing", + .msg = "Missing fields in JSON response", + .ssl = ssl, + .failFetch = true, + .failApply = true}}); testFetchList( good, - {{"/validators2/missing", "Missing fields in JSON response", ssl, true, true}}); + {{.path = "/validators2/missing", + .msg = "Missing fields in JSON response", + .ssl = ssl, + .failFetch = true, + .failApply = true}}); // timeout - testFetchList(good, {{"/sleep/13", "took too long", ssl, true, true}}); + testFetchList( + good, + {{.path = "/sleep/13", + .msg = "took too long", + .ssl = ssl, + .failFetch = true, + .failApply = true}}); // bad manifest format using known versions // * Retrieves a v1 formatted list claiming version 2 - testFetchList(good, {{"/validators", "Missing fields", ssl, true, true, 2}}); + testFetchList( + good, + {{.path = "/validators", + .msg = "Missing fields", + .ssl = ssl, + .failFetch = true, + .failApply = true, + .serverVersion = 2}}); // * Retrieves a v2 formatted list claiming version 1 - testFetchList(good, {{"/validators2", "Missing fields", ssl, true, true, 0}}); + testFetchList( + good, + {{.path = "/validators2", + .msg = "Missing fields", + .ssl = ssl, + .failFetch = true, + .failApply = true, + .serverVersion = 0}}); // bad manifest version // Because versions other than 1 are treated as v2, the v1 // list won't have the blobs_v2 fields, and thus will claim to have // missing fields - testFetchList(good, {{"/validators", "Missing fields", ssl, true, true, 4}}); - testFetchList(good, {{"/validators2", "1 unsupported version", ssl, false, true, 4}}); + testFetchList( + good, + {{.path = "/validators", + .msg = "Missing fields", + .ssl = ssl, + .failFetch = true, + .failApply = true, + .serverVersion = 4}}); + testFetchList( + good, + {{.path = "/validators2", + .msg = "1 unsupported version", + .ssl = ssl, + .failFetch = false, + .failApply = true, + .serverVersion = 4}}); using namespace std::chrono_literals; // get expired validator list testFetchList( good, - {{"/validators", "Applied 1 expired validator list(s)", ssl, false, false, 1, 0s}}); + {{.path = "/validators", + .msg = "Applied 1 expired validator list(s)", + .ssl = ssl, + .failFetch = false, + .failApply = false, + .serverVersion = 1, + .expiresFromNow = 0s}}); testFetchList( good, - {{"/validators2", - "Applied 1 expired validator list(s)", - ssl, - false, - false, - 1, - 0s, - -1s}}); + {{.path = "/validators2", + .msg = "Applied 1 expired validator list(s)", + .ssl = ssl, + .failFetch = false, + .failApply = false, + .serverVersion = 1, + .expiresFromNow = 0s, + .effectiveOverlap = -1s}}); // force an out-of-range validUntil value testFetchList( good, - {{"/validators", - "1 invalid validator list(s)", - ssl, - false, - true, - 1, - std::chrono::seconds{json::Value::kMinInt}}}); + {{.path = "/validators", + .msg = "1 invalid validator list(s)", + .ssl = ssl, + .failFetch = false, + .failApply = true, + .serverVersion = 1, + .expiresFromNow = std::chrono::seconds{json::Value::kMinInt}}}); // force an out-of-range validUntil value on the future list // The first list is accepted. The second fails. The parser // returns the "best" result, so this looks like a success. testFetchList( good, - {{"/validators2", - "", - ssl, - false, - false, - 1, - std::chrono::seconds{json::Value::kMaxInt - 300}, - 299s}}); + {{.path = "/validators2", + .msg = "", + .ssl = ssl, + .failFetch = false, + .failApply = false, + .serverVersion = 1, + .expiresFromNow = std::chrono::seconds{json::Value::kMaxInt - 300}, + .effectiveOverlap = 299s}}); // force an out-of-range validFrom value // The first list is accepted. The second fails. The parser // returns the "best" result, so this looks like a success. testFetchList( good, - {{"/validators2", - "", - ssl, - false, - false, - 1, - std::chrono::seconds{json::Value::kMaxInt - 300}, - 301s}}); + {{.path = "/validators2", + .msg = "", + .ssl = ssl, + .failFetch = false, + .failApply = false, + .serverVersion = 1, + .expiresFromNow = std::chrono::seconds{json::Value::kMaxInt - 300}, + .effectiveOverlap = 301s}}); // force an out-of-range validUntil value on _both_ lists testFetchList( good, - {{"/validators2", - "2 invalid validator list(s)", - ssl, - false, - true, - 1, - std::chrono::seconds{json::Value::kMinInt}, - std::chrono::seconds{json::Value::kMaxInt - 6000}}}); + {{.path = "/validators2", + .msg = "2 invalid validator list(s)", + .ssl = ssl, + .failFetch = false, + .failApply = true, + .serverVersion = 1, + .expiresFromNow = std::chrono::seconds{json::Value::kMinInt}, + .effectiveOverlap = std::chrono::seconds{json::Value::kMaxInt - 6000}}}); // verify refresh intervals are properly clamped testFetchList( good, - {{"/validators/refresh/0", - "", - ssl, - false, - false, - 1, - detail::kDefaultExpires, - detail::kDefaultEffectiveOverlap, - 1}}); // minimum of 1 minute + {{.path = "/validators/refresh/0", + .msg = "", + .ssl = ssl, + .failFetch = false, + .failApply = false, + .serverVersion = 1, + .expiresFromNow = detail::kDefaultExpires, + .effectiveOverlap = detail::kDefaultEffectiveOverlap, + .expectedRefreshMin = 1}}); // minimum of 1 minute testFetchList( good, - {{"/validators2/refresh/0", - "", - ssl, - false, - false, - 1, - detail::kDefaultExpires, - detail::kDefaultEffectiveOverlap, - 1}}); // minimum of 1 minute + {{.path = "/validators2/refresh/0", + .msg = "", + .ssl = ssl, + .failFetch = false, + .failApply = false, + .serverVersion = 1, + .expiresFromNow = detail::kDefaultExpires, + .effectiveOverlap = detail::kDefaultEffectiveOverlap, + .expectedRefreshMin = 1}}); // minimum of 1 minute testFetchList( good, - {{"/validators/refresh/10", - "", - ssl, - false, - false, - 1, - detail::kDefaultExpires, - detail::kDefaultEffectiveOverlap, - 10}}); // 10 minutes is fine + {{.path = "/validators/refresh/10", + .msg = "", + .ssl = ssl, + .failFetch = false, + .failApply = false, + .serverVersion = 1, + .expiresFromNow = detail::kDefaultExpires, + .effectiveOverlap = detail::kDefaultEffectiveOverlap, + .expectedRefreshMin = 10}}); // 10 minutes is fine testFetchList( good, - {{"/validators2/refresh/10", - "", - ssl, - false, - false, - 1, - detail::kDefaultExpires, - detail::kDefaultEffectiveOverlap, - 10}}); // 10 minutes is fine + {{.path = "/validators2/refresh/10", + .msg = "", + .ssl = ssl, + .failFetch = false, + .failApply = false, + .serverVersion = 1, + .expiresFromNow = detail::kDefaultExpires, + .effectiveOverlap = detail::kDefaultEffectiveOverlap, + .expectedRefreshMin = 10}}); // 10 minutes is fine testFetchList( good, - {{"/validators/refresh/2000", - "", - ssl, - false, - false, - 1, - detail::kDefaultExpires, - detail::kDefaultEffectiveOverlap, - 60 * 24}}); // max of 24 hours + {{.path = "/validators/refresh/2000", + .msg = "", + .ssl = ssl, + .failFetch = false, + .failApply = false, + .serverVersion = 1, + .expiresFromNow = detail::kDefaultExpires, + .effectiveOverlap = detail::kDefaultEffectiveOverlap, + .expectedRefreshMin = 60 * 24}}); // max of 24 hours testFetchList( good, - {{"/validators2/refresh/2000", - "", - ssl, - false, - false, - 1, - detail::kDefaultExpires, - detail::kDefaultEffectiveOverlap, - 60 * 24}}); // max of 24 hours + {{.path = "/validators2/refresh/2000", + .msg = "", + .ssl = ssl, + .failFetch = false, + .failApply = false, + .serverVersion = 1, + .expiresFromNow = detail::kDefaultExpires, + .effectiveOverlap = detail::kDefaultEffectiveOverlap, + .expectedRefreshMin = 60 * 24}}); // max of 24 hours } using namespace boost::filesystem; for (auto const& file : directory_iterator(good.subdir())) diff --git a/src/test/basics/PerfLog_test.cpp b/src/test/basics/PerfLog_test.cpp index c370c241c5..41b5f81f5d 100644 --- a/src/test/basics/PerfLog_test.cpp +++ b/src/test/basics/PerfLog_test.cpp @@ -619,7 +619,7 @@ public: // Total queued duration is triangle number of (i + 1). BEAST_EXPECT( - jsonToUInt64(total[jss::queued_duration_us]) == (((i * i) + 3 * i + 2) / 2)); + jsonToUInt64(total[jss::queued_duration_us]) == (((i * i) + (3 * i) + 2) / 2)); BEAST_EXPECT(total[jss::running_duration_us] == "0"); } diff --git a/src/test/beast/aged_associative_container_test.cpp b/src/test/beast/aged_associative_container_test.cpp index f2ce72b584..d7f74aaa7d 100644 --- a/src/test/beast/aged_associative_container_test.cpp +++ b/src/test/beast/aged_associative_container_test.cpp @@ -414,11 +414,11 @@ public: // unordered template - std::enable_if_t::type::is_unordered::value> + std::enable_if_t::is_unordered::value> checkUnorderedContentsRefRef(C&& c, Values const& v); template - std::enable_if_t::type::is_unordered::value> + std::enable_if_t::is_unordered::value> checkUnorderedContentsRefRef(C&&, Values const&) { } @@ -641,7 +641,7 @@ AgedAssociativeContainerTestBase::checkMapContents(Container& c, Values const& v // unordered template -std::enable_if_t::type::is_unordered::value> +std::enable_if_t::is_unordered::value> AgedAssociativeContainerTestBase::checkUnorderedContentsRefRef(C&& c, Values const& v) { using Cont = std::remove_reference_t; diff --git a/src/test/core/Config_test.cpp b/src/test/core/Config_test.cpp index ce6774827e..92f59fe644 100644 --- a/src/test/core/Config_test.cpp +++ b/src/test/core/Config_test.cpp @@ -1457,14 +1457,14 @@ r.ripple.com:51235 }; std::vector const units = { - {"seconds", 1, 15 * 60, false}, - {"minutes", 60, 14, false}, - {"minutes", 60, 15, true}, - {"hours", 3600, 10, true}, - {"days", 86400, 10, true}, - {"weeks", 604800, 2, true}, - {"months", 2592000, 1, false}, - {"years", 31536000, 1, false}}; + {.unit = "seconds", .numSeconds = 1, .configVal = 15 * 60, .shouldPass = false}, + {.unit = "minutes", .numSeconds = 60, .configVal = 14, .shouldPass = false}, + {.unit = "minutes", .numSeconds = 60, .configVal = 15, .shouldPass = true}, + {.unit = "hours", .numSeconds = 3600, .configVal = 10, .shouldPass = true}, + {.unit = "days", .numSeconds = 86400, .configVal = 10, .shouldPass = true}, + {.unit = "weeks", .numSeconds = 604800, .configVal = 2, .shouldPass = true}, + {.unit = "months", .numSeconds = 2592000, .configVal = 1, .shouldPass = false}, + {.unit = "years", .numSeconds = 31536000, .configVal = 1, .shouldPass = false}}; std::string space; for (auto& [unit, sec, val, shouldPass] : units) diff --git a/src/test/jtx/impl/WSClient.cpp b/src/test/jtx/impl/WSClient.cpp index 551fd1404b..6d069523d2 100644 --- a/src/test/jtx/impl/WSClient.cpp +++ b/src/test/jtx/impl/WSClient.cpp @@ -70,7 +70,7 @@ class WSClientImpl : public WSClient continue; ParsedPort pp; parsePort(pp, cfg[name], log); - if (pp.protocol.count(ps) == 0) + if (!pp.protocol.contains(ps)) continue; using namespace boost::asio::ip; if (pp.ip && pp.ip->is_unspecified()) diff --git a/src/test/jtx/impl/permissioned_dex.cpp b/src/test/jtx/impl/permissioned_dex.cpp index 5c059e9e80..a6b24d7ac6 100644 --- a/src/test/jtx/impl/permissioned_dex.cpp +++ b/src/test/jtx/impl/permissioned_dex.cpp @@ -26,7 +26,7 @@ setupDomain( env.fund(XRP(100000), domainOwner); env.close(); - pdomain::Credentials const credentials{{domainOwner, credType}}; + pdomain::Credentials const credentials{{.issuer = domainOwner, .credType = credType}}; env(pdomain::setTx(domainOwner, credentials)); auto const objects = pdomain::getObjects(domainOwner, env); diff --git a/src/test/jtx/impl/permissioned_domains.cpp b/src/test/jtx/impl/permissioned_domains.cpp index 690451c7d8..385008be43 100644 --- a/src/test/jtx/impl/permissioned_domains.cpp +++ b/src/test/jtx/impl/permissioned_domains.cpp @@ -130,7 +130,9 @@ credentialsFromJson( auto const& credentialType = obj["CredentialType"]; // NOLINTNEXTLINE(bugprone-unchecked-optional-access): used only in tests auto blob = strUnHex(credentialType.asString()).value(); - ret.push_back({human2Acc.at(issuer.asString()), std::string(blob.begin(), blob.end())}); + ret.push_back( + {.issuer = human2Acc.at(issuer.asString()), + .credType = std::string(blob.begin(), blob.end())}); } return ret; } diff --git a/src/test/nodestore/import_test.cpp b/src/test/nodestore/import_test.cpp index a80b5ccc93..de99edd655 100644 --- a/src/test/nodestore/import_test.cpp +++ b/src/test/nodestore/import_test.cpp @@ -297,17 +297,17 @@ public: auto const args = parseArgs(arg()); bool usage = args.empty(); - if (!usage && args.find("from") == args.end()) + if (!usage && !args.contains("from")) { log << "Missing parameter: from"; usage = true; } - if (!usage && args.find("to") == args.end()) + if (!usage && !args.contains("to")) { log << "Missing parameter: to"; usage = true; } - if (!usage && args.find("buffer") == args.end()) + if (!usage && !args.contains("buffer")) { log << "Missing parameter: buffer"; usage = true; diff --git a/src/test/rpc/AccountObjects_test.cpp b/src/test/rpc/AccountObjects_test.cpp index 4307b7ab7f..31b20b37d4 100644 --- a/src/test/rpc/AccountObjects_test.cpp +++ b/src/test/rpc/AccountObjects_test.cpp @@ -692,11 +692,11 @@ public: { std::string const credentialType1 = "credential1"; - Account issuer("issuer"); + Account const issuer("issuer"); env.fund(XRP(5000), issuer); // gw creates an PermissionedDomain. - env(pdomain::setTx(gw, {{issuer, credentialType1}})); + env(pdomain::setTx(gw, {{.issuer = issuer, .credType = credentialType1}})); env.close(); // Find the PermissionedDomain. diff --git a/src/test/rpc/DepositAuthorized_test.cpp b/src/test/rpc/DepositAuthorized_test.cpp index 89053557a7..e6720602c9 100644 --- a/src/test/rpc/DepositAuthorized_test.cpp +++ b/src/test/rpc/DepositAuthorized_test.cpp @@ -324,7 +324,7 @@ public: env.close(); // becky authorize any account recognized by carol to make a payment - env(deposit::authCredentials(becky, {{carol, credType}})); + env(deposit::authCredentials(becky, {{.issuer = carol, .credType = credType}})); env.close(); { @@ -507,7 +507,7 @@ public: env.close(); // becky authorize any account recognized by carol to make a payment - env(deposit::authCredentials(becky, {{carol, credType2}})); + env(deposit::authCredentials(becky, {{.issuer = carol, .credType = credType2}})); env.close(); { diff --git a/src/test/rpc/LedgerEntry_test.cpp b/src/test/rpc/LedgerEntry_test.cpp index d231a2d4a0..dd9eb1c119 100644 --- a/src/test/rpc/LedgerEntry_test.cpp +++ b/src/test/rpc/LedgerEntry_test.cpp @@ -784,8 +784,8 @@ class LedgerEntry_test : public beast::unit_test::Suite env, jss::amm, { - {jss::asset, "malformedRequest"}, - {jss::asset2, "malformedRequest"}, + {.fieldName = jss::asset, .malformedErrorMsg = "malformedRequest"}, + {.fieldName = jss::asset2, .malformedErrorMsg = "malformedRequest"}, }); }; auto getIOU = [&](Env& env) -> PrettyAsset { return alice["USD"]; }; @@ -900,9 +900,9 @@ class LedgerEntry_test : public beast::unit_test::Suite env, jss::credential, { - {jss::subject, "malformedRequest"}, - {jss::issuer, "malformedRequest"}, - {jss::credential_type, "malformedRequest"}, + {.fieldName = jss::subject, .malformedErrorMsg = "malformedRequest"}, + {.fieldName = jss::issuer, .malformedErrorMsg = "malformedRequest"}, + {.fieldName = jss::credential_type, .malformedErrorMsg = "malformedRequest"}, }); } } @@ -954,8 +954,8 @@ class LedgerEntry_test : public beast::unit_test::Suite env, jss::delegate, { - {jss::account, "malformedAddress"}, - {jss::authorize, "malformedAddress"}, + {.fieldName = jss::account, .malformedErrorMsg = "malformedAddress"}, + {.fieldName = jss::authorize, .malformedErrorMsg = "malformedAddress"}, }); } } @@ -1011,8 +1011,10 @@ class LedgerEntry_test : public beast::unit_test::Suite env, jss::deposit_preauth, { - {jss::owner, "malformedOwner"}, - {jss::authorized, "malformedAuthorized", false}, + {.fieldName = jss::owner, .malformedErrorMsg = "malformedOwner"}, + {.fieldName = jss::authorized, + .malformedErrorMsg = "malformedAuthorized", + .required = false}, }); } } @@ -1037,7 +1039,7 @@ class LedgerEntry_test : public beast::unit_test::Suite // Setup Bob with DepositAuth env(fset(bob, asfDepositAuth)); env.close(); - env(deposit::authCredentials(bob, {{issuer, credType}})); + env(deposit::authCredentials(bob, {{.issuer = issuer, .credType = credType}})); env.close(); } @@ -1458,7 +1460,10 @@ class LedgerEntry_test : public beast::unit_test::Suite { // Malformed escrow fields runLedgerEntryTest( - env, jss::escrow, {{jss::owner, "malformedOwner"}, {jss::seq, "malformedSeq"}}); + env, + jss::escrow, + {{.fieldName = jss::owner, .malformedErrorMsg = "malformedOwner"}, + {.fieldName = jss::seq, .malformedErrorMsg = "malformedSeq"}}); } } @@ -1667,7 +1672,8 @@ class LedgerEntry_test : public beast::unit_test::Suite runLedgerEntryTest( env, jss::offer, - {{jss::account, "malformedAddress"}, {jss::seq, "malformedRequest"}}); + {{.fieldName = jss::account, .malformedErrorMsg = "malformedAddress"}, + {.fieldName = jss::seq, .malformedErrorMsg = "malformedRequest"}}); } } @@ -1774,8 +1780,8 @@ class LedgerEntry_test : public beast::unit_test::Suite env, fieldName, { - {jss::accounts, "malformedRequest"}, - {jss::currency, "malformedCurrency"}, + {.fieldName = jss::accounts, .malformedErrorMsg = "malformedRequest"}, + {.fieldName = jss::currency, .malformedErrorMsg = "malformedCurrency"}, }); } { @@ -1955,8 +1961,8 @@ class LedgerEntry_test : public beast::unit_test::Suite env, jss::ticket, { - {jss::account, "malformedAddress"}, - {jss::ticket_seq, "malformedRequest"}, + {.fieldName = jss::account, .malformedErrorMsg = "malformedAddress"}, + {.fieldName = jss::ticket_seq, .malformedErrorMsg = "malformedRequest"}, }); } } @@ -2034,8 +2040,9 @@ class LedgerEntry_test : public beast::unit_test::Suite env, jss::oracle, { - {jss::account, "malformedAccount"}, - {jss::oracle_document_id, "malformedDocumentID"}, + {.fieldName = jss::account, .malformedErrorMsg = "malformedAccount"}, + {.fieldName = jss::oracle_document_id, + .malformedErrorMsg = "malformedDocumentID"}, }); } } @@ -2172,7 +2179,7 @@ class LedgerEntry_test : public beast::unit_test::Suite env.close(); auto const seq = env.seq(alice); - env(pdomain::setTx(alice, {{alice, "first credential"}})); + env(pdomain::setTx(alice, {{.issuer = alice, .credType = "first credential"}})); env.close(); auto const objects = pdomain::getObjects(alice, env); if (!BEAST_EXPECT(objects.size() == 1)) @@ -2221,8 +2228,8 @@ class LedgerEntry_test : public beast::unit_test::Suite env, jss::permissioned_domain, { - {jss::account, "malformedAddress"}, - {jss::seq, "malformedRequest"}, + {.fieldName = jss::account, .malformedErrorMsg = "malformedAddress"}, + {.fieldName = jss::seq, .malformedErrorMsg = "malformedRequest"}, }); } } diff --git a/src/xrpld/app/misc/detail/ValidatorList.cpp b/src/xrpld/app/misc/detail/ValidatorList.cpp index 57b65814e1..0981c32050 100644 --- a/src/xrpld/app/misc/detail/ValidatorList.cpp +++ b/src/xrpld/app/misc/detail/ValidatorList.cpp @@ -455,7 +455,7 @@ ValidatorList::parseBlobs(std::uint32_t version, json::Value const& body) std::vector ValidatorList::parseBlobs(protocol::TMValidatorList const& body) { - return {{body.blob(), body.signature(), {}}}; + return {{.blob = body.blob(), .signature = body.signature(), .manifest = {}}}; } // static diff --git a/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp b/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp index fcf30fa4f4..5d276dc9c5 100644 --- a/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp +++ b/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp @@ -18,7 +18,8 @@ Config::Config() : outPeers(calcOutPeers()) std::size_t Config::calcOutPeers() const { - return std::max((maxPeers * Tuning::kOutPercent + 50) / 100, std::size_t(Tuning::kMinOutCount)); + return std::max( + ((maxPeers * Tuning::kOutPercent) + 50) / 100, std::size_t(Tuning::kMinOutCount)); } void diff --git a/src/xrpld/rpc/detail/Pathfinder.cpp b/src/xrpld/rpc/detail/Pathfinder.cpp index daa50cfb07..25da86ef8f 100644 --- a/src/xrpld/rpc/detail/Pathfinder.cpp +++ b/src/xrpld/rpc/detail/Pathfinder.cpp @@ -568,7 +568,11 @@ Pathfinder::rankPaths( JLOG(j_.debug()) << "findPaths: quality: " << uQuality << ": " << currentPath.getJson(JsonOptions::Values::None); - rankedPaths.push_back({uQuality, currentPath.size(), liquidity, i}); + rankedPaths.push_back( + {.quality = uQuality, + .length = currentPath.size(), + .liquidity = liquidity, + .index = i}); } } } @@ -1373,7 +1377,7 @@ fillPaths(Pathfinder::PaymentType type, PathCostList const& costs) auto& list = gPathTable[type]; XRPL_ASSERT(list.empty(), "xrpl::fillPaths : empty paths"); for (auto& cost : costs) - list.push_back({cost.cost, makePath(cost.path)}); + list.push_back({.searchLevel = cost.cost, .type = makePath(cost.path)}); } } // namespace @@ -1396,58 +1400,58 @@ Pathfinder::initPathTable() fillPaths( PaymentType::XrpToNonXrp, - {{1, "sfd"}, // source -> book -> gateway - {3, "sfad"}, // source -> book -> account -> destination - {5, "sfaad"}, // source -> book -> account -> account -> destination - {6, "sbfd"}, // source -> book -> book -> destination - {8, "sbafd"}, // source -> book -> account -> book -> destination - {9, "sbfad"}, // source -> book -> book -> account -> destination - {10, "sbafad"}}); + {{.cost = 1, .path = "sfd"}, // source -> book -> gateway + {.cost = 3, .path = "sfad"}, // source -> book -> account -> destination + {.cost = 5, .path = "sfaad"}, // source -> book -> account -> account -> destination + {.cost = 6, .path = "sbfd"}, // source -> book -> book -> destination + {.cost = 8, .path = "sbafd"}, // source -> book -> account -> book -> destination + {.cost = 9, .path = "sbfad"}, // source -> book -> book -> account -> destination + {.cost = 10, .path = "sbafad"}}); fillPaths( PaymentType::NonXrpToXrp, - {{1, "sxd"}, // gateway buys XRP - {2, "saxd"}, // source -> gateway -> book(XRP) -> dest - {6, "saaxd"}, - {7, "sbxd"}, - {8, "sabxd"}, - {9, "sabaxd"}}); + {{.cost = 1, .path = "sxd"}, // gateway buys XRP + {.cost = 2, .path = "saxd"}, // source -> gateway -> book(XRP) -> dest + {.cost = 6, .path = "saaxd"}, + {.cost = 7, .path = "sbxd"}, + {.cost = 8, .path = "sabxd"}, + {.cost = 9, .path = "sabaxd"}}); // non-XRP to non-XRP (same currency) fillPaths( PaymentType::NonXrpToSame, { - {1, "sad"}, // source -> gateway -> destination - {1, "sfd"}, // source -> book -> destination - {4, "safd"}, // source -> gateway -> book -> destination - {4, "sfad"}, - {5, "saad"}, - {5, "sbfd"}, - {6, "sxfad"}, - {6, "safad"}, - {6, "saxfd"}, // source -> gateway -> book to XRP -> book -> - // destination - {6, "saxfad"}, - {6, "sabfd"}, // source -> gateway -> book -> book -> destination - {7, "saaad"}, + {.cost = 1, .path = "sad"}, // source -> gateway -> destination + {.cost = 1, .path = "sfd"}, // source -> book -> destination + {.cost = 4, .path = "safd"}, // source -> gateway -> book -> destination + {.cost = 4, .path = "sfad"}, + {.cost = 5, .path = "saad"}, + {.cost = 5, .path = "sbfd"}, + {.cost = 6, .path = "sxfad"}, + {.cost = 6, .path = "safad"}, + {.cost = 6, .path = "saxfd"}, // source -> gateway -> book to XRP -> book -> + // destination + {.cost = 6, .path = "saxfad"}, + {.cost = 6, .path = "sabfd"}, // source -> gateway -> book -> book -> destination + {.cost = 7, .path = "saaad"}, }); // non-XRP to non-XRP (different currency) fillPaths( PaymentType::NonXrpToNonXrp, { - {1, "sfad"}, - {1, "safd"}, - {3, "safad"}, - {4, "sxfd"}, - {5, "saxfd"}, - {5, "sxfad"}, - {5, "sbfd"}, - {6, "saxfad"}, - {6, "sabfd"}, - {7, "saafd"}, - {8, "saafad"}, - {9, "safaad"}, + {.cost = 1, .path = "sfad"}, + {.cost = 1, .path = "safd"}, + {.cost = 3, .path = "safad"}, + {.cost = 4, .path = "sxfd"}, + {.cost = 5, .path = "saxfd"}, + {.cost = 5, .path = "sxfad"}, + {.cost = 5, .path = "sbfd"}, + {.cost = 6, .path = "saxfad"}, + {.cost = 6, .path = "sabfd"}, + {.cost = 7, .path = "saafd"}, + {.cost = 8, .path = "saafad"}, + {.cost = 9, .path = "safaad"}, }); /* cspell: enable */ } diff --git a/src/xrpld/rpc/detail/ServerHandler.cpp b/src/xrpld/rpc/detail/ServerHandler.cpp index 0bdece3ec3..c73e474e18 100644 --- a/src/xrpld/rpc/detail/ServerHandler.cpp +++ b/src/xrpld/rpc/detail/ServerHandler.cpp @@ -165,10 +165,10 @@ ServerHandler::setup(Setup const& setup, beast::Journal journal) port.port = endpointPort; if ((setup_.client.port == 0u) && - (port.protocol.count("http") > 0 || port.protocol.count("https") > 0)) + (port.protocol.contains("http") || port.protocol.contains("https"))) setup_.client.port = endpointPort; - if ((setup_.overlay.port() == 0u) && (port.protocol.count("peer") > 0)) + if ((setup_.overlay.port() == 0u) && (port.protocol.contains("peer"))) setup_.overlay.port(endpointPort); } } @@ -217,7 +217,7 @@ ServerHandler::onHandoff( using namespace boost::beast; auto const& p{session.port().protocol}; bool const isWs{ - p.count("ws") > 0 || p.count("ws2") > 0 || p.count("wss") > 0 || p.count("wss2") > 0}; + p.contains("ws") || p.contains("ws2") || p.contains("wss") || p.contains("wss2")}; if (websocket::is_upgrade(request)) { @@ -251,7 +251,7 @@ ServerHandler::onHandoff( return handoff; } - if (bundle && p.count("peer") > 0) + if (bundle && p.contains("peer")) return app_.getOverlay().onHandoff(std::move(bundle), std::move(request), remoteAddress); if (isWs && isStatusRequest(request)) @@ -301,7 +301,7 @@ void ServerHandler::onRequest(Session& session) { // Make sure RPC is enabled on the port - if (session.port().protocol.count("http") == 0 && session.port().protocol.count("https") == 0) + if (!session.port().protocol.contains("http") && !session.port().protocol.contains("https")) { httpReply(403, "Forbidden", makeOutput(session), app_.getJournal("RPC")); session.close(true); @@ -1180,7 +1180,7 @@ parsePorts(Config const& config, std::ostream& log) else { auto const count = std::count_if(result.cbegin(), result.cend(), [](Port const& p) { - return p.protocol.count("peer") != 0; + return p.protocol.contains("peer"); }); if (count > 1) @@ -1203,12 +1203,12 @@ setupClient(ServerHandler::Setup& setup) decltype(setup.ports)::const_iterator iter; for (iter = setup.ports.cbegin(); iter != setup.ports.cend(); ++iter) { - if (iter->protocol.count("http") > 0 || iter->protocol.count("https") > 0) + if (iter->protocol.contains("http") || iter->protocol.contains("https")) break; } if (iter == setup.ports.cend()) return; - setup.client.secure = iter->protocol.count("https") > 0; + setup.client.secure = iter->protocol.contains("https"); if (beast::IP::isUnspecified(iter->ip)) { // VFALCO HACK! to make localhost work @@ -1230,7 +1230,7 @@ static void setupOverlay(ServerHandler::Setup& setup) { auto const iter = std::ranges::find_if( - setup.ports, [](Port const& port) { return port.protocol.count("peer") != 0; }); + setup.ports, [](Port const& port) { return port.protocol.contains("peer"); }); if (iter == setup.ports.cend()) { setup.overlay = {}; From 6571f75d399e3e237fbcb1ddfe23adbe3d98286c Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Fri, 5 Jun 2026 15:36:05 +0100 Subject: [PATCH 12/78] ci: Use multiple directories in dependabot config (#7413) --- .github/dependabot.yml | 40 ++++++---------------------------------- 1 file changed, 6 insertions(+), 34 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 0e6b840fe7..da7a30dc77 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,40 +1,12 @@ version: 2 updates: - package-ecosystem: github-actions - directory: / - schedule: - interval: weekly - day: monday - time: "04:00" - timezone: Etc/GMT - commit-message: - prefix: "ci: [DEPENDABOT] " - target-branch: develop - - - package-ecosystem: github-actions - directory: .github/actions/build-deps/ - schedule: - interval: weekly - day: monday - time: "04:00" - timezone: Etc/GMT - commit-message: - prefix: "ci: [DEPENDABOT] " - target-branch: develop - - - package-ecosystem: github-actions - directory: .github/actions/generate-version/ - schedule: - interval: weekly - day: monday - time: "04:00" - timezone: Etc/GMT - commit-message: - prefix: "ci: [DEPENDABOT] " - target-branch: develop - - - package-ecosystem: github-actions - directory: .github/actions/setup-conan/ + directories: + - / + - .github/actions/build-deps/ + - .github/actions/generate-version/ + - .github/actions/set-compiler-env/ + - .github/actions/setup-conan/ schedule: interval: weekly day: monday From 63ffdc39dc6bc1565b7e6437ed6686721c9379c2 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Fri, 5 Jun 2026 18:05:19 +0100 Subject: [PATCH 13/78] ci: Refactor build-related nix / docker / workflows (#7408) --- .github/scripts/strategy-matrix/linux.json | 2 +- .github/workflows/build-nix-image.yml | 109 ------------------ .github/workflows/build-nix-images.yml | 56 +++++++++ .github/workflows/build-packaging-images.yml | 48 ++++++++ .github/workflows/publish-docs.yml | 18 +-- .../workflows/reusable-build-docker-image.yml | 2 +- .../reusable-build-merge-docker-images.yml | 89 ++++++++++++++ .github/workflows/reusable-upload-recipe.yml | 2 +- .../nix.Dockerfile => nix/docker/Dockerfile | 12 +- {docker => nix/docker}/check-tools.sh | 0 .../docker}/install-sanitizer-libs.sh | 0 {docker => nix/docker}/loader-path.sh | 0 .../docker}/test_files/compile-cpp-sources.sh | 0 .../docker}/test_files/cpp_sources/asan.cpp | 0 .../test_files/cpp_sources/regular.cpp | 0 .../docker}/test_files/cpp_sources/tsan.cpp | 0 .../docker}/test_files/cpp_sources/ubsan.cpp | 0 .../docker}/test_files/run-test-binaries.sh | 0 package/Dockerfile | 14 +++ package/README.md | 13 +-- package/install-packaging-tools.sh | 68 +++++++++++ 21 files changed, 295 insertions(+), 138 deletions(-) delete mode 100644 .github/workflows/build-nix-image.yml create mode 100644 .github/workflows/build-nix-images.yml create mode 100644 .github/workflows/build-packaging-images.yml create mode 100644 .github/workflows/reusable-build-merge-docker-images.yml rename docker/nix.Dockerfile => nix/docker/Dockerfile (90%) rename {docker => nix/docker}/check-tools.sh (100%) rename {docker => nix/docker}/install-sanitizer-libs.sh (100%) rename {docker => nix/docker}/loader-path.sh (100%) rename {docker => nix/docker}/test_files/compile-cpp-sources.sh (100%) rename {docker => nix/docker}/test_files/cpp_sources/asan.cpp (100%) rename {docker => nix/docker}/test_files/cpp_sources/regular.cpp (100%) rename {docker => nix/docker}/test_files/cpp_sources/tsan.cpp (100%) rename {docker => nix/docker}/test_files/cpp_sources/ubsan.cpp (100%) rename {docker => nix/docker}/test_files/run-test-binaries.sh (100%) create mode 100644 package/Dockerfile create mode 100755 package/install-packaging-tools.sh diff --git a/.github/scripts/strategy-matrix/linux.json b/.github/scripts/strategy-matrix/linux.json index 3070b8d9f4..7da48a6a25 100644 --- a/.github/scripts/strategy-matrix/linux.json +++ b/.github/scripts/strategy-matrix/linux.json @@ -1,5 +1,5 @@ { - "image_tag": "sha-6c54342", + "image_tag": "sha-8abe82e", "configs": { "ubuntu": [ { diff --git a/.github/workflows/build-nix-image.yml b/.github/workflows/build-nix-image.yml deleted file mode 100644 index bae4cfd437..0000000000 --- a/.github/workflows/build-nix-image.yml +++ /dev/null @@ -1,109 +0,0 @@ -name: Build Nix Docker image - -on: - push: - branches: - - develop - paths: - - ".github/workflows/build-nix-image.yml" - - ".github/workflows/reusable-build-docker-image.yml" - - "docker/**" - - "flake.nix" - - "flake.lock" - - "nix/**" - pull_request: - paths: - - ".github/workflows/build-nix-image.yml" - - ".github/workflows/reusable-build-docker-image.yml" - - "docker/**" - - "flake.nix" - - "flake.lock" - - "nix/**" - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -defaults: - run: - shell: bash - -jobs: - build: - name: Build ${{ matrix.distro.name }} (${{ matrix.target.platform }}) - permissions: - contents: read - packages: write - strategy: - fail-fast: false - matrix: - # The base images are the oldest supported version of each distro - # that we want to build images for. - distro: - - name: nixos - base_image: nixos/nix:latest - - name: ubuntu - base_image: ubuntu:20.04 - - name: rhel - base_image: registry.access.redhat.com/ubi9/ubi:latest - - name: debian - base_image: debian:bookworm - 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: ghcr.io/xrplf/xrpld/nix-${{ matrix.distro.name }} - dockerfile: docker/nix.Dockerfile - base_image: ${{ matrix.distro.base_image }} - platform: ${{ matrix.target.platform }} - runner: ${{ matrix.target.runner }} - push: ${{ github.repository == 'XRPLF/rippled' && github.event_name == 'push' }} - - merge: - name: Merge ${{ matrix.distro }} manifest - needs: build - if: ${{ github.repository == 'XRPLF/rippled' && github.event_name == 'push' }} - runs-on: ubuntu-latest - permissions: - contents: read - packages: write - strategy: - fail-fast: false - matrix: - distro: [nixos, ubuntu, rhel, debian] - env: - IMAGE_NAME: ghcr.io/xrplf/xrpld/nix-${{ matrix.distro }} - - 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: ${{ env.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 - 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 - run: | - docker buildx imagetools inspect "${IMAGE_NAME}:${{ steps.meta.outputs.version }}" diff --git a/.github/workflows/build-nix-images.yml b/.github/workflows/build-nix-images.yml new file mode 100644 index 0000000000..dc02f84e0f --- /dev/null +++ b/.github/workflows/build-nix-images.yml @@ -0,0 +1,56 @@ +name: Build Nix Docker images + +on: + push: + branches: + - 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/**" + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +defaults: + run: + shell: bash + +jobs: + build-merge: + name: Build and push nix-${{ matrix.distro.name }} + permissions: + contents: read + packages: write + strategy: + fail-fast: false + matrix: + # The base images are the oldest supported version of each distro + # that we want to build images for. + distro: + - name: nixos + base_image: nixos/nix:latest + - name: ubuntu + base_image: ubuntu:20.04 + - name: debian + base_image: debian:bookworm + - name: rhel + base_image: registry.access.redhat.com/ubi9/ubi:latest + uses: ./.github/workflows/reusable-build-merge-docker-images.yml + with: + image_name: ghcr.io/xrplf/xrpld/nix-${{ matrix.distro.name }} + dockerfile: nix/docker/Dockerfile + base_image: ${{ matrix.distro.base_image }} diff --git a/.github/workflows/build-packaging-images.yml b/.github/workflows/build-packaging-images.yml new file mode 100644 index 0000000000..a11a16f298 --- /dev/null +++ b/.github/workflows/build-packaging-images.yml @@ -0,0 +1,48 @@ +name: Build packaging Docker images + +on: + push: + branches: + - 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: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +defaults: + run: + shell: bash + +jobs: + build-merge: + name: Build and push packaging-${{ matrix.distro.name }} + permissions: + contents: read + packages: write + strategy: + fail-fast: false + matrix: + distro: + - name: debian + base_image: debian:bookworm + - name: rhel + base_image: registry.access.redhat.com/ubi9/ubi:latest + uses: ./.github/workflows/reusable-build-merge-docker-images.yml + with: + image_name: ghcr.io/xrplf/xrpld/packaging-${{ matrix.distro.name }} + dockerfile: package/Dockerfile + base_image: ${{ matrix.distro.base_image }} diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index d619be5543..bbe6ec4592 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -41,7 +41,7 @@ env: jobs: build: runs-on: ubuntu-latest - container: ghcr.io/xrplf/ci/tools-rippled-documentation:sha-a8c7be1 + container: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-8abe82e steps: - name: Checkout repository uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 @@ -57,19 +57,11 @@ jobs: with: subtract: ${{ env.NPROC_SUBTRACT }} - - name: Check configuration - run: | - echo 'Checking path.' - echo ${PATH} | tr ':' '\n' + - name: Print build environment + uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574 - echo 'Checking environment variables.' - env | sort - - echo 'Checking CMake version.' - cmake --version - - echo 'Checking Doxygen version.' - doxygen --version + - name: Check Doxygen version + run: doxygen --version - name: Build documentation env: diff --git a/.github/workflows/reusable-build-docker-image.yml b/.github/workflows/reusable-build-docker-image.yml index c3795e56fa..5830ef9ece 100644 --- a/.github/workflows/reusable-build-docker-image.yml +++ b/.github/workflows/reusable-build-docker-image.yml @@ -38,7 +38,7 @@ defaults: jobs: build: - name: Build (${{ inputs.platform }}) + name: Build ${{ inputs.platform }} runs-on: ${{ inputs.runner }} permissions: contents: read diff --git a/.github/workflows/reusable-build-merge-docker-images.yml b/.github/workflows/reusable-build-merge-docker-images.yml new file mode 100644 index 0000000000..98deb6ea3f --- /dev/null +++ b/.github/workflows/reusable-build-merge-docker-images.yml @@ -0,0 +1,89 @@ +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/.github/workflows/reusable-upload-recipe.yml b/.github/workflows/reusable-upload-recipe.yml index d3fe0f356b..b7ec5f9ef7 100644 --- a/.github/workflows/reusable-upload-recipe.yml +++ b/.github/workflows/reusable-upload-recipe.yml @@ -40,7 +40,7 @@ defaults: jobs: upload: runs-on: ubuntu-latest - container: ghcr.io/xrplf/ci/ubuntu-noble:gcc-13-sha-5dd7158 + container: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-8abe82e steps: - name: Checkout repository uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 diff --git a/docker/nix.Dockerfile b/nix/docker/Dockerfile similarity index 90% rename from docker/nix.Dockerfile rename to nix/docker/Dockerfile index 6248708417..e6df48e18c 100644 --- a/docker/nix.Dockerfile +++ b/nix/docker/Dockerfile @@ -56,7 +56,7 @@ ENV GIT_SSL_CAINFO="/nix/ci-env/etc/ssl/certs/ca-bundle.crt" # Externally-built dynamically-linked ELF binaries hard-code the loader path # (e.g. /lib64/ld-linux-x86-64.so.2) in their PT_INTERP header. Install it # from the Nix store when the base image doesn't already provide one. -COPY docker/loader-path.sh /tmp/loader-path.sh +COPY nix/docker/loader-path.sh /tmp/loader-path.sh RUN < deb, `dnf`/`yum` -> rpm). The image tag is composed as -`ghcr.io/xrplf/ci/{distro}-{version}:{compiler}-{cver}-sha-{image_sha}` — +`ghcr.io/xrplf/xrpld/packaging-:sha-` — the same scheme used by `reusable-build-test.yml`. Bump `image_sha` in `linux.json` and both CI and local builds pick up the new image with no workflow edits. | Package type | Image (derived from `linux.json`) | Tool required | | ------------ | ---------------------------------------------------- | --------------------------------------------------------------- | -| RPM | `ghcr.io/xrplf/ci/rhel-9:gcc-12-sha-` | `rpmbuild` | -| DEB | `ghcr.io/xrplf/ci/ubuntu-jammy:gcc-12-sha-` | `dpkg-buildpackage`, `debhelper (>= 13)`, `dh-sequence-systemd` | +| RPM | `ghcr.io/xrplf/xrpld/packaging-rhel:sha-` | `rpmbuild` | +| DEB | `ghcr.io/xrplf/xrpld/packaging-debian:sha-` | `dpkg-buildpackage`, `debhelper (>= 13)`, `dh-sequence-systemd` | To print the exact image tags for the current `linux.json`: ```bash -./.github/scripts/strategy-matrix/generate.py --packaging --config=.github/scripts/strategy-matrix/linux.json +./.github/scripts/strategy-matrix/generate.py --packaging ``` ## Building packages diff --git a/package/install-packaging-tools.sh b/package/install-packaging-tools.sh new file mode 100755 index 0000000000..a26159a204 --- /dev/null +++ b/package/install-packaging-tools.sh @@ -0,0 +1,68 @@ +#!/bin/bash + +set -euo pipefail + +if [ ! -f /etc/os-release ]; then + echo "ERROR: /etc/os-release not found; cannot detect OS" >&2 + exit 1 +fi + +# shellcheck source=/dev/null +. /etc/os-release + +echo "Detected OS: ${ID} ${VERSION_ID:-}" + +case "${ID}" in + ubuntu | debian | rhel | centos | rocky | almalinux) + echo "Supported OS detected: ${ID}" + ;; + *) + echo "ERROR: unsupported OS '${ID}'. Supported: debian, ubuntu, rhel-family" >&2 + exit 1 + ;; +esac + +function install() { + case "${ID}" in + debian | ubuntu) + apt-get update -y + apt-get install -y --no-install-recommends \ + ca-certificates \ + debhelper \ + debhelper-compat \ + dpkg-dev \ + git + ;; + + rhel | centos | rocky | almalinux) + dnf install -y --setopt=install_weak_deps=False \ + git \ + rpm-build \ + redhat-rpm-config \ + systemd-rpm-macros + ;; + esac +} + +function postinstall() { + # Don't clear cache in non-CI environments + if [ -z "${CI:-}" ]; then + echo "Not running in CI environment; skipping cache cleanup" + return + fi + + case "${ID}" in + debian | ubuntu) + apt-get clean + rm -rf /var/lib/apt/lists/* + ;; + + rhel | centos | rocky | almalinux) + dnf clean -y all + rm -rf /var/cache/dnf/* + ;; + esac +} + +install +postinstall From fc57dab78bd7dc4a9a022c16fd557b18f7a5e571 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 5 Jun 2026 17:17:47 +0000 Subject: [PATCH 14/78] ci: [DEPENDABOT] bump actions/checkout from 6.0.2 to 6.0.3 (#7414) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/check-pr-description.yml | 2 +- .github/workflows/on-pr.yml | 2 +- .github/workflows/publish-docs.yml | 2 +- .github/workflows/reusable-build-docker-image.yml | 2 +- .github/workflows/reusable-build-test-config.yml | 2 +- .github/workflows/reusable-check-levelization.yml | 2 +- .github/workflows/reusable-check-rename.yml | 2 +- .github/workflows/reusable-clang-tidy.yml | 2 +- .github/workflows/reusable-package.yml | 6 +++--- .github/workflows/reusable-strategy-matrix.yml | 2 +- .github/workflows/reusable-upload-recipe.yml | 2 +- .github/workflows/upload-conan-deps.yml | 2 +- 12 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.github/workflows/check-pr-description.yml b/.github/workflows/check-pr-description.yml index ff28220171..a60b83738a 100644 --- a/.github/workflows/check-pr-description.yml +++ b/.github/workflows/check-pr-description.yml @@ -23,7 +23,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Write PR body to file env: diff --git a/.github/workflows/on-pr.yml b/.github/workflows/on-pr.yml index db3c8667e5..4b2edeb93d 100644 --- a/.github/workflows/on-pr.yml +++ b/.github/workflows/on-pr.yml @@ -33,7 +33,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Determine changed files # This step checks whether any files have changed that should # cause the next jobs to run. We do it this way rather than diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index bbe6ec4592..35f33b6446 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -44,7 +44,7 @@ jobs: container: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-8abe82e steps: - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Prepare runner uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab diff --git a/.github/workflows/reusable-build-docker-image.yml b/.github/workflows/reusable-build-docker-image.yml index 5830ef9ece..253563c6a5 100644 --- a/.github/workflows/reusable-build-docker-image.yml +++ b/.github/workflows/reusable-build-docker-image.yml @@ -46,7 +46,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Determine arch id: vars diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index e1154f74be..6f0750e3f7 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -110,7 +110,7 @@ jobs: uses: XRPLF/actions/cleanup-workspace@c7d9ce5ebb03c752a354889ecd870cadfc2b1cd4 - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Prepare runner uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab diff --git a/.github/workflows/reusable-check-levelization.yml b/.github/workflows/reusable-check-levelization.yml index b5d57a177a..813c0e1e36 100644 --- a/.github/workflows/reusable-check-levelization.yml +++ b/.github/workflows/reusable-check-levelization.yml @@ -18,7 +18,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Check levelization run: python .github/scripts/levelization/generate.py - name: Check for differences diff --git a/.github/workflows/reusable-check-rename.yml b/.github/workflows/reusable-check-rename.yml index 7aa5b80594..5002cc7f40 100644 --- a/.github/workflows/reusable-check-rename.yml +++ b/.github/workflows/reusable-check-rename.yml @@ -18,7 +18,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Check definitions run: .github/scripts/rename/definitions.sh . - name: Check copyright notices diff --git a/.github/workflows/reusable-clang-tidy.yml b/.github/workflows/reusable-clang-tidy.yml index cfbd8af963..31e06d05eb 100644 --- a/.github/workflows/reusable-clang-tidy.yml +++ b/.github/workflows/reusable-clang-tidy.yml @@ -42,7 +42,7 @@ jobs: issues: write steps: - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Prepare runner uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab diff --git a/.github/workflows/reusable-package.yml b/.github/workflows/reusable-package.yml index 670c01733e..890277d184 100644 --- a/.github/workflows/reusable-package.yml +++ b/.github/workflows/reusable-package.yml @@ -27,7 +27,7 @@ jobs: matrix: ${{ steps.generate.outputs.matrix }} steps: - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Set up Python uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 @@ -45,7 +45,7 @@ jobs: version: ${{ steps.version.outputs.version }} steps: - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 with: sparse-checkout: | .github/actions/generate-version @@ -94,7 +94,7 @@ jobs: systemd-rpm-macros - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Download pre-built binary uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 diff --git a/.github/workflows/reusable-strategy-matrix.yml b/.github/workflows/reusable-strategy-matrix.yml index 16a2b4e336..ea134b43b2 100644 --- a/.github/workflows/reusable-strategy-matrix.yml +++ b/.github/workflows/reusable-strategy-matrix.yml @@ -23,7 +23,7 @@ jobs: matrix: ${{ steps.generate.outputs.matrix }} steps: - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Set up Python uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 diff --git a/.github/workflows/reusable-upload-recipe.yml b/.github/workflows/reusable-upload-recipe.yml index b7ec5f9ef7..6e1ea943ca 100644 --- a/.github/workflows/reusable-upload-recipe.yml +++ b/.github/workflows/reusable-upload-recipe.yml @@ -43,7 +43,7 @@ jobs: container: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-8abe82e steps: - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Generate build version number id: version diff --git a/.github/workflows/upload-conan-deps.yml b/.github/workflows/upload-conan-deps.yml index 87465b4d3d..6310c90899 100644 --- a/.github/workflows/upload-conan-deps.yml +++ b/.github/workflows/upload-conan-deps.yml @@ -64,7 +64,7 @@ jobs: uses: XRPLF/actions/cleanup-workspace@c7d9ce5ebb03c752a354889ecd870cadfc2b1cd4 - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Prepare runner uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab From 949887feb9f32b49829e9c29712697f567b23916 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Fri, 5 Jun 2026 20:24:32 +0100 Subject: [PATCH 15/78] build: Create single test binary xrpl_tests (#7327) --- .gersemi/definitions.cmake | 3 - .github/scripts/rename/cmake.sh | 4 - .../workflows/reusable-build-test-config.yml | 21 ++--- cmake/XrplAddTest.cmake | 22 ----- cmake/XrplCov.cmake | 2 +- src/tests/libxrpl/CMakeLists.txt | 89 ++++++++++--------- src/tests/libxrpl/crypto/main.cpp | 8 -- src/tests/libxrpl/json/main.cpp | 8 -- src/tests/libxrpl/{basics => }/main.cpp | 0 src/tests/libxrpl/net/main.cpp | 8 -- src/tests/libxrpl/tx/main.cpp | 8 -- 11 files changed, 59 insertions(+), 114 deletions(-) delete mode 100644 cmake/XrplAddTest.cmake delete mode 100644 src/tests/libxrpl/crypto/main.cpp delete mode 100644 src/tests/libxrpl/json/main.cpp rename src/tests/libxrpl/{basics => }/main.cpp (100%) delete mode 100644 src/tests/libxrpl/net/main.cpp delete mode 100644 src/tests/libxrpl/tx/main.cpp diff --git a/.gersemi/definitions.cmake b/.gersemi/definitions.cmake index a16e330ffa..245f827f90 100644 --- a/.gersemi/definitions.cmake +++ b/.gersemi/definitions.cmake @@ -11,9 +11,6 @@ endfunction() function(create_symbolic_link target link) endfunction() -function(xrpl_add_test name) -endfunction() - macro(exclude_from_default target_) endmacro() diff --git a/.github/scripts/rename/cmake.sh b/.github/scripts/rename/cmake.sh index 28bf777fed..3539f563e0 100755 --- a/.github/scripts/rename/cmake.sh +++ b/.github/scripts/rename/cmake.sh @@ -43,9 +43,6 @@ pushd "${DIRECTORY}" # Rename the files. find cmake -type f -name 'Rippled*.cmake' -exec bash -c 'mv "${1}" "${1/Rippled/Xrpl}"' - {} \; find cmake -type f -name 'Ripple*.cmake' -exec bash -c 'mv "${1}" "${1/Ripple/Xrpl}"' - {} \; -if [ -e cmake/xrpl_add_test.cmake ]; then - mv cmake/xrpl_add_test.cmake cmake/XrplAddTest.cmake -fi if [ -e include/xrpl/proto/ripple.proto ]; then mv include/xrpl/proto/ripple.proto include/xrpl/proto/xrpl.proto fi @@ -60,7 +57,6 @@ find cmake -type f -name '*.cmake' | while read -r FILE; do done ${SED_COMMAND} -i -E 's/Rippled?/Xrpl/g' CMakeLists.txt ${SED_COMMAND} -i 's/ripple/xrpl/g' CMakeLists.txt -${SED_COMMAND} -i 's/include(xrpl_add_test)/include(XrplAddTest)/' src/tests/libxrpl/CMakeLists.txt ${SED_COMMAND} -i 's/ripple.pb.h/xrpl.pb.h/' include/xrpl/protocol/messages.h ${SED_COMMAND} -i 's/ripple.pb.h/xrpl.pb.h/' BUILD.md ${SED_COMMAND} -i 's/ripple.pb.h/xrpl.pb.h/' BUILD.md diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index 6f0750e3f7..c215540b2e 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -236,6 +236,15 @@ jobs: retention-days: 3 if-no-files-found: error + - name: Upload the test binary (Linux) + if: ${{ github.event.repository.visibility == 'public' && runner.os == 'Linux' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: xrpl_tests-${{ inputs.config_name }} + path: ${{ env.BUILD_DIR }}/xrpl_tests + retention-days: 3 + if-no-files-found: error + - name: Export server definitions if: ${{ runner.os != 'Windows' && !inputs.build_only && env.VOIDSTAR_ENABLED != 'true' }} working-directory: ${{ env.BUILD_DIR }} @@ -286,16 +295,8 @@ jobs: - name: Run the separate tests if: ${{ !inputs.build_only }} - working-directory: ${{ env.BUILD_DIR }} - # Windows locks some of the build files while running tests, and parallel jobs can collide - env: - BUILD_TYPE: ${{ inputs.build_type }} - PARALLELISM: ${{ runner.os == 'Windows' && '1' || steps.nproc.outputs.nproc }} - run: | - ctest \ - --output-on-failure \ - -C "${BUILD_TYPE}" \ - -j "${PARALLELISM}" + working-directory: ${{ runner.os == 'Windows' && format('{0}/{1}', env.BUILD_DIR, inputs.build_type) || env.BUILD_DIR }} + run: ./xrpl_tests - name: Run the embedded tests if: ${{ !inputs.build_only }} diff --git a/cmake/XrplAddTest.cmake b/cmake/XrplAddTest.cmake deleted file mode 100644 index 2f1209e03c..0000000000 --- a/cmake/XrplAddTest.cmake +++ /dev/null @@ -1,22 +0,0 @@ -include(isolate_headers) - -function(xrpl_add_test name) - set(target ${PROJECT_NAME}.test.${name}) - - file( - GLOB_RECURSE sources - CONFIGURE_DEPENDS - "${CMAKE_CURRENT_SOURCE_DIR}/${name}/*.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/${name}.cpp" - ) - add_executable(${target} ${ARGN} ${sources}) - - isolate_headers( - ${target} - "${CMAKE_SOURCE_DIR}" - "${CMAKE_SOURCE_DIR}/tests/${name}" - PRIVATE - ) - - add_test(NAME ${target} COMMAND ${target}) -endfunction() diff --git a/cmake/XrplCov.cmake b/cmake/XrplCov.cmake index d81d7e689f..86ba534a88 100644 --- a/cmake/XrplCov.cmake +++ b/cmake/XrplCov.cmake @@ -47,7 +47,7 @@ setup_target_for_coverage_gcovr( "include/xrpl/beast/test" "include/xrpl/beast/unit_test" "${CMAKE_BINARY_DIR}/pb-xrpl.libpb" - DEPENDENCIES xrpld xrpl.tests + DEPENDENCIES xrpld xrpl_tests ) add_code_coverage_to_target(opts INTERFACE) diff --git a/src/tests/libxrpl/CMakeLists.txt b/src/tests/libxrpl/CMakeLists.txt index ee07698519..60288e5f20 100644 --- a/src/tests/libxrpl/CMakeLists.txt +++ b/src/tests/libxrpl/CMakeLists.txt @@ -1,51 +1,56 @@ -include(XrplAddTest) +include(GoogleTest) +include(isolate_headers) # Test requirements. find_package(GTest REQUIRED) -# Custom target for all tests defined in this file -add_custom_target(xrpl.tests) - -# Test helpers -add_library(xrpl.helpers.test STATIC) -target_sources( - xrpl.helpers.test - PRIVATE helpers/Account.cpp helpers/TestSink.cpp helpers/TxTest.cpp +# Single combined gtest binary built from the shared test helpers and all test +# modules below. +add_executable( + xrpl_tests + main.cpp + helpers/Account.cpp + helpers/TestSink.cpp + helpers/TxTest.cpp ) -target_include_directories(xrpl.helpers.test PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) -target_link_libraries(xrpl.helpers.test PUBLIC xrpl.libxrpl gtest::gtest) - -# Common library dependencies for the rest of the tests. -add_library(xrpl.imports.test INTERFACE) -target_link_libraries( - xrpl.imports.test - INTERFACE gtest::gtest xrpl.libxrpl xrpl.helpers.test +set_target_properties( + xrpl_tests + PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" ) +# Lets test sources include the shared helpers as . +target_include_directories(xrpl_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) +target_link_libraries(xrpl_tests PRIVATE GTest::gtest xrpl.libxrpl) -# One test for each module. -xrpl_add_test(basics) -target_link_libraries(xrpl.test.basics PRIVATE xrpl.imports.test) -add_dependencies(xrpl.tests xrpl.test.basics) - -xrpl_add_test(crypto) -target_link_libraries(xrpl.test.crypto PRIVATE xrpl.imports.test) -add_dependencies(xrpl.tests xrpl.test.crypto) - -xrpl_add_test(json) -target_link_libraries(xrpl.test.json PRIVATE xrpl.imports.test) -add_dependencies(xrpl.tests xrpl.test.json) - -xrpl_add_test(tx) -target_link_libraries(xrpl.test.tx PRIVATE xrpl.imports.test) -add_dependencies(xrpl.tests xrpl.test.tx) - -xrpl_add_test(protocol_autogen) -target_link_libraries(xrpl.test.protocol_autogen PRIVATE xrpl.imports.test) -add_dependencies(xrpl.tests xrpl.test.protocol_autogen) - -# Network unit tests are currently not supported on Windows +# One source subdirectory per module. Network unit tests are currently not +# supported on Windows. +set(test_modules + basics + crypto + json + tx + protocol_autogen +) if(NOT WIN32) - xrpl_add_test(net) - target_link_libraries(xrpl.test.net PRIVATE xrpl.imports.test) - add_dependencies(xrpl.tests xrpl.test.net) + list(APPEND test_modules net) endif() + +foreach(module IN LISTS test_modules) + # Append the module's sources (${module}/*.cpp and ${module}.cpp, if any). + file( + GLOB_RECURSE sources + CONFIGURE_DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/${module}/*.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/${module}.cpp" + ) + target_sources(xrpl_tests PRIVATE ${sources}) + + # Expose the module's private headers under their canonical include path. + isolate_headers( + xrpl_tests + "${CMAKE_SOURCE_DIR}" + "${CMAKE_SOURCE_DIR}/tests/${module}" + PRIVATE + ) +endforeach() + +gtest_discover_tests(xrpl_tests) diff --git a/src/tests/libxrpl/crypto/main.cpp b/src/tests/libxrpl/crypto/main.cpp deleted file mode 100644 index 5142bbe08a..0000000000 --- a/src/tests/libxrpl/crypto/main.cpp +++ /dev/null @@ -1,8 +0,0 @@ -#include - -int -main(int argc, char** argv) -{ - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} diff --git a/src/tests/libxrpl/json/main.cpp b/src/tests/libxrpl/json/main.cpp deleted file mode 100644 index 5142bbe08a..0000000000 --- a/src/tests/libxrpl/json/main.cpp +++ /dev/null @@ -1,8 +0,0 @@ -#include - -int -main(int argc, char** argv) -{ - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} diff --git a/src/tests/libxrpl/basics/main.cpp b/src/tests/libxrpl/main.cpp similarity index 100% rename from src/tests/libxrpl/basics/main.cpp rename to src/tests/libxrpl/main.cpp diff --git a/src/tests/libxrpl/net/main.cpp b/src/tests/libxrpl/net/main.cpp deleted file mode 100644 index 5142bbe08a..0000000000 --- a/src/tests/libxrpl/net/main.cpp +++ /dev/null @@ -1,8 +0,0 @@ -#include - -int -main(int argc, char** argv) -{ - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} diff --git a/src/tests/libxrpl/tx/main.cpp b/src/tests/libxrpl/tx/main.cpp deleted file mode 100644 index 5142bbe08a..0000000000 --- a/src/tests/libxrpl/tx/main.cpp +++ /dev/null @@ -1,8 +0,0 @@ -#include - -int -main(int argc, char** argv) -{ - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} From 79f4ddc4a684d84701a1d97304c18285a7640cf8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 8 Jun 2026 05:37:50 -0400 Subject: [PATCH 16/78] ci: [DEPENDABOT] bump codecov/codecov-action from 6.0.1 to 7.0.0 (#7426) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/reusable-build-test-config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index c215540b2e..dc3336dd2a 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -370,7 +370,7 @@ jobs: - name: Upload coverage report if: ${{ github.repository == 'XRPLF/rippled' && !inputs.build_only && env.COVERAGE_ENABLED == 'true' }} - uses: codecov/codecov-action@e79a6962e0d4c0c17b229090214935d2e33f8354 # v6.0.1 + uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 with: disable_search: true disable_telem: true From a389f922ddfacb5e28be461252ad1a57f5c4a265 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Mon, 8 Jun 2026 14:41:08 +0100 Subject: [PATCH 17/78] ci: Use new packaging images and don't cancel develop builds (#7417) Co-authored-by: Bart --- .github/scripts/strategy-matrix/linux.json | 6 ++--- .github/workflows/build-nix-images.yml | 3 ++- .github/workflows/build-packaging-images.yml | 3 ++- .github/workflows/pre-commit.yml | 2 +- .github/workflows/publish-docs.yml | 4 +-- .../workflows/reusable-build-test-config.yml | 2 +- .github/workflows/reusable-clang-tidy.yml | 6 ++--- .github/workflows/reusable-package.yml | 25 ------------------- .github/workflows/reusable-upload-recipe.yml | 2 +- .github/workflows/upload-conan-deps.yml | 2 +- src/tests/libxrpl/CMakeLists.txt | 2 +- 11 files changed, 17 insertions(+), 40 deletions(-) diff --git a/.github/scripts/strategy-matrix/linux.json b/.github/scripts/strategy-matrix/linux.json index 7da48a6a25..edacdbde4c 100644 --- a/.github/scripts/strategy-matrix/linux.json +++ b/.github/scripts/strategy-matrix/linux.json @@ -1,5 +1,5 @@ { - "image_tag": "sha-8abe82e", + "image_tag": "sha-63ffdc3", "configs": { "ubuntu": [ { @@ -67,7 +67,7 @@ "compiler": ["gcc"], "build_type": ["Release"], "arch": ["amd64"], - "image": "debian:bookworm" + "image": "ghcr.io/xrplf/xrpld/packaging-debian:sha-63ffdc3" } ], @@ -76,7 +76,7 @@ "compiler": ["gcc"], "build_type": ["Release"], "arch": ["amd64"], - "image": "registry.access.redhat.com/ubi9/ubi:latest" + "image": "ghcr.io/xrplf/xrpld/packaging-rhel:sha-63ffdc3" } ] } diff --git a/.github/workflows/build-nix-images.yml b/.github/workflows/build-nix-images.yml index dc02f84e0f..4e38ca7c57 100644 --- a/.github/workflows/build-nix-images.yml +++ b/.github/workflows/build-nix-images.yml @@ -22,7 +22,8 @@ on: workflow_dispatch: concurrency: - group: ${{ github.workflow }}-${{ github.ref }} + # Read `on-trigger.yml` for the rationale behind this concurrency group name. + group: ${{ github.workflow }}-${{ github.event_name == 'push' && github.ref == 'refs/heads/develop' && github.sha || github.ref }} cancel-in-progress: true defaults: diff --git a/.github/workflows/build-packaging-images.yml b/.github/workflows/build-packaging-images.yml index a11a16f298..c445dbf726 100644 --- a/.github/workflows/build-packaging-images.yml +++ b/.github/workflows/build-packaging-images.yml @@ -20,7 +20,8 @@ on: workflow_dispatch: concurrency: - group: ${{ github.workflow }}-${{ github.ref }} + # Read `on-trigger.yml` for the rationale behind this concurrency group name. + group: ${{ github.workflow }}-${{ github.event_name == 'push' && github.ref == 'refs/heads/develop' && github.sha || github.ref }} cancel-in-progress: true defaults: diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index de6a4f40b4..aecf0c2a8b 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -14,7 +14,7 @@ on: jobs: # Call the workflow in the XRPLF/actions repo that runs the pre-commit hooks. run-hooks: - uses: XRPLF/actions/.github/workflows/pre-commit.yml@cba1f0891650baf1a9c88624dc2d72573be2eb81 + uses: XRPLF/actions/.github/workflows/pre-commit.yml@312aaab296060ff89d7f798dcab59f019bea6e02 with: runs_on: ubuntu-latest container: '{ "image": "ghcr.io/xrplf/ci/tools-rippled-pre-commit:sha-41ec7c1" }' diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index 35f33b6446..bcf5968384 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -41,13 +41,13 @@ env: jobs: build: runs-on: ubuntu-latest - container: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-8abe82e + container: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-63ffdc3 steps: - name: Checkout repository uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab + uses: XRPLF/actions/prepare-runner@c47daebb2f9db64ffbac71b47d68a661498d5ce8 with: enable_ccache: false diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index dc3336dd2a..d53cf97a39 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -113,7 +113,7 @@ jobs: uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab + uses: XRPLF/actions/prepare-runner@c47daebb2f9db64ffbac71b47d68a661498d5ce8 with: enable_ccache: ${{ inputs.ccache_enabled }} diff --git a/.github/workflows/reusable-clang-tidy.yml b/.github/workflows/reusable-clang-tidy.yml index 31e06d05eb..9f10711b6f 100644 --- a/.github/workflows/reusable-clang-tidy.yml +++ b/.github/workflows/reusable-clang-tidy.yml @@ -29,14 +29,14 @@ jobs: if: ${{ inputs.check_only_changed }} permissions: contents: read - uses: XRPLF/actions/.github/workflows/determine-tidy-files.yml@224f3c48d3014d082a1129237b8291ff0b0a331f + uses: XRPLF/actions/.github/workflows/determine-tidy-files.yml@312aaab296060ff89d7f798dcab59f019bea6e02 run-clang-tidy: name: Run clang tidy needs: [determine-files] if: ${{ always() && !cancelled() && (!inputs.check_only_changed || needs.determine-files.outputs.cpp_changed_files != '' || needs.determine-files.outputs.clang_tidy_config_changed == 'true') }} runs-on: ["self-hosted", "Linux", "X64", "heavy"] - container: "ghcr.io/xrplf/xrpld/nix-debian:sha-8abe82e" + container: "ghcr.io/xrplf/xrpld/nix-debian:sha-63ffdc3" permissions: contents: read issues: write @@ -45,7 +45,7 @@ jobs: uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab + uses: XRPLF/actions/prepare-runner@c47daebb2f9db64ffbac71b47d68a661498d5ce8 with: enable_ccache: false diff --git a/.github/workflows/reusable-package.yml b/.github/workflows/reusable-package.yml index 890277d184..0e3f657006 100644 --- a/.github/workflows/reusable-package.yml +++ b/.github/workflows/reusable-package.yml @@ -68,31 +68,6 @@ jobs: timeout-minutes: 30 steps: - # Packaging runs in a vanilla distro image, so the tooling has to come - # from the distro's archive: debhelper for deb, rpm-build (and the - # systemd / find-debuginfo macros it depends on) for rpm. Run this - # before actions/checkout so the latter can use git (real history) for - # build_pkg.sh's SOURCE_DATE_EPOCH; otherwise it falls back to a tarball - # download and the timestamp comes from wall-clock time. - - name: Install packaging tooling (deb) - if: ${{ matrix.distro == 'debian' }} - run: | - export DEBIAN_FRONTEND=noninteractive - apt-get update - apt-get install -y --no-install-recommends \ - ca-certificates \ - debhelper \ - git - - - name: Install packaging tooling (rpm) - if: ${{ matrix.distro == 'rhel' }} - run: | - dnf install -y --setopt=install_weak_deps=False \ - git \ - rpm-build \ - redhat-rpm-config \ - systemd-rpm-macros - - name: Checkout repository uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 diff --git a/.github/workflows/reusable-upload-recipe.yml b/.github/workflows/reusable-upload-recipe.yml index 6e1ea943ca..1c90fb0e72 100644 --- a/.github/workflows/reusable-upload-recipe.yml +++ b/.github/workflows/reusable-upload-recipe.yml @@ -40,7 +40,7 @@ defaults: jobs: upload: runs-on: ubuntu-latest - container: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-8abe82e + container: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-63ffdc3 steps: - name: Checkout repository uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 diff --git a/.github/workflows/upload-conan-deps.yml b/.github/workflows/upload-conan-deps.yml index 6310c90899..1a52ceee63 100644 --- a/.github/workflows/upload-conan-deps.yml +++ b/.github/workflows/upload-conan-deps.yml @@ -67,7 +67,7 @@ jobs: uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab + uses: XRPLF/actions/prepare-runner@c47daebb2f9db64ffbac71b47d68a661498d5ce8 with: enable_ccache: false diff --git a/src/tests/libxrpl/CMakeLists.txt b/src/tests/libxrpl/CMakeLists.txt index 60288e5f20..2dae6fccb9 100644 --- a/src/tests/libxrpl/CMakeLists.txt +++ b/src/tests/libxrpl/CMakeLists.txt @@ -53,4 +53,4 @@ foreach(module IN LISTS test_modules) ) endforeach() -gtest_discover_tests(xrpl_tests) +gtest_discover_tests(xrpl_tests DISCOVERY_TIMEOUT 60) From 577d7457f1e8e9389eb24d49e34ed7cb3b00d28f Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Mon, 8 Jun 2026 18:10:05 +0100 Subject: [PATCH 18/78] 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 19/78] 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 20/78] 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 21/78] 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 22/78] 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 23/78] 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 24/78] 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 8617eaeb26f07e7c671b8f86fb639179a5998f71 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 10 Jun 2026 01:00:19 +0100 Subject: [PATCH 25/78] 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 From 742aa0878bbccdce385db4c8b6b77f2da19fad4a Mon Sep 17 00:00:00 2001 From: Bart Date: Wed, 10 Jun 2026 05:16:53 -0400 Subject: [PATCH 26/78] test: Do not create data directory for memory databases (#7323) Co-authored-by: Bart <11445373+bthomee@users.noreply.github.com> --- src/xrpld/app/misc/SHAMapStoreImp.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/xrpld/app/misc/SHAMapStoreImp.cpp b/src/xrpld/app/misc/SHAMapStoreImp.cpp index 7259c233e4..33bbf1c613 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.cpp +++ b/src/xrpld/app/misc/SHAMapStoreImp.cpp @@ -387,8 +387,12 @@ void SHAMapStoreImp::dbPaths() { Section const section{app_.config().section(Sections::kNodeDatabase)}; - boost::filesystem::path dbPath = get(section, Keys::kPath); + // Skip creating the directory when an in-memory database is used. + if (boost::iequals(get(section, Keys::kType), "memory")) + return; + + boost::filesystem::path dbPath = get(section, Keys::kPath); if (boost::filesystem::exists(dbPath)) { if (!boost::filesystem::is_directory(dbPath)) From 8a4bf2dee60e4082b584c1702eabf93225f8da40 Mon Sep 17 00:00:00 2001 From: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Date: Wed, 10 Jun 2026 11:16:03 +0100 Subject: [PATCH 27/78] refactor: Retire fixUniversalNumber amendment (#5962) Signed-off-by: Pratik Mankawde Signed-off-by: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Co-authored-by: Claude Opus 4.6 (1M context) --- include/xrpl/protocol/AMMCore.h | 2 +- include/xrpl/protocol/IOUAmount.h | 33 ---- include/xrpl/protocol/Rules.h | 2 - include/xrpl/protocol/detail/features.macro | 2 +- src/libxrpl/protocol/AMMCore.cpp | 2 +- src/libxrpl/protocol/IOUAmount.cpp | 104 +---------- src/libxrpl/protocol/Rules.cpp | 4 - src/libxrpl/protocol/STAmount.cpp | 188 +++----------------- src/libxrpl/tx/Transactor.cpp | 3 - src/libxrpl/tx/apply.cpp | 2 - src/libxrpl/tx/applySteps.cpp | 4 +- src/test/app/AMM_test.cpp | 7 +- src/test/app/NFToken_test.cpp | 14 +- src/test/app/OfferMPT_test.cpp | 1 - src/test/app/Offer_test.cpp | 60 +++---- src/test/basics/Number_test.cpp | 1 - src/xrpld/app/misc/detail/TxQ.cpp | 5 - 17 files changed, 55 insertions(+), 379 deletions(-) diff --git a/include/xrpl/protocol/AMMCore.h b/include/xrpl/protocol/AMMCore.h index ced84c4c87..a83c8bfa84 100644 --- a/include/xrpl/protocol/AMMCore.h +++ b/include/xrpl/protocol/AMMCore.h @@ -65,7 +65,7 @@ invalidAMMAssetPair( std::optional ammAuctionTimeSlot(std::uint64_t current, STObject const& auctionSlot); -/** Return true if required AMM amendments are enabled +/** Return true if required AMM amendment is enabled */ bool ammEnabled(Rules const&); diff --git a/include/xrpl/protocol/IOUAmount.h b/include/xrpl/protocol/IOUAmount.h index 9e0fbe38eb..b057f1c245 100644 --- a/include/xrpl/protocol/IOUAmount.h +++ b/include/xrpl/protocol/IOUAmount.h @@ -1,6 +1,5 @@ #pragma once -#include #include #include @@ -179,36 +178,4 @@ to_string(IOUAmount const& amount); IOUAmount mulRatio(IOUAmount const& amt, std::uint32_t num, std::uint32_t den, bool roundUp); -// Since many uses of the number class do not have access to a ledger, -// getSTNumberSwitchover needs to be globally accessible. - -bool -getSTNumberSwitchover(); - -void -setSTNumberSwitchover(bool v); - -/** RAII class to set and restore the Number switchover. - */ - -class NumberSO -{ - bool saved_; - -public: - ~NumberSO() - { - setSTNumberSwitchover(saved_); - } - - NumberSO(NumberSO const&) = delete; - NumberSO& - operator=(NumberSO const&) = delete; - - explicit NumberSO(bool v) : saved_(getSTNumberSwitchover()) - { - setSTNumberSwitchover(v); - } -}; - } // namespace xrpl diff --git a/include/xrpl/protocol/Rules.h b/include/xrpl/protocol/Rules.h index 9c17ff2391..47b20756db 100644 --- a/include/xrpl/protocol/Rules.h +++ b/include/xrpl/protocol/Rules.h @@ -122,7 +122,6 @@ private: std::optional saved_; }; -class NumberSO; class NumberMantissaScaleGuard; bool @@ -131,7 +130,6 @@ useRulesGuards(Rules const& rules); void createGuards( Rules const& rules, - std::optional& stNumberSO, std::optional& rulesGuard, std::optional& mantissaScaleGuard); diff --git a/include/xrpl/protocol/detail/features.macro b/include/xrpl/protocol/detail/features.macro index c99c1e5ce8..2b2f24ba53 100644 --- a/include/xrpl/protocol/detail/features.macro +++ b/include/xrpl/protocol/detail/features.macro @@ -64,7 +64,6 @@ XRPL_FIX (DisallowIncomingV1, Supported::Yes, VoteBehavior::DefaultNo XRPL_FEATURE(XChainBridge, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FEATURE(AMM, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FEATURE(Clawback, Supported::Yes, VoteBehavior::DefaultNo) -XRPL_FIX (UniversalNumber, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FEATURE(XRPFees, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FIX (RemoveNFTokenAutoTrustLine, Supported::Yes, VoteBehavior::DefaultYes) @@ -112,6 +111,7 @@ XRPL_RETIRE_FIX(RmSmallIncreasedQOffers) XRPL_RETIRE_FIX(STAmountCanonicalize) XRPL_RETIRE_FIX(TakerDryOfferRemoval) XRPL_RETIRE_FIX(TrustLinesToSelf) +XRPL_RETIRE_FIX(UniversalNumber) XRPL_RETIRE_FEATURE(Checks) XRPL_RETIRE_FEATURE(CheckCashMakesTrustLine) diff --git a/src/libxrpl/protocol/AMMCore.cpp b/src/libxrpl/protocol/AMMCore.cpp index eccb581c6d..e58ab29257 100644 --- a/src/libxrpl/protocol/AMMCore.cpp +++ b/src/libxrpl/protocol/AMMCore.cpp @@ -127,7 +127,7 @@ ammAuctionTimeSlot(std::uint64_t current, STObject const& auctionSlot) bool ammEnabled(Rules const& rules) { - return rules.enabled(featureAMM) && rules.enabled(fixUniversalNumber); + return rules.enabled(featureAMM); } } // namespace xrpl diff --git a/src/libxrpl/protocol/IOUAmount.cpp b/src/libxrpl/protocol/IOUAmount.cpp index d214995809..acbf6724e1 100644 --- a/src/libxrpl/protocol/IOUAmount.cpp +++ b/src/libxrpl/protocol/IOUAmount.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -17,29 +16,6 @@ namespace xrpl { -namespace { - -// Use a static inside a function to help prevent order-of-initialization issues -LocalValue& -getStaticSTNumberSwitchover() -{ - static LocalValue kR{true}; - return kR; -} -} // namespace - -bool -getSTNumberSwitchover() -{ - return *getStaticSTNumberSwitchover(); -} - -void -setSTNumberSwitchover(bool v) -{ - *getStaticSTNumberSwitchover() = v; -} - /* The range for the mantissa when normalized */ // log(2^63,10) ~ 18.96 // @@ -75,56 +51,20 @@ IOUAmount::normalize() return; } - if (getSTNumberSwitchover()) - { - Number const v{mantissa_, exponent_}; - *this = fromNumber(v); - if (exponent_ > kMaxExponent) - Throw("value overflow"); - if (exponent_ < kMinExponent) - *this = beast::kZero; - return; - } - - bool const negative = (mantissa_ < 0); - - if (negative) - mantissa_ = -mantissa_; - - while ((mantissa_ < kMinMantissa) && (exponent_ > kMinExponent)) - { - mantissa_ *= 10; - --exponent_; - } - - while (mantissa_ > kMaxMantissa) - { - if (exponent_ >= kMaxExponent) - Throw("IOUAmount::normalize"); - - mantissa_ /= 10; - ++exponent_; - } - - if ((exponent_ < kMinExponent) || (mantissa_ < kMinMantissa)) - { - *this = beast::kZero; - return; - } - - if (exponent_ > kMaxExponent) - Throw("value overflow"); - - if (negative) - mantissa_ = -mantissa_; + Number const v{mantissa_, exponent_}; + *this = IOUAmount(v); } IOUAmount::IOUAmount(Number const& other) : IOUAmount(fromNumber(other)) { if (exponent_ > kMaxExponent) + { Throw("value overflow"); + } if (exponent_ < kMinExponent) + { *this = beast::kZero; + } } IOUAmount& @@ -139,37 +79,7 @@ IOUAmount::operator+=(IOUAmount const& other) return *this; } - if (getSTNumberSwitchover()) - { - *this = IOUAmount{Number{*this} + Number{other}}; - return *this; - } - auto m = other.mantissa_; - auto e = other.exponent_; - - while (exponent_ < e) - { - mantissa_ /= 10; - ++exponent_; - } - - while (e < exponent_) - { - m /= 10; - ++e; - } - - // This addition cannot overflow an std::int64_t but we may throw from - // normalize if the result isn't representable. - mantissa_ += m; - - if (mantissa_ >= -10 && mantissa_ <= 10) - { - *this = beast::kZero; - return *this; - } - - normalize(); + *this = IOUAmount{Number{*this} + Number{other}}; return *this; } diff --git a/src/libxrpl/protocol/Rules.cpp b/src/libxrpl/protocol/Rules.cpp index 08a95145eb..e0968ea868 100644 --- a/src/libxrpl/protocol/Rules.cpp +++ b/src/libxrpl/protocol/Rules.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include @@ -83,15 +82,12 @@ useRulesGuards(Rules const& rules) void createGuards( Rules const& rules, - std::optional& stNumberSO, std::optional& rulesGuard, std::optional& mantissaScaleGuard) { if (useRulesGuards(rules)) { // raii classes for the current ledger rules. - // fixUniversalNumber predates the rulesGuard and should be replaced. - stNumberSO.emplace(rules.enabled(fixUniversalNumber)); rulesGuard.emplace(rules); } else diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index 1ba9cd042f..449efc9543 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -388,47 +388,9 @@ operator+(STAmount const& v1, STAmount const& v2) if (v1.holds()) return {v1.asset_, v1.mpt().value() + v2.mpt().value()}; - if (getSTNumberSwitchover()) - { - auto x = v1; - x = v1.iou() + v2.iou(); - return x; - } - - int ov1 = v1.exponent(), ov2 = v2.exponent(); - std::int64_t vv1 = static_cast(v1.mantissa()); - std::int64_t vv2 = static_cast(v2.mantissa()); - - if (v1.negative()) - vv1 = -vv1; - - if (v2.negative()) - vv2 = -vv2; - - while (ov1 < ov2) - { - vv1 /= 10; - ++ov1; - } - - while (ov2 < ov1) - { - vv2 /= 10; - ++ov2; - } - - // This addition cannot overflow an std::int64_t. It can overflow an - // STAmount and the constructor will throw. - - std::int64_t const fv = vv1 + vv2; - - if ((fv >= -10) && (fv <= 10)) - return {v1.getFName(), v1.asset()}; - - if (fv >= 0) - return STAmount{v1.getFName(), v1.asset(), static_cast(fv), ov1, false}; - - return STAmount{v1.getFName(), v1.asset(), static_cast(-fv), ov1, true}; + auto x = v1; + x = v1.iou() + v2.iou(); + return x; } STAmount @@ -877,53 +839,25 @@ STAmount::canonicalize() if (asset_.holds() && offset_ > 18) Throw("MPT amount out of range"); - if (getSTNumberSwitchover()) + Number const num(isNegative_, value_, offset_, Number::Unchecked{}); + auto set = [&](auto const& val) { + auto const value = val.value(); + isNegative_ = value < 0; + value_ = isNegative_ ? -value : value; + }; + if (native()) { - Number const num(isNegative_, value_, offset_, Number::Unchecked{}); - auto set = [&](auto const& val) { - auto const value = val.value(); - isNegative_ = value < 0; - value_ = isNegative_ ? -value : value; - }; - if (native()) - { - set(XRPAmount{num}); - } - else if (asset_.holds()) - { - set(MPTAmount{num}); - } - else - { - Throw("Unknown integral asset type"); - } - offset_ = 0; + set(XRPAmount{num}); + } + else if (asset_.holds()) + { + set(MPTAmount{num}); } else { - while (offset_ < 0) - { - value_ /= 10; - ++offset_; - } - - while (offset_ > 0) - { - // N.B. do not move the overflow check to after the - // multiplication - if (native() && value_ > kMaxNativeN) - { - Throw("Native currency amount out of range"); - } - else if (!native() && value_ > kMaxMpTokenAmount) - { - Throw("MPT amount out of range"); - } - - value_ *= 10; - --offset_; - } + Throw("Unknown integral asset type"); // LCOV_EXCL_LINE } + offset_ = 0; if (native() && value_ > kMaxNativeN) { @@ -937,53 +871,7 @@ STAmount::canonicalize() return; } - if (getSTNumberSwitchover()) - { - *this = iou(); - return; - } - - if (value_ == 0) - { - offset_ = -100; - isNegative_ = false; - return; - } - - while ((value_ < kMinValue) && (offset_ > kMinOffset)) - { - value_ *= 10; - --offset_; - } - - while (value_ > kMaxValue) - { - if (offset_ >= kMaxOffset) - Throw("value overflow"); - - value_ /= 10; - ++offset_; - } - - if ((offset_ < kMinOffset) || (value_ < kMinValue)) - { - value_ = 0; - isNegative_ = false; - offset_ = -100; - return; - } - - if (offset_ > kMaxOffset) - Throw("value overflow"); - - XRPL_ASSERT( - (value_ == 0) || ((value_ >= kMinValue) && (value_ <= kMaxValue)), - "xrpl::STAmount::canonicalize : value inside range"); - XRPL_ASSERT( - (value_ == 0) || ((offset_ >= kMinOffset) && (offset_ <= kMaxOffset)), - "xrpl::STAmount::canonicalize : offset inside range"); - XRPL_ASSERT( - (value_ != 0) || (offset_ != -100), "xrpl::STAmount::canonicalize : value or offset set"); + *this = iou(); } void @@ -1395,44 +1283,8 @@ multiply(STAmount const& v1, STAmount const& v2, Asset const& asset) return STAmount(asset, minV * maxV); } - if (getSTNumberSwitchover()) - { - auto const r = Number{v1} * Number{v2}; - return STAmount{asset, r}; - } - - std::uint64_t value1 = v1.mantissa(); - std::uint64_t value2 = v2.mantissa(); - int offset1 = v1.exponent(); - int offset2 = v2.exponent(); - - if (v1.integral()) - { - while (value1 < STAmount::kMinValue) - { - value1 *= 10; - --offset1; - } - } - - if (v2.integral()) - { - while (value2 < STAmount::kMinValue) - { - value2 *= 10; - --offset2; - } - } - - // We multiply the two mantissas (each is between 10^15 - // and 10^16), so their product is in the 10^30 to 10^32 - // range. Dividing their product by 10^14 maintains the - // precision, by scaling the result to 10^16 to 10^18. - return STAmount( - asset, - muldiv(value1, value2, kTenTO14) + 7, - offset1 + offset2 + 14, - v1.negative() != v2.negative()); + auto const r = Number{v1} * Number{v2}; + return STAmount{asset, r}; } // This is the legacy version of canonicalizeRound. It's been in use diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index 51541cc2e3..68d3f36916 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -20,7 +20,6 @@ #include #include #include -#include #include #include #include @@ -1199,8 +1198,6 @@ Transactor::operator()() // with_txn_type(). // // raii classes for the current ledger rules. - // fixUniversalNumber predate the rulesGuard and should be replaced. - NumberSO const stNumberSO{view().rules().enabled(fixUniversalNumber)}; CurrentTransactionRulesGuard const currentTransactionRulesGuard(view().rules()); #ifdef DEBUG diff --git a/src/libxrpl/tx/apply.cpp b/src/libxrpl/tx/apply.cpp index 0fc0275eb0..b70cb0d345 100644 --- a/src/libxrpl/tx/apply.cpp +++ b/src/libxrpl/tx/apply.cpp @@ -9,7 +9,6 @@ #include #include #include -#include #include #include #include @@ -133,7 +132,6 @@ template ApplyResult apply(ServiceRegistry& registry, OpenView& view, PreflightChecks&& preflightChecks) { - NumberSO const stNumberSO{view.rules().enabled(fixUniversalNumber)}; return doApply(preclaim(preflightChecks(), registry, view), registry, view); } diff --git a/src/libxrpl/tx/applySteps.cpp b/src/libxrpl/tx/applySteps.cpp index 217fdd717f..336bb2004b 100644 --- a/src/libxrpl/tx/applySteps.cpp +++ b/src/libxrpl/tx/applySteps.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include #include @@ -70,10 +69,9 @@ withTxnType(Rules const& rules, TxType txnType, F&& f) // // See also Transactor::operator(). // - std::optional stNumberSO; std::optional rulesGuard; std::optional mantissaScaleGuard; - createGuards(rules, stNumberSO, rulesGuard, mantissaScaleGuard); + createGuards(rules, rulesGuard, mantissaScaleGuard); switch (txnType) { diff --git a/src/test/app/AMM_test.cpp b/src/test/app/AMM_test.cpp index 64972c24ab..e3a1cc935f 100644 --- a/src/test/app/AMM_test.cpp +++ b/src/test/app/AMM_test.cpp @@ -4333,15 +4333,10 @@ private: testAmendment() { testcase("Amendment"); - FeatureBitset const all{testableAmendments()}; - FeatureBitset const noAMM{all - featureAMM}; - FeatureBitset const noNumber{all - fixUniversalNumber}; - FeatureBitset const noAMMAndNumber{all - featureAMM - fixUniversalNumber}; using namespace jtx; + Env env{*this, testableAmendments() - featureAMM}; - for (auto const& feature : {noAMM, noNumber, noAMMAndNumber}) { - Env env{*this, feature}; fund(env, gw_, {alice_}, {USD(1'000)}, Fund::All); AMM amm(env, alice_, XRP(1'000), USD(1'000), Ter(temDISABLED)); diff --git a/src/test/app/NFToken_test.cpp b/src/test/app/NFToken_test.cpp index 269bc72c53..ba8f09c449 100644 --- a/src/test/app/NFToken_test.cpp +++ b/src/test/app/NFToken_test.cpp @@ -2236,17 +2236,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // See the impact of rounding when the nft is sold for small amounts // of drops. - for (auto numberSwitchOver : {true}) { - if (numberSwitchOver) - { - env.enableFeature(fixUniversalNumber); - } - else - { - env.disableFeature(fixUniversalNumber); - } - // An nft with a transfer fee of 1 basis point. uint256 const nftID = token::getNextID(env, alice, 0u, tfTransferable, 1); env(token::mint(alice), Txflags(tfTransferable), token::XferFee(1)); @@ -2268,7 +2258,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // minter sells to carol. The payment is just small enough that // alice does not get any transfer fee. - auto pmt = numberSwitchOver ? drops(50000) : drops(99999); + auto pmt = drops(50000); STAmount carolBalance = env.balance(carol); uint256 const minterSellOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; env(token::createOffer(minter, nftID, pmt), Txflags(tfSellNFToken)); @@ -2285,7 +2275,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite // transfer that enables a transfer fee of 1 basis point. STAmount beckyBalance = env.balance(becky); uint256 const beckyBuyOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; - pmt = numberSwitchOver ? drops(50001) : drops(100000); + pmt = drops(50001); env(token::createOffer(becky, nftID, pmt), token::Owner(carol)); env.close(); env(token::acceptBuyOffer(carol, beckyBuyOfferIndex)); diff --git a/src/test/app/OfferMPT_test.cpp b/src/test/app/OfferMPT_test.cpp index e0f2f4eab0..ed0b2ffbe3 100644 --- a/src/test/app/OfferMPT_test.cpp +++ b/src/test/app/OfferMPT_test.cpp @@ -1827,7 +1827,6 @@ public: using namespace jtx; Env env{*this, features}; - env.enableFeature(fixUniversalNumber); auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; diff --git a/src/test/app/Offer_test.cpp b/src/test/app/Offer_test.cpp index 83c58884e0..7382f4f090 100644 --- a/src/test/app/Offer_test.cpp +++ b/src/test/app/Offer_test.cpp @@ -1973,54 +1973,36 @@ public: using namespace jtx; - for (auto numberSwitchOver : {false, true}) - { - Env env{*this, features}; - if (numberSwitchOver) - { - env.enableFeature(fixUniversalNumber); - } - else - { - env.disableFeature(fixUniversalNumber); - } + Env env{*this, features}; - auto const gw = Account{"gateway"}; - auto const alice = Account{"alice"}; - auto const bob = Account{"bob"}; - auto const usd = gw["USD"]; + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + auto const usd = gw["USD"]; - env.fund(XRP(10000), gw, alice, bob); - env.close(); + env.fund(XRP(10000), gw, alice, bob); + env.close(); - env(rate(gw, 1.005)); + env(rate(gw, 1.005)); - env(trust(alice, usd(1000))); - env(trust(bob, usd(1000))); - env(trust(gw, alice["USD"](50))); + env(trust(alice, usd(1000))); + env(trust(bob, usd(1000))); + env(trust(gw, alice["USD"](50))); - env(pay(gw, bob, bob["USD"](1))); - env(pay(alice, gw, usd(50))); + env(pay(gw, bob, bob["USD"](1))); + env(pay(alice, gw, usd(50))); - env(trust(gw, alice["USD"](0))); + env(trust(gw, alice["USD"](0))); - env(offer(alice, usd(50), XRP(150000))); - env(offer(bob, XRP(100), usd(0.1))); + env(offer(alice, usd(50), XRP(150000))); + env(offer(bob, XRP(100), usd(0.1))); - auto jrr = ledgerEntryState(env, alice, gw, "USD"); - BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "49.96666666666667"); + auto jrr = ledgerEntryState(env, alice, gw, "USD"); + BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "49.96666666666667"); - jrr = ledgerEntryState(env, bob, gw, "USD"); - json::Value const bobUSD = jrr[jss::node][sfBalance.fieldName][jss::value]; - if (!numberSwitchOver) - { - BEAST_EXPECT(bobUSD == "-0.966500000033334"); - } - else - { - BEAST_EXPECT(bobUSD == "-0.9665000000333333"); - } - } + jrr = ledgerEntryState(env, bob, gw, "USD"); + json::Value const bobUSD = jrr[jss::node][sfBalance.fieldName][jss::value]; + BEAST_EXPECT(bobUSD == "-0.9665000000333333"); } void diff --git a/src/test/basics/Number_test.cpp b/src/test/basics/Number_test.cpp index f4bd1c9d66..2d2745de14 100644 --- a/src/test/basics/Number_test.cpp +++ b/src/test/basics/Number_test.cpp @@ -1514,7 +1514,6 @@ public: void testToStAmount() { - NumberSO const stNumberSO{true}; Issue const issue; Number const n{7'518'783'80596, -5}; SaveNumberRoundMode const save{Number::setround(Number::RoundingMode::ToNearest)}; diff --git a/src/xrpld/app/misc/detail/TxQ.cpp b/src/xrpld/app/misc/detail/TxQ.cpp index f98580ede4..0326828a70 100644 --- a/src/xrpld/app/misc/detail/TxQ.cpp +++ b/src/xrpld/app/misc/detail/TxQ.cpp @@ -16,8 +16,6 @@ #include #include #include -#include -#include #include #include #include @@ -306,7 +304,6 @@ TxQ::MaybeTx::apply(Application& app, OpenView& view, beast::Journal j) { // If the rules or flags change, preflight again XRPL_ASSERT(pfResult, "xrpl::TxQ::MaybeTx::apply : preflight result is set"); - NumberSO const stNumberSO{view.rules().enabled(fixUniversalNumber)}; // NOLINTBEGIN(bugprone-unchecked-optional-access) assert above if (pfResult->rules != view.rules() || pfResult->flags != flags) @@ -731,8 +728,6 @@ TxQ::apply( ApplyFlags flags, beast::Journal j) { - NumberSO const stNumberSO{view.rules().enabled(fixUniversalNumber)}; - // See if the transaction is valid, properly formed, // etc. before doing potentially expensive queue // replace and multi-transaction operations. From 97ca7d57bcedab341e7887cd7950299d2bde9598 Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Wed, 10 Jun 2026 13:44:57 +0200 Subject: [PATCH 28/78] perf: Dispatch "hasInvalidAmount()" on type tag instead of dynamic_cast (#7402) --- src/libxrpl/protocol/STAmount.cpp | 32 ++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index 449efc9543..748d00f25a 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -1138,16 +1138,34 @@ hasInvalidAmount(STBase const& field, int depth, beast::Journal j) return true; } - if (auto const amount = dynamic_cast(&field)) - return !isLegalMPT(*amount) || !isLegalNet(*amount); + // Dispatch on the serialized type tag rather than RTTI: this is on the invariant-checking path + // and a dynamic_cast chain over every field of every modified entry is measurably expensive. + // The object-like tags below all denote STObject subclasses (STLedgerEntry, STTx), so the + // downcast is sound; nested fields are only ever plain STI_OBJECT / STI_ARRAY containers. + // safeDowncast keeps a dynamic_cast validity assert in debug builds while compiling to + // static_cast in release. + switch (field.getSType()) + { + case STI_AMOUNT: { + auto const& amount = safeDowncast(field); + return !isLegalMPT(amount) || !isLegalNet(amount); + } - if (auto const object = dynamic_cast(&field)) - return hasInvalidAmount(*object, depth + 1, j); + case STI_OBJECT: + case STI_LEDGERENTRY: + case STI_TRANSACTION: + return hasInvalidAmount(safeDowncast(field), depth + 1, j); - if (auto const array = dynamic_cast(&field)) - return hasInvalidAmount(*array, depth + 1, j); + case STI_ARRAY: + return hasInvalidAmount(safeDowncast(field), depth + 1, j); - return false; + default: { + XRPL_ASSERT( + dynamic_cast(&field) == nullptr, + "xrpl::hasInvalidAmount : unhandled STObject type"); + return false; + } + } } bool From 83cc5df72e9fa2f4d9d91a674908afcd6a50302a Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Wed, 10 Jun 2026 14:05:53 +0200 Subject: [PATCH 29/78] fix: Disable transaction invariants (#7409) --- src/libxrpl/tx/Transactor.cpp | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index 68d3f36916..aa7b81c015 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -1171,21 +1171,17 @@ Transactor::checkTransactionInvariants(TER result, XRPAmount fee) [[nodiscard]] TER Transactor::checkInvariants(TER result, XRPAmount fee) { - // Transaction invariants first (more specific). These check post-conditions of the specific - // transaction. If these fail, the transaction's core logic is wrong. - auto const txResult = checkTransactionInvariants(result, fee); - - // Protocol invariants second (broader). These check properties that must hold regardless of - // transaction type. - auto const protoResult = ctx_.checkInvariants(result, fee); - - // Fail if either check failed. tef (fatal) takes priority over tec. - if (protoResult == tefINVARIANT_FAILED) - return tefINVARIANT_FAILED; - if (txResult == tecINVARIANT_FAILED || protoResult == tecINVARIANT_FAILED) - return tecINVARIANT_FAILED; - - return result; + /* + * DISABLED for 3.2.0 — Must be re-introduced for 3.3.0 + * + * Transaction invariants are disabled due to a performance regression: + * the two-pass design (transaction-specific invariants + protocol invariants) + * iterates over modified ledger entries twice per transaction. + * + * Until resolved, only protocol invariants are checked (delegated to ctx_). + * This is safe because all transaction invariants in 3.2.0 are no-ops. + */ + return ctx_.checkInvariants(result, fee); } //------------------------------------------------------------------------------ ApplyResult From dd0b6754d4c33d906d54f317dcc9f4da800488ec Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 10 Jun 2026 15:45:51 +0100 Subject: [PATCH 30/78] ci: Add `gh` and `file` to nix packages (#7444) --- cspell.config.yaml | 1 + flake.lock | 6 +++--- nix/docker/check-tools.sh | 2 ++ nix/packages.nix | 2 ++ 4 files changed, 8 insertions(+), 3 deletions(-) diff --git a/cspell.config.yaml b/cspell.config.yaml index cab2fc3da6..926ac06596 100644 --- a/cspell.config.yaml +++ b/cspell.config.yaml @@ -84,6 +84,7 @@ words: - coro - coros - cowid + - cpack - cryptocondition - cryptoconditional - cryptoconditions diff --git a/flake.lock b/flake.lock index 2013cfabd4..f8553af703 100644 --- a/flake.lock +++ b/flake.lock @@ -2,11 +2,11 @@ "nodes": { "nixpkgs": { "locked": { - "lastModified": 1780243769, - "narHash": "sha256-x5UQuRsH3MqI0U9afaXSNqzTPSeZlRLvFAav2Ux1pNw=", + "lastModified": 1780749050, + "narHash": "sha256-3av0pIjlOWQ6rDbNOmpUSvbNnJkGORQKKjb4LtCZsIY=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "331800de5053fcebacf6813adb5db9c9dca22a0c", + "rev": "a799d3e3886da994fa307f817a6bc705ae538eeb", "type": "github" }, "original": { diff --git a/nix/docker/check-tools.sh b/nix/docker/check-tools.sh index 67bcdff8a9..276e5977ff 100755 --- a/nix/docker/check-tools.sh +++ b/nix/docker/check-tools.sh @@ -10,10 +10,12 @@ cmake --version conan --version curl --version doxygen --version +file --version g++ --version gcc --version gcov --version gcovr --version +gh --version git --version git-cliff --version gpg --version diff --git a/nix/packages.nix b/nix/packages.nix index d40472634b..fc4eff679e 100644 --- a/nix/packages.nix +++ b/nix/packages.nix @@ -13,7 +13,9 @@ in conan curlMinimal # needed for codecov/codecov-action doxygen + file # needed for cpack in Clio gcovr + gh git git-cliff gnumake From 1f359f719cbf475e6c010ad0fcf5b4044c6768d1 Mon Sep 17 00:00:00 2001 From: Shi Cheng <97218929+shichengripple001@users.noreply.github.com> Date: Thu, 11 Jun 2026 01:24:44 +0800 Subject: [PATCH 31/78] fix: Add [[maybe_unused]] to fix320Enabled for assert=OFF builds (#7446) Co-authored-by: Claude Sonnet 4.6 --- src/libxrpl/ledger/helpers/LendingHelpers.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libxrpl/ledger/helpers/LendingHelpers.cpp b/src/libxrpl/ledger/helpers/LendingHelpers.cpp index 676b473132..f7ec8a8bc3 100644 --- a/src/libxrpl/ledger/helpers/LendingHelpers.cpp +++ b/src/libxrpl/ledger/helpers/LendingHelpers.cpp @@ -813,7 +813,7 @@ doOverpayment( // 3. The overpayment's penalty interest part (= untrackedInterest // for the overpayment path; see computeOverpaymentComponents): // trackedInterestPart() - bool const fix320Enabled = rules.enabled(fixCleanup3_2_0); + [[maybe_unused]] bool const fix320Enabled = rules.enabled(fixCleanup3_2_0); XRPL_ASSERT_IF( fix320Enabled, overpaymentComponents.trackedPrincipalDelta == From 8000adfa797f3d5c81284cb3bcc8c6e9213549ec Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 10 Jun 2026 19:08:34 +0100 Subject: [PATCH 32/78] ci: Make configurations launch on certain event types (#7447) --- .github/scripts/strategy-matrix/generate.py | 57 ++++++++++++++++--- .github/scripts/strategy-matrix/linux.json | 3 +- .github/scripts/strategy-matrix/macos.json | 3 +- .github/scripts/strategy-matrix/windows.json | 6 +- .../workflows/reusable-strategy-matrix.yml | 3 +- 5 files changed, 61 insertions(+), 11 deletions(-) diff --git a/.github/scripts/strategy-matrix/generate.py b/.github/scripts/strategy-matrix/generate.py index aaf84a51d0..6353567f27 100755 --- a/.github/scripts/strategy-matrix/generate.py +++ b/.github/scripts/strategy-matrix/generate.py @@ -27,6 +27,19 @@ def get_cmake_args(build_type: str, extra_args: str) -> str: return " ".join(args) +def runs_on_event(exclude_event_types: list[str], event: str | None) -> bool: + """Whether a config should run for the current event. + + 'exclude_event_types' is a list of GitHub event names (e.g. + ["pull_request"]) on which the config should NOT run; an empty list means + the config runs on every event. When no event is given (event is None), no + filtering is applied. + """ + if event is None: + return True + return event not in exclude_event_types + + # --------------------------------------------------------------------------- # Input types — shapes of the JSON config files # --------------------------------------------------------------------------- @@ -43,6 +56,9 @@ class LinuxConfig: suffix: str = "" extra_cmake_args: str = "" image: str = "" # only used by package_configs entries + # List of GitHub event names (e.g. "pull_request") on which this config + # should NOT run. Empty means it runs on every event. + exclude_event_types: list[str] = dataclasses.field(default_factory=list) @dataclasses.dataclass @@ -77,6 +93,9 @@ class PlatformConfig: build_type: list[str] build_only: bool = False # if true, skip tests (e.g. macos/Windows Debug) extra_cmake_args: str = "" + # List of GitHub event names (e.g. "pull_request") on which this config + # should NOT run. Empty means it runs on every event. + exclude_event_types: list[str] = dataclasses.field(default_factory=list) def __post_init__(self) -> None: if isinstance(self.build_type, str): @@ -151,16 +170,21 @@ _ARCHS: dict[str, Architecture] = { } -def expand_linux_matrix(linux: LinuxFile) -> list[MatrixEntry]: +def expand_linux_matrix( + linux: LinuxFile, event: str | None = None +) -> list[MatrixEntry]: """Expand a LinuxFile into a flat list of matrix entries. Each config entry is expanded over the cross-product of its - compiler, build_type, sanitizers, and architecture lists. + compiler, build_type, sanitizers, and architecture lists. Configs that + exclude the current event are skipped. """ entries: list[MatrixEntry] = [] for distro, configs in linux.configs.items(): for cfg in configs: + if not runs_on_event(cfg.exclude_event_types, event): + continue # An empty sanitizers list means "one entry with no sanitizer". effective_sanitizers = cfg.sanitizers or [""] effective_archs = {arch: _ARCHS[arch] for arch in cfg.arch} @@ -218,13 +242,20 @@ def expand_linux_packaging(linux: LinuxFile) -> list[PackagingEntry]: return entries -def expand_platform_matrix(pf: PlatformFile) -> list[MatrixEntry]: - """Expand a PlatformFile (macOS or Windows) into matrix entries.""" +def expand_platform_matrix( + pf: PlatformFile, event: str | None = None +) -> list[MatrixEntry]: + """Expand a PlatformFile (macOS or Windows) into matrix entries. + + Configs that exclude the current event are skipped. + """ platform_name, arch = pf.platform.split("/") is_windows = platform_name == "windows" entries: list[MatrixEntry] = [] for cfg in pf.configs: + if not runs_on_event(cfg.exclude_event_types, event): + continue for build_type in cfg.build_type: entries.append( MatrixEntry( @@ -262,6 +293,14 @@ if __name__ == "__main__": help="Emit the Linux packaging matrix instead of the build/test matrix.", action="store_true", ) + parser.add_argument( + "-e", + "--event", + help="The GitHub event name that triggered the workflow (e.g. 'push', " + "'pull_request'). Configs are filtered by their 'event_type'. If " + "omitted, no filtering is applied.", + default=None, + ) args = parser.parse_args() matrix: list[MatrixEntry] | list[PackagingEntry] = [] @@ -270,12 +309,16 @@ if __name__ == "__main__": matrix = expand_linux_packaging(LinuxFile.load(THIS_DIR / "linux.json")) else: if args.config in ("linux", None): - matrix += expand_linux_matrix(LinuxFile.load(THIS_DIR / "linux.json")) + matrix += expand_linux_matrix( + LinuxFile.load(THIS_DIR / "linux.json"), args.event + ) if args.config in ("macos", None): - matrix += expand_platform_matrix(PlatformFile.load(THIS_DIR / "macos.json")) + matrix += expand_platform_matrix( + PlatformFile.load(THIS_DIR / "macos.json"), args.event + ) if args.config in ("windows", None): matrix += expand_platform_matrix( - PlatformFile.load(THIS_DIR / "windows.json") + PlatformFile.load(THIS_DIR / "windows.json"), args.event ) print(f"matrix={json.dumps({'include': [dataclasses.asdict(e) for e in matrix]})}") diff --git a/.github/scripts/strategy-matrix/linux.json b/.github/scripts/strategy-matrix/linux.json index edacdbde4c..e6c807ac95 100644 --- a/.github/scripts/strategy-matrix/linux.json +++ b/.github/scripts/strategy-matrix/linux.json @@ -41,7 +41,8 @@ "build_type": ["Debug"], "arch": ["amd64"], "suffix": "unity", - "extra_cmake_args": "-Dunity=ON" + "extra_cmake_args": "-Dunity=ON", + "exclude_event_types": ["pull_request"] } ], diff --git a/.github/scripts/strategy-matrix/macos.json b/.github/scripts/strategy-matrix/macos.json index 5b9e32f88e..66d7a55a43 100644 --- a/.github/scripts/strategy-matrix/macos.json +++ b/.github/scripts/strategy-matrix/macos.json @@ -9,7 +9,8 @@ { "build_type": "Debug", "extra_cmake_args": "-DCMAKE_POLICY_VERSION_MINIMUM=3.5", - "build_only": true + "build_only": true, + "exclude_event_types": ["pull_request"] } ] } diff --git a/.github/scripts/strategy-matrix/windows.json b/.github/scripts/strategy-matrix/windows.json index e4678b60db..e25f9ad131 100644 --- a/.github/scripts/strategy-matrix/windows.json +++ b/.github/scripts/strategy-matrix/windows.json @@ -3,6 +3,10 @@ "runner": ["self-hosted", "Windows", "devbox"], "configs": [ { "build_type": "Release" }, - { "build_type": "Debug", "build_only": true } + { + "build_type": "Debug", + "build_only": true, + "exclude_event_types": ["pull_request"] + } ] } diff --git a/.github/workflows/reusable-strategy-matrix.yml b/.github/workflows/reusable-strategy-matrix.yml index ea134b43b2..4518a8ffef 100644 --- a/.github/workflows/reusable-strategy-matrix.yml +++ b/.github/workflows/reusable-strategy-matrix.yml @@ -35,4 +35,5 @@ jobs: id: generate env: GENERATE_CONFIG: ${{ inputs.os != '' && format('--config={0}', inputs.os) || '' }} - run: ./generate.py ${GENERATE_CONFIG} >>"${GITHUB_OUTPUT}" + GENERATE_EVENT: ${{ github.event_name }} + run: ./generate.py ${GENERATE_CONFIG} --event="${GENERATE_EVENT}" >>"${GITHUB_OUTPUT}" From 2f6b466feb716198bf62dacd55b23332dd09e16c Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 10 Jun 2026 19:24:34 +0100 Subject: [PATCH 33/78] ci: Make sanitizer flags lists in the profile, not a string (#7449) --- conan/profiles/sanitizers | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/conan/profiles/sanitizers b/conan/profiles/sanitizers index 4a05fda734..083807ea9e 100644 --- a/conan/profiles/sanitizers +++ b/conan/profiles/sanitizers @@ -52,52 +52,50 @@ include(default) {% endif %} {# Frame pointer required for meaningful stack traces; -O1 for reasonable performance #} -{% set compile_flags = ["-fno-omit-frame-pointer", "-O1"] %} +{% set sanitizer_compiler_flags = ["-fno-omit-frame-pointer", "-O1"] %} {% if compiler == "gcc" %} {# Suppress false positive warnings with GCC #} - {% set _ = compile_flags.append("-Wno-stringop-overflow") %} + {% set _ = sanitizer_compiler_flags.append("-Wno-stringop-overflow") %} {% set relocation_flags = [] %} {% if arch == "x86_64" and enable_asan %} {# Large code model prevents relocation errors in instrumented ASAN binaries #} - {% set _ = compile_flags.append("-mcmodel=large") %} + {% set _ = sanitizer_compiler_flags.append("-mcmodel=large") %} {% set _ = relocation_flags.append("-mcmodel=large") %} {% elif enable_tsan %} {# GCC doesn't support atomic_thread_fence with TSAN; suppress warnings #} - {% set _ = compile_flags.append("-Wno-tsan") %} + {% set _ = sanitizer_compiler_flags.append("-Wno-tsan") %} {% if arch == "x86_64" %} {# Medium code model for TSAN; large is incompatible #} - {% set _ = compile_flags.append("-mcmodel=medium") %} + {% set _ = sanitizer_compiler_flags.append("-mcmodel=medium") %} {% set _ = relocation_flags.append("-mcmodel=medium") %} {% endif %} {% endif %} {% set fsanitize = "-fsanitize=" ~ ",".join(sanitizer_types) %} - {% set _ = compile_flags.append(fsanitize) %} + {% set _ = sanitizer_compiler_flags.append(fsanitize) %} {% set _ = relocation_flags.append(fsanitize) %} - {% set sanitizer_compiler_flags = " ".join(compile_flags) %} - {% set sanitizer_linker_flags = " ".join(relocation_flags) %} + {% set sanitizer_linker_flags = relocation_flags %} {% elif compiler == "clang" or compiler == "apple-clang" %} {% set fsanitize = "-fsanitize=" ~ ",".join(sanitizer_types) %} - {% set _ = compile_flags.append(fsanitize) %} + {% set _ = sanitizer_compiler_flags.append(fsanitize) %} - {% set sanitizer_compiler_flags = " ".join(compile_flags) %} - {% set sanitizer_linker_flags = fsanitize %} + {% set sanitizer_linker_flags = [fsanitize] %} {% endif %} [conf] tools.build:defines+={{defines}} -tools.build:cxxflags+=['{{sanitizer_compiler_flags}}'] -tools.build:sharedlinkflags+=['{{sanitizer_linker_flags}}'] -tools.build:exelinkflags+=['{{sanitizer_linker_flags}}'] +tools.build:cxxflags+={{sanitizer_compiler_flags}} +tools.build:sharedlinkflags+={{sanitizer_linker_flags}} +tools.build:exelinkflags+={{sanitizer_linker_flags}} tools.info.package_id:confs+=["tools.build:cxxflags", "tools.build:exelinkflags", "tools.build:sharedlinkflags", "tools.build:defines"] # &: means "apply only to the consumer/root package" -&:tools.cmake.cmaketoolchain:extra_variables={"SANITIZERS": "{{sanitizers}}", "SANITIZERS_COMPILER_FLAGS": "{{sanitizer_compiler_flags}}", "SANITIZERS_LINKER_FLAGS": "{{sanitizer_linker_flags}}"} +&:tools.cmake.cmaketoolchain:extra_variables={"SANITIZERS": "{{sanitizers}}", "SANITIZERS_COMPILER_FLAGS": "{{sanitizer_compiler_flags | join(' ')}}", "SANITIZERS_LINKER_FLAGS": "{{sanitizer_linker_flags | join(' ')}}"} [options] {% if enable_asan %} From 09c36d066ec6e1ffdcc6b98075c991e202873d5f Mon Sep 17 00:00:00 2001 From: Zhiyuan Wang <96991820+Kassaking7@users.noreply.github.com> Date: Wed, 10 Jun 2026 16:42:41 -0400 Subject: [PATCH 34/78] fix: Correct hybrid offer deletion on credential expiry (#6843) Co-authored-by: Bart --- include/xrpl/protocol/detail/features.macro | 1 + src/libxrpl/tx/paths/OfferStream.cpp | 9 +- src/test/app/PermissionedDEX_test.cpp | 801 ++++++++++++-------- 3 files changed, 475 insertions(+), 336 deletions(-) diff --git a/include/xrpl/protocol/detail/features.macro b/include/xrpl/protocol/detail/features.macro index 2b2f24ba53..d3500ab144 100644 --- a/include/xrpl/protocol/detail/features.macro +++ b/include/xrpl/protocol/detail/features.macro @@ -15,6 +15,7 @@ // Add new amendments to the top of this list. // Keep it sorted in reverse chronological order. +XRPL_FIX (Cleanup3_3_0, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FIX (Cleanup3_2_0, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FEATURE(MPTokensV2, Supported::No, VoteBehavior::DefaultNo) XRPL_FIX (Cleanup3_1_3, Supported::Yes, VoteBehavior::DefaultYes) diff --git a/src/libxrpl/tx/paths/OfferStream.cpp b/src/libxrpl/tx/paths/OfferStream.cpp index b7defb4df8..ecc8416a2b 100644 --- a/src/libxrpl/tx/paths/OfferStream.cpp +++ b/src/libxrpl/tx/paths/OfferStream.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -249,7 +250,13 @@ TOfferStreamBase::step() continue; } - if (entry->isFieldPresent(sfDomainID) && + // Pre-fixCleanup3_3_0: validate domain membership for any book. + // Post-fixCleanup3_3_0: only validate when walking a domain book. + // Hybrid offers carry sfDomainID but also participate in the open + // book; expiry of the owner's domain credential should not evict + // the offer from the open book. + if ((!view_.rules().enabled(fixCleanup3_3_0) || book_.domain.has_value()) && + entry->isFieldPresent(sfDomainID) && !permissioned_dex::offerInDomain( view_, entry->key(), entry->getFieldH256(sfDomainID), j_)) { diff --git a/src/test/app/PermissionedDEX_test.cpp b/src/test/app/PermissionedDEX_test.cpp index d534f20248..99e69ce482 100644 --- a/src/test/app/PermissionedDEX_test.cpp +++ b/src/test/app/PermissionedDEX_test.cpp @@ -185,15 +185,15 @@ class PermissionedDEX_test : public beast::unit_test::Suite // test preflight { Env env(*this, features - featurePermissionedDEX); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - env(offer(bob_, XRP(10), USD(10)), Domain(domainID), Ter(temDISABLED)); + env(offer(bob, XRP(10), USD(10)), Domain(domainID), Ter(temDISABLED)); env.close(); env.enableFeature(featurePermissionedDEX); env.close(); - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); } @@ -214,7 +214,7 @@ class PermissionedDEX_test : public beast::unit_test::Suite // preclaim - someone outside of the domain cannot create domain offer { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); // create devin account who is not part of the domain @@ -223,7 +223,7 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); env.trust(USD(1000), devin); env.close(); - env(pay(gw_, devin, USD(100))); + env(pay(gw, devin, USD(100))); env.close(); env(offer(devin, XRP(10), USD(10)), Domain(domainID), Ter(tecNO_PERMISSION)); @@ -247,7 +247,7 @@ class PermissionedDEX_test : public beast::unit_test::Suite // preclaim - someone with expired cred cannot create domain offer { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); // create devin account who is not part of the domain @@ -256,7 +256,7 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); env.trust(USD(1000), devin); env.close(); - env(pay(gw_, devin, USD(100))); + env(pay(gw, devin, USD(100))); env.close(); auto jv = credentials::create(devin, domainOwner, credType); @@ -282,13 +282,13 @@ class PermissionedDEX_test : public beast::unit_test::Suite // preclaim - cannot create an offer in a non existent domain { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); uint256 const badDomain{ "F10D0CC9A0F9A3CBF585B80BE09A186483668FDBDD39AA7E3370F3649CE134" "E5"}; - env(offer(bob_, XRP(10), USD(10)), Domain(badDomain), Ter(tecNO_PERMISSION)); + env(offer(bob, XRP(10), USD(10)), Domain(badDomain), Ter(tecNO_PERMISSION)); env.close(); } @@ -296,68 +296,68 @@ class PermissionedDEX_test : public beast::unit_test::Suite // domain { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - env(credentials::deleteCred(domainOwner, gw_, domainOwner, credType)); + env(credentials::deleteCred(domainOwner, gw, domainOwner, credType)); env.close(); - auto const bobOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + auto const bobOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, bobOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); } // apply - offer can be created even if takerpays issuer is not in // domain { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - env(credentials::deleteCred(domainOwner, gw_, domainOwner, credType)); + env(credentials::deleteCred(domainOwner, gw, domainOwner, credType)); env.close(); - auto const bobOfferSeq{env.seq(bob_)}; - env(offer(bob_, USD(10), XRP(10)), Domain(domainID)); + auto const bobOfferSeq{env.seq(bob)}; + env(offer(bob, USD(10), XRP(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, bobOfferSeq, USD(10), XRP(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, USD(10), XRP(10), 0, true)); } // apply - two domain offers cross with each other { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - auto const bobOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + auto const bobOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, bobOfferSeq, XRP(10), USD(10), 0, true)); - BEAST_EXPECT(ownerCount(env, bob_) == 3); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(ownerCount(env, bob) == 3); // a non domain offer cannot cross with domain offer - env(offer(carol_, USD(10), XRP(10))); + env(offer(carol, USD(10), XRP(10))); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, bobOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); - auto const aliceOfferSeq{env.seq(alice_)}; - env(offer(alice_, USD(10), XRP(10)), Domain(domainID)); + auto const aliceOfferSeq{env.seq(alice)}; + env(offer(alice, USD(10), XRP(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(!offerExists(env, alice_, aliceOfferSeq)); - BEAST_EXPECT(!offerExists(env, bob_, bobOfferSeq)); - BEAST_EXPECT(ownerCount(env, alice_) == 2); + BEAST_EXPECT(!offerExists(env, alice, aliceOfferSeq)); + BEAST_EXPECT(!offerExists(env, bob, bobOfferSeq)); + BEAST_EXPECT(ownerCount(env, alice) == 2); } // apply - create lots of domain offers { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); std::vector offerSeqs; @@ -365,19 +365,19 @@ class PermissionedDEX_test : public beast::unit_test::Suite for (size_t i = 0; i <= 100; i++) { - auto const bobOfferSeq{env.seq(bob_)}; + auto const bobOfferSeq{env.seq(bob)}; offerSeqs.emplace_back(bobOfferSeq); - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, bobOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); } for (auto const offerSeq : offerSeqs) { - env(offerCancel(bob_, offerSeq)); + env(offerCancel(bob, offerSeq)); env.close(); - BEAST_EXPECT(!offerExists(env, bob_, offerSeq)); + BEAST_EXPECT(!offerExists(env, bob, offerSeq)); } } } @@ -390,10 +390,10 @@ class PermissionedDEX_test : public beast::unit_test::Suite // test preflight - without enabling featurePermissionedDEX amendment { Env env(*this, features - featurePermissionedDEX); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - env(pay(bob_, alice_, USD(10)), + env(pay(bob, alice, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID), @@ -403,10 +403,10 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.enableFeature(featurePermissionedDEX); env.close(); - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); - env(pay(bob_, alice_, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); + env(pay(bob, alice, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); env.close(); } @@ -431,13 +431,13 @@ class PermissionedDEX_test : public beast::unit_test::Suite // preclaim - cannot send payment with non existent domain { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); uint256 const badDomain{ "F10D0CC9A0F9A3CBF585B80BE09A186483668FDBDD39AA7E3370F3649CE134" "E5"}; - env(pay(bob_, alice_, USD(10)), + env(pay(bob, alice, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(badDomain), @@ -448,10 +448,10 @@ class PermissionedDEX_test : public beast::unit_test::Suite // preclaim - payment with non-domain destination fails { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); // create devin account who is not part of the domain @@ -460,11 +460,11 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); env.trust(USD(1000), devin); env.close(); - env(pay(gw_, devin, USD(100))); + env(pay(gw, devin, USD(100))); env.close(); // devin is not part of domain - env(pay(alice_, devin, USD(10)), + env(pay(alice, devin, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID), @@ -476,7 +476,7 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); // devin has not yet accepted cred - env(pay(alice_, devin, USD(10)), + env(pay(alice, devin, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID), @@ -487,17 +487,17 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); // devin can now receive payment after he is in domain - env(pay(alice_, devin, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); + env(pay(alice, devin, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); env.close(); } // preclaim - non-domain sender cannot send payment { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); // create devin account who is not part of the domain @@ -506,11 +506,11 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); env.trust(USD(1000), devin); env.close(); - env(pay(gw_, devin, USD(100))); + env(pay(gw, devin, USD(100))); env.close(); // devin tries to send domain payment - env(pay(devin, alice_, USD(10)), + env(pay(devin, alice, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID), @@ -522,7 +522,7 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); // devin has not yet accepted cred - env(pay(devin, alice_, USD(10)), + env(pay(devin, alice, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID), @@ -533,28 +533,28 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); // devin can now send payment after he is in domain - env(pay(devin, alice_, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); + env(pay(devin, alice, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); env.close(); } // apply - domain owner can always send and receive domain payment { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); // domain owner can always be destination - env(pay(alice_, domainOwner, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); + env(pay(alice, domainOwner, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); env.close(); - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); // domain owner can send - env(pay(domainOwner, alice_, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); + env(pay(domainOwner, alice, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); env.close(); } } @@ -567,22 +567,22 @@ class PermissionedDEX_test : public beast::unit_test::Suite // test domain cross currency payment consuming one offer { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); // create a regular offer without domain - auto const regularOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10))); + auto const regularOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10))); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, regularOfferSeq, XRP(10), USD(10))); + BEAST_EXPECT(checkOffer(env, bob, regularOfferSeq, XRP(10), USD(10))); - auto const regularDirKey = getDefaultOfferDirKey(env, bob_, regularOfferSeq); + auto const regularDirKey = getDefaultOfferDirKey(env, bob, regularOfferSeq); BEAST_EXPECT(regularDirKey); BEAST_EXPECT(checkDirectorySize( env, *regularDirKey, 1)); // NOLINT(bugprone-unchecked-optional-access) // a domain payment cannot consume regular offers - env(pay(alice_, carol_, USD(10)), + env(pay(alice, carol, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID), @@ -590,23 +590,23 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); // create a domain offer - auto const domainOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + auto const domainOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, domainOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, domainOfferSeq, XRP(10), USD(10), 0, true)); - auto const domainDirKey = getDefaultOfferDirKey(env, bob_, domainOfferSeq); + auto const domainDirKey = getDefaultOfferDirKey(env, bob, domainOfferSeq); BEAST_EXPECT(domainDirKey); BEAST_EXPECT(checkDirectorySize( env, *domainDirKey, 1)); // NOLINT(bugprone-unchecked-optional-access) // cross-currency permissioned payment consumed // domain offer instead of regular offer - env(pay(alice_, carol_, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); + env(pay(alice, carol, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(!offerExists(env, bob_, domainOfferSeq)); - BEAST_EXPECT(checkOffer(env, bob_, regularOfferSeq, XRP(10), USD(10))); + BEAST_EXPECT(!offerExists(env, bob, domainOfferSeq)); + BEAST_EXPECT(checkOffer(env, bob, regularOfferSeq, XRP(10), USD(10))); // domain directory is empty BEAST_EXPECT(checkDirectorySize( @@ -618,79 +618,79 @@ class PermissionedDEX_test : public beast::unit_test::Suite // test domain payment consuming two offers in the path { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - auto const eur = gw_["EUR"]; - env.trust(eur(1000), alice_); + auto const eur = gw["EUR"]; + env.trust(eur(1000), alice); env.close(); - env.trust(eur(1000), bob_); + env.trust(eur(1000), bob); env.close(); - env.trust(eur(1000), carol_); + env.trust(eur(1000), carol); env.close(); - env(pay(gw_, bob_, eur(100))); + env(pay(gw, bob, eur(100))); env.close(); // create XRP/USD domain offer - auto const usdOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + auto const usdOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, usdOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); // payment fail because there isn't eur offer - env(pay(alice_, carol_, eur(10)), + env(pay(alice, carol, eur(10)), Path(~USD, ~eur), Sendmax(XRP(10)), Domain(domainID), Ter(tecPATH_PARTIAL)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, usdOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); - // bob_ creates a regular USD/EUR offer - auto const regularOfferSeq{env.seq(bob_)}; - env(offer(bob_, USD(10), eur(10))); + // bob creates a regular USD/EUR offer + auto const regularOfferSeq{env.seq(bob)}; + env(offer(bob, USD(10), eur(10))); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, regularOfferSeq, USD(10), eur(10))); + BEAST_EXPECT(checkOffer(env, bob, regularOfferSeq, USD(10), eur(10))); - // alice_ tries to pay again, but still fails because the regular + // alice tries to pay again, but still fails because the regular // offer cannot be consumed - env(pay(alice_, carol_, eur(10)), + env(pay(alice, carol, eur(10)), Path(~USD, ~eur), Sendmax(XRP(10)), Domain(domainID), Ter(tecPATH_PARTIAL)); env.close(); - // bob_ creates a domain USD/EUR offer - auto const eurOfferSeq{env.seq(bob_)}; - env(offer(bob_, USD(10), eur(10)), Domain(domainID)); + // bob creates a domain USD/EUR offer + auto const eurOfferSeq{env.seq(bob)}; + env(offer(bob, USD(10), eur(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, eurOfferSeq, USD(10), eur(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, eurOfferSeq, USD(10), eur(10), 0, true)); - // alice_ successfully consume two domain offers: xrp/usd and usd/eur - env(pay(alice_, carol_, eur(5)), Sendmax(XRP(5)), Domain(domainID), Path(~USD, ~eur)); + // alice successfully consume two domain offers: xrp/usd and usd/eur + env(pay(alice, carol, eur(5)), Sendmax(XRP(5)), Domain(domainID), Path(~USD, ~eur)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, usdOfferSeq, XRP(5), USD(5), 0, true)); - BEAST_EXPECT(checkOffer(env, bob_, eurOfferSeq, USD(5), eur(5), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(5), USD(5), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, eurOfferSeq, USD(5), eur(5), 0, true)); - // alice_ successfully consume two domain offers and deletes them + // alice successfully consume two domain offers and deletes them // we compute path this time using `paths` - env(pay(alice_, carol_, eur(5)), Sendmax(XRP(5)), Domain(domainID), Paths(XRP)); + env(pay(alice, carol, eur(5)), Sendmax(XRP(5)), Domain(domainID), Paths(XRP)); env.close(); - BEAST_EXPECT(!offerExists(env, bob_, usdOfferSeq)); - BEAST_EXPECT(!offerExists(env, bob_, eurOfferSeq)); + BEAST_EXPECT(!offerExists(env, bob, usdOfferSeq)); + BEAST_EXPECT(!offerExists(env, bob, eurOfferSeq)); // regular offer is not consumed - BEAST_EXPECT(checkOffer(env, bob_, regularOfferSeq, USD(10), eur(10))); + BEAST_EXPECT(checkOffer(env, bob, regularOfferSeq, USD(10), eur(10))); } // domain payment cannot consume offer from another domain { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); // Fund devin and create USD trustline @@ -700,7 +700,7 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); env.trust(USD(1000), devin); env.close(); - env(pay(gw_, devin, USD(100))); + env(pay(gw, devin, USD(100))); env.close(); auto const badCredType = "badCred"; @@ -720,24 +720,24 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); // domain payment can't consume an offer from another domain - env(pay(alice_, carol_, USD(10)), + env(pay(alice, carol, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID), Ter(tecPATH_PARTIAL)); env.close(); - // bob_ creates an offer under the right domain - auto const bobOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + // bob creates an offer under the right domain + auto const bobOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, bobOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); // domain payment now consumes from the right domain - env(pay(alice_, carol_, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); + env(pay(alice, carol, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(!offerExists(env, bob_, bobOfferSeq)); + BEAST_EXPECT(!offerExists(env, bob, bobOfferSeq)); } // sanity check: devin, who is part of the domain but doesn't have a @@ -745,10 +745,10 @@ class PermissionedDEX_test : public beast::unit_test::Suite // offer { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); // fund devin but don't create a USD trustline with gateway @@ -764,14 +764,14 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); // successful payment because offer is consumed - env(pay(devin, alice_, USD(10)), Sendmax(XRP(10)), Domain(domainID)); + env(pay(devin, alice, USD(10)), Sendmax(XRP(10)), Domain(domainID)); env.close(); } // offer becomes unfunded when offer owner's cred expires { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); // create devin account who is not part of the domain @@ -780,7 +780,7 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); env.trust(USD(1000), devin); env.close(); - env(pay(gw_, devin, USD(100))); + env(pay(gw, devin, USD(100))); env.close(); auto jv = credentials::create(devin, domainOwner, credType); @@ -797,7 +797,7 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); // devin's offer can still be consumed while his cred isn't expired - env(pay(alice_, carol_, USD(5)), Path(~USD), Sendmax(XRP(5)), Domain(domainID)); + env(pay(alice, carol, USD(5)), Path(~USD), Sendmax(XRP(5)), Domain(domainID)); env.close(); BEAST_EXPECT(checkOffer(env, devin, offerSeq, XRP(5), USD(5), 0, true)); @@ -805,7 +805,7 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(std::chrono::seconds(20)); // devin's offer is unfunded now due to expired cred - env(pay(alice_, carol_, USD(5)), + env(pay(alice, carol, USD(5)), Path(~USD), Sendmax(XRP(5)), Domain(domainID), @@ -817,30 +817,30 @@ class PermissionedDEX_test : public beast::unit_test::Suite // offer becomes unfunded when offer owner's cred is removed { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - auto const offerSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + auto const offerSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); - // bob_'s offer can still be consumed while his cred exists - env(pay(alice_, carol_, USD(5)), Path(~USD), Sendmax(XRP(5)), Domain(domainID)); + // bob's offer can still be consumed while his cred exists + env(pay(alice, carol, USD(5)), Path(~USD), Sendmax(XRP(5)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, offerSeq, XRP(5), USD(5), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, offerSeq, XRP(5), USD(5), 0, true)); - // remove bob_'s cred - env(credentials::deleteCred(domainOwner, bob_, domainOwner, credType)); + // remove bob's cred + env(credentials::deleteCred(domainOwner, bob, domainOwner, credType)); env.close(); - // bob_'s offer is unfunded now due to expired cred - env(pay(alice_, carol_, USD(5)), + // bob's offer is unfunded now due to expired cred + env(pay(alice, carol, USD(5)), Path(~USD), Sendmax(XRP(5)), Domain(domainID), Ter(tecPATH_PARTIAL)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, offerSeq, XRP(5), USD(5), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, offerSeq, XRP(5), USD(5), 0, true)); } } @@ -853,34 +853,34 @@ class PermissionedDEX_test : public beast::unit_test::Suite // payment. If the domain wishes to control who is allowed to ripple // through, they should set the rippling individually Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - auto const eura = alice_["EUR"]; - auto const eurb = bob_["EUR"]; + auto const eura = alice["EUR"]; + auto const eurb = bob["EUR"]; - env.trust(eura(100), bob_); - env.trust(eurb(100), carol_); + env.trust(eura(100), bob); + env.trust(eurb(100), carol); env.close(); - // remove bob_ from domain - env(credentials::deleteCred(domainOwner, bob_, domainOwner, credType)); + // remove bob from domain + env(credentials::deleteCred(domainOwner, bob, domainOwner, credType)); env.close(); - // alice_ can still ripple through bob_ even though he's not part + // alice can still ripple through bob even though he's not part // of the domain, this is intentional - env(pay(alice_, carol_, eurb(10)), Paths(eura), Domain(domainID)); + env(pay(alice, carol, eurb(10)), Paths(eura), Domain(domainID)); env.close(); - env.require(Balance(bob_, eura(10)), Balance(carol_, eurb(10))); + env.require(Balance(bob, eura(10)), Balance(carol, eurb(10))); - // carol_ sets no ripple on bob_ - env(trust(carol_, bob_["EUR"](0), bob_, tfSetNoRipple)); + // carol sets no ripple on bob + env(trust(carol, bob["EUR"](0), bob, tfSetNoRipple)); env.close(); - // payment no longer works because carol_ has no ripple on bob_ - env(pay(alice_, carol_, eurb(5)), Paths(eura), Domain(domainID), Ter(tecPATH_DRY)); + // payment no longer works because carol has no ripple on bob + env(pay(alice, carol, eurb(5)), Paths(eura), Domain(domainID), Ter(tecPATH_DRY)); env.close(); - env.require(Balance(bob_, eura(10)), Balance(carol_, eurb(10))); + env.require(Balance(bob, eura(10)), Balance(carol, eurb(10))); } void @@ -891,37 +891,37 @@ class PermissionedDEX_test : public beast::unit_test::Suite // whether the issuer is in the domain should NOT affect whether an // offer can be consumed in domain payment Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); // create an xrp/usd offer with usd as takergets - auto const bobOffer1Seq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + auto const bobOffer1Seq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); // create an usd/xrp offer with usd as takerpays - auto const bobOffer2Seq{env.seq(bob_)}; - env(offer(bob_, USD(10), XRP(10)), Domain(domainID), Txflags(tfPassive)); + auto const bobOffer2Seq{env.seq(bob)}; + env(offer(bob, USD(10), XRP(10)), Domain(domainID), Txflags(tfPassive)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, bobOffer1Seq, XRP(10), USD(10), 0, true)); - BEAST_EXPECT(checkOffer(env, bob_, bobOffer2Seq, USD(10), XRP(10), lsfPassive, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOffer1Seq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOffer2Seq, USD(10), XRP(10), lsfPassive, true)); // remove gateway from domain - env(credentials::deleteCred(domainOwner, gw_, domainOwner, credType)); + env(credentials::deleteCred(domainOwner, gw, domainOwner, credType)); env.close(); // payment succeeds even if issuer is not in domain // xrp/usd offer is consumed - env(pay(alice_, carol_, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); + env(pay(alice, carol, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(!offerExists(env, bob_, bobOffer1Seq)); + BEAST_EXPECT(!offerExists(env, bob, bobOffer1Seq)); // payment succeeds even if issuer is not in domain // usd/xrp offer is consumed - env(pay(alice_, carol_, XRP(10)), Path(~XRP), Sendmax(USD(10)), Domain(domainID)); + env(pay(alice, carol, XRP(10)), Path(~XRP), Sendmax(USD(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(!offerExists(env, bob_, bobOffer2Seq)); + BEAST_EXPECT(!offerExists(env, bob, bobOffer2Seq)); } void @@ -932,36 +932,36 @@ class PermissionedDEX_test : public beast::unit_test::Suite // checking that an unfunded offer will be implicitly removed by a // successful payment tx Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - auto const aliceOfferSeq{env.seq(alice_)}; - env(offer(alice_, XRP(100), USD(100)), Domain(domainID)); + auto const aliceOfferSeq{env.seq(alice)}; + env(offer(alice, XRP(100), USD(100)), Domain(domainID)); env.close(); - auto const bobOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(20), USD(20)), Domain(domainID)); + auto const bobOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(20), USD(20)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, bobOfferSeq, XRP(20), USD(20), 0, true)); - BEAST_EXPECT(checkOffer(env, alice_, aliceOfferSeq, XRP(100), USD(100), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(20), USD(20), 0, true)); + BEAST_EXPECT(checkOffer(env, alice, aliceOfferSeq, XRP(100), USD(100), 0, true)); - auto const domainDirKey = getDefaultOfferDirKey(env, bob_, bobOfferSeq); + auto const domainDirKey = getDefaultOfferDirKey(env, bob, bobOfferSeq); BEAST_EXPECT(domainDirKey); BEAST_EXPECT(checkDirectorySize( env, *domainDirKey, 2)); // NOLINT(bugprone-unchecked-optional-access) - // remove alice_ from domain and thus alice_'s offer becomes unfunded - env(credentials::deleteCred(domainOwner, alice_, domainOwner, credType)); + // remove alice from domain and thus alice's offer becomes unfunded + env(credentials::deleteCred(domainOwner, alice, domainOwner, credType)); env.close(); - env(pay(gw_, carol_, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); + env(pay(gw, carol, USD(10)), Path(~USD), Sendmax(XRP(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, bobOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); - // alice_'s unfunded offer is removed implicitly - BEAST_EXPECT(!offerExists(env, alice_, aliceOfferSeq)); + // alice's unfunded offer is removed implicitly + BEAST_EXPECT(!offerExists(env, alice, aliceOfferSeq)); BEAST_EXPECT(checkDirectorySize( env, *domainDirKey, 1)); // NOLINT(bugprone-unchecked-optional-access) } @@ -972,12 +972,12 @@ class PermissionedDEX_test : public beast::unit_test::Suite testcase("AMM not used"); Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - AMM const amm(env, alice_, XRP(10), USD(50)); + AMM const amm(env, alice, XRP(10), USD(50)); // a domain payment isn't able to consume AMM - env(pay(bob_, carol_, USD(5)), + env(pay(bob, carol, USD(5)), Path(~USD), Sendmax(XRP(5)), Domain(domainID), @@ -985,7 +985,7 @@ class PermissionedDEX_test : public beast::unit_test::Suite env.close(); // a non domain payment can use AMM - env(pay(bob_, carol_, USD(5)), Path(~USD), Sendmax(XRP(5))); + env(pay(bob, carol, USD(5)), Path(~USD), Sendmax(XRP(5))); env.close(); // USD amount in AMM is changed @@ -1001,126 +1001,126 @@ class PermissionedDEX_test : public beast::unit_test::Suite // test preflight - invalid hybrid flag { Env env(*this, features - featurePermissionedDEX); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - env(offer(bob_, XRP(10), USD(10)), + env(offer(bob, XRP(10), USD(10)), Domain(domainID), Txflags(tfHybrid), Ter(temDISABLED)); env.close(); - env(offer(bob_, XRP(10), USD(10)), Txflags(tfHybrid), Ter(temINVALID_FLAG)); + env(offer(bob, XRP(10), USD(10)), Txflags(tfHybrid), Ter(temINVALID_FLAG)); env.close(); env.enableFeature(featurePermissionedDEX); env.close(); // hybrid offer must have domainID - env(offer(bob_, XRP(10), USD(10)), Txflags(tfHybrid), Ter(temINVALID_FLAG)); + env(offer(bob, XRP(10), USD(10)), Txflags(tfHybrid), Ter(temINVALID_FLAG)); env.close(); // hybrid offer must have domainID - auto const offerSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10)), Txflags(tfHybrid), Domain(domainID)); + auto const offerSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10)), Txflags(tfHybrid), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, offerSeq, XRP(10), USD(10), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, offerSeq, XRP(10), USD(10), lsfHybrid, true)); } // apply - domain offer can cross with hybrid { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - auto const bobOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10)), Txflags(tfHybrid), Domain(domainID)); + auto const bobOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10)), Txflags(tfHybrid), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, bobOfferSeq, XRP(10), USD(10), lsfHybrid, true)); - BEAST_EXPECT(offerExists(env, bob_, bobOfferSeq)); - BEAST_EXPECT(ownerCount(env, bob_) == 3); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), lsfHybrid, true)); + BEAST_EXPECT(offerExists(env, bob, bobOfferSeq)); + BEAST_EXPECT(ownerCount(env, bob) == 3); - auto const aliceOfferSeq{env.seq(alice_)}; - env(offer(alice_, USD(10), XRP(10)), Domain(domainID)); + auto const aliceOfferSeq{env.seq(alice)}; + env(offer(alice, USD(10), XRP(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(!offerExists(env, alice_, aliceOfferSeq)); - BEAST_EXPECT(!offerExists(env, bob_, bobOfferSeq)); - BEAST_EXPECT(ownerCount(env, alice_) == 2); + BEAST_EXPECT(!offerExists(env, alice, aliceOfferSeq)); + BEAST_EXPECT(!offerExists(env, bob, bobOfferSeq)); + BEAST_EXPECT(ownerCount(env, alice) == 2); } // apply - open offer can cross with hybrid { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - auto const bobOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10)), Txflags(tfHybrid), Domain(domainID)); + auto const bobOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10)), Txflags(tfHybrid), Domain(domainID)); env.close(); - BEAST_EXPECT(offerExists(env, bob_, bobOfferSeq)); - BEAST_EXPECT(ownerCount(env, bob_) == 3); - BEAST_EXPECT(checkOffer(env, bob_, bobOfferSeq, XRP(10), USD(10), lsfHybrid, true)); + BEAST_EXPECT(offerExists(env, bob, bobOfferSeq)); + BEAST_EXPECT(ownerCount(env, bob) == 3); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), lsfHybrid, true)); - auto const aliceOfferSeq{env.seq(alice_)}; - env(offer(alice_, USD(10), XRP(10))); + auto const aliceOfferSeq{env.seq(alice)}; + env(offer(alice, USD(10), XRP(10))); env.close(); - BEAST_EXPECT(!offerExists(env, alice_, aliceOfferSeq)); - BEAST_EXPECT(!offerExists(env, bob_, bobOfferSeq)); - BEAST_EXPECT(ownerCount(env, alice_) == 2); + BEAST_EXPECT(!offerExists(env, alice, aliceOfferSeq)); + BEAST_EXPECT(!offerExists(env, bob, bobOfferSeq)); + BEAST_EXPECT(ownerCount(env, alice) == 2); } // apply - by default, hybrid offer tries to cross with offers in the // domain book { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - auto const bobOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + auto const bobOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, bobOfferSeq, XRP(10), USD(10), 0, true)); - BEAST_EXPECT(ownerCount(env, bob_) == 3); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(ownerCount(env, bob) == 3); // hybrid offer auto crosses with domain offer - auto const aliceOfferSeq{env.seq(alice_)}; - env(offer(alice_, USD(10), XRP(10)), Domain(domainID), Txflags(tfHybrid)); + auto const aliceOfferSeq{env.seq(alice)}; + env(offer(alice, USD(10), XRP(10)), Domain(domainID), Txflags(tfHybrid)); env.close(); - BEAST_EXPECT(!offerExists(env, alice_, aliceOfferSeq)); - BEAST_EXPECT(!offerExists(env, bob_, bobOfferSeq)); - BEAST_EXPECT(ownerCount(env, alice_) == 2); + BEAST_EXPECT(!offerExists(env, alice, aliceOfferSeq)); + BEAST_EXPECT(!offerExists(env, bob, bobOfferSeq)); + BEAST_EXPECT(ownerCount(env, alice) == 2); } // apply - hybrid offer does not automatically cross with open offers // because by default, it only tries to cross domain offers { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - auto const bobOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10))); + auto const bobOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10))); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, bobOfferSeq, XRP(10), USD(10), 0, false)); - BEAST_EXPECT(ownerCount(env, bob_) == 3); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, false)); + BEAST_EXPECT(ownerCount(env, bob) == 3); // hybrid offer auto crosses with domain offer - auto const aliceOfferSeq{env.seq(alice_)}; - env(offer(alice_, USD(10), XRP(10)), Domain(domainID), Txflags(tfHybrid)); + auto const aliceOfferSeq{env.seq(alice)}; + env(offer(alice, USD(10), XRP(10)), Domain(domainID), Txflags(tfHybrid)); env.close(); - BEAST_EXPECT(offerExists(env, alice_, aliceOfferSeq)); - BEAST_EXPECT(offerExists(env, bob_, bobOfferSeq)); - BEAST_EXPECT(checkOffer(env, bob_, bobOfferSeq, XRP(10), USD(10), 0, false)); - BEAST_EXPECT(checkOffer(env, alice_, aliceOfferSeq, USD(10), XRP(10), lsfHybrid, true)); - BEAST_EXPECT(ownerCount(env, alice_) == 3); + BEAST_EXPECT(offerExists(env, alice, aliceOfferSeq)); + BEAST_EXPECT(offerExists(env, bob, bobOfferSeq)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, false)); + BEAST_EXPECT(checkOffer(env, alice, aliceOfferSeq, USD(10), XRP(10), lsfHybrid, true)); + BEAST_EXPECT(ownerCount(env, alice) == 3); } } @@ -1129,58 +1129,97 @@ class PermissionedDEX_test : public beast::unit_test::Suite { testcase("Hybrid invalid offer"); - // bob_ has a hybrid offer and then he is removed from domain. - // in this case, the hybrid offer will be considered as unfunded even in - // a regular payment + // bob has a hybrid offer and then he is removed from the domain. + // Domain payments must not consume the offer; regular open-book + // payments follow the fixCleanup3_3_0 behavior checked below. Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - auto const hybridOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(50), USD(50)), Txflags(tfHybrid), Domain(domainID)); + auto const hybridOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(50), USD(50)), Txflags(tfHybrid), Domain(domainID)); env.close(); - // remove bob_ from domain - env(credentials::deleteCred(domainOwner, bob_, domainOwner, credType)); + // remove bob from domain + env(credentials::deleteCred(domainOwner, bob, domainOwner, credType)); env.close(); - // bob_'s hybrid offer is unfunded and can not be consumed in a domain + // bob's hybrid offer is unfunded and can not be consumed in a domain // payment - env(pay(alice_, carol_, USD(5)), + env(pay(alice, carol, USD(5)), Path(~USD), Sendmax(XRP(5)), Domain(domainID), Ter(tecPATH_PARTIAL)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, hybridOfferSeq, XRP(50), USD(50), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, hybridOfferSeq, XRP(50), USD(50), lsfHybrid, true)); - // bob_'s unfunded hybrid offer can't be consumed even with a regular - // payment - env(pay(alice_, carol_, USD(5)), Path(~USD), Sendmax(XRP(5)), Ter(tecPATH_PARTIAL)); - env.close(); - BEAST_EXPECT(checkOffer(env, bob_, hybridOfferSeq, XRP(50), USD(50), lsfHybrid, true)); + if (features[fixCleanup3_3_0]) + { + // Post-fixCleanup3_3_0: hybrid offer can still be consumed via a regular + // open-book payment even though the domain credential was revoked. + auto const carolBalBefore = env.balance(carol, USD); + env(pay(alice, carol, USD(5)), Path(~USD), Sendmax(XRP(5))); + env.close(); + BEAST_EXPECT(env.balance(carol, USD) - carolBalBefore == USD(5)); + BEAST_EXPECT(checkOffer(env, bob, hybridOfferSeq, XRP(45), USD(45), lsfHybrid, true)); - // create a regular offer - auto const regularOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10))); - env.close(); - BEAST_EXPECT(offerExists(env, bob_, regularOfferSeq)); - BEAST_EXPECT(checkOffer(env, bob_, regularOfferSeq, XRP(10), USD(10))); + // create a regular offer alongside the hybrid one + auto const regularOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10))); + env.close(); + BEAST_EXPECT(checkOffer(env, bob, regularOfferSeq, XRP(10), USD(10))); - auto const sleHybridOffer = env.le(keylet::offer(bob_.id(), hybridOfferSeq)); - BEAST_EXPECT(sleHybridOffer); - auto const openDir = - sleHybridOffer->getFieldArray(sfAdditionalBooks)[0].getFieldH256(sfBookDirectory); - BEAST_EXPECT(checkDirectorySize(env, openDir, 2)); + auto const sleHybridOffer = env.le(keylet::offer(bob.id(), hybridOfferSeq)); + if (!BEAST_EXPECT(sleHybridOffer)) + return; + auto const openDir = + sleHybridOffer->getFieldArray(sfAdditionalBooks)[0].getFieldH256(sfBookDirectory); + // both offers are in the open book directory + BEAST_EXPECT(checkDirectorySize(env, openDir, 2)); - // this normal payment should consume the regular offer and remove the - // unfunded hybrid offer - env(pay(alice_, carol_, USD(5)), Path(~USD), Sendmax(XRP(5))); - env.close(); + // A regular payment crosses the hybrid offer first (FIFO, older + // offer), then stops; the regular offer is untouched. + env(pay(alice, carol, USD(5)), Path(~USD), Sendmax(XRP(5))); + env.close(); - BEAST_EXPECT(!offerExists(env, bob_, hybridOfferSeq)); - BEAST_EXPECT(checkOffer(env, bob_, regularOfferSeq, XRP(5), USD(5))); - BEAST_EXPECT(checkDirectorySize(env, openDir, 1)); + BEAST_EXPECT(checkOffer(env, bob, hybridOfferSeq, XRP(40), USD(40), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, regularOfferSeq, XRP(10), USD(10))); + BEAST_EXPECT(checkDirectorySize(env, openDir, 2)); + } + else + { + // Pre-fixCleanup3_3_0: the open-book traversal + // also runs the offerInDomain eviction check, so the hybrid offer + // is treated as unfunded and the regular payment fails. + env(pay(alice, carol, USD(5)), Path(~USD), Sendmax(XRP(5)), Ter(tecPATH_PARTIAL)); + env.close(); + BEAST_EXPECT(checkOffer(env, bob, hybridOfferSeq, XRP(50), USD(50), lsfHybrid, true)); + + // create a regular offer + auto const regularOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10))); + env.close(); + BEAST_EXPECT(offerExists(env, bob, regularOfferSeq)); + BEAST_EXPECT(checkOffer(env, bob, regularOfferSeq, XRP(10), USD(10))); + + auto const sleHybridOffer = env.le(keylet::offer(bob.id(), hybridOfferSeq)); + if (!BEAST_EXPECT(sleHybridOffer)) + return; + auto const openDir = + sleHybridOffer->getFieldArray(sfAdditionalBooks)[0].getFieldH256(sfBookDirectory); + BEAST_EXPECT(checkDirectorySize(env, openDir, 2)); + + // This payment crosses the regular offer and permanently evicts the + // hybrid offer from the open book (since the payment succeeds, the + // sandbox, including the hybrid eviction, is committed). + env(pay(alice, carol, USD(5)), Path(~USD), Sendmax(XRP(5))); + env.close(); + + BEAST_EXPECT(!offerExists(env, bob, hybridOfferSeq)); + BEAST_EXPECT(checkOffer(env, bob, regularOfferSeq, XRP(5), USD(5))); + BEAST_EXPECT(checkDirectorySize(env, openDir, 1)); + } } void @@ -1191,29 +1230,29 @@ class PermissionedDEX_test : public beast::unit_test::Suite // both non domain and domain payments can consume hybrid offer { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - auto const hybridOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10)), Txflags(tfHybrid), Domain(domainID)); + auto const hybridOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10)), Txflags(tfHybrid), Domain(domainID)); env.close(); - env(pay(alice_, carol_, USD(5)), Path(~USD), Sendmax(XRP(5)), Domain(domainID)); + env(pay(alice, carol, USD(5)), Path(~USD), Sendmax(XRP(5)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, hybridOfferSeq, XRP(5), USD(5), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, hybridOfferSeq, XRP(5), USD(5), lsfHybrid, true)); - // hybrid offer can't be consumed since bob_ is not in domain anymore - env(pay(alice_, carol_, USD(5)), Path(~USD), Sendmax(XRP(5))); + // hybrid offer can't be consumed since bob is not in domain anymore + env(pay(alice, carol, USD(5)), Path(~USD), Sendmax(XRP(5))); env.close(); - BEAST_EXPECT(!offerExists(env, bob_, hybridOfferSeq)); + BEAST_EXPECT(!offerExists(env, bob, hybridOfferSeq)); } // someone from another domain can't cross hybrid if they specified // wrong domainID { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); // Fund accounts @@ -1235,8 +1274,8 @@ class PermissionedDEX_test : public beast::unit_test::Suite env(credentials::accept(devin, badDomainOwner, badCredType)); env.close(); - auto const hybridOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10)), Txflags(tfHybrid), Domain(domainID)); + auto const hybridOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10)), Txflags(tfHybrid), Domain(domainID)); env.close(); // other domains can't consume the offer @@ -1246,107 +1285,197 @@ class PermissionedDEX_test : public beast::unit_test::Suite Domain(badDomainID), Ter(tecPATH_DRY)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, hybridOfferSeq, XRP(10), USD(10), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, hybridOfferSeq, XRP(10), USD(10), lsfHybrid, true)); - env(pay(alice_, carol_, USD(5)), Path(~USD), Sendmax(XRP(5)), Domain(domainID)); + env(pay(alice, carol, USD(5)), Path(~USD), Sendmax(XRP(5)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, hybridOfferSeq, XRP(5), USD(5), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, hybridOfferSeq, XRP(5), USD(5), lsfHybrid, true)); - // hybrid offer can't be consumed since bob_ is not in domain anymore - env(pay(alice_, carol_, USD(5)), Path(~USD), Sendmax(XRP(5))); + // hybrid offer can't be consumed since bob is not in domain anymore + env(pay(alice, carol, USD(5)), Path(~USD), Sendmax(XRP(5))); env.close(); - BEAST_EXPECT(!offerExists(env, bob_, hybridOfferSeq)); + BEAST_EXPECT(!offerExists(env, bob, hybridOfferSeq)); } // test domain payment consuming two offers w/ hybrid offer { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - auto const eur = gw_["EUR"]; - env.trust(eur(1000), alice_); + auto const eur = gw["EUR"]; + env.trust(eur(1000), alice); env.close(); - env.trust(eur(1000), bob_); + env.trust(eur(1000), bob); env.close(); - env.trust(eur(1000), carol_); + env.trust(eur(1000), carol); env.close(); - env(pay(gw_, bob_, eur(100))); + env(pay(gw, bob, eur(100))); env.close(); - auto const usdOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10)), Domain(domainID)); + auto const usdOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, usdOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); // payment fail because there isn't eur offer - env(pay(alice_, carol_, eur(5)), + env(pay(alice, carol, eur(5)), Path(~USD, ~eur), Sendmax(XRP(5)), Domain(domainID), Ter(tecPATH_PARTIAL)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, usdOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); - // bob_ creates a hybrid eur offer - auto const eurOfferSeq{env.seq(bob_)}; - env(offer(bob_, USD(10), eur(10)), Domain(domainID), Txflags(tfHybrid)); + // bob creates a hybrid eur offer + auto const eurOfferSeq{env.seq(bob)}; + env(offer(bob, USD(10), eur(10)), Domain(domainID), Txflags(tfHybrid)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, eurOfferSeq, USD(10), eur(10), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, eurOfferSeq, USD(10), eur(10), lsfHybrid, true)); - // alice_ successfully consume two domain offers: xrp/usd and usd/eur - env(pay(alice_, carol_, eur(5)), Path(~USD, ~eur), Sendmax(XRP(5)), Domain(domainID)); + // alice successfully consume two domain offers: xrp/usd and usd/eur + env(pay(alice, carol, eur(5)), Path(~USD, ~eur), Sendmax(XRP(5)), Domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, usdOfferSeq, XRP(5), USD(5), 0, true)); - BEAST_EXPECT(checkOffer(env, bob_, eurOfferSeq, USD(5), eur(5), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(5), USD(5), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, eurOfferSeq, USD(5), eur(5), lsfHybrid, true)); } // test regular payment using a regular offer and a hybrid offer { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - auto const eur = gw_["EUR"]; - env.trust(eur(1000), alice_); + auto const eur = gw["EUR"]; + env.trust(eur(1000), alice); env.close(); - env.trust(eur(1000), bob_); + env.trust(eur(1000), bob); env.close(); - env.trust(eur(1000), carol_); + env.trust(eur(1000), carol); env.close(); - env(pay(gw_, bob_, eur(100))); + env(pay(gw, bob, eur(100))); env.close(); - // bob_ creates a regular usd offer - auto const usdOfferSeq{env.seq(bob_)}; - env(offer(bob_, XRP(10), USD(10))); + // bob creates a regular usd offer + auto const usdOfferSeq{env.seq(bob)}; + env(offer(bob, XRP(10), USD(10))); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, usdOfferSeq, XRP(10), USD(10), 0, false)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, false)); - // bob_ creates a hybrid eur offer - auto const eurOfferSeq{env.seq(bob_)}; - env(offer(bob_, USD(10), eur(10)), Domain(domainID), Txflags(tfHybrid)); + // bob creates a hybrid eur offer + auto const eurOfferSeq{env.seq(bob)}; + env(offer(bob, USD(10), eur(10)), Domain(domainID), Txflags(tfHybrid)); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, eurOfferSeq, USD(10), eur(10), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, eurOfferSeq, USD(10), eur(10), lsfHybrid, true)); - // alice_ successfully consume two offers: xrp/usd and usd/eur - env(pay(alice_, carol_, eur(5)), Path(~USD, ~eur), Sendmax(XRP(5))); + // alice successfully consume two offers: xrp/usd and usd/eur + env(pay(alice, carol, eur(5)), Path(~USD, ~eur), Sendmax(XRP(5))); env.close(); - BEAST_EXPECT(checkOffer(env, bob_, usdOfferSeq, XRP(5), USD(5), 0, false)); - BEAST_EXPECT(checkOffer(env, bob_, eurOfferSeq, USD(5), eur(5), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(5), USD(5), 0, false)); + BEAST_EXPECT(checkOffer(env, bob, eurOfferSeq, USD(5), eur(5), lsfHybrid, true)); } } + // Test that a hybrid offer remains crossable in the open book after the + // owner's domain credential expires. A domain payment after expiry should + // fail (domain book evicts the offer in its sandbox), but the open book + // remains usable. + void + testHybridOpenBookAfterCredentialExpiry(FeatureBitset features) + { + testcase("Hybrid open book after credential expiry"); + + Env env(*this, features); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); + + Account const devin("devin"); + env.fund(XRP(100000), devin); + env.close(); + env.trust(USD(1000), devin); + env.close(); + env(pay(gw, devin, USD(100))); + env.close(); + + // Give devin a credential that expires far enough in the future to + // survive the setup env.close() calls. + auto jv = credentials::create(devin, domainOwner, credType); + uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count(); + jv[sfExpiration.jsonName] = t + 100; + env(jv); + env.close(); + env(credentials::accept(devin, domainOwner, credType)); + env.close(); + + // Devin creates a hybrid offer: sell USD(10) for XRP(10). + // The offer is placed in both the domain book and the open book. + auto const hybridOfferSeq{env.seq(devin)}; + env(offer(devin, XRP(10), USD(10)), Txflags(tfHybrid), Domain(domainID)); + env.close(); + + BEAST_EXPECT(checkOffer(env, devin, hybridOfferSeq, XRP(10), USD(10), lsfHybrid, true)); + + // A non-domain open-book payment partially crosses the offer while + // devin's credential is still valid. + auto carolBalance = env.balance(carol, USD); + env(pay(alice, carol, USD(5)), Path(~USD), Sendmax(XRP(5))); + env.close(); + BEAST_EXPECT(env.balance(carol, USD) - carolBalance == USD(5)); + BEAST_EXPECT(checkOffer(env, devin, hybridOfferSeq, XRP(5), USD(5), lsfHybrid, true)); + + // Advance time so that devin's credential expires. + env.close(std::chrono::seconds(100)); + + // Confirm devin can no longer create domain offers. + env(offer(devin, XRP(1), USD(1)), Domain(domainID), Ter(tecNO_PERMISSION)); + env.close(); + + // The hybrid offer must still exist in the open book after expiry. + BEAST_EXPECT(offerExists(env, devin, hybridOfferSeq)); + + // A non-domain open-book payment must cross (not evict) the + // remaining portion of devin's hybrid offer. + carolBalance = env.balance(carol, USD); + env(pay(alice, carol, USD(2)), Path(~USD), Sendmax(XRP(2))); + env.close(); + + // Carol received USD; the offer was crossed, not evicted. + BEAST_EXPECT(env.balance(carol, USD) - carolBalance == USD(2)); + // Offer still exists with 3 USD / 3 XRP remaining. + BEAST_EXPECT(checkOffer(env, devin, hybridOfferSeq, XRP(3), USD(3), lsfHybrid, true)); + + // A domain payment now fails because the domain book evicts devin's + // offer (his credential has expired). The eviction is rolled back with + // the failed sandbox, so the offer is NOT permanently removed. + env(pay(alice, carol, USD(1)), + Path(~USD), + Sendmax(XRP(1)), + Domain(domainID), + Ter(tecPATH_PARTIAL)); + env.close(); + + // Offer still intact in the open book; domain payment did not + // permanently delete it. + BEAST_EXPECT(checkOffer(env, devin, hybridOfferSeq, XRP(3), USD(3), lsfHybrid, true)); + + // The open book can still fully consume the remaining portion. + carolBalance = env.balance(carol, USD); + env(pay(alice, carol, USD(3)), Path(~USD), Sendmax(XRP(3))); + env.close(); + BEAST_EXPECT(env.balance(carol, USD) - carolBalance == USD(3)); + BEAST_EXPECT(!offerExists(env, devin, hybridOfferSeq)); + } + void testHybridOfferDirectories(FeatureBitset features) { Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); std::vector offerSeqs; @@ -1362,12 +1491,12 @@ class PermissionedDEX_test : public beast::unit_test::Suite for (size_t i = 1; i <= dirCnt; i++) { - auto const bobOfferSeq{env.seq(bob_)}; + auto const bobOfferSeq{env.seq(bob)}; offerSeqs.emplace_back(bobOfferSeq); - env(offer(bob_, XRP(10), USD(10)), Txflags(tfHybrid), Domain(domainID)); + env(offer(bob, XRP(10), USD(10)), Txflags(tfHybrid), Domain(domainID)); env.close(); - auto const sleOffer = env.le(keylet::offer(bob_.id(), bobOfferSeq)); + auto const sleOffer = env.le(keylet::offer(bob.id(), bobOfferSeq)); BEAST_EXPECT(sleOffer); BEAST_EXPECT(sleOffer->getFieldH256(sfBookDirectory) == domainDir); BEAST_EXPECT(sleOffer->getFieldArray(sfAdditionalBooks).size() == 1); @@ -1375,17 +1504,17 @@ class PermissionedDEX_test : public beast::unit_test::Suite sleOffer->getFieldArray(sfAdditionalBooks)[0].getFieldH256(sfBookDirectory) == openDir); - BEAST_EXPECT(checkOffer(env, bob_, bobOfferSeq, XRP(10), USD(10), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), lsfHybrid, true)); BEAST_EXPECT(checkDirectorySize(env, domainDir, i)); BEAST_EXPECT(checkDirectorySize(env, openDir, i)); } for (auto const offerSeq : offerSeqs) { - env(offerCancel(bob_, offerSeq)); + env(offerCancel(bob, offerSeq)); env.close(); dirCnt--; - BEAST_EXPECT(!offerExists(env, bob_, offerSeq)); + BEAST_EXPECT(!offerExists(env, bob, offerSeq)); BEAST_EXPECT(checkDirectorySize(env, domainDir, dirCnt)); BEAST_EXPECT(checkDirectorySize(env, openDir, dirCnt)); } @@ -1397,34 +1526,34 @@ class PermissionedDEX_test : public beast::unit_test::Suite testcase("Auto bridge"); Env env(*this, features); - auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - auto const eur = gw_["EUR"]; + auto const eur = gw["EUR"]; - for (auto const& account : {alice_, bob_, carol_}) + for (auto const& account : {alice, bob, carol}) { env(trust(account, eur(10000))); env.close(); } - env(pay(gw_, carol_, eur(1))); + env(pay(gw, carol, eur(1))); env.close(); - auto const aliceOfferSeq{env.seq(alice_)}; - auto const bobOfferSeq{env.seq(bob_)}; - env(offer(alice_, XRP(100), USD(1)), Domain(domainID)); - env(offer(bob_, eur(1), XRP(100)), Domain(domainID)); + auto const aliceOfferSeq{env.seq(alice)}; + auto const bobOfferSeq{env.seq(bob)}; + env(offer(alice, XRP(100), USD(1)), Domain(domainID)); + env(offer(bob, eur(1), XRP(100)), Domain(domainID)); env.close(); - // carol_'s offer should cross bob_ and alice_'s offers due to auto + // carol's offer should cross bob and alice's offers due to auto // bridging - auto const carolOfferSeq{env.seq(carol_)}; - env(offer(carol_, USD(1), eur(1)), Domain(domainID)); + auto const carolOfferSeq{env.seq(carol)}; + env(offer(carol, USD(1), eur(1)), Domain(domainID)); env.close(); - BEAST_EXPECT(!offerExists(env, bob_, aliceOfferSeq)); - BEAST_EXPECT(!offerExists(env, bob_, bobOfferSeq)); - BEAST_EXPECT(!offerExists(env, bob_, carolOfferSeq)); + BEAST_EXPECT(!offerExists(env, bob, aliceOfferSeq)); + BEAST_EXPECT(!offerExists(env, bob, bobOfferSeq)); + BEAST_EXPECT(!offerExists(env, bob, carolOfferSeq)); } void @@ -1819,7 +1948,9 @@ public: // Test hybrid offers testHybridOfferCreate(all); testHybridBookStep(all); + testHybridInvalidOffer(all - fixCleanup3_3_0); testHybridInvalidOffer(all); + testHybridOpenBookAfterCredentialExpiry(all); testHybridOfferDirectories(all); testHybridMalformedOffer(all); testHybridMalformedOffer(all - fixCleanup3_1_3); From cee157485e1e08181a37afc579bdd6f8fabf263e Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Thu, 11 Jun 2026 13:59:22 +0100 Subject: [PATCH 35/78] ci: Run sanitizers on release builds too (#7527) --- .github/scripts/strategy-matrix/linux.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/scripts/strategy-matrix/linux.json b/.github/scripts/strategy-matrix/linux.json index e6c807ac95..4f45216cda 100644 --- a/.github/scripts/strategy-matrix/linux.json +++ b/.github/scripts/strategy-matrix/linux.json @@ -10,7 +10,7 @@ { "compiler": ["gcc", "clang"], - "build_type": ["Debug"], + "build_type": ["Debug", "Release"], "arch": ["amd64"], "sanitizers": ["address", "undefinedbehavior"] }, From 8e618d68cd254d44b40bb41ce588d58b8b34c2c3 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Thu, 11 Jun 2026 18:36:33 +0100 Subject: [PATCH 36/78] ci: Patch conan recipe for Nix to be able to use on macOS (#7532) --- cspell.config.yaml | 2 ++ nix/devshell.nix | 22 +++++++++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/cspell.config.yaml b/cspell.config.yaml index 926ac06596..77f0e9df7a 100644 --- a/cspell.config.yaml +++ b/cspell.config.yaml @@ -233,8 +233,10 @@ words: - pyenv - pyparsing - qalloc + - qbsprofile - queuable - Raphson + - rcflags - replayer - rerere - retriable diff --git a/nix/devshell.nix b/nix/devshell.nix index 1bd7ea4c0c..105033eb06 100644 --- a/nix/devshell.nix +++ b/nix/devshell.nix @@ -1,6 +1,26 @@ { pkgs, ... }: let - inherit (import ./packages.nix { inherit pkgs; }) commonPackages; + # conan is in the binary cache for Linux but not for Darwin, so on Darwin + # it is always built from source — and its bundled test suite is unreliable + # in the sandbox: `test_qbsprofile_rcflags` needs gcc (absent on Darwin, see + # https://github.com/NixOS/nixpkgs/pull/528995) and the patch tests are + # flaky from source. We only use conan as a build tool, so skip its tests on + # Darwin. Scoped to the dev shell (not the CI env, which builds conan on + # Linux from the cache). Drop once the fix reaches nixos-unstable and the + # lock is bumped. + pkgs_patched = + if pkgs.stdenv.isDarwin then + pkgs.extend ( + final: prev: { + conan = prev.conan.overridePythonAttrs (_: { + doCheck = false; + }); + } + ) + else + pkgs; + + inherit (import ./packages.nix { pkgs = pkgs_patched; }) commonPackages; # Supported compiler versions gccVersion = pkgs.lib.range 13 15; From df395d685159717c1725219232b9a9b3b8dc45da Mon Sep 17 00:00:00 2001 From: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Date: Thu, 11 Jun 2026 19:05:36 +0100 Subject: [PATCH 37/78] test: Add null check unit test for `Oracle::aggregatePrice` (#7306) Signed-off-by: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> --- src/test/rpc/GetAggregatePrice_test.cpp | 89 +++++++++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/src/test/rpc/GetAggregatePrice_test.cpp b/src/test/rpc/GetAggregatePrice_test.cpp index 37ecc54172..214bd12183 100644 --- a/src/test/rpc/GetAggregatePrice_test.cpp +++ b/src/test/rpc/GetAggregatePrice_test.cpp @@ -3,12 +3,21 @@ #include #include +#include + #include +#include #include +#include +#include +#include #include +#include +#include #include #include +#include #include #include #include @@ -312,11 +321,91 @@ public: } } + void + testNullTxReadMeta() + { + testcase("Null txRead metadata"); + using namespace jtx; + + // Verify that iteratePriceData handles a null txRead result + // gracefully (returns early) rather than crashing with a + // nullptr dereference. This simulates local data corruption + // where a transaction referenced by sfPreviousTxnID is missing + // from the ledger's transaction map. + Env env(*this); + auto const baseFee = static_cast(env.current()->fees().base.drops()); + + Account const owner{"owner"}; + env.fund(XRP(1'000), owner); + + // Create oracle with XRP/USD and XRP/EUR + Oracle oracle( + env, + {.owner = owner, + .series = {{"XRP", "USD", 740, 1}, {"XRP", "EUR", 840, 1}}, + .fee = baseFee}); + + // Update oracle to only have XRP/EUR, pushing XRP/USD into + // history. iteratePriceData will need to read historical tx + // metadata to find the XRP/USD price. + oracle.set(UpdateArg{.series = {{"XRP", "EUR", 850, 1}}, .fee = baseFee}); + + OraclesData const oracles{{owner, oracle.documentID()}}; + + // Precondition: with an uncorrupted oracle, the historical + // traversal must succeed and produce a price for XRP/USD. + // This proves the test reaches iteratePriceData's history + // path; without it, a future change that breaks the setup + // could turn the post-corruption assertion into a vacuous + // pass (objectNotFound is reachable from many unrelated + // code paths). + { + auto const ret = Oracle::aggregatePrice(env, "XRP", "USD", oracles); + BEAST_EXPECT(!ret.isMember(jss::error)); + BEAST_EXPECT(ret.isMember(jss::median)); + } + + // Simulate data corruption: modify the oracle SLE in the open + // ledger to have a bogus sfPreviousTxnID that doesn't exist in + // any ledger. sfPreviousTxnLgrSeq still points to a valid closed + // ledger, so getLedgerBySeq succeeds but txRead returns null. + auto const oracleKeylet = keylet::oracle(owner, oracle.documentID()); + uint256 const bogusTxnID{0xABCABCAB}; + bool const modified = env.app().getOpenLedger().modify( + [&oracleKeylet, &bogusTxnID](OpenView& view, beast::Journal) -> bool { + auto const sle = view.read(oracleKeylet); + if (!sle) + return false; + auto replacement = std::make_shared(*sle, sle->key()); + replacement->setFieldH256(sfPreviousTxnID, bogusTxnID); + view.rawReplace(replacement); + return true; + }); + + // Confirm the injection actually took effect: modify must + // report success, and re-reading the SLE must show the + // bogus hash. Otherwise the failure-mode assertion below + // would not be exercising the null-txRead path at all. + BEAST_EXPECT(modified); + if (auto const sle = env.current()->read(oracleKeylet); BEAST_EXPECT(sle)) + BEAST_EXPECT(sle->getFieldH256(sfPreviousTxnID) == bogusTxnID); + + // Query for XRP/USD using the "current" (open) ledger. + // The oracle SLE now has a bogus sfPreviousTxnID. The current + // oracle only has EUR, so iteratePriceData will try to read + // history. txRead returns null for the bogus hash, and the + // null check should cause a graceful early return instead of + // a nullptr dereference. + auto const ret = Oracle::aggregatePrice(env, "XRP", "USD", oracles); + BEAST_EXPECT(ret[jss::error].asString() == "objectNotFound"); + } + void run() override { testErrors(); testRpc(); + testNullTxReadMeta(); } }; From 4387aac1a5275ad987412b63b61e7aed2ef93e1a Mon Sep 17 00:00:00 2001 From: Sergey Kuznetsov Date: Mon, 15 Jun 2026 15:55:43 +0100 Subject: [PATCH 38/78] chore: Remove conan patch in nix (#7534) --- flake.lock | 13 +++++++------ flake.nix | 2 +- nix/devshell.nix | 22 +--------------------- 3 files changed, 9 insertions(+), 28 deletions(-) diff --git a/flake.lock b/flake.lock index f8553af703..80243ccf15 100644 --- a/flake.lock +++ b/flake.lock @@ -2,17 +2,18 @@ "nodes": { "nixpkgs": { "locked": { - "lastModified": 1780749050, - "narHash": "sha256-3av0pIjlOWQ6rDbNOmpUSvbNnJkGORQKKjb4LtCZsIY=", + "lastModified": 1781173989, + "narHash": "sha256-fnzKKPvS+oieI/pTzotA5tkoM47EB1NpaBcgk4R97hE=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "a799d3e3886da994fa307f817a6bc705ae538eeb", + "rev": "8c91a71d13451abc40eb9dae8910f972f979852f", "type": "github" }, "original": { - "id": "nixpkgs", - "ref": "nixos-unstable", - "type": "indirect" + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" } }, "nixpkgs-custom-glibc": { diff --git a/flake.nix b/flake.nix index 3b3ec7ea08..c52f4d050e 100644 --- a/flake.nix +++ b/flake.nix @@ -1,7 +1,7 @@ { description = "Nix related things for xrpld"; inputs = { - nixpkgs.url = "nixpkgs/nixos-unstable"; + nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; # nixpkgs snapshot (2020-06-30) that shipped glibc 2.31 as the primary # version — matches the system libc on Ubuntu 20.04 LTS. Imported # manually (flake = false) because this revision predates nixpkgs' diff --git a/nix/devshell.nix b/nix/devshell.nix index 105033eb06..1bd7ea4c0c 100644 --- a/nix/devshell.nix +++ b/nix/devshell.nix @@ -1,26 +1,6 @@ { pkgs, ... }: let - # conan is in the binary cache for Linux but not for Darwin, so on Darwin - # it is always built from source — and its bundled test suite is unreliable - # in the sandbox: `test_qbsprofile_rcflags` needs gcc (absent on Darwin, see - # https://github.com/NixOS/nixpkgs/pull/528995) and the patch tests are - # flaky from source. We only use conan as a build tool, so skip its tests on - # Darwin. Scoped to the dev shell (not the CI env, which builds conan on - # Linux from the cache). Drop once the fix reaches nixos-unstable and the - # lock is bumped. - pkgs_patched = - if pkgs.stdenv.isDarwin then - pkgs.extend ( - final: prev: { - conan = prev.conan.overridePythonAttrs (_: { - doCheck = false; - }); - } - ) - else - pkgs; - - inherit (import ./packages.nix { pkgs = pkgs_patched; }) commonPackages; + inherit (import ./packages.nix { inherit pkgs; }) commonPackages; # Supported compiler versions gccVersion = pkgs.lib.range 13 15; From f5985e73ecce0de85eae73e54405d62fa16a091b Mon Sep 17 00:00:00 2001 From: Bart Date: Mon, 15 Jun 2026 10:55:56 -0400 Subject: [PATCH 39/78] fix: Always charge peer on strand (#7422) Co-authored-by: Bart <11445373+bthomee@users.noreply.github.com> --- src/xrpld/overlay/detail/PeerImp.cpp | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 323dc14673..cda576add0 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -58,7 +58,6 @@ #include #include #include -#include #include #include #include @@ -68,6 +67,7 @@ #include #include #include +#include #include #include #include @@ -392,13 +392,15 @@ PeerImp::removeTxQueue(uint256 const& hash) void PeerImp::charge(Resource::Charge const& fee, std::string const& context) { - if ((usage_.charge(fee, context) == Resource::Disposition::Drop) && - usage_.disconnect(pJournal_) && strand_.running_in_this_thread()) - { - // Sever the connection - overlay_.incPeerDisconnectCharges(); - fail("charge: Resources"); - } + dispatch(strand_, [this, self = shared_from_this(), fee, context]() { + if (usage_.charge(fee, context) == Resource::Disposition::Drop && + usage_.disconnect(pJournal_)) + { + // Sever the connection. + overlay_.incPeerDisconnectCharges(); + fail("charge: Resources"); + } + }); } //------------------------------------------------------------------------------ From b34aa84e5aa0ba8741e38f037350677239f9da12 Mon Sep 17 00:00:00 2001 From: Zhiyuan Wang <96991820+Kassaking7@users.noreply.github.com> Date: Mon, 15 Jun 2026 11:31:22 -0400 Subject: [PATCH 40/78] fix: Check Fee-Free Division by Zero in AMMWithdraw singleWithdrawEPrice (#6989) --- .../tx/transactors/dex/AMMWithdraw.cpp | 11 +++++--- src/test/app/AMM_test.cpp | 25 +++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp b/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp index e57f8558ff..d3a6c9c74c 100644 --- a/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp @@ -1091,10 +1091,13 @@ AMMWithdraw::singleWithdrawEPrice( // t = T*(T + A*E*(f - 2))/(T*f - A*E) Number const ae = amountBalance * ePrice; auto const f = getFee(tfee); - auto tokNoRoundCb = [&] { - return lptAMMBalance * (lptAMMBalance + ae * (f - 2)) / (lptAMMBalance * f - ae); - }; - auto tokProdCb = [&] { return (lptAMMBalance + ae * (f - 2)) / (lptAMMBalance * f - ae); }; + auto const denom = lptAMMBalance * f - ae; + // fixCleanup3_3_0: guard against division by zero + // when ePrice == lptAMMBalance*f/amountBalance + if (view.rules().enabled(fixCleanup3_3_0) && denom == beast::kZero) + return {tecAMM_FAILED, STAmount{}}; + auto tokNoRoundCb = [&] { return lptAMMBalance * (lptAMMBalance + ae * (f - 2)) / denom; }; + auto tokProdCb = [&] { return (lptAMMBalance + ae * (f - 2)) / denom; }; auto const tokensAdj = getRoundedLPTokens(view.rules(), tokNoRoundCb, lptAMMBalance, tokProdCb, IsDeposit::No); if (tokensAdj <= beast::kZero) diff --git a/src/test/app/AMM_test.cpp b/src/test/app/AMM_test.cpp index e3a1cc935f..1b54c2aab9 100644 --- a/src/test/app/AMM_test.cpp +++ b/src/test/app/AMM_test.cpp @@ -2229,6 +2229,31 @@ private: ammAlice.withdraw(alice_, XRPAmount{9'999'999'999}); BEAST_EXPECT(ammAlice.expectBalances(XRPAmount{1}, USD(10'000), IOUAmount{100})); }); + + // singleWithdrawEPrice: crafted ePrice = lptAMMBalance*f/amountBalance + // makes the denominator (T*f - A*E) exactly zero. + // Pre-fixCleanup3_3_0: std::overflow_error escapes to the + // transactor backstop and is returned as tefEXCEPTION. + // Post-fixCleanup3_3_0: denominator check returns tecAMM_FAILED. + // + // Pool: USD(100)/EUR(100), baseFee=1000 (1%). + // Alice is the creator so her discounted fee is 100 (0.1%), f=0.001. + // ePrice = lptAMMBalance(100) * f(0.001) / amountBalance(100) = 0.001 + testAMM( + [&](AMM& ammAlice, Env& env) { + auto const err = + env.enabled(fixCleanup3_3_0) ? Ter(tecAMM_FAILED) : Ter(tefEXCEPTION); + ammAlice.withdraw( + WithdrawArg{ + .account = alice_, + .asset1Out = USD(0), + .maxEP = IOUAmount{1, -3}, // ePrice=0.001 → denom=0 + .err = err}); + }, + {{USD(100), EUR(100)}}, + 1000, + std::nullopt, + {all - fixCleanup3_3_0, all}); } void From fe4c8ae82a76ccd853171ce7547a4e1785d0de87 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Mon, 15 Jun 2026 20:04:33 +0100 Subject: [PATCH 41/78] build: Add ClangBuildAnalyzer to Nix (#7538) Co-authored-by: Bart --- nix/docker/check-tools.sh | 1 + nix/packages.nix | 1 + 2 files changed, 2 insertions(+) diff --git a/nix/docker/check-tools.sh b/nix/docker/check-tools.sh index 276e5977ff..a46c2dd997 100755 --- a/nix/docker/check-tools.sh +++ b/nix/docker/check-tools.sh @@ -6,6 +6,7 @@ ccache --version clang --version clang++ --version clang-format --version +ClangBuildAnalyzer --version cmake --version conan --version curl --version diff --git a/nix/packages.nix b/nix/packages.nix index fc4eff679e..5a7f20ec49 100644 --- a/nix/packages.nix +++ b/nix/packages.nix @@ -9,6 +9,7 @@ in { commonPackages = with pkgs; [ ccache + clangbuildanalyzer cmake conan curlMinimal # needed for codecov/codecov-action From 2df96b155061bbd23a6477776ea3af3f0cd26e94 Mon Sep 17 00:00:00 2001 From: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Date: Mon, 15 Jun 2026 20:25:37 +0100 Subject: [PATCH 42/78] fix: Silence UBSan diagnostics in the ubsan build config (#7531) Co-authored-by: Claude Opus 4.8 --- .../workflows/reusable-build-test-config.yml | 35 +++--- .../suppressions/runtime-ubsan-options.txt | 2 +- sanitizers/suppressions/ubsan.supp | 106 +++++++++++++----- src/xrpld/rpc/handlers/ledger/Ledger.cpp | 15 ++- 4 files changed, 112 insertions(+), 46 deletions(-) diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index 8cb5f8c46a..28d317e4dd 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -164,6 +164,27 @@ jobs: ${CMAKE_ARGS} \ .. + # Export the sanitizer options before any instrumented binary runs. The + # protocol code-gen and build steps below invoke instrumented dependency + # tools (protoc, grpc), so setting UBSAN_OPTIONS here lets the UBSan + # suppression list silence their diagnostics too, not just at test time. + # GITHUB_WORKSPACE (not the github.workspace context) is used so the path + # resolves correctly inside the container job. + - name: Set sanitizer options + if: ${{ !inputs.build_only && env.SANITIZERS_ENABLED == 'true' }} + env: + CONFIG_NAME: ${{ inputs.config_name }} + run: | + SUPP="${GITHUB_WORKSPACE}/sanitizers/suppressions" + ASAN_OPTS="include=${SUPP}/runtime-asan-options.txt:suppressions=${SUPP}/asan.supp" + if [[ "${CONFIG_NAME}" == *gcc* ]]; then + ASAN_OPTS="${ASAN_OPTS}:alloc_dealloc_mismatch=0" + fi + echo "ASAN_OPTIONS=${ASAN_OPTS}" >>${GITHUB_ENV} + echo "TSAN_OPTIONS=include=${SUPP}/runtime-tsan-options.txt:suppressions=${SUPP}/tsan.supp" >>${GITHUB_ENV} + echo "UBSAN_OPTIONS=include=${SUPP}/runtime-ubsan-options.txt:suppressions=${SUPP}/ubsan.supp" >>${GITHUB_ENV} + echo "LSAN_OPTIONS=include=${SUPP}/runtime-lsan-options.txt:suppressions=${SUPP}/lsan.supp" >>${GITHUB_ENV} + - name: Check protocol autogen files are up-to-date working-directory: ${{ env.BUILD_DIR }} env: @@ -279,20 +300,6 @@ jobs: run: | ./xrpld --version | grep libvoidstar - - name: Set sanitizer options - if: ${{ !inputs.build_only && env.SANITIZERS_ENABLED == 'true' }} - env: - CONFIG_NAME: ${{ inputs.config_name }} - run: | - ASAN_OPTS="include=${GITHUB_WORKSPACE}/sanitizers/suppressions/runtime-asan-options.txt:suppressions=${GITHUB_WORKSPACE}/sanitizers/suppressions/asan.supp" - if [[ "${CONFIG_NAME}" == *gcc* ]]; then - ASAN_OPTS="${ASAN_OPTS}:alloc_dealloc_mismatch=0" - fi - echo "ASAN_OPTIONS=${ASAN_OPTS}" >>${GITHUB_ENV} - echo "TSAN_OPTIONS=include=${GITHUB_WORKSPACE}/sanitizers/suppressions/runtime-tsan-options.txt:suppressions=${GITHUB_WORKSPACE}/sanitizers/suppressions/tsan.supp" >>${GITHUB_ENV} - echo "UBSAN_OPTIONS=include=${GITHUB_WORKSPACE}/sanitizers/suppressions/runtime-ubsan-options.txt:suppressions=${GITHUB_WORKSPACE}/sanitizers/suppressions/ubsan.supp" >>${GITHUB_ENV} - echo "LSAN_OPTIONS=include=${GITHUB_WORKSPACE}/sanitizers/suppressions/runtime-lsan-options.txt:suppressions=${GITHUB_WORKSPACE}/sanitizers/suppressions/lsan.supp" >>${GITHUB_ENV} - - name: Run the separate tests if: ${{ !inputs.build_only }} working-directory: ${{ runner.os == 'Windows' && format('{0}/{1}', env.BUILD_DIR, inputs.build_type) || env.BUILD_DIR }} diff --git a/sanitizers/suppressions/runtime-ubsan-options.txt b/sanitizers/suppressions/runtime-ubsan-options.txt index fcfccf7bae..4b48efbe08 100644 --- a/sanitizers/suppressions/runtime-ubsan-options.txt +++ b/sanitizers/suppressions/runtime-ubsan-options.txt @@ -1 +1 @@ -halt_on_error=false +halt_on_error=true diff --git a/sanitizers/suppressions/ubsan.supp b/sanitizers/suppressions/ubsan.supp index 88d8e82e33..7e3e02f855 100644 --- a/sanitizers/suppressions/ubsan.supp +++ b/sanitizers/suppressions/ubsan.supp @@ -72,7 +72,7 @@ vptr:boost # Google protobuf - intentional overflows in hash functions undefined:protobuf -unsigned-integer-overflow:google/protobuf/stubs/stringpiece.h +unsigned-integer-overflow:protobuf # gRPC intentional overflows in timer calculations unsigned-integer-overflow:grpc @@ -102,47 +102,103 @@ undefined:nudb # Snappy compression library intentional overflows unsigned-integer-overflow:snappy.cc -# Abseil intentional overflows -unsigned-integer-overflow:absl/strings/numbers.cc -unsigned-integer-overflow:absl/strings/internal/cord_rep_flat.h -unsigned-integer-overflow:absl/base/internal/low_level_alloc.cc -unsigned-integer-overflow:absl/hash/internal/hash.h -unsigned-integer-overflow:absl/container/internal/raw_hash_set.h +# Abseil intentional overflows in hashing, RNG and time arithmetic. +# Matched at library scope (like boost above): the wraparound is by design +# across many absl files (hash mixing, raw_hash_set probing, duration math, +# int128, uniform_int_distribution), so listing individual files just churns. +unsigned-integer-overflow:absl # Standard library intentional overflows unsigned-integer-overflow:basic_string.h +unsigned-integer-overflow:bits/align.h +unsigned-integer-overflow:bits/basic_string.tcc unsigned-integer-overflow:bits/chrono.h unsigned-integer-overflow:bits/random.h unsigned-integer-overflow:bits/random.tcc unsigned-integer-overflow:bits/stl_algobase.h +unsigned-integer-overflow:bits/string_view.tcc unsigned-integer-overflow:bits/uniform_int_dist.h unsigned-integer-overflow:string_view unsigned-integer-overflow:__random/seed_seq.h unsigned-integer-overflow:__charconv/traits.h unsigned-integer-overflow:__chrono/duration.h +# libstdc++ (std::__bit_ceil etc.) negates an unsigned width; is a +# distinct header from the bits/ directory so it needs its own entry. +unsigned-integer-overflow:include/c++/*/bit # ============================================================================= # Rippled code suppressions # ============================================================================= -# Signed integer negation (-value) in amount types. -# INT64_MIN cannot occur in practice due to domain invariants (mantissa ranges -# are well within int64_t bounds), but UBSan flags the pattern as potential -# signed overflow. Narrowed to operator- to avoid suppressing unrelated -# overflows anywhere in a stack trace containing these type names. -signed-integer-overflow:operator-*IOUAmount* -signed-integer-overflow:operator-*XRPAmount* -signed-integer-overflow:operator-*MPTAmount* -signed-integer-overflow:operator-*STAmount* +# These suppressions are keyed by SOURCE FILE, not function name. This UBSan +# build runs without symbol information, so the runtime only knows the +# file:line of each report, never the enclosing function — function-name +# patterns silently never match. Each entry below is therefore scoped to the +# file whose arithmetic is intentional; the comment names the specific +# construct. -# STAmount::operator+ signed addition — operands are bounded by total supply -# (~10^17 for XRP, ~10^18 for MPT) so overflow cannot occur in practice. -signed-integer-overflow:operator+*STAmount* +# STAmount amount-type arithmetic. Unary negation of the mantissa in xrp()/ +# iou()/mpt()/canonicalize() and getInt64Value, plus bounded +/- on amounts: +# INT64_MIN cannot occur because canonicalize() keeps the mantissa well within +# int64_t, and operands are bounded by total supply (~10^17 XRP, ~10^18 MPT). +signed-integer-overflow:protocol/STAmount.cpp -# STAmount::getRate uses unsigned shift and addition -unsigned-integer-overflow:*STAmount*getRate* -# STAmount::serialize uses unsigned bitwise operations -unsigned-integer-overflow:*STAmount*serialize* +# nft::cipheredTaxon uses intentional uint32 wraparound (LCG permutation); +# the helper lives in the generated protocol header nft.h. +unsigned-integer-overflow:protocol/nft.h -# nft::cipheredTaxon uses intentional uint32 wraparound (LCG permutation) -unsigned-integer-overflow:cipheredTaxon +# STPathElement::getHash multiplies/adds accumulators (non-secure, speed-first). +unsigned-integer-overflow:protocol/STPathSet.cpp + +# beast XorShiftEngine PRNG and murmurhash3 mixing wrap by design. +unsigned-integer-overflow:beast/xor_shift_engine.h + +# Number::normalizeToRange multiplies the mantissa by powers of ten; the result +# is intentionally allowed to wrap while searching for the in-range value. +unsigned-integer-overflow:basics/Number.h + +# Counter / sequence arithmetic with intentional unsigned wraparound, each +# guarded by an explicit overflow or domain check at the call site: +# base_uint operator++/-- wrap by definition; +# ApplyView::insertPage ++page is asserted to wrap to 0 (page exhaustion); +# confineOwnerCount documents "overflow is well defined on unsigned"; +# NFTokenMint checks tokenSeq + 1u == 0u; AmendmentTable does (seq - 1) / 256. +unsigned-integer-overflow:basics/base_uint.h +unsigned-integer-overflow:ledger/ApplyView.cpp +unsigned-integer-overflow:ledger/helpers/AccountRootHelpers.cpp +unsigned-integer-overflow:tx/transactors/nft/NFTokenMint.cpp +unsigned-integer-overflow:app/misc/detail/AmendmentTable.cpp + +# Sentinel / bounded subtractions that wrap by design (loop counters, reverse +# iteration, "not found" sentinels, balance math bounded by issuance invariants, +# base58/base64 codec index math, hash-router and role bit math). +unsigned-integer-overflow:shamap/SHAMap.cpp +unsigned-integer-overflow:protocol/Permissions.cpp +unsigned-integer-overflow:protocol/tokens.cpp +unsigned-integer-overflow:basics/base64.cpp +unsigned-integer-overflow:json/json_value.cpp +unsigned-integer-overflow:app/misc/NetworkOPs.cpp +unsigned-integer-overflow:rpc/detail/Role.cpp +unsigned-integer-overflow:tx/transactors/oracle/OracleSet.cpp +unsigned-integer-overflow:ledger/helpers/MPTokenHelpers.cpp +unsigned-integer-overflow:crypto/RFC1751.cpp +unsigned-integer-overflow:tx/paths/detail/StrandFlow.h +unsigned-integer-overflow:protocol/STObject.h + +# GetAggregatePrice negates an unsigned trim count to step a reverse iterator; +# trimCount is bounded by the price set size. +unsigned-integer-overflow:rpc/handlers/orderbook/GetAggregatePrice.cpp + +# Test-only intentional overflow/underflow in fixture and unit-test arithmetic. +unsigned-integer-overflow:tests/libxrpl/basics/RangeSet.cpp +unsigned-integer-overflow:test/app/Batch_test.cpp +unsigned-integer-overflow:test/app/Invariants_test.cpp +unsigned-integer-overflow:test/app/Loan_test.cpp +unsigned-integer-overflow:test/app/NFToken_test.cpp +unsigned-integer-overflow:test/app/OfferMPT_test.cpp +unsigned-integer-overflow:test/app/Offer_test.cpp +unsigned-integer-overflow:test/app/Path_test.cpp +unsigned-integer-overflow:test/jtx/impl/acctdelete.cpp +unsigned-integer-overflow:test/ledger/SkipList_test.cpp +unsigned-integer-overflow:test/rpc/Subscribe_test.cpp +signed-integer-overflow:test/basics/XRPAmount_test.cpp diff --git a/src/xrpld/rpc/handlers/ledger/Ledger.cpp b/src/xrpld/rpc/handlers/ledger/Ledger.cpp index 5938c8c9c5..23a97a5026 100644 --- a/src/xrpld/rpc/handlers/ledger/Ledger.cpp +++ b/src/xrpld/rpc/handlers/ledger/Ledger.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include namespace xrpl { @@ -349,13 +350,15 @@ doLedgerGrpc(RPC::GRPCContext& context) auto end = std::chrono::system_clock::now(); auto duration = std::chrono::duration_cast(end - begin).count() * 1.0; + // Guard the per-item rates: an empty ledger has zero objects and/or zero + // transactions, and dividing by zero is undefined for these doubles. + auto const numObjects = response.ledger_objects().objects_size(); + auto const numTxns = response.transactions_list().transactions_size(); + std::string const msPerObj = numObjects > 0 ? std::to_string(duration / numObjects) : "n/a"; + std::string const msPerTxn = numTxns > 0 ? std::to_string(duration / numTxns) : "n/a"; JLOG(context.j.warn()) << __func__ << " - Extract time = " << duration - << " - num objects = " << response.ledger_objects().objects_size() - << " - num txns = " << response.transactions_list().transactions_size() - << " - ms per obj " - << duration / response.ledger_objects().objects_size() - << " - ms per txn " - << duration / response.transactions_list().transactions_size(); + << " - num objects = " << numObjects << " - num txns = " << numTxns + << " - ms per obj " << msPerObj << " - ms per txn " << msPerTxn; return {response, status}; } From 9650fe8a6ecb8344d134e183ac74c15ac58dcc44 Mon Sep 17 00:00:00 2001 From: Jingchen Date: Tue, 26 May 2026 21:04:01 +0100 Subject: [PATCH 43/78] refactor: Use explicit types to help compiler --- .clang-tidy | 1 + src/xrpld/overlay/detail/PeerImp.cpp | 2 +- src/xrpld/overlay/detail/Tuning.h | 6 ++++-- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index b23d7ccbff..b0da673b13 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -153,6 +153,7 @@ Checks: "-*, readability-use-std-min-max " # --- +# bugprone-narrowing-conversions, # this will break a lot of code but we should enable it in the future because it can eliminate a lot of bugs # 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/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 325f8ba038..324e8e6b87 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -2032,7 +2032,7 @@ PeerImp::checkTracking(std::uint32_t validationSeq) void PeerImp::checkTracking(std::uint32_t seq1, std::uint32_t seq2) { - int const diff = std::max(seq1, seq2) - std::min(seq1, seq2); + std::uint32_t const diff = std::max(seq1, seq2) - std::min(seq1, seq2); if (diff < Tuning::kConvergedLedgerLimit) { diff --git a/src/xrpld/overlay/detail/Tuning.h b/src/xrpld/overlay/detail/Tuning.h index a0f57ec3d7..97ce3f5188 100644 --- a/src/xrpld/overlay/detail/Tuning.h +++ b/src/xrpld/overlay/detail/Tuning.h @@ -1,14 +1,16 @@ #pragma once +#include +#include namespace xrpl::Tuning { /** How many ledgers off a server can be and we will still consider it converged */ -static constexpr auto kConvergedLedgerLimit = 24; +static constexpr std::uint32_t kConvergedLedgerLimit = 24; /** How many ledgers off a server has to be before we consider it diverged */ -static constexpr auto kDivergedLedgerLimit = 128; +static constexpr std::uint32_t kDivergedLedgerLimit = 128; /** The soft cap on the number of ledger entries in a single reply. */ static constexpr auto kSoftMaxReplyNodes = 8192; From 2728e11809b3a62fc5e17af95a8f300364691c67 Mon Sep 17 00:00:00 2001 From: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Date: Wed, 27 May 2026 01:12:30 +0100 Subject: [PATCH 44/78] fix: Set request size limits and differential pricing for get-object-by-hash calls --- src/test/overlay/TMGetObjectByHash_test.cpp | 18 +- src/xrpld/overlay/detail/PeerImp.cpp | 224 +++++++++++++++----- src/xrpld/overlay/detail/PeerImp.h | 67 ++++++ src/xrpld/overlay/detail/Tuning.h | 90 ++++++++ 4 files changed, 346 insertions(+), 53 deletions(-) diff --git a/src/test/overlay/TMGetObjectByHash_test.cpp b/src/test/overlay/TMGetObjectByHash_test.cpp index 961e1b7eb4..e579989181 100644 --- a/src/test/overlay/TMGetObjectByHash_test.cpp +++ b/src/test/overlay/TMGetObjectByHash_test.cpp @@ -100,6 +100,17 @@ class TMGetObjectByHash_test : public beast::unit_test::Suite return lastSentMessage_; } + // Synchronous test access to the JobQueue-dispatched processor. + // The production path runs this on JtLedgerReq; tests need a + // synchronous entry point to inspect the reply via send(). + // PeerImp::processGetObjectByHash is `protected` so the derived + // test subclass can call it directly. + void + runProcessGetObjectByHash(std::shared_ptr const& m) + { + processGetObjectByHash(m); + } + static void resetId() { @@ -179,6 +190,10 @@ class TMGetObjectByHash_test : public beast::unit_test::Suite /** * Test that reply is limited to hardMaxReplyNodes when more objects * are requested than the limit allows. + * + * `onMessage(TMGetObjectByHash)` dispatches the generic-query path + * to the JobQueue, so tests invoke the synchronous processor + * directly via `runProcessGetObjectByHash`. */ void testReplyLimit(size_t const numObjects, int const expectedReplySize) @@ -191,8 +206,7 @@ class TMGetObjectByHash_test : public beast::unit_test::Suite auto peer = createPeer(env); auto request = createRequest(numObjects, env); - // Call the onMessage handler - peer->onMessage(request); + peer->runProcessGetObjectByHash(request); // Verify that a reply was sent auto sentMessage = peer->getLastSentMessage(); diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 324e8e6b87..822ef05304 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -81,6 +82,7 @@ #include #include +#include #include #include #include @@ -393,11 +395,21 @@ void PeerImp::charge(Resource::Charge const& fee, std::string const& context) { if ((usage_.charge(fee, context) == Resource::Disposition::Drop) && - usage_.disconnect(pJournal_) && strand_.running_in_this_thread()) + usage_.disconnect(pJournal_)) { - // Sever the connection - overlay_.incPeerDisconnectCharges(); - fail("charge: Resources"); + // Idempotent: only the first worker to observe Drop counts the + // metric and posts fail(). Without the guard, several queued + // workers can all see Drop before fail() lands on the strand, + // overcounting peerDisconnectsCharges_ and posting duplicate + // shutdowns. fail(std::string const&) self-posts to strand_ + // when invoked off-strand. + bool expected = false; + if (chargeDisconnectFired_.compare_exchange_strong( + expected, true, std::memory_order_acq_rel)) + { + overlay_.incPeerDisconnectCharges(); + fail("charge: Resources"); + } } } @@ -2473,63 +2485,63 @@ PeerImp::onMessage(std::shared_ptr const& m) return; } - protocol::TMGetObjectByHash reply; - - reply.set_query(false); - - reply.set_type(packet.type()); - if (packet.has_ledgerhash()) { if (!stringIsUInt256Sized(packet.ledgerhash())) { - fee_.update(Resource::kFeeMalformedRequest, "ledger hash"); + JLOG(pJournal_.debug()) << "GetObj: malformed ledgerhash from peer " << id_; + fee_.update(Resource::kFeeMalformedRequest, "get object ledger hash"); return; } - - reply.set_ledgerhash(packet.ledgerhash()); } - - fee_.update(Resource::kFeeModerateBurdenPeer, " received a get object by hash request"); - - // This is a very minimal implementation - for (int i = 0; i < packet.objects_size(); ++i) + // Reject oversized requests before touching the NodeStore. + // The legitimate upper bound (InboundLedger::getNeededHashes()) + // is 8 hashes; anything beyond kHardMaxReplyNodes is non-conforming. + if (packet.objects_size() > Tuning::kHardMaxReplyNodes) { - auto const& obj = packet.objects(i); - if (obj.has_hash() && stringIsUInt256Sized(obj.hash())) - { - uint256 const hash = uint256::fromRaw(obj.hash()); - // VFALCO TODO Move this someplace more sensible so we dont - // need to inject the NodeStore interfaces. - std::uint32_t const seq{obj.has_ledgerseq() ? obj.ledgerseq() : 0}; - auto nodeObject{app_.getNodeStore().fetchNodeObject(hash, seq)}; - if (nodeObject) - { - protocol::TMIndexedObject& newObj = *reply.add_objects(); - newObj.set_hash(hash.begin(), hash.size()); - newObj.set_data(&nodeObject->getData().front(), nodeObject->getData().size()); - - if (obj.has_nodeid()) - newObj.set_index(obj.nodeid()); - if (obj.has_ledgerseq()) - newObj.set_ledgerseq(obj.ledgerseq()); - - // Check if by adding this object, reply has reached its - // limit - if (reply.objects_size() >= Tuning::kHardMaxReplyNodes) - { - fee_.update( - Resource::kFeeModerateBurdenPeer, - "Reply limit reached. Truncating reply."); - break; - } - } - } + JLOG(pJournal_.warn()) + << "GetObj: oversized request from peer " << id_ << " (" << packet.objects_size() + << " > " << Tuning::kHardMaxReplyNodes << ")"; + fee_.update(Resource::kFeeInvalidData, "oversized get object request"); + return; } - JLOG(pJournal_.trace()) << "GetObj: " << reply.objects_size() << " of " - << packet.objects_size(); - send(std::make_shared(reply, protocol::mtGET_OBJECTS)); + // Dispatch heavy synchronous NodeStore lookups off the peer's + // I/O strand and onto the bounded job queue, mirroring the pattern + // used by processLedgerRequest. + std::weak_ptr const weak = shared_from_this(); + bool const queued = app_.getJobQueue().addJob(JtLedgerReq, "RcvGetObjByHash", [weak, m]() { + auto peer = weak.lock(); + if (!peer) + return; + try + { + peer->processGetObjectByHash(m); + } + catch (std::exception const& e) + { + // Surface backend failures (NodeStore I/O, allocation) + // back through the resource model so a misbehaving peer + // is still accountable rather than silently dropped. + JLOG(peer->pJournal_.warn()) << "GetObj: handler threw: " << e.what(); + peer->charge(Resource::kFeeRequestNoReply, "get object handler exception"); + } + }); + if (!queued) + { + // The JobQueue is no longer accepting new work (typically + // because it is shutting down / has been joined). + JLOG(pJournal_.warn()) << "GetObj: job queue refused request from peer " << id_; + return; + } + + // Admission-time charge: a peer that floods enqueues would + // otherwise be billed only the trivial onMessageEnd fee per + // message until the JobQueue catches up, re-creating an + // uncharged DoS window. Charge the base burden up-front (after + // a successful enqueue); the per-lookup differential is added + // in the worker. + fee_.update(Resource::kFeeModerateBurdenPeer, "received a get object by hash request"); } else { @@ -2585,6 +2597,69 @@ PeerImp::onMessage(std::shared_ptr const& m) } } +void +PeerImp::processGetObjectByHash(std::shared_ptr const& m) +{ + protocol::TMGetObjectByHash const& packet = *m; + + protocol::TMGetObjectByHash reply; + reply.set_query(false); + reply.set_type(packet.type()); + + if (packet.has_ledgerhash()) + { + reply.set_ledgerhash(packet.ledgerhash()); + } + + // Defense in depth: caller (onMessage) already validates cheap + // structural properties of the request before dispatching here: + // - objects_size() <= kHardMaxReplyNodes (oversize gate) + // - if has_ledgerhash() then ledgerhash is uint256-sized + // The iteration cap below mirrors the oversize gate so this method + // remains safe if invoked directly by tests or future callers, and + // a peer cannot drive unbounded NodeStore lookups by sending + // non-existent hashes. + int const requested = packet.objects_size(); + int const iterLimit = std::min(requested, Tuning::kHardMaxReplyNodes); + + for (int i = 0; i < iterLimit; ++i) + { + auto const& obj = packet.objects(i); + if (!obj.has_hash() || !stringIsUInt256Sized(obj.hash())) + continue; + + uint256 const hash = uint256::fromRaw(obj.hash()); + // VFALCO TODO Move this someplace more sensible so we don't + // need to inject the NodeStore interfaces. + std::uint32_t const seq{obj.has_ledgerseq() ? obj.ledgerseq() : 0}; + auto const nodeObject = app_.getNodeStore().fetchNodeObject(hash, seq); + if (!nodeObject) + continue; + + protocol::TMIndexedObject& newObj = *reply.add_objects(); + newObj.set_hash(hash.begin(), hash.size()); + auto const& data = nodeObject->getData(); + newObj.set_data(data.data(), data.size()); + if (obj.has_nodeid()) + newObj.set_index(obj.nodeid()); + if (obj.has_ledgerseq()) + newObj.set_ledgerseq(obj.ledgerseq()); + } + + // Apply work-proportional charge. `charge()` posts the disconnect + // step (if any) back to strand_, so it is safe to call from this + // JobQueue worker thread. + charge( + // We pass `requested` directly here, instead of actual lookups done. Which could be + // std::min(packet.objects_size(), static_cast(Tuning::kHardMaxReplyNodes)); + // Because we want to charge as per the request size, to discourage large requests. + computeGetObjectByHashFee(requested, reply.objects_size()), + "processed get object by hash request"); + + JLOG(pJournal_.trace()) << "GetObj: " << reply.objects_size() << " of " << requested; + send(std::make_shared(reply, protocol::mtGET_OBJECTS)); +} + void PeerImp::onMessage(std::shared_ptr const& m) { @@ -3412,6 +3487,53 @@ PeerImp::processLedgerRequest(std::shared_ptr const& m) send(std::make_shared(ledgerData, protocol::mtLEDGER_DATA)); } +// Differential pricing helper. Returns only the *dynamic* component +// of the per-message charge — the base `kFeeModerateBurdenPeer` is +// applied at admission time in `onMessage(TMGetObjectByHash)` so a +// high traffic client pays for the message regardless of when (or +// whether) the worker runs. +// +// Dynamic charge model: +// +// billable = max(0, requested - kFreeObjectsPerRequest) +// missed = max(0, requested - found) +// billableMisses = min(missed, billable) // misses billed first +// billableHits = billable - billableMisses +// sizeBand = (requested > kBandMediumMax) ? kCostBandLarge +// : (requested > kBandSmallMax) ? kCostBandMedium +// : kCostBandSmall +// dynamic = billableHits * kCostPerLookupHit +// + billableMisses * kCostPerLookupMiss +// + sizeBand +// +// Misses are billed first against the billable budget because a node store +// seek dominates a cache hit and because invalid hashes are ~100% miss by construction. +Resource::Charge +PeerImp::computeGetObjectByHashFee(int const requested, int const found) +{ + int const billable = std::max(0, requested - static_cast(Tuning::kFreeObjectsPerRequest)); + // Clamp `missed` so a future caller passing found > requested cannot + // produce a negative value that flips the hits/misses split. + int const missed = std::max(0, requested - found); + int const billableMisses = std::min(missed, billable); + int const billableHits = billable - billableMisses; + + int sizeBand = Tuning::kCostBandSmall; + if (requested > Tuning::kBandMediumMax) + { + sizeBand = Tuning::kCostBandLarge; + } + else if (requested > Tuning::kBandSmallMax) + { + sizeBand = Tuning::kCostBandMedium; + } + + int const dynamic = (billableHits * Tuning::kCostPerLookupHit) + + (billableMisses * Tuning::kCostPerLookupMiss) + sizeBand; + + return Resource::Charge(dynamic, "GetObject differential"); +} + int PeerImp::getScore(bool haveItem) const { diff --git a/src/xrpld/overlay/detail/PeerImp.h b/src/xrpld/overlay/detail/PeerImp.h index f5d87371be..26d7e0a832 100644 --- a/src/xrpld/overlay/detail/PeerImp.h +++ b/src/xrpld/overlay/detail/PeerImp.h @@ -147,6 +147,12 @@ private: protocol::TMStatusChange lastStatus_; Resource::Consumer usage_; ChargeWithContext fee_; + + // One-shot guard so concurrent JobQueue workers cannot double-count + // the per-connection peer-disconnect-by-charge metric (and cannot + // post duplicate fail() calls) when several queued requests cross + // kDropThreshold before the first fail() lands on the strand. + std::atomic chargeDisconnectFired_{false}; std::shared_ptr const slot_; boost::beast::multi_buffer readBuffer_; http_request_type request_; @@ -624,6 +630,67 @@ private: void processLedgerRequest(std::shared_ptr const& m); + +protected: + // Kept `protected` so test subclasses (see + // TMGetObjectByHash_test) can drive the + // synchronous processor and the differential-pricing helper without + // routing through the JobQueue or going through `friend` plumbing. + // Production callers reach these members only via + // `onMessage(TMGetObjectByHash)` → JobQueue → `processGetObjectByHash`. + + /** Process a generic-query TMGetObjectByHash message. + + Dispatched from `onMessage(TMGetObjectByHash)` to the JobQueue + (`JtLedgerReq`) so synchronous NodeStore lookups do not block the + peer's I/O strand. Caps iteration at `Tuning::kHardMaxReplyNodes` + regardless of hit/miss outcome and applies differential pricing + via `computeGetObjectByHashFee()` after the fetch loop completes. + + @param m The protocol message containing requested object hashes. + */ + void + processGetObjectByHash(std::shared_ptr const& m); + + /** Compute the per-message resource charge for a TMGetObjectByHash + request based on how much work was actually performed. + + The charge has three components on top of the base + `Resource::kFeeModerateBurdenPeer`: + - per-hit lookup cost (cheap; usually served from cache) + - per-miss lookup cost (expensive node store seeks) + - request-size band surcharge (escalates abusive batch sizes) + + The first `Tuning::kFreeObjectsPerRequest` objects are free so + that legitimate `InboundLedger::getNeededHashes()` traffic + (at most 8 objects) is unaffected. + + @param requested Number of objects requested by the message. This + value is used for request-size pricing and may + exceed `Tuning::kHardMaxReplyNodes` when this + helper is called directly, even though processing + caps the iterations to `Tuning::kHardMaxReplyNodes`. + @param found Number of objects successfully returned in the + reply. + @return A `Resource::Charge` whose cost reflects the work performed. + */ + static Resource::Charge + computeGetObjectByHashFee(int const requested, int const found); + + /** Read-only accessor for the accumulated peer-message charge. + + Exposed at `protected` scope so test subclasses can verify the + oversized-request rejection path (Layer 1) without invoking the + full JobQueue handler. Production callers should never read this back — + the value is consumed by `charge()`/`disconnect()` internally. + + @return The current `Resource::Charge` accumulated on `fee_`. + */ + Resource::Charge + currentFeeCharge() const + { + return fee_.fee; + } }; //------------------------------------------------------------------------------ diff --git a/src/xrpld/overlay/detail/Tuning.h b/src/xrpld/overlay/detail/Tuning.h index 97ce3f5188..20a60d470e 100644 --- a/src/xrpld/overlay/detail/Tuning.h +++ b/src/xrpld/overlay/detail/Tuning.h @@ -1,4 +1,6 @@ #pragma once +#include + #include #include @@ -39,4 +41,92 @@ static constexpr auto kMaxQueryDepth = 3; /** Size of buffer used to read from the socket. */ constexpr std::size_t kReadBufferBytes = 16384; +/** TMGetObjectByHash differential pricing. + + Honest peers ask for at most 8 hashes per call (the header, or up to + 4 state + 4 tx hashes from `InboundLedger::getNeededHashes()`). The + free tier covers them at zero cost. Beyond that, each lookup is billed: + 'misses' cost much more than 'hits' because a miss does a node store seek + while a hit is usually served from cache. On top of that, a size-band + surcharge kicks in for larger requests so an attacker who crams a + single message with thousands of hashes blows past + `Resource::kDropThreshold` and gets disconnected. + + The numbers below are picked to keep three things true given + `kDropThreshold = 25000`: + + - Honest traffic (<= 8 objects per request) is free. + - A single all-miss request at `kHardMaxReplyNodes` (12288) costs + more than the drop threshold, so an attacker gets dropped in one + message. + - A peer spamming 1024-object hit-only requests gets dropped in + ~19 messages — fast enough to be useful, slow enough that an + honest peer momentarily sending oversized requests has time to + back off. */ + +/** How many objects a request can ask for before per-lookup billing + begins? + Twice the honest peak (8) so a peer that occasionally retries a hash + never trips pricing. Same value as `SHAMapInnerNode::kBranchFactor`; + that's a coincidence, not a requirement. */ +static constexpr auto kFreeObjectsPerRequest = 16; + +/** Cost of one cache-hit lookup. The unit; everything else is a + multiple of this. */ +static constexpr auto kCostPerLookupHit = 1; + +/** Cost of one node-store miss, in units of `kCostPerLookupHit`. + + A miss does a node store disk seek; a hit usually comes from cache. + The 8x ratio is an order-of-magnitude guess at the latency gap on + SSD-backed nodes, not a measured number. The math only requires this + to be at least 2 — any smaller and a full-miss request at the hard + cap wouldn't trip the drop threshold. 8 leaves headroom: if + `kDropThreshold` goes up or `kHardMaxReplyNodes` comes down, the + drop-on-attack property still holds without a code change. */ +static constexpr auto kCostPerLookupMiss = 8; + +/** Size-band surcharges. Whichever band a request's size falls into, + its surcharge is added once on top of the per-lookup cost. + + The job of the surcharge is to make crossing a band edge feel like + a step, not a slope. With these values, the cost roughly doubles or triples at each cliff: + + n=64: costs 48 => n=65 costs 149 (~3x jump) + n=1024: costs 1108 => n=1025 costs 2009 (~2x jump) + + The 10x step between medium and large mirrors the ~16x step + between the band edges (64 -> 1024) so the cliff feels comparable + at both scales. + */ +static constexpr auto kCostBandSmall = 0; +static constexpr auto kCostBandMedium = 100; +static constexpr auto kCostBandLarge = 1000; + +/** How many hashes per type an honest peer asks for at a time. + + Matches the `4` passed to `neededStateHashes(4)` and + `neededTxHashes(4)` in `InboundLedger::getNeededHashes()`. Kept here + instead of imported from the ledger module so overlay stays + self-contained; if that `4` ever changes, update this in lockstep or + the band thresholds below will start charging honest peers. */ +static constexpr auto kLegitHashesPerType = 4; + +/** Cutoffs that decide which size band a request falls into. + + A SHAMap inner node has 16 children; an honest peer asks for 4 + hashes per type. So: + + kBandSmallMax = 4 * 16 = 64 // one inner node's worth + kBandMediumMax = 4 * 16^2 = 1024 // a depth-2 subtree's worth + + A request up to 64 objects is small (no surcharge); up to 1024 is + medium; anything larger is large. The bounds are inclusive: a + request of exactly 64 is small, 65 is medium. Anything past 1024 is + well beyond what the honest sync path produces, so it's billed at + the large rate to drive attack-shaped traffic over the drop + threshold quickly. */ +static constexpr auto kBandSmallMax = kLegitHashesPerType * SHAMapInnerNode::kBranchFactor; +static constexpr auto kBandMediumMax = kBandSmallMax * SHAMapInnerNode::kBranchFactor; + } // namespace xrpl::Tuning From e29dc474b3d3eb10bb9ff3407cc378c71800124b Mon Sep 17 00:00:00 2001 From: Sergey Kuznetsov Date: Wed, 27 May 2026 14:42:48 +0100 Subject: [PATCH 45/78] refactor: Improve payment channel closing and returned error codes --- .../ledger/helpers/PaymentChannelHelpers.h | 36 +++++++++++++++++++ .../ledger/helpers/PaymentChannelHelpers.cpp | 30 ++++++++++++++++ .../payment_channel/PaymentChannelClaim.cpp | 28 +++++++++------ .../payment_channel/PaymentChannelFund.cpp | 34 +++++++++++------- src/test/app/PayChan_test.cpp | 5 ++- 5 files changed, 109 insertions(+), 24 deletions(-) diff --git a/include/xrpl/ledger/helpers/PaymentChannelHelpers.h b/include/xrpl/ledger/helpers/PaymentChannelHelpers.h index 24838f1331..4528431028 100644 --- a/include/xrpl/ledger/helpers/PaymentChannelHelpers.h +++ b/include/xrpl/ledger/helpers/PaymentChannelHelpers.h @@ -5,8 +5,21 @@ #include #include +#include +#include +#include + namespace xrpl { +/** Close a payment channel and return its remaining funds to the channel owner. + * + * @param slep The SLE for the PayChannel object to close. + * @param view The apply view in which ledger state modifications are made. + * @param key The ledger key identifying the PayChannel entry. + * @param j Journal used for fatal-level diagnostic messages. + * @return tesSUCCESS on success; tefBAD_LEDGER if a directory removal + * fails; tefINTERNAL if the source account SLE cannot be found. + */ TER closeChannel( std::shared_ptr const& slep, @@ -14,4 +27,27 @@ closeChannel( uint256 const& key, beast::Journal j); +/** Add two uint32_t values with saturation at UINT32_MAX. + * + * @param rules The current ledger rules used to check amendment status. + * @param lhs Left-hand operand. + * @param rhs Right-hand operand. + * @return @p lhs + @p rhs, saturated at UINT32_MAX when the amendment + * is active. + */ +uint32_t +saturatingAdd(Rules const& rules, uint32_t const lhs, uint32_t const rhs); + +/** Determine whether a payment channel time field represents an expired time. + * + * @param view The apply view providing the parent close time and rules. + * @param timeField The optional expiry timestamp (seconds since the XRP + * Ledger epoch). If empty, the function returns false. + * @return @c true if @p timeField is set and the indicated time is + * in the past relative to the view's parent close time; + * @c false otherwise. + */ +bool +isChannelExpired(ApplyView const& view, std::optional timeField); + } // namespace xrpl diff --git a/src/libxrpl/ledger/helpers/PaymentChannelHelpers.cpp b/src/libxrpl/ledger/helpers/PaymentChannelHelpers.cpp index 31c206d85b..ba5ce50989 100644 --- a/src/libxrpl/ledger/helpers/PaymentChannelHelpers.cpp +++ b/src/libxrpl/ledger/helpers/PaymentChannelHelpers.cpp @@ -5,14 +5,20 @@ #include #include #include +#include #include #include +#include #include #include #include #include +#include +#include +#include #include +#include namespace xrpl { @@ -65,4 +71,28 @@ closeChannel( return tesSUCCESS; } +uint32_t +saturatingAdd(Rules const& rules, uint32_t const lhs, uint32_t const rhs) +{ + if (rules.enabled(fixCleanup3_2_0)) + { + static constexpr auto kUint32Max = + static_cast(std::numeric_limits::max()); + uint64_t const saturatedResult = std::min(uint64_t{lhs} + rhs, kUint32Max); + return static_cast(saturatedResult); + } + + return lhs + rhs; +} + +bool +isChannelExpired(ApplyView const& view, std::optional timeField) +{ + if (!timeField) + return false; + if (view.rules().enabled(fixCleanup3_2_0)) + return after(view.header().parentCloseTime, *timeField); + return view.header().parentCloseTime.time_since_epoch().count() >= *timeField; +} + } // namespace xrpl diff --git a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp index cc99b8f62d..6a84d44746 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp @@ -43,6 +43,9 @@ PaymentChannelClaim::getFlagsMask(PreflightContext const&) NotTEC PaymentChannelClaim::preflight(PreflightContext const& ctx) { + if (ctx.rules.enabled(fixCleanup3_2_0) && ctx.tx[sfChannel] == beast::kZero) + return temMALFORMED; + auto const bal = ctx.tx[~sfBalance]; if (bal && (!isXRP(*bal) || *bal <= beast::kZero)) return temBAD_AMOUNT; @@ -117,12 +120,10 @@ PaymentChannelClaim::doApply() AccountID const txAccount = ctx_.tx[sfAccount]; auto const curExpiration = (*slep)[~sfExpiration]; + if (isChannelExpired(ctx_.view(), (*slep)[~sfCancelAfter]) || + isChannelExpired(ctx_.view(), curExpiration)) { - auto const cancelAfter = (*slep)[~sfCancelAfter]; - auto const closeTime = ctx_.view().header().parentCloseTime.time_since_epoch().count(); - if ((cancelAfter && closeTime >= *cancelAfter) || - (curExpiration && closeTime >= *curExpiration)) - return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.get().getJournal("View")); + return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.get().getJournal("View")); } if (txAccount != src && txAccount != dst) @@ -135,13 +136,19 @@ PaymentChannelClaim::doApply() auto const reqBalance = ctx_.tx[sfBalance].xrp(); if (txAccount == dst && !ctx_.tx[~sfSignature]) - return temBAD_SIGNATURE; + { + return ctx_.view().rules().enabled(fixCleanup3_2_0) ? TER{tecNO_PERMISSION} + : TER{temBAD_SIGNATURE}; + } if (ctx_.tx[~sfSignature]) { PublicKey const pk((*slep)[sfPublicKey]); if (ctx_.tx[sfPublicKey] != pk) - return temBAD_SIGNER; + { + return ctx_.view().rules().enabled(fixCleanup3_2_0) ? TER{tecNO_PERMISSION} + : TER{temBAD_SIGNER}; + } } if (reqBalance > chanFunds) @@ -185,9 +192,10 @@ PaymentChannelClaim::doApply() if (dst == txAccount || (*slep)[sfBalance] == (*slep)[sfAmount]) return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.get().getJournal("View")); - auto const settleExpiration = - ctx_.view().header().parentCloseTime.time_since_epoch().count() + - (*slep)[sfSettleDelay]; + auto const settleExpiration = saturatingAdd( + ctx_.view().rules(), + ctx_.view().header().parentCloseTime.time_since_epoch().count(), + (*slep)[sfSettleDelay]); if (!curExpiration || *curExpiration > settleExpiration) { diff --git a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp index 41906aa3da..dcd2797dd1 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +32,9 @@ PaymentChannelFund::makeTxConsequences(PreflightContext const& ctx) NotTEC PaymentChannelFund::preflight(PreflightContext const& ctx) { + if (ctx.rules.enabled(fixCleanup3_2_0) && ctx.tx[sfChannel] == beast::kZero) + return temMALFORMED; + if (!isXRP(ctx.tx[sfAmount]) || (ctx.tx[sfAmount] <= beast::kZero)) return temBAD_AMOUNT; @@ -47,13 +51,12 @@ PaymentChannelFund::doApply() AccountID const src = (*slep)[sfAccount]; auto const txAccount = ctx_.tx[sfAccount]; - auto const expiration = (*slep)[~sfExpiration]; + auto const curExpiration = (*slep)[~sfExpiration]; + if (isChannelExpired(ctx_.view(), (*slep)[~sfCancelAfter]) || + isChannelExpired(ctx_.view(), curExpiration)) { - auto const cancelAfter = (*slep)[~sfCancelAfter]; - auto const closeTime = ctx_.view().header().parentCloseTime.time_since_epoch().count(); - if ((cancelAfter && closeTime >= *cancelAfter) || (expiration && closeTime >= *expiration)) - return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.get().getJournal("View")); + return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.get().getJournal("View")); } if (src != txAccount) @@ -62,16 +65,21 @@ PaymentChannelFund::doApply() return tecNO_PERMISSION; } - if (auto extend = ctx_.tx[~sfExpiration]) + if (auto newExpiration = ctx_.tx[~sfExpiration]) { - auto minExpiration = ctx_.view().header().parentCloseTime.time_since_epoch().count() + - (*slep)[sfSettleDelay]; - if (expiration && *expiration < minExpiration) - minExpiration = *expiration; + auto minExpiration = saturatingAdd( + ctx_.view().rules(), + ctx_.view().header().parentCloseTime.time_since_epoch().count(), + (*slep)[sfSettleDelay]); + if (curExpiration && *curExpiration < minExpiration) + minExpiration = *curExpiration; - if (*extend < minExpiration) - return temBAD_EXPIRATION; - (*slep)[~sfExpiration] = *extend; + if (*newExpiration < minExpiration) + { + return ctx_.view().rules().enabled(fixCleanup3_2_0) ? TER{tecNO_PERMISSION} + : TER{temBAD_EXPIRATION}; + } + (*slep)[~sfExpiration] = *newExpiration; ctx_.view().update(slep); } diff --git a/src/test/app/PayChan_test.cpp b/src/test/app/PayChan_test.cpp index b81afa830e..1e465aad91 100644 --- a/src/test/app/PayChan_test.cpp +++ b/src/test/app/PayChan_test.cpp @@ -1992,7 +1992,10 @@ public: run() override { using namespace test::jtx; - FeatureBitset const all{testableAmendments()}; + // fixCleanup3_2_0 changes payment-channel error codes (tem* -> tec*) + // and channel-closing semantics. This suite asserts the + // pre-amendment behavior, so run it with the amendment disabled. + FeatureBitset const all{testableAmendments() - fixCleanup3_2_0}; testWithFeats(all); testDepositAuthCreds(); testMetaAndOwnership(all - fixIncludeKeyletFields); From f98c251011e606e13a562598f2ee974d0a35b624 Mon Sep 17 00:00:00 2001 From: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Date: Wed, 27 May 2026 16:18:18 +0100 Subject: [PATCH 46/78] refactor: Improve tracking of book (un)subscriptions --- .../scripts/levelization/results/ordering.txt | 2 - include/xrpl/ledger/BookListeners.h | 49 ----- include/xrpl/ledger/OrderBookDB.h | 50 ++--- include/xrpl/server/InfoSub.h | 84 ++++++++- include/xrpl/server/NetworkOPs.h | 13 ++ src/libxrpl/ledger/BookListeners.cpp | 55 ------ src/libxrpl/server/InfoSub.cpp | 87 +++++++-- src/xrpld/app/ledger/OrderBookDBImpl.cpp | 82 ++------ src/xrpld/app/ledger/OrderBookDBImpl.h | 19 -- src/xrpld/app/misc/NetworkOPs.cpp | 176 ++++++++++++++++-- .../rpc/handlers/subscribe/Unsubscribe.cpp | 14 +- 11 files changed, 384 insertions(+), 247 deletions(-) delete mode 100644 include/xrpl/ledger/BookListeners.h delete mode 100644 src/libxrpl/ledger/BookListeners.cpp diff --git a/.github/scripts/levelization/results/ordering.txt b/.github/scripts/levelization/results/ordering.txt index c2000d1768..7a5be869a5 100644 --- a/.github/scripts/levelization/results/ordering.txt +++ b/.github/scripts/levelization/results/ordering.txt @@ -12,7 +12,6 @@ libxrpl.ledger > xrpl.json libxrpl.ledger > xrpl.ledger libxrpl.ledger > xrpl.nodestore libxrpl.ledger > xrpl.protocol -libxrpl.ledger > xrpl.server libxrpl.ledger > xrpl.shamap libxrpl.net > xrpl.basics libxrpl.net > xrpl.net @@ -206,7 +205,6 @@ xrpl.core > xrpl.protocol xrpl.json > xrpl.basics xrpl.ledger > xrpl.basics xrpl.ledger > xrpl.protocol -xrpl.ledger > xrpl.server xrpl.ledger > xrpl.shamap xrpl.net > xrpl.basics xrpl.nodestore > xrpl.basics diff --git a/include/xrpl/ledger/BookListeners.h b/include/xrpl/ledger/BookListeners.h deleted file mode 100644 index 3b96aca680..0000000000 --- a/include/xrpl/ledger/BookListeners.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include -#include - -#include -#include - -namespace xrpl { - -/** Listen to public/subscribe messages from a book. */ -class BookListeners -{ -public: - using pointer = std::shared_ptr; - - BookListeners() = default; - - /** Add a new subscription for this book - */ - void - addSubscriber(InfoSub::ref sub); - - /** Stop publishing to a subscriber - */ - void - removeSubscriber(std::uint64_t sub); - - /** Publish a transaction to subscribers - - Publish a transaction to clients subscribed to changes on this book. - Uses havePublished to prevent sending duplicate transactions to clients - that have subscribed to multiple books. - - @param jvObj JSON transaction data to publish - @param havePublished InfoSub sequence numbers that have already - published this transaction. - - */ - void - publish(MultiApiJson const& jvObj, hash_set& havePublished); - -private: - std::recursive_mutex lock_; - - hash_map listeners_; -}; - -} // namespace xrpl diff --git a/include/xrpl/ledger/OrderBookDB.h b/include/xrpl/ledger/OrderBookDB.h index a0aee58e2a..a44183900c 100644 --- a/include/xrpl/ledger/OrderBookDB.h +++ b/include/xrpl/ledger/OrderBookDB.h @@ -1,11 +1,11 @@ #pragma once +#include +#include #include -#include #include #include #include -#include #include #include @@ -77,34 +77,24 @@ public: */ virtual bool isBookToXRP(Asset const& asset, std::optional const& domain = std::nullopt) = 0; - - /** - * Process a transaction for order book tracking. - * @param ledger The ledger the transaction was applied to - * @param alTx The transaction to process - * @param jvObj The JSON object of the transaction - */ - virtual void - processTxn( - std::shared_ptr const& ledger, - AcceptedLedgerTx const& alTx, - MultiApiJson const& jvObj) = 0; - - /** - * Get the book listeners for a book. - * @param book The book to get the listeners for - * @return The book listeners for the book - */ - virtual BookListeners::pointer - getBookListeners(Book const&) = 0; - - /** - * Create a new book listeners for a book. - * @param book The book to create the listeners for - * @return The new book listeners for the book - */ - virtual BookListeners::pointer - makeBookListeners(Book const&) = 0; }; +/** Extract the set of books affected by a transaction. + * + * Walks the transaction's metadata nodes and collects every order book + * whose offers were created, modified, or deleted. Used by NetworkOPs to + * fan transaction notifications out to book subscribers. + * + * @param alTx The accepted ledger transaction to inspect. + * @param j Journal used to log per-node parsing failures. Inspecting an + * offer node can throw if a required field is missing; in that + * case the bad node is skipped and a warn-level message is + * emitted via @p j. Other affected books in the same transaction + * are still returned. + * @return The set of books whose offers were created, modified, or + * deleted. May be empty for non-offer transactions. + */ +hash_set +affectedBooks(AcceptedLedgerTx const& alTx, beast::Journal const& j); + } // namespace xrpl diff --git a/include/xrpl/server/InfoSub.h b/include/xrpl/server/InfoSub.h index e93676a938..f316885fd6 100644 --- a/include/xrpl/server/InfoSub.h +++ b/include/xrpl/server/InfoSub.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -26,6 +27,19 @@ public: }; /** Manages a client's subscription to data feeds. + * + * An InfoSub holds a non-owning reference to its `Source` (typically the + * process-wide `NetworkOPsImp`). The destructor reaches back into the + * `Source` to remove this subscriber from every server-side subscription + * map. + * + * @note Lifetime contract: every `InfoSub` instance MUST be destroyed + * before the backing `Source`. NetworkOPsImp shutdown drops all + * subscriber strong refs before its own teardown to satisfy this. + * @note Thread-safety: per-instance state is guarded by `lock_`. The + * destructor reads tracking sets without taking `lock_` because + * the strong-pointer ref-count is zero at destruction time, so + * no other thread can be calling the public mutators. */ class InfoSub : public CountedObject { @@ -117,8 +131,43 @@ public: virtual bool subBook(ref ispListener, Book const&) = 0; + + /** + * Remove a book subscription for a live subscriber. + * + * Clears the book from the subscriber's own tracking set + * (InfoSub::bookSubscriptions_) and then removes the server-side + * entry from subBook_. Call this from RPC unsubscribe handlers. + * + * @param ispListener The subscriber requesting removal. + * @param book The order book to unsubscribe from. + * @return true if the entry was present and removed, false if the + * subscriber was not subscribed to @p book. + * + * @note Thread-safety: acquires subLock_ internally. + * @note Do NOT call from ~InfoSub(). Use unsubBookInternal instead + * to avoid a redundant write-back to bookSubscriptions_ on a + * partially-destroyed object. + */ virtual bool - unsubBook(std::uint64_t uListener, Book const&) = 0; + unsubBook(ref ispListener, Book const&) = 0; + + /** + * Remove a book subscription during InfoSub teardown. + * + * Removes only the server-side entry from subBook_. Does NOT touch + * InfoSub::bookSubscriptions_ because the InfoSub is being destroyed. + * Called by ~InfoSub() for each book in bookSubscriptions_. + * + * @param uListener The sequence number of the subscriber being torn down. + * @param book The order book entry to remove. + * @return true if the entry was present and removed, false otherwise + * (e.g., already removed by a concurrent RPC unsubscribe). + * + * @note Thread-safety: acquires subLock_ internally. + */ + virtual bool + unsubBookInternal(std::uint64_t uListener, Book const&) = 0; virtual bool subTransactions(ref ispListener) = 0; @@ -158,6 +207,13 @@ public: addRpcSub(std::string const& strUrl, ref rspEntry) = 0; virtual bool tryRemoveRpcSub(std::string const& strUrl) = 0; + + /** Journal used by InfoSub for diagnostics that occur after the + * owning subsystem (e.g. application-level Logs) is the only + * surviving sink — primarily destructor-time cleanup failures. + */ + [[nodiscard]] virtual beast::Journal const& + journal() const = 0; }; public: @@ -184,6 +240,31 @@ public: void deleteSubAccountInfo(AccountID const& account, bool rt); + /** Record that this subscriber is following @p book. + * + * Called by NetworkOPsImp::subBook so that ~InfoSub() can issue a + * matching unsubBook for every book this subscriber is tracking, + * keeping per-subscriber state symmetric with the server-side map. + * + * @param book The order book this subscriber has just subscribed to. + * @note Idempotent: re-inserting an already-tracked book is a no-op. + * @note Thread-safe: takes InfoSub::lock_. + */ + void + insertBookSubscription(Book const& book); + + /** Stop tracking @p book for this subscriber. + * + * Called by the unsubscribe RPC handler so that the book is not + * re-unsubscribed by ~InfoSub(). Pairs with insertBookSubscription. + * + * @param book The order book to forget. + * @note No-op if @p book was not previously inserted. + * @note Thread-safe: takes InfoSub::lock_. + */ + void + deleteBookSubscription(Book const& book); + // return false if already subscribed to this account bool insertSubAccountHistory(AccountID const& account); @@ -217,6 +298,7 @@ private: std::shared_ptr request_; std::uint64_t seq_; hash_set accountHistorySubscriptions_; + hash_set bookSubscriptions_; unsigned int apiVersion_ = 0; static int diff --git a/include/xrpl/server/NetworkOPs.h b/include/xrpl/server/NetworkOPs.h index e2aa17566e..785d808935 100644 --- a/include/xrpl/server/NetworkOPs.h +++ b/include/xrpl/server/NetworkOPs.h @@ -249,6 +249,19 @@ public: virtual void stateAccounting(json::Value& obj) = 0; + + /** Total number of (book, subscriber) entries currently tracked. + * + * Counts every weak_ptr stored across every book in subBook_, NOT the + * number of distinct subscribers and NOT the number of distinct + * books: a single subscriber following N books contributes N entries. + * + * @note Diagnostic accessor; intended for tests and operator visibility + * into per-book subscription state. The returned value is a + * snapshot under the subscription lock. + */ + virtual std::size_t + getBookSubscribersCount() = 0; }; } // namespace xrpl diff --git a/src/libxrpl/ledger/BookListeners.cpp b/src/libxrpl/ledger/BookListeners.cpp deleted file mode 100644 index d78da4c73e..0000000000 --- a/src/libxrpl/ledger/BookListeners.cpp +++ /dev/null @@ -1,55 +0,0 @@ -#include - -#include -#include -#include -#include - -#include -#include - -namespace xrpl { - -void -BookListeners::addSubscriber(InfoSub::ref sub) -{ - std::scoped_lock const sl(lock_); - listeners_[sub->getSeq()] = sub; -} - -void -BookListeners::removeSubscriber(std::uint64_t seq) -{ - std::scoped_lock const sl(lock_); - listeners_.erase(seq); -} - -void -BookListeners::publish(MultiApiJson const& jvObj, hash_set& havePublished) -{ - std::scoped_lock const sl(lock_); - auto it = listeners_.cbegin(); - - while (it != listeners_.cend()) - { - InfoSub::pointer p = it->second.lock(); - - if (p) - { - // Only publish jvObj if this is the first occurrence - if (havePublished.emplace(p->getSeq()).second) - { - jvObj.visit( - p->getApiVersion(), // - [&](json::Value const& jv) { p->send(jv, true); }); - } - ++it; - } - else - { - it = listeners_.erase(it); - } - } -} - -} // namespace xrpl diff --git a/src/libxrpl/server/InfoSub.cpp b/src/libxrpl/server/InfoSub.cpp index 87b48296a1..353c295856 100644 --- a/src/libxrpl/server/InfoSub.cpp +++ b/src/libxrpl/server/InfoSub.cpp @@ -1,15 +1,47 @@ #include +#include +#include #include #include +#include #include #include +#include #include #include namespace xrpl { +namespace { + +// Wraps a Source teardown call so that an exception from one cleanup +// step does not prevent the subsequent steps from running. Source methods +// acquire a lock and can throw std::system_error; a throw out of ~InfoSub +// during stack unwinding would terminate the process. Failures are +// reported through the Source's Journal so they reach the configured log +// sinks; JLOG itself cannot throw, so the noexcept guarantee holds. +template +void +safeUnsub(std::uint64_t seq, F&& f, beast::Journal j) noexcept +{ + try + { + f(); + } + catch (std::exception const& e) + { + JLOG(j.warn()) << "~InfoSub[seq=" << seq << "]: cleanup step failed: " << e.what(); + } + catch (...) + { + JLOG(j.warn()) << "~InfoSub[seq=" << seq << "]: cleanup step failed: unknown exception"; + } +} + +} // namespace + // This is the primary interface into the "client" portion of the program. // Code that wants to do normal operations on the network such as // creating and monitoring accounts, creating transactions, and so on @@ -32,25 +64,44 @@ InfoSub::InfoSub(Source& source, Consumer consumer) InfoSub::~InfoSub() { - source_.unsubTransactions(seq_); - source_.unsubRTTransactions(seq_); - source_.unsubLedger(seq_); - source_.unsubManifests(seq_); - source_.unsubServer(seq_); - source_.unsubValidations(seq_); - source_.unsubPeerStatus(seq_); - source_.unsubConsensus(seq_); + // Each Source teardown call below acquires a server-side lock and + // can throw. Wrap each independent call so partial failure does not + // skip the remaining teardown steps. + + auto const& j = source_.journal(); + + safeUnsub(seq_, [&] { source_.unsubTransactions(seq_); }, j); + safeUnsub(seq_, [&] { source_.unsubRTTransactions(seq_); }, j); + safeUnsub(seq_, [&] { source_.unsubLedger(seq_); }, j); + safeUnsub(seq_, [&] { source_.unsubManifests(seq_); }, j); + safeUnsub(seq_, [&] { source_.unsubServer(seq_); }, j); + safeUnsub(seq_, [&] { source_.unsubValidations(seq_); }, j); + safeUnsub(seq_, [&] { source_.unsubPeerStatus(seq_); }, j); + safeUnsub(seq_, [&] { source_.unsubConsensus(seq_); }, j); // Use the internal unsubscribe so that it won't call // back to us and modify its own parameter if (!realTimeSubscriptions_.empty()) - source_.unsubAccountInternal(seq_, realTimeSubscriptions_, true); + { + safeUnsub( + seq_, [&] { source_.unsubAccountInternal(seq_, realTimeSubscriptions_, true); }, j); + } if (!normalSubscriptions_.empty()) - source_.unsubAccountInternal(seq_, normalSubscriptions_, false); + { + safeUnsub( + seq_, [&] { source_.unsubAccountInternal(seq_, normalSubscriptions_, false); }, j); + } for (auto const& account : accountHistorySubscriptions_) - source_.unsubAccountHistoryInternal(seq_, account, false); + { + safeUnsub(seq_, [&] { source_.unsubAccountHistoryInternal(seq_, account, false); }, j); + } + + for (auto const& book : bookSubscriptions_) + { + safeUnsub(seq_, [&] { source_.unsubBookInternal(seq_, book); }, j); + } } Resource::Consumer& @@ -114,6 +165,20 @@ InfoSub::deleteSubAccountHistory(AccountID const& account) accountHistorySubscriptions_.erase(account); } +void +InfoSub::insertBookSubscription(Book const& book) +{ + std::scoped_lock const sl(lock_); + bookSubscriptions_.insert(book); +} + +void +InfoSub::deleteBookSubscription(Book const& book) +{ + std::scoped_lock const sl(lock_); + bookSubscriptions_.erase(book); +} + void InfoSub::clearRequest() { diff --git a/src/xrpld/app/ledger/OrderBookDBImpl.cpp b/src/xrpld/app/ledger/OrderBookDBImpl.cpp index 658ec4ea7a..1e474ef949 100644 --- a/src/xrpld/app/ledger/OrderBookDBImpl.cpp +++ b/src/xrpld/app/ledger/OrderBookDBImpl.cpp @@ -9,19 +9,17 @@ #include #include #include -#include #include +#include #include #include #include #include -#include #include #include #include #include -#include #include #include #include @@ -307,55 +305,10 @@ OrderBookDBImpl::isBookToXRP(Asset const& asset, std::optional const& do return xrpBooks_.contains(asset); } -BookListeners::pointer -OrderBookDBImpl::makeBookListeners(Book const& book) +hash_set +affectedBooks(AcceptedLedgerTx const& alTx, beast::Journal const& j) { - std::scoped_lock const sl(lock_); - auto ret = getBookListeners(book); - - if (!ret) - { - ret = std::make_shared(); - - listeners_[book] = ret; - XRPL_ASSERT( - getBookListeners(book) == ret, - "xrpl::OrderBookDB::makeBookListeners : result roundtrip " - "lookup"); - } - - return ret; -} - -BookListeners::pointer -OrderBookDBImpl::getBookListeners(Book const& book) -{ - BookListeners::pointer ret; - std::scoped_lock const sl(lock_); - - auto it0 = listeners_.find(book); - if (it0 != listeners_.end()) - ret = it0->second; - - return ret; -} - -// Based on the meta, send the meta to the streams that are listening. -// We need to determine which streams a given meta effects. -void -OrderBookDBImpl::processTxn( - std::shared_ptr const& ledger, - AcceptedLedgerTx const& alTx, - MultiApiJson const& jvObj) -{ - std::scoped_lock const sl(lock_); - - // For this particular transaction, maintain the set of unique - // subscriptions that have already published it. This prevents sending - // the transaction multiple times if it touches multiple ltOFFER - // entries for the same book, or if it touches multiple books and a - // single client has subscribed to those books. - hash_set havePublished; + hash_set result; for (auto const& node : alTx.getMeta().getNodes()) { @@ -363,40 +316,41 @@ OrderBookDBImpl::processTxn( { if (node.getFieldU16(sfLedgerEntryType) == ltOFFER) { - auto process = [&, this](SField const& field) { + auto extract = [&](SField const& field) { if (auto data = dynamic_cast(node.peekAtPField(field)); data && data->isFieldPresent(sfTakerPays) && data->isFieldPresent(sfTakerGets)) { - auto listeners = getBookListeners( - {data->getFieldAmount(sfTakerGets).asset(), - data->getFieldAmount(sfTakerPays).asset(), - (*data)[~sfDomainID]}); - if (listeners) - listeners->publish(jvObj, havePublished); + result.emplace( + data->getFieldAmount(sfTakerGets).asset(), + data->getFieldAmount(sfTakerPays).asset(), + (*data)[~sfDomainID]); } }; - // We need a field that contains the TakerGets and TakerPays - // parameters. if (node.getFName() == sfModifiedNode) { - process(sfPreviousFields); + extract(sfPreviousFields); } else if (node.getFName() == sfCreatedNode) { - process(sfNewFields); + extract(sfNewFields); } else if (node.getFName() == sfDeletedNode) { - process(sfFinalFields); + extract(sfFinalFields); } } } catch (std::exception const& ex) { - JLOG(j_.info()) << "processTxn: field not found (" << ex.what() << ")"; + // The bad node is skipped; other affected books in the same + // transaction are still returned. Logged at warn so a malformed + // offer node is visible to operators. + JLOG(j.warn()) << "affectedBooks: skipping malformed node (" << ex.what() << ")"; } } + + return result; } } // namespace xrpl diff --git a/src/xrpld/app/ledger/OrderBookDBImpl.h b/src/xrpld/app/ledger/OrderBookDBImpl.h index a50f512441..a68f63c043 100644 --- a/src/xrpld/app/ledger/OrderBookDBImpl.h +++ b/src/xrpld/app/ledger/OrderBookDBImpl.h @@ -1,10 +1,7 @@ #pragma once #include -#include -#include #include -#include #include #include @@ -54,18 +51,6 @@ public: void update(std::shared_ptr const& ledger); - // see if this txn effects any orderbook - void - processTxn( - std::shared_ptr const& ledger, - AcceptedLedgerTx const& alTx, - MultiApiJson const& jvObj) override; - - BookListeners::pointer - getBookListeners(Book const&) override; - BookListeners::pointer - makeBookListeners(Book const&) override; - private: std::reference_wrapper registry_; int const pathSearchMax_; @@ -84,10 +69,6 @@ private: std::recursive_mutex lock_; - using BookToListenersMap = hash_map; - - BookToListenersMap listeners_; - std::atomic seq_; beast::Journal const j_; diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index 12c79b821c..e59840befc 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -527,6 +527,8 @@ public: updateLocalTx(ReadView const& view) override; std::size_t getLocalTxCount() override; + std::size_t + getBookSubscribersCount() override; // // Monitoring: publisher side. @@ -586,7 +588,9 @@ public: bool subBook(InfoSub::ref ispListener, Book const&) override; bool - unsubBook(std::uint64_t uListener, Book const&) override; + unsubBook(InfoSub::ref ispListener, Book const&) override; + bool + unsubBookInternal(std::uint64_t uListener, Book const&) override; bool subManifests(InfoSub::ref ispListener) override; @@ -629,6 +633,12 @@ public: bool tryRemoveRpcSub(std::string const& strUrl) override; + beast::Journal const& + journal() const override + { + return journal_; + } + void stop() override { @@ -705,6 +715,32 @@ private: AcceptedLedgerTx const& transaction, bool last); + /** + * Fan transaction notifications out to all book subscribers. + * + * Extracts the set of order books affected by @p transaction, then + * delivers @p jvObj to every live subscriber of those books. + * + * Uses a two-pass design to keep subLock_ hold time short: + * 1. Under subLock_, collect strong InfoSub pointers for all live + * subscribers and prune any expired weak_ptrs encountered. + * 2. Release subLock_, then call send() on each collected pointer. + * + * @param transaction The accepted ledger transaction to inspect. + * @param jvObj JSON representation of the transaction to deliver. + * + * @note Thread-safety: acquires subLock_ for the collection pass only. + * send() is intentionally called outside the lock to avoid blocking + * all other sub/unsub/publish paths while I/O is in progress. + * @note Contention: subLock_ is shared with all other subscription types. + * On high-throughput nodes processing multi-hop payments that touch + * many offer nodes, this pass holds subLock_ longer than the old + * per-book BookListeners locks did. This is an accepted trade-off + * for lock-domain simplicity. + */ + void + pubBookTransaction(AcceptedLedgerTx const& transaction, MultiApiJson const& jvObj); + void pubProposedAccountTransaction( std::shared_ptr const& ledger, @@ -802,8 +838,19 @@ private: LedgerMaster& ledgerMaster_; + /** Maps each order book to its current set of subscribers. + * Outer key: the Book (currency pair + optional domain). + * Inner key: InfoSub::seq (unique per connection). + * Inner value: weak_ptr so that a dropped connection does not prevent + * the InfoSub from being destroyed; expired entries are pruned lazily + * by pubBookTransaction and eagerly by unsubBookInternal (~InfoSub path). + * Guarded by subLock_. + */ + using SubBookMapType = hash_map; + SubInfoMapType subAccount_; SubInfoMapType subRTAccount_; + SubBookMapType subBook_; ///< Guarded by subLock_. subRpcMapType rpcSubMap_; @@ -3191,6 +3238,16 @@ NetworkOPsImp::getLocalTxCount() return localTX_->size(); } +std::size_t +NetworkOPsImp::getBookSubscribersCount() +{ + std::scoped_lock const sl(subLock_); + std::size_t total = 0; + for (auto const& [_, subs] : subBook_) + total += subs.size(); + return total; +} + // This routine should only be used to publish accepted or validated // transactions. MultiApiJson @@ -3352,11 +3409,89 @@ NetworkOPsImp::pubValidatedTransaction( } if (transaction.getResult() == tesSUCCESS) - registry_.get().getOrderBookDB().processTxn(ledger, transaction, jvObj); + pubBookTransaction(transaction, jvObj); pubAccountTransaction(ledger, transaction, last); } +void +NetworkOPsImp::pubBookTransaction(AcceptedLedgerTx const& alTx, MultiApiJson const& jvObj) +{ + auto const books = affectedBooks(alTx, journal_); + if (books.empty()) + return; + + // Two-pass design: + // + // 1. Under subLock_, walk subBook_, collect a strong pointer for each + // unique listener (and prune any expired weak_ptrs we encounter). + // 2. Release subLock_, then send to each collected listener. + // + // Reasoning: + // * send() can be slow / blocking, so holding subLock_ across it would + // stall every other sub/unsub/pub path on this server (see the matching + // TODO above pubServer at line ~2275). + // * A strong pointer destructed while subLock_ is held risks running + // ~InfoSub() in-line, which re-enters unsubBook() and mutates the very + // subBook_/SubMapType being iterated -> dangling iterator UB. + // + // Releasing subLock_ before any InfoSub::pointer can decay solves both. + // ~InfoSub() reacquires subLock_ via unsubBook() on its own and serializes + // safely with concurrent traffic. + + std::vector listeners; + hash_set seen; + + // Sized for the common case where every affected book has at most + // one subscriber. Multi-subscriber books trigger reallocation, but + // that is rare and the upper-bound estimate (sum of per-book sizes) + // would itself require walking subBook_ twice. + listeners.reserve(books.size()); + seen.reserve(books.size()); + + { + std::scoped_lock const sl(subLock_); + + for (auto const& book : books) + { + auto it = subBook_.find(book); + if (it == subBook_.end()) + continue; + + for (auto sit = it->second.begin(); sit != it->second.end();) + { + if (auto p = sit->second.lock()) + { + // Defensive: subBook_ entries are normally cleared by + // ~InfoSub() -> unsubBook(), so we rarely see expired + // weak_ptrs here. The else branch covers the narrow race + // where the last strong ref is dropped between insertion + // and our lock() call. + if (seen.emplace(p->getSeq()).second) + listeners.emplace_back(std::move(p)); + ++sit; + } + else + { + JLOG(journal_.debug()) + << "pubBookTransaction: pruning expired weak_ptr for seq=" << sit->first; + sit = it->second.erase(sit); + } + } + + if (it->second.empty()) + subBook_.erase(it); + } + } + + for (auto const& p : listeners) + { + jvObj.visit(p->getApiVersion(), [&](json::Value const& jv) { p->send(jv, true); }); + } + // listeners destructs here, outside subLock_; ~InfoSub (if any fires) + // will reacquire subLock_ via unsubBook with no iterator hazard. +} + void NetworkOPsImp::pubAccountTransaction( std::shared_ptr const& ledger, @@ -4010,26 +4145,39 @@ NetworkOPsImp::unsubAccountHistoryInternal( bool NetworkOPsImp::subBook(InfoSub::ref isrListener, Book const& book) { - if (auto listeners = registry_.get().getOrderBookDB().makeBookListeners(book)) + // Server-side insert first, then InfoSub bookkeeping. If the InfoSub-side + // insert throws, the orphan in subBook_ is cleared by the expired-weak_ptr + // prune in pubBookTransaction. With the reverse ordering, ~InfoSub would + // call unsubBookInternal for a key that was never inserted server-side. { - listeners->addSubscriber(isrListener); - } - else - { - // LCOV_EXCL_START - UNREACHABLE("xrpl::NetworkOPsImp::subBook : null book listeners"); - // LCOV_EXCL_STOP + std::scoped_lock const sl(subLock_); + subBook_[book].try_emplace(isrListener->getSeq(), isrListener); } + isrListener->insertBookSubscription(book); return true; } bool -NetworkOPsImp::unsubBook(std::uint64_t uSeq, Book const& book) +NetworkOPsImp::unsubBook(InfoSub::ref isrListener, Book const& book) { - if (auto listeners = registry_.get().getOrderBookDB().getBookListeners(book)) - listeners->removeSubscriber(uSeq); + // Mirrors unsubAccount: clear the per-subscriber tracking set first so + // ~InfoSub does not re-issue an unsubBookInternal for a book the caller + // already removed, then erase the server-side entry. + isrListener->deleteBookSubscription(book); + return unsubBookInternal(isrListener->getSeq(), book); +} - return true; +bool +NetworkOPsImp::unsubBookInternal(std::uint64_t uSeq, Book const& book) +{ + std::scoped_lock const sl(subLock_); + auto it = subBook_.find(book); + if (it == subBook_.end()) + return false; + bool const erased = it->second.erase(uSeq) != 0u; + if (it->second.empty()) + subBook_.erase(it); + return erased; } std::uint32_t diff --git a/src/xrpld/rpc/handlers/subscribe/Unsubscribe.cpp b/src/xrpld/rpc/handlers/subscribe/Unsubscribe.cpp index 36dae615b3..af42af2a55 100644 --- a/src/xrpld/rpc/handlers/subscribe/Unsubscribe.cpp +++ b/src/xrpld/rpc/handlers/subscribe/Unsubscribe.cpp @@ -186,13 +186,23 @@ doUnsubscribe(RPC::JsonContext& context) book.domain = domain; } - context.netOps.unsubBook(ispSub->getSeq(), book); + if (!context.netOps.unsubBook(ispSub, book)) + { + JLOG(context.j.debug()) + << "doUnsubscribe: book not subscribed (no-op for seq=" << ispSub->getSeq() + << ")"; + } // both_sides is deprecated. if ((jv.isMember(jss::both) && jv[jss::both].asBool()) || (jv.isMember(jss::both_sides) && jv[jss::both_sides].asBool())) { - context.netOps.unsubBook(ispSub->getSeq(), reversed(book)); + if (!context.netOps.unsubBook(ispSub, reversed(book))) + { + JLOG(context.j.debug()) + << "doUnsubscribe: reversed book not subscribed (no-op for seq=" + << ispSub->getSeq() << ")"; + } } } } From 82ee5b7556456cf9f9b78bed91d24e1b72eeea50 Mon Sep 17 00:00:00 2001 From: Bart Date: Mon, 1 Jun 2026 16:04:45 -0400 Subject: [PATCH 47/78] refactor: Handle int and uint API versions separately --- include/xrpl/protocol/ApiVersion.h | 33 ++++++++++++++++++------------ 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/include/xrpl/protocol/ApiVersion.h b/include/xrpl/protocol/ApiVersion.h index 345049b377..10b7571641 100644 --- a/include/xrpl/protocol/ApiVersion.h +++ b/include/xrpl/protocol/ApiVersion.h @@ -102,25 +102,32 @@ getAPIVersionNumber(json::Value const& jv, bool betaEnabled) json::Value const maxVersion( betaEnabled ? RPC::kApiBetaVersion : RPC::kApiMaximumSupportedVersion); - if (jv.isObject()) + if (!jv.isObject() || !jv.isMember(jss::api_version)) + return RPC::kApiVersionIfUnspecified; + + try { - if (jv.isMember(jss::api_version)) + auto const& rawVersion = jv[jss::api_version]; + switch (rawVersion.type()) { - auto const specifiedVersion = jv[jss::api_version]; - if (!specifiedVersion.isInt() && !specifiedVersion.isUInt()) - { - return RPC::kApiInvalidVersion; + case json::ValueType::Int: + if (rawVersion.asInt() < 0) + return RPC::kApiInvalidVersion; + [[fallthrough]]; + case json::ValueType::UInt: { + auto const apiVersion = rawVersion.asUInt(); + if (apiVersion < kMinVersion || apiVersion > maxVersion) + return RPC::kApiInvalidVersion; + return apiVersion; } - auto const specifiedVersionInt = specifiedVersion.asInt(); - if (specifiedVersionInt < kMinVersion || specifiedVersionInt > maxVersion) - { + default: return RPC::kApiInvalidVersion; - } - return specifiedVersionInt; } } - - return RPC::kApiVersionIfUnspecified; + catch (...) + { + return RPC::kApiInvalidVersion; + } } } // namespace RPC From 5a25c9188bd5a6ed6aafbe5e8c3be25d53da5ad3 Mon Sep 17 00:00:00 2001 From: Bart Date: Mon, 1 Jun 2026 16:53:43 -0400 Subject: [PATCH 48/78] release: Bump version to 3.2.0-rc4 --- src/libxrpl/protocol/BuildInfo.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libxrpl/protocol/BuildInfo.cpp b/src/libxrpl/protocol/BuildInfo.cpp index 7de1862dfc..e81be00920 100644 --- a/src/libxrpl/protocol/BuildInfo.cpp +++ b/src/libxrpl/protocol/BuildInfo.cpp @@ -23,7 +23,7 @@ namespace { //------------------------------------------------------------------------------ // clang-format off // NOLINTNEXTLINE(readability-identifier-naming) -char const* const versionString = "3.2.0-rc3" +char const* const versionString = "3.2.0-rc4" // clang-format on ; From 47b06ecd17c3b9f2852ebd15987a85401965117e Mon Sep 17 00:00:00 2001 From: Sergey Kuznetsov Date: Wed, 3 Jun 2026 15:32:43 +0100 Subject: [PATCH 49/78] refactor: Use rocksdb includes only when it is available --- include/xrpl/basics/rocksdb.h | 29 ------------------- src/libxrpl/nodestore/ManagerImp.cpp | 4 +++ .../nodestore/backend/RocksDBFactory.cpp | 26 ++++++++--------- src/test/nodestore/import_test.cpp | 11 +++++-- 4 files changed, 24 insertions(+), 46 deletions(-) delete mode 100644 include/xrpl/basics/rocksdb.h diff --git a/include/xrpl/basics/rocksdb.h b/include/xrpl/basics/rocksdb.h deleted file mode 100644 index 3d468b0f1b..0000000000 --- a/include/xrpl/basics/rocksdb.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#if XRPL_ROCKSDB_AVAILABLE -// #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif diff --git a/src/libxrpl/nodestore/ManagerImp.cpp b/src/libxrpl/nodestore/ManagerImp.cpp index 5cefbfd357..1d87ff9199 100644 --- a/src/libxrpl/nodestore/ManagerImp.cpp +++ b/src/libxrpl/nodestore/ManagerImp.cpp @@ -44,8 +44,10 @@ ManagerImp::missingBackend() // the Factory classes is an undefined behaviour. void registerNuDBFactory(Manager& manager); +#if XRPL_ROCKSDB_AVAILABLE void registerRocksDBFactory(Manager& manager); +#endif void registerNullFactory(Manager& manager); void @@ -54,7 +56,9 @@ registerMemoryFactory(Manager& manager); ManagerImp::ManagerImp() { registerNuDBFactory(*this); +#if XRPL_ROCKSDB_AVAILABLE registerRocksDBFactory(*this); +#endif registerNullFactory(*this); registerMemoryFactory(*this); } diff --git a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp index d2c193888c..e7767cd4ac 100644 --- a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp @@ -1,12 +1,22 @@ +#if XRPL_ROCKSDB_AVAILABLE #include +#include #include #include +#include +#include +#include #include #include #include +#include +#include #include #include #include +#include +#include +#include #include #include @@ -24,26 +34,14 @@ #include #include +#include #include #include #include +#include #include #include -#if XRPL_ROCKSDB_AVAILABLE -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - namespace xrpl::NodeStore { class RocksDBEnv : public rocksdb::EnvWrapper diff --git a/src/test/nodestore/import_test.cpp b/src/test/nodestore/import_test.cpp index a80b5ccc93..d8c4a96713 100644 --- a/src/test/nodestore/import_test.cpp +++ b/src/test/nodestore/import_test.cpp @@ -21,11 +21,16 @@ #include #include #include + +#if XRPL_ROCKSDB_AVAILABLE + #include #include #include #include +#endif + #include #include #include @@ -297,17 +302,17 @@ public: auto const args = parseArgs(arg()); bool usage = args.empty(); - if (!usage && args.find("from") == args.end()) + if (!usage && !args.contains("from")) { log << "Missing parameter: from"; usage = true; } - if (!usage && args.find("to") == args.end()) + if (!usage && !args.contains("to")) { log << "Missing parameter: to"; usage = true; } - if (!usage && args.find("buffer") == args.end()) + if (!usage && !args.contains("buffer")) { log << "Missing parameter: buffer"; usage = true; From 8e3eabc398f1400dec1a9c4c63d9b2dabc0ad78d Mon Sep 17 00:00:00 2001 From: Michael Legleux Date: Wed, 3 Jun 2026 11:59:18 -0700 Subject: [PATCH 50/78] refactor: Remove auto-update script and update RPM version MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor: Update RPM version scheme; remove auto-update script; service hardening - **RPM version scheme**: pre-releases now use `~` in the `Version` field instead of the `0..` `Release`-field hack. Matches Debian's `~` convention, so RPM and DEB version strings are symmetric. Requires rpm ≥ 4.10 (RHEL 9 ships 4.17). Before/after for a pre-release build: ``` # before xrpld-3.2.0-0.1.rc3+202606011647.d4cb68d5.el9.x86_64.rpm # after (symmetric with DEB) xrpld-3.2.0~rc2+202606010139.7679a310-1.el9.x86_64.rpm xrpld_3.2.0~rc2+202606010139.7679a310-1_amd64.deb ``` - **Auto-update removed**: `update-xrpld`, `update-xrpld.service`, and `update-xrpld.timer` deleted. The `50-xrpld.preset` `disable` line for the timer is dropped too. - **Service hardening** (two new `[Service]` directives in `xrpld.service`): - `CapabilityBoundingSet=CAP_NET_BIND_SERVICE` — drops every Linux capability except `CAP_NET_BIND_SERVICE`, capping the privilege ceiling to least-privilege while still letting operators bind ports <1024 (e.g. WS/HTTPS on 443). - `SystemCallArchitectures=native` — restricts the service to the native syscall ABI, blocking alternate-ABI (32-bit/x32) syscalls used to evade seccomp filtering. - [ ] Build RPM from a pre-release version (e.g. `3.2.0-b1`) and confirm `rpm -qi` shows `Version: 3.2.0~b1`, `Release: 1` - [ ] Confirm `3.2.0~b1` sorts before `3.2.0` via `rpmvercmp` - [ ] Install package and confirm no `update-xrpld*` units appear in `systemctl list-unit-files` - [ ] Confirm `systemctl show xrpld` reflects the new `CapabilityBoundingSet` and `SystemCallArchitectures` * fix: Track tmpfiles-created directories in RPM %files as %ghost --- package/README.md | 1 - package/build_pkg.sh | 33 +++--- package/debian/rules | 2 - package/debian/xrpld.docs | 1 - package/rpm/xrpld.spec | 19 +--- package/shared/50-xrpld.preset | 2 - package/shared/update-xrpld | 152 ---------------------------- package/shared/update-xrpld.service | 16 --- package/shared/update-xrpld.timer | 10 -- package/shared/xrpld.service | 2 + 10 files changed, 19 insertions(+), 219 deletions(-) delete mode 100755 package/shared/update-xrpld delete mode 100644 package/shared/update-xrpld.service delete mode 100644 package/shared/update-xrpld.timer diff --git a/package/README.md b/package/README.md index 867ca273b4..d440f70fb8 100644 --- a/package/README.md +++ b/package/README.md @@ -15,7 +15,6 @@ package/ xrpld.sysusers sysusers.d config (used by both RPM and DEB) xrpld.tmpfiles tmpfiles.d config (used by both RPM and DEB) xrpld.logrotate logrotate config (installed to /etc/logrotate.d/xrpld) - update-xrpld auto-update script (installed to /usr/libexec/xrpld/, run by update-xrpld.timer) ``` ## Prerequisites diff --git a/package/build_pkg.sh b/package/build_pkg.sh index f2c2c63c12..e2ec8fee3d 100755 --- a/package/build_pkg.sh +++ b/package/build_pkg.sh @@ -114,10 +114,11 @@ VER_BASE="${VERSION%%-*}" VER_SUFFIX="${VERSION#*-}" [[ "${VER_SUFFIX}" == "${VERSION}" ]] && VER_SUFFIX="" -# Reject multi-segment suffixes (e.g. "beta-1", "rc1-15-gabc123"). The RPM -# Release field forbids '-', and the convention here is single-token suffixes -# like b1 or rc2. Fail early with a clear message rather than letting either -# rpmbuild blow up or silently mangling dashes into dots. +# Reject multi-segment suffixes (e.g. "beta-1", "rc1-15-gabc123"). Neither an +# RPM Version nor a Debian upstream version may contain '-' (it's the NVR / +# version-revision separator), and the convention here is single-token +# suffixes like b1 or rc2. Fail early with a clear message rather than letting +# the package tooling blow up or silently mangle dashes. if [[ "${VER_SUFFIX}" == *-* ]]; then echo "build_pkg.sh: multi-segment pre-release in VERSION='${VERSION}' (suffix '${VER_SUFFIX}')." >&2 echo "Use single-token suffixes like 3.2.0-b1 or 3.2.0-rc2." >&2 @@ -142,9 +143,6 @@ stage_common() { cp "${SHARED}/xrpld.sysusers" "${dest}/xrpld.sysusers" cp "${SHARED}/xrpld.tmpfiles" "${dest}/xrpld.tmpfiles" cp "${SHARED}/xrpld.logrotate" "${dest}/xrpld.logrotate" - cp "${SHARED}/update-xrpld" "${dest}/update-xrpld" - cp "${SHARED}/update-xrpld.service" "${dest}/update-xrpld.service" - cp "${SHARED}/update-xrpld.timer" "${dest}/update-xrpld.timer" cp "${SHARED}/50-xrpld.preset" "${dest}/50-xrpld.preset" } @@ -156,20 +154,18 @@ build_rpm() { cp "${SRC_DIR}/package/rpm/xrpld.spec" "${topdir}/SPECS/xrpld.spec" stage_common "${topdir}/SOURCES" - # RPM Version can't contain '-'. A pre-release goes in Release with a - # leading "0." so 3.2.0-b1 sorts before the final 3.2.0-. - # The order is "0.." (e.g. 0.1.b6) — the Fedora/EPEL - # convention. Reversing to "0.." (e.g. 0.b6.1) breaks - # rpmvercmp against the former because numeric segments outrank alphabetic - # ones, so "0.1.b5" would sort newer than "0.b6.1". - local rpm_release="${PKG_RELEASE}" - [[ -n "${VER_SUFFIX}" ]] && rpm_release="0.${PKG_RELEASE}.${VER_SUFFIX}" + # Pre-releases use the modern rpm '~' convention (rpm >= 4.10): the suffix + # goes in Version (e.g. 3.2.0~b1), which rpmvercmp sorts *before* the final + # 3.2.0 — identical semantics to Debian's '~'. Release is just the package + # release number. This replaces the older "0.." Release + # hack and keeps the RPM and DEB version strings symmetric. + local rpm_version="${VER_BASE}${VER_SUFFIX:+~${VER_SUFFIX}}" set -x rpmbuild -bb \ --define "_topdir ${topdir}" \ - --define "xrpld_version ${VER_BASE}" \ - --define "xrpld_release ${rpm_release}" \ + --define "xrpld_version ${rpm_version}" \ + --define "xrpld_release ${PKG_RELEASE}" \ "${topdir}/SPECS/xrpld.spec" } @@ -181,13 +177,10 @@ build_deb() { stage_common "${staging}" cp -r "${DEBIAN_DIR}" "${staging}/debian" - # Debhelper auto-discovers these only from debian/. cp "${staging}/xrpld.service" "${staging}/debian/xrpld.service" cp "${staging}/xrpld.sysusers" "${staging}/debian/xrpld.sysusers" cp "${staging}/xrpld.tmpfiles" "${staging}/debian/xrpld.tmpfiles" cp "${staging}/xrpld.logrotate" "${staging}/debian/xrpld.logrotate" - cp "${staging}/update-xrpld.service" "${staging}/debian/xrpld.update-xrpld.service" - cp "${staging}/update-xrpld.timer" "${staging}/debian/xrpld.update-xrpld.timer" # Debian '~' marks a pre-release; 3.2.0~b1 sorts before 3.2.0. local deb_full_version="${VER_BASE}${VER_SUFFIX:+~${VER_SUFFIX}}-${PKG_RELEASE}" diff --git a/package/debian/rules b/package/debian/rules index cd94da7e5b..16574bca3f 100644 --- a/package/debian/rules +++ b/package/debian/rules @@ -10,7 +10,6 @@ override_dh_auto_configure override_dh_auto_build override_dh_auto_test: override_dh_installsystemd: dh_installsystemd --no-stop-on-upgrade xrpld.service - dh_installsystemd --name=update-xrpld --no-start update-xrpld.service update-xrpld.timer execute_before_dh_installtmpfiles: dh_installsysusers @@ -21,7 +20,6 @@ override_dh_install: install -D -m 0755 xrpld debian/xrpld/usr/bin/xrpld install -D -m 0644 xrpld.cfg debian/xrpld/etc/xrpld/xrpld.cfg install -D -m 0644 validators.txt debian/xrpld/etc/xrpld/validators.txt - install -D -m 0755 update-xrpld debian/xrpld/usr/libexec/xrpld/update-xrpld override_dh_dwz: @: diff --git a/package/debian/xrpld.docs b/package/debian/xrpld.docs index 1217b6db43..b43bf86b50 100644 --- a/package/debian/xrpld.docs +++ b/package/debian/xrpld.docs @@ -1,2 +1 @@ README.md -LICENSE.md diff --git a/package/rpm/xrpld.spec b/package/rpm/xrpld.spec index 4933c724f7..5595fd0d8d 100644 --- a/package/rpm/xrpld.spec +++ b/package/rpm/xrpld.spec @@ -35,8 +35,6 @@ install -Dm0644 %{_sourcedir}/validators.txt %{buildroot}%{_sysconfdir}/%{ # systemd units, sysusers, tmpfiles, preset install -Dm0644 %{_sourcedir}/xrpld.service %{buildroot}%{_unitdir}/xrpld.service -install -Dm0644 %{_sourcedir}/update-xrpld.service %{buildroot}%{_unitdir}/update-xrpld.service -install -Dm0644 %{_sourcedir}/update-xrpld.timer %{buildroot}%{_unitdir}/update-xrpld.timer install -Dm0644 %{_sourcedir}/xrpld.sysusers %{buildroot}%{_sysusersdir}/xrpld.conf install -Dm0644 %{_sourcedir}/xrpld.tmpfiles %{buildroot}%{_tmpfilesdir}/xrpld.conf install -Dm0644 %{_sourcedir}/50-xrpld.preset %{buildroot}%{_presetdir}/50-xrpld.preset @@ -44,9 +42,6 @@ install -Dm0644 %{_sourcedir}/50-xrpld.preset %{buildroot}%{_presetdir}/50- # Logrotate config install -Dm0644 %{_sourcedir}/xrpld.logrotate %{buildroot}%{_sysconfdir}/logrotate.d/%{name} -# Update helper -install -Dm0755 %{_sourcedir}/update-xrpld %{buildroot}%{_libexecdir}/%{name}/update-xrpld - # Docs install -Dm0644 %{_sourcedir}/LICENSE.md %{buildroot}%{_docdir}/%{name}/LICENSE.md install -Dm0644 %{_sourcedir}/README.md %{buildroot}%{_docdir}/%{name}/README.md @@ -61,10 +56,10 @@ ln -s %{_bindir}/%{name} %{buildroot}/usr/local/bin/rippled %post systemd-tmpfiles --create %{_tmpfilesdir}/xrpld.conf || : -%systemd_post xrpld.service update-xrpld.timer +%systemd_post xrpld.service %preun -%systemd_preun xrpld.service update-xrpld.timer +%systemd_preun xrpld.service %postun %systemd_postun_with_restart xrpld.service @@ -74,7 +69,6 @@ systemd-tmpfiles --create %{_tmpfilesdir}/xrpld.conf || : %doc %{_docdir}/%{name}/README.md %dir %{_sysconfdir}/%{name} -%dir %{_libexecdir}/%{name} %{_bindir}/%{name} @@ -82,18 +76,13 @@ systemd-tmpfiles --create %{_tmpfilesdir}/xrpld.conf || : %config(noreplace) %{_sysconfdir}/%{name}/validators.txt %config(noreplace) %{_sysconfdir}/logrotate.d/%{name} -%{_libexecdir}/%{name}/update-xrpld %{_unitdir}/xrpld.service -%{_unitdir}/update-xrpld.service -%{_unitdir}/update-xrpld.timer %{_presetdir}/50-xrpld.preset %{_sysusersdir}/xrpld.conf %{_tmpfilesdir}/xrpld.conf - -%ghost %dir /var/lib/%{name} -%ghost %dir /var/log/%{name} - +%ghost %dir /var/lib/xrpld +%ghost %dir /var/log/xrpld # Legacy compatibility for pre-FHS package layouts. # TODO: remove after rippled fully deprecated. diff --git a/package/shared/50-xrpld.preset b/package/shared/50-xrpld.preset index 6264e00131..bfbcd56577 100644 --- a/package/shared/50-xrpld.preset +++ b/package/shared/50-xrpld.preset @@ -1,4 +1,2 @@ # /usr/lib/systemd/system-preset/50-xrpld.preset enable xrpld.service -# Don't enable automatic updates -disable update-xrpld.timer diff --git a/package/shared/update-xrpld b/package/shared/update-xrpld deleted file mode 100755 index 4bd4db2538..0000000000 --- a/package/shared/update-xrpld +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -# Optional: also write logs to a legacy file in addition to journald. -# By default, this script logs to systemd/journald, viewable via: -# journalctl -t update-xrpld -# -# Uncomment the line below if you need a flat file for compatibility with -# external tooling, manual inspection, or environments where journald logs -# are not persisted or easily accessible. -# -# Note: This duplicates all output (stdout/stderr) to both journald and the file. -# It is generally not needed on modern systems and may cause log file growth -# if left enabled long-term. -# -# Requires /var/log/xrpld/ to exist and be writable by the service (root). -# -# exec > >(tee -a /var/log/xrpld/update.log) 2>&1 - -PATH=/usr/sbin:/usr/bin:/sbin:/bin - -PKG_NAME=${PKG_NAME:-xrpld} - -log() { - # If running under systemd/journald, let it handle timestamps. - if [[ -n "${JOURNAL_STREAM:-}" ]]; then - printf '%s\n' "$*" - else - printf '%s %s\n' "$(date -u +'%Y-%m-%dT%H:%M:%SZ')" "$*" - fi -} - -require_root() { - if [[ ${EUID:-$(id -u)} -ne 0 ]]; then - log "RESULT: failed reason=not-root" - exit 1 - fi -} - -get_installed_version() { - if command -v dpkg-query >/dev/null 2>&1; then - dpkg-query -W -f='${Version}' "$PKG_NAME" 2>/dev/null || printf 'unknown' - elif command -v rpm >/dev/null 2>&1; then - rpm -q --qf '%{VERSION}-%{RELEASE}' "$PKG_NAME" 2>/dev/null || printf 'unknown' - else - printf 'unknown' - fi -} - -trap 'log "RESULT: failed reason=script-error exit_code=$?"' ERR - -apt_can_update() { - apt-get update -qq - apt-get -s --only-upgrade install "$PKG_NAME" 2>/dev/null | grep -q "^Inst ${PKG_NAME}\b" -} - -apt_apply_update() { - DEBIAN_FRONTEND=noninteractive apt-get install -y -qq \ - -o Dpkg::Options::="--force-confdef" \ - -o Dpkg::Options::="--force-confold" \ - "$PKG_NAME" -} - -get_rpm_pm() { - if command -v dnf >/dev/null 2>&1; then - printf 'dnf\n' - elif command -v yum >/dev/null 2>&1; then - printf 'yum\n' - else - return 1 - fi -} - -rpm_refresh_metadata() { - local pm=$1 - if [[ "$pm" == "dnf" ]]; then - dnf makecache --refresh -q >/dev/null - else - yum clean expire-cache -q >/dev/null - fi -} - -rpm_can_update() { - local pm=$1 - - rpm_refresh_metadata "$pm" - local rc=0 - set +e - "$pm" check-update -q "$PKG_NAME" >/dev/null 2>&1 - rc=$? - set -e - - if [[ $rc -eq 100 ]]; then - return 0 - elif [[ $rc -eq 0 ]]; then - return 1 - else - log "$pm check-update failed with exit code ${rc}." - exit 1 - fi -} - -rpm_apply_update() { - local pm=$1 - "$pm" update -y "$PKG_NAME" -} - -restart_service() { - # Preserve the operator's prior service state: if xrpld was intentionally - # stopped before the update, don't bring it back up just because the - # auto-update timer fired. - if systemctl is-active --quiet "${PKG_NAME}.service"; then - systemctl restart "${PKG_NAME}.service" - log "${PKG_NAME} service restarted successfully." - else - log "${PKG_NAME} service was not running; skipping restart to preserve prior state." - fi -} - -main() { - require_root - if command -v apt-get >/dev/null 2>&1; then - log "Checking for ${PKG_NAME} updates via apt" - if apt_can_update; then - log "Update available; installing." - apt_apply_update - restart_service - log "RESULT: updated ${PKG_NAME}=$(get_installed_version)" - else - log "RESULT: no-update ${PKG_NAME}=$(get_installed_version)" - fi - return - fi - - local rpm_pm="" - if rpm_pm="$(get_rpm_pm)"; then - log "Checking for ${PKG_NAME} updates via ${rpm_pm}" - if rpm_can_update "$rpm_pm"; then - log "Update available; installing" - rpm_apply_update "$rpm_pm" - restart_service - log "RESULT: updated ${PKG_NAME}=$(get_installed_version)" - else - log "RESULT: no-update ${PKG_NAME}=$(get_installed_version)" - fi - return - fi - log "RESULT: failed reason=no-package-manager" - exit 1 -} - -main "$@" diff --git a/package/shared/update-xrpld.service b/package/shared/update-xrpld.service deleted file mode 100644 index a964ca5482..0000000000 --- a/package/shared/update-xrpld.service +++ /dev/null @@ -1,16 +0,0 @@ -[Unit] -Description=Check for and install xrpld package updates -Documentation=man:systemd.service(5) -Wants=network-online.target -After=network-online.target -ConditionPathExists=/usr/libexec/xrpld/update-xrpld -ConditionPathExists=/usr/bin/xrpld - -[Service] -Type=oneshot -ExecStart=/usr/bin/flock -n /run/lock/xrpld-update.lock /usr/libexec/xrpld/update-xrpld -StandardOutput=journal -StandardError=journal -SyslogIdentifier=update-xrpld -TimeoutStartSec=30min -PrivateTmp=true diff --git a/package/shared/update-xrpld.timer b/package/shared/update-xrpld.timer deleted file mode 100644 index 21dabf1400..0000000000 --- a/package/shared/update-xrpld.timer +++ /dev/null @@ -1,10 +0,0 @@ -[Unit] -Description=Daily xrpld update check - -[Timer] -OnCalendar=*-*-* 00:00:00 -RandomizedDelaySec=24h -Persistent=true - -[Install] -WantedBy=timers.target diff --git a/package/shared/xrpld.service b/package/shared/xrpld.service index 72b6cc9938..0dd4e3a791 100644 --- a/package/shared/xrpld.service +++ b/package/shared/xrpld.service @@ -17,6 +17,8 @@ PrivateTmp=true User=xrpld Group=xrpld LimitNOFILE=65536 +CapabilityBoundingSet=CAP_NET_BIND_SERVICE +SystemCallArchitectures=native [Install] WantedBy=multi-user.target From e833e8884d01bdf5f1088215a4709c5b3d3b4aae Mon Sep 17 00:00:00 2001 From: Valentin Balaschenko <13349202+vlntb@users.noreply.github.com> Date: Wed, 3 Jun 2026 20:29:09 +0100 Subject: [PATCH 51/78] refactor: Revert "Explicitly trim the heap after cache sweeps (#6022)" --- src/xrpld/app/main/Application.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index 508dfc8590..15522b9806 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -43,7 +43,6 @@ #include #include #include -#include #include #include #include @@ -1088,8 +1087,6 @@ public: << "; size after: " << cachedSLEs_.size(); } - mallocTrim("doSweep", journal_); - // Set timer to do another sweep later. setSweepTimer(); } From fded06652ad3d85977e36af903548425e8ff8094 Mon Sep 17 00:00:00 2001 From: yinyiqian1 Date: Wed, 3 Jun 2026 15:57:34 -0400 Subject: [PATCH 52/78] fix: Add zero NFT Offer ID check for NFTokenCancelOffer --- .../tx/transactors/nft/NFTokenCancelOffer.cpp | 11 +++++++++-- src/test/app/NFToken_test.cpp | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/libxrpl/tx/transactors/nft/NFTokenCancelOffer.cpp b/src/libxrpl/tx/transactors/nft/NFTokenCancelOffer.cpp index 924dc49269..e00cd53685 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenCancelOffer.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenCancelOffer.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -23,8 +24,14 @@ namespace xrpl { NotTEC NFTokenCancelOffer::preflight(PreflightContext const& ctx) { - if (auto const& ids = ctx.tx[sfNFTokenOffers]; - ids.empty() || (ids.size() > kMaxTokenOfferCancelCount)) + auto const& offerIds = ctx.tx[sfNFTokenOffers]; + + if (offerIds.empty() || (offerIds.size() > kMaxTokenOfferCancelCount)) + return temMALFORMED; + + // Zero offer IDs cannot be passed as ledger entry keys. + if (ctx.rules.enabled(fixCleanup3_2_0) && + std::ranges::any_of(offerIds, [](uint256 const& id) { return id.isZero(); })) return temMALFORMED; // In order to prevent unnecessarily overlarge transactions, we diff --git a/src/test/app/NFToken_test.cpp b/src/test/app/NFToken_test.cpp index ebd470ec92..269bc72c53 100644 --- a/src/test/app/NFToken_test.cpp +++ b/src/test/app/NFToken_test.cpp @@ -892,6 +892,25 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite BEAST_EXPECT(ownerCount(env, buyer) == 1); } + // Only test this with fixCleanup3_2_0 enabled. Without the fix, + // an assert-enabled build can crash when Ledger::read() receives + // a zero-key offer ID. + if (features[fixCleanup3_2_0]) + { + // Zero is not a valid offer ID. + env(token::cancelOffer(buyer, {uint256{}}), Ter(temMALFORMED)); + env.close(); + BEAST_EXPECT(ownerCount(env, buyer) == 1); + + // List of offer IDs containing zero is invalid. + // craftedIndex is not a valid offer index but it is not zero. + auto const craftedIndex = keylet::nftoffer(gw, env.seq(gw)).key; + env(token::cancelOffer(buyer, {buyerOfferIndex, uint256{}, craftedIndex}), + Ter(temMALFORMED)); + env.close(); + BEAST_EXPECT(ownerCount(env, buyer) == 1); + } + // List of tokens to delete is too long. { std::vector const offers(kMaxTokenOfferCancelCount + 1, buyerOfferIndex); From 61dae6f79249a829b9204ba323250324c36ea273 Mon Sep 17 00:00:00 2001 From: Bart Date: Wed, 3 Jun 2026 16:18:08 -0400 Subject: [PATCH 53/78] release: Bump version to 3.2.0-rc5 --- src/libxrpl/protocol/BuildInfo.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libxrpl/protocol/BuildInfo.cpp b/src/libxrpl/protocol/BuildInfo.cpp index e81be00920..ab83236bb5 100644 --- a/src/libxrpl/protocol/BuildInfo.cpp +++ b/src/libxrpl/protocol/BuildInfo.cpp @@ -23,7 +23,7 @@ namespace { //------------------------------------------------------------------------------ // clang-format off // NOLINTNEXTLINE(readability-identifier-naming) -char const* const versionString = "3.2.0-rc4" +char const* const versionString = "3.2.0-rc5" // clang-format on ; From 96d0563ea644ba5bb28e08e37dc7752d05a204fb Mon Sep 17 00:00:00 2001 From: Michael Legleux Date: Thu, 4 Jun 2026 16:23:33 -0700 Subject: [PATCH 54/78] fix: Adjust xrpld systemd service --- package/shared/xrpld.service | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/package/shared/xrpld.service b/package/shared/xrpld.service index 0dd4e3a791..7f3496acbb 100644 --- a/package/shared/xrpld.service +++ b/package/shared/xrpld.service @@ -2,14 +2,15 @@ Description=XRP Ledger Daemon After=network-online.target Wants=network-online.target -StartLimitIntervalSec=300 +StartLimitIntervalSec=5min StartLimitBurst=5 [Service] Type=simple ExecStart=/usr/bin/xrpld --net --silent --conf /etc/xrpld/xrpld.cfg -Restart=always +Restart=on-failure RestartSec=5s +TimeoutStopSec=5min NoNewPrivileges=true ProtectSystem=full ProtectHome=true @@ -17,8 +18,11 @@ PrivateTmp=true User=xrpld Group=xrpld LimitNOFILE=65536 -CapabilityBoundingSet=CAP_NET_BIND_SERVICE SystemCallArchitectures=native +# Uncomment both lines to allow xrpld to bind to privileged ports (<1024) +#CapabilityBoundingSet=CAP_NET_BIND_SERVICE +#AmbientCapabilities=CAP_NET_BIND_SERVICE + [Install] WantedBy=multi-user.target From e5785c4fcbf45eb9fb80c87a2b19831badd791c1 Mon Sep 17 00:00:00 2001 From: Ed Hennis Date: Fri, 5 Jun 2026 15:57:23 -0400 Subject: [PATCH 55/78] fix: Fix Number comparison operator --- 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 781ef175c9e0826f12da0e8d9557eeb68c5c516a Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Fri, 5 Jun 2026 22:23:41 +0200 Subject: [PATCH 56/78] perf: Dispatch "hasInvalidAmount()" on type tag instead of dynamic_cast --- src/libxrpl/protocol/STAmount.cpp | 32 ++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index 1ba9cd042f..ddb2be29cf 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -1250,16 +1250,34 @@ hasInvalidAmount(STBase const& field, int depth, beast::Journal j) return true; } - if (auto const amount = dynamic_cast(&field)) - return !isLegalMPT(*amount) || !isLegalNet(*amount); + // Dispatch on the serialized type tag rather than RTTI: this is on the invariant-checking path + // and a dynamic_cast chain over every field of every modified entry is measurably expensive. + // The object-like tags below all denote STObject subclasses (STLedgerEntry, STTx), so the + // downcast is sound; nested fields are only ever plain STI_OBJECT / STI_ARRAY containers. + // safeDowncast keeps a dynamic_cast validity assert in debug builds while compiling to + // static_cast in release. + switch (field.getSType()) + { + case STI_AMOUNT: { + auto const& amount = safeDowncast(field); + return !isLegalMPT(amount) || !isLegalNet(amount); + } - if (auto const object = dynamic_cast(&field)) - return hasInvalidAmount(*object, depth + 1, j); + case STI_OBJECT: + case STI_LEDGERENTRY: + case STI_TRANSACTION: + return hasInvalidAmount(safeDowncast(field), depth + 1, j); - if (auto const array = dynamic_cast(&field)) - return hasInvalidAmount(*array, depth + 1, j); + case STI_ARRAY: + return hasInvalidAmount(safeDowncast(field), depth + 1, j); - return false; + default: { + XRPL_ASSERT( + dynamic_cast(&field) == nullptr, + "xrpl::hasInvalidAmount : valid object type"); + return false; + } + } } bool From ed5f13481a444380e7821d98d2ce73d316a77744 Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Fri, 5 Jun 2026 22:49:49 +0200 Subject: [PATCH 57/78] fix: Disable transaction invariants --- src/libxrpl/tx/Transactor.cpp | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index 28fa059902..1aa7567c6c 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -1173,21 +1173,17 @@ Transactor::checkTransactionInvariants(TER result, XRPAmount fee) [[nodiscard]] TER Transactor::checkInvariants(TER result, XRPAmount fee) { - // Transaction invariants first (more specific). These check post-conditions of the specific - // transaction. If these fail, the transaction's core logic is wrong. - auto const txResult = checkTransactionInvariants(result, fee); - - // Protocol invariants second (broader). These check properties that must hold regardless of - // transaction type. - auto const protoResult = ctx_.checkInvariants(result, fee); - - // Fail if either check failed. tef (fatal) takes priority over tec. - if (protoResult == tefINVARIANT_FAILED) - return tefINVARIANT_FAILED; - if (txResult == tecINVARIANT_FAILED || protoResult == tecINVARIANT_FAILED) - return tecINVARIANT_FAILED; - - return result; + /* + * DISABLED for 3.2.0 — Must be re-introduced for 3.3.0 + * + * Transaction invariants are disabled due to a performance regression: + * the two-pass design (transaction-specific invariants + protocol invariants) + * iterates over modified ledger entries twice per transaction. + * + * Until resolved, only protocol invariants are checked (delegated to ctx_). + * This is safe because all transaction invariants in 3.2.0 are no-ops. + */ + return ctx_.checkInvariants(result, fee); } //------------------------------------------------------------------------------ ApplyResult From 0ac8e6cf1ebf14d9ff1e6df700ce603fae507163 Mon Sep 17 00:00:00 2001 From: Bart Date: Fri, 5 Jun 2026 17:30:12 -0400 Subject: [PATCH 58/78] release: Bump version to 3.2.0-rc6 --- src/libxrpl/protocol/BuildInfo.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libxrpl/protocol/BuildInfo.cpp b/src/libxrpl/protocol/BuildInfo.cpp index ab83236bb5..b704f50813 100644 --- a/src/libxrpl/protocol/BuildInfo.cpp +++ b/src/libxrpl/protocol/BuildInfo.cpp @@ -23,7 +23,7 @@ namespace { //------------------------------------------------------------------------------ // clang-format off // NOLINTNEXTLINE(readability-identifier-naming) -char const* const versionString = "3.2.0-rc5" +char const* const versionString = "3.2.0-rc6" // clang-format on ; From 6b63f0ff614e090c8a782d63591e4b035c7715ab Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 8 Jun 2026 05:37:50 -0400 Subject: [PATCH 59/78] ci: [DEPENDABOT] bump codecov/codecov-action from 6.0.1 to 7.0.0 (#7426) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/reusable-build-test-config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index 31457bb892..4163e17779 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -324,7 +324,7 @@ jobs: - name: Upload coverage report if: ${{ github.repository == 'XRPLF/rippled' && !inputs.build_only && env.COVERAGE_ENABLED == 'true' }} - uses: codecov/codecov-action@e79a6962e0d4c0c17b229090214935d2e33f8354 # v6.0.1 + uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 with: disable_search: true disable_telem: true From 3c43f4614f87965298773279ff5b85d4c56c637b Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Mon, 15 Jun 2026 22:19:38 +0100 Subject: [PATCH 60/78] release: Bump version to 3.2.0 --- src/libxrpl/protocol/BuildInfo.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libxrpl/protocol/BuildInfo.cpp b/src/libxrpl/protocol/BuildInfo.cpp index b704f50813..c488bb20de 100644 --- a/src/libxrpl/protocol/BuildInfo.cpp +++ b/src/libxrpl/protocol/BuildInfo.cpp @@ -23,7 +23,7 @@ namespace { //------------------------------------------------------------------------------ // clang-format off // NOLINTNEXTLINE(readability-identifier-naming) -char const* const versionString = "3.2.0-rc6" +char const* const versionString = "3.2.0" // clang-format on ; From 0364e4dc4197cf8be2ac84ea8acdc438b72ad17e Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Tue, 16 Jun 2026 14:24:12 +0100 Subject: [PATCH 61/78] docs: Rewrite build environment docs (#7533) Co-authored-by: Ed Hennis --- .github/scripts/strategy-matrix/linux.json | 6 +- .github/workflows/build-nix-images.yml | 8 + .github/workflows/publish-docs.yml | 2 +- .../workflows/reusable-build-test-config.yml | 5 + .github/workflows/reusable-clang-tidy.yml | 2 +- .github/workflows/reusable-upload-recipe.yml | 2 +- BUILD.md | 391 ++++-------------- CONTRIBUTING.md | 16 +- bin/check-tools.sh | 158 +++++++ {nix/docker => bin}/install-sanitizer-libs.sh | 0 cspell.config.yaml | 1 + docs/build/advanced_conan.md | 193 +++++++++ docs/build/conan.md | 2 +- docs/build/environment.md | 162 +++----- docs/build/nix.md | 45 +- docs/build/nix_troubleshooting.md | 61 +++ nix/docker/Dockerfile | 4 +- nix/docker/README.md | 90 ++++ nix/docker/check-tools.sh | 39 -- 19 files changed, 710 insertions(+), 477 deletions(-) create mode 100755 bin/check-tools.sh rename {nix/docker => bin}/install-sanitizer-libs.sh (100%) create mode 100644 docs/build/advanced_conan.md create mode 100644 docs/build/nix_troubleshooting.md create mode 100644 nix/docker/README.md delete mode 100755 nix/docker/check-tools.sh diff --git a/.github/scripts/strategy-matrix/linux.json b/.github/scripts/strategy-matrix/linux.json index 4f45216cda..a9b85b766a 100644 --- a/.github/scripts/strategy-matrix/linux.json +++ b/.github/scripts/strategy-matrix/linux.json @@ -1,5 +1,5 @@ { - "image_tag": "sha-63ffdc3", + "image_tag": "sha-fe4c8ae", "configs": { "ubuntu": [ { @@ -68,7 +68,7 @@ "compiler": ["gcc"], "build_type": ["Release"], "arch": ["amd64"], - "image": "ghcr.io/xrplf/xrpld/packaging-debian:sha-63ffdc3" + "image": "ghcr.io/xrplf/xrpld/packaging-debian:sha-577d745" } ], @@ -77,7 +77,7 @@ "compiler": ["gcc"], "build_type": ["Release"], "arch": ["amd64"], - "image": "ghcr.io/xrplf/xrpld/packaging-rhel:sha-63ffdc3" + "image": "ghcr.io/xrplf/xrpld/packaging-rhel:sha-577d745" } ] } diff --git a/.github/workflows/build-nix-images.yml b/.github/workflows/build-nix-images.yml index 24f069902d..3af6a3b1d4 100644 --- a/.github/workflows/build-nix-images.yml +++ b/.github/workflows/build-nix-images.yml @@ -9,12 +9,20 @@ on: - "flake.nix" - "flake.lock" - "nix/**" + - "!nix/docker/README.md" + - "!nix/devshell.nix" + - "bin/check-tools.sh" + - "bin/install-sanitizer-libs.sh" pull_request: paths: - ".github/workflows/build-nix-images.yml" - "flake.nix" - "flake.lock" - "nix/**" + - "!nix/docker/README.md" + - "!nix/devshell.nix" + - "bin/check-tools.sh" + - "bin/install-sanitizer-libs.sh" workflow_dispatch: concurrency: diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index bcf5968384..0de5347aab 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -41,7 +41,7 @@ env: jobs: build: runs-on: ubuntu-latest - container: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-63ffdc3 + container: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-fe4c8ae steps: - name: Checkout repository uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index 28d317e4dd..95e6b0cbe2 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -121,6 +121,11 @@ jobs: if: ${{ inputs.ccache_enabled && runner.debug == '1' }} run: echo "CCACHE_LOGFILE=${{ runner.temp }}/ccache.log" >>"${GITHUB_ENV}" + - name: Check tools + env: + CHECK_TOOLS_SKIP_CLONE: "1" + run: ./bin/check-tools.sh + - name: Print build environment uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574 diff --git a/.github/workflows/reusable-clang-tidy.yml b/.github/workflows/reusable-clang-tidy.yml index 9f10711b6f..34fa860e12 100644 --- a/.github/workflows/reusable-clang-tidy.yml +++ b/.github/workflows/reusable-clang-tidy.yml @@ -36,7 +36,7 @@ jobs: needs: [determine-files] if: ${{ always() && !cancelled() && (!inputs.check_only_changed || needs.determine-files.outputs.cpp_changed_files != '' || needs.determine-files.outputs.clang_tidy_config_changed == 'true') }} runs-on: ["self-hosted", "Linux", "X64", "heavy"] - container: "ghcr.io/xrplf/xrpld/nix-debian:sha-63ffdc3" + container: "ghcr.io/xrplf/xrpld/nix-debian:sha-fe4c8ae" permissions: contents: read issues: write diff --git a/.github/workflows/reusable-upload-recipe.yml b/.github/workflows/reusable-upload-recipe.yml index 1c90fb0e72..ba7a0943d9 100644 --- a/.github/workflows/reusable-upload-recipe.yml +++ b/.github/workflows/reusable-upload-recipe.yml @@ -40,7 +40,7 @@ defaults: jobs: upload: runs-on: ubuntu-latest - container: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-63ffdc3 + container: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-fe4c8ae steps: - name: Checkout repository uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 diff --git a/BUILD.md b/BUILD.md index 662ba0d33d..2ac24f2c5d 100644 --- a/BUILD.md +++ b/BUILD.md @@ -1,26 +1,57 @@ -| :warning: **WARNING** :warning: | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| These instructions assume you have a C++ development environment ready with Git, Python, Conan, CMake, and a C++ compiler. For help setting one up on Linux, macOS, or Windows, [see this guide](./docs/build/environment.md). | +| :warning: **WARNING** :warning: | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| These instructions assume you have a C++ development environment ready with Git, Python, Conan, CMake, and a C++ compiler. For help setting one up on Linux, macOS, or Windows, [see this guide](./docs/build/environment.md).

These instructions also assume a basic familiarity with Conan and CMake. If you are unfamiliar with Conan, you can read our [crash course](./docs/build/conan.md) or the official [Getting Started][conan-getting-started] walkthrough. | -> These instructions also assume a basic familiarity with Conan and CMake. -> If you are unfamiliar with Conan, you can read our -> [crash course](./docs/build/conan.md) or the official [Getting Started][3] -> walkthrough. +## Minimum Requirements -## Branches +See [System Requirements](https://xrpl.org/system-requirements.html). -For a stable release, choose the `master` branch or one of the [tagged -releases](https://github.com/XRPLF/rippled/releases). +Building xrpld generally requires Git, Python, Conan, CMake, and a C++ +compiler. + +- [Python](https://www.python.org/downloads/) +- [Conan](https://conan.io/downloads.html) +- [CMake](https://cmake.org/download/) + +You can verify that the required tools are installed and runnable with: ```bash -git checkout master +./bin/check-tools.sh ``` -For the latest release candidate, choose the `release` branch. +`xrpld` is written in the C++23 dialect. The [tested compiler versions][cpp23-support] are: -```bash -git checkout release -``` +| Compiler | Version | +| ----------- | --------------- | +| GCC | 15.2 | +| Clang | 22 | +| Apple Clang | 17 | +| MSVC | 19.44[^windows] | + +## Operating Systems + +Please see the [environment setup guide](./docs/build/environment.md) for detailed instructions for all platforms. + +### Linux + +The Ubuntu Linux distribution has received the highest level of quality +assurance, testing, and support. We also support Red Hat and use Debian +internally. +Our Linux CI tooling is distro-independent and uses a Nix-based environment, so it should be possible to build on other Linux distributions as well, although we have not tested them. + +### macOS + +Many `xrpld` engineers use macOS for development. + +### Windows + +Windows is used by some engineers for development only. + +[^windows]: Windows is not recommended for production use. + +## Steps + +### Branches For the latest set of untested features, or to contribute, choose the `develop` branch. @@ -29,55 +60,15 @@ branch. git checkout develop ``` -## Minimum Requirements +For a release candidate, choose the relevant release branch, e.g. +`release/3.2.x`. -See [System Requirements](https://xrpl.org/system-requirements.html). +```bash +git checkout release/3.2.x +``` -Building xrpld generally requires git, Python, Conan, CMake, and a C++ -compiler. Some guidance on setting up such a [C++ development environment can be -found here](./docs/build/environment.md). - -- [Python 3.11](https://www.python.org/downloads/), or higher -- [Conan 2.17](https://conan.io/downloads.html)[^1], or higher -- [CMake 3.22](https://cmake.org/download/), or higher - -[^1]: - 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++23 dialect and includes the `` header. -The [tested compiler versions][2] are: - -| Compiler | Version | -| ----------- | --------- | -| GCC | 15 | -| Clang | 22 | -| Apple Clang | 17 | -| MSVC | 19.44[^3] | - -### Linux - -The Ubuntu Linux distribution has received the highest level of quality -assurance, testing, and support. We also support Red Hat and use Debian -internally. - -Here are [sample instructions for setting up a C++ development environment on -Linux](./docs/build/environment.md#linux). - -### Mac - -Many xrpld engineers use macOS for development. - -Here are [sample instructions for setting up a C++ development environment on -macOS](./docs/build/environment.md#macos). - -### Windows - -Windows is used by some engineers for development only. - -[^3]: Windows is not recommended for production use. - -## Steps +For a stable release, choose one of the [tagged +releases](https://github.com/XRPLF/rippled/releases). ### Set Up Conan @@ -86,18 +77,11 @@ Conan, CMake, and a C++ compiler, you may need to set up your Conan profile. These instructions assume a basic familiarity with Conan and CMake. If you are unfamiliar with Conan, then please read [this crash course](./docs/build/conan.md) or the official -[Getting Started][3] walkthrough. +[Getting Started][conan-getting-started] walkthrough. -#### Conan lockfile +#### Profiles -To achieve reproducible dependencies, we use a [Conan lockfile](https://docs.conan.io/2/tutorial/versioning/lockfiles.html), -which has to be updated every time dependencies change. - -Please see the [instructions on how to regenerate the lockfile](conan/lockfile/README.md). - -#### Default profile - -We recommend that you import the provided `conan/profiles/default` profile: +We recommend that you install our Conan profiles: ```bash conan config install conan/profiles/ -tf $(conan config home)/profiles/ @@ -109,222 +93,15 @@ You can check your Conan profile by running: conan profile show ``` -#### Custom profile +If the default profile is not suitable for your environment, you can create a custom profile and pass it to Conan. +More information on customizing Conan can be found in the [Advanced Conan configuration](./docs/build/advanced_conan.md). -If the default profile does not work for you and you do not yet have a Conan -profile, you can create one by running: +#### Add xrplf remote + +Run the following command to add the `xrplf` remote, which hosts some of our dependencies: ```bash -conan profile detect -``` - -You may need to make changes to the profile to suit your environment. You can -refer to the provided `conan/profiles/default` profile for inspiration, and you -may also need to apply the required [tweaks](#conan-profile-tweaks) to this -default profile. - -### Patched recipes - -Occasionally, we need patched recipes or recipes not present in Conan Center. -We maintain a fork of the Conan Center Index -[here](https://github.com/XRPLF/conan-center-index/) containing the modified and newly added recipes. - -To ensure our patched recipes are used, you must add our Conan remote at a -higher index than the default Conan Center remote, so it is consulted first. You -can do this by running: - -```bash -conan remote add --index 0 xrplf https://conan.ripplex.io -``` - -Alternatively, you can pull our recipes from the repository and export them locally: - -```bash -# Define which recipes to export. -recipes=('abseil' 'ed25519' 'mpt-crypto' 'openssl' 'secp256k1' 'snappy' 'soci' 'wasm-xrplf' 'wasmi') - -# Selectively check out the recipes from our CCI fork. -cd external -mkdir -p conan-center-index -cd conan-center-index -git init -git remote add origin git@github.com:XRPLF/conan-center-index.git -git sparse-checkout init -for recipe in "${recipes[@]}"; do - echo "Checking out recipe '${recipe}'..." - git sparse-checkout add recipes/${recipe} -done -git fetch origin master -git checkout master - -./export_all.sh -cd ../../ -``` - -In the case we switch to a newer version of a dependency that still requires a -patch or add a new dependency, it will be necessary for you to pull in the changes and re-export the -updated dependencies with the newer version. However, if we switch to a newer -version that no longer requires a patch, no action is required on your part, as -the new recipe will be automatically pulled from the official Conan Center. - -> [!NOTE] -> You might need to add `--lockfile=""` to your `conan install` command -> to avoid automatic use of the existing `conan.lock` file when you run -> `conan export` manually on your machine -> -> This is not recommended though, as you might end up using different revisions of recipes. - -### Conan profile tweaks - -#### Missing compiler version - -If you see an error similar to the following after running `conan profile show`: - -```text -ERROR: Invalid setting '17' is not a valid 'settings.compiler.version' value. -Possible values are ['5.0', '5.1', '6.0', '6.1', '7.0', '7.3', '8.0', '8.1', -'9.0', '9.1', '10.0', '11.0', '12.0', '13', '13.0', '13.1', '14', '14.0', '15', -'15.0', '16', '16.0'] -Read "http://docs.conan.io/2/knowledge/faq.html#error-invalid-setting" -``` - -you need to add your compiler to the list of compiler versions in -`$(conan config home)/settings_user.yml`, by adding the required version number(s) -to the `version` array specific for your compiler. For example: - -```yaml -compiler: - apple-clang: - version: ["17.0"] -``` - -#### Multiple compilers - -If you have multiple compilers installed, make sure to select the one to use in -your default Conan configuration **before** running `conan profile detect`, by -setting the `CC` and `CXX` environment variables. - -For example, if you are running MacOS and have [homebrew -LLVM@18](https://formulae.brew.sh/formula/llvm@18), and want to use it as a -compiler in the new Conan profile: - -```bash -export CC=$(brew --prefix llvm@18)/bin/clang -export CXX=$(brew --prefix llvm@18)/bin/clang++ -conan profile detect -``` - -You should also explicitly set the path to the compiler in the profile file, -which helps to avoid errors when `CC` and/or `CXX` are set and disagree with the -selected Conan profile. For example: - -```text -[conf] -tools.build:compiler_executables={'c':'/usr/bin/gcc','cpp':'/usr/bin/g++'} -``` - -#### Multiple profiles - -You can manage multiple Conan profiles in the directory -`$(conan config home)/profiles`, for example renaming `default` to a different -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++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=23|' $(conan config home)/profiles/default -``` - -#### Select standard library in Linux - -**Linux** developers will commonly have a default Conan [profile][] that -compiles with GCC and links with libstdc++. If you are linking with libstdc++ -(see profile setting `compiler.libcxx`), then you will need to choose the -`libstdc++11` ABI: - -```bash -sed -i.bak -e 's|^compiler\.libcxx=.*$|compiler.libcxx=libstdc++11|' $(conan config home)/profiles/default -``` - -#### Select architecture and runtime in Windows - -**Windows** developers may need to use the x64 native build tools. An easy way -to do that is to run the shortcut "x64 Native Tools Command Prompt" for the -version of Visual Studio that you have installed. - -Windows developers must also build `xrpld` and its dependencies for the x64 -architecture: - -```bash -sed -i.bak -e 's|^arch=.*$|arch=x86_64|' $(conan config home)/profiles/default -``` - -**Windows** developers also must select static runtime: - -```bash -sed -i.bak -e 's|^compiler\.runtime=.*$|compiler.runtime=static|' $(conan config home)/profiles/default -``` - -#### Clang workaround for grpc - -If your compiler is clang, version 19 or later, or apple-clang, version 17 or -later, you may encounter a compilation error while building the `grpc` -dependency: - -```text -In file included from .../lib/promise/try_seq.h:26: -.../lib/promise/detail/basic_seq.h:499:38: error: a template argument list is expected after a name prefixed by the template keyword [-Wmissing-template-arg-list-after-template-kw] - 499 | Traits::template CallSeqFactory(f_, *cur_, std::move(arg))); - | ^ -``` - -The workaround for this error is to add two lines to profile: - -```text -[conf] -tools.build:cxxflags=['-Wno-missing-template-arg-list-after-template-kw'] -``` - -#### Workaround for gcc 12 - -If your compiler is gcc, version 12, and you have enabled `werr` option, you may -encounter a compilation error such as: - -```text -/usr/include/c++/12/bits/char_traits.h:435:56: error: 'void* __builtin_memcpy(void*, const void*, long unsigned int)' accessing 9223372036854775810 or more bytes at offsets [2, 9223372036854775807] and 1 may overlap up to 9223372036854775813 bytes at offset -3 [-Werror=restrict] - 435 | return static_cast(__builtin_memcpy(__s1, __s2, __n)); - | ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~ -cc1plus: all warnings being treated as errors -``` - -The workaround for this error is to add two lines to your profile: - -```text -[conf] -tools.build:cxxflags=['-Wno-restrict'] -``` - -#### Workaround for clang 16 - -If your compiler is clang, version 16, you may encounter compilation error such -as: - -```text -In file included from .../boost/beast/websocket/stream.hpp:2857: -.../boost/beast/websocket/impl/read.hpp:695:17: error: call to 'async_teardown' is ambiguous - async_teardown(impl.role, impl.stream(), - ^~~~~~~~~~~~~~ -``` - -The workaround for this error is to add two lines to your profile: - -```text -[conf] -tools.build:cxxflags=['-DBOOST_ASIO_DISABLE_CONCEPTS'] +conan remote add --index 0 --force xrplf https://conan.ripplex.io ``` ### Set Up Ccache @@ -333,14 +110,7 @@ To speed up repeated compilations, we recommend that you install [ccache](https://ccache.dev), a tool that wraps your compiler so that it can cache build objects locally. -#### Linux - -You can install it using the package manager, e.g. `sudo apt install ccache` -(Ubuntu) or `sudo dnf install ccache` (RHEL). - -#### macOS - -You can install it using Homebrew, i.e. `brew install ccache`. +On Linux and macOS, `ccache` is included in the [Nix development shell](./docs/build/nix.md). #### Windows @@ -549,7 +319,7 @@ See [Sanitizers docs](./docs/build/sanitizers.md) for more details. | Option | Default Value | Description | | ---------- | ------------- | -------------------------------------------------------------- | -| `assert` | OFF | Enable assertions. | +| `assert` | OFF | Force enabling assertions. | | `coverage` | OFF | Prepare the coverage report. | | `tests` | OFF | Build tests. | | `unity` | OFF | Configure a unity build. | @@ -557,7 +327,7 @@ See [Sanitizers docs](./docs/build/sanitizers.md) for more details. | `werr` | OFF | Treat compilation warnings as errors | | `wextra` | OFF | Enable additional compilation warnings | -[Unity builds][5] may be faster for the first build (at the cost of much more +[Unity builds][unity-build] may be faster for the first build (at the cost of much more memory) since they concatenate sources into fewer translation units. Non-unity builds may be faster for incremental builds, and can be helpful for detecting `#include` omissions. @@ -583,14 +353,14 @@ After any updates or changes to dependencies, you may need to do the following: conan remove '*' ``` -3. Re-run [conan export](#patched-recipes) if needed. -4. [Regenerate lockfile](#conan-lockfile). +3. Re-run [conan export](./docs/build/advanced_conan.md#patched-recipes) if needed. +4. [Regenerate lockfile](./docs/build/advanced_conan.md#conan-lockfile). 5. Re-run [conan install](#build-and-test). #### ERROR: Package not resolved If you're seeing an error like `ERROR: Package 'snappy/1.1.10' not resolved: Unable to find 'snappy/1.1.10#968fef506ff261592ec30c574d4a7809%1756234314.246' in remotes.`, -please add `xrplf` remote or re-run `conan export` for [patched recipes](#patched-recipes). +please [add `xrplf` remote](#add-xrplf-remote) or re-run `conan export` for [patched recipes](./docs/build/advanced_conan.md#patched-recipes). ### `protobuf/port_def.inc` file not found @@ -610,28 +380,9 @@ For example, if you want to build Debug: 1. For conan install, pass `--settings build_type=Debug` 2. For cmake, pass `-DCMAKE_BUILD_TYPE=Debug` -## Add a Dependency - -If you want to experiment with a new package, follow these steps: - -1. Search for the package on [Conan Center](https://conan.io/center/). -2. Modify [`conanfile.py`](./conanfile.py): - - Add a version of the package to the `requires` property. - - Change any default options for the package by adding them to the - `default_options` property (with syntax `'$package:$option': $value`). -3. Modify [`CMakeLists.txt`](./CMakeLists.txt): - - Add a call to `find_package($package REQUIRED)`. - - Link a library from the package to the target `xrpl_libs` - (search for the existing call to `target_link_libraries(xrpl_libs INTERFACE ...)`). -4. Start coding! Don't forget to include whatever headers you need from the package. - -[1]: https://github.com/conan-io/conan-center-index/issues/13168 -[2]: https://en.cppreference.com/w/cpp/compiler_support/20 -[3]: https://docs.conan.io/en/latest/getting_started.html -[5]: https://en.wikipedia.org/wiki/Unity_build -[6]: https://github.com/boostorg/beast/issues/2648 -[7]: https://github.com/boostorg/beast/issues/2661 +[cpp23-support]: https://en.cppreference.com/w/cpp/compiler_support/23 +[conan-getting-started]: https://docs.conan.io/en/latest/getting_started.html +[unity-build]: https://en.wikipedia.org/wiki/Unity_build [gcovr]: https://gcovr.com/en/stable/getting-started.html [python-pip]: https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/ [build_type]: https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html -[profile]: https://docs.conan.io/en/latest/reference/profiles.html diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 25dd7ac059..fc93223925 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,9 +14,9 @@ The following branches exist in the main project repository: - `develop`: The latest set of unreleased features, and the most common starting point for contributions. -- `release`: The latest beta release or release candidate. -- `master`: The latest stable release. -- `gh-pages`: The documentation for this project, built by Doxygen. +- `release/*` (e.g. `release/3.2.x`): Release branches, one per release line, + holding the latest release candidate, or stable release for that line. + Stable releases are published as [tagged releases](https://github.com/XRPLF/rippled/releases). The tip of each branch must be signed. In order for GitHub to sign a squashed commit that it builds from your pull request, GitHub must know @@ -130,11 +130,9 @@ tl;dr ## Pull requests In general, pull requests use `develop` as the base branch. -The exceptions are -- Fixes and improvements to a release candidate use `release` as the - base. -- Hotfixes use `master` as the base. +The exceptions are fixes, improvements, and hotfixes for an existing release, +which use that release's branch (e.g. `release/3.2.x`) as the base. If your changes are not quite ready, but you want to make it easily available for preliminary examination or review, you can create a "Draft" pull request. @@ -216,7 +214,7 @@ coherent rather than a set of _thou shalt not_ commandments. ## Formatting -All code must conform to `clang-format` version 21, +All code must conform to `clang-format` version 22, according to the settings in [`.clang-format`](./.clang-format), unless the result would be unreasonably difficult to read or maintain. To demarcate lines that should be left as-is, surround them with comments like @@ -261,7 +259,7 @@ This ensures that configuration changes don't introduce new warnings across the ### Installing clang-tidy -See the [environment setup guide](./docs/build/environment.md#clang-tidy) for platform-specific installation instructions. +See the [environment setup guide](./docs/build/environment.md#clang-tidy) for how to get clang-tidy. ### Running clang-tidy locally diff --git a/bin/check-tools.sh b/bin/check-tools.sh new file mode 100755 index 0000000000..15b16b6fc8 --- /dev/null +++ b/bin/check-tools.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +# +# check-tools.sh — verify the xrpld development tooling is present and runnable. +# +# Works on Linux, macOS, and Windows (Git Bash / MSYS). For every expected tool +# it runs a version probe, collecting anything that is missing or fails to run, +# and prints a summary at the end (exiting non-zero if anything is missing). +# +# The tool set is platform-aware: +# - Linux: the full Nix CI environment (see nix/packages.nix, nix/ci-env.nix), +# with GCC, Clang and the sanitizer/coverage tooling. This script is +# run during the Nix Docker image build (nix/docker/Dockerfile), so +# the Linux list is kept in sync with that environment. +# - macOS: the same tooling, minus GCC/g++/gcov/mold +# - Windows: the core build tools only (CMake, Conan, Git, Python). +# MSVC is expected to be provided separately and is not checked here. +# +# Some tools (clang-format, doxygen, gcovr, gh, git-cliff, gpg, pre-commit, +# run-clang-tidy) are present in our Linux CI images and in local development +# setups, but not in the macOS CI environment. They are checked everywhere +# except when running in CI on macOS. +# +# Environment variables: +# CI if set, skip the tools above when on macOS. +# CHECK_TOOLS_SKIP_CLONE if set, skip the git-over-HTTPS connectivity check. + +set -uo pipefail + +missing=() +checked=0 + +# check [probe-command...] +# Runs the probe (default: " --version") quietly. Records as +# missing if the command is not found or exits non-zero. +check() { + local name="$1" + shift + local -a probe=("$@") + if [ "${#probe[@]}" -eq 0 ]; then + probe=("${name}" --version) + fi + + echo "Checking ${name}..." + checked=$((checked + 1)) + if "${probe[@]}" | head -n 1; then + printf ' [ ok ] %s\n' "${name}" + else + printf ' [MISS] %s\n' "${name}" + missing+=("${name}") + fi +} + +case "$(uname -s)" in + Linux*) os=linux ;; + Darwin*) os=macos ;; + MINGW* | MSYS* | CYGWIN*) os=windows ;; + *) + echo "Unknown OS: $(uname -s)" >&2 + exit 1 + ;; +esac + +echo "Detected OS: ${os} ($(uname -s) $(uname -m))" +echo +echo "Core build tools:" +check cmake +check conan +check git +if [ "${os}" = "windows" ]; then + check python python --version +else + check python3 +fi + +# The full development toolchain. Available from Nix on Linux and macOS; on +# Windows these are typically not installed, so they are skipped. +if [ "${os}" = "linux" ] || [ "${os}" = "macos" ]; then + echo + echo "Development tooling:" + check ccache + check clang + check clang++ + check ClangBuildAnalyzer + check curl + check file + check less + check make + check netstat which netstat + check ninja + check perl + check pkg-config + check vim + + # These tools are present in our Linux CI images and in local development + # setups, but not in the macOS CI environment. So check them everywhere + # except when running in CI on macOS. + if [ "${os}" = "linux" ] || [ -z "${CI:-}" ]; then + check clang-format + check doxygen + check gcovr + check gh + check git-cliff + check gpg + # pre-commit, or its alternative implementation prek + check pre-commit sh -c 'pre-commit --version || prek --version' + check run-clang-tidy run-clang-tidy --help + fi +fi + +# GCC is the default compiler on Linux. macOS uses the system Apple Clang +# instead, so GCC/g++/gcov are not expected there. +if [ "${os}" = "linux" ]; then + echo + echo "GCC toolchain:" + check gcc + check g++ + check gcov + + echo + echo "Mold:" + check mold +fi + +if [ "${os}" = "windows" ]; then + echo + echo "Note: on Windows the C++ compiler is MSVC, which is provided" + echo " separately (e.g. via Visual Studio) and is not checked here." +fi + +# A simple test to verify that git can clone a repository over HTTPS +# (i.e. the CA bundle is wired up). Clone to a temp dir and clean up. +if [ -n "${CHECK_TOOLS_SKIP_CLONE:-}" ]; then + echo + echo "Skipping git-over-HTTPS check (CHECK_TOOLS_SKIP_CLONE is set)." +else + echo + echo "Connectivity check:" + checked=$((checked + 1)) + tmp_clone="$(mktemp -d)" + if git clone --depth 1 https://github.com/XRPLF/actions.git "${tmp_clone}/actions" >/dev/null 2>&1; then + printf ' [ ok ] git clone over HTTPS\n' + else + printf ' [MISS] git clone over HTTPS\n' + missing+=("git-https-clone") + fi + rm -rf "${tmp_clone}" +fi + +echo +if [ "${#missing[@]}" -eq 0 ]; then + echo "All ${checked} checked tools are present and runnable." +else + echo "Missing or non-functional tools (${#missing[@]} of ${checked}):" >&2 + for tool in "${missing[@]}"; do + echo " - ${tool}" >&2 + done + exit 1 +fi diff --git a/nix/docker/install-sanitizer-libs.sh b/bin/install-sanitizer-libs.sh similarity index 100% rename from nix/docker/install-sanitizer-libs.sh rename to bin/install-sanitizer-libs.sh diff --git a/cspell.config.yaml b/cspell.config.yaml index 77f0e9df7a..0d38c4be7b 100644 --- a/cspell.config.yaml +++ b/cspell.config.yaml @@ -109,6 +109,7 @@ words: - enabled - enablerepo - endmacro + - envrc - exceptioned - EXPECT_STREQ - Falco diff --git a/docs/build/advanced_conan.md b/docs/build/advanced_conan.md new file mode 100644 index 0000000000..aae17e385a --- /dev/null +++ b/docs/build/advanced_conan.md @@ -0,0 +1,193 @@ +# Advanced Conan configuration + +This document provides advanced instructions for setting up and configuring Conan for `xrpld` development: custom profiles, the lockfile, patched recipes, and profile tweaks. + +## Custom profile + +If the default profile does not work for you and you do not yet have a Conan +profile, you can create one by running: + +```bash +conan profile detect +``` + +You may need to make changes to the profile to suit your environment. You can +refer to the provided `conan/profiles/default` profile for inspiration, and you +may also need to apply the required [tweaks](#conan-profile-tweaks) to this +default profile. + +## Conan lockfile + +To achieve reproducible dependencies, we use a [Conan lockfile](https://docs.conan.io/2/tutorial/versioning/lockfiles.html), +which has to be updated every time dependencies change. + +Please see the [instructions on how to regenerate the lockfile](../../conan/lockfile/README.md). + +## Patched recipes + +Occasionally, we need patched recipes or recipes not present in Conan Center. +We maintain a fork of the Conan Center Index +[here](https://github.com/XRPLF/conan-center-index/) containing the modified and newly added recipes. + +To ensure our patched recipes are used, you must add our Conan remote at a +higher index than the default Conan Center remote, so it is consulted first. You +can do this by running: + +```bash +conan remote add --index 0 --force xrplf https://conan.ripplex.io +``` + +Alternatively, you can pull our recipes from the repository and export them locally: + +```bash +# Define which recipes to export. +recipes=('abseil' 'ed25519' 'mpt-crypto' 'openssl' 'secp256k1' 'snappy' 'soci' 'wasm-xrplf' 'wasmi') + +# Selectively check out the recipes from our CCI fork. +cd external +mkdir -p conan-center-index +cd conan-center-index +git init +git remote add origin git@github.com:XRPLF/conan-center-index.git +git sparse-checkout init +for recipe in "${recipes[@]}"; do + echo "Checking out recipe '${recipe}'..." + git sparse-checkout add recipes/${recipe} +done +git fetch origin master +git checkout master + +./export_all.sh +cd ../../ +``` + +In the case we switch to a newer version of a dependency that still requires a +patch or add a new dependency, it will be necessary for you to pull in the changes and re-export the +updated dependencies with the newer version. However, if we switch to a newer +version that no longer requires a patch, no action is required on your part, as +the new recipe will be automatically pulled from the official Conan Center. + +> [!NOTE] +> You might need to add `--lockfile=""` to your `conan install` command +> to avoid automatic use of the existing `conan.lock` file when you run +> `conan export` manually on your machine +> +> This is not recommended though, as you might end up using different revisions of recipes. + +## Conan profile tweaks + +### Missing compiler version + +If you see an error similar to the following after running `conan profile show`: + +```text +ERROR: Invalid setting '17' is not a valid 'settings.compiler.version' value. +Possible values are ['5.0', '5.1', '6.0', '6.1', '7.0', '7.3', '8.0', '8.1', +'9.0', '9.1', '10.0', '11.0', '12.0', '13', '13.0', '13.1', '14', '14.0', '15', +'15.0', '16', '16.0'] +Read "http://docs.conan.io/2/knowledge/faq.html#error-invalid-setting" +``` + +you need to create `$(conan config home)/settings_user.yml` file if it doesn't exist and add the required version number(s) +to the `version` array specific for your compiler. For example: + +```yaml +compiler: + apple-clang: + version: ["17.0"] +``` + +### Multiple compilers + +If you have multiple compilers installed, make sure to select the one to use in +your default Conan configuration **before** running `conan profile detect`, by +setting the `CC` and `CXX` environment variables. + +For example, if you are running MacOS and have [homebrew +LLVM@18](https://formulae.brew.sh/formula/llvm@18), and want to use it as a +compiler in the new Conan profile: + +```bash +export CC=$(brew --prefix llvm@18)/bin/clang +export CXX=$(brew --prefix llvm@18)/bin/clang++ +conan profile detect +``` + +You should also explicitly set the path to the compiler in the profile file, +which helps to avoid errors when `CC` and/or `CXX` are set and disagree with the +selected Conan profile. For example: + +```text +[conf] +tools.build:compiler_executables={'c':'/usr/bin/gcc','cpp':'/usr/bin/g++'} +``` + +### Multiple profiles + +You can manage multiple Conan profiles in the directory +`$(conan config home)/profiles`, for example renaming `default` to a different +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++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=23|' $(conan config home)/profiles/default +``` + +### Select standard library in Linux + +**Linux** developers will commonly have a default Conan [profile][] that +compiles with GCC and links with libstdc++. If you are linking with libstdc++ +(see profile setting `compiler.libcxx`), then you will need to choose the +`libstdc++11` ABI: + +```bash +sed -i.bak -e 's|^compiler\.libcxx=.*$|compiler.libcxx=libstdc++11|' $(conan config home)/profiles/default +``` + +### Select architecture and runtime in Windows + +**Windows** developers may need to use the x64 native build tools. An easy way +to do that is to run the shortcut "x64 Native Tools Command Prompt" for the +version of Visual Studio that you have installed. + +Windows developers must also build `xrpld` and its dependencies for the x64 +architecture: + +```bash +sed -i.bak -e 's|^arch=.*$|arch=x86_64|' $(conan config home)/profiles/default +``` + +**Windows** developers also must select static runtime: + +```bash +sed -i.bak -e 's|^compiler\.runtime=.*$|compiler.runtime=static|' $(conan config home)/profiles/default +``` + +## Add a Dependency + +If you want to experiment with a new package, follow these steps: + +1. Search for the package on [Conan Center](https://conan.io/center/). +2. Modify [`conanfile.py`](../../conanfile.py): + - Add a version of the package to the `requires` property. + - Change any default options for the package by adding them to the + `default_options` property (with syntax `'$package:$option': $value`). +3. Regenerate the [Conan lockfile](../../conan/lockfile/README.md) so the new + dependency is captured: + + ```bash + ./conan/lockfile/regenerate.sh + ``` + +4. Modify [`CMakeLists.txt`](../../CMakeLists.txt): + - Add a call to `find_package($package REQUIRED)`. + - Link a library from the package to the target `xrpl_libs` + (search for the existing call to `target_link_libraries(xrpl_libs INTERFACE ...)`). +5. Start coding! Don't forget to include whatever headers you need from the package. + +[profile]: https://docs.conan.io/2/reference/config_files/profiles.html diff --git a/docs/build/conan.md b/docs/build/conan.md index 9dcd2c8f1c..22c25a0bf9 100644 --- a/docs/build/conan.md +++ b/docs/build/conan.md @@ -115,7 +115,7 @@ By default, Conan will use the profile named "default". [find_package]: https://cmake.org/cmake/help/latest/command/find_package.html [pcf]: https://cmake.org/cmake/help/latest/manual/cmake-packages.7.html#package-configuration-file [prefix_path]: https://cmake.org/cmake/help/latest/variable/CMAKE_PREFIX_PATH.html -[profile]: https://docs.conan.io/en/latest/reference/profiles.html +[profile]: https://docs.conan.io/2/reference/config_files/profiles.html [pvf]: https://cmake.org/cmake/help/latest/manual/cmake-packages.7.html#package-version-file [runtime]: https://cmake.org/cmake/help/latest/variable/CMAKE_MSVC_RUNTIME_LIBRARY.html [search]: https://cmake.org/cmake/help/latest/command/find_package.html#search-procedure diff --git a/docs/build/environment.md b/docs/build/environment.md index fb1ebde8bc..2cca608567 100644 --- a/docs/build/environment.md +++ b/docs/build/environment.md @@ -1,69 +1,73 @@ Our [build instructions][BUILD.md] assume you have a C++ development environment complete with Git, Python, Conan, CMake, and a C++ compiler. -This document exists to help readers set one up on any of the Big Three -platforms: Linux, macOS, or Windows. - -As an alternative to system packages, the Nix development shell can be used to provide a development environment. See [using nix development shell](./nix.md) for more details. +This document explains how to set one up. [BUILD.md]: ../../BUILD.md -## Linux +## Tested compiler versions -Package ecosystems vary across Linux distributions, -so there is no one set of instructions that will work for every Linux user. -The instructions below are written for Debian 12 (Bookworm). +`xrpld` is built in the **C++23** dialect by default. +Make sure your toolchain is recent enough — the compiler versions currently tested in CI are: -``` -export GCC_RELEASE=12 -sudo apt update -sudo apt install --yes gcc-${GCC_RELEASE} g++-${GCC_RELEASE} python3-pip \ - python-is-python3 python3-venv python3-dev curl wget ca-certificates \ - git build-essential cmake ninja-build libc6-dev -sudo pip install --break-system-packages conan +| Compiler | Version | +| ----------- | ------- | +| GCC | 15.2 | +| Clang | 22 | +| Apple Clang | 17 | +| MSVC | 19.44 | -sudo update-alternatives --install /usr/bin/cc cc /usr/bin/gcc-${GCC_RELEASE} 999 -sudo update-alternatives --install \ - /usr/bin/gcc gcc /usr/bin/gcc-${GCC_RELEASE} 100 \ - --slave /usr/bin/g++ g++ /usr/bin/g++-${GCC_RELEASE} \ - --slave /usr/bin/gcc-ar gcc-ar /usr/bin/gcc-ar-${GCC_RELEASE} \ - --slave /usr/bin/gcc-nm gcc-nm /usr/bin/gcc-nm-${GCC_RELEASE} \ - --slave /usr/bin/gcc-ranlib gcc-ranlib /usr/bin/gcc-ranlib-${GCC_RELEASE} \ - --slave /usr/bin/gcov gcov /usr/bin/gcov-${GCC_RELEASE} \ - --slave /usr/bin/gcov-tool gcov-tool /usr/bin/gcov-tool-${GCC_RELEASE} \ - --slave /usr/bin/gcov-dump gcov-dump /usr/bin/gcov-dump-${GCC_RELEASE} \ - --slave /usr/bin/lto-dump lto-dump /usr/bin/lto-dump-${GCC_RELEASE} -sudo update-alternatives --auto cc -sudo update-alternatives --auto gcc +LLVM tools (`clang-tidy` and `clang-format`) are also pinned to version 22. + +Older compilers may fail to build the latest `develop` code: the codebase now +relies on C++23 features and has been adjusted for `clang-tidy`. +If the latest code doesn't build for you, update your build toolchain first. + +## Linux and macOS + +The **recommended way** to get a development environment on Linux and macOS is +the Nix development shell. It provides the exact tooling used in CI — `git`, +`python`, `conan`, `cmake`, `clang-tidy`, `clang-format`, and everything else — +with a single command and without installing anything system-wide: + +```bash +nix --experimental-features 'nix-command flakes' develop ``` -If you use different Linux distribution, hope the instruction above can guide -you in the right direction. We try to maintain compatibility with all recent -compiler releases, so if you use a rolling distribution like e.g. Arch or CentOS -then there is a chance that everything will "just work". +On **Linux**, Nix also provides the compiler (GCC). On **macOS**, the shell uses +your **system-wide Apple Clang** as the compiler, so you still need to manage +its version (see below). -## macOS +See [Using the Nix development shell](./nix.md) for installation and usage +details, including how to select a different compiler. -Open a Terminal and enter the below command to bring up a dialog to install -the command line developer tools. -Once it is finished, this command should return a version greater than the -minimum required (see [BUILD.md][]). +> [!NOTE] +> Using Nix is not mandatory. Any custom environment (Homebrew packages or +> anything else) will continue to work, but then it is up to you to keep it in +> sync with the environment used in CI. Nix unifies the development environment +> for everyone and synchronizes updates, which is why we recommend it. -``` +### macOS: managing the Apple Clang version + +Because the Nix shell uses the system-wide Apple Clang on macOS, the compiler +version is whatever your installed Xcode (or Command Line Tools) provides. The +following command should return a version greater than or equal to the +[minimum required](#tested-compiler-versions): + +```bash clang --version ``` -### Install Xcode Specific Version (Optional) - -If you develop other applications using XCode you might be consistently updating to the newest version of Apple Clang. -This will likely cause issues building xrpld. You may want to install a specific version of Xcode: +If you develop other applications using Xcode, you might be consistently +updating to the newest version of Apple Clang, which will likely cause issues +building xrpld. You may want to install and pin a specific version of Xcode: 1. **Download Xcode** - Visit [Apple Developer Downloads](https://developer.apple.com/download/more/) - Sign in with your Apple Developer account - - Search for an Xcode version that includes **Apple Clang (Expected Version)** + - Search for an Xcode version that includes the expected Apple Clang version - Download the `.xip` file -2. **Install and Configure Xcode** +2. **Install and configure Xcode** ```bash # Extract the .xip file and rename for version management @@ -79,62 +83,28 @@ This will likely cause issues building xrpld. You may want to install a specific export DEVELOPER_DIR=/Applications/Xcode_16.2.app/Contents/Developer ``` -The command line developer tools should include Git too: +## Windows -``` -git --version -``` +Nix is not available on Windows, so the required tools have to be installed +manually: -Install [Homebrew][], -use it to install [pyenv][], -use it to install Python, -and use it to install Conan: +- [Visual Studio 2022](https://visualstudio.microsoft.com/) with the + **"Desktop development with C++"** workload — this provides MSVC and the + "x64 Native Tools Command Prompt". +- [Git for Windows](https://git-scm.com/download/win) +- [Python 3.11](https://www.python.org/downloads/), or higher +- [Conan 2.17](https://conan.io/downloads.html), or higher +- [CMake 3.22](https://cmake.org/download/), or higher -[Homebrew]: https://brew.sh/ -[pyenv]: https://github.com/pyenv/pyenv - -``` -/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" -brew update -brew install xz -brew install pyenv -pyenv install 3.11 -pyenv global 3.11 -eval "$(pyenv init -)" -pip install 'conan' -``` - -Install CMake with Homebrew too: - -``` -brew install cmake -``` +> [!NOTE] +> Windows is used for development only and is not recommended for production. ## Clang-tidy -Clang-tidy is required to run static analysis checks locally (see [CONTRIBUTING.md](../../CONTRIBUTING.md)). -It is not required to build the project. Currently this project uses clang-tidy version 21. +`clang-tidy` is required to run static analysis checks locally (see +[CONTRIBUTING.md](../../CONTRIBUTING.md)). It is not required to build the +project. This project currently uses `clang-tidy` version 22. -### Linux - -LLVM 21 is not available in the default Debian 12 (Bookworm) repositories. -Install it using the official LLVM apt installer: - -``` -wget https://apt.llvm.org/llvm.sh -chmod +x llvm.sh -sudo ./llvm.sh 21 -sudo apt install --yes clang-tidy-21 -``` - -Then use `run-clang-tidy-21` when running clang-tidy locally. - -### macOS - -Install LLVM 21 via Homebrew: - -``` -brew install llvm@21 -``` - -Then use `run-clang-tidy` from the LLVM 21 Homebrew prefix when running clang-tidy locally. +On Linux and macOS, the [Nix development shell](./nix.md) provides `clang-tidy` +22 out of the box — run it via `run-clang-tidy`. No separate installation is +needed. diff --git a/docs/build/nix.md b/docs/build/nix.md index 33bb3711d0..2ae483aefe 100644 --- a/docs/build/nix.md +++ b/docs/build/nix.md @@ -2,9 +2,12 @@ This guide explains how to use Nix to set up a reproducible development environment for xrpld. Using Nix eliminates the need to manually install utilities and ensures consistent tooling across different machines. +**The Nix development shell is the recommended way to develop xrpld.** It unifies the development environment for everyone and synchronizes updates: the same tooling and compiler versions are used both here and in CI. Any custom environment (Homebrew packages or anything else) will continue to work, but then it is up to you to keep it in sync with the environment used in CI. + ## Benefits of Using Nix - **Reproducible environment**: Everyone gets the same versions of tools and compilers +- **Matches CI**: The Linux CI runs in Docker images built from this exact Nix environment - **No system pollution**: Dependencies are isolated and don't affect your system packages - **Multiple compiler versions**: Easily switch between different GCC and Clang versions - **Quick setup**: Get started with a single command @@ -28,11 +31,22 @@ This will: - Download and set up all required development tools (CMake, Ninja, Conan, etc.) - Configure the appropriate compiler for your platform: - - **macOS**: Apple Clang (default system compiler) - - **Linux**: GCC 15 + - **Linux**: GCC 15.2 (provided by Nix) + - **macOS**: Apple Clang (your system compiler) The first time you run this command, it will take a few minutes to download and build the environment. Subsequent runs will be much faster. +### Platform notes + +- **Linux**: `nix develop` gives you a shell with all the tooling necessary to + develop xrpld and with GCC 15.2 (also provided by Nix). There are no caveats. +- **macOS**: `nix develop` gives you a full environment too. The compiler is + your system-wide Apple Clang, while every other tool — including Conan — is + provided by Nix. Conan has no binary in the Nix cache for macOS, so it is + built from source the first time you enter the shell, which makes the initial + setup slower (this is handled automatically; see + [`nix/devshell.nix`](../../nix/devshell.nix)). + > [!TIP] > To avoid typing `--experimental-features 'nix-command flakes'` every time, you can permanently enable flakes by creating `~/.config/nix/nix.conf`: > @@ -51,7 +65,7 @@ The first time you run this command, it will take a few minutes to download and A compiler can be chosen by providing its name with the `.#` prefix, e.g. `nix develop .#gcc15`. Use `nix flake show` to see all the available development shells. -Use `nix develop .#no_compiler` to use the compiler from your system. +Use `nix develop .#no-compiler` to use the compiler from your system. ### Example Usage @@ -68,12 +82,28 @@ nix develop ### Using a different shell -`nix develop` opens bash by default. If you want to use another shell this could be done by adding `-c` flag. For example: +`nix develop` opens bash by default. To use another shell, pass it with the `-c` flag — this works with any shell, e.g. `zsh` or `fish`: ```bash +# Use zsh nix develop -c zsh + +# Use fish +nix develop -c fish + +# Use your login shell +nix develop -c "$SHELL" ``` +> [!WARNING] +> Your shell's interactive startup files (e.g. `config.fish`, `.zshrc`) may prepend other directories — most commonly Homebrew — to `$PATH`, which can shadow the tools provided by the Nix shell. After entering, verify that tools resolve into the Nix store: +> +> ```bash +> command -v cmake # should print a /nix/store/... path +> ``` +> +> If it doesn't, either adjust your shell configuration so it doesn't override `$PATH`, or use [direnv](#automatic-activation-with-direnv) (below), which loads the environment _after_ your shell config and so takes precedence regardless of the shell you use. + ## Building xrpld with Nix Once inside the Nix development shell, follow the standard [build instructions](../../BUILD.md#steps). The Nix shell provides all necessary tools (CMake, Ninja, Conan, etc.). @@ -82,6 +112,8 @@ Once inside the Nix development shell, follow the standard [build instructions]( [direnv](https://direnv.net/) or [nix-direnv](https://github.com/nix-community/nix-direnv) can automatically activate the Nix development shell when you enter the repository directory. +This is also the most robust way to use the environment from **any shell** (bash, zsh, fish, …): direnv stays in your current shell and loads the environment _after_ your shell's startup files have run, so the Nix-provided tools take precedence over anything your shell configuration adds to `$PATH`. To use it, install direnv for your shell, then add an `.envrc` containing `use flake` at the repository root and run `direnv allow`. + ## Conan and Prebuilt Packages Please note that there is no guarantee that binaries from conan cache will work when using nix. If you encounter any errors, please use `--build '*'` to force conan to compile everything from source: @@ -93,3 +125,8 @@ conan install .. --output-folder . --build '*' --settings build_type=Release ## Updating `flake.lock` file To update `flake.lock` to the latest revision use `nix flake update` command. + +## Troubleshooting + +See [Troubleshooting Nix problems](./nix_troubleshooting.md) for common issues, +such as `nix develop` failing inside Git worktrees. diff --git a/docs/build/nix_troubleshooting.md b/docs/build/nix_troubleshooting.md new file mode 100644 index 0000000000..ae5cb8059a --- /dev/null +++ b/docs/build/nix_troubleshooting.md @@ -0,0 +1,61 @@ +# Troubleshooting Nix problems + +Common issues encountered when using the [Nix development shell](./nix.md), and +how to resolve them. + +## Git worktrees + +If `nix develop` fails with an error like: + +``` +error: + … while fetching the input 'git+file:///path/to/rippled' + + error: opening Git repository "/path/to/rippled": unsupported extension name extensions.relativeworktrees (libgit2 error code = 6) +``` + +then your Nix is linked against a libgit2 older than **1.9.4**. Git 2.48+ writes +the `extensions.relativeWorktrees` config entry when a worktree is created with +relative paths (`git worktree add --relative-paths`, or with +`worktree.useRelativePaths=true`), and older libgit2 versions refuse to open a +repository that uses it. Nix uses libgit2 to read the flake, so evaluation +fails. + +> [!IMPORTANT] +> This entry is written to the **shared** repository config, so once any +> relative worktree exists, `nix develop` fails in the main checkout too — not +> just inside the worktree. + +### Workarounds + +These work today, with any Nix version: + +- bypass libgit2 with a `path:` flakeref: `nix develop "path:$PWD"` + (note: this copies the working tree to the store and ignores `.gitignore`); or +- create worktrees with absolute paths (omit `--relative-paths`); or +- clear the extension if you don't need relative worktrees: + `git config --unset extensions.relativeWorktrees`. + +### Permanent fix + +The fix is in [libgit2 1.9.4](https://github.com/libgit2/libgit2/releases/tag/v1.9.4), +so the real solution is a Nix that links against libgit2 `1.9.4` or newer. Check +which version yours links against: + +```bash +nix-store -qR "$(readlink -f "$(command -v nix)")" | grep libgit2 +``` + +> [!WARNING] +> `nix upgrade-nix` does **not** help yet. It installs the build from the +> official [`nix-fallback-paths`](https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/installer/tools/nix-fallback-paths.nix), +> which is still linked against libgit2 `1.9.2` — there is no new upstream Nix +> release with the fix. (On some systems that build is even the exact store path +> you already have, making the upgrade a no-op.) + +nixpkgs has already rebuilt Nix against the fixed libgit2 (e.g. `nix-2.34.7+1`), +so the cleanest path is to reinstall Nix using your usual installation method +once it picks up that rebuild, then re-run the `grep libgit2` check above to +confirm it reports `1.9.4` or newer. + +Until then, prefer the workarounds above. diff --git a/nix/docker/Dockerfile b/nix/docker/Dockerfile index e6df48e18c..6d8980f897 100644 --- a/nix/docker/Dockerfile +++ b/nix/docker/Dockerfile @@ -71,7 +71,7 @@ if [ ! -e "${target}" ]; then fi EOF -COPY nix/docker/check-tools.sh /tmp/check-tools.sh +COPY bin/check-tools.sh /tmp/check-tools.sh RUN /tmp/check-tools.sh # Sanity-check that the g++/clang++ are able to build binaries, including sanitizer-instrumented ones. @@ -93,7 +93,7 @@ RUN if echo "${BASE_IMAGE}" | grep -qiE 'nixos'; then \ SHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"] # Sanity-check that the built binaries run correctly in the vanilla base image, with the necessary sanitizer runtime libraries installed. -COPY nix/docker/install-sanitizer-libs.sh /tmp/install-sanitizer-libs.sh +COPY bin/install-sanitizer-libs.sh /tmp/install-sanitizer-libs.sh COPY nix/docker/test_files/run-test-binaries.sh /tmp/run-test-binaries.sh COPY --from=final /tmp/bins /tmp/bins diff --git a/nix/docker/README.md b/nix/docker/README.md new file mode 100644 index 0000000000..085433b758 --- /dev/null +++ b/nix/docker/README.md @@ -0,0 +1,90 @@ +# Nix CI Docker images + +This directory builds the Docker images used by xrpld's Linux CI. Each image +bundles the **exact same toolchain that the Nix development shell provides** +(see [`docs/build/nix.md`](../../docs/build/nix.md)), so what runs in CI matches +what developers get locally from `nix develop`. + +The toolchain (CMake, Ninja, Conan, GCC, Clang, clang-tidy, the +sanitizer/coverage tools, …) is defined in [`nix/packages.nix`](../packages.nix) +and assembled for CI by [`nix/ci-env.nix`](../ci-env.nix). The Docker build +turns that Nix environment into an ordinary container image layered on top of a +conventional base image (Ubuntu, Debian, RHEL, or `nixos/nix`). + +## Images + +The images are built by the [`build-nix-images.yml`](../../.github/workflows/build-nix-images.yml) +workflow and pushed to `ghcr.io/xrplf/xrpld/nix-`. The `` is +selected through the `BASE_IMAGE` build argument; the base images are the +**oldest supported version** of each distribution we target: + +| Image | `BASE_IMAGE` | Notes | +| ------------ | -------------------------------------------- | -------------------------------------------------- | +| `nix-nixos` | `nixos/nix:latest` | Build/lint only; binaries are not run (see below). | +| `nix-ubuntu` | `ubuntu:20.04` | Oldest supported Ubuntu (glibc 2.31). | +| `nix-debian` | `debian:bookworm` | | +| `nix-rhel` | `registry.access.redhat.com/ubi9/ubi:latest` | | + +All images carry the full toolchain on `PATH` (via `/nix/ci-env/bin`) plus the +CA bundle shipped in the Nix environment, so HTTPS clients (git, curl, Conan) +work without `ca-certificates` being installed in the base image. + +## Build stages + +[`Dockerfile`](./Dockerfile) is a multi-stage build: + +1. **`builder`** — On a `nixos/nix` builder, evaluate the flake and build the + CI environment (`nix/ci-env.nix`). The resulting Nix store closure (the + complete set of store paths the toolchain depends on) is copied into a + staging directory. +2. **`final`** — Start from `BASE_IMAGE`, copy in the Nix store closure and the + `ci-env` symlink tree, and wire up `PATH` and the CA bundle. It then: + - installs the dynamic linker if the base image lacks one (see + [How libc is handled](#how-libc-is-handled)), + - runs [`bin/check-tools.sh`](../../bin/check-tools.sh) to verify every + expected tool is present and runnable, and + - compiles the C++ test programs in + [`test_files/`](./test_files) with both `g++` and `clang++`, and sanitizers. +3. **`tester`** — Start again from a clean `BASE_IMAGE` (no Nix toolchain), + install only the sanitizer runtime libraries + ([`install-sanitizer-libs.sh`](./install-sanitizer-libs.sh)), and run the + binaries compiled in `final`. This proves the binaries built with the Nix + toolchain actually run on a vanilla base image. On `nixos/nix` this step is + skipped (the binaries are patched for a conventional FHS loader). +4. **Output** — The final image is gated on the tester succeeding: it copies a + sentinel file out of `tester`, so a failed test run fails the whole build. + +## How libc is handled + +The goal is for binaries built in these images to run on the **oldest supported +base image** (Ubuntu 20.04, glibc 2.31) and newer — without the developer's Nix +toolchain being present at runtime. Two pieces make that work: + +- **Compilers linked against an old glibc.** The Nix CI environment does not use + nixpkgs' current glibc. Instead it pins a 2020 nixpkgs snapshot whose primary + glibc is **2.31** (matching Ubuntu 20.04), via the `nixpkgs-custom-glibc` + flake input. GCC, Clang, binutils and compiler-rt are all rebuilt/wrapped + against this custom glibc (see [`nix/ci-env.nix`](../ci-env.nix)). As a result + the libraries they emit (`libstdc++`, `libgcc_s`, the sanitizer runtimes) + reference only symbols available in glibc 2.31. + +- **An expected dynamic linker in the image.** + Binaries built in Nix environments reference a dynamic linker from Nix store paths, which won't be present in the base image. However, + [`loader-path.sh`](./loader-path.sh) reports the expected loader path for the + current architecture, so we can patch the binaries to use the correct loader. + +The build then verifies all of this end to end: the test programs in +`test_files/` (a regular binary plus ASan/TSan/UBSan variants) are compiled in +`final`, their `PT_INTERP` is patched to the target loader, and they are run in +the clean `tester` stage to confirm each emits the expected sanitizer +diagnostic on a stock base image. + +## Files + +| File | Purpose | +| ----------------------------------------------------------------------- | ----------------------------------------------------------------------------- | +| [`./Dockerfile`](./Dockerfile) | Multi-stage build described above. | +| [`./loader-path.sh`](./loader-path.sh) | Print the dynamic-linker (`PT_INTERP`) path for the current architecture. | +| [`./test_files/`](./test_files) | C++ sources and scripts to compile and run the sanitizer smoke tests. | +| [`/bin/check-tools.sh`](../../bin/check-tools.sh) | Verify every expected tools are present and runnable. | +| [`/bin/install-sanitizer-libs.sh`](../../bin/install-sanitizer-libs.sh) | Install `libasan`/`libtsan`/`libubsan` runtimes on the supported base images. | diff --git a/nix/docker/check-tools.sh b/nix/docker/check-tools.sh deleted file mode 100755 index a46c2dd997..0000000000 --- a/nix/docker/check-tools.sh +++ /dev/null @@ -1,39 +0,0 @@ -#!/bin/bash -# Verify that every tool expected in the Nix CI env is present and runnable. -set -euo pipefail - -ccache --version -clang --version -clang++ --version -clang-format --version -ClangBuildAnalyzer --version -cmake --version -conan --version -curl --version -doxygen --version -file --version -g++ --version -gcc --version -gcov --version -gcovr --version -gh --version -git --version -git-cliff --version -gpg --version -less --version -make --version -mold --version -netstat --version -ninja --version -perl --version -pkg-config --version -pre-commit --version -python3 --version -run-clang-tidy --help -vim --version - -# A simple test to verify that git can clone a repository over HTTPS -# (i.e. the CA bundle is wired up). Clone to a temp dir and clean up. -tmp_clone="$(mktemp -d)" -git clone --depth 1 https://github.com/XRPLF/actions.git "${tmp_clone}/actions" -rm -rf "${tmp_clone}" From 7b9d55326db2fc9f5da4d16f22985c4670af8082 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Tue, 16 Jun 2026 18:35:33 +0100 Subject: [PATCH 62/78] build: Add zip to Nix images (#7551) --- nix/packages.nix | 1 + 1 file changed, 1 insertion(+) diff --git a/nix/packages.nix b/nix/packages.nix index 5a7f20ec49..612b1cb215 100644 --- a/nix/packages.nix +++ b/nix/packages.nix @@ -33,5 +33,6 @@ in python3 runClangTidy vim + zip ]; } From 45ddc1d868cad0aa1ec9fedbdff3d4eaf882eb72 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 17 Jun 2026 00:13:33 +0100 Subject: [PATCH 63/78] build: Add git-lfs to Nix images (#7561) --- nix/packages.nix | 1 + 1 file changed, 1 insertion(+) diff --git a/nix/packages.nix b/nix/packages.nix index 612b1cb215..79de8fac89 100644 --- a/nix/packages.nix +++ b/nix/packages.nix @@ -19,6 +19,7 @@ in gh git git-cliff + git-lfs gnumake gnupg # needed for signing commits & codecov/codecov-action llvmPackages_22.clang-tools From 5de434436e339bfdd91b31319ca87ff8329a3465 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 17 Jun 2026 11:02:17 +0100 Subject: [PATCH 64/78] ci: Make clang-tidy workflow adjustments to stay in sync with Clio (#7563) --- .github/workflows/reusable-clang-tidy.yml | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/.github/workflows/reusable-clang-tidy.yml b/.github/workflows/reusable-clang-tidy.yml index 34fa860e12..5d2325cb1d 100644 --- a/.github/workflows/reusable-clang-tidy.yml +++ b/.github/workflows/reusable-clang-tidy.yml @@ -20,9 +20,12 @@ env: BUILD_DIR: build BUILD_TYPE: Debug # Debug so that ASSERTS and such participate in clang-tidy check - OUTPUT_FILE: clang-tidy-output.txt - DIFF_FILE: clang-tidy-git-diff.txt - ISSUE_FILE: clang-tidy-issue.md + OUTPUT_FILE: /tmp/clang-tidy-output.txt + FILTERED_OUTPUT_FILE: /tmp/clang-tidy-filtered-output.txt + DIFF_FILE: /tmp/clang-tidy-git-diff.txt + ISSUE_FILE: /tmp/clang-tidy-issue.md + + COMPILER: clang jobs: determine-files: @@ -59,7 +62,7 @@ jobs: - name: Set compiler environment uses: ./.github/actions/set-compiler-env with: - compiler: clang + compiler: ${{ env.COMPILER }} - name: Setup Conan uses: ./.github/actions/setup-conan @@ -150,21 +153,21 @@ jobs: run: | if [ -f "${OUTPUT_FILE}" ]; then # Extract lines containing 'error:', 'warning:', or 'note:' - grep -E '(error:|warning:|note:)' "${OUTPUT_FILE}" >filtered-output.txt || true + grep -E '(error:|warning:|note:)' "${OUTPUT_FILE}" >"${FILTERED_OUTPUT_FILE}" || true # If filtered output is empty, use original (might be a different error format) - if [ ! -s filtered-output.txt ]; then - cp "${OUTPUT_FILE}" filtered-output.txt + if [ ! -s "${FILTERED_OUTPUT_FILE}" ]; then + cp "${OUTPUT_FILE}" "${FILTERED_OUTPUT_FILE}" fi # Truncate if too large - head -c 60000 filtered-output.txt >>"${ISSUE_FILE}" - if [ "$(wc -c >"${ISSUE_FILE}" + if [ "$(wc -c <"${FILTERED_OUTPUT_FILE}")" -gt 60000 ]; then echo "" >>"${ISSUE_FILE}" echo "... (output truncated, see artifacts for full output)" >>"${ISSUE_FILE}" fi - rm filtered-output.txt + rm "${FILTERED_OUTPUT_FILE}" else echo "No output file found" >>"${ISSUE_FILE}" fi From 044ca7719dda036f1950e599cd636ce8276eb67e Mon Sep 17 00:00:00 2001 From: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Date: Wed, 17 Jun 2026 12:58:01 +0100 Subject: [PATCH 65/78] release: Bump version to 3.3.0-b0 Signed-off-by: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> --- src/libxrpl/protocol/BuildInfo.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libxrpl/protocol/BuildInfo.cpp b/src/libxrpl/protocol/BuildInfo.cpp index c488bb20de..820936a22d 100644 --- a/src/libxrpl/protocol/BuildInfo.cpp +++ b/src/libxrpl/protocol/BuildInfo.cpp @@ -23,7 +23,7 @@ namespace { //------------------------------------------------------------------------------ // clang-format off // NOLINTNEXTLINE(readability-identifier-naming) -char const* const versionString = "3.2.0" +char const* const versionString = "3.3.0-b0" // clang-format on ; From 7e0ff536f55b684f6c8e73028c20758c03e334bc Mon Sep 17 00:00:00 2001 From: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Date: Wed, 17 Jun 2026 13:31:04 +0100 Subject: [PATCH 66/78] refactor: Rerevert "Explicitly trim the heap after cache sweeps (#6022)" Signed-off-by: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> --- src/xrpld/app/main/Application.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index af32cf0ba6..67b5e30eb7 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -41,6 +41,7 @@ #include #include +#include #include #include #include @@ -1088,6 +1089,8 @@ public: << "; size after: " << cachedSLEs_.size(); } + mallocTrim("doSweep", journal_); + // Set timer to do another sweep later. setSweepTimer(); } From cb2642be050b2683c929d03ab10d85c6cb01f933 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 17 Jun 2026 14:54:46 +0100 Subject: [PATCH 67/78] build: Add graphviz to Nix images (#7566) --- nix/packages.nix | 1 + 1 file changed, 1 insertion(+) diff --git a/nix/packages.nix b/nix/packages.nix index 79de8fac89..6202168733 100644 --- a/nix/packages.nix +++ b/nix/packages.nix @@ -22,6 +22,7 @@ in git-lfs gnumake gnupg # needed for signing commits & codecov/codecov-action + graphviz llvmPackages_22.clang-tools less # needed for git diff mold From f07de6c4540e91ed312404bb8f511fdc562ea9b5 Mon Sep 17 00:00:00 2001 From: Michael Legleux Date: Wed, 17 Jun 2026 06:54:55 -0700 Subject: [PATCH 68/78] ci: Disable assertions on Release builds (#7443) --- .github/scripts/strategy-matrix/generate.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/scripts/strategy-matrix/generate.py b/.github/scripts/strategy-matrix/generate.py index 6353567f27..a269cb25d4 100755 --- a/.github/scripts/strategy-matrix/generate.py +++ b/.github/scripts/strategy-matrix/generate.py @@ -20,8 +20,6 @@ _SANITIZER_SUFFIX: dict[str, str] = { def get_cmake_args(build_type: str, extra_args: str) -> str: """Get the full list of CMake arguments for a config.""" args = _BASE_CMAKE_ARGS.copy() - if build_type == "Release": - args.append("-Dassert=ON") if extra_args: args.extend(extra_args.split()) return " ".join(args) From 480676d0bf9ec7dc6b35267c63dfd162746b5d3b Mon Sep 17 00:00:00 2001 From: solunolab Date: Wed, 17 Jun 2026 21:55:00 +0800 Subject: [PATCH 69/78] docs: Fix some comments to improve readability (#7405) Signed-off-by: solunolab Co-authored-by: Ayaz Salikhov --- include/xrpl/basics/sanitizers.h | 2 +- include/xrpl/ledger/helpers/CredentialHelpers.h | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/include/xrpl/basics/sanitizers.h b/include/xrpl/basics/sanitizers.h index b954952848..7937344b53 100644 --- a/include/xrpl/basics/sanitizers.h +++ b/include/xrpl/basics/sanitizers.h @@ -4,7 +4,7 @@ /* ASAN flags some false positives with sudden jumps in control flow, like exceptions, or when encountering coroutine stack switches. This macro can be used to disable ASAN - intrumentation for specific functions. + instrumentation for specific functions. */ #if defined(__GNUC__) || defined(__clang__) #define XRPL_NO_SANITIZE_ADDRESS __attribute__((no_sanitize("address", "hwaddress"))) diff --git a/include/xrpl/ledger/helpers/CredentialHelpers.h b/include/xrpl/ledger/helpers/CredentialHelpers.h index 549644764f..0cfbbde538 100644 --- a/include/xrpl/ledger/helpers/CredentialHelpers.h +++ b/include/xrpl/ledger/helpers/CredentialHelpers.h @@ -36,13 +36,13 @@ checkFields(STTx const& tx, beast::Journal j); TER valid(STTx const& tx, ReadView const& view, AccountID const& src, beast::Journal j); -// Check if subject has any credential maching the given domain. If you call it +// Check if subject has any credential matching the given domain. If you call it // in preclaim and it returns tecEXPIRED, you should call verifyValidDomain in // doApply. This will ensure that expired credentials are deleted. TER validDomain(ReadView const& view, uint256 domainID, AccountID const& subject); -// This function is only called when we about to return tecNO_PERMISSION +// This function is only called when we are about to return tecNO_PERMISSION // because all the checks for the DepositPreauth authorization failed. TER authorizedDepositPreauth(ReadView const& view, STVector256 const& ctx, AccountID const& dst); @@ -58,7 +58,7 @@ checkArray(STArray const& credentials, unsigned maxSize, beast::Journal j); } // namespace credentials -// Check expired credentials and for credentials maching DomainID of the ledger +// Check expired credentials and for credentials matching DomainID of the ledger // object TER verifyValidDomain(ApplyView& view, AccountID const& account, uint256 domainID, beast::Journal j); From 772ea80a25227b5e9fb75ea0cdb62723b099cd33 Mon Sep 17 00:00:00 2001 From: yinyiqian1 Date: Wed, 17 Jun 2026 19:20:54 -0400 Subject: [PATCH 70/78] fix: Use template for granular delegation permissions (#6613) Co-authored-by: Bart --- include/xrpl/ledger/helpers/DelegateHelpers.h | 10 +- include/xrpl/protocol/Permissions.h | 80 +++- include/xrpl/protocol/detail/features.macro | 2 +- .../xrpl/protocol/detail/permissions.macro | 89 ++-- include/xrpl/tx/Transactor.h | 63 ++- .../xrpl/tx/transactors/account/AccountSet.h | 3 - include/xrpl/tx/transactors/payment/Payment.h | 5 +- .../tx/transactors/token/MPTokenIssuanceSet.h | 3 - include/xrpl/tx/transactors/token/TrustSet.h | 5 +- src/libxrpl/protocol/Permissions.cpp | 317 +++++++++----- src/libxrpl/protocol/STTx.cpp | 2 +- src/libxrpl/tx/Transactor.cpp | 36 +- src/libxrpl/tx/applySteps.cpp | 3 +- .../tx/transactors/account/AccountSet.cpp | 51 --- .../tx/transactors/delegate/DelegateUtils.cpp | 12 +- .../tx/transactors/payment/Payment.cpp | 30 +- .../transactors/token/MPTokenIssuanceSet.cpp | 36 -- src/libxrpl/tx/transactors/token/TrustSet.cpp | 44 +- src/test/app/Delegate_test.cpp | 407 +++++++++++++++++- 19 files changed, 851 insertions(+), 347 deletions(-) diff --git a/include/xrpl/ledger/helpers/DelegateHelpers.h b/include/xrpl/ledger/helpers/DelegateHelpers.h index 9cdad7173d..a517eefdaa 100644 --- a/include/xrpl/ledger/helpers/DelegateHelpers.h +++ b/include/xrpl/ledger/helpers/DelegateHelpers.h @@ -23,13 +23,9 @@ checkTxPermission(SLE::const_ref delegate, STTx const& tx); * @param delegate The delegate account. * @param type Used to determine which granted granular permissions to load, * based on the transaction type. - * @param granularPermissions Granted granular permissions tied to the - * transaction type. + * @return the granted granular permissions tied to the transaction type. */ -void -loadGranularPermission( - SLE::const_ref delegate, - TxType const& type, - std::unordered_set& granularPermissions); +std::unordered_set +getGranularPermission(SLE::const_ref delegate, TxType const& type); } // namespace xrpl diff --git a/include/xrpl/protocol/Permissions.h b/include/xrpl/protocol/Permissions.h index 5d56fa4461..eb161ef7ad 100644 --- a/include/xrpl/protocol/Permissions.h +++ b/include/xrpl/protocol/Permissions.h @@ -7,8 +7,13 @@ #include #include #include +#include +#include namespace xrpl { + +class STTx; + /** * We have both transaction type permissions and granular type permissions. * Since we will reuse the TransactionFormats to parse the Transaction @@ -19,15 +24,15 @@ namespace xrpl { // Macro-generated, complex // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) enum GranularPermissionType : std::uint32_t { -#pragma push_macro("PERMISSION") -#undef PERMISSION +#pragma push_macro("GRANULAR_PERMISSION") +#undef GRANULAR_PERMISSION -#define PERMISSION(type, txType, value) type = (value), +#define GRANULAR_PERMISSION(name, txType, value, ...) name = (value), #include -#undef PERMISSION -#pragma pop_macro("PERMISSION") +#undef GRANULAR_PERMISSION +#pragma pop_macro("GRANULAR_PERMISSION") }; // Injected bare enumerators (xrpl::delegable / xrpl::notDelegable) are required by preprocessor @@ -40,15 +45,30 @@ class Permission private: Permission(); - std::unordered_map txFeatureMap_; + struct GranularPermissionEntry + { + std::string name; + TxType txType; + std::uint32_t permittedFlags; + SOTemplate permittedFields; - std::unordered_map delegableTx_; + GranularPermissionEntry( + std::string name, + TxType txType, + std::uint32_t permittedFlags, + std::vector fields); + }; - std::unordered_map granularPermissionMap_; + struct TxDelegationEntry + { + uint256 amendment; + Delegation delegable{NotDelegable}; + }; - std::unordered_map granularNameMap_; - - std::unordered_map granularTxTypeMap_; + std::unordered_set granularTxTypes_; + std::unordered_map txDelegationMap_; + std::unordered_map granularPermissionsByName_; + std::unordered_map granularPermissions_; public: static Permission const& @@ -59,30 +79,52 @@ public: operator=(Permission const&) = delete; [[nodiscard]] std::optional - getPermissionName(std::uint32_t const value) const; + getPermissionName(std::uint32_t value) const; [[nodiscard]] std::optional getGranularValue(std::string const& name) const; [[nodiscard]] std::optional - getGranularName(GranularPermissionType const& value) const; + getGranularName(GranularPermissionType value) const; [[nodiscard]] std::optional - getGranularTxType(GranularPermissionType const& gpType) const; + getGranularTxType(GranularPermissionType gpType) const; + // Returns a reference to avoid copying uint256 - 32 bytes. std::optional + // cannot hold references directly, so std::reference_wrapper is used. [[nodiscard]] std::optional> getTxFeature(TxType txType) const; [[nodiscard]] bool - isDelegable(std::uint32_t const& permissionValue, Rules const& rules) const; + isDelegable(std::uint32_t permissionValue, Rules const& rules) const; + + [[nodiscard]] bool + hasGranularPermissions(TxType txType) const; // for tx level permission, permission value is equal to tx type plus one - static uint32_t - txToPermissionType(TxType const& type); + [[nodiscard]] static uint32_t + txToPermissionType(TxType type); // tx type value is permission value minus one - static TxType - permissionToTxType(uint32_t const& value); + [[nodiscard]] static TxType + permissionToTxType(std::uint32_t value); + + /** + * @brief Verifies a delegated transaction against its granular permission template. + * + * @note WARNING: Do not move this check before standard transaction-level + * format checks, which is in preclaim. This function assumes the transaction's + * base structural integrity (fees, sequence, signatures) has already been + * validated. + * + * @param tx The transaction to verify. + * @param heldPermissions The granular permissions that the sender hold. + * @return true if the transaction fields and flags comply with the granular template. + */ + [[nodiscard]] bool + checkGranularSandbox( + STTx const& tx, + std::unordered_set const& heldPermissions) const; }; } // namespace xrpl diff --git a/include/xrpl/protocol/detail/features.macro b/include/xrpl/protocol/detail/features.macro index d3500ab144..d25b0b1f2c 100644 --- a/include/xrpl/protocol/detail/features.macro +++ b/include/xrpl/protocol/detail/features.macro @@ -21,7 +21,7 @@ XRPL_FEATURE(MPTokensV2, Supported::No, VoteBehavior::DefaultN XRPL_FIX (Cleanup3_1_3, Supported::Yes, VoteBehavior::DefaultYes) XRPL_FIX (BatchInnerSigs, Supported::No, VoteBehavior::DefaultNo) XRPL_FEATURE(LendingProtocol, Supported::Yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(PermissionDelegationV1_1, Supported::No, VoteBehavior::DefaultNo) +XRPL_FEATURE(PermissionDelegationV1_1, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FIX (DirectoryLimit, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FIX (IncludeKeyletFields, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FEATURE(DynamicMPT, Supported::No, VoteBehavior::DefaultNo) diff --git a/include/xrpl/protocol/detail/permissions.macro b/include/xrpl/protocol/detail/permissions.macro index 729861a013..35532a03ca 100644 --- a/include/xrpl/protocol/detail/permissions.macro +++ b/include/xrpl/protocol/detail/permissions.macro @@ -1,49 +1,74 @@ -#if !defined(PERMISSION) -#error "undefined macro: PERMISSION" +#if !defined(GRANULAR_PERMISSION) +#error "undefined macro: GRANULAR_PERMISSION" #endif /** - * PERMISSION(name, type, txType, value) + * GRANULAR_PERMISSION(name, txType, value, allowedFlags, allowedFields) * - * This macro defines a permission: - * name: the name of the permission. - * type: the GranularPermissionType enum. - * txType: the corresponding TxType for this permission. - * value: the uint32 numeric value for the enum type. + * Defines a granular permission: + * name: the granular permission name. + * txType: the corresponding TxType for this permission. + * value: the uint32 numeric value for the enum type. + * allowedFlags: transaction flags permitted under this permission. + * allowedFields: transaction fields permitted under this permission. */ -/** This permission grants the delegated account the ability to authorize a trustline. */ -PERMISSION(TrustlineAuthorize, ttTRUST_SET, 65537) +/** Grants the ability to authorize a trustline. */ +GRANULAR_PERMISSION(TrustlineAuthorize, ttTRUST_SET, 65537, tfUniversal | tfSetfAuth, + ({{sfLimitAmount, SoeRequired}})) -/** This permission grants the delegated account the ability to freeze a trustline. */ -PERMISSION(TrustlineFreeze, ttTRUST_SET, 65538) +/** Grants the ability to freeze a trustline. */ +GRANULAR_PERMISSION(TrustlineFreeze, ttTRUST_SET, 65538, tfUniversal | tfSetFreeze, + ({{sfLimitAmount, SoeRequired}})) -/** This permission grants the delegated account the ability to unfreeze a trustline. */ -PERMISSION(TrustlineUnfreeze, ttTRUST_SET, 65539) +/** Grants the ability to unfreeze a trustline. */ +GRANULAR_PERMISSION(TrustlineUnfreeze, ttTRUST_SET, 65539, tfUniversal | tfClearFreeze, + ({{sfLimitAmount, SoeRequired}})) -/** This permission grants the delegated account the ability to set Domain. */ -PERMISSION(AccountDomainSet, ttACCOUNT_SET, 65540) +/** Grants the ability to set Domain. */ +GRANULAR_PERMISSION(AccountDomainSet, ttACCOUNT_SET, 65540, tfUniversal, + ({{sfDomain, SoeOptional}})) -/** This permission grants the delegated account the ability to set EmailHashSet. */ -PERMISSION(AccountEmailHashSet, ttACCOUNT_SET, 65541) +/** Grants the ability to set EmailHash. */ +GRANULAR_PERMISSION(AccountEmailHashSet, ttACCOUNT_SET, 65541, tfUniversal, + ({{sfEmailHash, SoeOptional}})) -/** This permission grants the delegated account the ability to set MessageKey. */ -PERMISSION(AccountMessageKeySet, ttACCOUNT_SET, 65542) +/** Grants the ability to set MessageKey. */ +GRANULAR_PERMISSION(AccountMessageKeySet, ttACCOUNT_SET, 65542, tfUniversal, + ({{sfMessageKey, SoeOptional}})) -/** This permission grants the delegated account the ability to set TransferRate. */ -PERMISSION(AccountTransferRateSet, ttACCOUNT_SET, 65543) +/** Grants the ability to set TransferRate. */ +GRANULAR_PERMISSION(AccountTransferRateSet, ttACCOUNT_SET, 65543, tfUniversal, + ({{sfTransferRate, SoeOptional}})) -/** This permission grants the delegated account the ability to set TickSize. */ -PERMISSION(AccountTickSizeSet, ttACCOUNT_SET, 65544) +/** Grants the ability to set TickSize. */ +GRANULAR_PERMISSION(AccountTickSizeSet, ttACCOUNT_SET, 65544, tfUniversal, + ({{sfTickSize, SoeOptional}})) -/** This permission grants the delegated account the ability to mint payment, which means sending a payment for a currency where the sending account is the issuer. */ -PERMISSION(PaymentMint, ttPAYMENT, 65545) +/** Grants the ability to mint payment (sending account is the issuer). Cross-currency payments are disallowed. */ +GRANULAR_PERMISSION(PaymentMint, ttPAYMENT, 65545, tfUniversal, + ({{sfDestination, SoeRequired}, + {sfAmount, SoeRequired}, + {sfSendMax, SoeOptional}, + {sfInvoiceID, SoeOptional}, + {sfDestinationTag, SoeOptional}, + {sfCredentialIDs, SoeOptional}})) -/** This permission grants the delegated account the ability to burn payment, which means sending a payment for a currency where the destination account is the issuer */ -PERMISSION(PaymentBurn, ttPAYMENT, 65546) +/** Grants the ability to burn payment (destination account is the issuer). Cross-currency payments are disallowed. */ +GRANULAR_PERMISSION(PaymentBurn, ttPAYMENT, 65546, tfUniversal, + ({{sfDestination, SoeRequired}, + {sfAmount, SoeRequired}, + {sfSendMax, SoeOptional}, + {sfInvoiceID, SoeOptional}, + {sfDestinationTag, SoeOptional}, + {sfCredentialIDs, SoeOptional}})) -/** This permission grants the delegated account the ability to lock MPToken. */ -PERMISSION(MPTokenIssuanceLock, ttMPTOKEN_ISSUANCE_SET, 65547) +/** Grants the ability to lock an MPToken. */ +GRANULAR_PERMISSION(MPTokenIssuanceLock, ttMPTOKEN_ISSUANCE_SET, 65547, tfUniversal | tfMPTLock, + ({{sfMPTokenIssuanceID, SoeRequired}, + {sfHolder, SoeOptional}})) -/** This permission grants the delegated account the ability to unlock MPToken. */ -PERMISSION(MPTokenIssuanceUnlock, ttMPTOKEN_ISSUANCE_SET, 65548) +/** Grants the ability to unlock an MPToken. */ +GRANULAR_PERMISSION(MPTokenIssuanceUnlock, ttMPTOKEN_ISSUANCE_SET, 65548, tfUniversal | tfMPTUnlock, + ({{sfMPTokenIssuanceID, SoeRequired}, + {sfHolder, SoeOptional}})) diff --git a/include/xrpl/tx/Transactor.h b/include/xrpl/tx/Transactor.h index 86b1e856b3..a27d638107 100644 --- a/include/xrpl/tx/Transactor.h +++ b/include/xrpl/tx/Transactor.h @@ -222,8 +222,63 @@ public: return tesSUCCESS; } + /** + * This function can be overridden to introduce additional semantic constraints beyond the + * granular template validation for granular permissions. It is called by the base + * invokeCheckPermission method only after the transaction has successfully passed + * checkGranularSandbox. + */ static NotTEC - checkPermission(ReadView const& view, STTx const& tx); + checkGranularSemantics( + ReadView const& view, + STTx const& tx, + std::unordered_set const& heldGranularPermissions) + { + return tesSUCCESS; + } + + /** + * Checks whether the transaction is authorized to be executed by the delegated account. + * This function enforces the strict permission check hierarchy. It is explicitly + * designed NOT to be overridden. Derived transactors must instead implement + * checkGranularSemantics to add custom validation logic for granular permissions. + * + * The evaluation proceeds as follows: + * - If transaction-level permission is granted, the function immediately returns tesSUCCESS. + * - If transaction-level permission is not granted, the function checks whether the transaction + * matches the granular permission template defined in permissions.macro. If it does, it then + * calls checkGranularSemantics to perform any additional, fine-grained validation. + * + */ + template + static NotTEC + invokeCheckPermission(ReadView const& view, STTx const& tx) + { + // heldGranularPermissions is passed by reference into checkPermission. + // It is populated with the sender’s granular permissions only when the sender + // lacks tx-level permission but has granular permissions that satisfy the + // granular permission template. + // + // - result is terNO_DELEGATE_PERMISSION: return immediately. + // - result is tesSUCCESS and heldGranularPermissions is empty: tx-level permission was + // granted, so we returned success before populating it. + // - result is tesSUCCESS and heldGranularPermissions is not empty: tx-level permission was + // not granted, but the held granular permissions passed checkGranularSandbox, so we proceed + // to checkGranularSemantics. + // + // WARNING: Do not simplify checkPermission to return only + // heldGranularPermissions or the ter code. Both the result and the + // populated set are required to enforce the strict permission hierarchy + // described above. + std::unordered_set heldGranularPermissions; + if (NotTEC const result = checkPermission(view, tx, heldGranularPermissions); + !isTesSuccess(result) || heldGranularPermissions.empty()) + { + return result; + } + + return T::checkGranularSemantics(view, tx, heldGranularPermissions); + } ///////////////////////////////////////////////////// // Interface used by AccountDelete @@ -353,6 +408,12 @@ protected: unit::ValueUnit min = unit::ValueUnit{}); private: + static NotTEC + checkPermission( + ReadView const& view, + STTx const& tx, + std::unordered_set& heldGranularPermissions); + std::pair reset(XRPAmount fee); diff --git a/include/xrpl/tx/transactors/account/AccountSet.h b/include/xrpl/tx/transactors/account/AccountSet.h index a40a9ec963..91b38e7968 100644 --- a/include/xrpl/tx/transactors/account/AccountSet.h +++ b/include/xrpl/tx/transactors/account/AccountSet.h @@ -23,9 +23,6 @@ public: static NotTEC preflight(PreflightContext const& ctx); - static NotTEC - checkPermission(ReadView const& view, STTx const& tx); - static TER preclaim(PreclaimContext const& ctx); diff --git a/include/xrpl/tx/transactors/payment/Payment.h b/include/xrpl/tx/transactors/payment/Payment.h index 14897b4efe..dd792aa1c2 100644 --- a/include/xrpl/tx/transactors/payment/Payment.h +++ b/include/xrpl/tx/transactors/payment/Payment.h @@ -32,7 +32,10 @@ public: preflight(PreflightContext const& ctx); static NotTEC - checkPermission(ReadView const& view, STTx const& tx); + checkGranularSemantics( + ReadView const& view, + STTx const& tx, + std::unordered_set const& heldGranularPermissions); static TER preclaim(PreclaimContext const& ctx); diff --git a/include/xrpl/tx/transactors/token/MPTokenIssuanceSet.h b/include/xrpl/tx/transactors/token/MPTokenIssuanceSet.h index 6a6d1fc445..428c573e2f 100644 --- a/include/xrpl/tx/transactors/token/MPTokenIssuanceSet.h +++ b/include/xrpl/tx/transactors/token/MPTokenIssuanceSet.h @@ -22,9 +22,6 @@ public: static NotTEC preflight(PreflightContext const& ctx); - static NotTEC - checkPermission(ReadView const& view, STTx const& tx); - static TER preclaim(PreclaimContext const& ctx); diff --git a/include/xrpl/tx/transactors/token/TrustSet.h b/include/xrpl/tx/transactors/token/TrustSet.h index dcf454bea1..d719f06326 100644 --- a/include/xrpl/tx/transactors/token/TrustSet.h +++ b/include/xrpl/tx/transactors/token/TrustSet.h @@ -21,7 +21,10 @@ public: preflight(PreflightContext const& ctx); static NotTEC - checkPermission(ReadView const& view, STTx const& tx); + checkGranularSemantics( + ReadView const& view, + STTx const& tx, + std::unordered_set const& heldGranularPermissions); static TER preclaim(PreclaimContext const& ctx); diff --git a/src/libxrpl/protocol/Permissions.cpp b/src/libxrpl/protocol/Permissions.cpp index ce3baeb35e..3aa9705b03 100644 --- a/src/libxrpl/protocol/Permissions.cpp +++ b/src/libxrpl/protocol/Permissions.cpp @@ -1,91 +1,136 @@ #include #include +#include #include -#include // IWYU pragma: keep #include +#include +#include +#include +#include // IWYU pragma: keep #include +#include #include #include #include +#include #include +#include +#include +#include +#include namespace xrpl { +Permission::GranularPermissionEntry::GranularPermissionEntry( + std::string name, + TxType txType, + std::uint32_t permittedFlags, + std::vector permittedFields) + : name(std::move(name)) + , txType(txType) + , permittedFlags(permittedFlags) + , permittedFields(std::move(permittedFields), TxFormats::getCommonFields()) +{ +} + Permission::Permission() { - txFeatureMap_ = { -#pragma push_macro("TRANSACTION") -#undef TRANSACTION - -#define TRANSACTION(tag, value, name, delegable, amendment, ...) {value, amendment}, - -#include - -#undef TRANSACTION -#pragma pop_macro("TRANSACTION") - }; - - delegableTx_ = { -#pragma push_macro("TRANSACTION") -#undef TRANSACTION - -#define TRANSACTION(tag, value, name, delegable, ...) {value, delegable}, - -#include - -#undef TRANSACTION -#pragma pop_macro("TRANSACTION") - }; - - granularPermissionMap_ = { -#pragma push_macro("PERMISSION") -#undef PERMISSION - -#define PERMISSION(type, txType, value) {#type, type}, - -#include - -#undef PERMISSION -#pragma pop_macro("PERMISSION") - }; - - granularNameMap_ = { -#pragma push_macro("PERMISSION") -#undef PERMISSION - -#define PERMISSION(type, txType, value) {type, #type}, - -#include - -#undef PERMISSION -#pragma pop_macro("PERMISSION") - }; - - granularTxTypeMap_ = { -#pragma push_macro("PERMISSION") -#undef PERMISSION - -#define PERMISSION(type, txType, value) {type, txType}, - -#include - -#undef PERMISSION -#pragma pop_macro("PERMISSION") - }; - - XRPL_ASSERT( - txFeatureMap_.size() == delegableTx_.size(), - "xrpl::Permission : txFeatureMap_ and delegableTx_ must have same " - "size"); - - for ([[maybe_unused]] auto const& permission : granularPermissionMap_) { - XRPL_ASSERT( - permission.second > UINT16_MAX, - "xrpl::Permission::granularPermissionMap_ : granular permission " - "value must not exceed the maximum uint16_t value."); +#pragma push_macro("TRANSACTION") +#undef TRANSACTION + +#define TRANSACTION(tag, value, name, delegable, amendment, ...) \ + txDelegationMap_[static_cast(value)] = {amendment, delegable}; + +#include + +#undef TRANSACTION +#pragma pop_macro("TRANSACTION") + } + + granularPermissionsByName_ = { +#pragma push_macro("GRANULAR_PERMISSION") +#undef GRANULAR_PERMISSION + +#define GRANULAR_PERMISSION(type, ...) {#type, type}, + +#include + +#undef GRANULAR_PERMISSION +#pragma pop_macro("GRANULAR_PERMISSION") + }; + + { +#pragma push_macro("GRANULAR_PERMISSION") +#undef GRANULAR_PERMISSION + +// NOLINTBEGIN(bugprone-macro-parentheses) +#define GRANULAR_PERMISSION(type, txType, value, flags, fields) \ + granularPermissions_.emplace( \ + std::piecewise_construct, \ + std::forward_as_tuple(GranularPermissionType::type), \ + std::forward_as_tuple( \ + #type, txType, static_cast(flags), std::vector fields)); + // NOLINTEND(bugprone-macro-parentheses) + +#include + +#undef GRANULAR_PERMISSION +#pragma pop_macro("GRANULAR_PERMISSION") + } + + if (granularPermissionsByName_.size() != granularPermissions_.size()) + { + // LCOV_EXCL_START + Throw( + "granularPermissionsByName_ and granularPermissions_ must have same size"); + // LCOV_EXCL_STOP + } + + for (auto const& [name, type] : granularPermissionsByName_) + { + if (type <= UINT16_MAX) + { + // LCOV_EXCL_START + Throw( + "Granular permission value must exceed the maximum uint16_t value: " + name); + // LCOV_EXCL_STOP + } + } + + for (auto const& [type, entry] : granularPermissions_) + granularTxTypes_.insert(entry.txType); + + // Validate that all fields listed in permissions.macro exist in the + // corresponding transaction type's format, catching typos at startup. + for (auto const& [type, entry] : granularPermissions_) + { + if (!txDelegationMap_.contains(entry.txType)) + { + // LCOV_EXCL_START + Throw("Invalid granular permission txType in txDelegationMap_"); + // LCOV_EXCL_STOP + } + + auto const* fmt = TxFormats::getInstance().findByType(entry.txType); + if (fmt == nullptr) + { + // LCOV_EXCL_START + Throw("Invalid granular permission txType"); + // LCOV_EXCL_STOP + } + + for (auto const& field : entry.permittedFields) + { + if (fmt->getSOTemplate().getIndex(field.sField()) == -1) + { + // LCOV_EXCL_START + Throw("Invalid granular permission field"); + // LCOV_EXCL_STOP + } + } } } @@ -97,8 +142,11 @@ Permission::getInstance() } std::optional -Permission::getPermissionName(std::uint32_t const value) const +Permission::getPermissionName(std::uint32_t value) const { + if (value == 0) + return std::nullopt; + auto const permissionValue = static_cast(value); if (auto const granular = getGranularName(permissionValue)) return granular; @@ -114,90 +162,131 @@ Permission::getPermissionName(std::uint32_t const value) const std::optional Permission::getGranularValue(std::string const& name) const { - auto const it = granularPermissionMap_.find(name); - if (it != granularPermissionMap_.end()) + auto const it = granularPermissionsByName_.find(name); + if (it != granularPermissionsByName_.end()) return static_cast(it->second); return std::nullopt; } std::optional -Permission::getGranularName(GranularPermissionType const& value) const +Permission::getGranularName(GranularPermissionType value) const { - auto const it = granularNameMap_.find(value); - if (it != granularNameMap_.end()) - return it->second; + auto const it = granularPermissions_.find(value); + if (it != granularPermissions_.end()) + return it->second.name; return std::nullopt; } std::optional -Permission::getGranularTxType(GranularPermissionType const& gpType) const +Permission::getGranularTxType(GranularPermissionType gpType) const { - auto const it = granularTxTypeMap_.find(gpType); - if (it != granularTxTypeMap_.end()) - return it->second; + auto const it = granularPermissions_.find(gpType); + if (it != granularPermissions_.end()) + return it->second.txType; return std::nullopt; } +bool +Permission::hasGranularPermissions(TxType txType) const +{ + return granularTxTypes_.contains(txType); +} + std::optional> Permission::getTxFeature(TxType txType) const { - auto const txFeaturesIt = txFeatureMap_.find(txType); + auto const it = txDelegationMap_.find(txType); XRPL_ASSERT( - txFeaturesIt != txFeatureMap_.end(), - "xrpl::Permissions::getTxFeature : tx exists in txFeatureMap_"); + it != txDelegationMap_.end(), + "xrpl::Permission::getTxFeature : tx exists in txDelegationMap_"); - if (txFeaturesIt->second == uint256{}) + if (it->second.amendment == uint256{}) return std::nullopt; - return txFeaturesIt->second; + + return std::optional{std::cref(it->second.amendment)}; } bool -Permission::isDelegable(std::uint32_t const& permissionValue, Rules const& rules) const +Permission::isDelegable(std::uint32_t permissionValue, Rules const& rules) const { - auto const granularPermission = - getGranularName(static_cast(permissionValue)); - if (granularPermission) + if (permissionValue == 0) + return false; // LCOV_EXCL_LINE + + auto const amendmentEnabled = [&rules](TxDelegationEntry const& entry) { + return entry.amendment == uint256{} || rules.enabled(entry.amendment); + }; + + // Granular permissions may authorize a limited subset of a tx type even + // when the full tx type is not delegable. They still require the + // underlying transaction amendment to be enabled. + if (auto const granularIt = + granularPermissions_.find(static_cast(permissionValue)); + granularIt != granularPermissions_.end()) { - // granular permissions are always allowed to be delegated - return true; + auto const txIt = txDelegationMap_.find(granularIt->second.txType); + return txIt != txDelegationMap_.end() && amendmentEnabled(txIt->second); } auto const txType = permissionToTxType(permissionValue); - auto const it = delegableTx_.find(txType); + auto const txIt = txDelegationMap_.find(txType); - if (it == delegableTx_.end()) - return false; - - auto const txFeaturesIt = txFeatureMap_.find(txType); - XRPL_ASSERT( - txFeaturesIt != txFeatureMap_.end(), - "xrpl::Permissions::isDelegable : tx exists in txFeatureMap_"); - - // Delegation is only allowed if the required amendment for the transaction - // is enabled. For transactions that do not require an amendment, delegation - // is always allowed. - if (txFeaturesIt->second != uint256{} && !rules.enabled(txFeaturesIt->second)) - return false; - - if (it->second == Delegation::NotDelegable) - return false; - - return true; + // Tx-level permissions require the transaction type itself to be delegable, and + // the corresponding amendment enabled. + return txIt != txDelegationMap_.end() && txIt->second.delegable != NotDelegable && + amendmentEnabled(txIt->second); } uint32_t -Permission::txToPermissionType(TxType const& type) +Permission::txToPermissionType(TxType const type) { return static_cast(type) + 1; } TxType -Permission::permissionToTxType(uint32_t const& value) +Permission::permissionToTxType(uint32_t value) { + XRPL_ASSERT(value > 0, "xrpl::Permission::permissionToTxType : value is greater than 0"); return static_cast(value - 1); } +bool +Permission::checkGranularSandbox( + STTx const& tx, + std::unordered_set const& heldPermissions) const +{ + // Build union of flags upfront to enable an early exit. Fields are not stored and + // grouped in advance to avoid heap allocation. + std::uint32_t unionFlags = 0; + for (auto const& gp : heldPermissions) + { + auto const it = granularPermissions_.find(gp); + if (it != granularPermissions_.end()) + unionFlags |= it->second.permittedFlags; + } + + // Check if flags are permitted + if ((tx.getFlags() & ~unionFlags) != 0) + return false; + + // Check if fields are permitted. Every present field must appear in at least one held + // permission's template. The common fields are included in the constructor. + for (auto const& field : tx) + { + if (field.getSType() == STI_NOTPRESENT) + continue; + + if (!std::ranges::any_of(heldPermissions, [&](auto const& gp) { + auto const it = granularPermissions_.find(gp); + return it != granularPermissions_.end() && + it->second.permittedFields.getIndex(field.getFName()) != -1; + })) + return false; + } + + return true; +} + } // namespace xrpl diff --git a/src/libxrpl/protocol/STTx.cpp b/src/libxrpl/protocol/STTx.cpp index 55f0ea1289..be3b1a082f 100644 --- a/src/libxrpl/protocol/STTx.cpp +++ b/src/libxrpl/protocol/STTx.cpp @@ -217,7 +217,7 @@ STTx::getFeePayer() const { // If sfDelegate is present, the delegate account is the payer // note: if a delegate is specified, its authorization to act on behalf of the account is - // enforced in `Transactor::checkPermission` + // enforced in `Transactor::invokeCheckPermission` // cryptographic signature validity is checked separately (e.g., in `Transactor::checkSign`) if (isFieldPresent(sfDelegate)) return getAccountID(sfDelegate); diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index aa7b81c015..b57d30d2b3 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -46,6 +47,7 @@ #include #include #include +#include #include #include @@ -175,6 +177,16 @@ Transactor::preflight1(PreflightContext const& ctx, std::uint32_t flagMask) if (ctx.tx[sfDelegate] == ctx.tx[sfAccount]) return temBAD_SIGNER; + + auto const& perm = Permission::getInstance(); + auto const txType = ctx.tx.getTxnType(); + + // If the transaction is not delegable and does not have granular permissions, fail earlier + // with temINVALID. This is to prevent transactions that are not delegable at all from + // being processed further in the invokeCheckPermission function. + if (!perm.isDelegable(Permission::txToPermissionType(txType), ctx.rules) && + !perm.hasGranularPermissions(txType)) + return temINVALID; } if (auto const ret = preflight0(ctx, flagMask)) @@ -295,19 +307,33 @@ Transactor::preflightSigValidated(PreflightContext const& ctx) } NotTEC -Transactor::checkPermission(ReadView const& view, STTx const& tx) +Transactor::checkPermission( + ReadView const& view, + STTx const& tx, + std::unordered_set& heldGranularPermissions) { auto const delegate = tx[~sfDelegate]; if (!delegate) return tesSUCCESS; - auto const delegateKey = keylet::delegate(tx[sfAccount], *delegate); - auto const sle = view.read(delegateKey); - + auto const sle = view.read(keylet::delegate(tx[sfAccount], *delegate)); if (!sle) return terNO_DELEGATE_PERMISSION; - return checkTxPermission(sle, tx); + if (isTesSuccess(checkTxPermission(sle, tx))) + return tesSUCCESS; + + if (!Permission::getInstance().hasGranularPermissions(tx.getTxnType())) + return terNO_DELEGATE_PERMISSION; + + heldGranularPermissions = getGranularPermission(sle, tx.getTxnType()); + if (heldGranularPermissions.empty()) + return terNO_DELEGATE_PERMISSION; + + if (!Permission::getInstance().checkGranularSandbox(tx, heldGranularPermissions)) + return terNO_DELEGATE_PERMISSION; + + return tesSUCCESS; } XRPAmount diff --git a/src/libxrpl/tx/applySteps.cpp b/src/libxrpl/tx/applySteps.cpp index 336bb2004b..caaacfd010 100644 --- a/src/libxrpl/tx/applySteps.cpp +++ b/src/libxrpl/tx/applySteps.cpp @@ -181,7 +181,8 @@ invokePreclaim(PreclaimContext const& ctx) if (NotTEC const result = T::checkPriorTxAndLastLedger(ctx)) return result; - if (NotTEC const result = T::checkPermission(ctx.view, ctx.tx)) + if (NotTEC const result = + Transactor::invokeCheckPermission(ctx.view, ctx.tx)) return result; if (NotTEC const result = T::checkSign(ctx)) diff --git a/src/libxrpl/tx/transactors/account/AccountSet.cpp b/src/libxrpl/tx/transactors/account/AccountSet.cpp index bc207b39dc..36a7e7419f 100644 --- a/src/libxrpl/tx/transactors/account/AccountSet.cpp +++ b/src/libxrpl/tx/transactors/account/AccountSet.cpp @@ -6,7 +6,6 @@ #include #include #include -#include #include #include #include @@ -20,13 +19,11 @@ #include #include #include -#include #include #include #include #include -#include namespace xrpl { @@ -168,54 +165,6 @@ AccountSet::preflight(PreflightContext const& ctx) return tesSUCCESS; } -NotTEC -AccountSet::checkPermission(ReadView const& view, STTx const& tx) -{ - // AccountSet is prohibited to be granted on a transaction level, - // but some granular permissions are allowed. - auto const delegate = tx[~sfDelegate]; - if (!delegate) - return tesSUCCESS; - - auto const delegateKey = keylet::delegate(tx[sfAccount], *delegate); - auto const sle = view.read(delegateKey); - - if (!sle) - return terNO_DELEGATE_PERMISSION; - - std::unordered_set granularPermissions; - loadGranularPermission(sle, ttACCOUNT_SET, granularPermissions); - - auto const uSetFlag = tx.getFieldU32(sfSetFlag); - auto const uClearFlag = tx.getFieldU32(sfClearFlag); - // We don't support any flag based granular permission under - // AccountSet transaction. If any delegated account is trying to - // update the flag on behalf of another account, it is not - // authorized. - if (uSetFlag != 0 || uClearFlag != 0 || ((tx.getFlags() & tfUniversalMask) != 0u)) - return terNO_DELEGATE_PERMISSION; - - if (tx.isFieldPresent(sfEmailHash) && !granularPermissions.contains(AccountEmailHashSet)) - return terNO_DELEGATE_PERMISSION; - - if (tx.isFieldPresent(sfWalletLocator) || tx.isFieldPresent(sfNFTokenMinter)) - return terNO_DELEGATE_PERMISSION; - - if (tx.isFieldPresent(sfMessageKey) && !granularPermissions.contains(AccountMessageKeySet)) - return terNO_DELEGATE_PERMISSION; - - if (tx.isFieldPresent(sfDomain) && !granularPermissions.contains(AccountDomainSet)) - return terNO_DELEGATE_PERMISSION; - - if (tx.isFieldPresent(sfTransferRate) && !granularPermissions.contains(AccountTransferRateSet)) - return terNO_DELEGATE_PERMISSION; - - if (tx.isFieldPresent(sfTickSize) && !granularPermissions.contains(AccountTickSizeSet)) - return terNO_DELEGATE_PERMISSION; - - return tesSUCCESS; -} - TER AccountSet::preclaim(PreclaimContext const& ctx) { diff --git a/src/libxrpl/tx/transactors/delegate/DelegateUtils.cpp b/src/libxrpl/tx/transactors/delegate/DelegateUtils.cpp index dc6c98f95e..6def542c7d 100644 --- a/src/libxrpl/tx/transactors/delegate/DelegateUtils.cpp +++ b/src/libxrpl/tx/transactors/delegate/DelegateUtils.cpp @@ -29,14 +29,12 @@ checkTxPermission(SLE::const_ref delegate, STTx const& tx) return terNO_DELEGATE_PERMISSION; } -void -loadGranularPermission( - SLE::const_ref delegate, - TxType const& txType, - std::unordered_set& granularPermissions) +std::unordered_set +getGranularPermission(SLE::const_ref delegate, TxType const& txType) { + std::unordered_set granularPermissions; if (!delegate) - return; + return granularPermissions; auto const permissionArray = delegate->getFieldArray(sfPermissions); for (auto const& permission : permissionArray) @@ -47,6 +45,8 @@ loadGranularPermission( if (type && *type == txType) granularPermissions.insert(granularValue); } + + return granularPermissions; } } // namespace xrpl diff --git a/src/libxrpl/tx/transactors/payment/Payment.cpp b/src/libxrpl/tx/transactors/payment/Payment.cpp index 805ebe3684..9a9a01ec19 100644 --- a/src/libxrpl/tx/transactors/payment/Payment.cpp +++ b/src/libxrpl/tx/transactors/payment/Payment.cpp @@ -8,7 +8,6 @@ #include #include #include -#include #include #include #include @@ -29,7 +28,6 @@ #include #include #include -#include #include #include #include @@ -273,38 +271,24 @@ Payment::preflight(PreflightContext const& ctx) } NotTEC -Payment::checkPermission(ReadView const& view, STTx const& tx) +Payment::checkGranularSemantics( + ReadView const& view, + STTx const& tx, + std::unordered_set const& heldGranularPermissions) { - auto const delegate = tx[~sfDelegate]; - if (!delegate) - return tesSUCCESS; - - auto const delegateKey = keylet::delegate(tx[sfAccount], *delegate); - auto const sle = view.read(delegateKey); - - if (!sle) - return terNO_DELEGATE_PERMISSION; - - if (isTesSuccess(checkTxPermission(sle, tx))) - return tesSUCCESS; - - std::unordered_set granularPermissions; - loadGranularPermission(sle, ttPAYMENT, granularPermissions); - auto const& dstAmount = tx.getFieldAmount(sfAmount); auto const& amountAsset = dstAmount.asset(); // Granular permissions are only valid for direct payments. - if ((tx.isFieldPresent(sfSendMax) && tx[sfSendMax].asset() != amountAsset) || - tx.isFieldPresent(sfPaths)) + if (tx.isFieldPresent(sfSendMax) && tx[sfSendMax].asset() != amountAsset) return terNO_DELEGATE_PERMISSION; // PaymentMint and PaymentBurn apply to both IOU and MPT direct payments. - if (granularPermissions.contains(PaymentMint) && !isXRP(amountAsset) && + if (heldGranularPermissions.contains(PaymentMint) && !isXRP(amountAsset) && amountAsset.getIssuer() == tx[sfAccount]) return tesSUCCESS; - if (granularPermissions.contains(PaymentBurn) && !isXRP(amountAsset) && + if (heldGranularPermissions.contains(PaymentBurn) && !isXRP(amountAsset) && amountAsset.getIssuer() == tx[sfDestination]) return tesSUCCESS; diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp index 9b25531161..683d65b6f9 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -16,14 +15,12 @@ #include #include #include -#include #include #include #include #include #include -#include namespace xrpl { @@ -138,39 +135,6 @@ MPTokenIssuanceSet::preflight(PreflightContext const& ctx) return tesSUCCESS; } -NotTEC -MPTokenIssuanceSet::checkPermission(ReadView const& view, STTx const& tx) -{ - auto const delegate = tx[~sfDelegate]; - if (!delegate) - return tesSUCCESS; - - auto const delegateKey = keylet::delegate(tx[sfAccount], *delegate); - auto const sle = view.read(delegateKey); - - if (!sle) - return terNO_DELEGATE_PERMISSION; - - if (isTesSuccess(checkTxPermission(sle, tx))) - return tesSUCCESS; - - // this is added in case more flags will be added for MPTokenIssuanceSet - // in the future. Currently unreachable. - if ((tx.getFlags() & tfMPTokenIssuanceSetMask) != 0u) - return terNO_DELEGATE_PERMISSION; // LCOV_EXCL_LINE - - std::unordered_set granularPermissions; - loadGranularPermission(sle, ttMPTOKEN_ISSUANCE_SET, granularPermissions); - - if (tx.isFlag(tfMPTLock) && !granularPermissions.contains(MPTokenIssuanceLock)) - return terNO_DELEGATE_PERMISSION; - - if (tx.isFlag(tfMPTUnlock) && !granularPermissions.contains(MPTokenIssuanceUnlock)) - return terNO_DELEGATE_PERMISSION; - - return tesSUCCESS; -} - TER MPTokenIssuanceSet::preclaim(PreclaimContext const& ctx) { diff --git a/src/libxrpl/tx/transactors/token/TrustSet.cpp b/src/libxrpl/tx/transactors/token/TrustSet.cpp index 1d2bc96693..7838b212b2 100644 --- a/src/libxrpl/tx/transactors/token/TrustSet.cpp +++ b/src/libxrpl/tx/transactors/token/TrustSet.cpp @@ -6,7 +6,6 @@ #include #include #include -#include #include #include #include @@ -21,7 +20,6 @@ #include #include #include -#include #include #include #include @@ -124,51 +122,21 @@ TrustSet::preflight(PreflightContext const& ctx) } NotTEC -TrustSet::checkPermission(ReadView const& view, STTx const& tx) +TrustSet::checkGranularSemantics( + ReadView const& view, + STTx const& tx, + std::unordered_set const& heldGranularPermissions) { - auto const delegate = tx[~sfDelegate]; - if (!delegate) - return tesSUCCESS; - - auto const delegateKey = keylet::delegate(tx[sfAccount], *delegate); - auto const sle = view.read(delegateKey); - - if (!sle) - return terNO_DELEGATE_PERMISSION; - - if (isTesSuccess(checkTxPermission(sle, tx))) - return tesSUCCESS; - - // Currently we only support TrustlineAuthorize, TrustlineFreeze and - // TrustlineUnfreeze granular permission. Setting other flags returns - // error. - if ((tx.getFlags() & tfTrustSetPermissionMask) != 0u) - return terNO_DELEGATE_PERMISSION; - - if (tx.isFieldPresent(sfQualityIn) || tx.isFieldPresent(sfQualityOut)) - return terNO_DELEGATE_PERMISSION; - auto const saLimitAmount = tx.getFieldAmount(sfLimitAmount); auto const sleRippleState = view.read( keylet::line( tx[sfAccount], saLimitAmount.getIssuer(), saLimitAmount.get().currency)); - // if the trustline does not exist, granular permissions are - // not allowed to create trustline + // granular permissions are not allowed to create a trustline if (!sleRippleState) return terNO_DELEGATE_PERMISSION; - std::unordered_set granularPermissions; - loadGranularPermission(sle, ttTRUST_SET, granularPermissions); - - if (tx.isFlag(tfSetfAuth) && !granularPermissions.contains(TrustlineAuthorize)) - return terNO_DELEGATE_PERMISSION; - if (tx.isFlag(tfSetFreeze) && !granularPermissions.contains(TrustlineFreeze)) - return terNO_DELEGATE_PERMISSION; - if (tx.isFlag(tfClearFreeze) && !granularPermissions.contains(TrustlineUnfreeze)) - return terNO_DELEGATE_PERMISSION; - - // updating LimitAmount is not allowed only with granular permissions, + // updating LimitAmount is not allowed with granular permissions, // unless there's a new granular permission for this in the future. auto const curLimit = tx[sfAccount] > saLimitAmount.getIssuer() ? sleRippleState->getFieldAmount(sfHighLimit) diff --git a/src/test/app/Delegate_test.cpp b/src/test/app/Delegate_test.cpp index 70b091290c..20668a42bf 100644 --- a/src/test/app/Delegate_test.cpp +++ b/src/test/app/Delegate_test.cpp @@ -5,8 +5,11 @@ #include #include #include +#include #include +#include #include +#include #include #include #include @@ -22,7 +25,9 @@ #include #include #include +#include +#include #include #include #include @@ -33,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -41,6 +47,7 @@ #include #include #include +#include #include #include @@ -1063,6 +1070,93 @@ class Delegate_test : public beast::unit_test::Suite } } + // PaymentMint/PaymentBurn with sfSendMax of the same asset is allowed, + // same-asset SendMax is still a direct payment, not cross-currency. + { + Env env(*this, features); + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const gw{"gw"}; + auto const usd = gw["USD"]; + env.fund(XRP(10000), alice, bob, gw); + env.trust(usd(200), alice); + env.close(); + + env(delegate::set(gw, bob, {"PaymentMint"})); + env.close(); + + // sfSendMax with same asset as sfAmount, still a direct payment + env(pay(gw, alice, usd(50)), Sendmax(usd(50)), delegate::As(bob)); + env.require(Balance(alice, usd(50))); + + env(delegate::set(alice, bob, {"PaymentBurn"})); + env.close(); + + env(pay(alice, gw, usd(30)), Sendmax(usd(30)), delegate::As(bob)); + env.require(Balance(alice, usd(20))); + } + + // Test invalid fields or flags not allowed in granular permission template + { + Env env(*this, features); + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const gw{"gw"}; + auto const usd = gw["USD"]; + env.fund(XRP(10000), alice, bob, gw); + env.trust(usd(200), alice); + env.close(); + + env(delegate::set(gw, bob, {"PaymentMint"})); + env(delegate::set(alice, bob, {"PaymentBurn"})); + env.close(); + + // sfDeliverMin (with tfPartialPayment) is not in the PaymentMint + // or PaymentBurn template. + env(pay(gw, alice, usd(100)), + DeliverMin(usd(50)), + Txflags(tfPartialPayment), + delegate::As(bob), + Ter(terNO_DELEGATE_PERMISSION)); + env(pay(alice, gw, usd(50)), + DeliverMin(usd(25)), + Txflags(tfPartialPayment), + delegate::As(bob), + Ter(terNO_DELEGATE_PERMISSION)); + + // sfDomainID is not in the PaymentMint or PaymentBurn template. + env(pay(gw, alice, usd(100)), + Domain(uint256{1}), + delegate::As(bob), + Ter(terNO_DELEGATE_PERMISSION)); + env(pay(alice, gw, usd(50)), + Domain(uint256{1}), + delegate::As(bob), + Ter(terNO_DELEGATE_PERMISSION)); + } + + // Delegate account holds no granular permissions for the tx type: + // getGranularPermission returns empty set. + { + Env env(*this, features); + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const gw{"gw"}; + auto const usd = gw["USD"]; + env.fund(XRP(10000), alice, bob, gw); + env.trust(usd(200), alice); + env.close(); + + // Bob holds only an AccountSet granular permission. + env(delegate::set(alice, bob, {"AccountDomainSet"})); + env.close(); + + // Payment has granular permissions defined in permissions.macro, + // but bob only holds AccountSet's granular permission, + // getGranularPermission returns empty. + env(pay(alice, gw, usd(50)), delegate::As(bob), Ter(terNO_DELEGATE_PERMISSION)); + } + // PaymentMint and PaymentBurn for MPT { std::string logs; @@ -1119,6 +1213,40 @@ class Delegate_test : public beast::unit_test::Suite BEAST_EXPECT(env.balance(bob, MPT) == bobMPT + MPT(100)); } } + + // Verify granular permissions of different tx types in the same SLE are scoped + // correctly. AccountSet permissions don't apply to Payment and vice versa + { + Env env(*this); + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const gw{"gw"}; + auto const usd = gw["USD"]; + env.fund(XRP(10000), alice, bob, gw); + env.trust(usd(200), alice); + env.close(); + + // Alice granted bob with both AccountDomainSet and PaymentMint. + env(delegate::set(alice, bob, {"AccountDomainSet", "PaymentMint"})); + env.close(); + + // PaymentMint fails at granular semantic check because alice is not the issuer. + env(pay(alice, gw, usd(50)), delegate::As(bob), Ter(terNO_DELEGATE_PERMISSION)); + + // AccountDomainSet applies correctly to AccountSet + std::string const domain = "example.com"; + auto jt = noop(alice); + jt[sfDomain] = strHex(domain); + jt[sfDelegate] = bob.human(); + env(jt); + BEAST_EXPECT((*env.le(alice))[sfDomain] == makeSlice(domain)); + + // gw gives bob PaymentMint and bob can mint on gw's behalf + env(delegate::set(gw, bob, {"PaymentMint"})); + env.close(); + env(pay(gw, alice, usd(50)), delegate::As(bob)); + env.require(Balance(alice, usd(50))); + } } void @@ -1301,6 +1429,34 @@ class Delegate_test : public beast::unit_test::Suite env(trust(gw, gw["USD"](0), alice, tfSetfAuth | tfFullyCanonicalSig), delegate::As(bob)); } + + { + Env env(*this); + Account const gw{"gw"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(10000), gw, alice, bob); + + env(fset(gw, asfRequireAuth)); + env.close(); + env(trust(alice, gw["USD"](50))); + env.close(); + env(delegate::set(gw, bob, {"TrustlineAuthorize"})); + env.close(); + + env(trust(gw, gw["USD"](0), alice, tfSetfAuth), delegate::As(bob)); + env.close(); + + // sfQualityOut is a valid TrustSet field, but not permitted in granular template + json::Value txJson = trust(gw, gw["USD"](0), alice, tfSetfAuth); + txJson[sfQualityOut.jsonName] = 100; + env(txJson, delegate::As(bob), Ter(terNO_DELEGATE_PERMISSION)); + + // tfSetNoRipple is a valid flag for TrustSet, but not permitted in granular template + env(trust(gw, gw["USD"](0), alice, tfSetfAuth | tfSetNoRipple), + delegate::As(bob), + Ter(terNO_DELEGATE_PERMISSION)); + } } void @@ -1456,7 +1612,9 @@ class Delegate_test : public beast::unit_test::Suite env(jv2, Ter(terNO_DELEGATE_PERMISSION)); } - // can not set AccountSet flags on behalf of other account + // can not set AccountSet flags on behalf of other account, + // in permissions.macro, the template for AccountSet does + // not allow any flag set or clear. { Env env(*this); auto const alice = Account{"alice"}; @@ -1552,6 +1710,71 @@ class Delegate_test : public beast::unit_test::Suite env(jt); BEAST_EXPECT((*env.le(alice))[sfDomain] == makeSlice(domain)); } + + // setting invalid field not in permissions.macro template will be rejected. + { + Env env(*this); + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + env.fund(XRP(10000), alice, bob); + env.close(); + + // Alice gives Bob permission to set her Domain + env(delegate::set(alice, bob, {"AccountDomainSet"})); + env.close(); + + std::string const domain = "example.com"; + auto txJson = noop(alice); + txJson[sfDomain] = strHex(domain); + txJson[sfDelegate] = bob.human(); + + // sfNFTokenMinter is a valid field in AccountSet tx, but + // it is not permitted for granular template + txJson[sfNFTokenMinter] = bob.human(); + + env(txJson, Ter(terNO_DELEGATE_PERMISSION)); + } + + // Delegated AccountSet with no fields and no flags is allowed, + // because it is allowed in the non-delegated case as well. + { + Env env(*this); + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(10000), alice, bob); + env.close(); + + env(delegate::set(alice, bob, {"AccountDomainSet"})); + env.close(); + + auto jt = noop(alice); + jt[sfDelegate] = bob.human(); + env(jt); + } + + // Revoking all permissions deletes the SLE and subsequent attempts are rejected. + { + Env env(*this); + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(10000), alice, bob); + env.close(); + + env(delegate::set(alice, bob, {"AccountDomainSet"})); + env.close(); + + std::string const domain = "example.com"; + auto jt = noop(alice); + jt[sfDomain] = strHex(domain); + jt[sfDelegate] = bob.human(); + env(jt); + + // empty DelegateSet deletes the SLE + env(delegate::set(alice, bob, {})); + env.close(); + + env(jt, Ter(terNO_DELEGATE_PERMISSION)); + } } void @@ -1672,6 +1895,37 @@ class Delegate_test : public beast::unit_test::Suite env.close(); mpt.set({.account = alice, .flags = tfMPTLock | tfFullyCanonicalSig, .delegate = bob}); } + + // field not permitted to exist in granular delegation + { + Env env(*this); + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(100000), alice, bob); + + MPTTester mpt(env, alice, {.fund = false}); + mpt.create({.flags = tfMPTCanLock}); + env.close(); + + // alice gives granular permission to bob for MPTokenIssuanceLock + env(delegate::set(alice, bob, {"MPTokenIssuanceLock"})); + env.close(); + + // Field is not permitted, permitted fields for delegation is defined in + // permissions.macro. + mpt.set( + {.account = alice, + .mutableFlags = 2, + .delegate = bob, + .err = terNO_DELEGATE_PERMISSION}); + + // Notice: flags not defined in permissions.macro are not permitted for delegation. + // Since preflight will check invalid flag for the tx, it is not reachable. + // If any new flag is defined into the transaction in the future, + // but is not allowed for delegation, the transaction will be rejected with + // terNO_DELEGATE_PERMISSION. The set of permitted flags for delegation is defined in + // permissions.macro. + } } void @@ -2141,6 +2395,62 @@ class Delegate_test : public beast::unit_test::Suite for (auto const& tx : txRequiredFeatures) txAmendmentEnabled(tx.first); } + + // Granular permissions also require the amendment for their underlying + // transaction type. + { + for (auto const permission : {"MPTokenIssuanceLock", "MPTokenIssuanceUnlock"}) + { + Env env(*this, features - featureMPTokensV1); + + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(100000), alice, bob); + env.close(); + + env(delegate::set(alice, bob, {permission}), Ter(temMALFORMED)); + } + } + } + + void + testGranularSandboxCheckOrder() + { + testcase("Make sure GranularSandbox is checked after transaction-level permission"); + + using namespace jtx; + + Env env(*this); + Account const gw{"gw"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(10000), gw, alice, bob); + + env(fset(gw, asfRequireAuth)); + env.close(); + env(trust(alice, gw["USD"](50))); + env.close(); + env(delegate::set(gw, bob, {"TrustlineAuthorize"})); + env.close(); + + env(trust(gw, gw["USD"](0), alice, tfSetfAuth), delegate::As(bob)); + env.close(); + + // sfQualityOut is a valid TrustSet field, but not permitted in granular template + json::Value txJson = trust(gw, gw["USD"](0), alice, tfSetfAuth); + txJson[sfQualityOut.jsonName] = 100; + env(txJson, delegate::As(bob), Ter(terNO_DELEGATE_PERMISSION)); + + // Now Alice grants Bob with transaction level permission + env(delegate::set(gw, bob, {"TrustlineAuthorize", "TrustSet"})); + env.close(); + + // NOTE: This case is to ensure that if a delegate possesses a + // transaction-level permission (e.g., TrustSet), the granular sandbox must not incorrectly + // block the transaction. The function checkGranularSandbox MUST be called after the + // transaction-level permission check. This test case is to avoid future refactor mistakes, + // modifying the order will fail here. + env(txJson, delegate::As(bob)); } void @@ -2193,6 +2503,94 @@ class Delegate_test : public beast::unit_test::Suite "\n Action: Verify security requirements to interact with Delegation feature"); } + void + testNonDelegableTxWithDelegate(FeatureBitset features) + { + testcase("non-delegable tx with sfDelegate is rejected at preflight"); + using namespace jtx; + + Env env(*this, features); + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(10000), alice, bob); + env.close(); + + // Transactions that are notDelegable and have no granular permissions + // will be rejected with temINVALID at preflight. + // Note: pseudo-transactions (EnableAmendment, SetFee and UNLModify) are also + // notDelegable but are excluded here — passesLocalChecks() blocks them + // before preflight1 is ever reached. + { + // SetRegularKey, SignerListSet, AccountDelete, DelegateSet. + env(regkey(alice, bob), delegate::As(bob), Ter(temINVALID)); + env(signers(alice, 1, {{bob, 1}}), delegate::As(bob), Ter(temINVALID)); + env(acctdelete(alice, bob), delegate::As(bob), Ter(temINVALID)); + env(delegate::set(alice, bob, {"Payment"}), delegate::As(bob), Ter(temINVALID)); + + // SAV transactions. + { + Vault const vault{env}; + auto [createTx, keylet] = vault.create({.owner = alice, .asset = xrpIssue()}); + env(createTx, delegate::As(bob), Ter(temINVALID)); + + env(vault.set({.owner = alice, .id = keylet.key}), + delegate::As(bob), + Ter(temINVALID)); + env(vault.del({.owner = alice, .id = keylet.key}), + delegate::As(bob), + Ter(temINVALID)); + env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = XRP(1)}), + delegate::As(bob), + Ter(temINVALID)); + env(vault.withdraw({.depositor = alice, .id = keylet.key, .amount = XRP(1)}), + delegate::As(bob), + Ter(temINVALID)); + env(vault.clawback({.issuer = alice, .id = keylet.key, .holder = bob}), + delegate::As(bob), + Ter(temINVALID)); + } + + // Batch transaction: the outer Batch itself is non-delegable. + { + auto const seq = env.seq(alice); + auto const batchFee = batch::calcBatchFee(env, 0, 1); + env(batch::outer(alice, seq, batchFee, tfAllOrNothing), + batch::Inner(pay(alice, bob, XRP(1)), seq + 1), + delegate::As(bob), + Ter(temINVALID)); + } + + // Lending protocol transactions + { + Vault const vault{env}; + auto [createTx, keylet] = vault.create({.owner = alice, .asset = xrpIssue()}); + env(createTx); + + env(loanBroker::set(alice, keylet.key), delegate::As(bob), Ter(temINVALID)); + env(loanBroker::del(alice, keylet.key), delegate::As(bob), Ter(temINVALID)); + env(loanBroker::coverDeposit(alice, keylet.key, XRP(1)), + delegate::As(bob), + Ter(temINVALID)); + env(loanBroker::coverWithdraw(alice, keylet.key, XRP(1)), + delegate::As(bob), + Ter(temINVALID)); + env(loanBroker::coverClawback(alice), delegate::As(bob), Ter(temINVALID)); + + env(loan::set(alice, keylet.key, Number(100)), delegate::As(bob), Ter(temINVALID)); + env(loan::manage(alice, keylet.key, 0), delegate::As(bob), Ter(temINVALID)); + env(loan::del(alice, keylet.key), delegate::As(bob), Ter(temINVALID)); + env(loan::pay(alice, keylet.key, XRP(1)), delegate::As(bob), Ter(temINVALID)); + } + } + + // AccountSet is notDelegable at tx level but has granular permissions, + // so sfDelegate passes preflight and is rejected at invokeCheckPermission with + // terNO_DELEGATE_PERMISSION. + { + env(fset(alice, asfDefaultRipple), delegate::As(bob), Ter(terNO_DELEGATE_PERMISSION)); + } + } + void testDelegateUtilsNullptrCheck() { @@ -2202,9 +2600,8 @@ class Delegate_test : public beast::unit_test::Suite STTx const tx{ttPAYMENT, [](STObject&) {}}; BEAST_EXPECT(checkTxPermission(nullptr, tx) == terNO_DELEGATE_PERMISSION); - // loadGranularPermission nullptr check - std::unordered_set granularPermissions; - loadGranularPermission(nullptr, ttPAYMENT, granularPermissions); + // getGranularPermission nullptr check + auto const granularPermissions = getGranularPermission(nullptr, ttPAYMENT); BEAST_EXPECT(granularPermissions.empty()); } @@ -2234,7 +2631,9 @@ class Delegate_test : public beast::unit_test::Suite testSignForDelegated(); testPermissionValue(all); testTxRequireFeatures(all); + testGranularSandboxCheckOrder(); testTxDelegableCount(); + testNonDelegableTxWithDelegate(all); testDelegateUtilsNullptrCheck(); } }; From b6a1ad5bb3cea836b4d4571238640c8007ed27d9 Mon Sep 17 00:00:00 2001 From: Michael Legleux Date: Thu, 18 Jun 2026 12:21:12 -0700 Subject: [PATCH 71/78] fix: Ensure xrpld service directories exist at startup (#7565) --- package/shared/xrpld.service | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/package/shared/xrpld.service b/package/shared/xrpld.service index 7f3496acbb..f54e47aa14 100644 --- a/package/shared/xrpld.service +++ b/package/shared/xrpld.service @@ -17,6 +17,10 @@ ProtectHome=true PrivateTmp=true User=xrpld Group=xrpld +StateDirectory=xrpld +StateDirectoryMode=0750 +LogsDirectory=xrpld +LogsDirectoryMode=0750 LimitNOFILE=65536 SystemCallArchitectures=native From b1f794f06792a55bd33e5b544593425713c6cd0f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 22 Jun 2026 09:39:38 -0400 Subject: [PATCH 72/78] ci: [DEPENDABOT] bump actions/checkout from 6.0.3 to 7.0.0 (#7585) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/check-pr-description.yml | 2 +- .github/workflows/on-pr.yml | 2 +- .github/workflows/publish-docs.yml | 2 +- .github/workflows/reusable-build-test-config.yml | 2 +- .github/workflows/reusable-check-levelization.yml | 2 +- .github/workflows/reusable-check-rename.yml | 2 +- .github/workflows/reusable-clang-tidy.yml | 2 +- .github/workflows/reusable-package.yml | 6 +++--- .github/workflows/reusable-strategy-matrix.yml | 2 +- .github/workflows/reusable-upload-recipe.yml | 2 +- .github/workflows/upload-conan-deps.yml | 2 +- 11 files changed, 13 insertions(+), 13 deletions(-) diff --git a/.github/workflows/check-pr-description.yml b/.github/workflows/check-pr-description.yml index a60b83738a..744449f216 100644 --- a/.github/workflows/check-pr-description.yml +++ b/.github/workflows/check-pr-description.yml @@ -23,7 +23,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - name: Write PR body to file env: diff --git a/.github/workflows/on-pr.yml b/.github/workflows/on-pr.yml index 4b2edeb93d..0cc9b375a7 100644 --- a/.github/workflows/on-pr.yml +++ b/.github/workflows/on-pr.yml @@ -33,7 +33,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - name: Determine changed files # This step checks whether any files have changed that should # cause the next jobs to run. We do it this way rather than diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index 0de5347aab..cc7b6b6e7e 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -44,7 +44,7 @@ jobs: container: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-fe4c8ae steps: - name: Checkout repository - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - name: Prepare runner uses: XRPLF/actions/prepare-runner@c47daebb2f9db64ffbac71b47d68a661498d5ce8 diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index 95e6b0cbe2..3e6464aaba 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -110,7 +110,7 @@ jobs: uses: XRPLF/actions/cleanup-workspace@c7d9ce5ebb03c752a354889ecd870cadfc2b1cd4 - name: Checkout repository - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - name: Prepare runner uses: XRPLF/actions/prepare-runner@c47daebb2f9db64ffbac71b47d68a661498d5ce8 diff --git a/.github/workflows/reusable-check-levelization.yml b/.github/workflows/reusable-check-levelization.yml index 813c0e1e36..88c95ac3ba 100644 --- a/.github/workflows/reusable-check-levelization.yml +++ b/.github/workflows/reusable-check-levelization.yml @@ -18,7 +18,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - name: Check levelization run: python .github/scripts/levelization/generate.py - name: Check for differences diff --git a/.github/workflows/reusable-check-rename.yml b/.github/workflows/reusable-check-rename.yml index 5002cc7f40..9a91e98ee3 100644 --- a/.github/workflows/reusable-check-rename.yml +++ b/.github/workflows/reusable-check-rename.yml @@ -18,7 +18,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - name: Check definitions run: .github/scripts/rename/definitions.sh . - name: Check copyright notices diff --git a/.github/workflows/reusable-clang-tidy.yml b/.github/workflows/reusable-clang-tidy.yml index 5d2325cb1d..c663f71842 100644 --- a/.github/workflows/reusable-clang-tidy.yml +++ b/.github/workflows/reusable-clang-tidy.yml @@ -45,7 +45,7 @@ jobs: issues: write steps: - name: Checkout repository - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - name: Prepare runner uses: XRPLF/actions/prepare-runner@c47daebb2f9db64ffbac71b47d68a661498d5ce8 diff --git a/.github/workflows/reusable-package.yml b/.github/workflows/reusable-package.yml index 0e3f657006..eed4bfc4a3 100644 --- a/.github/workflows/reusable-package.yml +++ b/.github/workflows/reusable-package.yml @@ -27,7 +27,7 @@ jobs: matrix: ${{ steps.generate.outputs.matrix }} steps: - name: Checkout repository - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - name: Set up Python uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 @@ -45,7 +45,7 @@ jobs: version: ${{ steps.version.outputs.version }} steps: - name: Checkout repository - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: sparse-checkout: | .github/actions/generate-version @@ -69,7 +69,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - name: Download pre-built binary uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 diff --git a/.github/workflows/reusable-strategy-matrix.yml b/.github/workflows/reusable-strategy-matrix.yml index 4518a8ffef..c1a1c1a78b 100644 --- a/.github/workflows/reusable-strategy-matrix.yml +++ b/.github/workflows/reusable-strategy-matrix.yml @@ -23,7 +23,7 @@ jobs: matrix: ${{ steps.generate.outputs.matrix }} steps: - name: Checkout repository - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - name: Set up Python uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 diff --git a/.github/workflows/reusable-upload-recipe.yml b/.github/workflows/reusable-upload-recipe.yml index ba7a0943d9..a389e98771 100644 --- a/.github/workflows/reusable-upload-recipe.yml +++ b/.github/workflows/reusable-upload-recipe.yml @@ -43,7 +43,7 @@ jobs: container: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-fe4c8ae steps: - name: Checkout repository - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - name: Generate build version number id: version diff --git a/.github/workflows/upload-conan-deps.yml b/.github/workflows/upload-conan-deps.yml index 7ca9d13007..5d3712cf9e 100644 --- a/.github/workflows/upload-conan-deps.yml +++ b/.github/workflows/upload-conan-deps.yml @@ -65,7 +65,7 @@ jobs: uses: XRPLF/actions/cleanup-workspace@c7d9ce5ebb03c752a354889ecd870cadfc2b1cd4 - name: Checkout repository - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - name: Prepare runner uses: XRPLF/actions/prepare-runner@c47daebb2f9db64ffbac71b47d68a661498d5ce8 From e29b523620ee47cc1ecd1df523b80ffdcacc1c9e Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Mon, 22 Jun 2026 18:00:40 +0100 Subject: [PATCH 73/78] ci: Build and push docker images in forks too (#7588) --- .github/workflows/build-nix-images.yml | 6 +++--- .github/workflows/build-packaging-images.yml | 6 +++--- .github/workflows/pre-commit.yml | 2 +- .github/workflows/reusable-clang-tidy.yml | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/build-nix-images.yml b/.github/workflows/build-nix-images.yml index 3af6a3b1d4..54911ef6e0 100644 --- a/.github/workflows/build-nix-images.yml +++ b/.github/workflows/build-nix-images.yml @@ -54,9 +54,9 @@ jobs: base_image: debian:bookworm - name: rhel base_image: registry.access.redhat.com/ubi9/ubi:latest - uses: XRPLF/actions/.github/workflows/build-multiarch-image.yml@c1b480188519e0cad040e6aa70db1cbc5a797e07 + uses: XRPLF/actions/.github/workflows/build-multiarch-image.yml@ee03d31bcc4501d7599dc1b1ecd7a34af582ad1c with: - image_name: ghcr.io/xrplf/xrpld/nix-${{ matrix.distro.name }} + image_name: xrpld/nix-${{ matrix.distro.name }} dockerfile: nix/docker/Dockerfile base_image: ${{ matrix.distro.base_image }} - push: ${{ github.repository == 'XRPLF/rippled' && github.event_name == 'push' }} + push: ${{ github.event_name == 'push' }} diff --git a/.github/workflows/build-packaging-images.yml b/.github/workflows/build-packaging-images.yml index d6dabb0f95..3633847ef3 100644 --- a/.github/workflows/build-packaging-images.yml +++ b/.github/workflows/build-packaging-images.yml @@ -38,9 +38,9 @@ jobs: base_image: debian:bookworm - name: rhel base_image: registry.access.redhat.com/ubi9/ubi:latest - uses: XRPLF/actions/.github/workflows/build-multiarch-image.yml@c1b480188519e0cad040e6aa70db1cbc5a797e07 + uses: XRPLF/actions/.github/workflows/build-multiarch-image.yml@ee03d31bcc4501d7599dc1b1ecd7a34af582ad1c with: - image_name: ghcr.io/xrplf/xrpld/packaging-${{ matrix.distro.name }} + image_name: xrpld/packaging-${{ matrix.distro.name }} dockerfile: package/Dockerfile base_image: ${{ matrix.distro.base_image }} - push: ${{ github.repository == 'XRPLF/rippled' && github.event_name == 'push' }} + push: ${{ github.event_name == 'push' }} diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index aecf0c2a8b..0363534af5 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -14,7 +14,7 @@ on: jobs: # Call the workflow in the XRPLF/actions repo that runs the pre-commit hooks. run-hooks: - uses: XRPLF/actions/.github/workflows/pre-commit.yml@312aaab296060ff89d7f798dcab59f019bea6e02 + uses: XRPLF/actions/.github/workflows/pre-commit.yml@e06d4138c9ec8dceeb7c818645faa38087ea9e3d with: runs_on: ubuntu-latest container: '{ "image": "ghcr.io/xrplf/ci/tools-rippled-pre-commit:sha-41ec7c1" }' diff --git a/.github/workflows/reusable-clang-tidy.yml b/.github/workflows/reusable-clang-tidy.yml index c663f71842..e99ef574bf 100644 --- a/.github/workflows/reusable-clang-tidy.yml +++ b/.github/workflows/reusable-clang-tidy.yml @@ -32,7 +32,7 @@ jobs: if: ${{ inputs.check_only_changed }} permissions: contents: read - uses: XRPLF/actions/.github/workflows/determine-tidy-files.yml@312aaab296060ff89d7f798dcab59f019bea6e02 + uses: XRPLF/actions/.github/workflows/determine-tidy-files.yml@c7045074aafe9fb92fa537aa4446f81fbfc17e8b run-clang-tidy: name: Run clang tidy From 997267f84555ca9758394681e26b888eb0699bed Mon Sep 17 00:00:00 2001 From: yinyiqian1 Date: Mon, 22 Jun 2026 13:36:06 -0400 Subject: [PATCH 74/78] feat: Remove clear mutable flags for DynamicMPT XLS-94 (#7439) --- include/xrpl/protocol/LedgerFormats.h | 12 +- include/xrpl/protocol/TxFlags.h | 42 +- include/xrpl/protocol/detail/features.macro | 2 +- .../transactors/token/MPTokenIssuanceSet.cpp | 66 +- src/test/app/AMMMPT_test.cpp | 16 +- src/test/app/Loan_test.cpp | 189 +-- src/test/app/MPToken_test.cpp | 1260 ++++++++--------- src/test/app/Vault_test.cpp | 243 +--- src/test/jtx/impl/mpt.cpp | 72 +- 9 files changed, 684 insertions(+), 1218 deletions(-) diff --git a/include/xrpl/protocol/LedgerFormats.h b/include/xrpl/protocol/LedgerFormats.h index 99d5d818f1..c1274e9e91 100644 --- a/include/xrpl/protocol/LedgerFormats.h +++ b/include/xrpl/protocol/LedgerFormats.h @@ -180,12 +180,12 @@ enum LedgerEntryType : std::uint16_t { LSF_FLAG(lsfMPTCanClawback, 0x00000040)) \ \ LEDGER_OBJECT(MPTokenIssuanceMutable, \ - LSF_FLAG(lsmfMPTCanMutateCanLock, 0x00000002) \ - LSF_FLAG(lsmfMPTCanMutateRequireAuth, 0x00000004) \ - LSF_FLAG(lsmfMPTCanMutateCanEscrow, 0x00000008) \ - LSF_FLAG(lsmfMPTCanMutateCanTrade, 0x00000010) \ - LSF_FLAG(lsmfMPTCanMutateCanTransfer, 0x00000020) \ - LSF_FLAG(lsmfMPTCanMutateCanClawback, 0x00000040) \ + LSF_FLAG(lsmfMPTCanEnableCanLock, 0x00000002) \ + LSF_FLAG(lsmfMPTCanEnableRequireAuth, 0x00000004) \ + LSF_FLAG(lsmfMPTCanEnableCanEscrow, 0x00000008) \ + LSF_FLAG(lsmfMPTCanEnableCanTrade, 0x00000010) \ + LSF_FLAG(lsmfMPTCanEnableCanTransfer, 0x00000020) \ + LSF_FLAG(lsmfMPTCanEnableCanClawback, 0x00000040) \ LSF_FLAG(lsmfMPTCanMutateMetadata, 0x00010000) \ LSF_FLAG(lsmfMPTCanMutateTransferFee, 0x00020000)) \ \ diff --git a/include/xrpl/protocol/TxFlags.h b/include/xrpl/protocol/TxFlags.h index 4652cc1bf0..f9c7bc1a5d 100644 --- a/include/xrpl/protocol/TxFlags.h +++ b/include/xrpl/protocol/TxFlags.h @@ -341,38 +341,32 @@ inline constexpr FlagValue tfTrustSetPermissionMask = // MPTokenIssuanceCreate MutableFlags: // Indicating specific fields or flags may be changed after issuance. -inline constexpr FlagValue tmfMPTCanMutateCanLock = lsmfMPTCanMutateCanLock; -inline constexpr FlagValue tmfMPTCanMutateRequireAuth = lsmfMPTCanMutateRequireAuth; -inline constexpr FlagValue tmfMPTCanMutateCanEscrow = lsmfMPTCanMutateCanEscrow; -inline constexpr FlagValue tmfMPTCanMutateCanTrade = lsmfMPTCanMutateCanTrade; -inline constexpr FlagValue tmfMPTCanMutateCanTransfer = lsmfMPTCanMutateCanTransfer; -inline constexpr FlagValue tmfMPTCanMutateCanClawback = lsmfMPTCanMutateCanClawback; +inline constexpr FlagValue tmfMPTCanEnableCanLock = lsmfMPTCanEnableCanLock; +inline constexpr FlagValue tmfMPTCanEnableRequireAuth = lsmfMPTCanEnableRequireAuth; +inline constexpr FlagValue tmfMPTCanEnableCanEscrow = lsmfMPTCanEnableCanEscrow; +inline constexpr FlagValue tmfMPTCanEnableCanTrade = lsmfMPTCanEnableCanTrade; +inline constexpr FlagValue tmfMPTCanEnableCanTransfer = lsmfMPTCanEnableCanTransfer; +inline constexpr FlagValue tmfMPTCanEnableCanClawback = lsmfMPTCanEnableCanClawback; inline constexpr FlagValue tmfMPTCanMutateMetadata = lsmfMPTCanMutateMetadata; inline constexpr FlagValue tmfMPTCanMutateTransferFee = lsmfMPTCanMutateTransferFee; inline constexpr FlagValue tmfMPTokenIssuanceCreateMutableMask = - ~(tmfMPTCanMutateCanLock | tmfMPTCanMutateRequireAuth | tmfMPTCanMutateCanEscrow | - tmfMPTCanMutateCanTrade | tmfMPTCanMutateCanTransfer | tmfMPTCanMutateCanClawback | + ~(tmfMPTCanEnableCanLock | tmfMPTCanEnableRequireAuth | tmfMPTCanEnableCanEscrow | + tmfMPTCanEnableCanTrade | tmfMPTCanEnableCanTransfer | tmfMPTCanEnableCanClawback | tmfMPTCanMutateMetadata | tmfMPTCanMutateTransferFee); // MPTokenIssuanceSet MutableFlags: -// Set or Clear flags. +// Enable mutable capability flags. These flags are one-way: once enabled, +// the corresponding capability cannot be disabled by MPTokenIssuanceSet. inline constexpr FlagValue tmfMPTSetCanLock = 0x00000001; -inline constexpr FlagValue tmfMPTClearCanLock = 0x00000002; -inline constexpr FlagValue tmfMPTSetRequireAuth = 0x00000004; -inline constexpr FlagValue tmfMPTClearRequireAuth = 0x00000008; -inline constexpr FlagValue tmfMPTSetCanEscrow = 0x00000010; -inline constexpr FlagValue tmfMPTClearCanEscrow = 0x00000020; -inline constexpr FlagValue tmfMPTSetCanTrade = 0x00000040; -inline constexpr FlagValue tmfMPTClearCanTrade = 0x00000080; -inline constexpr FlagValue tmfMPTSetCanTransfer = 0x00000100; -inline constexpr FlagValue tmfMPTClearCanTransfer = 0x00000200; -inline constexpr FlagValue tmfMPTSetCanClawback = 0x00000400; -inline constexpr FlagValue tmfMPTClearCanClawback = 0x00000800; -inline constexpr FlagValue tmfMPTokenIssuanceSetMutableMask = ~( - tmfMPTSetCanLock | tmfMPTClearCanLock | tmfMPTSetRequireAuth | tmfMPTClearRequireAuth | - tmfMPTSetCanEscrow | tmfMPTClearCanEscrow | tmfMPTSetCanTrade | tmfMPTClearCanTrade | - tmfMPTSetCanTransfer | tmfMPTClearCanTransfer | tmfMPTSetCanClawback | tmfMPTClearCanClawback); +inline constexpr FlagValue tmfMPTSetRequireAuth = 0x00000002; +inline constexpr FlagValue tmfMPTSetCanEscrow = 0x00000004; +inline constexpr FlagValue tmfMPTSetCanTrade = 0x00000008; +inline constexpr FlagValue tmfMPTSetCanTransfer = 0x00000010; +inline constexpr FlagValue tmfMPTSetCanClawback = 0x00000020; +inline constexpr FlagValue tmfMPTokenIssuanceSetMutableMask = + ~(tmfMPTSetCanLock | tmfMPTSetRequireAuth | tmfMPTSetCanEscrow | tmfMPTSetCanTrade | + tmfMPTSetCanTransfer | tmfMPTSetCanClawback); // Prior to fixRemoveNFTokenAutoTrustLine, transfer of an NFToken between accounts allowed a // TrustLine to be added to the issuer of that token without explicit permission from that issuer. diff --git a/include/xrpl/protocol/detail/features.macro b/include/xrpl/protocol/detail/features.macro index d25b0b1f2c..573dca951d 100644 --- a/include/xrpl/protocol/detail/features.macro +++ b/include/xrpl/protocol/detail/features.macro @@ -24,7 +24,7 @@ XRPL_FEATURE(LendingProtocol, Supported::Yes, VoteBehavior::DefaultN XRPL_FEATURE(PermissionDelegationV1_1, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FIX (DirectoryLimit, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FIX (IncludeKeyletFields, Supported::Yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(DynamicMPT, Supported::No, VoteBehavior::DefaultNo) +XRPL_FEATURE(DynamicMPT, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FIX (TokenEscrowV1, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FIX (PriceOracleOrder, Supported::Yes, VoteBehavior::DefaultNo) XRPL_FIX (MPTDeliveredAmount, Supported::Yes, VoteBehavior::DefaultNo) diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp index 683d65b6f9..1cb12709d5 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp @@ -38,35 +38,34 @@ MPTokenIssuanceSet::getFlagsMask(PreflightContext const& ctx) return tfMPTokenIssuanceSetMask; } -// Maps set/clear mutable flags in an MPTokenIssuanceSet transaction to the -// corresponding ledger mutable flags that control whether the change is -// allowed. +// Maps each MPTokenIssuanceSet MutableFlags to the corresponding mutable +// flag and the target ledger flag to mutate. struct MPTMutabilityFlags { std::uint32_t setFlag; - std::uint32_t clearFlag; - std::uint32_t canMutateFlag; + std::uint32_t canEnableFlag; + std::uint32_t ledgerFlag; }; static constexpr std::array kMptMutabilityFlags = { {{.setFlag = tmfMPTSetCanLock, - .clearFlag = tmfMPTClearCanLock, - .canMutateFlag = lsmfMPTCanMutateCanLock}, + .canEnableFlag = lsmfMPTCanEnableCanLock, + .ledgerFlag = lsfMPTCanLock}, {.setFlag = tmfMPTSetRequireAuth, - .clearFlag = tmfMPTClearRequireAuth, - .canMutateFlag = lsmfMPTCanMutateRequireAuth}, + .canEnableFlag = lsmfMPTCanEnableRequireAuth, + .ledgerFlag = lsfMPTRequireAuth}, {.setFlag = tmfMPTSetCanEscrow, - .clearFlag = tmfMPTClearCanEscrow, - .canMutateFlag = lsmfMPTCanMutateCanEscrow}, + .canEnableFlag = lsmfMPTCanEnableCanEscrow, + .ledgerFlag = lsfMPTCanEscrow}, {.setFlag = tmfMPTSetCanTrade, - .clearFlag = tmfMPTClearCanTrade, - .canMutateFlag = lsmfMPTCanMutateCanTrade}, + .canEnableFlag = lsmfMPTCanEnableCanTrade, + .ledgerFlag = lsfMPTCanTrade}, {.setFlag = tmfMPTSetCanTransfer, - .clearFlag = tmfMPTClearCanTransfer, - .canMutateFlag = lsmfMPTCanMutateCanTransfer}, + .canEnableFlag = lsmfMPTCanEnableCanTransfer, + .ledgerFlag = lsfMPTCanTransfer}, {.setFlag = tmfMPTSetCanClawback, - .clearFlag = tmfMPTClearCanClawback, - .canMutateFlag = lsmfMPTCanMutateCanClawback}}}; + .canEnableFlag = lsmfMPTCanEnableCanClawback, + .ledgerFlag = lsfMPTCanClawback}}}; NotTEC MPTokenIssuanceSet::preflight(PreflightContext const& ctx) @@ -118,17 +117,6 @@ MPTokenIssuanceSet::preflight(PreflightContext const& ctx) { if ((*mutableFlags == 0u) || ((*mutableFlags & tmfMPTokenIssuanceSetMutableMask) != 0u)) return temINVALID_FLAG; - - // Can not set and clear the same flag - if (std::ranges::any_of(kMptMutabilityFlags, [mutableFlags](auto const& f) { - return (*mutableFlags & f.setFlag) && (*mutableFlags & f.clearFlag); - })) - return temINVALID_FLAG; - - // Trying to set a non-zero TransferFee and clear MPTCanTransfer - // in the same transaction is not allowed. - if ((transferFee.value_or(0) != 0u) && ((*mutableFlags & tmfMPTClearCanTransfer) != 0u)) - return temMALFORMED; } } @@ -196,16 +184,9 @@ MPTokenIssuanceSet::preclaim(PreclaimContext const& ctx) if (auto const mutableFlags = ctx.tx[~sfMutableFlags]) { if (std::ranges::any_of(kMptMutabilityFlags, [mutableFlags, &isMutableFlag](auto const& f) { - return !isMutableFlag(f.canMutateFlag) && - ((*mutableFlags & (f.setFlag | f.clearFlag))); + return !isMutableFlag(f.canEnableFlag) && ((*mutableFlags & f.setFlag) != 0u); })) return tecNO_PERMISSION; - - // Clearing lsfMPTRequireAuth is invalid when the issuance already has - // a DomainID set, because a DomainID requires RequireAuth to be active. - if ((*mutableFlags & tmfMPTClearRequireAuth) != 0u && - sleMptIssuance->isFieldPresent(sfDomainID)) - return tecNO_PERMISSION; } if (!isMutableFlag(lsmfMPTCanMutateMetadata) && ctx.tx.isFieldPresent(sfMPTokenMetadata)) @@ -265,19 +246,8 @@ MPTokenIssuanceSet::doApply() { if ((mutableFlags & f.setFlag) != 0u) { - flagsOut |= f.canMutateFlag; + flagsOut |= f.ledgerFlag; } - else if ((mutableFlags & f.clearFlag) != 0u) - { - flagsOut &= ~f.canMutateFlag; - } - } - - if ((mutableFlags & tmfMPTClearCanTransfer) != 0u) - { - // If the lsfMPTCanTransfer flag is being cleared, then also clear - // the TransferFee field. - sle->makeFieldAbsent(sfTransferFee); } } diff --git a/src/test/app/AMMMPT_test.cpp b/src/test/app/AMMMPT_test.cpp index 31b54ceee0..5b576b41e4 100644 --- a/src/test/app/AMMMPT_test.cpp +++ b/src/test/app/AMMMPT_test.cpp @@ -2240,7 +2240,9 @@ private: .err = Ter(tecNO_AUTH)}); } - // MPTCanTransfer is not set and the account is not the issuer of MPT + // MPTCanTransfer is not set and the account is not the issuer of MPT. + // The issuer can create the AMM, and an existing LP token holder can + // still withdraw. { Env env{*this}; env.fund(XRP(30'000), gw_, alice_); @@ -2250,15 +2252,17 @@ private: .issuer = gw_, .holders = {alice_}, .pay = 30'000, - .flags = kMptDexFlags, - .mutableFlags = tmfMPTCanMutateCanTransfer, + .flags = tfMPTCanTrade, .authHolder = true}); AMM amm(env, gw_, XRP(10'000), btc(10'000)); - amm.deposit(DepositArg{.account = alice_, .asset1In = XRP(200), .asset2In = btc(200)}); - // Allow to withdraw if transfer is disabled - btc.set({.mutableFlags = tmfMPTClearCanTransfer}); + auto const lpIssue = amm.lptIssue(); + env.trust(STAmount{lpIssue, 20'000'000}, alice_); + env.close(); + env(pay(gw_, alice_, LPToken(1'000'000).tokens(lpIssue))); + env.close(); + amm.withdraw( WithdrawArg{.account = alice_, .asset1Out = btc(100), .assets = {{XRP, btc}}}); } diff --git a/src/test/app/Loan_test.cpp b/src/test/app/Loan_test.cpp index c3b5850231..dbb0033368 100644 --- a/src/test/app/Loan_test.cpp +++ b/src/test/app/Loan_test.cpp @@ -4,7 +4,6 @@ #include #include #include -#include #include #include #include @@ -5423,110 +5422,12 @@ protected: } void - testCoverDepositWithdrawNonTransferableMPT(FeatureBitset feature) + testLendingCanTradeDisabledNoImpact() { - testcase("CoverDeposit blocked, CoverWithdraw allowed when CanTransfer cleared"); - using namespace jtx; - using namespace loanBroker; - - Env env(*this, feature); - - Account const issuer{"issuer"}; - Account const alice{"alice"}; - - env.fund(XRP(100'000), issuer, alice); - env.close(); - - MPTTester mpt( - {.env = env, - .issuer = issuer, - .holders = {alice}, - .pay = 100, - .flags = tfMPTCanTransfer, - .mutableFlags = tmfMPTCanMutateCanTransfer}); - PrettyAsset const asset = mpt["MPT"]; - - Vault const vault{env}; - auto const [createTx, vaultKeylet] = vault.create({.owner = alice, .asset = asset}); - env(createTx); - env.close(); - - auto const brokerKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); - env(set(alice, vaultKeylet.key)); - env.close(); - - auto const brokerSle = env.le(brokerKeylet); - if (!BEAST_EXPECT(brokerSle)) - return; - - Account const pseudoAccount{"Loan Broker pseudo-account", brokerSle->at(sfAccount)}; - - // First, deposit some cover while CanTransfer is set so we have an - // existing position to withdraw from after the governance action. - auto const depositAmount = asset(1); - env(coverDeposit(alice, brokerKeylet.key, depositAmount)); - env.close(); - - if (auto const refreshed = env.le(brokerKeylet); BEAST_EXPECT(refreshed)) - { - BEAST_EXPECT(refreshed->at(sfCoverAvailable) == 1); - env.require(Balance(pseudoAccount, depositAmount)); - } - - // Issuer governance: clear CanTransfer. - mpt.set({.mutableFlags = tmfMPTClearCanTransfer}); - env.close(); - - // Standard Payment path still forbids third-party transfers. - auto const err = feature[featureMPTokensV2] ? tecNO_PERMISSION : tecNO_AUTH; - env(pay(alice, pseudoAccount, asset(1)), Ter(err)); - env.close(); - - // New cover deposits are blocked - this would create new exposure. - env(coverDeposit(alice, brokerKeylet.key, depositAmount), Ter{tecNO_AUTH}); - env.close(); - - if (auto const refreshed = env.le(brokerKeylet); BEAST_EXPECT(refreshed)) - { - BEAST_EXPECT(refreshed->at(sfCoverAvailable) == 1); - env.require(Balance(pseudoAccount, depositAmount)); - } - - bool const postAmendment = feature[fixCleanup3_2_0]; - if (postAmendment) - { - // Post-fixCleanup3_2_0: existing cover can always be withdrawn - // even when CanTransfer is cleared, so the broker is not trapped. - env(coverWithdraw(alice, brokerKeylet.key, depositAmount)); - env.close(); - - if (auto const refreshed = env.le(brokerKeylet); BEAST_EXPECT(refreshed)) - { - BEAST_EXPECT(refreshed->at(sfCoverAvailable) == 0); - env.require(Balance(pseudoAccount, asset(0))); - } - } - else - { - // Pre-fixCleanup3_2_0 regression: cover withdraw was blocked, - // trapping the broker's first-loss capital. - env(coverWithdraw(alice, brokerKeylet.key, depositAmount), Ter{tecNO_AUTH}); - env.close(); - - if (auto const refreshed = env.le(brokerKeylet); BEAST_EXPECT(refreshed)) - { - BEAST_EXPECT(refreshed->at(sfCoverAvailable) == 1); - env.require(Balance(pseudoAccount, depositAmount)); - } - } - } - - void - testLoanSetBlockedLoanPayAllowedWhenCanTransferCleared() - { - testcase("LoanSet blocked, LoanPay allowed when CanTransfer cleared"); + testcase("Lending: CanTrade disabled has no impact"); using namespace jtx; using namespace loan; + using namespace loanBroker; Env env(*this, all_); @@ -5542,67 +5443,7 @@ protected: .issuer = issuer, .holders = {lender, borrower}, .flags = tfMPTCanTransfer | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTransfer}); - PrettyAsset const asset = mpt.issuanceID(); - env(pay(issuer, lender, asset(10'000'000))); - // Fund the borrower with enough to cover principal+interest+fees - env(pay(issuer, borrower, asset(100'000))); - env.close(); - - // Create vault and broker while CanTransfer is set. - auto const broker = createVaultAndBroker(env, asset, lender); - - auto const loanSetFee = Fee(env.current()->fees().base * 2); - - // Create an existing loan while CanTransfer is set. - env(set(borrower, broker.brokerID, 1'000), - Sig(sfCounterpartySignature, lender), - loanSetFee); - env.close(); - auto const loanKeylet = keylet::loan(broker.brokerID, 1); - BEAST_EXPECT(env.le(loanKeylet)); - - // Issuer governance: clear CanTransfer. - mpt.set({.mutableFlags = tmfMPTClearCanTransfer}); - env.close(); - - // Issuing a NEW loan is blocked - it would create new exposure into - // a pool the issuer is restricting. - env(set(borrower, broker.brokerID, 1'000), - Sig(sfCounterpartySignature, lender), - loanSetFee, - Ter{tecNO_AUTH}); - env.close(); - - // Repaying an existing loan is always allowed - blocking it would - // create irrecoverable bad debt and trap SAV depositor principal. - env(pay(borrower, loanKeylet.key, asset(1'000))); - env.close(); - } - - void - testLendingCanTradeClearedNoImpact() - { - testcase("Lending: CanTrade cleared has no impact"); - using namespace jtx; - using namespace loan; - using namespace loanBroker; - - Env env(*this, all_); - - Account const issuer{"issuer"}; - Account const lender{"lender"}; - Account const borrower{"borrower"}; - - env.fund(XRP(1'000'000), issuer, lender, borrower); - env.close(); - - MPTTester mpt( - {.env = env, - .issuer = issuer, - .holders = {lender, borrower}, - .flags = tfMPTCanTransfer | tfMPTCanTrade | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTrade}); + .mutableFlags = tmfMPTCanEnableCanTrade}); PrettyAsset const asset = mpt.issuanceID(); env(pay(issuer, lender, asset(10'000'000))); env(pay(issuer, borrower, asset(100'000))); @@ -5610,16 +5451,7 @@ protected: auto const broker = createVaultAndBroker(env, asset, lender); - // Sanity: while CanTrade is set, the asset can be placed on the DEX. - env(offer(lender, XRP(1), asset(10))); - env.close(); - - // Issuer governance: clear CanTrade. Loan origination and repayment - // are not trades: nothing in the Lending Protocol should be impacted. - mpt.set({.mutableFlags = tmfMPTClearCanTrade}); - env.close(); - - // Control: clearing CanTrade is observable on the DEX path. + // CanTrade is not set env(offer(lender, XRP(1), asset(10)), Ter{tecNO_PERMISSION}); env.close(); @@ -5644,6 +5476,13 @@ protected: // Cover withdrawal still works. env(coverWithdraw(lender, broker.brokerID, asset(100))); env.close(); + + // Enable CanTrade and verify the DEX path is restored. + mpt.set({.mutableFlags = tmfMPTSetCanTrade}); + env.close(); + + env(offer(lender, XRP(1), asset(10))); + env.close(); } #if LOAN_TODO @@ -8716,8 +8555,7 @@ protected: testRIPD3901(); testBorrowerIsBroker(); testLimitExceeded(); - testLoanSetBlockedLoanPayAllowedWhenCanTransferCleared(); - testLendingCanTradeClearedNoImpact(); + testLendingCanTradeDisabledNoImpact(); testBugOverpaymentPrincipalChange(); testBugOverpayUnroundedAmount(); @@ -8747,7 +8585,6 @@ protected: testPoCUnsignedUnderflowOnFullPayAfterEarlyPeriodic(features); testBatchBypassCounterparty(features); testLoanNextPaymentDueDateOverflow(features); - testCoverDepositWithdrawNonTransferableMPT(features); testSequentialFLCDepletion(features); // Invariants diff --git a/src/test/app/MPToken_test.cpp b/src/test/app/MPToken_test.cpp index 3d6cff0885..2cab3e7c89 100644 --- a/src/test/app/MPToken_test.cpp +++ b/src/test/app/MPToken_test.cpp @@ -3485,7 +3485,7 @@ class MPToken_test : public beast::unit_test::Suite MPTTester mptAlice(env, alice, {.holders = {bob}}); mptAlice.create( {.ownerCount = 1, - .mutableFlags = tmfMPTCanMutateMetadata | tmfMPTCanMutateCanLock | + .mutableFlags = tmfMPTCanMutateMetadata | tmfMPTCanEnableCanLock | tmfMPTCanMutateTransferFee}); // Setting flags is not allowed when MutableFlags is present @@ -3533,33 +3533,6 @@ class MPToken_test : public beast::unit_test::Suite } } - // Can not set and clear the same mutable flag - { - Env env{*this, features}; - MPTTester mptAlice(env, alice, {.holders = {bob}}); - auto const mptID = makeMptID(env.seq(alice), alice); - - auto const flagCombinations = { - tmfMPTSetCanLock | tmfMPTClearCanLock, - tmfMPTSetRequireAuth | tmfMPTClearRequireAuth, - tmfMPTSetCanEscrow | tmfMPTClearCanEscrow, - tmfMPTSetCanTrade | tmfMPTClearCanTrade, - tmfMPTSetCanTransfer | tmfMPTClearCanTransfer, - tmfMPTSetCanClawback | tmfMPTClearCanClawback, - tmfMPTSetCanLock | tmfMPTClearCanLock | tmfMPTClearCanTrade, - tmfMPTSetCanTransfer | tmfMPTClearCanTransfer | tmfMPTSetCanEscrow | - tmfMPTClearCanClawback}; - - for (auto const& mutableFlags : flagCombinations) - { - mptAlice.set( - {.account = alice, - .id = mptID, - .mutableFlags = mutableFlags, - .err = temINVALID_FLAG}); - } - } - // Can not mutate flag which is not mutable { Env env{*this, features}; @@ -3569,17 +3542,11 @@ class MPToken_test : public beast::unit_test::Suite auto const mutableFlags = { tmfMPTSetCanLock, - tmfMPTClearCanLock, tmfMPTSetRequireAuth, - tmfMPTClearRequireAuth, tmfMPTSetCanEscrow, - tmfMPTClearCanEscrow, tmfMPTSetCanTrade, - tmfMPTClearCanTrade, tmfMPTSetCanTransfer, - tmfMPTClearCanTransfer, - tmfMPTSetCanClawback, - tmfMPTClearCanClawback}; + tmfMPTSetCanClawback}; for (auto const& mutableFlag : mutableFlags) { @@ -3623,34 +3590,6 @@ class MPToken_test : public beast::unit_test::Suite .err = temBAD_TRANSFER_FEE}); } - // Test setting non-zero transfer fee and clearing MPTCanTransfer at the - // same time - { - Env env{*this, features}; - MPTTester mptAlice(env, alice, {.holders = {bob}}); - - mptAlice.create( - {.transferFee = 100, - .ownerCount = 1, - .flags = tfMPTCanTransfer, - .mutableFlags = tmfMPTCanMutateTransferFee | tmfMPTCanMutateCanTransfer}); - - // Can not set non-zero transfer fee and clear MPTCanTransfer at the - // same time - mptAlice.set( - {.account = alice, - .mutableFlags = tmfMPTClearCanTransfer, - .transferFee = 1, - .err = temMALFORMED}); - - // Can set transfer fee to zero and clear MPTCanTransfer at the same - // time. tfMPTCanTransfer will be cleared and TransferFee field will - // be removed. - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearCanTransfer, .transferFee = 0}); - BEAST_EXPECT(!mptAlice.isTransferFeePresent()); - } - // Can not set non-zero transfer fee when MPTCanTransfer is not set { Env env{*this, features}; @@ -3658,7 +3597,7 @@ class MPToken_test : public beast::unit_test::Suite mptAlice.create( {.ownerCount = 1, - .mutableFlags = tmfMPTCanMutateTransferFee | tmfMPTCanMutateCanTransfer}); + .mutableFlags = tmfMPTCanMutateTransferFee | tmfMPTCanEnableCanTransfer}); mptAlice.set({.account = alice, .transferFee = 100, .err = tecNO_PERMISSION}); @@ -3691,21 +3630,14 @@ class MPToken_test : public beast::unit_test::Suite mptAlice.create( {.ownerCount = 1, - .mutableFlags = tmfMPTCanMutateCanTrade | tmfMPTCanMutateCanTransfer | + .mutableFlags = tmfMPTCanEnableCanTrade | tmfMPTCanEnableCanTransfer | tmfMPTCanMutateMetadata}); // Can not mutate transfer fee mptAlice.set({.account = alice, .transferFee = 100, .err = tecNO_PERMISSION}); auto const invalidFlags = { - tmfMPTSetCanLock, - tmfMPTClearCanLock, - tmfMPTSetRequireAuth, - tmfMPTClearRequireAuth, - tmfMPTSetCanEscrow, - tmfMPTClearCanEscrow, - tmfMPTSetCanClawback, - tmfMPTClearCanClawback}; + tmfMPTSetCanLock, tmfMPTSetRequireAuth, tmfMPTSetCanEscrow, tmfMPTSetCanClawback}; // Can not mutate flags which are not mutable for (auto const& mutableFlag : invalidFlags) @@ -3716,11 +3648,9 @@ class MPToken_test : public beast::unit_test::Suite // Can mutate MPTCanTrade mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanTrade}); - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanTrade}); // Can mutate MPTCanTransfer mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanTransfer}); - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanTransfer}); // Can mutate metadata mptAlice.set({.account = alice, .metadata = "test"}); @@ -3789,37 +3719,26 @@ class MPToken_test : public beast::unit_test::Suite BEAST_EXPECT(mptAlice.checkTransferFee(10)); } - // Test flag toggling + // Test mutable flag enablement { - auto testFlagToggle = [&](std::uint32_t createFlags, - std::uint32_t setFlags, - std::uint32_t clearFlags) { + auto testFlagSet = [&](std::uint32_t createFlags, std::uint32_t setFlags) { Env env{*this, features}; MPTTester mptAlice(env, alice); // Create the MPT object with the specified initial flags mptAlice.create({.metadata = "test", .ownerCount = 1, .mutableFlags = createFlags}); - // Set and clear the flag multiple times - mptAlice.set({.account = alice, .mutableFlags = setFlags}); - mptAlice.set({.account = alice, .mutableFlags = clearFlags}); - mptAlice.set({.account = alice, .mutableFlags = clearFlags}); + // Setting the same mutable capability more than once is harmless. mptAlice.set({.account = alice, .mutableFlags = setFlags}); mptAlice.set({.account = alice, .mutableFlags = setFlags}); - mptAlice.set({.account = alice, .mutableFlags = clearFlags}); - mptAlice.set({.account = alice, .mutableFlags = setFlags}); - mptAlice.set({.account = alice, .mutableFlags = clearFlags}); }; - testFlagToggle(tmfMPTCanMutateCanLock, tfMPTCanLock, tmfMPTClearCanLock); - testFlagToggle( - tmfMPTCanMutateRequireAuth, tmfMPTSetRequireAuth, tmfMPTClearRequireAuth); - testFlagToggle(tmfMPTCanMutateCanEscrow, tmfMPTSetCanEscrow, tmfMPTClearCanEscrow); - testFlagToggle(tmfMPTCanMutateCanTrade, tmfMPTSetCanTrade, tmfMPTClearCanTrade); - testFlagToggle( - tmfMPTCanMutateCanTransfer, tmfMPTSetCanTransfer, tmfMPTClearCanTransfer); - testFlagToggle( - tmfMPTCanMutateCanClawback, tmfMPTSetCanClawback, tmfMPTClearCanClawback); + testFlagSet(tmfMPTCanEnableCanLock, tmfMPTSetCanLock); + testFlagSet(tmfMPTCanEnableRequireAuth, tmfMPTSetRequireAuth); + testFlagSet(tmfMPTCanEnableCanEscrow, tmfMPTSetCanEscrow); + testFlagSet(tmfMPTCanEnableCanTrade, tmfMPTSetCanTrade); + testFlagSet(tmfMPTCanEnableCanTransfer, tmfMPTSetCanTransfer); + testFlagSet(tmfMPTCanEnableCanClawback, tmfMPTSetCanClawback); } } @@ -3840,7 +3759,7 @@ class MPToken_test : public beast::unit_test::Suite {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock | tfMPTCanTransfer, - .mutableFlags = tmfMPTCanMutateCanLock | tmfMPTCanMutateCanTrade | + .mutableFlags = tmfMPTCanEnableCanLock | tmfMPTCanEnableCanTrade | tmfMPTCanMutateTransferFee}); mptAlice.authorize({.account = bob, .holderCount = 1}); @@ -3848,11 +3767,8 @@ class MPToken_test : public beast::unit_test::Suite mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTLock}); // Can mutate the mutable flags and fields - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanLock}); mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanLock}); - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanLock}); mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanTrade}); - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanTrade}); mptAlice.set({.account = alice, .transferFee = 200}); } @@ -3864,7 +3780,7 @@ class MPToken_test : public beast::unit_test::Suite {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanLock | tmfMPTCanMutateCanClawback | + .mutableFlags = tmfMPTCanEnableCanLock | tmfMPTCanEnableCanClawback | tmfMPTCanMutateMetadata}); mptAlice.authorize({.account = bob, .holderCount = 1}); @@ -3872,36 +3788,23 @@ class MPToken_test : public beast::unit_test::Suite mptAlice.set({.account = alice, .flags = tfMPTLock}); // Can mutate the mutable flags and fields - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanLock}); mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanLock}); - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanLock}); mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanClawback}); - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanClawback}); mptAlice.set({.account = alice, .metadata = "mutate"}); } - // Test lock and unlock after mutating MPTCanLock + // Test lock and unlock after enabling MPTCanLock { Env env{*this, features}; MPTTester mptAlice(env, alice, {.holders = {bob}}); mptAlice.create( {.ownerCount = 1, .holderCount = 0, - .flags = tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanLock | tmfMPTCanMutateCanClawback | + .mutableFlags = tmfMPTCanEnableCanLock | tmfMPTCanEnableCanClawback | tmfMPTCanMutateMetadata}); mptAlice.authorize({.account = bob, .holderCount = 1}); - // Can lock and unlock - mptAlice.set({.account = alice, .flags = tfMPTLock}); - mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTLock}); - mptAlice.set({.account = alice, .flags = tfMPTUnlock}); - mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTUnlock}); - - // Clear lsfMPTCanLock - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanLock}); - - // Can not lock or unlock + // Can not lock or unlock before MPTCanLock is enabled mptAlice.set({.account = alice, .flags = tfMPTLock, .err = tecNO_PERMISSION}); mptAlice.set({.account = alice, .flags = tfMPTUnlock, .err = tecNO_PERMISSION}); mptAlice.set( @@ -3909,10 +3812,10 @@ class MPToken_test : public beast::unit_test::Suite mptAlice.set( {.account = alice, .holder = bob, .flags = tfMPTUnlock, .err = tecNO_PERMISSION}); - // Set MPTCanLock again + // Set MPTCanLock mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanLock}); - // Can lock and unlock again + // Can lock and unlock mptAlice.set({.account = alice, .flags = tfMPTLock}); mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTLock}); mptAlice.set({.account = alice, .flags = tfMPTUnlock}); @@ -3926,83 +3829,30 @@ class MPToken_test : public beast::unit_test::Suite testcase("Mutate MPTRequireAuth"); using namespace test::jtx; - // test mutating RequireAuth flag on the issuance and its effect on payment authorization - { - Env env{*this, features}; - Account const alice("alice"); - Account const bob("bob"); + // test enabling RequireAuth flag on the issuance and its effect on payment + // authorization + Env env{*this, features}; + Account const alice("alice"); + Account const bob("bob"); - MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create( - {.ownerCount = 1, - .flags = tfMPTRequireAuth, - .mutableFlags = tmfMPTCanMutateRequireAuth}); + MPTTester mptAlice(env, alice, {.holders = {bob}}); + mptAlice.create( + {.ownerCount = 1, + .flags = tfMPTCanTransfer, + .mutableFlags = tmfMPTCanEnableRequireAuth}); - mptAlice.authorize({.account = bob}); - mptAlice.authorize({.account = alice, .holder = bob}); + mptAlice.authorize({.account = bob}); + mptAlice.pay(alice, bob, 1000); - // Pay to bob - mptAlice.pay(alice, bob, 1000); + // Set RequireAuth because it is mutable. + mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetRequireAuth}); - // Unauthorize bob - mptAlice.authorize({.account = alice, .holder = bob, .flags = tfMPTUnauthorize}); + // This should fail because bob is not authorized yet. + mptAlice.pay(alice, bob, 1000, tecNO_AUTH); - // Can not pay to bob - mptAlice.pay(bob, alice, 100, tecNO_AUTH); - - // Clear RequireAuth - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearRequireAuth}); - - // Can pay to bob - mptAlice.pay(alice, bob, 1000); - - // Set RequireAuth again - mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetRequireAuth}); - - // Can not pay to bob since he is not authorized - mptAlice.pay(bob, alice, 100, tecNO_AUTH); - - // Authorize bob again - mptAlice.authorize({.account = alice, .holder = bob}); - - // Can pay to bob again - mptAlice.pay(alice, bob, 100); - } - - // Cannot clear RequireAuth when a DomainID is set on the issuance - { - Account const alice{"alice"}; - Account const bob{"bob"}; - Account const credIssuer{"credIssuer"}; - pdomain::Credentials const credentials{ - {.issuer = credIssuer, .credType = "credential"}}; - - Env env{*this, features}; - env.fund(XRP(1000), credIssuer); - env.close(); - - env(pdomain::setTx(credIssuer, credentials)); - env.close(); - auto const domainId = pdomain::getNewDomain(env.meta()); - - MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create({ - .ownerCount = 1, - .flags = tfMPTRequireAuth, - .mutableFlags = tmfMPTCanMutateRequireAuth, - .domainID = domainId, - }); - - // Clearing RequireAuth while a DomainID is present must be rejected, - mptAlice.set({ - .account = alice, - .mutableFlags = tmfMPTClearRequireAuth, - .err = tecNO_PERMISSION, - }); - - // Setting RequireAuth (already set) is still allowed, though it has no effect. - mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetRequireAuth}); - } + // Issuer authorizes bob and pay should succeed. + mptAlice.authorize({.account = alice, .holder = bob}); + mptAlice.pay(alice, bob, 1000); } void @@ -4023,7 +3873,7 @@ class MPToken_test : public beast::unit_test::Suite {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer, - .mutableFlags = tmfMPTCanMutateCanEscrow}); + .mutableFlags = tmfMPTCanEnableCanEscrow}); mptAlice.authorize({.account = carol}); mptAlice.authorize({.account = bob}); @@ -4045,14 +3895,6 @@ class MPToken_test : public beast::unit_test::Suite escrow::kCondition(escrow::kCb1), escrow::kFinishTime(env.now() + 1s), Fee(baseFee * 150)); - - // Clear MPTCanEscrow - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanEscrow}); - env(escrow::create(carol, bob, mpt(3)), - escrow::kCondition(escrow::kCb1), - escrow::kFinishTime(env.now() + 1s), - Fee(baseFee * 150), - Ter(tecNO_PERMISSION)); } void @@ -4071,7 +3913,7 @@ class MPToken_test : public beast::unit_test::Suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); mptAlice.create( {.ownerCount = 1, - .mutableFlags = tmfMPTCanMutateCanTransfer | tmfMPTCanMutateTransferFee}); + .mutableFlags = tmfMPTCanEnableCanTransfer | tmfMPTCanMutateTransferFee}); mptAlice.authorize({.account = bob}); mptAlice.authorize({.account = carol}); @@ -4115,19 +3957,9 @@ class MPToken_test : public beast::unit_test::Suite env(pay(bob, carol, mptAlice(50)), Txflags(tfPartialPayment)); BEAST_EXPECT(env.balance(carol, mptc) == mptc(49)); } - - // Alice clears MPTCanTransfer - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanTransfer}); - - // TransferFee field is removed when MPTCanTransfer is cleared - BEAST_EXPECT(!mptAlice.isTransferFeePresent()); - - // Bob can not pay - mptAlice.pay(bob, carol, 50, tecNO_AUTH); } - // Can set transfer fee to zero when MPTCanTransfer is not set, but - // tmfMPTCanMutateTransferFee is set. + // Can set transfer fee to zero when tmfMPTCanMutateTransferFee is set. { Env env{*this, features}; @@ -4136,18 +3968,12 @@ class MPToken_test : public beast::unit_test::Suite {.transferFee = 100, .ownerCount = 1, .flags = tfMPTCanTransfer, - .mutableFlags = tmfMPTCanMutateTransferFee | tmfMPTCanMutateCanTransfer}); + .mutableFlags = tmfMPTCanMutateTransferFee}); BEAST_EXPECT(mptAlice.checkTransferFee(100)); - // Clear MPTCanTransfer and transfer fee is removed - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanTransfer}); - BEAST_EXPECT(!mptAlice.isTransferFeePresent()); - - // Can still set transfer fee to zero, although it is already zero + // Setting transfer fee to zero removes the field. mptAlice.set({.account = alice, .transferFee = 0}); - - // TransferFee field is still not present BEAST_EXPECT(!mptAlice.isTransferFeePresent()); } } @@ -4165,7 +3991,7 @@ class MPToken_test : public beast::unit_test::Suite MPTTester mptAlice(env, alice, {.holders = {bob}}); mptAlice.create( - {.ownerCount = 1, .holderCount = 0, .mutableFlags = tmfMPTCanMutateCanClawback}); + {.ownerCount = 1, .holderCount = 0, .mutableFlags = tmfMPTCanEnableCanClawback}); // Bob creates an MPToken mptAlice.authorize({.account = bob}); @@ -4181,12 +4007,6 @@ class MPToken_test : public beast::unit_test::Suite // Can clawback now mptAlice.claw(alice, bob, 1); - - // Clear MPTCanClawback - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanClawback}); - - // Can not clawback - mptAlice.claw(alice, bob, 1, tecNO_PERMISSION); } void @@ -4536,27 +4356,22 @@ class MPToken_test : public beast::unit_test::Suite { Env env(*this); env.fund(XRP(1'000), gw, alice, carol); - MPTTester btc( + MPTTester const btc( {.env = env, .issuer = gw, .holders = {alice, carol}, .pay = 100, - .flags = tfMPTCanTrade, - .mutableFlags = tmfMPTCanMutateCanTransfer}); - MPTTester eth( + .flags = tfMPTCanTrade | tfMPTCanTransfer}); + MPTTester const eth( {.env = env, .issuer = gw, .holders = {alice, carol}, .pay = 100, - .flags = tfMPTCanTrade | tfMPTCanTransfer, - .mutableFlags = tmfMPTCanMutateCanTransfer}); + .flags = tfMPTCanTrade}); // Can create env(offer(alice, eth(10), btc(10)), Txflags(tfPassive)); - btc.set({.mutableFlags = tmfMPTSetCanTransfer}); - eth.set({.mutableFlags = tmfMPTClearCanTransfer}); - env(offer(alice, eth(10), btc(10)), Txflags(tfPassive)); - BEAST_EXPECT(getAccountOffers(env, alice)[jss::offers].size() == 2); + BEAST_EXPECT(getAccountOffers(env, alice)[jss::offers].size() == 1); // issuer can create env(offer(gw, eth(10), btc(10)), Txflags(tfPassive)); @@ -4584,14 +4399,14 @@ class MPToken_test : public beast::unit_test::Suite .holders = {alice, carol}, .pay = 100, .flags = tfMPTCanTransfer, - .mutableFlags = tmfMPTCanMutateCanTrade}); + .mutableFlags = tmfMPTCanEnableCanTrade}); MPTTester const eth( {.env = env, .issuer = gw, .holders = {alice, carol}, .pay = 100, .flags = tfMPTCanTrade, - .mutableFlags = tmfMPTCanMutateCanTrade}); + .mutableFlags = tmfMPTCanEnableCanTrade}); // Can't create env(offer(gw, eth(10), btc(10)), Ter(tecNO_PERMISSION)); @@ -4828,29 +4643,29 @@ class MPToken_test : public beast::unit_test::Suite .holders = {alice, carol, bob}, .pay = 1'000, .flags = tfMPTCanLock | kMptDexFlags, - .mutableFlags = tmfMPTCanMutateRequireAuth | tmfMPTCanMutateCanTrade | - tmfMPTCanMutateCanTransfer}); + .mutableFlags = tmfMPTCanEnableRequireAuth | tmfMPTCanEnableCanTrade | + tmfMPTCanEnableCanTransfer}); MPTTester eth( {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 1'000, .flags = tfMPTCanLock | kMptDexFlags, - .mutableFlags = tmfMPTCanMutateCanTransfer}); + .mutableFlags = tmfMPTCanEnableCanTransfer}); MPTTester const usd( {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 1'000, .flags = kMptDexFlags | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTransfer}); + .mutableFlags = tmfMPTCanEnableCanTransfer}); MPTTester const cad( {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 1'000, .flags = kMptDexFlags | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTransfer}); + .mutableFlags = tmfMPTCanEnableCanTransfer}); env(offer(bob, eth(1'000), btc(1'000)), Txflags(tfPassive)); env.close(); @@ -4896,13 +4711,33 @@ class MPToken_test : public beast::unit_test::Suite // BTC is transferred from ed to bob, ed is not authorized env(pay(ed, gw, eth(10)), Path(~eth), Sendmax(btc(10)), Ter(tecNO_AUTH)); env.close(); - btc.set({.mutableFlags = tmfMPTClearRequireAuth}); + } - // MPTCanTransfer is not set + // MPTCanTransfer is not set. + { + auto const ed = Account{"ed"}; + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol, bob, ed); + MPTTester const btc( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob, ed}, + .pay = 1'000, + .flags = tfMPTCanTrade}); + MPTTester const eth( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob, ed}, + .pay = 1'000, + .flags = kMptDexFlags}); + + env(offer(bob, eth(1'000), btc(1'000)), Txflags(tfPassive)); + env.close(); + env(offer(bob, btc(1'000), eth(1'000)), Txflags(tfPassive)); + env.close(); // Fail regardless if source/destination is the issuer or // not since the offer is owned by a holder. - btc.set({.mutableFlags = tmfMPTClearCanTransfer}); env(pay(ed, carol, btc(10)), Path(~btc), Sendmax(eth(10)), Ter(tecPATH_PARTIAL)); env(pay(carol, ed, btc(10)), Path(~btc), Sendmax(eth(10)), Ter(tecPATH_PARTIAL)); env(pay(ed, carol, eth(10)), Path(~eth), Sendmax(btc(10)), Ter(tecPATH_PARTIAL)); @@ -4926,124 +4761,166 @@ class MPToken_test : public beast::unit_test::Suite env(pay(ed, gw, btc(10)), Path(~btc), Sendmax(eth(10))); env.close(); } - // Multiple steps: CAD/USD, USD/BTC, BTC/ETH + + // Multiple steps: CAD/USD, USD/BTC, BTC/ETH. + // takerGets can transfer if: + // - CanTransfer is set + // - The offer's owner is the issuer + // - BookStep is the last step, which means strand's destination is + // the issuer + // takerPays can transfer if + // - BookStep is the first step, which means strand's source is + // the issuer + // - The offer's owner is the issuer + // - Previous step is BookStep, which transfers per above + // - CanTransfer is set { - auto const ed = Account{"ed"}; - Env env{*this, features}; - env.fund(XRP(1'000), gw, alice, carol, bob, ed); - env.close(); - MPTTester btc( - {.env = env, - .issuer = gw, - .holders = {alice, carol, bob}, - .pay = 1'000, - .flags = tfMPTCanLock | kMptDexFlags, - .mutableFlags = tmfMPTCanMutateCanTransfer}); - MPTTester eth( - {.env = env, - .issuer = gw, - .holders = {alice, carol, bob}, - .pay = 1'000, - .flags = tfMPTCanLock | kMptDexFlags, - .mutableFlags = tmfMPTCanMutateCanTransfer}); - MPTTester usd( - {.env = env, - .issuer = gw, - .holders = {alice, carol, bob}, - .pay = 1'000, - .flags = kMptDexFlags | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTransfer}); - MPTTester cad( - {.env = env, - .issuer = gw, - .holders = {alice, carol, bob}, - .pay = 1'000, - .flags = kMptDexFlags | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTransfer}); - // takerGets can transfer if: - // - CanTransfer is set - // - The offer's owner is the issuer - // - BookStep is the last step, which means strand's destination is - // the issuer - // takerPays can transfer if - // - BookStep is the first step, which means strand's source is - // the issuer - // - The offer's owner is the issuer - // - Previous step is BookStep, which transfers per above - // - CanTransfer is set - env(offer(bob, cad(100), usd(100)), Txflags(tfPassive)); - env(offer(bob, usd(100), btc(100)), Txflags(tfPassive)); - env(offer(bob, btc(100), eth(100)), Txflags(tfPassive)); - env.close(); - BEAST_EXPECT(expectOffers(env, bob, 3)); - btc.set({.mutableFlags = tmfMPTSetCanTransfer}); - usd.set({.mutableFlags = tmfMPTClearCanTransfer}); - // TakerGets - // fail - CAD/USD is owned by bob - env(pay(alice, carol, eth(1)), - Path(~usd, ~btc, ~eth), - Sendmax(cad(1)), - Ter(tecPATH_PARTIAL)); - auto seq(env.seq(gw)); - env(offer(gw, usd(1), btc(1)), Txflags(tfPassive)); - env.close(); - // fail - CAD/USD is owned by bob - env(pay(alice, carol, eth(1)), - Path(~usd, ~btc, ~eth), - Sendmax(cad(1)), - Ter(tecPATH_PARTIAL)); - env.close(); - env(offerCancel(gw, seq)); - env(offer(gw, cad(1), usd(1)), Txflags(tfPassive)); - env.close(); - BEAST_EXPECT(expectOffers(env, bob, 3)); - // succeed - CAD/USD is owned by issuer - env(pay(alice, carol, eth(1)), Path(~usd, ~btc, ~eth), Sendmax(cad(1))); - env.close(); - // bob's CAD/USD is deleted - BEAST_EXPECT(expectOffers(env, bob, 2)); - env(offer(bob, cad(100), usd(100)), Txflags(tfPassive)); - BEAST_EXPECT(expectOffers(env, gw, 0)); - usd.set({.mutableFlags = tmfMPTSetCanTransfer}); - eth.set({.mutableFlags = tmfMPTClearCanTransfer}); - // fail - BTC/ETH is owned by bob, destination is carol - env(pay(alice, carol, eth(1)), - Path(~usd, ~btc, ~eth), - Sendmax(cad(1)), - Ter(tecPATH_PARTIAL)); - env.close(); - BEAST_EXPECT(expectOffers(env, bob, 3)); - // succeed - destination is an issuer - env(pay(alice, gw, eth(1)), Path(~usd, ~btc, ~eth), Sendmax(cad(1))); - env.close(); - BEAST_EXPECT(expectOffers(env, bob, 3)); - // TakerPays - eth.set({.mutableFlags = tmfMPTSetCanTransfer}); - cad.set({.mutableFlags = tmfMPTClearCanTransfer}); - // fail - CAD/USD is owned by bob, source is alice - env(pay(alice, carol, eth(1)), - Path(~usd, ~btc, ~eth), - Sendmax(cad(1)), - Ter(tecPATH_PARTIAL)); - // succeed - source is the issuer - env(pay(gw, carol, eth(1)), Path(~usd, ~btc, ~eth), Sendmax(cad(1))); - env.close(); - env(offer(gw, cad(1), usd(1)), Txflags(tfPassive)); - env.close(); - // succeed - CAD/USD is owned by issuer - env(pay(alice, carol, eth(1)), Path(~usd, ~btc, ~eth), Sendmax(cad(1))); - env.close(); - BEAST_EXPECT(expectOffers(env, gw, 0)); - BEAST_EXPECT(expectOffers(env, bob, 2)); - cad.set({.mutableFlags = tmfMPTSetCanTransfer}); - btc.set({.mutableFlags = tmfMPTClearCanTransfer}); - env(offer(bob, cad(1), usd(1)), Txflags(tfPassive)); - env(offer(gw, usd(1), btc(1)), Txflags(tfPassive)); - env.close(); - // succeed - USD/BTC is owned by issuer - env(pay(alice, carol, eth(1)), Path(~usd, ~btc, ~eth), Sendmax(cad(1))); - env.close(); - BEAST_EXPECT(expectOffers(env, gw, 0)); + // enum to indicate which MPT doesn't set CanTransfer flag. + enum class NoTransferMPT { BTC, ETH, USD, CAD }; + + // Lambda to test multi-step payment with one of the MPTs not setting CanTransfer flag. + auto const testMultiStepMPTCanTransfer = [&](NoTransferMPT const noTransferMPT, + auto const& test) { + auto const getFlags = [&](NoTransferMPT const mpt) { + return mpt == noTransferMPT ? tfMPTCanTrade : kMptDexFlags; + }; + + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol, bob); + env.close(); + MPTTester const btc( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = getFlags(NoTransferMPT::BTC)}); + MPTTester const eth( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = getFlags(NoTransferMPT::ETH)}); + MPTTester const usd( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = getFlags(NoTransferMPT::USD)}); + MPTTester const cad( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = getFlags(NoTransferMPT::CAD)}); + + env(offer(bob, cad(100), usd(100)), Txflags(tfPassive)); + env(offer(bob, usd(100), btc(100)), Txflags(tfPassive)); + env(offer(bob, btc(100), eth(100)), Txflags(tfPassive)); + env.close(); + + test(env, btc, eth, usd, cad); + }; + + // USD starts without MPTCanTransfer. + testMultiStepMPTCanTransfer( + NoTransferMPT::USD, + [&](Env& env, + MPTTester const& btc, + MPTTester const& eth, + MPTTester const& usd, + MPTTester const& cad) { + BEAST_EXPECT(expectOffers(env, bob, 3)); + + // fail - CAD/USD is owned by bob + env(pay(alice, carol, eth(1)), + Path(~usd, ~btc, ~eth), + Sendmax(cad(1)), + Ter(tecPATH_PARTIAL)); + + auto seq(env.seq(gw)); + env(offer(gw, usd(1), btc(1)), Txflags(tfPassive)); + env.close(); + // fail - CAD/USD is owned by bob + env(pay(alice, carol, eth(1)), + Path(~usd, ~btc, ~eth), + Sendmax(cad(1)), + Ter(tecPATH_PARTIAL)); + env.close(); + env(offerCancel(gw, seq)); + env(offer(gw, cad(1), usd(1)), Txflags(tfPassive)); + env.close(); + BEAST_EXPECT(expectOffers(env, bob, 3)); + // succeed - CAD/USD is owned by issuer + env(pay(alice, carol, eth(1)), Path(~usd, ~btc, ~eth), Sendmax(cad(1))); + env.close(); + // bob's CAD/USD is deleted. + BEAST_EXPECT(expectOffers(env, bob, 2)); + env(offer(bob, cad(100), usd(100)), Txflags(tfPassive)); + BEAST_EXPECT(expectOffers(env, gw, 0)); + }); + + // ETH starts without MPTCanTransfer. + testMultiStepMPTCanTransfer( + NoTransferMPT::ETH, + [&](Env& env, + MPTTester const& btc, + MPTTester const& eth, + MPTTester const& usd, + MPTTester const& cad) { + // fail - BTC/ETH is owned by bob, destination is carol + env(pay(alice, carol, eth(1)), + Path(~usd, ~btc, ~eth), + Sendmax(cad(1)), + Ter(tecPATH_PARTIAL)); + env.close(); + BEAST_EXPECT(expectOffers(env, bob, 3)); + + // succeed - destination is an issuer + env(pay(alice, gw, eth(1)), Path(~usd, ~btc, ~eth), Sendmax(cad(1))); + env.close(); + BEAST_EXPECT(expectOffers(env, bob, 3)); + }); + + // CAD starts without MPTCanTransfer. + testMultiStepMPTCanTransfer( + NoTransferMPT::CAD, + [&](Env& env, + MPTTester const& btc, + MPTTester const& eth, + MPTTester const& usd, + MPTTester const& cad) { + // fail - CAD/USD is owned by bob, source is alice + env(pay(alice, carol, eth(1)), + Path(~usd, ~btc, ~eth), + Sendmax(cad(1)), + Ter(tecPATH_PARTIAL)); + // succeed - source is the issuer + env(pay(gw, carol, eth(1)), Path(~usd, ~btc, ~eth), Sendmax(cad(1))); + env.close(); + env(offer(gw, cad(1), usd(1)), Txflags(tfPassive)); + env.close(); + // succeed - CAD/USD is owned by issuer + env(pay(alice, carol, eth(1)), Path(~usd, ~btc, ~eth), Sendmax(cad(1))); + env.close(); + BEAST_EXPECT(expectOffers(env, gw, 0)); + BEAST_EXPECT(expectOffers(env, bob, 2)); + }); + + // BTC starts without MPTCanTransfer. + testMultiStepMPTCanTransfer( + NoTransferMPT::BTC, + [&](Env& env, + MPTTester const& btc, + MPTTester const& eth, + MPTTester const& usd, + MPTTester const& cad) { + env(offer(gw, usd(1), btc(1)), Txflags(tfPassive)); + env.close(); + // succeed - USD/BTC is owned by issuer + env(pay(alice, carol, eth(1)), Path(~usd, ~btc, ~eth), Sendmax(cad(1))); + env.close(); + BEAST_EXPECT(expectOffers(env, gw, 0)); + }); } // MPTCanTrade is not set @@ -5057,48 +4934,38 @@ class MPToken_test : public beast::unit_test::Suite .holders = {alice, carol, bob}, .pay = 1'000, .flags = tfMPTCanTransfer, - .mutableFlags = tmfMPTCanMutateCanTrade}); + .mutableFlags = tmfMPTCanEnableCanTrade}); MPTTester const eth( {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 1'000, - .flags = tfMPTCanTransfer | tfMPTCanTrade, - .mutableFlags = tmfMPTCanMutateCanTrade}); + .flags = kMptDexFlags}); MPTTester const usd( {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 1'000, - .flags = tfMPTCanTransfer | tfMPTCanTrade, - .mutableFlags = tmfMPTCanMutateCanTrade}); + .flags = kMptDexFlags}); env(pay(alice, carol, eth(1)), Path(~eth), Sendmax(btc(1)), Ter(tecNO_PERMISSION)); env(pay(alice, carol, btc(1)), Path(~btc), Sendmax(eth(1)), Ter(tecNO_PERMISSION)); env.close(); + // Enable MPTCanTrade so BTC can be crossed through offers. btc.set({.mutableFlags = tmfMPTSetCanTrade}); env(offer(bob, XRP(1), btc(1))); env(offer(bob, btc(1), eth(1))); env(offer(bob, eth(1), usd(1))); env.close(); - btc.set({.mutableFlags = tmfMPTClearCanTrade}); + BEAST_EXPECT(expectOffers(env, bob, 3)); + env(pay(gw, carol, usd(1)), Path(~btc, ~eth, ~usd), Sendmax(XRP(1)), - Txflags(tfPartialPayment | tfNoRippleDirect), - Ter(tecNO_PERMISSION)); + Txflags(tfPartialPayment | tfNoRippleDirect)); env.close(); - BEAST_EXPECT(expectOffers(env, bob, 3)); - - env(pay(carol, bob, btc(10)), Sendmax(XRP(10)), Ter(tecNO_PERMISSION)); - env(pay(carol, bob, XRP(10)), Sendmax(btc(10)), Ter(tecNO_PERMISSION)); - env(pay(gw, bob, btc(10)), Sendmax(XRP(10)), Ter(tecNO_PERMISSION)); - env(pay(gw, bob, XRP(10)), Sendmax(btc(10)), Ter(tecNO_PERMISSION)); - env(pay(carol, gw, btc(10)), Sendmax(XRP(10)), Ter(tecNO_PERMISSION)); - env(pay(carol, gw, XRP(10)), Sendmax(btc(10)), Ter(tecNO_PERMISSION)); - env.close(); - BEAST_EXPECT(expectOffers(env, bob, 3)); + BEAST_EXPECT(expectOffers(env, bob, 0)); } // Holders are locked @@ -6891,7 +6758,7 @@ class MPToken_test : public beast::unit_test::Suite .issuer = gw, .holders = {alice, carol}, .flags = tfMPTCanTrade, - .mutableFlags = tmfMPTCanMutateCanTransfer}); + .mutableFlags = tmfMPTCanEnableCanTransfer}); // src is issuer uint256 checkId{keylet::check(gw, env.seq(gw)).key}; @@ -6933,13 +6800,8 @@ class MPToken_test : public beast::unit_test::Suite env.close(); env(pay(gw, alice, mpt(10))); env.close(); - // can't cash - mpt.set({.account = gw, .mutableFlags = tmfMPTClearCanTransfer}); - env.close(); - env(check::cash(carol, checkId, mpt(10)), Ter(tecNO_AUTH)); - env.close(); - // can cash - mpt.set({.account = gw, .mutableFlags = tmfMPTSetCanTransfer}); + + // can cash since MPTCanTransfer is enabled env(check::cash(carol, checkId, mpt(10))); env.close(); } @@ -7358,296 +7220,332 @@ class MPToken_test : public beast::unit_test::Suite Env env(*this); env.fund(XRP(1'000'000), gw, alice, carol); - auto usd = MPTTester( - {.env = env, - .issuer = gw, - .flags = tfMPTCanLock | kMptDexFlags, - .mutableFlags = tmfMPTCanMutateRequireAuth | tmfMPTCanMutateCanTransfer | - tmfMPTCanMutateCanClawback | tmfMPTCanMutateCanTrade}); - auto eur = MPTTester({.env = env, .issuer = gw, .holders = {alice}, .pay = 1'000'000}); - auto const increment = env.current()->fees().increment; auto const txfee = Fee(drops(increment)); auto const badMPT = MPT(gw, 1'000); - auto createDeleteAMM = [&](Account const& lp) { - AMM amm( - env, - lp, - usd(1'000), - eur(1'000), - CreateArg{.fee = static_cast(increment.value())}); - amm.withdrawAll(lp); - BEAST_EXPECT(!amm.ammExists()); + auto const makeMPT = [&](std::uint32_t const flags, + Holders holders = {}, + std::uint64_t const pay = 0, + std::optional const mutableFlags = + std::nullopt) { + return MPTTester( + {.env = env, + .issuer = gw, + .holders = holders, + .pay = pay ? std::optional{pay} : std::nullopt, + .flags = flags, + .mutableFlags = mutableFlags}); + }; + + auto const makeDexMPT = [&](Holders holders = {}, std::uint64_t const pay = 0) { + return makeMPT( + tfMPTCanLock | kMptDexFlags, + holders, + pay, + tmfMPTCanEnableRequireAuth | tmfMPTCanEnableCanTransfer | + tmfMPTCanEnableCanTrade); + }; + + auto const makeNoTransferMPT = [&](Holders holders = {}, std::uint64_t const pay = 0) { + return makeMPT( + tfMPTCanLock | tfMPTCanTrade, holders, pay, tmfMPTCanEnableCanTransfer); + }; + + auto const makeNoTradeMPT = [&](Holders holders = {}, std::uint64_t const pay = 0) { + return makeMPT( + tfMPTCanLock | tfMPTCanTransfer, holders, pay, tmfMPTCanEnableCanTrade); }; - // // AMMCreate - // - - auto createJv = AMM::createJv(alice, badMPT(1'000), eur(1'000), 0); - - auto createFail = [&](Account const& account, auto const& err) { - createJv[sfAccount] = account.human(); - env(createJv, txfee, Ter(err)); - env.close(); - }; - - // MPTokenIssuance doesn't exist - - createFail(alice, tecOBJECT_NOT_FOUND); - - // MPToken doesn't exist - - createJv[sfAmount] = STAmount{usd(1'000)}.getJson(); - createFail(alice, tecNO_AUTH); - - // alice authorizes MPToken, can create - usd.authorize({.account = alice}); - env(pay(gw, alice, usd(1'000'000)), txfee); - env.close(); - createDeleteAMM(alice); - - // MPTLock is set - - // alice and issuer can't create - usd.set({.flags = tfMPTLock}); - createFail(alice, tecLOCKED); - createFail(gw, tecLOCKED); - - // MPTRequireAuth is set - - // alice is not authorized - usd.set({.flags = tfMPTUnlock}); - usd.set({.mutableFlags = tmfMPTSetRequireAuth}); - createFail(alice, tecNO_AUTH); - // issuer can create - createDeleteAMM(gw); - - // alice is authorized, can create - usd.authorize({.account = gw, .holder = alice}); - createDeleteAMM(alice); - - // MPTCanTransfer is not set - - usd.set({.mutableFlags = tmfMPTClearRequireAuth}); - usd.set({.mutableFlags = tmfMPTClearCanTransfer}); - // alice can't create - createFail(alice, tecNO_AUTH); - // issuer can create - createDeleteAMM(gw); - usd.set({.mutableFlags = tmfMPTSetCanTransfer}); - // alice can create - createDeleteAMM(alice); - - // MPTCanTrade is not set - - usd.set({.mutableFlags = tmfMPTSetCanTransfer}); - usd.set({.mutableFlags = tmfMPTClearCanTrade}); - // alice and issuer can't create - createFail(alice, tecNO_PERMISSION); - createFail(gw, tecNO_PERMISSION); - usd.set({.mutableFlags = tmfMPTSetCanTrade}); - - // - // AMMDeposit - // - - AMM amm(env, gw, usd(1'000), eur(1'000)); - - // MPTokenIssuance doesn't exist - - amm.deposit( - {.account = alice, - .asset1In = badMPT(1), - .asset2In = eur(1), - .assets = std::make_pair(badMPT, eur), - .err = Ter(terNO_AMM)}); - - // MPToken doesn't exist - - amm.deposit( - {.account = carol, .asset1In = usd(1), .asset2In = eur(1), .err = Ter(tecNO_AUTH)}); - - // MPTLock is set - - usd.set({.flags = tfMPTLock}); - // alice and issuer can't deposit - for (auto const& account : {carol, gw}) { + auto usd = makeDexMPT(); + auto eur = makeDexMPT({alice}, 1'000'000); + + auto createDeleteAMM = [&](auto const& asset, Account const& lp) { + AMM amm( + env, + lp, + asset(1'000), + eur(1'000), + CreateArg{.fee = static_cast(increment.value())}); + amm.withdrawAll(lp); + BEAST_EXPECT(!amm.ammExists()); + }; + + auto createFail = [&](auto const& asset, Account const& account, auto const& err) { + auto const createJv = AMM::createJv(account, asset(1'000), eur(1'000), 0); + env(createJv, txfee, Ter(err)); + env.close(); + }; + + // MPTokenIssuance doesn't exist + createFail(badMPT, alice, tecOBJECT_NOT_FOUND); + + // MPToken doesn't exist + createFail(usd, alice, tecNO_AUTH); + + // alice authorizes MPToken, can create + usd.authorize({.account = alice}); + env(pay(gw, alice, usd(1'000'000)), txfee); + env.close(); + createDeleteAMM(usd, alice); + + // MPTLock is set + // alice and issuer can't create + usd.set({.flags = tfMPTLock}); + createFail(usd, alice, tecLOCKED); + createFail(usd, gw, tecLOCKED); + + // MPTRequireAuth is set + // alice is not authorized + usd.set({.flags = tfMPTUnlock}); + usd.set({.mutableFlags = tmfMPTSetRequireAuth}); + createFail(usd, alice, tecNO_AUTH); + // issuer can create + createDeleteAMM(usd, gw); + + // alice is authorized, can create + usd.authorize({.account = gw, .holder = alice}); + createDeleteAMM(usd, alice); + + // MPTCanTransfer is not set + { + auto usd2 = makeNoTransferMPT({alice}, 1'000'000); + + // alice can't create + createFail(usd2, alice, tecNO_AUTH); + // issuer can create + createDeleteAMM(usd2, gw); + usd2.set({.mutableFlags = tmfMPTSetCanTransfer}); + // alice can create + createDeleteAMM(usd2, alice); + } + + // MPTCanTrade is not set + { + auto usd3 = makeNoTradeMPT({alice}, 1'000'000); + + // alice and issuer can't create + createFail(usd3, alice, tecNO_PERMISSION); + createFail(usd3, gw, tecNO_PERMISSION); + usd3.set({.mutableFlags = tmfMPTSetCanTrade}); + // alice can create + createDeleteAMM(usd3, alice); + } + } + + // AMMDeposit + { + auto usd = makeDexMPT(); + auto eur = makeDexMPT({alice}, 1'000'000); + AMM amm(env, gw, usd(1'000), eur(1'000)); + + // MPTokenIssuance doesn't exist amm.deposit( - {.account = account, + {.account = alice, + .asset1In = badMPT(1), + .asset2In = eur(1), + .assets = std::make_pair(badMPT, eur), + .err = Ter(terNO_AMM)}); + + // MPToken doesn't exist + amm.deposit( + {.account = carol, .asset1In = usd(1), .asset2In = eur(1), - .err = Ter(tecLOCKED)}); + .err = Ter(tecNO_AUTH)}); + + // Fund carol for the AMMDeposit checks. + usd.authorize({.account = carol}); + env(pay(gw, carol, usd(1'000'000))); + eur.authorize({.account = carol}); + env(pay(gw, carol, eur(1'000'000))); + env.close(); + + // MPTLock is set + usd.set({.flags = tfMPTLock}); + + // alice and issuer can't deposit + for (auto const& account : {carol, gw}) + { + amm.deposit( + {.account = account, + .asset1In = usd(1), + .asset2In = eur(1), + .err = Ter(tecLOCKED)}); + amm.deposit( + {.account = account, + .asset1In = eur(1), + .assets = std::make_pair(eur, usd), + .err = Ter(tecLOCKED)}); + } + usd.set({.flags = tfMPTUnlock}); + + // MPTRequireAuth is set + // carol is not authorized by the issuer + usd.set({.mutableFlags = tmfMPTSetRequireAuth}); + env.close(); amm.deposit( - {.account = account, + {.account = carol, + .asset1In = usd(1), + .asset2In = eur(1), + .err = Ter(tecNO_AUTH)}); + amm.deposit( + {.account = carol, .asset1In = eur(1), .assets = std::make_pair(eur, usd), - .err = Ter(tecLOCKED)}); + .err = Ter(tecNO_AUTH)}); + // issuer can deposit + amm.deposit({.account = gw, .tokens = 1'000}); + // carol is authorized, can deposit + usd.authorize({.account = gw, .holder = carol}); + amm.deposit({.account = carol, .tokens = 1'000}); + // Can't authorize or unauthorize AMM pseudo-account + usd.authorize( + {.account = gw, + .holder = Account{"amm", amm.ammAccount()}, + .err = tecNO_PERMISSION}); + usd.authorize( + {.account = gw, + .holder = Account{"amm", amm.ammAccount()}, + .flags = tfMPTUnauthorize, + .err = tecNO_PERMISSION}); + + // MPTCanTransfer is not set + { + auto usd2 = makeNoTransferMPT({carol}, 1'000'000); + AMM amm2(env, gw, usd2(1'000), eur(1'000)); + + // carol can't deposit + amm2.deposit( + {.account = carol, + .asset1In = usd2(1), + .asset2In = eur(1), + .err = Ter(tecNO_AUTH)}); + amm2.deposit( + {.account = carol, + .asset1In = eur(1), + .assets = std::make_pair(eur, usd2), + .err = Ter(tecNO_AUTH)}); + // issuer can deposit + amm2.deposit({.account = gw, .tokens = 1'000}); + usd2.set({.mutableFlags = tmfMPTSetCanTransfer}); + // carol can deposit + amm2.deposit({.account = carol, .tokens = 1'000}); + } } - usd.set({.flags = tfMPTUnlock}); - // MPTRequireAuth is set - - // carol authorizes MPToken but is not authorized by the issuer - usd.authorize({.account = carol}); - env(pay(gw, carol, usd(1'000'000))); - // carol authorizes EUR - eur.authorize({.account = carol}); - env(pay(gw, carol, eur(1'000'000))); - usd.set({.mutableFlags = tmfMPTSetRequireAuth}); - env.close(); - amm.deposit( - {.account = carol, .asset1In = usd(1), .asset2In = eur(1), .err = Ter(tecNO_AUTH)}); - amm.deposit( - {.account = carol, - .asset1In = eur(1), - .assets = std::make_pair(eur, usd), - .err = Ter(tecNO_AUTH)}); - // issuer can deposit - amm.deposit({.account = gw, .tokens = 1'000}); - // carol is authorized, can deposit - usd.authorize({.account = gw, .holder = carol}); - amm.deposit({.account = carol, .tokens = 1'000}); - // Can't authorize or unauthorize AMM pseudo-account - usd.authorize( - {.account = gw, - .holder = Account{"amm", amm.ammAccount()}, - .err = tecNO_PERMISSION}); - usd.authorize( - {.account = gw, - .holder = Account{"amm", amm.ammAccount()}, - .flags = tfMPTUnauthorize, - .err = tecNO_PERMISSION}); - - // MPTCanTransfer is not set - - usd.set({.mutableFlags = tmfMPTClearRequireAuth}); - usd.set({.mutableFlags = tmfMPTClearCanTransfer}); - // carol can't deposit - amm.deposit( - {.account = carol, .asset1In = usd(1), .asset2In = eur(1), .err = Ter(tecNO_AUTH)}); - amm.deposit( - {.account = carol, - .asset1In = eur(1), - .assets = std::make_pair(eur, usd), - .err = Ter(tecNO_AUTH)}); - // issuer can deposit - amm.deposit({.account = gw, .tokens = 1'000}); - // carol can deposit - usd.set({.mutableFlags = tmfMPTSetCanTransfer}); - amm.deposit({.account = carol, .tokens = 1'000}); - - // MPTCanTrade is not set - - usd.set({.mutableFlags = tmfMPTSetCanTransfer}); - usd.set({.mutableFlags = tmfMPTClearCanTrade}); - amm.deposit({.account = gw, .tokens = 1'000, .err = Ter(tecNO_PERMISSION)}); - amm.deposit({.account = carol, .tokens = 1'000, .err = Ter(tecNO_PERMISSION)}); - usd.set({.mutableFlags = tmfMPTSetCanTrade}); - - // // AMMWithdraw - // - - // MPTokenIssuance doesn't exist - - amm.withdraw( - WithdrawArg{ - .account = carol, - .asset1Out = badMPT(1), - .asset2Out = eur(1), - .assets = std::make_pair(badMPT, eur), - .err = Ter(terNO_AMM)}); - - // MPToken doesn't exist - doesn't apply since MPToken is created - // on withdraw in this case - - // MPTLock is set - - usd.set({.flags = tfMPTLock}); - // carol and issuer can't withdraw - for (auto const& account : {carol, gw}) { + auto usd = makeDexMPT(); + auto eur = makeDexMPT({carol}, 1'000'000); + AMM amm(env, gw, usd(1'000), eur(1'000)); + + usd.authorize({.account = carol}); + env(pay(gw, carol, usd(1'000'000))); + env.close(); + amm.deposit({.account = carol, .tokens = 1'000}); + + // MPTokenIssuance doesn't exist amm.withdraw( - {.account = account, + WithdrawArg{ + .account = carol, + .asset1Out = badMPT(1), + .asset2Out = eur(1), + .assets = std::make_pair(badMPT, eur), + .err = Ter(terNO_AMM)}); + + // MPToken doesn't exist - doesn't apply since MPToken is created + // on withdraw in this case + + // MPTLock is set + usd.set({.flags = tfMPTLock}); + // carol and issuer can't withdraw + for (auto const& account : {carol, gw}) + { + amm.withdraw( + {.account = account, + .asset1Out = usd(1), + .asset2Out = eur(1), + .err = Ter(tecLOCKED)}); + amm.withdraw({.account = account, .tokens = 1'000, .err = Ter(tecLOCKED)}); + // can single withdraw another asset + amm.withdraw( + {.account = account, + .asset1Out = eur(1), + .assets = std::make_pair(eur, usd)}); + } + usd.set({.flags = tfMPTUnlock}); + + // MPTRequireAuth is set + usd.set({.mutableFlags = tmfMPTSetRequireAuth}); + usd.authorize({.account = gw, .holder = carol, .flags = tfMPTUnauthorize}); + // carol can't withdraw + amm.withdraw( + {.account = carol, .asset1Out = usd(1), .asset2Out = eur(1), - .err = Ter(tecLOCKED)}); - amm.withdraw({.account = account, .tokens = 1'000, .err = Ter(tecLOCKED)}); - // can single withdraw another asset + .err = Ter(tecNO_AUTH)}); + // can withdraw another asset amm.withdraw( - {.account = account, .asset1Out = eur(1), .assets = std::make_pair(eur, usd)}); + {.account = carol, .asset1Out = eur(1), .assets = std::make_pair(eur, usd)}); + // issuer can withdraw + amm.withdraw({.account = gw, .asset1Out = usd(1), .asset2Out = eur(1)}); + // carol is authorized, can withdraw + usd.authorize({.account = gw, .holder = carol}); + amm.withdraw({.account = carol, .asset1Out = usd(1), .asset2Out = eur(1)}); + + // MPTCanTransfer is not set, allow to withdraw + { + auto usd2 = makeNoTransferMPT({carol}, 1'000'000); + AMM amm2(env, gw, usd2(1'000), eur(1'000)); + + // carol cannot deposit usd2 without MPTCanTransfer, so give her + // LP tokens directly to test the withdraw path. + env.trust(STAmount{amm2.lptIssue(), 1'000}, carol); + env(pay(gw, carol, STAmount{amm2.lptIssue(), 100})); + env.close(); + + // carol can withdraw + amm2.withdraw({.account = carol, .asset1Out = usd2(1), .asset2Out = eur(1)}); + // can withdraw another asset + amm2.withdraw( + {.account = carol, + .asset1Out = eur(1), + .assets = std::make_pair(eur, usd2)}); + // issuer can withdraw + amm2.withdraw({.account = gw, .asset1Out = usd2(1), .asset2Out = eur(1)}); + // Holder can't transfer to another holder + env.fund(XRP(1'000), bob); + usd2.authorize({.account = bob}); + env(pay(carol, bob, usd2(1)), Ter(tecNO_AUTH)); + usd2.authorize({.account = bob, .flags = tfMPTUnauthorize}); + // Can redeem + env(pay(carol, gw, usd2(1))); + usd2.set({.mutableFlags = tmfMPTSetCanTransfer}); + // carol can withdraw + amm2.withdraw({.account = carol, .asset1Out = usd2(1), .asset2Out = eur(1)}); + } + + // MPToken created on withdraw + { + auto usd3 = makeDexMPT(); + auto eur3 = makeDexMPT({carol}, 1'000'000); + AMM amm3(env, gw, usd3(1'000), eur3(1'000)); + + BEAST_EXPECT(env.le(keylet::mptoken(usd3.issuanceID(), carol)) == nullptr); + // single-deposit EUR + amm3.deposit( + {.account = carol, + .asset1In = eur3(1'000), + .assets = std::make_pair(eur3, usd3)}); + BEAST_EXPECT(env.le(keylet::mptoken(usd3.issuanceID(), carol)) == nullptr); + // withdraw in USD to create MPToken + amm3.withdraw({.account = carol, .asset1Out = usd3(100)}); + BEAST_EXPECT(env.le(keylet::mptoken(usd3.issuanceID(), carol))); + } } - usd.set({.flags = tfMPTUnlock}); - - // MPTRequireAuth is set - - usd.set({.mutableFlags = tmfMPTSetRequireAuth}); - usd.authorize({.account = gw, .holder = carol, .flags = tfMPTUnauthorize}); - // carol can't withdraw - amm.withdraw( - {.account = carol, - .asset1Out = usd(1), - .asset2Out = eur(1), - .err = Ter(tecNO_AUTH)}); - // can withdraw another asset - amm.withdraw( - {.account = carol, .asset1Out = eur(1), .assets = std::make_pair(eur, usd)}); - // issuer can withdraw - amm.withdraw({.account = gw, .asset1Out = usd(1), .asset2Out = eur(1)}); - // carol is authorized, can withdraw - usd.authorize({.account = gw, .holder = carol}); - amm.withdraw({.account = carol, .asset1Out = usd(1), .asset2Out = eur(1)}); - - // MPTCanTransfer is not set, allow to withdraw - - usd.set({.mutableFlags = tmfMPTClearRequireAuth}); - usd.set({.mutableFlags = tmfMPTClearCanTransfer}); - // carol can withdraw - amm.withdraw({.account = carol, .asset1Out = usd(1), .asset2Out = eur(1)}); - // can withdraw another asset - amm.withdraw( - {.account = carol, .asset1Out = eur(1), .assets = std::make_pair(eur, usd)}); - // issuer can withdraw - amm.withdraw({.account = gw, .asset1Out = usd(1), .asset2Out = eur(1)}); - // Holder can't transfer to another holder - env.fund(XRP(1'000), bob); - usd.authorize({.account = bob}); - env(pay(carol, bob, usd(1)), Ter(tecNO_AUTH)); - usd.authorize({.account = bob, .flags = tfMPTUnauthorize}); - // Can redeem - env(pay(carol, gw, usd(1))); - // carol can withdraw - usd.set({.mutableFlags = tmfMPTSetCanTransfer}); - amm.withdraw({.account = carol, .asset1Out = usd(1), .asset2Out = eur(1)}); - - usd.set({.mutableFlags = tmfMPTSetCanTransfer}); - - // MPTCanTrade is not set, allow to withdraw - - usd.set({.mutableFlags = tmfMPTClearCanTrade}); - amm.withdraw({.account = gw, .tokens = 1'000}); - amm.withdraw({.account = carol, .tokens = 1'000}); - // Can't DEX - amm.deposit( - DepositArg{.account = carol, .asset1In = usd(1), .err = Ter(tecNO_PERMISSION)}); - usd.set({.mutableFlags = tmfMPTSetCanTrade}); - - // MPToken created on withdraw - - // redeem all carol's USD and unauthorize USD - amm.withdrawAll(carol); - env(pay(carol, gw, env.balance(carol, usd))); - usd.authorize({.account = carol, .flags = tfMPTUnauthorize}); - BEAST_EXPECT(env.le(keylet::mptoken(usd.issuanceID(), carol)) == nullptr); - // single-deposit EUR - amm.deposit( - {.account = carol, .asset1In = eur(1'000), .assets = std::make_pair(eur, usd)}); - // withdraw in USD to create MPToken - amm.withdraw({.account = carol, .asset1Out = usd(100)}); - BEAST_EXPECT(env.le(keylet::mptoken(usd.issuanceID(), carol))); } } @@ -7707,41 +7605,37 @@ class MPToken_test : public beast::unit_test::Suite Env env(*this); env.fund(XRP(1'000), gw, alice, carol); - MPTTester mpt( - {.env = env, - .issuer = gw, - .holders = {alice, carol}, - .pay = 100, - .flags = kMptDexFlags, - .mutableFlags = tmfMPTCanMutateCanTransfer | tmfMPTCanMutateCanTrade}); + auto const checkCanTradeCanTransfer = [&](std::uint32_t const flags, + TER const gwToGw, + TER const gwToAlice, + TER const aliceToAlice, + TER const aliceToCarol) { + MPTTester const mpt( + {.env = env, .issuer = gw, .holders = {alice, carol}, .pay = 100, .flags = flags}); + + BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, gw, gw) == gwToGw); + BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, gw, alice) == gwToAlice); + BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, alice, alice) == aliceToAlice); + BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, alice, carol) == aliceToCarol); + }; // Both flags are enabled - BEAST_EXPECT(isTesSuccess(canMPTTradeAndTransfer(*env.current(), mpt, gw, gw))); - BEAST_EXPECT(isTesSuccess(canMPTTradeAndTransfer(*env.current(), mpt, gw, alice))); - BEAST_EXPECT(isTesSuccess(canMPTTradeAndTransfer(*env.current(), mpt, alice, alice))); - BEAST_EXPECT(isTesSuccess(canMPTTradeAndTransfer(*env.current(), mpt, alice, carol))); + checkCanTradeCanTransfer(kMptDexFlags, tesSUCCESS, tesSUCCESS, tesSUCCESS, tesSUCCESS); // MPTCanTrade is disabled - mpt.set({.mutableFlags = tmfMPTClearCanTrade}); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, gw, gw) == tecNO_PERMISSION); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, gw, alice) == tecNO_PERMISSION); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, alice, alice) == tecNO_PERMISSION); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, alice, carol) == tecNO_PERMISSION); + checkCanTradeCanTransfer( + tfMPTCanTransfer, + tecNO_PERMISSION, + tecNO_PERMISSION, + tecNO_PERMISSION, + tecNO_PERMISSION); // MPTCanTransfer is disabled - mpt.set({.mutableFlags = tmfMPTSetCanTrade}); - mpt.set({.mutableFlags = tmfMPTClearCanTransfer}); - BEAST_EXPECT(isTesSuccess(canMPTTradeAndTransfer(*env.current(), mpt, gw, gw))); - BEAST_EXPECT(isTesSuccess(canMPTTradeAndTransfer(*env.current(), mpt, gw, alice))); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, alice, alice) == tecNO_AUTH); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, alice, carol) == tecNO_AUTH); + checkCanTradeCanTransfer(tfMPTCanTrade, tesSUCCESS, tesSUCCESS, tecNO_AUTH, tecNO_AUTH); // Both flags are disabled - mpt.set({.mutableFlags = tmfMPTClearCanTrade}); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, gw, gw) == tecNO_PERMISSION); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, gw, alice) == tecNO_PERMISSION); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, alice, alice) == tecNO_PERMISSION); - BEAST_EXPECT(canMPTTradeAndTransfer(*env.current(), mpt, alice, carol) == tecNO_PERMISSION); + checkCanTradeCanTransfer( + 0, tecNO_PERMISSION, tecNO_PERMISSION, tecNO_PERMISSION, tecNO_PERMISSION); } public: diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index 2c83ad91ec..065b6b0044 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -1599,7 +1599,7 @@ class Vault_test : public beast::unit_test::Suite {.flags = tfMPTCanTransfer | tfMPTCanLock | (args.enableClawback ? tfMPTCanClawback : kNone) | (args.requireAuth ? tfMPTRequireAuth : kNone), - .mutableFlags = tmfMPTCanMutateCanTransfer}); + .mutableFlags = tmfMPTCanEnableCanTransfer}); PrettyAsset const asset = mptt.issuanceID(); mptt.authorize({.account = owner}); mptt.authorize({.account = depositor}); @@ -2238,149 +2238,6 @@ class Vault_test : public beast::unit_test::Suite env.close(); } - testCase([this]( - Env& env, - Account const&, - Account const& owner, - Account const& depositor, - PrettyAsset const& asset, - Vault& vault, - MPTTester& mptt) { - testcase("MPT non-transferable: block deposit, allow withdraw"); - - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); - env(tx); - env.close(); - - // Issuer governance: clear CanTransfer. New exposure must be - // blocked, but recovery paths must remain open so existing - // depositors are not trapped. - mptt.set({.mutableFlags = tmfMPTClearCanTransfer}); - env.close(); - - // New deposit is blocked. - env(tx, Ter{tecNO_AUTH}); - env.close(); - - // Existing depositor can always withdraw, even though the asset - // is no longer freely transferable. - tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); - env(tx); - env.close(); - - // Delete vault with zero balance - env(vault.del({.owner = owner, .id = keylet.key})); - }); - - { - testcase("MPT non-transferable: pre-fixCleanup3_2_0 withdraw blocked"); - - // Regression: before fixCleanup3_2_0 a depositor was trapped if - // the issuer cleared lsfMPTCanTransfer. Verify that the legacy - // (broken) behavior is preserved when the amendment is disabled. - Env env{*this, testableAmendments() - fixCleanup3_2_0}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - Account const depositor{"depositor"}; - env.fund(XRP(10'000), issuer, owner, depositor); - env.close(); - Vault const vault{env}; - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create( - {.flags = tfMPTCanTransfer | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTransfer}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = owner}); - mptt.authorize({.account = depositor}); - env(pay(issuer, depositor, asset(1'000))); - env.close(); - - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - env(vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)})); - env.close(); - - mptt.set({.mutableFlags = tmfMPTClearCanTransfer}); - env.close(); - - // Pre-amendment: deposit blocked (matches new behavior). - env(vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}), - Ter{tecNO_AUTH}); - env.close(); - - // Pre-amendment: withdraw is also blocked - this is the bug - // that fixCleanup3_2_0 fixes. - env(vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}), - Ter{tecNO_AUTH}); - env.close(); - } - - { - testcase("MPT non-transferable: vault shares inherit restriction"); - - Env env{*this, testableAmendments()}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - Account const alice{"alice"}; - Account const bob{"bob"}; - env.fund(XRP(10'000), issuer, owner, alice, bob); - env.close(); - Vault const vault{env}; - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create( - {.flags = tfMPTCanTransfer | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTransfer}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = owner}); - mptt.authorize({.account = alice}); - mptt.authorize({.account = bob}); - env(pay(issuer, alice, asset(1'000))); - env(pay(issuer, bob, asset(1'000))); - env.close(); - - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = asset(500)})); - // Bob also deposits so he has a share MPToken to receive into. - env(vault.deposit({.depositor = bob, .id = keylet.key, .amount = asset(500)})); - env.close(); - - auto const shares = [&]() -> PrettyAsset { - auto const sle = env.le(keylet); - BEAST_EXPECT(sle != nullptr); - return MPTIssue(sle->at(sfShareMPTID)); - }(); - - // Sanity: while CanTransfer is set on the underlying, peer-to-peer - // share transfers are allowed. - env(pay(alice, bob, shares(1))); - env.close(); - - // Issuer governance: clear CanTransfer on the underlying. - mptt.set({.mutableFlags = tmfMPTClearCanTransfer}); - env.close(); - - // Vault shares inherit the restriction: third-party share-to-share - // payments are blocked. - env(pay(alice, bob, shares(1)), Ter{tecNO_AUTH}); - env.close(); - - // Recovery path: existing share holders can still redeem shares - // for the underlying asset via VaultWithdraw. - env(vault.withdraw({.depositor = alice, .id = keylet.key, .amount = shares(1)})); - env.close(); - } - { testcase("MPT locked: vault shares inherit underlying lock"); @@ -2458,56 +2315,6 @@ class Vault_test : public beast::unit_test::Suite BEAST_EXPECT(expectOffers(env, alice, 1)); } - { - testcase("MPT non-transferable: pre-fixCleanup3_2_0 share transfer succeeds"); - - // Regression: before fixCleanup3_2_0 a peer-to-peer share Payment - // succeeded even when the underlying asset's lsfMPTCanTransfer - // was cleared. Verify that the legacy (non-inheriting) behavior - // is preserved when the amendment is disabled. - Env env{*this, testableAmendments() - fixCleanup3_2_0}; - Account const issuer{"issuer"}; - Account const owner{"owner"}; - Account const alice{"alice"}; - Account const bob{"bob"}; - env.fund(XRP(10'000), issuer, owner, alice, bob); - env.close(); - Vault const vault{env}; - - MPTTester mptt{env, issuer, kMptInitNoFund}; - mptt.create( - {.flags = tfMPTCanTransfer | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTransfer}); - PrettyAsset const asset = mptt.issuanceID(); - mptt.authorize({.account = owner}); - mptt.authorize({.account = alice}); - mptt.authorize({.account = bob}); - env(pay(issuer, alice, asset(1'000))); - env(pay(issuer, bob, asset(1'000))); - env.close(); - - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - - env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = asset(500)})); - env(vault.deposit({.depositor = bob, .id = keylet.key, .amount = asset(500)})); - env.close(); - - auto const shares = [&]() -> PrettyAsset { - auto const sle = env.le(keylet); - BEAST_EXPECT(sle != nullptr); - return MPTIssue(sle->at(sfShareMPTID)); - }(); - - mptt.set({.mutableFlags = tmfMPTClearCanTransfer}); - env.close(); - - // Pre-amendment: share transfer leaks past underlying restriction. - env(pay(alice, bob, shares(1))); - env.close(); - } - { testcase("MPT CanTrade governance: share inherits underlying on DEX and AMM"); @@ -2522,8 +2329,8 @@ class Vault_test : public beast::unit_test::Suite MPTTester mptt{env, issuer, kMptInitNoFund}; mptt.create( - {.flags = tfMPTCanTransfer | tfMPTCanTrade | tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanTrade}); + {.flags = tfMPTCanTransfer | tfMPTCanLock, + .mutableFlags = tmfMPTCanEnableCanTrade}); PrettyAsset const asset = mptt.issuanceID(); mptt.authorize({.account = owner}); mptt.authorize({.account = alice}); @@ -2547,38 +2354,18 @@ class Vault_test : public beast::unit_test::Suite return MPTIssue(sle->at(sfShareMPTID)); }(); - // Sanity: while CanTrade is set on the underlying, both the asset - // and the vault share can be placed on the DEX. - env(offer(alice, XRP(1), asset(10))); - env(offer(alice, XRP(1), shares(1))); - env.close(); - - // Issuer governance: clear CanTrade on the underlying. - mptt.set({.mutableFlags = tmfMPTClearCanTrade}); - env.close(); - - // Control: clearing CanTrade on the underlying is observable on - // the DEX path for that asset. + // CanTrade is not set on the underlying, both the asset and + // the vault share are blocked on the DEX. env(offer(alice, XRP(1), asset(10)), Ter{tecNO_PERMISSION}); + env(offer(alice, XRP(1), shares(1)), Ter{tecNO_PERMISSION}); env.close(); - // Control: clearing CanTrade on the underlying is also observable - // on the AMM path for that asset. - AMM const ammUnderlyingFails( + // The inherited CanTrade restriction also blocks AMM creation. + AMM const ammUnderlyingFail( env, alice, XRP(1'000), asset(1'000), Ter{tecNO_PERMISSION}); - - // Post-fixCleanup3_2_0: vault shares inherit the underlying's - // CanTrade restriction on the DEX path (canTrade reads the - // share's sfReferenceHolding and dispatches to the underlying). - env(offer(bob, XRP(1), shares(1)), Ter{tecNO_PERMISSION}); - env.close(); - - // checkMPTAllowed mirrors the inheritance for AMM/Offer- - // crossing/Check paths, so a share AMM also cannot be created - // when the underlying CanTrade is cleared. AMM const ammShares(env, alice, XRP(1'000), shares(100), Ter{tecNO_PERMISSION}); - // Deposit still works (canAddHolding does not consult the field). + // Deposit still works before enabling CanTrade. env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = asset(100)})); env.close(); @@ -2587,9 +2374,19 @@ class Vault_test : public beast::unit_test::Suite env(pay(alice, bob, shares(1))); env.close(); - // Withdraw still works. + // Withdraw still works before enabling CanTrade. env(vault.withdraw({.depositor = alice, .id = keylet.key, .amount = asset(100)})); env.close(); + + // Enable CanTrade on the underlying. + mptt.set({.mutableFlags = tmfMPTSetCanTrade}); + env.close(); + + env(offer(alice, XRP(1), asset(10))); + env(offer(alice, XRP(1), shares(1))); + env.close(); + + AMM const ammUnderlying(env, alice, XRP(1'000), asset(1'000)); } { diff --git a/src/test/jtx/impl/mpt.cpp b/src/test/jtx/impl/mpt.cpp index 1e127e7c05..7da3305eec 100644 --- a/src/test/jtx/impl/mpt.cpp +++ b/src/test/jtx/impl/mpt.cpp @@ -28,6 +28,7 @@ #include #include +#include #include #include #include @@ -40,6 +41,21 @@ namespace xrpl::test::jtx { +struct MPTSetFlagMapping +{ + std::uint32_t setFlag; + std::uint32_t ledgerFlag; +}; + +static constexpr std::array mptSetFlagMappings = {{ + {.setFlag = tmfMPTSetCanLock, .ledgerFlag = lsfMPTCanLock}, + {.setFlag = tmfMPTSetRequireAuth, .ledgerFlag = lsfMPTRequireAuth}, + {.setFlag = tmfMPTSetCanEscrow, .ledgerFlag = lsfMPTCanEscrow}, + {.setFlag = tmfMPTSetCanClawback, .ledgerFlag = lsfMPTCanClawback}, + {.setFlag = tmfMPTSetCanTrade, .ledgerFlag = lsfMPTCanTrade}, + {.setFlag = tmfMPTSetCanTransfer, .ledgerFlag = lsfMPTCanTransfer}, +}}; + void MptFlags::operator()(Env& env) const { @@ -424,58 +440,12 @@ MPTTester::set(MPTSet const& arg) if (arg.mutableFlags) { - if (*arg.mutableFlags & tmfMPTSetCanLock) + for (auto const& [setFlag, ledgerFlag] : mptSetFlagMappings) { - flags |= lsfMPTCanLock; - } - else if (*arg.mutableFlags & tmfMPTClearCanLock) - { - flags &= ~lsfMPTCanLock; - } - - if (*arg.mutableFlags & tmfMPTSetRequireAuth) - { - flags |= lsfMPTRequireAuth; - } - else if (*arg.mutableFlags & tmfMPTClearRequireAuth) - { - flags &= ~lsfMPTRequireAuth; - } - - if (*arg.mutableFlags & tmfMPTSetCanEscrow) - { - flags |= lsfMPTCanEscrow; - } - else if (*arg.mutableFlags & tmfMPTClearCanEscrow) - { - flags &= ~lsfMPTCanEscrow; - } - - if (*arg.mutableFlags & tmfMPTSetCanClawback) - { - flags |= lsfMPTCanClawback; - } - else if (*arg.mutableFlags & tmfMPTClearCanClawback) - { - flags &= ~lsfMPTCanClawback; - } - - if (*arg.mutableFlags & tmfMPTSetCanTrade) - { - flags |= lsfMPTCanTrade; - } - else if (*arg.mutableFlags & tmfMPTClearCanTrade) - { - flags &= ~lsfMPTCanTrade; - } - - if (*arg.mutableFlags & tmfMPTSetCanTransfer) - { - flags |= lsfMPTCanTransfer; - } - else if (*arg.mutableFlags & tmfMPTClearCanTransfer) - { - flags &= ~lsfMPTCanTransfer; + if ((*arg.mutableFlags & setFlag) != 0u) + { + flags |= ledgerFlag; + } } } } From 93eab33dc23e0a026c55234ae7b5190bb195d93e Mon Sep 17 00:00:00 2001 From: Zhiyuan Wang <96991820+Kassaking7@users.noreply.github.com> Date: Mon, 22 Jun 2026 13:45:42 -0400 Subject: [PATCH 75/78] fix: Improve ValidAMM invariant (#7295) --- include/xrpl/tx/invariants/AMMInvariant.h | 11 ++- src/libxrpl/tx/invariants/AMMInvariant.cpp | 92 +++++++++++++++++++--- src/test/app/Invariants_test.cpp | 84 ++++++++++++++++++++ 3 files changed, 175 insertions(+), 12 deletions(-) diff --git a/include/xrpl/tx/invariants/AMMInvariant.h b/include/xrpl/tx/invariants/AMMInvariant.h index ee2fb66a1c..4b56370774 100644 --- a/include/xrpl/tx/invariants/AMMInvariant.h +++ b/include/xrpl/tx/invariants/AMMInvariant.h @@ -15,7 +15,9 @@ class ValidAMM std::optional ammAccount_; std::optional lptAMMBalanceAfter_; std::optional lptAMMBalanceBefore_; + std::optional lptAMMBalanceBeforeDeletion_; bool ammPoolChanged_{false}; + bool ammDeleted_{false}; public: enum class ZeroAllowed : bool { No = false, Yes = true }; @@ -35,12 +37,17 @@ private: [[nodiscard]] bool finalizeCreate(STTx const&, ReadView const&, bool enforce, beast::Journal const&) const; [[nodiscard]] bool - finalizeDelete(bool enforce, TER res, beast::Journal const&) const; + finalizeDelete(bool enforce, bool enforceAMMDelete, TER res, beast::Journal const&) const; [[nodiscard]] bool finalizeDeposit(STTx const&, ReadView const&, bool enforce, beast::Journal const&) const; // Includes clawback [[nodiscard]] bool - finalizeWithdraw(STTx const&, ReadView const&, bool enforce, beast::Journal const&) const; + finalizeWithdraw( + STTx const&, + ReadView const&, + bool enforce, + bool enforceAMMDelete, + beast::Journal const&) const; [[nodiscard]] bool finalizeDEX(bool enforce, beast::Journal const&) const; [[nodiscard]] bool diff --git a/src/libxrpl/tx/invariants/AMMInvariant.cpp b/src/libxrpl/tx/invariants/AMMInvariant.cpp index ecd7bedf89..356c26d6b0 100644 --- a/src/libxrpl/tx/invariants/AMMInvariant.cpp +++ b/src/libxrpl/tx/invariants/AMMInvariant.cpp @@ -27,7 +27,14 @@ void ValidAMM::visitEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) { if (isDelete) + { + if (before && before->getType() == ltAMM) + { + ammDeleted_ = true; + lptAMMBalanceBeforeDeletion_ = before->getFieldAmount(sfLPTokenBalance); + } return; + } if (after) { @@ -166,18 +173,60 @@ ValidAMM::finalizeCreate( } bool -ValidAMM::finalizeDelete(bool enforce, TER res, beast::Journal const& j) const +ValidAMM::finalizeDelete(bool enforce, bool enforceAMMDelete, TER res, beast::Journal const& j) + const { if (ammAccount_) { // LCOV_EXCL_START - std::string const msg = (isTesSuccess(res)) ? "AMM object is not deleted on tesSUCCESS" - : "AMM object is changed on tecINCOMPLETE"; + std::string const msg = (isTesSuccess(res)) ? "AMM object remained on tesSUCCESS" + : "AMM object changed on tecINCOMPLETE"; JLOG(j.error()) << "Invariant failed: AMMDelete failed, " << msg; if (enforce) return false; // LCOV_EXCL_STOP } + if (enforceAMMDelete) + { + if (isTesSuccess(res)) + { + if (!ammDeleted_) + { + // LCOV_EXCL_START + JLOG(j.error()) + << "Invariant failed: AMMDelete failed, AMM object remained on tesSUCCESS"; + return false; + // LCOV_EXCL_STOP + } + if (!lptAMMBalanceBeforeDeletion_) + { + // LCOV_EXCL_START + JLOG(j.error()) + << "Invariant failed: AMMDelete failed, AMM object deleted without LP balance"; + return false; + // LCOV_EXCL_STOP + } + if (*lptAMMBalanceBeforeDeletion_ != beast::kZero) + { + // LCOV_EXCL_START + JLOG(j.error()) + << "Invariant failed: AMMDelete failed, AMM object deleted with non-zero LP " + "balance: " + << *lptAMMBalanceBeforeDeletion_; + return false; + // LCOV_EXCL_STOP + } + } + else if (ammDeleted_) + { + // AMM should only be fully deleted when AMMDelete returns tesSUCCESS. + // LCOV_EXCL_START + JLOG(j.error()) << "Invariant failed: AMMDelete failed, AMM object deleted when result " + "is not tesSUCCESS"; + return false; + // LCOV_EXCL_STOP + } + } return true; } @@ -271,16 +320,20 @@ ValidAMM::finalizeWithdraw( xrpl::STTx const& tx, xrpl::ReadView const& view, bool enforce, + bool enforceAMMDelete, beast::Journal const& j) const { - if (!ammAccount_) + if (enforceAMMDelete && ammDeleted_) { - // Last Withdraw or Clawback deleted AMM + // Last Withdraw or Clawback can delete the AMM. We don't have to check + // the LPToken balance because a final AMMWithdraw or AMMClawback can + // redeem the remaining LP tokens and delete the AMM entry in the same + // transaction. + return true; } - else if (!generalInvariant(tx, view, ZeroAllowed::Yes, j)) + if (ammAccount_ && !generalInvariant(tx, view, ZeroAllowed::Yes, j) && enforce) { - if (enforce) - return false; + return false; } return true; @@ -300,6 +353,25 @@ ValidAMM::finalize( return true; bool const enforce = view.rules().enabled(fixAMMv1_3); + bool const enforceAMMDelete = view.rules().enabled(fixCleanup3_3_0); + + // AMM can only be deleted by AMMWithdraw, AMMClawback, and AMMDelete + if (enforceAMMDelete && ammDeleted_) + { + switch (tx.getTxnType()) + { + case ttAMM_WITHDRAW: + case ttAMM_CLAWBACK: + case ttAMM_DELETE: + break; + default: + // LCOV_EXCL_START + JLOG(j.error()) << "Invariant failed: AMM failed, unexpected AMM deletion by " + << tx.getTxnType(); + return false; + // LCOV_EXCL_STOP + } + } switch (tx.getTxnType()) { @@ -309,13 +381,13 @@ ValidAMM::finalize( return finalizeDeposit(tx, view, enforce, j); case ttAMM_CLAWBACK: case ttAMM_WITHDRAW: - return finalizeWithdraw(tx, view, enforce, j); + return finalizeWithdraw(tx, view, enforce, enforceAMMDelete, j); case ttAMM_BID: return finalizeBid(enforce, j); case ttAMM_VOTE: return finalizeVote(enforce, j); case ttAMM_DELETE: - return finalizeDelete(enforce, result, j); + return finalizeDelete(enforce, enforceAMMDelete, result, j); case ttCHECK_CASH: case ttOFFER_CREATE: case ttPAYMENT: diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index 6d53d25661..e0c29ea72a 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -51,6 +51,7 @@ #include #include #include +#include #include #include @@ -1277,6 +1278,87 @@ class Invariants_test : public beast::unit_test::Suite }); } + void + testAMMDeleteInvariants(FeatureBitset features) + { + using namespace test::jtx; + + bool const enforceAMMDelete = features[fixCleanup3_3_0]; + testcase << "AMM delete invariants" + std::string(enforceAMMDelete ? " fix" : ""); + + Env env(*this, features); + Account const issuer{"issuer"}; + Issue const lptIssue{Currency(0x4c50540000000000), issuer.id()}; + STAmount const zeroLP{lptIssue, 0}; + STAmount const nonZeroLP{lptIssue, 1}; + + auto const makeAMM = [](STAmount const& lptBalance) { + auto sleAMM = std::make_shared(keylet::amm(uint256(1))); + sleAMM->setFieldAmount(sfLPTokenBalance, lptBalance); + return sleAMM; + }; + + auto const checkInvariant = [&](TxType txType, + TER result, + std::optional const& deletedLPBalance, + bool expected, + std::string const& expectedLog) { + test::StreamSink sink{beast::Severity::Warning}; + beast::Journal const jlog{sink}; + ValidAMM invariant; + + if (deletedLPBalance) + invariant.visitEntry(true, makeAMM(*deletedLPBalance), nullptr); + + bool const actual = invariant.finalize( + STTx{txType, [](STObject&) {}}, result, XRPAmount{}, *env.current(), jlog); + + BEAST_EXPECTS(actual == expected, "unexpected AMM delete invariant result"); + auto const messages = sink.messages().str(); + auto const expectedLogWhenEnforced = enforceAMMDelete ? expectedLog : ""; + if (!expectedLogWhenEnforced.empty()) + { + BEAST_EXPECTS(messages.contains(expectedLogWhenEnforced), expectedLogWhenEnforced); + } + else + { + BEAST_EXPECTS(messages.empty(), messages); + } + }; + + checkInvariant( + ttPAYMENT, + tesSUCCESS, + nonZeroLP, + !enforceAMMDelete, + "Invariant failed: AMM failed, unexpected AMM deletion by"); + checkInvariant( + ttAMM_DELETE, + tesSUCCESS, + std::nullopt, + !enforceAMMDelete, + "Invariant failed: AMMDelete failed, AMM object remained on tesSUCCESS"); + checkInvariant( + ttAMM_DELETE, + tesSUCCESS, + nonZeroLP, + !enforceAMMDelete, + "Invariant failed: AMMDelete failed, AMM object deleted with non-zero LP balance"); + checkInvariant( + ttAMM_DELETE, + tecINCOMPLETE, + zeroLP, + !enforceAMMDelete, + "Invariant failed: AMMDelete failed, AMM object deleted when result is not tesSUCCESS"); + + checkInvariant(ttAMM_WITHDRAW, tesSUCCESS, nonZeroLP, true, ""); + checkInvariant(ttAMM_CLAWBACK, tesSUCCESS, nonZeroLP, true, ""); + + checkInvariant(ttAMM_DELETE, tesSUCCESS, zeroLP, true, ""); + checkInvariant(ttAMM_WITHDRAW, tesSUCCESS, zeroLP, true, ""); + checkInvariant(ttAMM_CLAWBACK, tesSUCCESS, zeroLP, true, ""); + } + static SLE::pointer createPermissionedDomain( ApplyContext& ac, @@ -4900,6 +4982,8 @@ public: testNoZeroEscrow(); testValidNewAccountRoot(); testNFTokenPageInvariants(); + testAMMDeleteInvariants(defaultAmendments()); + testAMMDeleteInvariants(defaultAmendments() - fixCleanup3_3_0); testPermissionedDomainInvariants(defaultAmendments() | fixCleanup3_1_3); testPermissionedDomainInvariants(defaultAmendments() - fixCleanup3_1_3); testPermissionedDEX(defaultAmendments() | fixCleanup3_1_3); From 19a9ed776761ee738da4ee2ffde88aa349a9ae31 Mon Sep 17 00:00:00 2001 From: Zhiyuan Wang <96991820+Kassaking7@users.noreply.github.com> Date: Mon, 22 Jun 2026 14:42:57 -0400 Subject: [PATCH 76/78] fix: Move AMMInvariant weakInvariantCheck logic into the transaction (#7032) --- include/xrpl/ledger/helpers/AMMHelpers.h | 26 +++++++++++++ src/libxrpl/ledger/helpers/AMMHelpers.cpp | 37 +++++++++++++++++++ src/libxrpl/tx/invariants/AMMInvariant.cpp | 9 +---- .../tx/transactors/dex/AMMClawback.cpp | 10 +++++ src/libxrpl/tx/transactors/dex/AMMDeposit.cpp | 13 +++++++ .../tx/transactors/dex/AMMWithdraw.cpp | 10 +++++ src/test/app/AMMClawback_test.cpp | 18 ++++++++- src/test/app/AMM_test.cpp | 16 ++++++-- 8 files changed, 127 insertions(+), 12 deletions(-) diff --git a/include/xrpl/ledger/helpers/AMMHelpers.h b/include/xrpl/ledger/helpers/AMMHelpers.h index d21e50e7cb..de8bb9d3f7 100644 --- a/include/xrpl/ledger/helpers/AMMHelpers.h +++ b/include/xrpl/ledger/helpers/AMMHelpers.h @@ -37,6 +37,8 @@ reduceOffer(auto const& amount) enum class IsDeposit : bool { No = false, Yes = true }; +inline Number const kAMMInvariantRelativeTolerance{1, -11}; + /** Calculate LP Tokens given AMM pool reserves. * @param asset1 AMM one side of the pool reserve * @param asset2 AMM another side of the pool reserve @@ -738,6 +740,30 @@ ammPoolHolds( AuthHandling authHandling, beast::Journal const j); +/** Check AMM pool product invariant after an AMM operation that changes LP tokens + * (deposit/withdraw/clawback) from an already calculated pool product mean. + * Returns tecPRECISION_LOSS if poolProductMean < newLPTokenBalance beyond the + * invariant tolerance, + * tesSUCCESS otherwise. Skips check when newLPTokenBalance is zero (last withdrawal). + */ +TER +checkAMMPrecisionLoss(Number const& poolProductMean, STAmount const& newLPTokenBalance); + +/** Check AMM pool product invariant after an AMM operation that changes LP tokens + * (deposit/withdraw/clawback). + * Returns tecPRECISION_LOSS if sqrt(asset1 * asset2) < newLPTokenBalance beyond + * the invariant tolerance, + * tesSUCCESS otherwise. Skips check when newLPTokenBalance is zero (last withdrawal). + */ +TER +checkAMMPrecisionLoss( + ReadView const& view, + AccountID const& ammAccountID, + Asset const& asset1, + Asset const& asset2, + STAmount const& newLPTokenBalance, + beast::Journal const j); + /** Get AMM pool and LP token balances. If both optIssue are * provided then they are used as the AMM token pair issues. * Otherwise the missing issues are fetched from ammSle. diff --git a/src/libxrpl/ledger/helpers/AMMHelpers.cpp b/src/libxrpl/ledger/helpers/AMMHelpers.cpp index a59b8e4436..cacbfc9d58 100644 --- a/src/libxrpl/ledger/helpers/AMMHelpers.cpp +++ b/src/libxrpl/ledger/helpers/AMMHelpers.cpp @@ -433,6 +433,43 @@ ammPoolHolds( return std::make_pair(assetInBalance, assetOutBalance); } +TER +checkAMMPrecisionLoss(Number const& poolProductMean, STAmount const& newLPTokenBalance) +{ + if (newLPTokenBalance <= beast::kZero) + return tesSUCCESS; + if (poolProductMean >= newLPTokenBalance) + return tesSUCCESS; + // Strong check failed. Allow the same relative tolerance as the invariant + // checker's weak check. Only return tecPRECISION_LOSS when both fail. + if (withinRelativeDistance( + poolProductMean, Number{newLPTokenBalance}, kAMMInvariantRelativeTolerance)) + return tesSUCCESS; + return tecPRECISION_LOSS; +} + +TER +checkAMMPrecisionLoss( + ReadView const& view, + AccountID const& ammAccountID, + Asset const& asset1, + Asset const& asset2, + STAmount const& newLPTokenBalance, + beast::Journal const j) +{ + if (newLPTokenBalance <= beast::kZero) + return tesSUCCESS; + auto const [amount, amount2] = ammPoolHolds( + view, + ammAccountID, + asset1, + asset2, + FreezeHandling::IgnoreFreeze, + AuthHandling::IgnoreAuth, + j); + return checkAMMPrecisionLoss(root2(amount * amount2), newLPTokenBalance); +} + std::expected, TER> ammHolds( ReadView const& view, diff --git a/src/libxrpl/tx/invariants/AMMInvariant.cpp b/src/libxrpl/tx/invariants/AMMInvariant.cpp index 356c26d6b0..cca0ce149c 100644 --- a/src/libxrpl/tx/invariants/AMMInvariant.cpp +++ b/src/libxrpl/tx/invariants/AMMInvariant.cpp @@ -270,13 +270,8 @@ ValidAMM::generalInvariant( auto const poolProductMean = root2(amount * amount2); bool const nonNegativeBalances = validBalances(amount, amount2, *lptAMMBalanceAfter_, zeroAllowed); - bool const strongInvariantCheck = poolProductMean >= *lptAMMBalanceAfter_; - // Allow for a small relative error if strongInvariantCheck fails - auto weakInvariantCheck = [&]() { - return *lptAMMBalanceAfter_ != beast::kZero && - withinRelativeDistance(poolProductMean, Number{*lptAMMBalanceAfter_}, Number{1, -11}); - }; - if (!nonNegativeBalances || (!strongInvariantCheck && !weakInvariantCheck())) + auto const precisionLoss = checkAMMPrecisionLoss(poolProductMean, *lptAMMBalanceAfter_); + if (!nonNegativeBalances || !isTesSuccess(precisionLoss)) { JLOG(j.error()) << "Invariant failed: AMM " << tx.getTxnType() << " " << tx.getHash(HashPrefix::TransactionId) << " " << ammPoolChanged_ << " " diff --git a/src/libxrpl/tx/transactors/dex/AMMClawback.cpp b/src/libxrpl/tx/transactors/dex/AMMClawback.cpp index b94e97e931..0cc2be381f 100644 --- a/src/libxrpl/tx/transactors/dex/AMMClawback.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMClawback.cpp @@ -258,6 +258,16 @@ AMMClawback::applyGuts(Sandbox& sb) if (!isTesSuccess(result)) return result; // LCOV_EXCL_LINE + if (sb.rules().enabled(fixCleanup3_3_0) && sb.rules().enabled(fixAMMv1_3)) + { + if (auto const ter = + checkAMMPrecisionLoss(sb, ammAccount, asset, asset2, newLPTokenBalance, j_); + !isTesSuccess(ter)) + { + return ter; + } + } + auto const res = AMMWithdraw::deleteAMMAccountIfEmpty(sb, ammSle, newLPTokenBalance, asset, asset2, j_); if (!res.second) diff --git a/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp b/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp index 91858e3cd7..653e8c6961 100644 --- a/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp @@ -470,6 +470,19 @@ AMMDeposit::applyGuts(Sandbox& sb) XRPL_ASSERT( newLPTokenBalance > beast::kZero, "xrpl::AMMDeposit::applyGuts : valid new LP token balance"); + // Defensive check: deposit formulas with fixAMMv1_3 round LP tokens + // down and asset amounts up, so sqrt(pool1*pool2) >= newLPTokenBalance + // is guaranteed to hold. A precision loss failure is not expected. + if (sb.rules().enabled(fixCleanup3_3_0) && sb.rules().enabled(fixAMMv1_3)) + { + if (auto const ter = checkAMMPrecisionLoss( + sb, ammAccountID, ctx_.tx[sfAsset], ctx_.tx[sfAsset2], newLPTokenBalance, j_); + !isTesSuccess(ter)) + { + UNREACHABLE("xrpl::AMMDeposit::applyGuts : AMM precision loss"); + return {ter, false}; // LCOV_EXCL_LINE + } + } ammSle->setFieldAmount(sfLPTokenBalance, newLPTokenBalance); // LP depositing into AMM empty state gets the auction slot // and the voting diff --git a/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp b/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp index d3a6c9c74c..17ce1a6b83 100644 --- a/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp @@ -406,6 +406,16 @@ AMMWithdraw::applyGuts(Sandbox& sb) if (!isTesSuccess(result)) return {result, false}; + if (sb.rules().enabled(fixCleanup3_3_0) && sb.rules().enabled(fixAMMv1_3)) + { + if (auto const ter = checkAMMPrecisionLoss( + sb, ammAccountID, ctx_.tx[sfAsset], ctx_.tx[sfAsset2], newLPTokenBalance, j_); + !isTesSuccess(ter)) + { + return {ter, false}; + } + } + auto const res = deleteAMMAccountIfEmpty( sb, ammSle, newLPTokenBalance, ctx_.tx[sfAsset], ctx_.tx[sfAsset2], j_); // LCOV_EXCL_START diff --git a/src/test/app/AMMClawback_test.cpp b/src/test/app/AMMClawback_test.cpp index 9683e8ac17..ba416d8192 100644 --- a/src/test/app/AMMClawback_test.cpp +++ b/src/test/app/AMMClawback_test.cpp @@ -2486,8 +2486,17 @@ class AMMClawback_test : public beast::unit_test::Suite else if (!features[fixAMMClawbackRounding]) { // sqrt(amount * amount2) >= LPTokens and exceeds the allowed - // tolerance - env(amm::ammClawback(gw, alice, usd, eur, usd(1)), Ter(tecINVARIANT_FAILED)); + // tolerance. + // With fixCleanup3_3_0 this is caught in the transaction layer; + // without it the invariant checker fires instead. + if (features[fixCleanup3_3_0]) + { + env(amm::ammClawback(gw, alice, usd, eur, usd(1)), Ter(tecPRECISION_LOSS)); + } + else + { + env(amm::ammClawback(gw, alice, usd, eur, usd(1)), Ter(tecINVARIANT_FAILED)); + } BEAST_EXPECT(amm.ammExists()); } else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) @@ -2514,6 +2523,11 @@ class AMMClawback_test : public beast::unit_test::Suite testFeatureDisabled(all - featureAMMClawback); for (auto const& features : {all - fixAMMv1_3 - fixAMMClawbackRounding - featureMPTokensV2, + // fixAMMv1_3 on, fixAMMClawbackRounding off, fixCleanup3_3_0 off: + // precision loss caught by invariant checker -> tecINVARIANT_FAILED + all - fixAMMClawbackRounding - fixCleanup3_3_0 - featureMPTokensV2, + // fixAMMv1_3 on, fixAMMClawbackRounding off, fixCleanup3_3_0 on: + // precision loss caught in transaction layer -> tecPRECISION_LOSS all - fixAMMClawbackRounding - featureMPTokensV2, all - featureMPTokensV2, all}) diff --git a/src/test/app/AMM_test.cpp b/src/test/app/AMM_test.cpp index 1b54c2aab9..b01d58ddff 100644 --- a/src/test/app/AMM_test.cpp +++ b/src/test/app/AMM_test.cpp @@ -1842,8 +1842,18 @@ private: // are rounded to all LP tokens. testAMM( [&](AMM& ammAlice, Env& env) { - auto const err = - env.enabled(fixAMMv1_3) ? Ter(tecINVARIANT_FAILED) : Ter(tecAMM_BALANCE); + // Without fixAMMv1_3: sub-method returns tecAMM_BALANCE early. + // With fixAMMv1_3 but without fixCleanup3_3_0: sub-method succeeds + // but invariant check catches the precision violation. + // With fixCleanup3_3_0: caught in the transaction layer before + // the invariant checker runs. + auto const err = [&] { + if (!env.enabled(fixAMMv1_3)) + return Ter(tecAMM_BALANCE); + if (env.enabled(fixCleanup3_3_0)) + return Ter(tecPRECISION_LOSS); + return Ter(tecINVARIANT_FAILED); + }(); ammAlice.withdraw( alice_, STAmount{USD, UINT64_C(9'999'999999999999), -12}, @@ -1851,7 +1861,7 @@ private: std::nullopt, err); }, - {.features = {all, all - fixAMMv1_3}, .noLog = true}); + {.features = {all, all - fixAMMv1_3, all - fixCleanup3_3_0}, .noLog = true}); // Tiny withdraw testAMM([&](AMM& ammAlice, Env&) { From dd7401fde21c6ddd5d5e1ef4761a3de6630b40fa Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Mon, 22 Jun 2026 14:44:42 -0400 Subject: [PATCH 77/78] refactor: Clean up tec object deletion logic (#6588) Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- include/xrpl/tx/Transactor.h | 7 + src/libxrpl/tx/Transactor.cpp | 238 ++++++++++++++-------------- src/test/app/NFToken_test.cpp | 2 + src/test/app/Offer_test.cpp | 25 +++ src/test/app/SetRegularKey_test.cpp | 22 +++ 5 files changed, 172 insertions(+), 122 deletions(-) diff --git a/include/xrpl/tx/Transactor.h b/include/xrpl/tx/Transactor.h index a27d638107..470571eb48 100644 --- a/include/xrpl/tx/Transactor.h +++ b/include/xrpl/tx/Transactor.h @@ -7,6 +7,7 @@ #include #include +#include #include namespace xrpl { @@ -419,8 +420,13 @@ private: TER consumeSeqProxy(SLE::pointer const& sleAccount); + TER payFee(); + + std::tuple + processPersistentChanges(TER result, XRPAmount fee); + static NotTEC checkSingleSign( ReadView const& view, @@ -428,6 +434,7 @@ private: AccountID const& idAccount, SLE::const_pointer sleAccount, beast::Journal const j); + static NotTEC checkMultiSign( ReadView const& view, diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index b57d30d2b3..2ff24d92b5 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -45,8 +45,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -1078,26 +1080,6 @@ removeDeletedTrustLines( } } -static void -removeDeletedMPTs(ApplyView& view, std::vector const& mpts, beast::Journal viewJ) -{ - // There could be at most two MPTs - one for each side of AMM pool - if (mpts.size() > 2) - { - JLOG(viewJ.error()) << "removeDeletedMPTs: deleted mpts exceed 2 " << mpts.size(); - return; - } - - for (auto const& index : mpts) - { - if (auto const sleState = view.peek({ltMPTOKEN, index}); sleState && - deleteAMMMPToken(view, sleState, (*sleState)[sfIssuer], viewJ) != tesSUCCESS) - { - JLOG(viewJ.error()) << "removeDeletedMPTs: failed to delete AMM MPT"; - } - } -} - /** Reset the context, discarding any changes made and adjust the fee. @param fee The transaction fee to be charged. @@ -1160,6 +1142,118 @@ Transactor::trapTransaction(uint256 txHash) const JLOG(j_.debug()) << "Transaction trapped: " << txHash; } +std::tuple +Transactor::processPersistentChanges(TER result, XRPAmount fee) +{ + JLOG(j_.trace()) << "reapplying because of " << transToken(result); + + // FIXME: This mechanism for doing work while returning a `tec` is + // awkward and very limiting. A more general purpose approach + // should be used, making it possible to do more useful work + // when transactions fail with a `tec` code. + + auto typesForResult = [](TER const ter) { + std::unordered_set types; + if ((ter == tecOVERSIZE) || (ter == tecKILLED)) + { + types.insert(ltOFFER); + } + else if (ter == tecINCOMPLETE) + { + types.insert(ltRIPPLE_STATE); + } + else if (ter == tecEXPIRED) + { + types.insert(ltNFTOKEN_OFFER); + types.insert(ltCREDENTIAL); + } + return types; + }; + + // Build a list of ledger entry types to collect, based on the + // result code. Only deleted objects of these types will be + // re-applied after the context is reset. + auto const typesToCollect = typesForResult(result); + + std::map> deletedObjects; + if (!typesToCollect.empty()) + { + ctx_.visit( + [&typesToCollect, &deletedObjects]( + uint256 const& index, bool isDelete, SLE::const_ref before, SLE::const_ref after) { + if (isDelete) + { + XRPL_ASSERT( + before && after, + "xrpl::Transactor::processPersistentChanges : non-null " + "SLE inputs"); + if (before && after) + { + auto const type = before->getType(); + if (typesToCollect.contains(type)) + { + // For offers, only collect unfunded removals + // (where TakerPays is unchanged) + if (type == ltOFFER && + before->getFieldAmount(sfTakerPays) != + after->getFieldAmount(sfTakerPays)) + return; + + deletedObjects[type].push_back(index); + } + } + } + }); + } + + // Reset the context, potentially adjusting the fee. + { + auto const resetResult = reset(fee); + if (!isTesSuccess(resetResult.first)) + result = resetResult.first; + + fee = resetResult.second; + } + + // Re-apply the collected deletions, but only if the reset succeeded + // and the post-reset result still allows the same deletion type. + auto const typesToApply = typesForResult(result); + if (isTecClaim(result) && !typesToApply.empty()) + { + auto const viewJ = ctx_.registry.get().getJournal("View"); + for (auto const& [type, ids] : deletedObjects) + { + if (ids.empty() || !typesToApply.contains(type)) + continue; + + switch (type) + { + case ltOFFER: + removeUnfundedOffers(view(), ids, viewJ); + break; + case ltNFTOKEN_OFFER: + removeExpiredNFTokenOffers(view(), ids, viewJ); + break; + case ltRIPPLE_STATE: + removeDeletedTrustLines(view(), ids, viewJ); + break; + case ltCREDENTIAL: + removeExpiredCredentials(view(), ids, viewJ); + break; + // LCOV_EXCL_START + default: + UNREACHABLE( + "xrpl::Transactor::processPersistentChanges() : " + "unexpected type"); + break; + // LCOV_EXCL_STOP + } + } + } + + return {result, fee, isTecClaim(result)}; +} + [[nodiscard]] TER Transactor::checkTransactionInvariants(TER result, XRPAmount fee) { @@ -1209,6 +1303,7 @@ Transactor::checkInvariants(TER result, XRPAmount fee) */ return ctx_.checkInvariants(result, fee); } + //------------------------------------------------------------------------------ ApplyResult Transactor::operator()() @@ -1275,108 +1370,7 @@ Transactor::operator()() (result == tecOVERSIZE) || (result == tecKILLED) || (result == tecINCOMPLETE) || (result == tecEXPIRED) || (isTecClaimHardFail(result, view().flags()))) { - JLOG(j_.trace()) << "reapplying because of " << transToken(result); - - // FIXME: This mechanism for doing work while returning a `tec` is - // awkward and very limiting. A more general purpose approach - // should be used, making it possible to do more useful work - // when transactions fail with a `tec` code. - std::vector removedOffers; - std::vector removedTrustLines; - std::vector removedMPTs; - std::vector expiredNFTokenOffers; - std::vector expiredCredentials; - - bool const doOffers = ((result == tecOVERSIZE) || (result == tecKILLED)); - bool const doLinesOrMPTs = (result == tecINCOMPLETE); - bool const doNFTokenOffers = (result == tecEXPIRED); - bool const doCredentials = (result == tecEXPIRED); - if (doOffers || doLinesOrMPTs || doNFTokenOffers || doCredentials) - { - ctx_.visit([doOffers, - &removedOffers, - doLinesOrMPTs, - &removedTrustLines, - &removedMPTs, - doNFTokenOffers, - &expiredNFTokenOffers, - doCredentials, - &expiredCredentials]( - uint256 const& index, - bool isDelete, - SLE::const_ref before, - SLE::const_ref after) { - if (isDelete) - { - XRPL_ASSERT( - before && after, - "xrpl::Transactor::operator()::visit : non-null SLE " - "inputs"); - if (doOffers && before && after && (before->getType() == ltOFFER) && - (before->getFieldAmount(sfTakerPays) == after->getFieldAmount(sfTakerPays))) - { - // Removal of offer found or made unfunded - removedOffers.push_back(index); - } - - if (doLinesOrMPTs && before && after) - { - // Removal of obsolete AMM trust line - if (before->getType() == ltRIPPLE_STATE) - { - removedTrustLines.push_back(index); - } - else if (before->getType() == ltMPTOKEN) - { - removedMPTs.push_back(index); - } - } - - if (doNFTokenOffers && before && after && - (before->getType() == ltNFTOKEN_OFFER)) - expiredNFTokenOffers.push_back(index); - - if (doCredentials && before && after && (before->getType() == ltCREDENTIAL)) - expiredCredentials.push_back(index); - } - }); - } - - // Reset the context, potentially adjusting the fee. - { - auto const resetResult = reset(fee); - if (!isTesSuccess(resetResult.first)) - result = resetResult.first; - - fee = resetResult.second; - } - - // If necessary, remove any offers found unfunded during processing - if ((result == tecOVERSIZE) || (result == tecKILLED)) - { - removeUnfundedOffers(view(), removedOffers, ctx_.registry.get().getJournal("View")); - } - - if (result == tecEXPIRED) - { - removeExpiredNFTokenOffers( - view(), expiredNFTokenOffers, ctx_.registry.get().getJournal("View")); - } - - if (result == tecINCOMPLETE) - { - removeDeletedTrustLines( - view(), removedTrustLines, ctx_.registry.get().getJournal("View")); - removeDeletedMPTs(view(), removedMPTs, ctx_.registry.get().getJournal("View")); - } - - if (result == tecEXPIRED) - { - removeExpiredCredentials( - view(), expiredCredentials, ctx_.registry.get().getJournal("View")); - } - - applied = isTecClaim(result); + std::tie(result, fee, applied) = processPersistentChanges(result, fee); } if (applied) diff --git a/src/test/app/NFToken_test.cpp b/src/test/app/NFToken_test.cpp index ba8f09c449..cb92b23a4c 100644 --- a/src/test/app/NFToken_test.cpp +++ b/src/test/app/NFToken_test.cpp @@ -1120,6 +1120,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite if (features[fixCleanup3_1_3]) { buyerCount--; + BEAST_EXPECT(!env.closed()->exists(keylet::nftoffer(buyerExpOfferIndex))); } BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); @@ -1143,6 +1144,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::Suite if (features[fixCleanup3_1_3]) { aliceCount--; + BEAST_EXPECT(!env.closed()->exists(keylet::nftoffer(aliceExpOfferIndex))); } BEAST_EXPECT(ownerCount(env, alice) == aliceCount); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); diff --git a/src/test/app/Offer_test.cpp b/src/test/app/Offer_test.cpp index 7382f4f090..ea8b0a7c0e 100644 --- a/src/test/app/Offer_test.cpp +++ b/src/test/app/Offer_test.cpp @@ -797,11 +797,13 @@ public: // The offer expires (it's not removed yet). env.close(); env.require(Owners(bob, 1), offers(bob, 1)); + auto const expiredBobOffer = keylet::offer(bob, env.seq(bob) - 1); // bob creates the offer that will be crossed. env(offer(bob, usd(500), XRP(500)), Ter(tesSUCCESS)); env.close(); env.require(Owners(bob, 2), offers(bob, 2)); + auto const crossedBobOffer = keylet::offer(bob, env.seq(bob) - 1); env(trust(alice, usd(1000)), Ter(tesSUCCESS)); env(pay(gw, alice, usd(1000)), Ter(tesSUCCESS)); @@ -820,6 +822,8 @@ public: Balance(bob, usd(kNone)), Owners(bob, 1), offers(bob, 1)); + BEAST_EXPECT(!env.current()->exists(expiredBobOffer)); + BEAST_EXPECT(env.current()->exists(crossedBobOffer)); // Order that can be filled env(offer(alice, XRP(500), usd(500)), Txflags(tfFillOrKill), Ter(tesSUCCESS)); @@ -835,6 +839,27 @@ public: offers(bob, 0)); } + // A failed Fill-or-Kill may tentatively consume a funded offer before + // the transaction is reset. That offer must not be treated as an + // unfunded offer cleanup. + { + Env env{*this, features}; + + env.fund(startBalance, gw, alice, bob); + env.close(); + + env(offer(bob, usd(500), XRP(500)), Ter(tesSUCCESS)); + env.close(); + auto const bobOffer = keylet::offer(bob, env.seq(bob) - 1); + + env(trust(alice, usd(1000)), Ter(tesSUCCESS)); + env(pay(gw, alice, usd(1000)), Ter(tesSUCCESS)); + env(offer(alice, XRP(1000), usd(1000)), Txflags(tfFillOrKill), Ter(tecKILLED)); + + env.require(offers(alice, 0), offers(bob, 1), Balance(alice, usd(1000))); + BEAST_EXPECT(env.current()->exists(bobOffer)); + } + // Immediate or Cancel - cross as much as possible // and add nothing on the books: { diff --git a/src/test/app/SetRegularKey_test.cpp b/src/test/app/SetRegularKey_test.cpp index b5d1af9ef0..b512885606 100644 --- a/src/test/app/SetRegularKey_test.cpp +++ b/src/test/app/SetRegularKey_test.cpp @@ -72,6 +72,27 @@ public: env(regkey(alice, alice), Ter(temBAD_REGKEY)); } + void + testNoAlternativeKey() + { + using namespace test::jtx; + + testcase("Cannot remove last signing method"); + Env env{*this, testableAmendments()}; + Account const alice("alice"); + Account const bob("bob"); + env.fund(XRP(10000), alice); + + env(regkey(alice, bob)); + env(fset(alice, asfDisableMaster), Sig(alice)); + + env(regkey(alice, kDisabled), Sig(bob), Ter(tecNO_ALTERNATIVE_KEY)); + + auto const sle = env.le(alice); + BEAST_EXPECT( + sle && sle->isFlag(lsfDisableMaster) && sle->getAccountID(sfRegularKey) == bob.id()); + } + void testPasswordSpent() { @@ -169,6 +190,7 @@ public: { testDisabledMasterKey(); testDisabledRegularKey(); + testNoAlternativeKey(); testPasswordSpent(); testUniversalMask(); testTicketRegularKey(); From ff02269c0dd1707b38ae783fdf9ba05b07037af7 Mon Sep 17 00:00:00 2001 From: Bart Date: Mon, 22 Jun 2026 18:35:28 -0400 Subject: [PATCH 78/78] refactor: Use dispatch instead of post (#7438) Co-authored-by: Bart <11445373+bthomee@users.noreply.github.com> --- src/xrpld/overlay/detail/PeerImp.cpp | 367 ++++++++++++--------------- 1 file changed, 167 insertions(+), 200 deletions(-) diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 21e84d6fc7..e1d7d23215 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -70,7 +70,6 @@ #include #include #include -#include #include #include #include @@ -198,78 +197,70 @@ stringIsUInt256Sized(std::string const& pBuffStr) void PeerImp::run() { - if (!strand_.running_in_this_thread()) - { - post(strand_, std::bind(&PeerImp::run, shared_from_this())); - return; - } + dispatch(strand_, [self = shared_from_this()]() { + auto parseLedgerHash = [](std::string_view value) -> std::optional { + if (uint256 ret; ret.parseHex(value)) + return ret; - auto parseLedgerHash = [](std::string_view value) -> std::optional { - if (uint256 ret; ret.parseHex(value)) - return ret; + if (auto const s = base64Decode(value); s.size() == uint256::size()) + return uint256::fromRaw(s); - if (auto const s = base64Decode(value); s.size() == uint256::size()) - return uint256::fromRaw(s); + return std::nullopt; + }; - return std::nullopt; - }; + std::optional closed; + std::optional previous; - std::optional closed; - std::optional previous; + if (auto const iter = self->headers_.find("Closed-Ledger"); iter != self->headers_.end()) + { + closed = parseLedgerHash(iter->value()); - if (auto const iter = headers_.find("Closed-Ledger"); iter != headers_.end()) - { - closed = parseLedgerHash(iter->value()); + if (!closed) + self->fail("Malformed handshake data (1)"); + } - if (!closed) - fail("Malformed handshake data (1)"); - } + if (auto const iter = self->headers_.find("Previous-Ledger"); iter != self->headers_.end()) + { + previous = parseLedgerHash(iter->value()); - if (auto const iter = headers_.find("Previous-Ledger"); iter != headers_.end()) - { - previous = parseLedgerHash(iter->value()); + if (!previous) + self->fail("Malformed handshake data (2)"); + } - if (!previous) - fail("Malformed handshake data (2)"); - } + if (previous && !closed) + self->fail("Malformed handshake data (3)"); - if (previous && !closed) - fail("Malformed handshake data (3)"); + { + std::scoped_lock const sl(self->recentLock_); + if (closed) + self->closedLedgerHash_ = *closed; + if (previous) + self->previousLedgerHash_ = *previous; + } - { - std::scoped_lock const sl(recentLock_); - if (closed) - closedLedgerHash_ = *closed; - if (previous) - previousLedgerHash_ = *previous; - } + if (self->inbound_) + { + self->doAccept(); + } + else + { + self->doProtocolStart(); + } - if (inbound_) - { - doAccept(); - } - else - { - doProtocolStart(); - } - - // Anything else that needs to be done with the connection should be - // done in doProtocolStart + // Anything else that needs to be done with the connection should be + // done in doProtocolStart + }); } void PeerImp::stop() { - if (!strand_.running_in_this_thread()) - { - post(strand_, std::bind(&PeerImp::stop, shared_from_this())); - return; - } + dispatch(strand_, [self = shared_from_this()]() { + if (!self->socket_.is_open()) + return; - if (!socket_.is_open()) - return; - - close(); + self->close(); + }); } //------------------------------------------------------------------------------ @@ -277,126 +268,111 @@ PeerImp::stop() void PeerImp::send(std::shared_ptr const& m) { - if (!strand_.running_in_this_thread()) - { - post(strand_, std::bind(&PeerImp::send, shared_from_this(), m)); - return; - } - if (gracefulClose_) - return; - if (detaching_) - return; - if (!socket_.is_open()) - return; + dispatch(strand_, [self = shared_from_this(), m]() { + if (self->gracefulClose_) + return; + if (self->detaching_) + return; + if (!self->socket_.is_open()) + return; - auto validator = m->getValidatorKey(); - if (validator && !squelch_.expireSquelch(*validator)) - { - overlay_.reportOutboundTraffic( - TrafficCount::Category::SquelchSuppressed, - static_cast(m->getBuffer(compressionEnabled_).size())); - return; - } + auto validator = m->getValidatorKey(); + if (validator && !self->squelch_.expireSquelch(*validator)) + { + self->overlay_.reportOutboundTraffic( + TrafficCount::Category::SquelchSuppressed, + static_cast(m->getBuffer(self->compressionEnabled_).size())); + return; + } - // report categorized outgoing traffic - overlay_.reportOutboundTraffic( - safeCast(m->getCategory()), - static_cast(m->getBuffer(compressionEnabled_).size())); + // report categorized outgoing traffic + self->overlay_.reportOutboundTraffic( + safeCast(m->getCategory()), + static_cast(m->getBuffer(self->compressionEnabled_).size())); - // report total outgoing traffic - overlay_.reportOutboundTraffic( - TrafficCount::Category::Total, static_cast(m->getBuffer(compressionEnabled_).size())); + // report total outgoing traffic + self->overlay_.reportOutboundTraffic( + TrafficCount::Category::Total, + static_cast(m->getBuffer(self->compressionEnabled_).size())); - auto sendqSize = sendQueue_.size(); + auto sendqSize = self->sendQueue_.size(); - if (sendqSize < Tuning::kTargetSendQueue) - { - // To detect a peer that does not read from their - // side of the connection, we expect a peer to have - // a small senq periodically - largeSendq_ = 0; - } - else if (auto sink = journal_.debug(); sink && (sendqSize % Tuning::kSendQueueLogFreq) == 0) - { - std::string const n = name(); - sink << n << " sendq: " << sendqSize; - } + if (sendqSize < Tuning::kTargetSendQueue) + { + // To detect a peer that does not read from their + // side of the connection, we expect a peer to have + // a small sendq periodically + self->largeSendq_ = 0; + } + else if ( + auto sink = self->journal_.debug(); + sink && (sendqSize % Tuning::kSendQueueLogFreq) == 0) + { + std::string const n = self->name(); + sink << n << " sendq: " << sendqSize; + } - sendQueue_.push(m); + self->sendQueue_.push(m); - if (sendqSize != 0) - return; + if (sendqSize != 0) + return; - boost::asio::async_write( - stream_, - boost::asio::buffer(sendQueue_.front()->getBuffer(compressionEnabled_)), - bind_executor( - strand_, - std::bind( - &PeerImp::onWriteMessage, - shared_from_this(), - std::placeholders::_1, - std::placeholders::_2))); + boost::asio::async_write( + self->stream_, + boost::asio::buffer(self->sendQueue_.front()->getBuffer(self->compressionEnabled_)), + bind_executor( + self->strand_, + std::bind( + &PeerImp::onWriteMessage, self, std::placeholders::_1, std::placeholders::_2))); + }); } void PeerImp::sendTxQueue() { - if (!strand_.running_in_this_thread()) - { - post(strand_, std::bind(&PeerImp::sendTxQueue, shared_from_this())); - return; - } - - if (!txQueue_.empty()) - { - protocol::TMHaveTransactions ht; - std::ranges::for_each( - txQueue_, [&](auto const& hash) { ht.add_hashes(hash.data(), hash.size()); }); - JLOG(pJournal_.trace()) << "sendTxQueue " << txQueue_.size(); - txQueue_.clear(); - send(std::make_shared(ht, protocol::mtHAVE_TRANSACTIONS)); - } + dispatch(strand_, [self = shared_from_this()]() { + if (!self->txQueue_.empty()) + { + protocol::TMHaveTransactions ht; + std::ranges::for_each( + self->txQueue_, [&](auto const& hash) { ht.add_hashes(hash.data(), hash.size()); }); + JLOG(self->pJournal_.trace()) << "sendTxQueue " << self->txQueue_.size(); + self->txQueue_.clear(); + self->send(std::make_shared(ht, protocol::mtHAVE_TRANSACTIONS)); + } + }); } void PeerImp::addTxQueue(uint256 const& hash) { - if (!strand_.running_in_this_thread()) - { - post(strand_, std::bind(&PeerImp::addTxQueue, shared_from_this(), hash)); - return; - } + dispatch(strand_, [self = shared_from_this(), hash]() { + if (self->txQueue_.size() == reduce_relay::kMaxTxQueueSize) + { + JLOG(self->pJournal_.warn()) << "addTxQueue exceeds the cap"; + self->sendTxQueue(); + } - if (txQueue_.size() == reduce_relay::kMaxTxQueueSize) - { - JLOG(pJournal_.warn()) << "addTxQueue exceeds the cap"; - sendTxQueue(); - } - - txQueue_.insert(hash); - JLOG(pJournal_.trace()) << "addTxQueue " << txQueue_.size(); + self->txQueue_.insert(hash); + JLOG(self->pJournal_.trace()) << "addTxQueue " << self->txQueue_.size(); + }); } void PeerImp::removeTxQueue(uint256 const& hash) { - if (!strand_.running_in_this_thread()) - { - post(strand_, std::bind(&PeerImp::removeTxQueue, shared_from_this(), hash)); - return; - } - - auto removed = txQueue_.erase(hash); - JLOG(pJournal_.trace()) << "removeTxQueue " << removed; + dispatch(strand_, [self = shared_from_this(), hash]() { + auto removed = self->txQueue_.erase(hash); + JLOG(self->pJournal_.trace()) << "removeTxQueue " << removed; + }); } void PeerImp::charge(Resource::Charge const& fee, std::string const& context) { - dispatch(strand_, [this, self = shared_from_this(), fee, context]() { - if ((usage_.charge(fee, context) == Resource::Disposition::Drop) && - usage_.disconnect(pJournal_)) + dispatch(strand_, [self = shared_from_this(), fee, context]() { + if ((self->usage_.charge(fee, context) == Resource::Disposition::Drop) && + self->usage_.disconnect(self->pJournal_)) { // Idempotent: only the first worker to observe Drop counts the // metric and posts fail(). Without the guard, several queued @@ -405,11 +381,11 @@ PeerImp::charge(Resource::Charge const& fee, std::string const& context) // shutdowns. fail(std::string const&) self-posts to strand_ // when invoked off-strand. bool expected = false; - if (chargeDisconnectFired_.compare_exchange_strong( + if (self->chargeDisconnectFired_.compare_exchange_strong( expected, true, std::memory_order_acq_rel)) { - overlay_.incPeerDisconnectCharges(); - fail("charge: Resources"); + self->overlay_.incPeerDisconnectCharges(); + self->fail("charge: Resources"); } } }); @@ -640,20 +616,14 @@ PeerImp::close() void PeerImp::fail(std::string const& reason) { - if (!strand_.running_in_this_thread()) - { - post( - strand_, - std::bind( - (void (Peer::*)(std::string const&))&PeerImp::fail, shared_from_this(), reason)); - return; - } - if (journal_.active(beast::Severity::Warning) && socket_.is_open()) - { - std::string const n = name(); - JLOG(journal_.warn()) << n << " failed: " << reason; - } - close(); + dispatch(strand_, [self = shared_from_this(), reason]() { + if (self->journal_.active(beast::Severity::Warning) && self->socket_.is_open()) + { + std::string const n = self->name(); + JLOG(self->journal_.warn()) << n << " failed: " << reason; + } + self->close(); + }); } void @@ -2752,45 +2722,42 @@ PeerImp::onMessage(std::shared_ptr const& m) void PeerImp::onMessage(std::shared_ptr const& m) { - using on_message_fn = void (PeerImp::*)(std::shared_ptr const&); - if (!strand_.running_in_this_thread()) - { - post(strand_, std::bind((on_message_fn)&PeerImp::onMessage, shared_from_this(), m)); - return; - } + dispatch(strand_, [self = shared_from_this(), m]() { + if (!m->has_validatorpubkey()) + { + self->fee_.update(Resource::kFeeInvalidData, "squelch no pubkey"); + return; + } + auto validator = m->validatorpubkey(); + auto const slice{makeSlice(validator)}; + if (!publicKeyType(slice)) + { + self->fee_.update(Resource::kFeeInvalidData, "squelch bad pubkey"); + return; + } + PublicKey const key(slice); - if (!m->has_validatorpubkey()) - { - fee_.update(Resource::kFeeInvalidData, "squelch no pubkey"); - return; - } - auto validator = m->validatorpubkey(); - auto const slice{makeSlice(validator)}; - if (!publicKeyType(slice)) - { - fee_.update(Resource::kFeeInvalidData, "squelch bad pubkey"); - return; - } - PublicKey const key(slice); + // Ignore the squelch for validator's own messages. + if (key == self->app_.getValidationPublicKey()) + { + JLOG(self->pJournal_.debug()) + << "onMessage: TMSquelch discarding validator's squelch " << slice; + return; + } - // Ignore the squelch for validator's own messages. - if (key == app_.getValidationPublicKey()) - { - JLOG(pJournal_.debug()) << "onMessage: TMSquelch discarding validator's squelch " << slice; - return; - } + std::uint32_t const duration = m->has_squelchduration() ? m->squelchduration() : 0; + if (!m->squelch()) + { + self->squelch_.removeSquelch(key); + } + else if (!self->squelch_.addSquelch(key, std::chrono::seconds{duration})) + { + self->fee_.update(Resource::kFeeInvalidData, "squelch duration"); + } - std::uint32_t const duration = m->has_squelchduration() ? m->squelchduration() : 0; - if (!m->squelch()) - { - squelch_.removeSquelch(key); - } - else if (!squelch_.addSquelch(key, std::chrono::seconds{duration})) - { - fee_.update(Resource::kFeeInvalidData, "squelch duration"); - } - - JLOG(pJournal_.debug()) << "onMessage: TMSquelch " << slice << " " << id() << " " << duration; + JLOG(self->pJournal_.debug()) + << "onMessage: TMSquelch " << slice << " " << self->id() << " " << duration; + }); } //--------------------------------------------------------------------------