From 6809690fadbc8f93a462f0682d277b2e67879166 Mon Sep 17 00:00:00 2001 From: Ed Hennis Date: Fri, 15 May 2026 14:04:49 -0400 Subject: [PATCH 01/17] release: Set version to 3.3.0-b0 (#7280) Co-authored-by: Bart --- 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 07c5f6f4dc..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-b0" +char const* const versionString = "3.3.0-b0" // clang-format on ; From c7ecfc6a970b2ef527097e51545cebc4285ed684 Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Fri, 15 May 2026 19:02:04 -0400 Subject: [PATCH 02/17] refactor: Clean up comments post-clang-tidy changes (#7283) --- .../xrpl/protocol/detail/ledger_entries.macro | 4 ++-- .../ledger/helpers/RippleStateHelpers.cpp | 16 ++++++++-------- src/libxrpl/ledger/helpers/TokenHelpers.cpp | 2 +- src/libxrpl/tx/Transactor.cpp | 2 +- .../tx/transactors/delegate/DelegateSet.cpp | 4 ++-- src/libxrpl/tx/transactors/dex/AMMVote.cpp | 10 +++++----- src/libxrpl/tx/transactors/lending/LoanPay.cpp | 2 +- src/test/app/AMMMPT_test.cpp | 2 +- src/test/app/Invariants_test.cpp | 2 +- src/xrpld/app/misc/NetworkOPs.cpp | 2 +- src/xrpld/app/misc/detail/TxQ.cpp | 2 +- 11 files changed, 24 insertions(+), 24 deletions(-) diff --git a/include/xrpl/protocol/detail/ledger_entries.macro b/include/xrpl/protocol/detail/ledger_entries.macro index bf641862d1..c4b392a92f 100644 --- a/include/xrpl/protocol/detail/ledger_entries.macro +++ b/include/xrpl/protocol/detail/ledger_entries.macro @@ -84,7 +84,7 @@ LEDGER_ENTRY(ltNEGATIVE_UNL, 0x004e, NegativeUNL, nunl, ({ /** A ledger object which contains a list of NFTs - \sa keylet::nftpage_min, keylet::nftpage_max, keylet::nftpage + \sa keylet::nftpageMin, keylet::nftpageMax, keylet::nftpage */ LEDGER_ENTRY(ltNFTOKEN_PAGE, 0x0050, NFTokenPage, nft_page, ({ {sfPreviousPageMin, SoeOptional}, @@ -112,7 +112,7 @@ LEDGER_ENTRY(ltSIGNER_LIST, 0x0053, SignerList, signer_list, ({ /** A ledger object which describes a ticket. - \sa keylet::ticket + \sa keylet::kTicket */ LEDGER_ENTRY(ltTICKET, 0x0054, Ticket, ticket, ({ {sfAccount, SoeRequired}, diff --git a/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp b/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp index 3b37dff23c..5aaa417ad9 100644 --- a/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp +++ b/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp @@ -183,15 +183,15 @@ trustCreate( bool const bSrcHigh, AccountID const& uSrcAccountID, AccountID const& uDstAccountID, - uint256 const& uIndex, // --> ripple state entry - SLE::ref sleAccount, // --> the account being set. - bool const bAuth, // --> authorize account. - bool const bNoRipple, // --> others cannot ripple through - bool const bFreeze, // --> funds cannot leave - bool bDeepFreeze, // --> can neither receive nor send funds - STAmount const& saBalance, // --> balance of account being set. + uint256 const& uIndex, // ripple state entry + SLE::ref sleAccount, // the account being set. + bool const bAuth, // authorize account. + bool const bNoRipple, // others cannot ripple through + bool const bFreeze, // funds cannot leave + bool bDeepFreeze, // can neither receive nor send funds + STAmount const& saBalance, // balance of account being set. // Issuer should be noAccount() - STAmount const& saLimit, // --> limit for account being set. + STAmount const& saLimit, // limit for account being set. // Issuer should be the account being set. std::uint32_t uQualityIn, std::uint32_t uQualityOut, diff --git a/src/libxrpl/ledger/helpers/TokenHelpers.cpp b/src/libxrpl/ledger/helpers/TokenHelpers.cpp index 0c20392f4f..c9dccb884d 100644 --- a/src/libxrpl/ledger/helpers/TokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/TokenHelpers.cpp @@ -1191,7 +1191,7 @@ directSendNoLimitMultiMPT( // Use uint64_t, not STAmount, to keep MaximumAmount comparisons in exact // integer arithmetic. STAmount implicitly converts to Number, whose // small-scale mantissa (~16 digits) can lose precision for values near - // maxMPTokenAmount (19 digits). + // kMaxMpTokenAmount (19 digits). std::uint64_t totalSendAmount{0}; std::uint64_t const maximumAmount = sle->at(~sfMaximumAmount).value_or(kMaxMpTokenAmount); std::uint64_t const outstandingAmount = sle->getFieldU64(sfOutstandingAmount); diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index 81a30fc5ef..995013a3ca 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -1238,7 +1238,7 @@ Transactor::operator()() if (isTecClaim(result) && ((view().flags() & TapFailHard) != 0u)) { - // If the tapFAIL_HARD flag is set, a tec result + // If the TapFailHard flag is set, a tec result // must not do anything ctx_.discard(); applied = false; diff --git a/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp b/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp index 085af8b4c7..990767c819 100644 --- a/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp +++ b/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp @@ -115,8 +115,8 @@ DelegateSet::doApply() (*sle)[sfOwnerNode] = *page; - // Add to authorized account's owner directory so the object can be found - // and cleaned up when the authorized account is deleted. + // Add to authorized account's owner directory so AccountDelete can find + // and clean up inbound delegations when the authorized account is deleted. auto const destPage = ctx_.view().dirInsert( keylet::ownerDir(authAccount), delegateKey, describeOwnerDir(authAccount)); diff --git a/src/libxrpl/tx/transactors/dex/AMMVote.cpp b/src/libxrpl/tx/transactors/dex/AMMVote.cpp index 30ae6004f0..a4afb5392e 100644 --- a/src/libxrpl/tx/transactors/dex/AMMVote.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMVote.cpp @@ -80,14 +80,14 @@ AMMVote::preclaim(PreclaimContext const& ctx) } static std::pair -applyVote(ApplyContext& ctx, Sandbox& sb, AccountID const& account, beast::Journal j) +applyVote(ApplyContext& ctx, Sandbox& sb, AccountID const& accountID, beast::Journal j) { auto const feeNew = ctx.tx[sfTradingFee]; auto ammSle = sb.peek(keylet::amm(ctx.tx[sfAsset], ctx.tx[sfAsset2])); if (!ammSle) return {tecINTERNAL, false}; STAmount const lptAMMBalance = (*ammSle)[sfLPTokenBalance]; - auto const lpTokensNew = ammLPHolds(sb, *ammSle, account, ctx.journal); + auto const lpTokensNew = ammLPHolds(sb, *ammSle, accountID, ctx.journal); std::optional minTokens; std::size_t minPos{0}; AccountID minAccount{0}; @@ -108,13 +108,13 @@ applyVote(ApplyContext& ctx, Sandbox& sb, AccountID const& account, beast::Journ auto lpTokens = ammLPHolds(sb, *ammSle, entryAccount, ctx.journal); if (lpTokens == beast::kZero) { - JLOG(j.debug()) << "AMMVote::applyVote, account " << entryAccount << " is not LP"; + JLOG(j.debug()) << "AMMVote::applyVote, accountID " << entryAccount << " is not LP"; continue; } auto feeVal = entry[sfTradingFee]; STObject newEntry = STObject::makeInnerObject(sfVoteEntry); // The account already has the vote entry. - if (entryAccount == account) + if (entryAccount == accountID) { lpTokens = lpTokensNew; feeVal = feeNew; @@ -156,7 +156,7 @@ applyVote(ApplyContext& ctx, Sandbox& sb, AccountID const& account, beast::Journ sfVoteWeight, static_cast( Number(lpTokensNew) * kVoteWeightScaleFactor / lptAMMBalance)); - newEntry.setAccountID(sfAccount, account); + newEntry.setAccountID(sfAccount, accountID); num += feeNew * lpTokensNew; den += lpTokensNew; if (minPos) diff --git a/src/libxrpl/tx/transactors/lending/LoanPay.cpp b/src/libxrpl/tx/transactors/lending/LoanPay.cpp index 89e7bee60b..12a0212b72 100644 --- a/src/libxrpl/tx/transactors/lending/LoanPay.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanPay.cpp @@ -99,7 +99,7 @@ LoanPay::calculateBaseFee(ReadView const& view, STTx const& tx) if (loanSle->at(sfPaymentRemaining) <= kLoanPaymentsPerFeeIncrement) { - // If there are fewer than loanPaymentsPerFeeIncrement payments left to + // If there are fewer than kLoanPaymentsPerFeeIncrement payments left to // pay, we can skip the computations. return normalCost; } diff --git a/src/test/app/AMMMPT_test.cpp b/src/test/app/AMMMPT_test.cpp index 4d073d0188..eba388e5fd 100644 --- a/src/test/app/AMMMPT_test.cpp +++ b/src/test/app/AMMMPT_test.cpp @@ -7037,7 +7037,7 @@ private: } // This test validates both invariant changes work together for - // the specific case of MPT/MPT pools with > maxDeletableAMMTrustLines. + // the specific case of MPT/MPT pools with > kMaxDeletableAmmTrustLines. { Env env( *this, diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index 4b24f83180..775e18656b 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -182,7 +182,7 @@ class Invariants_test : public beast::unit_test::Suite // Invariants normally run in the Transaction's "apply" (operator()) context, and can always // access global Rules. - CurrentTransactionRulesGuard const rg(ov.rules()); + CurrentTransactionRulesGuard const rulesGuard(ov.rules()); BEAST_EXPECT(precheck(a1, a2, ac)); diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index 343f5dff94..d6f9d10f05 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -4549,7 +4549,7 @@ NetworkOPsImp::getBookPage( uOfferOwnerID, book.out.currency, book.out.account, - FreezeHandling::fhZERO_IF_FROZEN); + FreezeHandling::ZeroIfFrozen); if (saOwnerFunds.isNegative()) { diff --git a/src/xrpld/app/misc/detail/TxQ.cpp b/src/xrpld/app/misc/detail/TxQ.cpp index d23aca8744..0f70f17046 100644 --- a/src/xrpld/app/misc/detail/TxQ.cpp +++ b/src/xrpld/app/misc/detail/TxQ.cpp @@ -395,7 +395,7 @@ TxQ::canBeHeld( // PreviousTxnID is deprecated and should never be used. // AccountTxnID is not supported by the transaction // queue yet, but should be added in the future. - // tapFAIL_HARD transactions are never held + // TapFailHard transactions are never held if (tx.isFieldPresent(sfPreviousTxnID) || tx.isFieldPresent(sfAccountTxnID) || ((flags & TapFailHard) != 0u)) return telCAN_NOT_QUEUE; From 93836f22db8e71acad06d6a390f25d3d41795380 Mon Sep 17 00:00:00 2001 From: Michael Legleux Date: Fri, 15 May 2026 22:08:37 -0700 Subject: [PATCH 03/17] ci: Add Linux package builds (DEB + RPM) to CI (#6639) --- .github/scripts/strategy-matrix/generate.py | 64 +++++-- .github/scripts/strategy-matrix/linux.json | 6 +- .github/workflows/on-pr.yml | 12 ++ .github/workflows/on-tag.yml | 23 ++- .github/workflows/on-trigger.yml | 9 + .github/workflows/reusable-package.yml | 99 ++++++++++ CMakeLists.txt | 1 + cfg/validators-example.txt | 2 +- cmake/XrplPackaging.cmake | 44 +++++ cspell.config.yaml | 12 +- package/README.md | 175 ++++++++++++++++++ package/build_pkg.sh | 192 ++++++++++++++++++++ package/debian/control | 23 +++ package/debian/copyright | 18 ++ package/debian/rules | 27 +++ package/debian/source/format | 1 + package/debian/xrpld.docs | 2 + package/debian/xrpld.links | 2 + package/rpm/xrpld.spec | 100 ++++++++++ package/shared/50-xrpld.preset | 4 + package/shared/update-xrpld | 152 ++++++++++++++++ package/shared/update-xrpld.service | 16 ++ package/shared/update-xrpld.timer | 10 + package/shared/xrpld.logrotate | 19 ++ package/shared/xrpld.service | 22 +++ package/shared/xrpld.sysusers | 1 + package/shared/xrpld.tmpfiles | 2 + src/test/app/ValidatorSite_test.cpp | 2 +- src/xrpld/core/detail/Config.cpp | 4 +- 29 files changed, 1018 insertions(+), 26 deletions(-) create mode 100644 .github/workflows/reusable-package.yml create mode 100644 cmake/XrplPackaging.cmake create mode 100644 package/README.md create mode 100755 package/build_pkg.sh create mode 100644 package/debian/control create mode 100644 package/debian/copyright create mode 100644 package/debian/rules create mode 100644 package/debian/source/format create mode 100644 package/debian/xrpld.docs create mode 100644 package/debian/xrpld.links create mode 100644 package/rpm/xrpld.spec create mode 100644 package/shared/50-xrpld.preset create mode 100755 package/shared/update-xrpld create mode 100644 package/shared/update-xrpld.service create mode 100644 package/shared/update-xrpld.timer create mode 100644 package/shared/xrpld.logrotate create mode 100644 package/shared/xrpld.service create mode 100644 package/shared/xrpld.sysusers create mode 100644 package/shared/xrpld.tmpfiles diff --git a/.github/scripts/strategy-matrix/generate.py b/.github/scripts/strategy-matrix/generate.py index 6f00c69416..6eccfcc6be 100755 --- a/.github/scripts/strategy-matrix/generate.py +++ b/.github/scripts/strategy-matrix/generate.py @@ -32,7 +32,32 @@ We will further set additional CMake arguments as follows: """ -def generate_strategy_matrix(all: bool, config: Config) -> list: +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) + + +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. + """ + return [ + { + "artifact_name": f"xrpld-{build_config_name(os, 'linux/amd64', 'Release')}", + "os": os, + } + for os in config.os + if os.get("package", False) + ] + + +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 @@ -101,14 +126,15 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: continue # RHEL: - # - 9 using GCC 12: Debug on linux/amd64. + # - 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 == "Debug" + and build_type in ["Debug", "Release"] and architecture["platform"] == "linux/amd64" ): skip = False @@ -123,7 +149,8 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: continue # Ubuntu: - # - Jammy using GCC 12: Debug on linux/arm64. + # - 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. @@ -136,6 +163,12 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: 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" @@ -218,17 +251,7 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: # Generate a unique name for the configuration, e.g. macos-arm64-debug # or debian-bookworm-gcc-12-amd64-release. - config_name = os["distro_name"] - if (n := os["distro_version"]) != "": - config_name += f"-{n}" - if (n := os["compiler_name"]) != "": - config_name += f"-{n}" - if (n := os["compiler_version"]) != "": - config_name += f"-{n}" - config_name += ( - f"-{architecture['platform'][architecture['platform'].find('/')+1:]}" - ) - config_name += f"-{build_type.lower()}" + 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: @@ -332,10 +355,19 @@ if __name__ == "__main__": required=False, type=Path, ) + parser.add_argument( + "-p", + "--packaging", + help="Emit the packaging matrix (derived from the 'package' field on os entries) instead of the build/test matrix.", + action="store_true", + ) args = parser.parse_args() matrix = [] - if args.config is None or args.config == "": + 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") ) diff --git a/.github/scripts/strategy-matrix/linux.json b/.github/scripts/strategy-matrix/linux.json index 1b9af523cb..4f090a81a3 100644 --- a/.github/scripts/strategy-matrix/linux.json +++ b/.github/scripts/strategy-matrix/linux.json @@ -127,7 +127,8 @@ "distro_version": "9", "compiler_name": "gcc", "compiler_version": "12", - "image_sha": "4c086b9" + "image_sha": "4c086b9", + "package": true }, { "distro_name": "rhel", @@ -169,7 +170,8 @@ "distro_version": "jammy", "compiler_name": "gcc", "compiler_version": "12", - "image_sha": "4c086b9" + "image_sha": "4c086b9", + "package": true }, { "distro_name": "ubuntu", diff --git a/.github/workflows/on-pr.yml b/.github/workflows/on-pr.yml index d95f3a6c00..ca715e0376 100644 --- a/.github/workflows/on-pr.yml +++ b/.github/workflows/on-pr.yml @@ -64,11 +64,13 @@ jobs: .github/workflows/reusable-build-test-config.yml .github/workflows/reusable-build-test.yml .github/workflows/reusable-clang-tidy.yml + .github/workflows/reusable-package.yml .github/workflows/reusable-strategy-matrix.yml .github/workflows/reusable-test.yml .github/workflows/reusable-upload-recipe.yml .clang-tidy .codecov.yml + cfg/** cmake/** conan/** external/** @@ -78,6 +80,10 @@ jobs: CMakeLists.txt conanfile.py conan.lock + LICENSE.md + package/** + README.md + - name: Check whether to run # This step determines whether the rest of the workflow should # run. The rest of the workflow will run if this job runs AND at @@ -134,6 +140,11 @@ jobs: secrets: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + package: + needs: [should-run, build-test] + if: ${{ needs.should-run.outputs.go == 'true' }} + uses: ./.github/workflows/reusable-package.yml + upload-recipe: needs: - should-run @@ -168,6 +179,7 @@ jobs: - check-rename - clang-tidy - build-test + - package - upload-recipe - notify-clio runs-on: ubuntu-latest diff --git a/.github/workflows/on-tag.yml b/.github/workflows/on-tag.yml index e570a0e119..b7517ccf11 100644 --- a/.github/workflows/on-tag.yml +++ b/.github/workflows/on-tag.yml @@ -1,5 +1,5 @@ -# This workflow uploads the libxrpl recipe to the Conan remote when a versioned -# tag is pushed. +# This workflow uploads the libxrpl recipe to the Conan remote and builds +# release packages when a versioned tag is pushed. name: Tag on: @@ -22,3 +22,22 @@ jobs: secrets: remote_username: ${{ secrets.CONAN_REMOTE_USERNAME }} remote_password: ${{ secrets.CONAN_REMOTE_PASSWORD }} + + build-test: + if: ${{ github.repository == 'XRPLF/rippled' }} + uses: ./.github/workflows/reusable-build-test.yml + strategy: + fail-fast: true + matrix: + os: [linux] + with: + ccache_enabled: false + os: ${{ matrix.os }} + strategy_matrix: minimal + secrets: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + + package: + if: ${{ github.repository == 'XRPLF/rippled' }} + needs: build-test + uses: ./.github/workflows/reusable-package.yml diff --git a/.github/workflows/on-trigger.yml b/.github/workflows/on-trigger.yml index 11d98bffb7..803ba3c87b 100644 --- a/.github/workflows/on-trigger.yml +++ b/.github/workflows/on-trigger.yml @@ -21,11 +21,13 @@ on: - ".github/workflows/reusable-build-test-config.yml" - ".github/workflows/reusable-build-test.yml" - ".github/workflows/reusable-clang-tidy.yml" + - ".github/workflows/reusable-package.yml" - ".github/workflows/reusable-strategy-matrix.yml" - ".github/workflows/reusable-test.yml" - ".github/workflows/reusable-upload-recipe.yml" - ".clang-tidy" - ".codecov.yml" + - "cfg/**" - "cmake/**" - "conan/**" - "external/**" @@ -35,6 +37,9 @@ on: - "CMakeLists.txt" - "conanfile.py" - "conan.lock" + - "LICENSE.md" + - "package/**" + - "README.md" # Run at 06:32 UTC on every day of the week from Monday through Friday. This # will force all dependencies to be rebuilt, which is useful to verify that @@ -95,3 +100,7 @@ jobs: secrets: remote_username: ${{ secrets.CONAN_REMOTE_USERNAME }} remote_password: ${{ secrets.CONAN_REMOTE_PASSWORD }} + + package: + needs: build-test + uses: ./.github/workflows/reusable-package.yml diff --git a/.github/workflows/reusable-package.yml b/.github/workflows/reusable-package.yml new file mode 100644 index 0000000000..ad73cd8733 --- /dev/null +++ b/.github/workflows/reusable-package.yml @@ -0,0 +1,99 @@ +# 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. +name: Package + +on: + workflow_call: + inputs: + pkg_release: + description: "Package release number. Increment when repackaging the same executable." + required: false + type: string + default: "1" + +defaults: + run: + shell: bash + +env: + BUILD_DIR: build + +jobs: + generate-matrix: + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.generate.outputs.matrix }} + steps: + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Set up Python + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + 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}" + + generate-version: + runs-on: ubuntu-latest + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + sparse-checkout: | + .github/actions/generate-version + src/libxrpl/protocol/BuildInfo.cpp + - name: Generate version + id: version + uses: ./.github/actions/generate-version + + package: + needs: [generate-matrix, generate-version] + strategy: + fail-fast: false + matrix: ${{ fromJson(needs.generate-matrix.outputs.matrix) }} + name: "${{ matrix.artifact_name }}" + 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) }} + timeout-minutes: 30 + + steps: + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Download pre-built binary + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: ${{ matrix.artifact_name }} + path: ${{ env.BUILD_DIR }} + + - name: Make binary executable + run: chmod +x "${BUILD_DIR}/xrpld" + + - name: Build package + env: + PKG_VERSION: ${{ needs.generate-version.outputs.version }} + PKG_RELEASE: ${{ inputs.pkg_release }} + run: ./package/build_pkg.sh + + - name: Upload package artifact + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + if: ${{ github.event.repository.visibility == 'public' }} + with: + name: ${{ matrix.artifact_name }}-pkg-${{ needs.generate-version.outputs.version }} + path: | + ${{ env.BUILD_DIR }}/debbuild/*.deb + ${{ env.BUILD_DIR }}/debbuild/*.ddeb + ${{ env.BUILD_DIR }}/rpmbuild/RPMS/**/*.rpm + if-no-files-found: error diff --git a/CMakeLists.txt b/CMakeLists.txt index 80ff8fec13..d315a5dcec 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -134,6 +134,7 @@ endif() include(XrplCore) include(XrplProtocolAutogen) include(XrplInstall) +include(XrplPackaging) include(XrplValidatorKeys) if(tests) diff --git a/cfg/validators-example.txt b/cfg/validators-example.txt index 384db924f4..d690a67501 100644 --- a/cfg/validators-example.txt +++ b/cfg/validators-example.txt @@ -28,7 +28,7 @@ # https://vl.ripple.com # https://unl.xrplf.org # http://127.0.0.1:8000 -# file:///etc/opt/xrpld/vl.txt +# file:///etc/xrpld/vl.txt # # [validator_list_keys] # diff --git a/cmake/XrplPackaging.cmake b/cmake/XrplPackaging.cmake new file mode 100644 index 0000000000..fe885c200c --- /dev/null +++ b/cmake/XrplPackaging.cmake @@ -0,0 +1,44 @@ +#[===================================================================[ + Linux packaging support: 'package' target. + + The packaging script (package/build_pkg.sh) installs to FHS-standard + paths (/usr/bin, /etc/xrpld, etc.) regardless of CMAKE_INSTALL_PREFIX, + so no prefix guard is needed here. +#]===================================================================] +if(NOT is_linux) + message(STATUS "Packaging not supported on non-Linux hosts") + return() +endif() + +if(NOT DEFINED pkg_release) + set(pkg_release 1) +endif() + +find_program(RPMBUILD_EXECUTABLE rpmbuild) +find_program(DPKG_BUILDPACKAGE_EXECUTABLE dpkg-buildpackage) + +if(NOT (RPMBUILD_EXECUTABLE OR DPKG_BUILDPACKAGE_EXECUTABLE)) + message( + STATUS + "Neither rpmbuild nor dpkg-buildpackage found; 'package' target not available" + ) + return() +endif() + +set(package_env + SRC_DIR=${CMAKE_SOURCE_DIR} + BUILD_DIR=${CMAKE_BINARY_DIR} + PKG_VERSION=${xrpld_version} + PKG_RELEASE=${pkg_release} +) + +add_custom_target( + package + COMMAND + ${CMAKE_COMMAND} -E env ${package_env} + ${CMAKE_SOURCE_DIR}/package/build_pkg.sh + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + DEPENDS xrpld + COMMENT "Building Linux package (deb/rpm inferred from host tooling)" + VERBATIM +) diff --git a/cspell.config.yaml b/cspell.config.yaml index bc56ef5d79..275df41f58 100644 --- a/cspell.config.yaml +++ b/cspell.config.yaml @@ -99,12 +99,15 @@ words: - desync - desynced - determ + - disablerepo - distro - doxyfile - dxrpl - enabled + - enablerepo - endmacro - exceptioned + - EXPECT_STREQ - Falco - fcontext - finalizers @@ -162,6 +165,7 @@ words: - Merkle - Metafuncton - misprediction + - missingok - mptbalance - MPTDEX - mptflags @@ -193,7 +197,9 @@ words: - NOLINT - NOLINTNEXTLINE - nonxrp + - noreplace - noripple + - notifempty - nudb - nullptr - nunl @@ -213,6 +219,7 @@ words: - preauthorize - preauthorizes - preclaim + - preun - protobuf - protos - ptrs @@ -247,12 +254,14 @@ words: - sfields - shamap - shamapitem + - shlibs - sidechain - SIGGOOD - sle - sles - soci - socidb + - SRPMS - sslws - statsd - STATSDCOLLECTOR @@ -280,8 +289,8 @@ words: - txn - txns - txs - - UBSAN - ubsan + - UBSAN - umant - unacquired - unambiguity @@ -318,7 +327,6 @@ words: - xbridge - xchain - ximinez - - EXPECT_STREQ - XMACRO - xrpkuwait - xrpl diff --git a/package/README.md b/package/README.md new file mode 100644 index 0000000000..2089e32e64 --- /dev/null +++ b/package/README.md @@ -0,0 +1,175 @@ +# Linux Packaging + +This directory contains all files needed to build RPM and Debian packages for `xrpld`. + +## Directory layout + +``` +package/ + build_pkg.sh Staging and build script (called by CMake targets and CI) + rpm/ + xrpld.spec RPM spec (xrpld_version/pkg_release passed via rpmbuild --define) + debian/ Debian control files (control, rules, install, links, conffiles, ...) + shared/ + xrpld.service systemd unit file (used by both RPM and DEB) + 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 + +Packaging targets and their container images are declared in +[`.github/scripts/strategy-matrix/linux.json`](../.github/scripts/strategy-matrix/linux.json) +via a `"package": true` field on specific os entries. Today only +`linux/amd64` is emitted; the architecture is hardcoded in `generate.py` +and the workflow runner. The package format +(deb or rpm) is inferred at build time from the container's package manager +(`apt-get` -> deb, `dnf`/`yum` -> rpm). The image tag is composed as +`ghcr.io/xrplf/ci/{distro}-{version}:{compiler}-{cver}-sha-{image_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` | + +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 +``` + +## Building packages + +### Via CI + +Caller workflows (`on-pr.yml`, `on-tag.yml`, `on-trigger.yml`) call +`reusable-strategy-matrix.yml` with `mode: packaging` to generate the matrix of +`{artifact_name, os}` entries, then fan out to +`reusable-package.yml` per entry. That workflow downloads the pre-built `xrpld` +binary artifact, detects the package format from the container, and calls +`build_pkg.sh` directly — no CMake configure or build step is needed inside +the packaging job. + +### Locally (mirrors CI) + +With an `xrpld` binary already built at `build/xrpld`, run the packaging step +inside the same container CI uses. The image tag is derived from `linux.json` +so you don't need to hardcode a SHA. + +```bash +# From the repo root. Pick any image flagged with `"package": true` in +# linux.json; the package format is inferred from the container's package +# manager. Example for the rpm-producing image: +IMAGE=$(jq -r ' + .os | map(select(.package == true))[0] | + "ghcr.io/xrplf/ci/\(.distro_name)-\(.distro_version):\(.compiler_name)-\(.compiler_version)-sha-\(.image_sha)" +' .github/scripts/strategy-matrix/linux.json) + +VERSION=2.4.0-local +PKG_RELEASE=1 + +docker run --rm \ + -v "$(pwd):/src" \ + -w /src \ + "$IMAGE" \ + ./package/build_pkg.sh --pkg-version "$VERSION" --pkg-release "$PKG_RELEASE" + +# Output: +# build/debbuild/*.deb (DEB + dbgsym .ddeb) +# build/rpmbuild/RPMS/x86_64/*.rpm +``` + +### Via CMake (host-side target) + +If you run CMake configure on a host that has `rpmbuild` or `dpkg-buildpackage` +installed natively, you can use the CMake target directly — no container +needed, but the host toolchain replaces the pinned CI image: + +```bash +cmake \ + -Dxrpld=ON \ + -Dxrpld_version=2.4.0-local \ + -Dtests=OFF \ + .. + +cmake --build . --target package # deb on Debian/Ubuntu, rpm on RHEL +``` + +The `cmake/XrplPackaging.cmake` module defines the target only if at least one +of `rpmbuild` / `dpkg-buildpackage` is present; `build_pkg.sh` then infers the +package format from the host's package manager. The packaging script installs +to FHS-standard paths (`/usr/bin`, `/etc/xrpld`, etc.) regardless of +`CMAKE_INSTALL_PREFIX`. + +## How `build_pkg.sh` works + +`build_pkg.sh` accepts long-form flags, each of which can also be set via an +environment variable. Flags override env vars; env vars override the built-in +defaults. Run `./package/build_pkg.sh --help` for the same table: + +| Flag | Env var | Default | Purpose | +| -------------------------- | ------------------- | ----------------------------- | ----------------------------------- | +| `--src-dir DIR` | `SRC_DIR` | `$PWD` | repo root | +| `--build-dir DIR` | `BUILD_DIR` | `$PWD/build` | directory holding pre-built `xrpld` | +| `--pkg-version STR` | `PKG_VERSION` | parsed from `xrpld --version` | version string, e.g. `3.2.0-b1` | +| `--pkg-release N` | `PKG_RELEASE` | `1` | package release number | +| `--source-date-epoch SECS` | `SOURCE_DATE_EPOCH` | latest git commit ctime | reproducibility timestamp | + +The package format (`deb` or `rpm`) is inferred from the host's package +manager (`apt-get` -> deb, `dnf`/`yum` -> rpm). Hosts without one of those +fail early. + +Flags are for explicit invocation; environment variables are intended for +CMake/systemd/CI integration. The CI workflow and the CMake `package` target +both invoke `build_pkg.sh` with no flags, configuring it entirely via env +(see `cmake/XrplPackaging.cmake`). + +It resolves `SRC_DIR` and `BUILD_DIR` to absolute paths, then calls +`stage_common()` to copy the binary, config files, and shared support files +into the staging area, and invokes the platform build tool. + +### RPM + +1. Creates the standard `rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}` tree inside the build directory. +2. Copies `xrpld.spec` and all source files (binary, configs, service files) into `SOURCES/`. +3. Runs `rpmbuild -bb --define "xrpld_version ..." --define "pkg_release ..."`. The spec uses manual `install` commands to place files. +4. Output: `rpmbuild/RPMS/x86_64/xrpld-*.rpm` + +### DEB + +1. Creates a staging source tree at `debbuild/source/` inside the build directory. +2. Stages the binary, configs, `README.md`, and `LICENSE.md`. +3. Copies `package/debian/` control files into `debbuild/source/debian/`. +4. Copies shared service/sysusers/tmpfiles into `debian/` where `dh_installsystemd`, `dh_installsysusers`, and `dh_installtmpfiles` pick them up automatically. +5. Generates a minimal `debian/changelog` (pre-release versions use `~` instead of `-`). +6. Runs `dpkg-buildpackage -b --no-sign`. `debian/rules` uses manual `install` commands. +7. Output: `debbuild/*.deb` and `debbuild/*.ddeb` (dbgsym package) + +## Post-build verification + +```bash +# DEB +dpkg-deb -c debbuild/*.deb | grep -E 'systemd|sysusers|tmpfiles' +lintian -I debbuild/*.deb + +# RPM +rpm -qlp rpmbuild/RPMS/x86_64/*.rpm +``` + +## Reproducibility + +The following environment variables improve build reproducibility. They are not +set automatically by `build_pkg.sh`; set them manually if needed: + +```bash +export SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct) +export TZ=UTC +export LC_ALL=C.UTF-8 +export GZIP=-n +export DEB_BUILD_OPTIONS="noautodbgsym reproducible=+fixfilepath" +``` diff --git a/package/build_pkg.sh b/package/build_pkg.sh new file mode 100755 index 0000000000..c834951493 --- /dev/null +++ b/package/build_pkg.sh @@ -0,0 +1,192 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Build an RPM or Debian package from a pre-built xrpld binary. +# +# Flags override env vars; env vars override defaults. Env vars are intended +# for CMake/systemd/CI integration; flags are for explicit invocation. + +usage() { + cat <<'EOF' +Usage: build_pkg.sh [options] + +Options (each can also be set via the env var shown): + --src-dir DIR repo root [SRC_DIR; default: $PWD] + --build-dir DIR directory holding xrpld [BUILD_DIR; default: $PWD/build] + --pkg-version STR version, e.g. 3.2.0-b1 [PKG_VERSION; default: parsed from xrpld --version] + --pkg-release N package release number [PKG_RELEASE; default: 1] + --source-date-epoch SECS reproducibility timestamp [SOURCE_DATE_EPOCH; default: latest git commit ctime] + -h, --help show this help and exit +EOF +} + +need_arg() { + if [[ $# -lt 2 || "$2" == --* ]]; then + echo "Missing value for $1" >&2 + exit 2 + fi +} + +# Seed from env. CLI parsing below overrides these directly. +SRC_DIR="${SRC_DIR:-}" +BUILD_DIR="${BUILD_DIR:-}" +PKG_VERSION="${PKG_VERSION:-}" +PKG_RELEASE="${PKG_RELEASE:-}" +SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-}" + +while [[ $# -gt 0 ]]; do + case "$1" in + --src-dir) need_arg "$@"; SRC_DIR="$2"; shift 2 ;; + --build-dir) need_arg "$@"; BUILD_DIR="$2"; shift 2 ;; + --pkg-version) need_arg "$@"; PKG_VERSION="$2"; shift 2 ;; + --pkg-release) need_arg "$@"; PKG_RELEASE="$2"; shift 2 ;; + --source-date-epoch) need_arg "$@"; SOURCE_DATE_EPOCH="$2"; shift 2 ;; + -h|--help) usage; exit 0 ;; + *) + echo "Unknown argument: $1" >&2 + usage >&2 + exit 2 + ;; + esac +done + +SRC_DIR="$(cd "${SRC_DIR:-${PWD}}" && pwd)" +BUILD_DIR="$(cd "${BUILD_DIR:-${PWD}/build}" && pwd)" +PKG_RELEASE="${PKG_RELEASE:-1}" + +if [[ -z "${PKG_VERSION}" ]]; then + PKG_VERSION="$("${BUILD_DIR}/xrpld" --version | awk 'NR==1 {print $3; exit}')" +fi + +if [[ -z "${PKG_VERSION}" ]]; then + echo "PKG_VERSION is empty (not provided and could not be derived)." >&2 + exit 1 +fi + +VERSION="${PKG_VERSION}" + +if command -v apt-get >/dev/null 2>&1; then + pkg_type=deb +elif command -v dnf >/dev/null 2>&1 || command -v yum >/dev/null 2>&1; then + pkg_type=rpm +else + echo "Cannot infer pkg_type: no apt-get, dnf, or yum on PATH." >&2 + exit 1 +fi + +if [[ -z "${SOURCE_DATE_EPOCH}" ]]; then + if git -C "$SRC_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then + SOURCE_DATE_EPOCH="$(git -C "$SRC_DIR" log -1 --format=%ct)" + else + SOURCE_DATE_EPOCH="$(date +%s)" + fi +fi + +export SOURCE_DATE_EPOCH +CHANGELOG_DATE="$(date -u -R -d "@$SOURCE_DATE_EPOCH")" + +# Split VERSION at the first '-' into base and optional pre-release suffix. +# Examples: "3.2.0" -> ("3.2.0", ""); "3.2.0-b1" -> ("3.2.0", "b1"). +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. +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 + exit 1 +fi + +SHARED="${SRC_DIR}/package/shared" +DEBIAN_DIR="${SRC_DIR}/package/debian" + +# Stage files that both packaging systems consume using the same filenames. +stage_common() { + local dest="$1" + mkdir -p "${dest}" + + cp "${BUILD_DIR}/xrpld" "${dest}/xrpld" + cp "${SRC_DIR}/cfg/xrpld-example.cfg" "${dest}/xrpld.cfg" + cp "${SRC_DIR}/cfg/validators-example.txt" "${dest}/validators.txt" + cp "${SRC_DIR}/LICENSE.md" "${dest}/LICENSE.md" + cp "${SRC_DIR}/README.md" "${dest}/README.md" + + cp "${SHARED}/xrpld.service" "${dest}/xrpld.service" + 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" +} + +build_rpm() { + local topdir="${BUILD_DIR}/rpmbuild" + rm -rf "${topdir}" + mkdir -p "${topdir}"/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS} + + 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-. + local rpm_release="${PKG_RELEASE}" + [[ -n "${VER_SUFFIX}" ]] && rpm_release="0.${VER_SUFFIX}.${PKG_RELEASE}" + + set -x + rpmbuild -bb \ + --define "_topdir ${topdir}" \ + --define "xrpld_version ${VER_BASE}" \ + --define "xrpld_release ${rpm_release}" \ + "${topdir}/SPECS/xrpld.spec" +} + +build_deb() { + local staging="${BUILD_DIR}/debbuild/source" + rm -rf "${staging}" + mkdir -p "${staging}" + + 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}" + + # Derive release channel from the version suffix: + # (none) -> stable (tagged release) + # b0 -> develop (develop-branch build) + # b, rc -> unstable (pre-release) + local deb_distribution + case "${VER_SUFFIX}" in + "") deb_distribution="stable" ;; + b0) deb_distribution="develop" ;; + *) deb_distribution="unstable" ;; + esac + + cat > "${staging}/debian/changelog" < ${CHANGELOG_DATE} +EOF + + chmod +x "${staging}/debian/rules" + + set -x + ( cd "${staging}" && dpkg-buildpackage -b --no-sign -d ) +} + +"build_${pkg_type}" diff --git a/package/debian/control b/package/debian/control new file mode 100644 index 0000000000..45d2acbbea --- /dev/null +++ b/package/debian/control @@ -0,0 +1,23 @@ +Source: xrpld +Section: net +Priority: optional +Maintainer: XRPL Foundation +Rules-Requires-Root: no +Build-Depends: + debhelper-compat (= 13) +Standards-Version: 4.7.0 +Homepage: https://github.com/XRPLF/rippled +Vcs-Git: https://github.com/XRPLF/rippled.git +Vcs-Browser: https://github.com/XRPLF/rippled + +Package: xrpld +Section: net +Priority: optional +Architecture: any +Depends: + ${shlibs:Depends}, + ${misc:Depends} +Description: XRP Ledger daemon + Reference implementation of the XRP Ledger protocol. + Participates in the peer-to-peer network, processes transactions, + and maintains a local ledger copy. diff --git a/package/debian/copyright b/package/debian/copyright new file mode 100644 index 0000000000..ddaa719e3a --- /dev/null +++ b/package/debian/copyright @@ -0,0 +1,18 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: rippled +Source: https://github.com/XRPLF/rippled + +Files: * +Copyright: 2011-present, the XRP Ledger developers +License: ISC + Permission to use, copy, modify, and distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + . + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/package/debian/rules b/package/debian/rules new file mode 100644 index 0000000000..0fae101358 --- /dev/null +++ b/package/debian/rules @@ -0,0 +1,27 @@ +#!/usr/bin/make -f + +export DH_VERBOSE = 1 + +%: + dh $@ + +override_dh_auto_configure override_dh_auto_build override_dh_auto_test: + @: + +override_dh_installsystemd: + dh_installsystemd --no-start xrpld.service + dh_installsystemd --name=update-xrpld --no-start update-xrpld.service update-xrpld.timer + +execute_before_dh_installtmpfiles: + dh_installsysusers + +override_dh_installsysusers: + +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/source/format b/package/debian/source/format new file mode 100644 index 0000000000..163aaf8d82 --- /dev/null +++ b/package/debian/source/format @@ -0,0 +1 @@ +3.0 (quilt) diff --git a/package/debian/xrpld.docs b/package/debian/xrpld.docs new file mode 100644 index 0000000000..1217b6db43 --- /dev/null +++ b/package/debian/xrpld.docs @@ -0,0 +1,2 @@ +README.md +LICENSE.md diff --git a/package/debian/xrpld.links b/package/debian/xrpld.links new file mode 100644 index 0000000000..10d34f5b8c --- /dev/null +++ b/package/debian/xrpld.links @@ -0,0 +1,2 @@ +# Legacy compat symlinks (remove next major release) +usr/bin/xrpld usr/local/bin/rippled diff --git a/package/rpm/xrpld.spec b/package/rpm/xrpld.spec new file mode 100644 index 0000000000..4933c724f7 --- /dev/null +++ b/package/rpm/xrpld.spec @@ -0,0 +1,100 @@ +Name: xrpld +Version: %{xrpld_version} +Release: %{xrpld_release}%{?dist} +Summary: XRP Ledger daemon + +License: ISC +URL: https://github.com/XRPLF/rippled + +ExclusiveArch: x86_64 aarch64 +BuildRequires: systemd-rpm-macros + +%undefine _debugsource_packages +%debug_package + +%build_mtime_policy clamp_to_source_date_epoch + +%{?systemd_requires} +%{?sysusers_requires_compat} + +%description +xrpld is the reference implementation of the XRP Ledger protocol. It +participates in the peer-to-peer XRP Ledger network, processes +transactions, and maintains the ledger database. + +%prep +: + +%build +: + +%install +install -Dm0755 %{_sourcedir}/xrpld %{buildroot}%{_bindir}/%{name} +install -Dm0644 %{_sourcedir}/xrpld.cfg %{buildroot}%{_sysconfdir}/%{name}/xrpld.cfg +install -Dm0644 %{_sourcedir}/validators.txt %{buildroot}%{_sysconfdir}/%{name}/validators.txt + +# 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 + +# 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 + +# Legacy compatibility for pre-FHS package layouts. +# TODO: remove after rippled fully deprecated. +install -d %{buildroot}/usr/local/bin +ln -s %{_bindir}/%{name} %{buildroot}/usr/local/bin/rippled + +%pre +%sysusers_create_package %{name} %{_sourcedir}/xrpld.sysusers + +%post +systemd-tmpfiles --create %{_tmpfilesdir}/xrpld.conf || : +%systemd_post xrpld.service update-xrpld.timer + +%preun +%systemd_preun xrpld.service update-xrpld.timer + +%postun +%systemd_postun_with_restart xrpld.service + +%files +%license %{_docdir}/%{name}/LICENSE.md +%doc %{_docdir}/%{name}/README.md + +%dir %{_sysconfdir}/%{name} +%dir %{_libexecdir}/%{name} + +%{_bindir}/%{name} + +%config(noreplace) %{_sysconfdir}/%{name}/xrpld.cfg +%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} + + +# Legacy compatibility for pre-FHS package layouts. +# TODO: remove after rippled fully deprecated. +/usr/local/bin/rippled diff --git a/package/shared/50-xrpld.preset b/package/shared/50-xrpld.preset new file mode 100644 index 0000000000..6264e00131 --- /dev/null +++ b/package/shared/50-xrpld.preset @@ -0,0 +1,4 @@ +# /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 new file mode 100755 index 0000000000..86be33118b --- /dev/null +++ b/package/shared/update-xrpld @@ -0,0 +1,152 @@ +#!/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 new file mode 100644 index 0000000000..a964ca5482 --- /dev/null +++ b/package/shared/update-xrpld.service @@ -0,0 +1,16 @@ +[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 new file mode 100644 index 0000000000..21dabf1400 --- /dev/null +++ b/package/shared/update-xrpld.timer @@ -0,0 +1,10 @@ +[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.logrotate b/package/shared/xrpld.logrotate new file mode 100644 index 0000000000..0ae2b7783b --- /dev/null +++ b/package/shared/xrpld.logrotate @@ -0,0 +1,19 @@ +/var/log/xrpld/*.log { + daily + minsize 200M + rotate 7 + nocreate + missingok + notifempty + compress + compresscmd /usr/bin/gzip + compressext .gz + postrotate + # Only signal the daemon if it's actually running; otherwise the RPC + # call returns a transport error and logrotate marks the rotation as + # failed, generating recurring errors on stopped nodes. + if systemctl is-active --quiet xrpld; then + /usr/bin/xrpld --conf /etc/xrpld/xrpld.cfg logrotate + fi + endscript +} diff --git a/package/shared/xrpld.service b/package/shared/xrpld.service new file mode 100644 index 0000000000..72b6cc9938 --- /dev/null +++ b/package/shared/xrpld.service @@ -0,0 +1,22 @@ +[Unit] +Description=XRP Ledger Daemon +After=network-online.target +Wants=network-online.target +StartLimitIntervalSec=300 +StartLimitBurst=5 + +[Service] +Type=simple +ExecStart=/usr/bin/xrpld --net --silent --conf /etc/xrpld/xrpld.cfg +Restart=always +RestartSec=5s +NoNewPrivileges=true +ProtectSystem=full +ProtectHome=true +PrivateTmp=true +User=xrpld +Group=xrpld +LimitNOFILE=65536 + +[Install] +WantedBy=multi-user.target diff --git a/package/shared/xrpld.sysusers b/package/shared/xrpld.sysusers new file mode 100644 index 0000000000..4547ac6f3d --- /dev/null +++ b/package/shared/xrpld.sysusers @@ -0,0 +1 @@ +u xrpld - "XRP Ledger daemon" /var/lib/xrpld /sbin/nologin diff --git a/package/shared/xrpld.tmpfiles b/package/shared/xrpld.tmpfiles new file mode 100644 index 0000000000..ff9b4d95c2 --- /dev/null +++ b/package/shared/xrpld.tmpfiles @@ -0,0 +1,2 @@ +d /var/lib/xrpld 0750 xrpld xrpld - +d /var/log/xrpld 0750 xrpld xrpld - diff --git a/src/test/app/ValidatorSite_test.cpp b/src/test/app/ValidatorSite_test.cpp index b10667c467..f7f805faa2 100644 --- a/src/test/app/ValidatorSite_test.cpp +++ b/src/test/app/ValidatorSite_test.cpp @@ -78,7 +78,7 @@ private: "http://207.261.33.37:8080/validators", "https://ripple.com/validators", "https://ripple.com:443/validators", - "file:///etc/opt/xrpld/validators.txt", + "file:///etc/xrpld/validators.txt", "file:///C:/Lib/validators.txt" #if !_MSC_VER , diff --git a/src/xrpld/core/detail/Config.cpp b/src/xrpld/core/detail/Config.cpp index 7830ad9c56..d8789795c0 100644 --- a/src/xrpld/core/detail/Config.cpp +++ b/src/xrpld/core/detail/Config.cpp @@ -372,8 +372,8 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand } // As a last resort, check the system config directory. - dataDir = "/var/opt/" + systemName(); - CONFIG_DIR = "/etc/opt/" + systemName(); + dataDir = "/var/lib/" + systemName(); + CONFIG_DIR = "/etc/" + systemName(); CONFIG_FILE_ = CONFIG_DIR / kConfigFileName; if (boost::filesystem::exists(CONFIG_FILE_)) break; From ad7232cbc52ce472d22c86bf5da8a918de4c2add Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Mon, 18 May 2026 06:56:54 -0400 Subject: [PATCH 04/17] refactor: Rename `account_` to `accountID_` (#7284) --- include/xrpl/tx/Transactor.h | 2 +- include/xrpl/tx/paths/Offer.h | 8 +-- include/xrpl/tx/transactors/dex/AMMContext.h | 7 +-- src/libxrpl/tx/Transactor.cpp | 12 ++--- .../tx/transactors/account/AccountDelete.cpp | 10 ++-- .../tx/transactors/account/AccountSet.cpp | 6 +-- .../tx/transactors/account/SetRegularKey.cpp | 4 +- .../tx/transactors/account/SignerListSet.cpp | 18 +++---- .../tx/transactors/bridge/XChainBridge.cpp | 6 ++- .../tx/transactors/check/CheckCash.cpp | 28 +++++----- .../tx/transactors/check/CheckCreate.cpp | 12 ++--- .../credentials/CredentialAccept.cpp | 4 +- .../credentials/CredentialCreate.cpp | 12 ++--- .../credentials/CredentialDelete.cpp | 6 +-- .../tx/transactors/delegate/DelegateSet.cpp | 10 ++-- src/libxrpl/tx/transactors/dex/AMMBid.cpp | 2 +- src/libxrpl/tx/transactors/dex/AMMCreate.cpp | 2 +- src/libxrpl/tx/transactors/dex/AMMDeposit.cpp | 21 +++++--- src/libxrpl/tx/transactors/dex/AMMVote.cpp | 2 +- .../tx/transactors/dex/AMMWithdraw.cpp | 8 +-- .../tx/transactors/dex/OfferCancel.cpp | 4 +- .../tx/transactors/dex/OfferCreate.cpp | 22 ++++---- src/libxrpl/tx/transactors/did/DIDDelete.cpp | 2 +- src/libxrpl/tx/transactors/did/DIDSet.cpp | 6 +-- .../tx/transactors/escrow/EscrowCancel.cpp | 2 +- .../tx/transactors/escrow/EscrowCreate.cpp | 14 ++--- .../tx/transactors/escrow/EscrowFinish.cpp | 5 +- .../lending/LoanBrokerCoverDeposit.cpp | 3 +- .../lending/LoanBrokerCoverWithdraw.cpp | 4 +- .../transactors/lending/LoanBrokerDelete.cpp | 6 +-- .../tx/transactors/lending/LoanBrokerSet.cpp | 8 +-- .../tx/transactors/lending/LoanPay.cpp | 51 ++++++++++--------- .../tx/transactors/lending/LoanSet.cpp | 8 +-- .../tx/transactors/nft/NFTokenAcceptOffer.cpp | 6 +-- .../tx/transactors/nft/NFTokenMint.cpp | 8 +-- .../tx/transactors/oracle/OracleDelete.cpp | 4 +- .../tx/transactors/oracle/OracleSet.cpp | 4 +- .../tx/transactors/payment/DepositPreauth.cpp | 24 ++++----- .../tx/transactors/payment/Payment.cpp | 28 +++++----- .../PermissionedDomainDelete.cpp | 4 +- .../PermissionedDomainSet.cpp | 8 +-- src/libxrpl/tx/transactors/system/Change.cpp | 2 +- .../tx/transactors/system/TicketCreate.cpp | 10 ++-- .../tx/transactors/token/MPTokenAuthorize.cpp | 2 +- .../token/MPTokenIssuanceCreate.cpp | 2 +- .../token/MPTokenIssuanceDestroy.cpp | 6 +-- src/libxrpl/tx/transactors/token/TrustSet.cpp | 16 +++--- .../tx/transactors/vault/VaultClawback.cpp | 6 +-- .../tx/transactors/vault/VaultCreate.cpp | 12 ++--- .../tx/transactors/vault/VaultDelete.cpp | 8 +-- .../tx/transactors/vault/VaultDeposit.cpp | 24 ++++----- .../tx/transactors/vault/VaultWithdraw.cpp | 18 +++---- 52 files changed, 259 insertions(+), 248 deletions(-) diff --git a/include/xrpl/tx/Transactor.h b/include/xrpl/tx/Transactor.h index bee2e2942c..61d943c4d5 100644 --- a/include/xrpl/tx/Transactor.h +++ b/include/xrpl/tx/Transactor.h @@ -115,7 +115,7 @@ protected: beast::WrappedSink sink_; beast::Journal const j_; - AccountID const account_; + AccountID const accountID_; XRPAmount preFeeBalance_{}; // Balance before fees. public: diff --git a/include/xrpl/tx/paths/Offer.h b/include/xrpl/tx/paths/Offer.h index bbed179bc7..2dab5bcebf 100644 --- a/include/xrpl/tx/paths/Offer.h +++ b/include/xrpl/tx/paths/Offer.h @@ -21,7 +21,7 @@ class TOffer private: SLE::pointer entry_; Quality quality_{}; - AccountID account_; + AccountID accountID_; Asset assetIn_; Asset assetOut_; @@ -53,7 +53,7 @@ public: [[nodiscard]] AccountID const& owner() const { - return account_; + return accountID_; } /** Returns the in and out amounts. @@ -122,7 +122,7 @@ public: isFunded() const { // Offer owner is issuer; they have unlimited funds if IOU - return account_ == assetOut_.getIssuer() && assetOut_.holds(); + return accountID_ == assetOut_.getIssuer() && assetOut_.holds(); } static std::pair @@ -159,7 +159,7 @@ public: template TOffer::TOffer(SLE::pointer entry, Quality quality) - : entry_(std::move(entry)), quality_(quality), account_(entry_->getAccountID(sfAccount)) + : entry_(std::move(entry)), quality_(quality), accountID_(entry_->getAccountID(sfAccount)) { auto const tp = entry_->getFieldAmount(sfTakerPays); auto const tg = entry_->getFieldAmount(sfTakerGets); diff --git a/include/xrpl/tx/transactors/dex/AMMContext.h b/include/xrpl/tx/transactors/dex/AMMContext.h index 92de3f7b97..65954044be 100644 --- a/include/xrpl/tx/transactors/dex/AMMContext.h +++ b/include/xrpl/tx/transactors/dex/AMMContext.h @@ -22,7 +22,7 @@ public: private: // Tx account owner is required to get the AMM trading fee in BookStep - AccountID account_; + AccountID accountID_; // true if payment has multiple paths bool multiPath_{false}; // Is true if AMM offer is consumed during a payment engine iteration. @@ -31,7 +31,8 @@ private: std::uint16_t ammIters_{0}; public: - AMMContext(AccountID const& account, bool multiPath) : account_(account), multiPath_(multiPath) + AMMContext(AccountID const& account, bool multiPath) + : accountID_(account), multiPath_(multiPath) { } ~AMMContext() = default; @@ -80,7 +81,7 @@ public: [[nodiscard]] AccountID account() const { - return account_; + return accountID_; } /** Strand execution may fail. Reset the flag at the start diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index 995013a3ca..97f2cabff2 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -262,7 +262,7 @@ Transactor::Transactor(ApplyContext& ctx) : ctx_(ctx) , sink_(ctx.journal, toShortString(ctx.tx.getTransactionID()) + " ") , j_(sink_) - , account_(ctx.tx.getAccountID(sfAccount)) + , accountID_(ctx.tx.getAccountID(sfAccount)) { } @@ -431,7 +431,7 @@ Transactor::payFee() // Deduct the fee, so it's not available during the transaction. // Will only write the account back if the transaction succeeds. sle->setFieldAmount(sfBalance, sle->getFieldAmount(sfBalance) - feePaid); - if (feePayer != account_) + if (feePayer != accountID_) view().update(sle); // done in `apply()` for the account // VFALCO Should we call view().rawDestroyXRP() here as well? @@ -544,7 +544,7 @@ Transactor::consumeSeqProxy(SLE::pointer const& sleAccount) sleAccount->setFieldU32(sfSequence, seqProx.value() + 1); return tesSUCCESS; } - return ticketDelete(view(), account_, getTicketIndex(account_, seqProx), j_); + return ticketDelete(view(), accountID_, getTicketIndex(accountID_, seqProx), j_); } // Remove a single Ticket from the ledger. @@ -617,7 +617,7 @@ Transactor::ticketDelete( void Transactor::preCompute() { - XRPL_ASSERT(account_ != beast::kZero, "xrpl::Transactor::preCompute : nonzero account"); + XRPL_ASSERT(accountID_ != beast::kZero, "xrpl::Transactor::preCompute : nonzero account"); } TER @@ -627,12 +627,12 @@ Transactor::apply() // If the transactor requires a valid account and the transaction doesn't // list one, preflight will have already a flagged a failure. - auto const sle = view().peek(keylet::account(account_)); + auto const sle = view().peek(keylet::account(accountID_)); // sle must exist except for transactions // that allow zero account. XRPL_ASSERT( - sle != nullptr || account_ == beast::kZero, + sle != nullptr || accountID_ == beast::kZero, "xrpl::Transactor::apply : non-null SLE or zero account"); if (sle) diff --git a/src/libxrpl/tx/transactors/account/AccountDelete.cpp b/src/libxrpl/tx/transactors/account/AccountDelete.cpp index 809888e1f7..c0e8fe05c6 100644 --- a/src/libxrpl/tx/transactors/account/AccountDelete.cpp +++ b/src/libxrpl/tx/transactors/account/AccountDelete.cpp @@ -344,7 +344,7 @@ AccountDelete::preclaim(PreclaimContext const& ctx) TER AccountDelete::doApply() { - auto src = view().peek(keylet::account(account_)); + auto src = view().peek(keylet::account(accountID_)); XRPL_ASSERT(src, "xrpl::AccountDelete::doApply : non-null source account"); auto const dstID = ctx_.tx[sfDestination]; @@ -357,12 +357,12 @@ AccountDelete::doApply() if (ctx_.tx.isFieldPresent(sfCredentialIDs)) { if (auto err = - verifyDepositPreauth(ctx_.tx, ctx_.view(), account_, dstID, dst, ctx_.journal); + verifyDepositPreauth(ctx_.tx, ctx_.view(), accountID_, dstID, dst, ctx_.journal); !isTesSuccess(err)) return err; } - Keylet const ownerDirKeylet{keylet::ownerDir(account_)}; + Keylet const ownerDirKeylet{keylet::ownerDir(accountID_)}; auto const ter = cleanupOnAccountDelete( view(), ownerDirKeylet, @@ -371,7 +371,7 @@ AccountDelete::doApply() std::shared_ptr& sleItem) -> std::pair { if (auto deleter = nonObligationDeleter(nodeType)) { - TER const result{deleter(ctx_.registry, view(), account_, dirEntry, sleItem, j_)}; + TER const result{deleter(ctx_.registry, view(), accountID_, dirEntry, sleItem, j_)}; return {result, SkipEntry::No}; } @@ -402,7 +402,7 @@ AccountDelete::doApply() // delete it. if (view().exists(ownerDirKeylet) && !view().emptyDirDelete(ownerDirKeylet)) { - JLOG(j_.error()) << "AccountDelete cannot delete root dir node of " << toBase58(account_); + JLOG(j_.error()) << "AccountDelete cannot delete root dir node of " << toBase58(accountID_); return tecHAS_OBLIGATIONS; } diff --git a/src/libxrpl/tx/transactors/account/AccountSet.cpp b/src/libxrpl/tx/transactors/account/AccountSet.cpp index 69db85d8df..b52db14720 100644 --- a/src/libxrpl/tx/transactors/account/AccountSet.cpp +++ b/src/libxrpl/tx/transactors/account/AccountSet.cpp @@ -279,7 +279,7 @@ AccountSet::preclaim(PreclaimContext const& ctx) TER AccountSet::doApply() { - auto const sle = view().peek(keylet::account(account_)); + auto const sle = view().peek(keylet::account(accountID_)); if (!sle) return tefINTERNAL; // LCOV_EXCL_LINE @@ -298,7 +298,7 @@ AccountSet::doApply() bool const bSetDisallowXRP{tx.isFlag(tfDisallowXRP) || (uSetFlag == asfDisallowXRP)}; bool const bClearDisallowXRP{tx.isFlag(tfAllowXRP) || (uClearFlag == asfDisallowXRP)}; - bool const sigWithMaster{[&tx, &acct = account_]() { + bool const sigWithMaster{[&tx, &acct = accountID_]() { auto const spk = tx.getSigningPubKey(); if (publicKeyType(makeSlice(spk))) @@ -367,7 +367,7 @@ AccountSet::doApply() return tecNEED_MASTER_KEY; } - if ((!sle->isFieldPresent(sfRegularKey)) && (!view().peek(keylet::signers(account_)))) + if ((!sle->isFieldPresent(sfRegularKey)) && (!view().peek(keylet::signers(accountID_)))) { // Account has no regular key or multi-signer signer list. return tecNO_ALTERNATIVE_KEY; diff --git a/src/libxrpl/tx/transactors/account/SetRegularKey.cpp b/src/libxrpl/tx/transactors/account/SetRegularKey.cpp index f74407b433..66a0bef336 100644 --- a/src/libxrpl/tx/transactors/account/SetRegularKey.cpp +++ b/src/libxrpl/tx/transactors/account/SetRegularKey.cpp @@ -55,7 +55,7 @@ SetRegularKey::preflight(PreflightContext const& ctx) TER SetRegularKey::doApply() { - auto const sle = view().peek(keylet::account(account_)); + auto const sle = view().peek(keylet::account(accountID_)); if (!sle) return tefINTERNAL; // LCOV_EXCL_LINE @@ -69,7 +69,7 @@ SetRegularKey::doApply() else { // Account has disabled master key and no multi-signer signer list. - if (sle->isFlag(lsfDisableMaster) && !view().peek(keylet::signers(account_))) + if (sle->isFlag(lsfDisableMaster) && !view().peek(keylet::signers(accountID_))) return tecNO_ALTERNATIVE_KEY; sle->makeFieldAbsent(sfRegularKey); diff --git a/src/libxrpl/tx/transactors/account/SignerListSet.cpp b/src/libxrpl/tx/transactors/account/SignerListSet.cpp index 5a399fee7c..7a5d2c60b0 100644 --- a/src/libxrpl/tx/transactors/account/SignerListSet.cpp +++ b/src/libxrpl/tx/transactors/account/SignerListSet.cpp @@ -300,9 +300,9 @@ SignerListSet::validateQuorumAndSignerEntries( TER SignerListSet::replaceSignerList() { - auto const accountKeylet = keylet::account(account_); - auto const ownerDirKeylet = keylet::ownerDir(account_); - auto const signerListKeylet = keylet::signers(account_); + auto const accountKeylet = keylet::account(accountID_); + auto const ownerDirKeylet = keylet::ownerDir(accountID_); + auto const signerListKeylet = keylet::signers(accountID_); // This may be either a create or a replace. Preemptively remove any // old signer list. May reduce the reserve, so this is done before @@ -337,9 +337,9 @@ SignerListSet::replaceSignerList() auto viewJ = ctx_.registry.get().getJournal("View"); // Add the signer list to the account's directory. auto const page = - ctx_.view().dirInsert(ownerDirKeylet, signerListKeylet, describeOwnerDir(account_)); + ctx_.view().dirInsert(ownerDirKeylet, signerListKeylet, describeOwnerDir(accountID_)); - JLOG(j_.trace()) << "Create signer list for account " << toBase58(account_) << ": " + JLOG(j_.trace()) << "Create signer list for account " << toBase58(accountID_) << ": " << (page ? "success" : "failure"); if (!page) @@ -356,7 +356,7 @@ SignerListSet::replaceSignerList() TER SignerListSet::destroySignerList() { - auto const accountKeylet = keylet::account(account_); + auto const accountKeylet = keylet::account(accountID_); // Destroying the signer list is only allowed if either the master key // is enabled or there is a regular key. SLE::pointer const ledgerEntry = view().peek(accountKeylet); @@ -366,8 +366,8 @@ SignerListSet::destroySignerList() if ((ledgerEntry->isFlag(lsfDisableMaster)) && (!ledgerEntry->isFieldPresent(sfRegularKey))) return tecNO_ALTERNATIVE_KEY; - auto const ownerDirKeylet = keylet::ownerDir(account_); - auto const signerListKeylet = keylet::signers(account_); + auto const ownerDirKeylet = keylet::ownerDir(accountID_); + auto const signerListKeylet = keylet::signers(accountID_); return removeSignersFromLedger( ctx_.registry, view(), accountKeylet, ownerDirKeylet, signerListKeylet, j_); } @@ -378,7 +378,7 @@ SignerListSet::writeSignersToSLE(SLE::pointer const& ledgerEntry, std::uint32_t // Assign the quorum, default SignerListID, and flags. if (ctx_.view().rules().enabled(fixIncludeKeyletFields)) { - ledgerEntry->setAccountID(sfOwner, account_); + ledgerEntry->setAccountID(sfOwner, accountID_); } ledgerEntry->setFieldU32(sfSignerQuorum, quorum_); ledgerEntry->setFieldU32(sfSignerListID, kDefaultSignerListId); diff --git a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp index 9d72311b2b..76b274a609 100644 --- a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp +++ b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp @@ -1920,7 +1920,7 @@ XChainCommit::doApply() // Support dipping into reserves to pay the fee TransferHelperSubmittingAccountInfo submittingAccountInfo{ - .account = account_, + .account = accountID_, .preFeeBalance = preFeeBalance_, .postFeeBalance = (*sleAccount)[sfBalance]}; @@ -2197,7 +2197,9 @@ XChainCreateAccountCommit::doApply() // Support dipping into reserves to pay the fee TransferHelperSubmittingAccountInfo submittingAccountInfo{ - .account = account_, .preFeeBalance = preFeeBalance_, .postFeeBalance = (*sle)[sfBalance]}; + .account = accountID_, + .preFeeBalance = preFeeBalance_, + .postFeeBalance = (*sle)[sfBalance]}; STAmount const toTransfer = amount + reward; auto const thTer = transferHelper( psb, diff --git a/src/libxrpl/tx/transactors/check/CheckCash.cpp b/src/libxrpl/tx/transactors/check/CheckCash.cpp index 9ec4d0b5b0..f8dbae66fc 100644 --- a/src/libxrpl/tx/transactors/check/CheckCash.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCash.cpp @@ -294,7 +294,7 @@ CheckCash::doApply() } AccountID const srcId{sleCheck->getAccountID(sfAccount)}; - if (!psb.exists(keylet::account(srcId)) || !psb.exists(keylet::account(account_))) + if (!psb.exists(keylet::account(srcId)) || !psb.exists(keylet::account(accountID_))) { // LCOV_EXCL_START JLOG(ctx_.journal.fatal()) << "Precheck did not verify source or destination's existence."; @@ -315,7 +315,7 @@ CheckCash::doApply() auto viewJ = ctx_.registry.get().getJournal("View"); auto const optDeliverMin = ctx_.tx[~sfDeliverMin]; - if (srcId != account_) + if (srcId != accountID_) { STAmount const sendMax = sleCheck->at(sfSendMax); @@ -353,7 +353,7 @@ CheckCash::doApply() } // The source account has enough XRP so make the ledger change. - if (TER const ter{transferXRP(psb, srcId, account_, xrpDeliver, viewJ)}; + if (TER const ter{transferXRP(psb, srcId, accountID_, xrpDeliver, viewJ)}; !isTesSuccess(ter)) { // The transfer failed. Return the error code. @@ -383,7 +383,7 @@ CheckCash::doApply() // Check reserve. Return destination account SLE if enough reserve, // otherwise return nullptr. auto checkReserve = [&]() -> std::shared_ptr { - auto sleDst = psb.peek(keylet::account(account_)); + auto sleDst = psb.peek(keylet::account(accountID_)); // Can the account cover the trust line's or MPT reserve? if (std::uint32_t const ownerCount = {sleDst->at(sfOwnerCount)}; @@ -405,9 +405,9 @@ CheckCash::doApply() [&](Issue const& issue) -> std::optional { // If a trust line does not exist yet create one. Issue const& trustLineIssue = issue; - AccountID const truster = deliverIssuer == account_ ? srcId : account_; + AccountID const truster = deliverIssuer == accountID_ ? srcId : accountID_; trustLineKey = keylet::line(truster, trustLineIssue); - destLow = deliverIssuer > account_; + destLow = deliverIssuer > accountID_; if (!psb.exists(*trustLineKey)) { @@ -433,7 +433,7 @@ CheckCash::doApply() psb, // payment sandbox destLow, // is dest low? deliverIssuer, // source - account_, // destination + accountID_, // destination trustLineKey->key, // ledger index sleDst, // Account to add to false, // authorize account @@ -441,7 +441,7 @@ CheckCash::doApply() false, // freeze trust line false, // deep freeze trust line initialBalance, // zero initial balance - Issue(currency, account_), // limit of zero + Issue(currency, accountID_), // limit of zero 0, // quality in 0, // quality out viewJ); // journal @@ -479,18 +479,18 @@ CheckCash::doApply() return std::nullopt; }, [&](MPTIssue const& issue) -> std::optional { - if (account_ != deliverIssuer) + if (accountID_ != deliverIssuer) { auto const& mptID = issue.getMptID(); // Create MPT if it doesn't exist - auto const mptokenKey = keylet::mptoken(mptID, account_); + auto const mptokenKey = keylet::mptoken(mptID, accountID_); if (!psb.exists(mptokenKey)) { auto sleDst = checkReserve(); if (sleDst == nullptr) return tecINSUFFICIENT_RESERVE; - if (auto const err = checkCreateMPT(psb, mptID, account_, j_); + if (auto const err = checkCreateMPT(psb, mptID, accountID_, j_); !isTesSuccess(err)) { return err; @@ -518,7 +518,7 @@ CheckCash::doApply() psb, flowDeliver, srcId, - account_, + accountID_, STPathSet{}, true, // default path static_cast(optDeliverMin), // partial payment @@ -556,9 +556,9 @@ CheckCash::doApply() // Check was cashed. If not a self send (and it shouldn't be), remove // check link from destination directory. - if (srcId != account_ && + if (srcId != accountID_ && !psb.dirRemove( - keylet::ownerDir(account_), sleCheck->at(sfDestinationNode), sleCheck->key(), true)) + keylet::ownerDir(accountID_), sleCheck->at(sfDestinationNode), sleCheck->key(), true)) { // LCOV_EXCL_START JLOG(j_.fatal()) << "Unable to delete check from destination."; diff --git a/src/libxrpl/tx/transactors/check/CheckCreate.cpp b/src/libxrpl/tx/transactors/check/CheckCreate.cpp index b94a44c65f..6373d7e343 100644 --- a/src/libxrpl/tx/transactors/check/CheckCreate.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCreate.cpp @@ -175,7 +175,7 @@ CheckCreate::preclaim(PreclaimContext const& ctx) TER CheckCreate::doApply() { - auto const sle = view().peek(keylet::account(account_)); + auto const sle = view().peek(keylet::account(accountID_)); if (!sle) return tefINTERNAL; // LCOV_EXCL_LINE @@ -192,10 +192,10 @@ CheckCreate::doApply() // Note that we use the value from the sequence or ticket as the // Check sequence. For more explanation see comments in SeqProxy.h. std::uint32_t const seq = ctx_.tx.getSeqValue(); - Keylet const checkKeylet = keylet::check(account_, seq); + Keylet const checkKeylet = keylet::check(accountID_, seq); auto sleCheck = std::make_shared(checkKeylet); - sleCheck->setAccountID(sfAccount, account_); + sleCheck->setAccountID(sfAccount, accountID_); AccountID const dstAccountId = ctx_.tx[sfDestination]; sleCheck->setAccountID(sfDestination, dstAccountId); sleCheck->setFieldU32(sfSequence, seq); @@ -214,7 +214,7 @@ CheckCreate::doApply() auto viewJ = ctx_.registry.get().getJournal("View"); // If it's not a self-send (and it shouldn't be), add Check to the // destination's owner directory. - if (dstAccountId != account_) + if (dstAccountId != accountID_) { auto const page = view().dirInsert( keylet::ownerDir(dstAccountId), checkKeylet, describeOwnerDir(dstAccountId)); @@ -229,8 +229,8 @@ CheckCreate::doApply() } { - auto const page = - view().dirInsert(keylet::ownerDir(account_), checkKeylet, describeOwnerDir(account_)); + auto const page = view().dirInsert( + keylet::ownerDir(accountID_), checkKeylet, describeOwnerDir(accountID_)); JLOG(j_.trace()) << "Adding Check to owner directory " << to_string(checkKeylet.key) << ": " << (page ? "success" : "failure"); diff --git a/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp b/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp index 325425c46a..4e9857d782 100644 --- a/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp +++ b/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp @@ -89,7 +89,7 @@ CredentialAccept::doApply() AccountID const issuer{ctx_.tx[sfIssuer]}; // Both exist as credential object exist itself (checked in preclaim) - auto const sleSubject = view().peek(keylet::account(account_)); + auto const sleSubject = view().peek(keylet::account(accountID_)); auto const sleIssuer = view().peek(keylet::account(issuer)); if (!sleSubject || !sleIssuer) @@ -103,7 +103,7 @@ CredentialAccept::doApply() } auto const credType(ctx_.tx[sfCredentialType]); - Keylet const credentialKey = keylet::credential(account_, issuer, credType); + Keylet const credentialKey = keylet::credential(accountID_, issuer, credType); auto const sleCred = view().peek(credentialKey); // Checked in preclaim() if (!sleCred) return tefINTERNAL; // LCOV_EXCL_LINE diff --git a/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp b/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp index ec4a5c7eaa..bcb0a6fefa 100644 --- a/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp +++ b/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp @@ -104,7 +104,7 @@ CredentialCreate::doApply() { auto const subject = ctx_.tx[sfSubject]; auto const credType(ctx_.tx[sfCredentialType]); - Keylet const credentialKey = keylet::credential(subject, account_, credType); + Keylet const credentialKey = keylet::credential(subject, accountID_, credType); auto const sleCred = std::make_shared(credentialKey); if (!sleCred) @@ -126,7 +126,7 @@ CredentialCreate::doApply() sleCred->setFieldU32(sfExpiration, *optExp); } - auto const sleIssuer = view().peek(keylet::account(account_)); + auto const sleIssuer = view().peek(keylet::account(accountID_)); if (!sleIssuer) return tefINTERNAL; // LCOV_EXCL_LINE @@ -138,15 +138,15 @@ CredentialCreate::doApply() } sleCred->setAccountID(sfSubject, subject); - sleCred->setAccountID(sfIssuer, account_); + sleCred->setAccountID(sfIssuer, accountID_); sleCred->setFieldVL(sfCredentialType, credType); if (ctx_.tx.isFieldPresent(sfURI)) sleCred->setFieldVL(sfURI, ctx_.tx.getFieldVL(sfURI)); { - auto const page = - view().dirInsert(keylet::ownerDir(account_), credentialKey, describeOwnerDir(account_)); + auto const page = view().dirInsert( + keylet::ownerDir(accountID_), credentialKey, describeOwnerDir(accountID_)); JLOG(j_.trace()) << "Adding Credential to owner directory " << to_string(credentialKey.key) << ": " << (page ? "success" : "failure"); if (!page) @@ -156,7 +156,7 @@ CredentialCreate::doApply() adjustOwnerCount(view(), sleIssuer, 1, j_); } - if (subject == account_) + if (subject == accountID_) { sleCred->setFieldU32(sfFlags, lsfAccepted); } diff --git a/src/libxrpl/tx/transactors/credentials/CredentialDelete.cpp b/src/libxrpl/tx/transactors/credentials/CredentialDelete.cpp index da1b91b2f5..fcd1848cbe 100644 --- a/src/libxrpl/tx/transactors/credentials/CredentialDelete.cpp +++ b/src/libxrpl/tx/transactors/credentials/CredentialDelete.cpp @@ -78,15 +78,15 @@ CredentialDelete::preclaim(PreclaimContext const& ctx) TER CredentialDelete::doApply() { - auto const subject = ctx_.tx[~sfSubject].value_or(account_); - auto const issuer = ctx_.tx[~sfIssuer].value_or(account_); + auto const subject = ctx_.tx[~sfSubject].value_or(accountID_); + auto const issuer = ctx_.tx[~sfIssuer].value_or(accountID_); auto const credType(ctx_.tx[sfCredentialType]); auto const sleCred = view().peek(keylet::credential(subject, issuer, credType)); if (!sleCred) return tefINTERNAL; // LCOV_EXCL_LINE - if ((subject != account_) && (issuer != account_) && + if ((subject != accountID_) && (issuer != accountID_) && !checkExpired(*sleCred, ctx_.view().header().parentCloseTime)) { JLOG(j_.trace()) << "Can't delete non-expired credential."; diff --git a/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp b/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp index 990767c819..30d703686c 100644 --- a/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp +++ b/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp @@ -68,12 +68,12 @@ DelegateSet::preclaim(PreclaimContext const& ctx) TER DelegateSet::doApply() { - auto const sleOwner = ctx_.view().peek(keylet::account(account_)); + auto const sleOwner = ctx_.view().peek(keylet::account(accountID_)); if (!sleOwner) return tefINTERNAL; // LCOV_EXCL_LINE auto const& authAccount = ctx_.tx[sfAuthorize]; - auto const delegateKey = keylet::delegate(account_, authAccount); + auto const delegateKey = keylet::delegate(accountID_, authAccount); auto sle = ctx_.view().peek(delegateKey); if (sle) @@ -101,14 +101,14 @@ DelegateSet::doApply() return tecINSUFFICIENT_RESERVE; sle = std::make_shared(delegateKey); - sle->setAccountID(sfAccount, account_); + sle->setAccountID(sfAccount, accountID_); sle->setAccountID(sfAuthorize, authAccount); sle->setFieldArray(sfPermissions, permissions); // Add to delegating account's owner directory - auto const page = - ctx_.view().dirInsert(keylet::ownerDir(account_), delegateKey, describeOwnerDir(account_)); + auto const page = ctx_.view().dirInsert( + keylet::ownerDir(accountID_), delegateKey, describeOwnerDir(accountID_)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE diff --git a/src/libxrpl/tx/transactors/dex/AMMBid.cpp b/src/libxrpl/tx/transactors/dex/AMMBid.cpp index 9b1acc5571..b3b41fbfa2 100644 --- a/src/libxrpl/tx/transactors/dex/AMMBid.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMBid.cpp @@ -371,7 +371,7 @@ AMMBid::doApply() // as we go on processing transactions. Sandbox sb(&ctx_.view()); - auto const result = applyBid(ctx_, sb, account_, j_); + auto const result = applyBid(ctx_, sb, accountID_, j_); if (result.second) sb.apply(ctx_.rawView()); diff --git a/src/libxrpl/tx/transactors/dex/AMMCreate.cpp b/src/libxrpl/tx/transactors/dex/AMMCreate.cpp index 325ca2988d..3e1fe97a76 100644 --- a/src/libxrpl/tx/transactors/dex/AMMCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMCreate.cpp @@ -385,7 +385,7 @@ AMMCreate::doApply() // as we go on processing transactions. Sandbox sb(&ctx_.view()); - auto const result = applyCreate(ctx_, sb, account_, j_); + auto const result = applyCreate(ctx_, sb, accountID_, j_); if (result.second) sb.apply(ctx_.rawView()); diff --git a/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp b/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp index b19b6eff6c..86cd52300d 100644 --- a/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp @@ -403,7 +403,7 @@ AMMDeposit::applyGuts(Sandbox& sb) auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected; auto const tfee = (lptAMMBalance == beast::kZero) ? ctx_.tx[~sfTradingFee].value_or(0) - : getTradingFee(ctx_.view(), *ammSle, account_); + : getTradingFee(ctx_.view(), *ammSle, accountID_); auto const subTxType = ctx_.tx.getFlags() & tfDepositSubTx; @@ -474,7 +474,7 @@ AMMDeposit::applyGuts(Sandbox& sb) // LP depositing into AMM empty state gets the auction slot // and the voting if (lptAMMBalance == beast::kZero) - initializeFeeAuctionVote(sb, ammSle, account_, lptAMMBalance.asset(), tfee); + initializeFeeAuctionVote(sb, ammSle, accountID_, lptAMMBalance.asset(), tfee); sb.update(ammSle); } @@ -519,14 +519,14 @@ AMMDeposit::deposit( { auto const& lpIssue = lpTokensDeposit.get(); // Adjust the reserve if LP doesn't have LPToken trustline - auto const sle = view.read(keylet::line(account_, lpIssue.account, lpIssue.currency)); - if (xrpLiquid(view, account_, !sle, j_) >= depositAmount) + auto const sle = view.read(keylet::line(accountID_, lpIssue.account, lpIssue.currency)); + if (xrpLiquid(view, accountID_, !sle, j_) >= depositAmount) return tesSUCCESS; } else if ( accountFunds( view, - account_, + accountID_, depositAmount, FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, @@ -574,7 +574,7 @@ AMMDeposit::deposit( } auto res = accountSend( - view, account_, ammAccount, amountDepositActual, ctx_.journal, WaiveTransferFee::Yes); + view, accountID_, ammAccount, amountDepositActual, ctx_.journal, WaiveTransferFee::Yes); if (!isTesSuccess(res)) { JLOG(ctx_.journal.debug()) << "AMM Deposit: failed to deposit " << amountDepositActual; @@ -593,7 +593,12 @@ AMMDeposit::deposit( } res = accountSend( - view, account_, ammAccount, *amount2DepositActual, ctx_.journal, WaiveTransferFee::Yes); + view, + accountID_, + ammAccount, + *amount2DepositActual, + ctx_.journal, + WaiveTransferFee::Yes); if (!isTesSuccess(res)) { JLOG(ctx_.journal.debug()) @@ -603,7 +608,7 @@ AMMDeposit::deposit( } // Deposit LP tokens - res = accountSend(view, ammAccount, account_, lpTokensDepositActual, ctx_.journal); + res = accountSend(view, ammAccount, accountID_, lpTokensDepositActual, ctx_.journal); if (!isTesSuccess(res)) { JLOG(ctx_.journal.debug()) << "AMM Deposit: failed to deposit LPTokens"; diff --git a/src/libxrpl/tx/transactors/dex/AMMVote.cpp b/src/libxrpl/tx/transactors/dex/AMMVote.cpp index a4afb5392e..391f7e1ecc 100644 --- a/src/libxrpl/tx/transactors/dex/AMMVote.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMVote.cpp @@ -241,7 +241,7 @@ AMMVote::doApply() // as we go on processing transactions. Sandbox sb(&ctx_.view()); - auto const result = applyVote(ctx_, sb, account_, j_); + auto const result = applyVote(ctx_, sb, accountID_, j_); if (result.second) sb.apply(ctx_.rawView()); diff --git a/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp b/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp index 60968227ea..a4fd1518f5 100644 --- a/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp @@ -329,11 +329,11 @@ AMMWithdraw::applyGuts(Sandbox& sb) // might not match the LP's trustline balance if (sb.rules().enabled(fixAMMv1_1)) { - if (auto const res = verifyAndAdjustLPTokenBalance(sb, lpTokens, ammSle, account_); !res) + if (auto const res = verifyAndAdjustLPTokenBalance(sb, lpTokens, ammSle, accountID_); !res) return {res.error(), false}; } - auto const tfee = getTradingFee(ctx_.view(), *ammSle, account_); + auto const tfee = getTradingFee(ctx_.view(), *ammSle, accountID_); auto const expected = ammHolds( sb, @@ -458,7 +458,7 @@ AMMWithdraw::withdraw( view, ammSle, ammAccount, - account_, + accountID_, amountBalance, amountWithdraw, amount2Withdraw, @@ -748,7 +748,7 @@ AMMWithdraw::equalWithdrawTokens( std::tie(ter, newLPTokenBalance, std::ignore, std::ignore) = equalWithdrawTokens( view, ammSle, - account_, + accountID_, ammAccount, amountBalance, amount2Balance, diff --git a/src/libxrpl/tx/transactors/dex/OfferCancel.cpp b/src/libxrpl/tx/transactors/dex/OfferCancel.cpp index 547db00dca..42692b59cc 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCancel.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCancel.cpp @@ -55,11 +55,11 @@ OfferCancel::doApply() { auto const offerSequence = ctx_.tx[sfOfferSequence]; - auto const sle = view().read(keylet::account(account_)); + auto const sle = view().read(keylet::account(accountID_)); if (!sle) return tefINTERNAL; // LCOV_EXCL_LINE - if (auto sleOffer = view().peek(keylet::offer(account_, offerSequence))) + if (auto sleOffer = view().peek(keylet::offer(accountID_, offerSequence))) { JLOG(j_.debug()) << "Trying to cancel offer #" << offerSequence; return offerDelete(view(), sleOffer, ctx_.registry.get().getJournal("View")); diff --git a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp index 97121ce398..69c101644c 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp @@ -341,14 +341,14 @@ OfferCreate::flowCross( // below the reserve) so we check this case again. STAmount const inStartBalance = accountFunds( psb, - account_, + accountID_, takerAmount.in, FreezeHandling::ZeroIfFrozen, AuthHandling::ZeroIfUnauthorized, j_); // Allow unfunded MPT issuer auto const disallowUnfunded = - !inStartBalance.holds() || inStartBalance.getIssuer() != account_; + !inStartBalance.holds() || inStartBalance.getIssuer() != accountID_; if (disallowUnfunded && inStartBalance <= beast::kZero) { // The account balance can't cover even part of the offer. @@ -361,7 +361,7 @@ OfferCreate::flowCross( // offer taker. Set sendMax to allow for the gateway's cut. Rate gatewayXferRate{QUALITY_ONE}; STAmount sendMax = takerAmount.in; - if (!sendMax.native() && (account_ != sendMax.getIssuer())) + if (!sendMax.native() && (accountID_ != sendMax.getIssuer())) { gatewayXferRate = transferRate(psb, sendMax); if (gatewayXferRate.value != QUALITY_ONE) @@ -428,8 +428,8 @@ OfferCreate::flowCross( auto const result = flow( psb, deliver, - account_, - account_, + accountID_, + accountID_, paths, true, // default path !ctx_.tx.isFlag(tfFillOrKill), // partial payment @@ -455,7 +455,7 @@ OfferCreate::flowCross( { STAmount const takerInBalance = accountFunds( psb, - account_, + accountID_, takerAmount.in, FreezeHandling::ZeroIfFrozen, AuthHandling::ZeroIfUnauthorized, @@ -619,7 +619,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) // Process a cancellation request that's passed along with an offer. if (cancelSequence) { - auto const sleCancel = sb.peek(keylet::offer(account_, *cancelSequence)); + auto const sleCancel = sb.peek(keylet::offer(accountID_, *cancelSequence)); // It's not an error to not find the offer to cancel: it might have // been consumed or removed. If it is found, however, it's an error @@ -810,7 +810,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) return {tesSUCCESS, true}; } - auto const sleCreator = sb.peek(keylet::account(account_)); + auto const sleCreator = sb.peek(keylet::account(accountID_)); if (!sleCreator) return {tefINTERNAL, false}; @@ -836,11 +836,11 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) } // We need to place the remainder of the offer into its order book. - auto const offerIndex = keylet::offer(account_, offerSequence); + auto const offerIndex = keylet::offer(accountID_, offerSequence); // Add offer to owner's directory. auto const ownerNode = - sb.dirInsert(keylet::ownerDir(account_), offerIndex, describeOwnerDir(account_)); + sb.dirInsert(keylet::ownerDir(accountID_), offerIndex, describeOwnerDir(accountID_)); if (!ownerNode) { @@ -905,7 +905,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) } auto sleOffer = std::make_shared(offerIndex); - sleOffer->setAccountID(sfAccount, account_); + sleOffer->setAccountID(sfAccount, accountID_); sleOffer->setFieldU32(sfSequence, offerSequence); sleOffer->setFieldH256(sfBookDirectory, dir.key); sleOffer->setFieldAmount(sfTakerPays, saTakerPays); diff --git a/src/libxrpl/tx/transactors/did/DIDDelete.cpp b/src/libxrpl/tx/transactors/did/DIDDelete.cpp index 9f9f54e6f6..4b4fb47169 100644 --- a/src/libxrpl/tx/transactors/did/DIDDelete.cpp +++ b/src/libxrpl/tx/transactors/did/DIDDelete.cpp @@ -67,7 +67,7 @@ DIDDelete::deleteSLE( TER DIDDelete::doApply() { - return deleteSLE(ctx_, keylet::did(account_), account_); + return deleteSLE(ctx_, keylet::did(accountID_), accountID_); } void diff --git a/src/libxrpl/tx/transactors/did/DIDSet.cpp b/src/libxrpl/tx/transactors/did/DIDSet.cpp index f7276eac04..a930c3c754 100644 --- a/src/libxrpl/tx/transactors/did/DIDSet.cpp +++ b/src/libxrpl/tx/transactors/did/DIDSet.cpp @@ -99,7 +99,7 @@ TER DIDSet::doApply() { // Edit ledger object if it already exists - Keylet const didKeylet = keylet::did(account_); + Keylet const didKeylet = keylet::did(accountID_); if (auto const sleDID = ctx_.view().peek(didKeylet)) { auto update = [&](auto const& sField) { @@ -130,7 +130,7 @@ DIDSet::doApply() // Create new ledger object otherwise auto const sleDID = std::make_shared(didKeylet); - (*sleDID)[sfAccount] = account_; + (*sleDID)[sfAccount] = accountID_; auto set = [&](auto const& sField) { if (auto const field = ctx_.tx[~sField]; field && !field->empty()) @@ -146,7 +146,7 @@ DIDSet::doApply() return tecEMPTY_DID; } - return addSLE(ctx_, sleDID, account_); + return addSLE(ctx_, sleDID, accountID_); } void diff --git a/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp b/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp index d249bb8379..99cf467ee9 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp @@ -178,7 +178,7 @@ EscrowCancel::doApply() return temDISABLED; // LCOV_EXCL_LINE auto const issuer = amount.getIssuer(); - bool const createAsset = account == account_; + bool const createAsset = account == accountID_; if (auto const ret = std::visit( [&](T const&) { return escrowUnlockApplyHelper( diff --git a/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp b/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp index 2e738d0de5..0b1db125f6 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp @@ -417,7 +417,7 @@ EscrowCreate::doApply() if (ctx_.tx[~sfFinishAfter] && after(closeTime, ctx_.tx[sfFinishAfter])) return tecNO_PERMISSION; - auto const sle = ctx_.view().peek(keylet::account(account_)); + auto const sle = ctx_.view().peek(keylet::account(accountID_)); if (!sle) return tefINTERNAL; // LCOV_EXCL_LINE @@ -448,10 +448,10 @@ EscrowCreate::doApply() // Create escrow in ledger. Note that we use the value from the // sequence or ticket. For more explanation see comments in SeqProxy.h. - Keylet const escrowKeylet = keylet::escrow(account_, ctx_.tx.getSeqValue()); + Keylet const escrowKeylet = keylet::escrow(accountID_, ctx_.tx.getSeqValue()); auto const slep = std::make_shared(escrowKeylet); (*slep)[sfAmount] = amount; - (*slep)[sfAccount] = account_; + (*slep)[sfAccount] = accountID_; (*slep)[~sfCondition] = ctx_.tx[~sfCondition]; (*slep)[~sfSourceTag] = ctx_.tx[~sfSourceTag]; (*slep)[sfDestination] = ctx_.tx[sfDestination]; @@ -476,7 +476,7 @@ EscrowCreate::doApply() // Add escrow to sender's owner directory { auto page = ctx_.view().dirInsert( - keylet::ownerDir(account_), escrowKeylet, describeOwnerDir(account_)); + keylet::ownerDir(accountID_), escrowKeylet, describeOwnerDir(accountID_)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE (*slep)[sfOwnerNode] = *page; @@ -484,7 +484,7 @@ EscrowCreate::doApply() // If it's not a self-send, add escrow to recipient's owner directory. AccountID const dest = ctx_.tx[sfDestination]; - if (dest != account_) + if (dest != accountID_) { auto page = ctx_.view().dirInsert(keylet::ownerDir(dest), escrowKeylet, describeOwnerDir(dest)); @@ -497,7 +497,7 @@ EscrowCreate::doApply() // track the total locked balance. For MPT, this isn't necessary because the // locked balance is already stored directly in the MPTokenIssuance object. AccountID const issuer = amount.getIssuer(); - if (!isXRP(amount) && issuer != account_ && issuer != dest && !amount.holds()) + if (!isXRP(amount) && issuer != accountID_ && issuer != dest && !amount.holds()) { auto page = ctx_.view().dirInsert(keylet::ownerDir(issuer), escrowKeylet, describeOwnerDir(issuer)); @@ -515,7 +515,7 @@ EscrowCreate::doApply() { if (auto const ret = std::visit( [&](T const&) { - return escrowLockApplyHelper(ctx_.view(), issuer, account_, amount, j_); + return escrowLockApplyHelper(ctx_.view(), issuer, accountID_, amount, j_); }, amount.asset().value()); !isTesSuccess(ret)) diff --git a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp index 499db45794..13bd4b1682 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp @@ -310,7 +310,8 @@ EscrowFinish::doApply() if (!sled) return tecNO_DST; - if (auto err = verifyDepositPreauth(ctx_.tx, ctx_.view(), account_, destID, sled, ctx_.journal); + if (auto err = + verifyDepositPreauth(ctx_.tx, ctx_.view(), accountID_, destID, sled, ctx_.journal); !isTesSuccess(err)) return err; @@ -355,7 +356,7 @@ EscrowFinish::doApply() ? xrpl::Rate(slep->getFieldU32(sfTransferRate)) : kParityRate; auto const issuer = amount.getIssuer(); - bool const createAsset = destID == account_; + bool const createAsset = destID == accountID_; if (auto const ret = std::visit( [&](T const&) { return escrowUnlockApplyHelper( diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp index 3ea37bbf27..04905d5ea3 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp @@ -121,7 +121,8 @@ LoanBrokerCoverDeposit::doApply() auto const brokerPseudoID = broker->at(sfAccount); // Transfer assets from depositor to pseudo-account. - if (auto ter = accountSend(view(), account_, brokerPseudoID, amount, j_, WaiveTransferFee::Yes)) + if (auto ter = + accountSend(view(), accountID_, brokerPseudoID, amount, j_, WaiveTransferFee::Yes)) return ter; // Increase the LoanBroker's CoverAvailable by Amount diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp index 824c6ea25c..17a9683690 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp @@ -163,7 +163,7 @@ LoanBrokerCoverWithdraw::doApply() auto const brokerID = tx[sfLoanBrokerID]; auto const amount = tx[sfAmount]; - auto const dstAcct = tx[~sfDestination].value_or(account_); + auto const dstAcct = tx[~sfDestination].value_or(accountID_); auto broker = view().peek(keylet::loanbroker(brokerID)); if (!broker) @@ -183,7 +183,7 @@ LoanBrokerCoverWithdraw::doApply() associateAsset(*broker, vaultAsset); - return doWithdraw(view(), tx, account_, dstAcct, brokerPseudoID, preFeeBalance_, amount, j_); + return doWithdraw(view(), tx, accountID_, dstAcct, brokerPseudoID, preFeeBalance_, amount, j_); } void diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp index 134e0090fa..805a4612f2 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp @@ -130,7 +130,7 @@ LoanBrokerDelete::doApply() auto const brokerPseudoID = broker->at(sfAccount); if (!view().dirRemove( - keylet::ownerDir(account_), broker->at(sfOwnerNode), broker->key(), false)) + keylet::ownerDir(accountID_), broker->at(sfOwnerNode), broker->key(), false)) { return tefBAD_LEDGER; // LCOV_EXCL_LINE } @@ -143,7 +143,7 @@ LoanBrokerDelete::doApply() { auto const coverAvailable = STAmount{vaultAsset, broker->at(sfCoverAvailable)}; if (auto const ter = accountSend( - view(), brokerPseudoID, account_, coverAvailable, j_, WaiveTransferFee::Yes)) + view(), brokerPseudoID, accountID_, coverAvailable, j_, WaiveTransferFee::Yes)) return ter; } @@ -177,7 +177,7 @@ LoanBrokerDelete::doApply() view().erase(broker); { - auto owner = view().peek(keylet::account(account_)); + auto owner = view().peek(keylet::account(accountID_)); if (!owner) return tefBAD_LEDGER; // LCOV_EXCL_LINE diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp index 2a40ed1429..6e3d2ad0a8 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp @@ -220,7 +220,7 @@ LoanBrokerSet::doApply() auto const vaultAsset = sleVault->at(sfAsset); auto const sequence = tx.getSeqValue(); - auto owner = view.peek(keylet::account(account_)); + auto owner = view.peek(keylet::account(accountID_)); if (!owner) { // This should be impossible @@ -229,9 +229,9 @@ LoanBrokerSet::doApply() return tefBAD_LEDGER; // LCOV_EXCL_STOP } - auto broker = std::make_shared(keylet::loanbroker(account_, sequence)); + auto broker = std::make_shared(keylet::loanbroker(accountID_, sequence)); - if (auto const ter = dirLink(view, account_, broker)) + if (auto const ter = dirLink(view, accountID_, broker)) return ter; // LCOV_EXCL_LINE if (auto const ter = dirLink(view, vaultPseudoID, broker, sfVaultNode)) return ter; // LCOV_EXCL_LINE @@ -255,7 +255,7 @@ LoanBrokerSet::doApply() // Initialize data fields: broker->at(sfSequence) = sequence; broker->at(sfVaultID) = vaultID; - broker->at(sfOwner) = account_; + broker->at(sfOwner) = accountID_; broker->at(sfAccount) = pseudoId; // The LoanSequence indexes loans created by this broker, starting at 1 broker->at(sfLoanSequence) = 1; diff --git a/src/libxrpl/tx/transactors/lending/LoanPay.cpp b/src/libxrpl/tx/transactors/lending/LoanPay.cpp index 12a0212b72..b8b940f3e3 100644 --- a/src/libxrpl/tx/transactors/lending/LoanPay.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanPay.cpp @@ -581,13 +581,13 @@ LoanPay::doApply() // These three values are used to check that funds are conserved after the transfers auto const accountBalanceBefore = accountHolds( view, - account_, + accountID_, asset, FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, j_, SpendableHandling::FullBalance); - auto const vaultBalanceBefore = account_ == vaultPseudoAccount + auto const vaultBalanceBefore = accountID_ == vaultPseudoAccount ? STAmount{asset, 0} : accountHolds( view, @@ -597,15 +597,16 @@ LoanPay::doApply() AuthHandling::IgnoreAuth, j_, SpendableHandling::FullBalance); - auto const brokerBalanceBefore = account_ == brokerPayee ? STAmount{asset, 0} - : accountHolds( - view, - brokerPayee, - asset, - FreezeHandling::IgnoreFreeze, - AuthHandling::IgnoreAuth, - j_, - SpendableHandling::FullBalance); + auto const brokerBalanceBefore = accountID_ == brokerPayee + ? STAmount{asset, 0} + : accountHolds( + view, + brokerPayee, + asset, + FreezeHandling::IgnoreFreeze, + AuthHandling::IgnoreAuth, + j_, + SpendableHandling::FullBalance); if (totalPaidToVaultRounded != beast::kZero) { @@ -615,7 +616,7 @@ LoanPay::doApply() if (totalPaidToBroker != beast::kZero) { - if (brokerPayee == account_) + if (brokerPayee == accountID_) { // The broker may have deleted their holding. Recreate it if needed if (auto const ter = addEmptyHolding( @@ -633,7 +634,7 @@ LoanPay::doApply() if (auto const ter = accountSendMulti( view, - account_, + accountID_, asset, {{vaultPseudoAccount, totalPaidToVaultRounded}, {brokerPayee, totalPaidToBroker}}, j_, @@ -659,13 +660,13 @@ LoanPay::doApply() // Check that funds are conserved auto const accountBalanceAfter = accountHolds( view, - account_, + accountID_, asset, FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, j_, SpendableHandling::FullBalance); - auto const vaultBalanceAfter = account_ == vaultPseudoAccount + auto const vaultBalanceAfter = accountID_ == vaultPseudoAccount ? STAmount{asset, 0} : accountHolds( view, @@ -675,15 +676,15 @@ LoanPay::doApply() AuthHandling::IgnoreAuth, j_, SpendableHandling::FullBalance); - auto const brokerBalanceAfter = account_ == brokerPayee ? STAmount{asset, 0} - : accountHolds( - view, - brokerPayee, - asset, - FreezeHandling::IgnoreFreeze, - AuthHandling::IgnoreAuth, - j_, - SpendableHandling::FullBalance); + auto const brokerBalanceAfter = accountID_ == brokerPayee ? STAmount{asset, 0} + : accountHolds( + view, + brokerPayee, + asset, + FreezeHandling::IgnoreFreeze, + AuthHandling::IgnoreAuth, + j_, + SpendableHandling::FullBalance); auto const balanceScale = [&]() { // Find a reasonable scale to use for the balance comparisons. // @@ -800,7 +801,7 @@ LoanPay::doApply() goodRounding, "xrpl::LoanPay::doApply", "funds are conserved (with rounding)"); XRPL_ASSERT_PARTS( - accountBalanceAfter < accountBalanceBefore || account_ == asset.getIssuer(), + accountBalanceAfter < accountBalanceBefore || accountID_ == asset.getIssuer(), "xrpl::LoanPay::doApply", "account balance decreased"); XRPL_ASSERT_PARTS( diff --git a/src/libxrpl/tx/transactors/lending/LoanSet.cpp b/src/libxrpl/tx/transactors/lending/LoanSet.cpp index 83eccf1809..a3b71fd20d 100644 --- a/src/libxrpl/tx/transactors/lending/LoanSet.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanSet.cpp @@ -388,7 +388,7 @@ LoanSet::doApply() Asset const vaultAsset = vaultSle->at(sfAsset); auto const counterparty = tx[~sfCounterparty].value_or(brokerOwner); - auto const borrower = counterparty == brokerOwner ? account_ : counterparty; + auto const borrower = counterparty == brokerOwner ? accountID_ : counterparty; auto const borrowerSle = view.peek(keylet::account(borrower)); if (!borrowerSle) { @@ -508,7 +508,7 @@ LoanSet::doApply() { auto const ownerCount = borrowerSle->at(sfOwnerCount); auto const balance = - account_ == borrower ? preFeeBalance_ : borrowerSle->at(sfBalance).value().xrp(); + accountID_ == borrower ? preFeeBalance_ : borrowerSle->at(sfBalance).value().xrp(); if (balance < view.fees().accountReserve(ownerCount)) return tecINSUFFICIENT_RESERVE; } @@ -520,7 +520,7 @@ LoanSet::doApply() // Create a holding for the borrower if one does not already exist. XRPL_ASSERT_PARTS( - borrower == account_ || borrower == counterparty, + borrower == accountID_ || borrower == counterparty, "xrpl::LoanSet::doApply", "borrower signed transaction"); if (auto const ter = addEmptyHolding( @@ -542,7 +542,7 @@ LoanSet::doApply() // Create the holding if it doesn't already exist (necessary for MPTs). // The owner may have deleted their MPT / line at some point. XRPL_ASSERT_PARTS( - brokerOwner == account_ || brokerOwner == counterparty, + brokerOwner == accountID_ || brokerOwner == counterparty, "xrpl::LoanSet::doApply", "broker owner signed transaction"); diff --git a/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp b/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp index 00441795e2..b80d282d70 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp @@ -407,8 +407,8 @@ NFTokenAcceptOffer::acceptOffer(std::shared_ptr const& offer) { bool const isSell = offer->isFlag(lsfSellNFToken); AccountID const owner = (*offer)[sfOwner]; - AccountID const& seller = isSell ? owner : account_; - AccountID const& buyer = isSell ? account_ : owner; + AccountID const& seller = isSell ? owner : accountID_; + AccountID const& buyer = isSell ? accountID_ : owner; auto const nftokenID = (*offer)[sfNFTokenID]; @@ -528,7 +528,7 @@ NFTokenAcceptOffer::doApply() // Send the broker the amount they requested. if (auto const cut = ctx_.tx[~sfNFTokenBrokerFee]; cut && cut.value() != beast::kZero) { - if (auto const r = pay(buyer, account_, cut.value()); !isTesSuccess(r)) + if (auto const r = pay(buyer, accountID_, cut.value()); !isTesSuccess(r)) return r; amount -= cut.value(); diff --git a/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp b/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp index 621364dc79..e7faa30df8 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp @@ -222,7 +222,7 @@ NFTokenMint::preclaim(PreclaimContext const& ctx) TER NFTokenMint::doApply() { - auto const issuer = ctx_.tx[~sfIssuer].value_or(account_); + auto const issuer = ctx_.tx[~sfIssuer].value_or(accountID_); auto const tokenSeq = [this, &issuer]() -> Expected { auto const root = view().peek(keylet::account(issuer)); @@ -279,7 +279,7 @@ NFTokenMint::doApply() return (tokenSeq.error()); std::uint32_t const ownerCountBefore = - view().read(keylet::account(account_))->getFieldU32(sfOwnerCount); + view().read(keylet::account(accountID_))->getFieldU32(sfOwnerCount); // Assemble the new NFToken. SOTemplate const* nfTokenTemplate = @@ -305,7 +305,7 @@ NFTokenMint::doApply() object.setFieldVL(sfURI, *uri); }); - if (TER const ret = nft::insertToken(ctx_.view(), account_, std::move(newToken)); + if (TER const ret = nft::insertToken(ctx_.view(), accountID_, std::move(newToken)); !isTesSuccess(ret)) return ret; @@ -333,7 +333,7 @@ NFTokenMint::doApply() // requiring the reserve to be met each time. The reserve is // only managed when a new NFT page or sell offer is added. if (auto const ownerCountAfter = - view().read(keylet::account(account_))->getFieldU32(sfOwnerCount); + view().read(keylet::account(accountID_))->getFieldU32(sfOwnerCount); ownerCountAfter > ownerCountBefore) { if (auto const reserve = view().fees().accountReserve(ownerCountAfter); diff --git a/src/libxrpl/tx/transactors/oracle/OracleDelete.cpp b/src/libxrpl/tx/transactors/oracle/OracleDelete.cpp index 99f2a14900..839b2b4e24 100644 --- a/src/libxrpl/tx/transactors/oracle/OracleDelete.cpp +++ b/src/libxrpl/tx/transactors/oracle/OracleDelete.cpp @@ -82,8 +82,8 @@ OracleDelete::deleteOracle( TER OracleDelete::doApply() { - if (auto sle = ctx_.view().peek(keylet::oracle(account_, ctx_.tx[sfOracleDocumentID]))) - return deleteOracle(ctx_.view(), sle, account_, j_); + if (auto sle = ctx_.view().peek(keylet::oracle(accountID_, ctx_.tx[sfOracleDocumentID]))) + return deleteOracle(ctx_.view(), sle, accountID_, j_); return tecINTERNAL; // LCOV_EXCL_LINE } diff --git a/src/libxrpl/tx/transactors/oracle/OracleSet.cpp b/src/libxrpl/tx/transactors/oracle/OracleSet.cpp index d0d488bbec..66ce95f46c 100644 --- a/src/libxrpl/tx/transactors/oracle/OracleSet.cpp +++ b/src/libxrpl/tx/transactors/oracle/OracleSet.cpp @@ -201,7 +201,7 @@ setPriceDataInnerObjTemplate(STObject& obj) TER OracleSet::doApply() { - auto const oracleID = keylet::oracle(account_, ctx_.tx[sfOracleDocumentID]); + auto const oracleID = keylet::oracle(accountID_, ctx_.tx[sfOracleDocumentID]); auto populatePriceData = [](STObject& priceData, STObject const& entry) { setPriceDataInnerObjTemplate(priceData); @@ -311,7 +311,7 @@ OracleSet::doApply() sle->setFieldU32(sfLastUpdateTime, ctx_.tx[sfLastUpdateTime]); auto page = ctx_.view().dirInsert( - keylet::ownerDir(account_), sle->key(), describeOwnerDir(account_)); + keylet::ownerDir(accountID_), sle->key(), describeOwnerDir(accountID_)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE diff --git a/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp b/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp index ed6699936e..8b4ad2f025 100644 --- a/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp +++ b/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp @@ -153,7 +153,7 @@ DepositPreauth::doApply() { if (ctx_.tx.isFieldPresent(sfAuthorize)) { - auto const sleOwner = view().peek(keylet::account(account_)); + auto const sleOwner = view().peek(keylet::account(accountID_)); if (!sleOwner) return {tefINTERNAL}; @@ -171,15 +171,15 @@ DepositPreauth::doApply() // Preclaim already verified that the Preauth entry does not yet exist. // Create and populate the Preauth entry. AccountID const auth{ctx_.tx[sfAuthorize]}; - Keylet const preauthKeylet = keylet::depositPreauth(account_, auth); + Keylet const preauthKeylet = keylet::depositPreauth(accountID_, auth); auto slePreauth = std::make_shared(preauthKeylet); - slePreauth->setAccountID(sfAccount, account_); + slePreauth->setAccountID(sfAccount, accountID_); slePreauth->setAccountID(sfAuthorize, auth); view().insert(slePreauth); - auto const page = - view().dirInsert(keylet::ownerDir(account_), preauthKeylet, describeOwnerDir(account_)); + auto const page = view().dirInsert( + keylet::ownerDir(accountID_), preauthKeylet, describeOwnerDir(accountID_)); JLOG(j_.trace()) << "Adding DepositPreauth to owner directory " << to_string(preauthKeylet.key) << ": " << (page ? "success" : "failure"); @@ -194,13 +194,13 @@ DepositPreauth::doApply() } else if (ctx_.tx.isFieldPresent(sfUnauthorize)) { - auto const preauth = keylet::depositPreauth(account_, ctx_.tx[sfUnauthorize]); + auto const preauth = keylet::depositPreauth(accountID_, ctx_.tx[sfUnauthorize]); return DepositPreauth::removeFromLedger(view(), preauth.key, j_); } else if (ctx_.tx.isFieldPresent(sfAuthorizeCredentials)) { - auto const sleOwner = view().peek(keylet::account(account_)); + auto const sleOwner = view().peek(keylet::account(accountID_)); if (!sleOwner) return tefINTERNAL; // LCOV_EXCL_LINE @@ -229,18 +229,18 @@ DepositPreauth::doApply() sortedLE.pushBack(std::move(cred)); } - Keylet const preauthKey = keylet::depositPreauth(account_, sortedTX); + Keylet const preauthKey = keylet::depositPreauth(accountID_, sortedTX); auto slePreauth = std::make_shared(preauthKey); if (!slePreauth) return tefINTERNAL; // LCOV_EXCL_LINE - slePreauth->setAccountID(sfAccount, account_); + slePreauth->setAccountID(sfAccount, accountID_); slePreauth->peekFieldArray(sfAuthorizeCredentials) = std::move(sortedLE); view().insert(slePreauth); - auto const page = - view().dirInsert(keylet::ownerDir(account_), preauthKey, describeOwnerDir(account_)); + auto const page = view().dirInsert( + keylet::ownerDir(accountID_), preauthKey, describeOwnerDir(accountID_)); JLOG(j_.trace()) << "Adding DepositPreauth to owner directory " << to_string(preauthKey.key) << ": " << (page ? "success" : "failure"); @@ -256,7 +256,7 @@ DepositPreauth::doApply() else if (ctx_.tx.isFieldPresent(sfUnauthorizeCredentials)) { auto const preauthKey = keylet::depositPreauth( - account_, credentials::makeSorted(ctx_.tx.getFieldArray(sfUnauthorizeCredentials))); + accountID_, credentials::makeSorted(ctx_.tx.getFieldArray(sfUnauthorizeCredentials))); return DepositPreauth::removeFromLedger(view(), preauthKey.key, j_); } diff --git a/src/libxrpl/tx/transactors/payment/Payment.cpp b/src/libxrpl/tx/transactors/payment/Payment.cpp index fa5f30785c..1848d34786 100644 --- a/src/libxrpl/tx/transactors/payment/Payment.cpp +++ b/src/libxrpl/tx/transactors/payment/Payment.cpp @@ -410,7 +410,7 @@ Payment::doApply() AccountID const dstAccountID(ctx_.tx.getAccountID(sfDestination)); STAmount const dstAmount(ctx_.tx.getFieldAmount(sfAmount)); bool const isDstMPT = dstAmount.holds(); - STAmount const maxSourceAmount = getMaxSourceAmount(account_, dstAmount, sendMax); + STAmount const maxSourceAmount = getMaxSourceAmount(accountID_, dstAmount, sendMax); JLOG(j_.trace()) << "maxSourceAmount=" << maxSourceAmount.getFullText() << " dstAmount=" << dstAmount.getFullText(); @@ -453,7 +453,7 @@ Payment::doApply() // 2. If Account is deposit preauthorized by destination. if (auto err = verifyDepositPreauth( - ctx_.tx, ctx_.view(), account_, dstAccountID, sleDst, ctx_.journal); + ctx_.tx, ctx_.view(), accountID_, dstAccountID, sleDst, ctx_.journal); !isTesSuccess(err)) return err; @@ -472,7 +472,7 @@ Payment::doApply() maxSourceAmount, dstAmount, dstAccountID, - account_, + accountID_, ctx_.tx.getFieldPathSet(sfPaths), ctx_.tx[~sfDomainID], ctx_.registry, @@ -512,18 +512,18 @@ Payment::doApply() JLOG(j_.trace()) << " dstAmount=" << dstAmount.getFullText(); auto const& mptIssue = dstAmount.get(); - if (auto const ter = requireAuth(view(), mptIssue, account_); !isTesSuccess(ter)) + if (auto const ter = requireAuth(view(), mptIssue, accountID_); !isTesSuccess(ter)) return ter; if (auto const ter = requireAuth(view(), mptIssue, dstAccountID); !isTesSuccess(ter)) return ter; - if (auto const ter = canTransfer(view(), mptIssue, account_, dstAccountID); + if (auto const ter = canTransfer(view(), mptIssue, accountID_, dstAccountID); !isTesSuccess(ter)) return ter; if (auto err = verifyDepositPreauth( - ctx_.tx, ctx_.view(), account_, dstAccountID, sleDst, ctx_.journal); + ctx_.tx, ctx_.view(), accountID_, dstAccountID, sleDst, ctx_.journal); !isTesSuccess(err)) return err; @@ -532,13 +532,13 @@ Payment::doApply() // Transfer rate Rate rate{QUALITY_ONE}; // Payment between the holders - if (account_ != issuer && dstAccountID != issuer) + if (accountID_ != issuer && dstAccountID != issuer) { // If globally/individually locked then // - can't send between holders // - holder can send back to issuer // - issuer can send to holder - if (isAnyFrozen(view(), {account_, dstAccountID}, mptIssue)) + if (isAnyFrozen(view(), {accountID_, dstAccountID}, mptIssue)) return tecLOCKED; // Get the rate for a payment between the holders. @@ -566,7 +566,7 @@ Payment::doApply() return tecPATH_PARTIAL; PaymentSandbox pv(&view()); - auto res = accountSend(pv, account_, dstAccountID, amountDeliver, ctx_.journal); + auto res = accountSend(pv, accountID_, dstAccountID, amountDeliver, ctx_.journal); if (isTesSuccess(res)) { pv.apply(ctx_.rawView()); @@ -589,7 +589,7 @@ Payment::doApply() // Direct XRP payment. - auto const sleSrc = view().peek(keylet::account(account_)); + auto const sleSrc = view().peek(keylet::account(accountID_)); if (!sleSrc) return tefINTERNAL; // LCOV_EXCL_LINE @@ -601,10 +601,10 @@ Payment::doApply() auto const reserve = view().fees().accountReserve(ownerCount); // In a delegated payment, the fee payer is the delegated account, - // not the source account (account_). - bool const accountIsPayer = (ctx_.tx.getFeePayer() == account_); + // not the source account (accountID_). + bool const accountIsPayer = (ctx_.tx.getFeePayer() == accountID_); - // preFeeBalance_ is the balance on the source account (account_) BEFORE the fees + // preFeeBalance_ is the balance on the source account (accountID_) BEFORE the fees // were charged. If source account is the fee payer, it must also cover the fee. // The final spend may use the reserve to cover fees. auto const minRequiredFunds = @@ -656,7 +656,7 @@ Payment::doApply() if (dstAmount > dstReserve || sleDst->getFieldAmount(sfBalance) > dstReserve) { if (auto err = verifyDepositPreauth( - ctx_.tx, ctx_.view(), account_, dstAccountID, sleDst, ctx_.journal); + ctx_.tx, ctx_.view(), accountID_, dstAccountID, sleDst, ctx_.journal); !isTesSuccess(err)) return err; } diff --git a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.cpp b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.cpp index b8de9b911e..e36a0eb584 100644 --- a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.cpp +++ b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.cpp @@ -55,7 +55,7 @@ PermissionedDomainDelete::doApply() auto const slePd = view().peek(keylet::permissionedDomain(ctx_.tx.at(sfDomainID))); auto const page = (*slePd)[sfOwnerNode]; - if (!view().dirRemove(keylet::ownerDir(account_), page, slePd->key(), true)) + if (!view().dirRemove(keylet::ownerDir(accountID_), page, slePd->key(), true)) { // LCOV_EXCL_START JLOG(j_.fatal()) << "Unable to delete permissioned domain directory entry."; @@ -63,7 +63,7 @@ PermissionedDomainDelete::doApply() // LCOV_EXCL_STOP } - auto const ownerSle = view().peek(keylet::account(account_)); + auto const ownerSle = view().peek(keylet::account(accountID_)); XRPL_ASSERT( ownerSle && ownerSle->getFieldU32(sfOwnerCount) > 0, "xrpl::PermissionedDomainDelete::doApply : nonzero owner count"); diff --git a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp index bd7f6a33a1..ff4019ec59 100644 --- a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp +++ b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp @@ -77,7 +77,7 @@ PermissionedDomainSet::preclaim(PreclaimContext const& ctx) TER PermissionedDomainSet::doApply() { - auto const ownerSle = view().peek(keylet::account(account_)); + auto const ownerSle = view().peek(keylet::account(accountID_)); if (!ownerSle) return tefINTERNAL; // LCOV_EXCL_LINE @@ -112,14 +112,14 @@ PermissionedDomainSet::doApply() bool const fixEnabled = view().rules().enabled(fixCleanup3_1_3); auto const seq = fixEnabled ? ctx_.tx.getSeqValue() : ctx_.tx.getFieldU32(sfSequence); - Keylet const pdKeylet = keylet::permissionedDomain(account_, seq); + Keylet const pdKeylet = keylet::permissionedDomain(accountID_, seq); auto slePd = std::make_shared(pdKeylet); - slePd->setAccountID(sfOwner, account_); + slePd->setAccountID(sfOwner, accountID_); slePd->setFieldU32(sfSequence, seq); slePd->peekFieldArray(sfAcceptedCredentials) = std::move(sortedLE); auto const page = - view().dirInsert(keylet::ownerDir(account_), pdKeylet, describeOwnerDir(account_)); + view().dirInsert(keylet::ownerDir(accountID_), pdKeylet, describeOwnerDir(accountID_)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE diff --git a/src/libxrpl/tx/transactors/system/Change.cpp b/src/libxrpl/tx/transactors/system/Change.cpp index 9e9850f5a1..92a06fd807 100644 --- a/src/libxrpl/tx/transactors/system/Change.cpp +++ b/src/libxrpl/tx/transactors/system/Change.cpp @@ -154,7 +154,7 @@ Change::doApply() void Change::preCompute() { - XRPL_ASSERT(account_ == beast::kZero, "xrpl::Change::preCompute : zero account"); + XRPL_ASSERT(accountID_ == beast::kZero, "xrpl::Change::preCompute : zero account"); } TER diff --git a/src/libxrpl/tx/transactors/system/TicketCreate.cpp b/src/libxrpl/tx/transactors/system/TicketCreate.cpp index e7673e0bff..f442ac223b 100644 --- a/src/libxrpl/tx/transactors/system/TicketCreate.cpp +++ b/src/libxrpl/tx/transactors/system/TicketCreate.cpp @@ -67,7 +67,7 @@ TicketCreate::preclaim(PreclaimContext const& ctx) TER TicketCreate::doApply() { - SLE::pointer const sleAccountRoot = view().peek(keylet::account(account_)); + SLE::pointer const sleAccountRoot = view().peek(keylet::account(accountID_)); if (!sleAccountRoot) return tefINTERNAL; // LCOV_EXCL_LINE @@ -100,15 +100,15 @@ TicketCreate::doApply() for (std::uint32_t i = 0; i < ticketCount; ++i) { std::uint32_t const curTicketSeq = firstTicketSeq + i; - Keylet const ticketKeylet = keylet::kTicket(account_, curTicketSeq); + Keylet const ticketKeylet = keylet::kTicket(accountID_, curTicketSeq); SLE::pointer const sleTicket = std::make_shared(ticketKeylet); - sleTicket->setAccountID(sfAccount, account_); + sleTicket->setAccountID(sfAccount, accountID_); sleTicket->setFieldU32(sfTicketSequence, curTicketSeq); view().insert(sleTicket); - auto const page = - view().dirInsert(keylet::ownerDir(account_), ticketKeylet, describeOwnerDir(account_)); + auto const page = view().dirInsert( + keylet::ownerDir(accountID_), ticketKeylet, describeOwnerDir(accountID_)); JLOG(j_.trace()) << "Creating ticket " << to_string(ticketKeylet.key) << ": " << (page ? "success" : "failure"); diff --git a/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp b/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp index eb1cb04fc7..382ea7d40e 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp @@ -148,7 +148,7 @@ MPTokenAuthorize::doApply() ctx_.view(), preFeeBalance_, tx[sfMPTokenIssuanceID], - account_, + accountID_, ctx_.journal, tx.getFlags(), tx[~sfHolder]); diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp index aa1cb559d2..1440b67309 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp @@ -159,7 +159,7 @@ MPTokenIssuanceCreate::doApply() j_, { .priorBalance = preFeeBalance_, - .account = account_, + .account = accountID_, .sequence = tx.getSeqValue(), .flags = tx.getFlags(), .maxAmount = tx[~sfMaximumAmount], diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceDestroy.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceDestroy.cpp index be03d78c64..46811508b7 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceDestroy.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceDestroy.cpp @@ -45,15 +45,15 @@ TER MPTokenIssuanceDestroy::doApply() { auto const mpt = view().peek(keylet::mptIssuance(ctx_.tx[sfMPTokenIssuanceID])); - if (account_ != mpt->getAccountID(sfIssuer)) + if (accountID_ != mpt->getAccountID(sfIssuer)) return tecINTERNAL; // LCOV_EXCL_LINE - if (!view().dirRemove(keylet::ownerDir(account_), (*mpt)[sfOwnerNode], mpt->key(), false)) + if (!view().dirRemove(keylet::ownerDir(accountID_), (*mpt)[sfOwnerNode], mpt->key(), false)) return tefBAD_LEDGER; // LCOV_EXCL_LINE view().erase(mpt); - adjustOwnerCount(view(), view().peek(keylet::account(account_)), -1, j_); + adjustOwnerCount(view(), view().peek(keylet::account(accountID_)), -1, j_); return tesSUCCESS; } diff --git a/src/libxrpl/tx/transactors/token/TrustSet.cpp b/src/libxrpl/tx/transactors/token/TrustSet.cpp index 7c99085071..a8ea786347 100644 --- a/src/libxrpl/tx/transactors/token/TrustSet.cpp +++ b/src/libxrpl/tx/transactors/token/TrustSet.cpp @@ -336,9 +336,9 @@ TrustSet::doApply() AccountID const uDstAccountID(saLimitAmount.getIssuer()); // true, if current is high account. - bool const bHigh = account_ > uDstAccountID; + bool const bHigh = accountID_ > uDstAccountID; - auto const sle = view().peek(keylet::account(account_)); + auto const sle = view().peek(keylet::account(accountID_)); if (!sle) return tefINTERNAL; // LCOV_EXCL_LINE @@ -391,10 +391,10 @@ TrustSet::doApply() } STAmount saLimitAllow = saLimitAmount; - saLimitAllow.get().account = account_; + saLimitAllow.get().account = accountID_; SLE::pointer const sleRippleState = - view().peek(keylet::line(account_, uDstAccountID, currency)); + view().peek(keylet::line(accountID_, uDstAccountID, currency)); if (sleRippleState) { @@ -406,8 +406,8 @@ TrustSet::doApply() std::uint32_t uLowQualityOut = 0; std::uint32_t uHighQualityIn = 0; std::uint32_t uHighQualityOut = 0; - auto const& uLowAccountID = !bHigh ? account_ : uDstAccountID; - auto const& uHighAccountID = bHigh ? account_ : uDstAccountID; + auto const& uLowAccountID = !bHigh ? accountID_ : uDstAccountID; + auto const& uHighAccountID = bHigh ? accountID_ : uDstAccountID; SLE::ref sleLowAccount = !bHigh ? sle : sleDst; SLE::ref sleHighAccount = bHigh ? sle : sleDst; @@ -642,7 +642,7 @@ TrustSet::doApply() // Zero balance in currency. STAmount const saBalance(Issue{currency, noAccount()}); - auto const k = keylet::line(account_, uDstAccountID, currency); + auto const k = keylet::line(accountID_, uDstAccountID, currency); JLOG(j_.trace()) << "doTrustSet: Creating ripple line: " << to_string(k.key); @@ -650,7 +650,7 @@ TrustSet::doApply() terResult = trustCreate( view(), bHigh, - account_, + accountID_, uDstAccountID, k.key, sle, diff --git a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp index 1bd61a0175..b5b2c1f384 100644 --- a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp @@ -349,7 +349,7 @@ VaultClawback::doApply() MPTIssue const share{mptIssuanceID}; Asset const vaultAsset = vault->at(sfAsset); - STAmount const amount = clawbackAmount(vault, tx[~sfAmount], account_); + STAmount const amount = clawbackAmount(vault, tx[~sfAmount], accountID_); auto assetsAvailable = vault->at(sfAssetsAvailable); auto assetsTotal = vault->at(sfAssetsTotal); @@ -364,7 +364,7 @@ VaultClawback::doApply() STAmount assetsRecovered = {vault->at(sfAsset)}; // The Owner is burning shares - if (account_ == vault->at(sfOwner) && amount.asset() == share) + if (accountID_ == vault->at(sfOwner) && amount.asset() == share) { sharesDestroyed = accountHolds( view(), holder, share, FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, j_); @@ -426,7 +426,7 @@ VaultClawback::doApply() { // Transfer assets from vault to issuer. if (auto const ter = accountSend( - view(), vaultAccount, account_, assetsRecovered, j_, WaiveTransferFee::Yes); + view(), vaultAccount, accountID_, assetsRecovered, j_, WaiveTransferFee::Yes); !isTesSuccess(ter)) return ter; diff --git a/src/libxrpl/tx/transactors/vault/VaultCreate.cpp b/src/libxrpl/tx/transactors/vault/VaultCreate.cpp index e1e321b2c6..c6e1f28d57 100644 --- a/src/libxrpl/tx/transactors/vault/VaultCreate.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultCreate.cpp @@ -145,13 +145,13 @@ VaultCreate::doApply() auto const& tx = ctx_.tx; auto const sequence = tx.getSeqValue(); - auto const owner = view().peek(keylet::account(account_)); + auto const owner = view().peek(keylet::account(accountID_)); if (owner == nullptr) return tefINTERNAL; // LCOV_EXCL_LINE - auto vault = std::make_shared(keylet::vault(account_, sequence)); + auto vault = std::make_shared(keylet::vault(accountID_, sequence)); - if (auto ter = dirLink(view(), account_, vault)) + if (auto ter = dirLink(view(), accountID_, vault)) return ter; // We will create Vault and PseudoAccount, hence increase OwnerCount by 2 adjustOwnerCount(view(), owner, 2, j_); @@ -204,7 +204,7 @@ VaultCreate::doApply() vault->setFieldIssue(sfAsset, STIssue{sfAsset, asset}); vault->at(sfFlags) = tx.getFlags() & tfVaultPrivate; vault->at(sfSequence) = sequence; - vault->at(sfOwner) = account_; + vault->at(sfOwner) = accountID_; vault->at(sfAccount) = pseudoId; vault->at(sfAssetsTotal) = Number(0); vault->at(sfAssetsAvailable) = Number(0); @@ -230,7 +230,7 @@ VaultCreate::doApply() // Explicitly create MPToken for the vault owner if (auto const err = - authorizeMPToken(view(), preFeeBalance_, mptIssuanceID, account_, ctx_.journal); + authorizeMPToken(view(), preFeeBalance_, mptIssuanceID, accountID_, ctx_.journal); !isTesSuccess(err)) return err; @@ -238,7 +238,7 @@ VaultCreate::doApply() if (tx.isFlag(tfVaultPrivate)) { if (auto const err = authorizeMPToken( - view(), preFeeBalance_, mptIssuanceID, pseudoId, ctx_.journal, {}, account_); + view(), preFeeBalance_, mptIssuanceID, pseudoId, ctx_.journal, {}, accountID_); !isTesSuccess(err)) return err; } diff --git a/src/libxrpl/tx/transactors/vault/VaultDelete.cpp b/src/libxrpl/tx/transactors/vault/VaultDelete.cpp index fc34aba150..438896e7ed 100644 --- a/src/libxrpl/tx/transactors/vault/VaultDelete.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultDelete.cpp @@ -122,16 +122,16 @@ VaultDelete::doApply() } // Try to remove MPToken for vault shares for the vault owner if it exists. - if (auto const mptoken = view().peek(keylet::mptoken(shareMPTID, account_))) + if (auto const mptoken = view().peek(keylet::mptoken(shareMPTID, accountID_))) { - if (auto const ter = removeEmptyHolding(view(), account_, MPTIssue(shareMPTID), j_); + if (auto const ter = removeEmptyHolding(view(), accountID_, MPTIssue(shareMPTID), j_); !isTesSuccess(ter)) { // LCOV_EXCL_START JLOG(j_.error()) // << "VaultDelete: failed to remove vault owner's MPToken" - << " MPTID=" << to_string(shareMPTID) // - << " account=" << toBase58(account_) // + << " MPTID=" << to_string(shareMPTID) // + << " account=" << toBase58(accountID_) // << " with result: " << transToken(ter); return ter; // LCOV_EXCL_STOP diff --git a/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp b/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp index a378c4b991..b8230b90c8 100644 --- a/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp @@ -156,20 +156,20 @@ VaultDeposit::doApply() auto const& vaultAccount = vault->at(sfAccount); // Note, vault owner is always authorized - if (vault->isFlag(lsfVaultPrivate) && account_ != vault->at(sfOwner)) + if (vault->isFlag(lsfVaultPrivate) && accountID_ != vault->at(sfOwner)) { if (auto const err = enforceMPTokenAuthorization( - ctx_.view(), mptIssuanceID, account_, preFeeBalance_, j_); + ctx_.view(), mptIssuanceID, accountID_, preFeeBalance_, j_); !isTesSuccess(err)) return err; } - else // !vault->isFlag(lsfVaultPrivate) || account_ == vault->at(sfOwner) + else // !vault->isFlag(lsfVaultPrivate) || accountID_ == vault->at(sfOwner) { // No authorization needed, but must ensure there is MPToken - if (!view().exists(keylet::mptoken(mptIssuanceID, account_))) + if (!view().exists(keylet::mptoken(mptIssuanceID, accountID_))) { if (auto const err = authorizeMPToken( - view(), preFeeBalance_, mptIssuanceID->value(), account_, ctx_.journal); + view(), preFeeBalance_, mptIssuanceID->value(), accountID_, ctx_.journal); !isTesSuccess(err)) return err; } @@ -179,15 +179,15 @@ VaultDeposit::doApply() { // This follows from the reverse of the outer enclosing if condition XRPL_ASSERT( - account_ == vault->at(sfOwner), "xrpl::VaultDeposit::doApply : account is owner"); + accountID_ == vault->at(sfOwner), "xrpl::VaultDeposit::doApply : account is owner"); if (auto const err = authorizeMPToken( view(), preFeeBalance_, // priorBalance mptIssuanceID->value(), // mptIssuanceID sleIssuance->at(sfIssuer), // account ctx_.journal, - {}, // flags - account_ // holderID + {}, // flags + accountID_ // holderID ); !isTesSuccess(err)) return err; @@ -247,15 +247,15 @@ VaultDeposit::doApply() return tecLIMIT_EXCEEDED; // Transfer assets from depositor to vault. - if (auto const ter = - accountSend(view(), account_, vaultAccount, assetsDeposited, j_, WaiveTransferFee::Yes); + if (auto const ter = accountSend( + view(), accountID_, vaultAccount, assetsDeposited, j_, WaiveTransferFee::Yes); !isTesSuccess(ter)) return ter; // Sanity check if (accountHolds( view(), - account_, + accountID_, assetsDeposited.asset(), FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, @@ -269,7 +269,7 @@ VaultDeposit::doApply() // Transfer shares from vault to depositor. if (auto const ter = - accountSend(view(), vaultAccount, account_, sharesCreated, j_, WaiveTransferFee::Yes); + accountSend(view(), vaultAccount, accountID_, sharesCreated, j_, WaiveTransferFee::Yes); !isTesSuccess(ter)) return ter; diff --git a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp index ddfc788928..136f9e17c6 100644 --- a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp @@ -222,7 +222,7 @@ VaultWithdraw::doApply() } if (accountHolds( - view(), account_, share, FreezeHandling::ZeroIfFrozen, AuthHandling::IgnoreAuth, j_) < + view(), accountID_, share, FreezeHandling::ZeroIfFrozen, AuthHandling::IgnoreAuth, j_) < sharesRedeemed) { JLOG(j_.debug()) << "VaultWithdraw: account doesn't hold enough shares"; @@ -251,23 +251,23 @@ VaultWithdraw::doApply() auto const& vaultAccount = vault->at(sfAccount); // Transfer shares from depositor to vault. - if (auto const ter = - accountSend(view(), account_, vaultAccount, sharesRedeemed, j_, WaiveTransferFee::Yes); + if (auto const ter = accountSend( + view(), accountID_, vaultAccount, sharesRedeemed, j_, WaiveTransferFee::Yes); !isTesSuccess(ter)) return ter; // Try to remove MPToken for shares, if the account balance is zero. Vault // pseudo-account will never set lsfMPTAuthorized, so we ignore flags. // Keep MPToken if holder is the vault owner. - if (account_ != vault->at(sfOwner)) + if (accountID_ != vault->at(sfOwner)) { - if (auto const ter = removeEmptyHolding(view(), account_, sharesRedeemed.asset(), j_); + if (auto const ter = removeEmptyHolding(view(), accountID_, sharesRedeemed.asset(), j_); isTesSuccess(ter)) { JLOG(j_.debug()) // << "VaultWithdraw: removed empty MPToken for vault shares" << " MPTID=" << to_string(mptIssuanceID) // - << " account=" << toBase58(account_); + << " account=" << toBase58(accountID_); } else if (ter != tecHAS_OBLIGATIONS) { @@ -275,7 +275,7 @@ VaultWithdraw::doApply() JLOG(j_.error()) // << "VaultWithdraw: failed to remove MPToken for vault shares" << " MPTID=" << to_string(mptIssuanceID) // - << " account=" << toBase58(account_) // + << " account=" << toBase58(accountID_) // << " with result: " << transToken(ter); return ter; // LCOV_EXCL_STOP @@ -283,12 +283,12 @@ VaultWithdraw::doApply() // else quietly ignore, account balance is not zero } - auto const dstAcct = ctx_.tx[~sfDestination].value_or(account_); + auto const dstAcct = ctx_.tx[~sfDestination].value_or(accountID_); associateAsset(*vault, vaultAsset); return doWithdraw( - view(), ctx_.tx, account_, dstAcct, vaultAccount, preFeeBalance_, assetsWithdrawn, j_); + view(), ctx_.tx, accountID_, dstAcct, vaultAccount, preFeeBalance_, assetsWithdrawn, j_); } void From ad3d172a1f0a6bcac7a3d18c2cb15366ee5b1e47 Mon Sep 17 00:00:00 2001 From: Denis Angell Date: Mon, 18 May 2026 22:08:48 +0200 Subject: [PATCH 05/17] fix: Use account ledger entry when canceling token escrows (#6171) --- .../tx/transactors/escrow/EscrowCancel.cpp | 2 +- src/test/app/EscrowToken_test.cpp | 66 +++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp b/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp index 99cf467ee9..123f83a1a6 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp @@ -184,7 +184,7 @@ EscrowCancel::doApply() return escrowUnlockApplyHelper( ctx_.view(), kParityRate, - slep, + ctx_.view().rules().enabled(fixCleanup3_2_0) ? sle : slep, preFeeBalance_, amount, issuer, diff --git a/src/test/app/EscrowToken_test.cpp b/src/test/app/EscrowToken_test.cpp index 82dd067bdc..5bb1303dba 100644 --- a/src/test/app/EscrowToken_test.cpp +++ b/src/test/app/EscrowToken_test.cpp @@ -886,6 +886,70 @@ struct EscrowToken_test : public beast::unit_test::Suite } } + void + testIOUCancelDoApply(FeatureBitset features) + { + testcase("IOU Cancel DoApply"); + using namespace jtx; + using namespace std::literals; + + { + Env env{*this, features}; + auto const baseFee = env.current()->fees().base; + auto const alice = Account("alice"); + auto const bob = Account("bob"); + auto const gw = Account("gw"); + auto const usd = gw["USD"]; + + env.fund(XRP(10'000), alice, bob, gw); + env.close(); + + env(fset(gw, asfAllowTrustLineLocking)); + env.close(); + + env.trust(usd(100'000), alice); + env.trust(usd(100'000), bob); + env.close(); + + env(pay(gw, alice, usd(10'000))); + env.close(); + + auto const seq = env.seq(alice); + env(escrow::create(alice, bob, usd(1'000)), + escrow::kFinishTime(env.now() + 1s), + escrow::kCancelTime(env.now() + 2s), + Fee(baseFee)); + env.close(); + + BEAST_EXPECT(env.balance(alice, usd) == usd(9'000)); + + env(pay(alice, gw, usd(9'000))); + env.close(); + + env(trust(alice, usd(0))); + env.close(); + + auto const trustLineKey = keylet::line(alice.id(), gw.id(), usd.currency); + BEAST_EXPECT(!env.current()->exists(trustLineKey)); + + env.close(); + env.close(); + + auto const expectedResult = env.current()->rules().enabled(fixCleanup3_2_0) + ? Ter(tesSUCCESS) + : Ter(tefEXCEPTION); + env(escrow::cancel(alice, alice, seq), Fee(baseFee), expectedResult); + env.close(); + + if (env.current()->rules().enabled(fixCleanup3_2_0)) + { + BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), seq))); + BEAST_EXPECT(env.current()->exists(trustLineKey)); + BEAST_EXPECT(env.balance(alice, usd) == usd(1'000)); + } + } + } + void testIOUBalances(FeatureBitset features) { @@ -3887,6 +3951,7 @@ struct EscrowToken_test : public beast::unit_test::Suite testIOUFinishPreclaim(features); testIOUFinishDoApply(features); testIOUCancelPreclaim(features); + testIOUCancelDoApply(features); testIOUBalances(features); testIOUMetaAndOwnership(features); testIOURippleState(features); @@ -3928,6 +3993,7 @@ public: {all - featureSingleAssetVault - featureLendingProtocol, all}) { testIOUWithFeats(feats); + testIOUWithFeats(feats - fixCleanup3_2_0); testMPTWithFeats(feats); testMPTWithFeats(feats - fixTokenEscrowV1); } From 1e45d363c56e45ac46f4a7c9295f916193bd4100 Mon Sep 17 00:00:00 2001 From: Fomo <508629+shortthefomo@users.noreply.github.com> Date: Tue, 19 May 2026 02:05:47 -0400 Subject: [PATCH 06/17] fix: Set default peering port to 2459 (#6848) Co-authored-by: Bart --- cfg/xrpld-example.cfg | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/cfg/xrpld-example.cfg b/cfg/xrpld-example.cfg index 5de61bb6d1..effc62c274 100644 --- a/cfg/xrpld-example.cfg +++ b/cfg/xrpld-example.cfg @@ -1466,10 +1466,7 @@ admin = 127.0.0.1 protocol = http [port_peer] -# Many servers still use the legacy port of 51235, so for backward-compatibility -# we maintain that port number here. However, for new servers we recommend -# changing this to the default port of 2459. -port = 51235 +port = 2459 ip = 0.0.0.0 # alternatively, to accept connections on IPv4 + IPv6, use: #ip = :: From 8d1083e5ea7c55c67af903c93dfedf990e71a2a0 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Tue, 19 May 2026 14:15:11 +0100 Subject: [PATCH 07/17] ci: Only run reusable package in public repos (#7293) --- .github/workflows/reusable-package.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/reusable-package.yml b/.github/workflows/reusable-package.yml index ad73cd8733..ec019b2e7e 100644 --- a/.github/workflows/reusable-package.yml +++ b/.github/workflows/reusable-package.yml @@ -58,6 +58,7 @@ jobs: package: needs: [generate-matrix, generate-version] + if: ${{ github.event.repository.visibility == 'public' }} strategy: fail-fast: false matrix: ${{ fromJson(needs.generate-matrix.outputs.matrix) }} @@ -89,7 +90,6 @@ jobs: - name: Upload package artifact uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 - if: ${{ github.event.repository.visibility == 'public' }} with: name: ${{ matrix.artifact_name }}-pkg-${{ needs.generate-version.outputs.version }} path: | From d9a3af82078d596b169de80bb4bda4d19ad58bb1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 19 May 2026 16:35:38 +0000 Subject: [PATCH 08/17] ci: [DEPENDABOT] bump actions/upload-artifact from 7.0.0 to 7.0.1 (#7286) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/reusable-package.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/reusable-package.yml b/.github/workflows/reusable-package.yml index ec019b2e7e..5108a55cd2 100644 --- a/.github/workflows/reusable-package.yml +++ b/.github/workflows/reusable-package.yml @@ -89,7 +89,7 @@ jobs: run: ./package/build_pkg.sh - name: Upload package artifact - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: ${{ matrix.artifact_name }}-pkg-${{ needs.generate-version.outputs.version }} path: | From 93ac1aa7aa23f801b0840a87804a6d755c944623 Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Tue, 19 May 2026 18:38:50 +0200 Subject: [PATCH 09/17] fix: Disable unnecessary sanity-check in VaultDeposit (#7288) --- .../tx/transactors/vault/VaultDeposit.cpp | 32 +++++--- src/test/app/Vault_test.cpp | 80 +++++++++++++++++++ 2 files changed, 100 insertions(+), 12 deletions(-) diff --git a/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp b/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp index b8230b90c8..aaaf3cced8 100644 --- a/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -252,19 +253,26 @@ VaultDeposit::doApply() !isTesSuccess(ter)) return ter; - // Sanity check - if (accountHolds( - view(), - accountID_, - assetsDeposited.asset(), - FreezeHandling::IgnoreFreeze, - AuthHandling::IgnoreAuth, - j_) < beast::kZero) + // This check is wrong. Disable it with fixCleanup3_2_0. + // For XRP and MPT the predicate is structurally unsatisfiable: xrpLiquid clamps at zero, and + // MPT balances are unsigned. For IOUs it only fires when the deposit drove the depositor's + // trust line into debt the exact case preclaim authorizes via SpendableHandling::FullBalance. + // The check thus converts a preclaim- authorized deposit into tefINTERNAL after the asset + // transfer. + if (!view().rules().enabled(fixCleanup3_2_0)) { - // LCOV_EXCL_START - JLOG(j_.error()) << "VaultDeposit: negative balance of account assets."; - return tefINTERNAL; - // LCOV_EXCL_STOP + // Sanity check + if (accountHolds( + view(), + accountID_, + assetsDeposited.asset(), + FreezeHandling::IgnoreFreeze, + AuthHandling::IgnoreAuth, + j_) < beast::kZero) + { + JLOG(j_.error()) << "VaultDeposit: negative balance of account assets."; + return tefINTERNAL; + } } // Transfer shares from vault to depositor. diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index cd4c35f1a5..318a6dc45c 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -6140,10 +6140,90 @@ class Vault_test : public beast::unit_test::Suite runTest(amendments); } + // VaultDeposit::preclaim uses accountHolds(..., SpendableHandling:: + // shFULL_BALANCE), which for an IOU asset adds the counterparty's + // LowLimit/HighLimit to the depositor's raw balance (TokenHelpers.cpp: + // getTrustLineBalance with includeOppositeLimit=true). When the + // depositor's raw balance < deposit amount but raw + opposite limit >= + // amount, preclaim is satisfied. doApply then calls + // directSendNoFeeIOU, which unconditionally subtracts saAmount from + // saBalance — driving the trust line negative — and returns tesSUCCESS. + // The post-send sanity check uses the default shSIMPLE_BALANCE (no + // opposite-limit add), sees a negative balance, and returns tefINTERNAL. + void + testVaultDepositNegativeBalanceFromOppositeLimit() + { + auto runTest = [&](FeatureBitset f, TER expected) { + using namespace test::jtx; + using namespace std::literals; + + Env env{*this, f}; + Account const gw{"gateway"}; + Account const owner{"owner"}; + Account const depositor{"depositor"}; + + env.fund(XRP(10000), gw, owner, depositor); + env.close(); + + // Gateway with DefaultRipple so vault creation on its IOU works. + env(fset(gw, asfDefaultRipple)); + env.close(); + + // Depositor opens a trust line to gateway and receives a small + // balance. + PrettyAsset const usd = gw["USD"]; + env.trust(usd(1000), depositor); + env(pay(gw, depositor, usd(100))); // raw trust-line balance: 100 + env.close(); + + // Key precondition: gateway sets a non-zero limit on the same + // RippleState — the "opposite field" from depositor's perspective. + // This is what inflates shFULL_BALANCE in preclaim above the raw + // balance. + env(trust(gw, depositor["USD"](1000))); + env.close(); + + // Create the IOU vault. + Vault const vault{env}; + auto [vaultTx, keylet] = vault.create({.owner = owner, .asset = usd}); + env(vaultTx); + env.close(); + + // Submit a deposit of 500 USD: + // - raw balance: 100 USD + // - opposite limit (gw's side): 1000 USD + // - preclaim sees 100 + 1000 = 1100, passes (>= 500) + // - doApply transfers 500, depositor's trust-line balance + // becomes -400 + // - sanity check at VaultDeposit.cpp:256 fires + // - tx returns tefINTERNAL (BUG — should be tesSUCCESS. + auto depositTx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = usd(500)}); + env(depositTx, Ter(expected)); + env.close(); + }; + + { + testcase( + "IOU vault deposit exceeding depositor's balance but " + "within counterparty's trust limit, pre-fixCleanup3_2_0 " + "(tefINTERNAL)"); + runTest(test::jtx::testableAmendments() - fixCleanup3_2_0, tefINTERNAL); + } + { + testcase( + "IOU vault deposit exceeding depositor's balance but " + "within counterparty's trust limit, post-fixCleanup3_2_0 " + "(tesSUCCESS)"); + runTest(test::jtx::testableAmendments(), tesSUCCESS); + } + } + public: void run() override { + testVaultDepositNegativeBalanceFromOppositeLimit(); testSequences(); testPreflight(); testCreateFailXRP(); From 9cb049276dcf166540f74bfc85c9d8581a163527 Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Wed, 20 May 2026 21:44:09 +0200 Subject: [PATCH 10/17] feat: Propagate underlying MPT flags to vault shares (#7077) Signed-off-by: dependabot[bot] Co-authored-by: Denis Angell Co-authored-by: Fomo <508629+shortthefomo@users.noreply.github.com> Co-authored-by: Bart Co-authored-by: Ayaz Salikhov Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- include/xrpl/ledger/View.h | 2 +- include/xrpl/ledger/helpers/MPTokenHelpers.h | 70 +- .../xrpl/ledger/helpers/RippleStateHelpers.h | 4 +- include/xrpl/ledger/helpers/TokenHelpers.h | 33 +- .../xrpl/protocol/detail/ledger_entries.macro | 1 + include/xrpl/protocol/detail/sfields.macro | 1 + .../ledger_entries/MPTokenIssuance.h | 35 + include/xrpl/tx/invariants/MPTInvariant.h | 15 + .../transactors/token/MPTokenIssuanceCreate.h | 23 +- src/libxrpl/ledger/View.cpp | 31 +- src/libxrpl/ledger/helpers/MPTokenHelpers.cpp | 153 +++- src/libxrpl/ledger/helpers/TokenHelpers.cpp | 28 +- src/libxrpl/tx/invariants/MPTInvariant.cpp | 88 +++ .../lending/LoanBrokerCoverWithdraw.cpp | 10 +- .../token/MPTokenIssuanceCreate.cpp | 22 + .../tx/transactors/vault/VaultCreate.cpp | 26 +- .../tx/transactors/vault/VaultWithdraw.cpp | 9 +- src/test/app/Invariants_test.cpp | 110 ++- src/test/app/Loan_test.cpp | 229 ++++-- src/test/app/MPToken_test.cpp | 19 +- src/test/app/Vault_test.cpp | 680 +++++++++++++++++- .../ledger_entries/MPTokenIssuanceTests.cpp | 27 + 22 files changed, 1483 insertions(+), 133 deletions(-) diff --git a/include/xrpl/ledger/View.h b/include/xrpl/ledger/View.h index 4958a89d8c..0d76c98a73 100644 --- a/include/xrpl/ledger/View.h +++ b/include/xrpl/ledger/View.h @@ -57,7 +57,7 @@ isVaultPseudoAccountFrozen( ReadView const& view, AccountID const& account, MPTIssue const& mptShare, - int depth); + std::uint8_t depth); [[nodiscard]] bool isLPTokenFrozen( diff --git a/include/xrpl/ledger/helpers/MPTokenHelpers.h b/include/xrpl/ledger/helpers/MPTokenHelpers.h index 6544b18dd1..491bd1933e 100644 --- a/include/xrpl/ledger/helpers/MPTokenHelpers.h +++ b/include/xrpl/ledger/helpers/MPTokenHelpers.h @@ -27,14 +27,18 @@ isGlobalFrozen(ReadView const& view, MPTIssue const& mptIssue); isIndividualFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue); [[nodiscard]] bool -isFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth = 0); +isFrozen( + ReadView const& view, + AccountID const& account, + MPTIssue const& mptIssue, + std::uint8_t depth = 0); [[nodiscard]] bool isAnyFrozen( ReadView const& view, std::initializer_list const& accounts, MPTIssue const& mptIssue, - int depth = 0); + std::uint8_t depth = 0); //------------------------------------------------------------------------------ // @@ -88,7 +92,7 @@ requireAuth( MPTIssue const& mptIssue, AccountID const& account, AuthType authType = AuthType::Legacy, - int depth = 0); + std::uint8_t depth = 0); /** Enforce account has MPToken to match its authorization. * @@ -104,22 +108,68 @@ enforceMPTokenAuthorization( XRPAmount const& priorBalance, beast::Journal j); -/** Check if the destination account is allowed - * to receive MPT. Return tecNO_AUTH if it doesn't - * and tesSUCCESS otherwise. +/** Resolve the underlying asset of a vault share. + * + * Reads sfReferenceHolding from @p sleShareIssuance to determine which + * asset the vault wraps. @p sleHolding must be the SLE that + * sfReferenceHolding points to — either an ltMPTOKEN (returns its + * MPTIssue) or an ltRIPPLE_STATE (returns its low/high Issue). + * + * @pre Both SLEs must exist and @p sleHolding must be of type ltMPTOKEN + * or ltRIPPLE_STATE. Passing any other type is undefined behaviour. + * @param sleShareIssuance MPTokenIssuance SLE for the vault share token. + * @param sleHolding SLE referenced by sfReferenceHolding. + * @return The underlying Asset (MPTIssue or Issue). + */ +[[nodiscard]] Asset +assetOfHolding(SLE const& sleShareIssuance, SLE const& sleHolding); + +/** Check whether @p to may receive the given MPT from @p from. + * + * The check passes when any of the following is true: + * - @p waive is WaiveMPTCanTransfer::Yes (recovery-path exemption), or + * - @p from or @p to is the issuer, or + * - lsfMPTCanTransfer is set on the MPTokenIssuance. + * + * For vault shares (MPTokenIssuances that carry sfReferenceHolding) the + * check recurses into the underlying asset's transferability. This + * recursion is defensive; vault-of-vault-shares is rejected at vault + * creation, so in practice depth never exceeds 1. + * + * @param view Ledger state to read from. + * @param mptIssue The MPT issuance being transferred. + * @param from Sending account. + * @param to Receiving account. + * @param waive WaiveMPTCanTransfer::Yes skips the lsfMPTCanTransfer + * check. Use for recovery paths (e.g. unwinding SAV or + * Lending Protocol positions after an issuer revokes + * transferability). + * @param depth Recursion depth; bounded at kMaxAssetCheckDepth. + * @return tesSUCCESS if the transfer is allowed, tecNO_AUTH otherwise. */ [[nodiscard]] TER canTransfer( ReadView const& view, MPTIssue const& mptIssue, AccountID const& from, - AccountID const& to); + AccountID const& to, + WaiveMPTCanTransfer waive = WaiveMPTCanTransfer::No, + std::uint8_t depth = 0); -/** Check if Asset can be traded on DEX. return tecNO_PERMISSION - * if it doesn't and tesSUCCESS otherwise. +/** Check whether @p asset may be traded on the DEX. + * + * For IOU assets the check delegates to the existing offer/AMM freeze + * logic. For MPT assets it checks lsfMPTCanTrade on the MPTokenIssuance. + * Vault shares recurse into the underlying asset's tradability via + * sfReferenceHolding; depth is bounded at kMaxAssetCheckDepth. + * + * @param view Ledger state to read from. + * @param asset The asset to check. + * @param depth Recursion depth; bounded at kMaxAssetCheckDepth. + * @return tesSUCCESS if trading is allowed, tecNO_PERMISSION otherwise. */ [[nodiscard]] TER -canTrade(ReadView const& view, Asset const& asset); +canTrade(ReadView const& view, Asset const& asset, std::uint8_t depth = 0); //------------------------------------------------------------------------------ // diff --git a/include/xrpl/ledger/helpers/RippleStateHelpers.h b/include/xrpl/ledger/helpers/RippleStateHelpers.h index 17b0f7673e..2616a6d5c9 100644 --- a/include/xrpl/ledger/helpers/RippleStateHelpers.h +++ b/include/xrpl/ledger/helpers/RippleStateHelpers.h @@ -93,7 +93,7 @@ isFrozen(ReadView const& view, AccountID const& account, Issue const& issue) // Overload with depth parameter for uniformity with MPTIssue version. // The depth parameter is ignored for IOUs since they don't have vault recursion. [[nodiscard]] inline bool -isFrozen(ReadView const& view, AccountID const& account, Issue const& issue, int /*depth*/) +isFrozen(ReadView const& view, AccountID const& account, Issue const& issue, std::uint8_t /*depth*/) { return isFrozen(view, account, issue); } @@ -110,7 +110,7 @@ isDeepFrozen( ReadView const& view, AccountID const& account, Issue const& issue, - int = 0 /*ignored*/) + std::uint8_t = 0 /*ignored*/) { return isDeepFrozen(view, account, issue.currency, issue.account); } diff --git a/include/xrpl/ledger/helpers/TokenHelpers.h b/include/xrpl/ledger/helpers/TokenHelpers.h index 3d41ac47cd..b47286a5d5 100644 --- a/include/xrpl/ledger/helpers/TokenHelpers.h +++ b/include/xrpl/ledger/helpers/TokenHelpers.h @@ -34,6 +34,15 @@ enum class WaiveTransferFee : bool { No = false, Yes }; /** Controls whether accountSend is allowed to overflow OutstandingAmount **/ enum class AllowMPTOverflow : bool { No = false, Yes }; +/** Controls whether canTransfer enforces lsfMPTCanTransfer on MPTs. + * + * Default is No (enforce). Use Yes at call sites that must remain available + * even when an MPT issuer has cleared lsfMPTCanTransfer - for example, + * unwinding existing positions in SAV or the Lending Protocol. Has no + * effect on the IOU branch of canTransfer. + */ +enum class WaiveMPTCanTransfer : bool { No = false, Yes }; + /* Check if MPToken (for MPT) or trust line (for IOU) exists: * - StrongAuth - before checking if authorization is required * - WeakAuth @@ -63,7 +72,11 @@ isIndividualFrozen(ReadView const& view, AccountID const& account, Asset const& * purely defensive, as we currently do not allow such vaults to be created. */ [[nodiscard]] bool -isFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth = 0); +isFrozen( + ReadView const& view, + AccountID const& account, + Asset const& asset, + std::uint8_t depth = 0); [[nodiscard]] TER checkFrozen(ReadView const& view, AccountID const& account, Issue const& issue); @@ -85,14 +98,14 @@ isAnyFrozen( ReadView const& view, std::initializer_list const& accounts, Asset const& asset, - int depth = 0); + std::uint8_t depth = 0); [[nodiscard]] bool isDeepFrozen( ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, - int depth = 0); + std::uint8_t depth = 0); /** * isFrozen check is recursive for MPT shares in a vault, descending to @@ -100,7 +113,11 @@ isDeepFrozen( * purely defensive, as we currently do not allow such vaults to be created. */ [[nodiscard]] bool -isDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth = 0); +isDeepFrozen( + ReadView const& view, + AccountID const& account, + Asset const& asset, + std::uint8_t depth = 0); [[nodiscard]] TER checkDeepFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue); @@ -234,7 +251,13 @@ requireAuth( AuthType authType = AuthType::Legacy); [[nodiscard]] TER -canTransfer(ReadView const& view, Asset const& asset, AccountID const& from, AccountID const& to); +canTransfer( + ReadView const& view, + Asset const& asset, + AccountID const& from, + AccountID const& to, + WaiveMPTCanTransfer waive = WaiveMPTCanTransfer::No, + std::uint8_t depth = 0); //------------------------------------------------------------------------------ // diff --git a/include/xrpl/protocol/detail/ledger_entries.macro b/include/xrpl/protocol/detail/ledger_entries.macro index c4b392a92f..19b8b44fe6 100644 --- a/include/xrpl/protocol/detail/ledger_entries.macro +++ b/include/xrpl/protocol/detail/ledger_entries.macro @@ -400,6 +400,7 @@ LEDGER_ENTRY(ltMPTOKEN_ISSUANCE, 0x007e, MPTokenIssuance, mpt_issuance, ({ {sfPreviousTxnLgrSeq, SoeRequired}, {sfDomainID, SoeOptional}, {sfMutableFlags, SoeDefault}, + {sfReferenceHolding, SoeOptional}, })) /** A ledger object which tracks MPToken diff --git a/include/xrpl/protocol/detail/sfields.macro b/include/xrpl/protocol/detail/sfields.macro index 5d1689dce9..01bb4fc480 100644 --- a/include/xrpl/protocol/detail/sfields.macro +++ b/include/xrpl/protocol/detail/sfields.macro @@ -205,6 +205,7 @@ TYPED_SFIELD(sfParentBatchID, UINT256, 36) TYPED_SFIELD(sfLoanBrokerID, UINT256, 37, SField::kSmdPseudoAccount | SField::kSmdDefault) TYPED_SFIELD(sfLoanID, UINT256, 38) +TYPED_SFIELD(sfReferenceHolding, UINT256, 39) // number (common) TYPED_SFIELD(sfNumber, NUMBER, 1) diff --git a/include/xrpl/protocol_autogen/ledger_entries/MPTokenIssuance.h b/include/xrpl/protocol_autogen/ledger_entries/MPTokenIssuance.h index 8377fdf1a4..7f772b1c74 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/MPTokenIssuance.h +++ b/include/xrpl/protocol_autogen/ledger_entries/MPTokenIssuance.h @@ -278,6 +278,30 @@ public: { return this->sle_->isFieldPresent(sfMutableFlags); } + + /** + * @brief Get sfReferenceHolding (SoeOptional) + * @return The field value, or std::nullopt if not present. + */ + [[nodiscard]] + protocol_autogen::Optional + getReferenceHolding() const + { + if (hasReferenceHolding()) + return this->sle_->at(sfReferenceHolding); + return std::nullopt; + } + + /** + * @brief Check if sfReferenceHolding is present. + * @return True if the field is present, false otherwise. + */ + [[nodiscard]] + bool + hasReferenceHolding() const + { + return this->sle_->isFieldPresent(sfReferenceHolding); + } }; /** @@ -469,6 +493,17 @@ public: return *this; } + /** + * @brief Set sfReferenceHolding (SoeOptional) + * @return Reference to this builder for method chaining. + */ + MPTokenIssuanceBuilder& + setReferenceHolding(std::decay_t const& value) + { + object_[sfReferenceHolding] = value; + return *this; + } + /** * @brief Build and return the completed MPTokenIssuance wrapper. * @param index The ledger entry index. diff --git a/include/xrpl/tx/invariants/MPTInvariant.h b/include/xrpl/tx/invariants/MPTInvariant.h index 7f405814e7..f2b0a18131 100644 --- a/include/xrpl/tx/invariants/MPTInvariant.h +++ b/include/xrpl/tx/invariants/MPTInvariant.h @@ -2,10 +2,13 @@ #include #include +#include #include #include #include +#include +#include namespace xrpl { @@ -20,6 +23,18 @@ class ValidMPTIssuance // MPToken by an issuer bool mptCreatedByIssuer_ = false; + /// sfReferenceHolding is intended to be set exactly once at vault + /// creation and immutable thereafter; true when that rule was violated. + bool referenceHoldingSetOnCreate_ = false; + + /// True when sfReferenceHolding was mutated on an existing MPTokenIssuance. + bool referenceHoldingMutated_ = false; + + /// MPTokens and RippleStates deleted during apply. finalize() checks each + /// holder's AccountRoot to detect vault pseudo-account holdings deleted + /// outside VaultDelete. All these checks are gated on fixCleanup3_2_0. + std::vector> deletedHoldings_; + public: void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); diff --git a/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h b/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h index 3861c19afc..6c59d85548 100644 --- a/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h +++ b/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h @@ -6,23 +6,28 @@ namespace xrpl { +// NOLINTBEGIN(readability-redundant-member-init) struct MPTCreateArgs { std::optional priorBalance; AccountID const& account; std::uint32_t sequence = 0; std::uint32_t flags = 0; - std::optional maxAmount = - std::nullopt; // NOLINT(readability-redundant-member-init) - std::optional assetScale = - std::nullopt; // NOLINT(readability-redundant-member-init) - std::optional transferFee = - std::nullopt; // NOLINT(readability-redundant-member-init) + std::optional maxAmount = std::nullopt; + std::optional assetScale = std::nullopt; + std::optional transferFee = std::nullopt; std::optional const& metadata{}; - std::optional domainId = std::nullopt; // NOLINT(readability-redundant-member-init) - std::optional mutableFlags = - std::nullopt; // NOLINT(readability-redundant-member-init) + std::optional domainId = std::nullopt; + std::optional mutableFlags = std::nullopt; + // Set only by callers that issue an MPT representing a wrapped asset + // (e.g. VaultCreate's share token). The keylet must point to an + // existing MPToken or RippleState owned by `account`. Surfaces on + // the resulting MPTokenIssuance via the optional sfReferenceHolding + // field. Used by readers (canTransfer, canTrade, freezing) to + // inherit the underlying asset's transferability. + std::optional referenceHolding = std::nullopt; }; +// NOLINTEND(readability-redundant-member-init) class MPTokenIssuanceCreate : public Transactor { diff --git a/src/libxrpl/ledger/View.cpp b/src/libxrpl/ledger/View.cpp index 4b67bb9867..c62d79dcac 100644 --- a/src/libxrpl/ledger/View.cpp +++ b/src/libxrpl/ledger/View.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -57,19 +58,45 @@ isVaultPseudoAccountFrozen( ReadView const& view, AccountID const& account, MPTIssue const& mptShare, - int depth) + std::uint8_t depth) { if (!view.rules().enabled(featureSingleAssetVault)) return false; if (depth >= kMaxAssetCheckDepth) - return true; // LCOV_EXCL_LINE + { + // LCOV_EXCL_START + UNREACHABLE("xrpl::View::isVaultPseudoAccountFrozen : reached asset check depth"); + return true; + // LCOV_EXCL_STOP + } auto const mptIssuance = view.read(keylet::mptIssuance(mptShare.getMptID())); if (mptIssuance == nullptr) return false; // zero MPToken won't block deletion of MPTokenIssuance auto const issuer = mptIssuance->getAccountID(sfIssuer); + + // Post-fixCleanup3_2_0: vault shares carry sfReferenceHolding pointing + // to the vault pseudo's MPToken or RippleState for the underlying. + // Read it to derive the underlying asset and recurse, skipping the + // issuer-account-then-vault chain. Pre-amendment shares (no field) + // fall back to the chain lookup below. + if (mptIssuance->isFieldPresent(sfReferenceHolding)) + { + auto const sleHolding = + view.read(keylet::unchecked(mptIssuance->getFieldH256(sfReferenceHolding))); + if (!sleHolding) + { + // LCOV_EXCL_START + UNREACHABLE("xrpl::isVaultPseudoAccountFrozen : dangling sfReferenceHolding"); + return false; + // LCOV_EXCL_STOP + } + return isAnyFrozen( + view, {issuer, account}, assetOfHolding(*mptIssuance, *sleHolding), depth + 1); + } + auto const mptIssuer = view.read(keylet::account(issuer)); if (mptIssuer == nullptr) { diff --git a/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp b/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp index 925f37c8ed..542a5b60ed 100644 --- a/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp @@ -55,7 +55,11 @@ isIndividualFrozen(ReadView const& view, AccountID const& account, MPTIssue cons } bool -isFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth) +isFrozen( + ReadView const& view, + AccountID const& account, + MPTIssue const& mptIssue, + std::uint8_t depth) { return isGlobalFrozen(view, mptIssue) || isIndividualFrozen(view, account, mptIssue) || isVaultPseudoAccountFrozen(view, account, mptIssue, depth); @@ -66,7 +70,7 @@ isAnyFrozen( ReadView const& view, std::initializer_list const& accounts, MPTIssue const& mptIssue, - int depth) + std::uint8_t depth) { if (isGlobalFrozen(view, mptIssue)) return true; @@ -303,7 +307,7 @@ requireAuth( MPTIssue const& mptIssue, AccountID const& account, AuthType authType, - int depth) + std::uint8_t depth) { auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); auto const sleIssuance = view.read(mptID); @@ -321,7 +325,12 @@ requireAuth( if (featureSAVEnabled) { if (depth >= kMaxAssetCheckDepth) - return tecINTERNAL; // LCOV_EXCL_LINE + { + // LCOV_EXCL_START + UNREACHABLE("xrpl::MPTokenHelpers::requireAuth : reached asset check depth"); + return tecINTERNAL; + // LCOV_EXCL_STOP + } // requireAuth is recursive if the issuer is a vault pseudo-account auto const sleIssuer = view.read(keylet::account(mptIssuer)); @@ -489,28 +498,88 @@ enforceMPTokenAuthorization( // LCOV_EXCL_STOP } +[[nodiscard]] Asset +assetOfHolding(SLE const& sleShareIssuance, SLE const& sleHolding) +{ + XRPL_ASSERT_PARTS( + sleHolding.getType() == ltRIPPLE_STATE || sleHolding.getType() == ltMPTOKEN, + "xrpl::assetOfHolding", + "unexpected holding type"); + XRPL_ASSERT_PARTS( + sleShareIssuance.getType() == ltMPTOKEN_ISSUANCE, + "xrpl::assetOfHolding", + "not SLE MPTokenIssuance"); + + if (sleHolding.getType() == ltMPTOKEN) + return MPTIssue{sleHolding.getFieldH192(sfMPTokenIssuanceID)}; + + auto const vaultPseudo = sleShareIssuance.at(sfIssuer); + auto const lowLimit = sleHolding.getFieldAmount(sfLowLimit); + auto const highLimit = sleHolding.getFieldAmount(sfHighLimit); + auto const& iouIssuer = + (lowLimit.getIssuer() != vaultPseudo) ? lowLimit.getIssuer() : highLimit.getIssuer(); + return Issue{lowLimit.get().currency, iouIssuer}; +} + TER canTransfer( ReadView const& view, MPTIssue const& mptIssue, AccountID const& from, - AccountID const& to) + AccountID const& to, + WaiveMPTCanTransfer waive, + std::uint8_t depth) { auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); auto const sleIssuance = view.read(mptID); if (!sleIssuance) return tecOBJECT_NOT_FOUND; + auto const issuer = (*sleIssuance)[sfIssuer]; + if (waive == WaiveMPTCanTransfer::Yes || from == issuer || to == issuer) + return tesSUCCESS; + if (!sleIssuance->isFlag(lsfMPTCanTransfer)) + return TER{tecNO_AUTH}; + + // Post-fixCleanup3_2_0: vault shares carry sfReferenceHolding pointing + // to the vault pseudo's MPToken or RippleState for the underlying asset. + // Third-party transfers inherit the underlying's transferability. + // Issuer-involving transfers and waived callers returned tesSUCCESS above. + // + // The recursive call always passes WaiveMPTCanTransfer::No so that + // a waived outer caller does not transitively unlock the underlying. + if (view.rules().enabled(fixCleanup3_2_0) && sleIssuance->isFieldPresent(sfReferenceHolding)) { - if (from != (*sleIssuance)[sfIssuer] && to != (*sleIssuance)[sfIssuer]) - return TER{tecNO_AUTH}; + // Defensive depth bound on the inheritance recursion. Unreachable + // in practice (vault-of-vault-shares is forbidden at VaultCreate). + if (depth >= kMaxAssetCheckDepth) + { + // LCOV_EXCL_START + UNREACHABLE("xrpl::MPTokenHelpers::canTransfer : reached asset check depth"); + return tecINTERNAL; + // LCOV_EXCL_STOP + } + + auto const sleHolding = + view.read(keylet::unchecked(sleIssuance->getFieldH256(sfReferenceHolding))); + if (!sleHolding) + return tefINTERNAL; // LCOV_EXCL_LINE + + return canTransfer( + view, + assetOfHolding(*sleIssuance, *sleHolding), + from, + to, + WaiveMPTCanTransfer::No, + depth + 1); } + return tesSUCCESS; } TER -canTrade(ReadView const& view, Asset const& asset) +canTrade(ReadView const& view, Asset const& asset, std::uint8_t depth) { return asset.visit( [&](Issue const&) -> TER { return tesSUCCESS; }, @@ -520,6 +589,31 @@ canTrade(ReadView const& view, Asset const& asset) return tecOBJECT_NOT_FOUND; if (!sleIssuance->isFlag(lsfMPTCanTrade)) return tecNO_PERMISSION; + + // Post-fixCleanup3_2_0: vault shares inherit the underlying + // asset's tradability. A share whose underlying has been + // removed from trading cannot itself be placed on the DEX. + if (view.rules().enabled(fixCleanup3_2_0) && + sleIssuance->isFieldPresent(sfReferenceHolding)) + { + // Defensive depth bound on the inheritance recursion. + // Unreachable in practice (vault-of-vault-shares + // forbidden at VaultCreate). + if (depth >= kMaxAssetCheckDepth) + { + // LCOV_EXCL_START + UNREACHABLE("xrpl::MPTokenHelpers::canTrade : reached asset check depth"); + return tecINTERNAL; + // LCOV_EXCL_STOP + } + auto const sleHolding = + view.read(keylet::unchecked(sleIssuance->getFieldH256(sfReferenceHolding))); + if (!sleHolding) + return tefINTERNAL; // LCOV_EXCL_LINE + + return canTrade(view, assetOfHolding(*sleIssuance, *sleHolding), depth + 1); + } + return tesSUCCESS; }); } @@ -892,7 +986,12 @@ issuerSelfDebitHookMPT(ApplyView& view, MPTIssue const& issue, std::uint64_t amo } static TER -checkMPTAllowed(ReadView const& view, TxType txType, Asset const& asset, AccountID const& accountID) +checkMPTAllowed( + ReadView const& view, + TxType txType, + Asset const& asset, + AccountID const& accountID, + std::uint8_t depth = 0) { if (!asset.holds()) return tesSUCCESS; @@ -914,17 +1013,15 @@ checkMPTAllowed(ReadView const& view, TxType txType, Asset const& asset, Account if (!issuanceSle) return tecOBJECT_NOT_FOUND; // LCOV_EXCL_LINE - auto const flags = issuanceSle->getFlags(); - - if ((flags & lsfMPTLocked) != 0u) + if (issuanceSle->isFlag(lsfMPTLocked)) return tecLOCKED; // LCOV_EXCL_LINE // Offer crossing and Payment - if ((flags & lsfMPTCanTrade) == 0) + if (!issuanceSle->isFlag(lsfMPTCanTrade)) return tecNO_PERMISSION; if (accountID != issuer) { - if ((flags & lsfMPTCanTransfer) == 0) + if (!issuanceSle->isFlag(lsfMPTCanTransfer)) return tecNO_PERMISSION; auto const mptSle = view.read(keylet::mptoken(issuanceKey.key, accountID)); @@ -935,6 +1032,34 @@ checkMPTAllowed(ReadView const& view, TxType txType, Asset const& asset, Account if (mptSle->isFlag(lsfMPTLocked)) return tecLOCKED; + + // Post-fixCleanup3_2_0: vault shares inherit the underlying + // asset's checks here too. Without this, a share could be + // placed on the AMM, in an Offer, or in a Check even after + // the issuer has restricted the underlying. Mirrors the + // canTransfer / canTrade inheritance for path-find-adjacent + // operations that don't go through canTransfer directly. + if (view.rules().enabled(fixCleanup3_2_0) && + issuanceSle->isFieldPresent(sfReferenceHolding)) + { + // Defensive depth bound on the inheritance recursion. + // Reachable only post-fixCleanup3_2_0 and unreachable in + // practice (vault-of-vault-shares forbidden at VaultCreate). + if (depth >= kMaxAssetCheckDepth) + { + // LCOV_EXCL_START + UNREACHABLE("xrpl::MPTokenHelpers::checkMPTAllowed : reached asset check depth"); + return tecINTERNAL; + // LCOV_EXCL_STOP + } + auto const sleHolding = + view.read(keylet::unchecked(issuanceSle->getFieldH256(sfReferenceHolding))); + if (!sleHolding) + return tefINTERNAL; // LCOV_EXCL_LINE + + return checkMPTAllowed( + view, txType, assetOfHolding(*issuanceSle, *sleHolding), accountID, depth + 1); + } } return tesSUCCESS; diff --git a/src/libxrpl/ledger/helpers/TokenHelpers.cpp b/src/libxrpl/ledger/helpers/TokenHelpers.cpp index c9dccb884d..71019761ed 100644 --- a/src/libxrpl/ledger/helpers/TokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/TokenHelpers.cpp @@ -63,7 +63,7 @@ isIndividualFrozen(ReadView const& view, AccountID const& account, Asset const& } bool -isFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth) +isFrozen(ReadView const& view, AccountID const& account, Asset const& asset, std::uint8_t depth) { return std::visit( [&](auto const& issue) { return isFrozen(view, account, issue, depth); }, asset.value()); @@ -107,7 +107,7 @@ isAnyFrozen( ReadView const& view, std::initializer_list const& accounts, Asset const& asset, - int depth) + std::uint8_t depth) { return asset.visit( [&](Issue const& issue) { return isAnyFrozen(view, accounts, issue); }, @@ -115,7 +115,11 @@ isAnyFrozen( } bool -isDeepFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth) +isDeepFrozen( + ReadView const& view, + AccountID const& account, + MPTIssue const& mptIssue, + std::uint8_t depth) { // Unlike IOUs, frozen / locked MPTs are not allowed to send or receive // funds, so checking "deep frozen" is the same as checking "frozen". @@ -123,7 +127,7 @@ isDeepFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mpt } bool -isDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth) +isDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset, std::uint8_t depth) { return std::visit( [&](auto const& issue) { return isDeepFrozen(view, account, issue, depth); }, @@ -500,13 +504,19 @@ requireAuth(ReadView const& view, Asset const& asset, AccountID const& account, } TER -canTransfer(ReadView const& view, Asset const& asset, AccountID const& from, AccountID const& to) +canTransfer( + ReadView const& view, + Asset const& asset, + AccountID const& from, + AccountID const& to, + WaiveMPTCanTransfer waive, + std::uint8_t depth) { - return std::visit( - [&](TIss const& issue) -> TER { - return canTransfer(view, issue, from, to); + return asset.visit( + [&](MPTIssue const& issue) -> TER { + return canTransfer(view, issue, from, to, waive, depth); }, - asset.value()); + [&](Issue const& issue) -> TER { return canTransfer(view, issue, from, to); }); } //------------------------------------------------------------------------------ diff --git a/src/libxrpl/tx/invariants/MPTInvariant.cpp b/src/libxrpl/tx/invariants/MPTInvariant.cpp index 43379b0b86..ecba0b6227 100644 --- a/src/libxrpl/tx/invariants/MPTInvariant.cpp +++ b/src/libxrpl/tx/invariants/MPTInvariant.cpp @@ -5,11 +5,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -30,6 +32,13 @@ ValidMPTIssuance::visitEntry( std::shared_ptr const& before, std::shared_ptr const& after) { + // The sfReferenceHolding tracking and the deleted-holding capture are + // only meaningful post-fixCleanup3_2_0 (the field is never set + // pre-amendment, and the holding-deletion rule does not apply). + // Skip both blocks when the amendment is off so we avoid wasted work + // on the hot path. + bool const fix320Enabled = isFeatureEnabled(fixCleanup3_2_0); + if (after && after->getType() == ltMPTOKEN_ISSUANCE) { if (isDelete) @@ -39,6 +48,21 @@ ValidMPTIssuance::visitEntry( else if (!before) { mptIssuancesCreated_++; + if (fix320Enabled && after->isFieldPresent(sfReferenceHolding)) + referenceHoldingSetOnCreate_ = true; + } + else if (fix320Enabled) + { + // Modified issuance: detect any change to sfReferenceHolding. + bool const beforePresent = before->isFieldPresent(sfReferenceHolding); + bool const afterPresent = after->isFieldPresent(sfReferenceHolding); + if (beforePresent != afterPresent || + (afterPresent && + before->getFieldH256(sfReferenceHolding) != + after->getFieldH256(sfReferenceHolding))) + { + referenceHoldingMutated_ = true; + } } } @@ -47,6 +71,8 @@ ValidMPTIssuance::visitEntry( if (isDelete) { mptokensDeleted_++; + if (fix320Enabled) + deletedHoldings_.push_back(after); } else if (!before) { @@ -56,6 +82,11 @@ ValidMPTIssuance::visitEntry( mptCreatedByIssuer_ = true; } } + + // Capture deleted RippleState SLEs so finalize() can verify none of + // them were owned by a vault pseudo-account outside VaultDelete. + if (fix320Enabled && isDelete && after && after->getType() == ltRIPPLE_STATE) + deletedHoldings_.push_back(after); } bool @@ -68,6 +99,63 @@ ValidMPTIssuance::finalize( { auto const& rules = view.rules(); bool const mptV2Enabled = rules.enabled(featureMPTokensV2); + + // Post-fixCleanup3_2_0: + // - sfReferenceHolding is set only by VaultCreate at share-issuance + // creation, and is immutable thereafter. + // - A vault pseudo-account's MPToken or RippleState may only be + // deleted by VaultDelete; the share's sfReferenceHolding pointer + // must not dangle outside that controlled lifecycle. + if (rules.enabled(fixCleanup3_2_0)) + { + bool invariantPasses = true; + if (referenceHoldingMutated_) + { + JLOG(j.fatal()) << "Invariant failed: sfReferenceHolding was modified " + "on an existing MPTokenIssuance"; + invariantPasses = false; + } + if (referenceHoldingSetOnCreate_ && tx.getTxnType() != ttVAULT_CREATE) + { + JLOG(j.fatal()) << "Invariant failed: sfReferenceHolding set on a new " + "MPTokenIssuance by a non-VaultCreate transaction"; + invariantPasses = false; + } + if (!deletedHoldings_.empty() && tx.getTxnType() != ttVAULT_DELETE) + { + auto const isVaultPseudo = [&](AccountID const& acct) { + auto const sle = view.read(keylet::account(acct)); + return sle && sle->isFieldPresent(sfVaultID); + }; + for (auto const& sleHolding : deletedHoldings_) + { + bool offending = false; + if (sleHolding->getType() == ltMPTOKEN) + { + offending = isVaultPseudo(sleHolding->at(sfAccount)); + } + else // ltRIPPLE_STATE + { + auto const lowLimit = sleHolding->getFieldAmount(sfLowLimit); + auto const highLimit = sleHolding->getFieldAmount(sfHighLimit); + // Each limit's STAmount.issuer is the COUNTERPARTY of + // that side's owner: lowLimit's issuer is the high + // account, highLimit's issuer is the low account. + offending = + isVaultPseudo(lowLimit.getIssuer()) || isVaultPseudo(highLimit.getIssuer()); + } + if (offending) + { + JLOG(j.fatal()) << "Invariant failed: vault pseudo-account holding " + "deleted by a non-VaultDelete transaction"; + invariantPasses = false; + } + } + } + if (!invariantPasses) + return false; + } + if (isTesSuccess(result) || (mptV2Enabled && result == tecINCOMPLETE)) { [[maybe_unused]] diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp index 17a9683690..331c44b1e8 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -95,8 +96,13 @@ LoanBrokerCoverWithdraw::preclaim(PreclaimContext const& ctx) // The broker's pseudo-account is the source of funds. auto const pseudoAccountID = sleBroker->at(sfAccount); - // Cannot transfer a non-transferable Asset - if (auto const ret = canTransfer(ctx.view, vaultAsset, pseudoAccountID, dstAcct)) + // Post-fixCleanup3_2_0: cover withdraw is a recovery path that bypasses + // the lsfMPTCanTransfer flag check, so an issuer cannot trap a broker's + // first-loss capital. Other transferability checks (IOU NoRipple, freeze, + // requireAuth) still apply. + auto const waive = ctx.view.rules().enabled(fixCleanup3_2_0) ? WaiveMPTCanTransfer::Yes + : WaiveMPTCanTransfer::No; + if (auto const ret = canTransfer(ctx.view, vaultAsset, pseudoAccountID, dstAcct, waive)) return ret; // Withdrawal to a 3rd party destination account is essentially a transfer. diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp index 1440b67309..64d0b01f5e 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -49,6 +50,11 @@ MPTokenIssuanceCreate::getFlagsMask(PreflightContext const& ctx) NotTEC MPTokenIssuanceCreate::preflight(PreflightContext const& ctx) { + // sfReferenceHolding is set only internally by VaultCreate. Reject + // any user-submitted MPTokenIssuanceCreate that attempts to carry it. + if (ctx.rules.enabled(fixCleanup3_2_0) && ctx.tx.isFieldPresent(sfReferenceHolding)) + return temMALFORMED; + // If the mutable flags field is included, at least one flag must be // specified. if (auto const mutableFlags = ctx.tx[~sfMutableFlags]; mutableFlags && @@ -141,6 +147,22 @@ MPTokenIssuanceCreate::create(ApplyView& view, beast::Journal journal, MPTCreate if (args.mutableFlags) (*mptIssuance)[sfMutableFlags] = *args.mutableFlags; + if (args.referenceHolding) + { + // Defensive: the holding must already exist and be of an + // expected type. Callers (currently only VaultCreate) + // populate this after the pseudo-account's MPToken / + // RippleState has been installed. A missing holding here + // 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 + auto const type = sleHolding->getType(); + if (type != ltMPTOKEN && type != ltRIPPLE_STATE) + return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + (*mptIssuance)[sfReferenceHolding] = *args.referenceHolding; + } + view.insert(mptIssuance); } diff --git a/src/libxrpl/tx/transactors/vault/VaultCreate.cpp b/src/libxrpl/tx/transactors/vault/VaultCreate.cpp index c6e1f28d57..7490f44619 100644 --- a/src/libxrpl/tx/transactors/vault/VaultCreate.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultCreate.cpp @@ -1,12 +1,14 @@ #include #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -162,9 +164,9 @@ VaultCreate::doApply() auto maybePseudo = createPseudoAccount(view(), vault->key(), sfVaultID); if (!maybePseudo) return maybePseudo.error(); // LCOV_EXCL_LINE - auto& pseudo = *maybePseudo; - auto pseudoId = pseudo->at(sfAccount); - auto asset = tx[sfAsset]; + auto const& pseudo = *maybePseudo; + AccountID const pseudoId = pseudo->at(sfAccount); + auto const asset = tx[sfAsset]; if (auto ter = addEmptyHolding(view(), pseudoId, preFeeBalance_, asset, j_); !isTesSuccess(ter)) return ter; @@ -182,13 +184,24 @@ VaultCreate::doApply() // Note, here we are **not** creating an MPToken for the assets held in // the vault. That MPToken or TrustLine/RippleState is created above, in // addEmptyHolding. Here we are creating MPTokenIssuance for the shares - // in the vault - auto maybeShare = MPTokenIssuanceCreate::create( + // in the vault. + // + // Post-fixCleanup3_2_0: surface the vault pseudo's holding (MPToken + // for MPT, RippleState for IOU) on the share via sfReferenceHolding. + // XRP underlyings leave it unset. + auto const referenceHolding = [&]() -> std::optional { + if (!view().rules().enabled(fixCleanup3_2_0) || asset.native()) + return std::nullopt; + return asset.holds() + ? keylet::mptoken(asset.get().getMptID(), pseudoId).key + : keylet::line(pseudoId, asset.get()).key; + }(); + auto const maybeShare = MPTokenIssuanceCreate::create( view(), j_, { .priorBalance = std::nullopt, - .account = pseudoId->value(), + .account = pseudoId, .sequence = 1, .flags = mptFlags, .assetScale = scale, @@ -196,6 +209,7 @@ VaultCreate::doApply() .metadata = tx[~sfMPTokenMetadata], .domainId = tx[~sfDomainID], .mutableFlags = std::nullopt, + .referenceHolding = referenceHolding, }); if (!maybeShare) return maybeShare.error(); // LCOV_EXCL_LINE diff --git a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp index 136f9e17c6..ced82f6735 100644 --- a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp @@ -65,7 +65,14 @@ VaultWithdraw::preclaim(PreclaimContext const& ctx) auto const& vaultAccount = vault->at(sfAccount); auto const& account = ctx.tx[sfAccount]; auto const& dstAcct = ctx.tx[~sfDestination].value_or(account); - if (auto ter = canTransfer(ctx.view, vaultAsset, vaultAccount, dstAcct); !isTesSuccess(ter)) + // Post-fixCleanup3_2_0: withdraw is a recovery path that bypasses the + // lsfMPTCanTransfer flag check, so an issuer cannot trap depositor funds. + // Other transferability checks (IOU NoRipple, freeze, requireAuth) still + // apply. + auto const waive = ctx.view.rules().enabled(fixCleanup3_2_0) ? WaiveMPTCanTransfer::Yes + : WaiveMPTCanTransfer::No; + if (auto ter = canTransfer(ctx.view, vaultAsset, vaultAccount, dstAcct, waive); + !isTesSuccess(ter)) { JLOG(ctx.j.debug()) << "VaultWithdraw: vault assets are non-transferable."; return ter; diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index 775e18656b..21094e0142 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -1783,7 +1783,7 @@ class Invariants_test : public beast::unit_test::Suite for (std::size_t n = 0; n < numCreds; ++n) { auto credType = "cred_type" + std::to_string(n); - credentials.push_back({a2, credType}); + credentials.push_back({.issuer = a2, .credType = credType}); } std::uint32_t const seq = env.seq(a1); @@ -4103,6 +4103,114 @@ class Invariants_test : public beast::unit_test::Suite return true; }); } + + // sfReferenceHolding can only be set on creation by VaultCreate. A + // non-VaultCreate transaction that creates an MPTokenIssuance with + // sfReferenceHolding present must trip the invariant. + doInvariantCheck( + {{"sfReferenceHolding set on a new MPTokenIssuance by a " + "non-VaultCreate transaction"}}, + [](Account const& a1, Account const&, ApplyContext& ac) { + auto const sleAcct = ac.view().peek(keylet::account(a1.id())); + if (!sleAcct) + return false; + MPTIssue const mpt{makeMptID(sleAcct->getFieldU32(sfSequence), a1)}; + auto sleNew = std::make_shared(keylet::mptIssuance(mpt.getMptID())); + sleNew->setFieldH256(sfReferenceHolding, uint256{1}); + ac.view().insert(sleNew); + return true; + }, + XRPAmount{}, + STTx{ttACCOUNT_SET, [](STObject&) {}}); + + // sfReferenceHolding is immutable: changing the field on an + // existing MPTokenIssuance must trip the invariant. Set up a real + // vault via preclose (so the share issuance carries + // sfReferenceHolding), then mutate it in precheck to produce a + // before/after pair. + { + uint256 vaultKey; + doInvariantCheck( + {{"sfReferenceHolding was modified on an existing " + "MPTokenIssuance"}}, + [&](Account const&, Account const&, ApplyContext& ac) { + auto const sleVault = ac.view().peek(keylet::vault(vaultKey)); + if (!sleVault) + return false; + auto sleIssuance = + ac.view().peek(keylet::mptIssuance(sleVault->at(sfShareMPTID))); + if (!sleIssuance) + return false; + sleIssuance->setFieldH256(sfReferenceHolding, uint256{2}); + ac.view().update(sleIssuance); + return true; + }, + XRPAmount{}, + STTx{ttACCOUNT_SET, [](STObject&) {}}, + {tecINVARIANT_FAILED, tefINVARIANT_FAILED}, + [&](Account const& a1, Account const&, Env& env) { + Account const issuer{"issuer"}; + env.fund(XRP(10'000), issuer); + env.close(); + MPTTester mptt{env, issuer, kMptInitNoFund}; + mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); + PrettyAsset const asset = mptt.issuanceID(); + mptt.authorize({.account = a1}); + env.close(); + + Vault const vault{env}; + auto [tx, keylet] = vault.create({.owner = a1, .asset = asset}); + env(tx); + env.close(); + vaultKey = keylet.key; + return true; + }); + } + + // A vault pseudo-account's MPToken cannot be deleted by anything + // other than a VaultDelete transaction. Set up a vault, then have + // an arbitrary tx erase the pseudo's MPToken in precheck. + { + uint256 vaultKey; + doInvariantCheck( + {{"vault pseudo-account holding deleted by a " + "non-VaultDelete transaction"}}, + [&](Account const&, Account const&, ApplyContext& ac) { + auto const sleVault = ac.view().peek(keylet::vault(vaultKey)); + if (!sleVault) + return false; + auto const sleIssuance = + ac.view().peek(keylet::mptIssuance(sleVault->at(sfShareMPTID))); + if (!sleIssuance || !sleIssuance->isFieldPresent(sfReferenceHolding)) + return false; + auto sleHolding = ac.view().peek( + keylet::unchecked(sleIssuance->getFieldH256(sfReferenceHolding))); + if (!sleHolding) + return false; + ac.view().erase(sleHolding); + return true; + }, + XRPAmount{}, + STTx{ttACCOUNT_SET, [](STObject&) {}}, + {tecINVARIANT_FAILED, tefINVARIANT_FAILED}, + [&](Account const& a1, Account const&, Env& env) { + Account const issuer{"issuer"}; + env.fund(XRP(10'000), issuer); + env.close(); + MPTTester mptt{env, issuer, kMptInitNoFund}; + mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); + PrettyAsset const asset = mptt.issuanceID(); + mptt.authorize({.account = a1}); + env.close(); + + Vault const vault{env}; + auto [tx, keylet] = vault.create({.owner = a1, .asset = asset}); + env(tx); + env.close(); + vaultKey = keylet.key; + return true; + }); + } } // Test the invariant overwrite fix for both pre- and post-amendment diff --git a/src/test/app/Loan_test.cpp b/src/test/app/Loan_test.cpp index a8132887fc..201bb6942a 100644 --- a/src/test/app/Loan_test.cpp +++ b/src/test/app/Loan_test.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -5254,7 +5255,7 @@ protected: auto const loanSequence = brokerStateBefore->at(sfLoanSequence); auto const keylet = keylet::loan(broker.brokerID, loanSequence); - auto const closeStartDate = (parentCloseTime() / 10 + 1) * 10; + auto const closeStartDate = ((parentCloseTime() / 10) + 1) * 10; auto const grace = 5'000; auto const interval = kMaxTime - closeStartDate - grace; auto const total = 1; @@ -5283,7 +5284,7 @@ protected: env(pay(issuer, borrower, iouAsset(Number{1'055'524'81, -2}))); // Start date when the ledger is closed will be larger - auto const closeStartDate = (parentCloseTime() / 10 + 1) * 10; + auto const closeStartDate = ((parentCloseTime() / 10) + 1) * 10; auto const grace = 5'000; auto const maxLoanTime = kMaxTime - closeStartDate - grace; auto const total = [&]() { @@ -5397,7 +5398,7 @@ protected: void testCoverDepositWithdrawNonTransferableMPT(FeatureBitset feature) { - testcase("CoverDeposit and CoverWithdraw reject MPT without CanTransfer"); + testcase("CoverDeposit blocked, CoverWithdraw allowed when CanTransfer cleared"); using namespace jtx; using namespace loanBroker; @@ -5409,19 +5410,14 @@ protected: env.fund(XRP(100'000), issuer, alice); env.close(); - MPTTester mpt{env, issuer, kMptInitNoFund}; - - mpt.create({.flags = tfMPTCanTransfer, .mutableFlags = tmfMPTCanMutateCanTransfer}); - - env.close(); - + MPTTester mpt( + {.env = env, + .issuer = issuer, + .holders = {alice}, + .pay = 100, + .flags = tfMPTCanTransfer, + .mutableFlags = tmfMPTCanMutateCanTransfer}); PrettyAsset const asset = mpt["MPT"]; - mpt.authorize({.account = alice}); - env.close(); - - // Issuer can fund the holder even if CanTransfer is not set. - env(pay(issuer, alice, asset(100))); - env.close(); Vault const vault{env}; auto const [createTx, vaultKeylet] = vault.create({.owner = alice, .asset = asset}); @@ -5438,30 +5434,9 @@ protected: Account const pseudoAccount{"Loan Broker pseudo-account", brokerSle->at(sfAccount)}; - // Remove CanTransfer after the broker is set up. - mpt.set({.mutableFlags = tmfMPTClearCanTransfer}); - env.close(); - - // Standard Payment path should forbid third-party transfers. - auto const err = feature[featureMPTokensV2] ? tecNO_PERMISSION : tecNO_AUTH; - env(pay(alice, pseudoAccount, asset(1)), Ter(err)); - env.close(); - - // Cover cannot be transferred to broker account + // 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), Ter{tecNO_AUTH}); - env.close(); - - if (auto const refreshed = env.le(brokerKeylet); BEAST_EXPECT(refreshed)) - { - BEAST_EXPECT(refreshed->at(sfCoverAvailable) == 0); - env.require(Balance(pseudoAccount, asset(0))); - } - - // Set CanTransfer again and transfer some deposit - mpt.set({.mutableFlags = tmfMPTSetCanTransfer}); - env.close(); - env(coverDeposit(alice, brokerKeylet.key, depositAmount)); env.close(); @@ -5471,26 +5446,177 @@ protected: env.require(Balance(pseudoAccount, depositAmount)); } - // Remove CanTransfer after the deposit + // Issuer governance: clear CanTransfer. mpt.set({.mutableFlags = tmfMPTClearCanTransfer}); env.close(); - // Cover cannot be transferred from broker account - env(coverWithdraw(alice, brokerKeylet.key, depositAmount), Ter{tecNO_AUTH}); + // 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(); - // Set CanTransfer again and withdraw - mpt.set({.mutableFlags = tmfMPTSetCanTransfer}); - env.close(); - - env(coverWithdraw(alice, brokerKeylet.key, depositAmount)); + // 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) == 0); - env.require(Balance(pseudoAccount, asset(0))); + 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"); + using namespace jtx; + using namespace loan; + + 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 | 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}); + PrettyAsset const asset = mpt.issuanceID(); + env(pay(issuer, lender, asset(10'000'000))); + env(pay(issuer, borrower, asset(100'000))); + env.close(); + + 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. + env(offer(lender, XRP(1), asset(10)), Ter{tecNO_PERMISSION}); + env.close(); + + auto const loanSetFee = Fee(env.current()->fees().base * 2); + + // New cover deposits still work. + env(coverDeposit(lender, broker.brokerID, asset(100))); + env.close(); + + // New loan issuance still works. + env(loan::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)); + + // Repayment still works. + env(pay(borrower, loanKeylet.key, asset(1'000))); + env.close(); + + // Cover withdrawal still works. + env(coverWithdraw(lender, broker.brokerID, asset(100))); + env.close(); } #if LOAN_TODO @@ -6882,7 +7008,7 @@ protected: auto credType = "credential1"; - pdomain::Credentials const credentials1{{issuer, credType}}; + pdomain::Credentials const credentials1{{.issuer = issuer, .credType = credType}}; env(pdomain::setTx(issuer, credentials1)); env.close(); @@ -6985,7 +7111,7 @@ protected: auto credType = "credential1"; - pdomain::Credentials const credentials1{{issuer, credType}}; + pdomain::Credentials const credentials1{{.issuer = issuer, .credType = credType}}; env(pdomain::setTx(issuer, credentials1)); env.close(); @@ -7631,6 +7757,9 @@ public: auto const all = jtx::testableAmendments(); testCoverDepositWithdrawNonTransferableMPT(all); testCoverDepositWithdrawNonTransferableMPT(all - featureMPTokensV2); + testCoverDepositWithdrawNonTransferableMPT(all - fixCleanup3_2_0); + testLoanSetBlockedLoanPayAllowedWhenCanTransferCleared(); + testLendingCanTradeClearedNoImpact(); testPoCUnsignedUnderflowOnFullPayAfterEarlyPeriodic(); testDisabled(); diff --git a/src/test/app/MPToken_test.cpp b/src/test/app/MPToken_test.cpp index 1e7763ac62..0e48db6080 100644 --- a/src/test/app/MPToken_test.cpp +++ b/src/test/app/MPToken_test.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -191,6 +192,22 @@ class MPToken_test : public beast::unit_test::Suite .metadata = "test", .err = temMALFORMED}); } + + // sfReferenceHolding is populated internally only by VaultCreate. + // A user-submitted MPTokenIssuanceCreate carrying the field must be + // rejected at preflight under fixCleanup3_2_0. + if (features[fixCleanup3_2_0]) + { + Env env{*this, features}; + env.fund(XRP(1'000), alice); + env.close(); + + json::Value jv; + jv[sfAccount] = alice.human(); + jv[sfTransactionType] = jss::MPTokenIssuanceCreate; + jv[sfReferenceHolding] = to_string(uint256{1}); + env(jv, Ter(temMALFORMED)); + } } void @@ -1777,7 +1794,7 @@ class MPToken_test : public beast::unit_test::Suite env.close(); // Bob authorize credentials - env(deposit::authCredentials(bob, {{dpIssuer, credType}})); + env(deposit::authCredentials(bob, {{.issuer = dpIssuer, .credType = credType}})); env.close(); // alice try to send 100 MPT to bob, not authorized diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index 318a6dc45c..af6f4841f4 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -2241,7 +2242,7 @@ class Vault_test : public beast::unit_test::Suite PrettyAsset const& asset, Vault& vault, MPTTester& mptt) { - testcase("MPT non-transferable"); + testcase("MPT non-transferable: block deposit, allow withdraw"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx); @@ -2251,22 +2252,19 @@ class Vault_test : public beast::unit_test::Suite env(tx); env.close(); - // Remove CanTransfer + // 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, Ter{tecNO_AUTH}); - env.close(); - - // Restore CanTransfer - mptt.set({.mutableFlags = tmfMPTSetCanTransfer}); - env.close(); - env(tx); env.close(); @@ -2274,6 +2272,245 @@ class Vault_test : public beast::unit_test::Suite 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 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"); + + Env env{*this, testableAmendments()}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(100'000), issuer, owner, alice, bob); + env.close(); + Vault const vault{env}; + + MPTTester mptt{env, issuer, kMptInitNoFund}; + mptt.create( + {.flags = tfMPTCanTransfer | tfMPTCanTrade | tfMPTCanLock, + .mutableFlags = tmfMPTCanMutateCanTrade}); + PrettyAsset const asset = mptt.issuanceID(); + mptt.authorize({.account = owner}); + mptt.authorize({.account = alice}); + mptt.authorize({.account = bob}); + env(pay(issuer, alice, asset(10'000))); + env(pay(issuer, bob, asset(10'000))); + env.close(); + + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + env(tx); + env.close(); + + // Seed shares so we can later place them on trading venues. + env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = asset(5'000)})); + env(vault.deposit({.depositor = bob, .id = keylet.key, .amount = asset(5'000)})); + env.close(); + + auto const shares = [&]() -> PrettyAsset { + auto const sle = env.le(keylet); + BEAST_EXPECT(sle != nullptr); + 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. + env(offer(alice, XRP(1), asset(10)), Ter{tecNO_PERMISSION}); + env.close(); + + // Control: clearing CanTrade on the underlying is also observable + // on the AMM path for that asset. + AMM const ammUnderlyingFails( + 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). + env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = asset(100)})); + env.close(); + + // Peer-to-peer share transfers still work (CanTransfer is set on + // both layers). + env(pay(alice, bob, shares(1))); + env.close(); + + // Withdraw still works. + env(vault.withdraw({.depositor = alice, .id = keylet.key, .amount = asset(100)})); + env.close(); + } + { testcase("MPT OutstandingAmount > MaximumAmount"); @@ -2744,16 +2981,17 @@ class Vault_test : public beast::unit_test::Suite env(tx); env.close(); } - env(pay(owner, charlie, shares(100))); - env.close(); - - // Charlie cannot withdraw - auto tx3 = vault.withdraw( - {.depositor = charlie, .id = keylet.key, .amount = shares(100)}); - env(tx3, Ter{terNO_RIPPLE}); - env.close(); - - env(pay(charlie, owner, shares(100))); + // Behavioural shift introduced by share inheritance: + // before fixCleanup3_2_0 this share Payment succeeded + // and the underlying IOU's NoRipple restriction surfaced + // only later on Charlie's withdrawal (terNO_RIPPLE). + // Post-amendment, canTransfer reads the share's + // sfReferenceHolding and dispatches to the underlying IOU; + // rippling is disabled between owner and charlie so the + // share payment itself is now blocked. tecPATH_DRY is + // the path-find layer's translation of the underlying + // terNO_RIPPLE under featureMPTokensV2. + env(pay(owner, charlie, shares(100)), Ter{tecPATH_DRY}); env.close(); } @@ -6140,6 +6378,406 @@ class Vault_test : public beast::unit_test::Suite runTest(amendments); } + void + testReferenceHolding() + { + using namespace test::jtx; + + auto readReferenceHolding = [&](Env const& env, + Keylet const& vaultKeylet) -> std::optional { + auto const sleVault = env.le(vaultKeylet); + if (!sleVault) + return std::nullopt; + auto const sleIssuance = env.le(keylet::mptIssuance(sleVault->at(sfShareMPTID))); + if (!sleIssuance || !sleIssuance->isFieldPresent(sfReferenceHolding)) + return std::nullopt; + return sleIssuance->getFieldH256(sfReferenceHolding); + }; + + // Post-fixCleanup3_2_0: vault share carries sfReferenceHolding + // pointing to the vault pseudo's MPToken (for MPT-backed vaults) + // or RippleState (for IOU-backed vaults). + { + testcase("sfReferenceHolding: MPT-backed vault, post-amendment"); + Env env{*this, testableAmendments()}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + env.fund(XRP(10'000), issuer, owner); + env.close(); + + MPTTester mptt{env, issuer, kMptInitNoFund}; + mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); + PrettyAsset const asset = mptt.issuanceID(); + mptt.authorize({.account = owner}); + + Vault const vault{env}; + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + env(tx); + env.close(); + + auto const sleVault = env.le(keylet); + BEAST_EXPECT(sleVault != nullptr); + auto const pseudoId = sleVault->at(sfAccount); + auto const expected = keylet::mptoken(mptt.issuanceID(), pseudoId).key; + + auto const stored = readReferenceHolding(env, keylet); + BEAST_EXPECT(stored.has_value()); + BEAST_EXPECT(stored && *stored == expected); + // The pointed-to MPToken must actually exist. + BEAST_EXPECT(env.le(keylet::mptoken(mptt.issuanceID(), pseudoId)) != nullptr); + } + + { + testcase("sfReferenceHolding: IOU-backed vault, post-amendment"); + Env env{*this, testableAmendments()}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + env.fund(XRP(10'000), issuer, owner); + env(fset(issuer, asfDefaultRipple)); + env.close(); + + PrettyAsset const asset = issuer["IOU"]; + env.trust(asset(1'000'000), owner); + env.close(); + + Vault const vault{env}; + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + env(tx); + env.close(); + + auto const sleVault = env.le(keylet); + BEAST_EXPECT(sleVault != nullptr); + auto const pseudoId = sleVault->at(sfAccount); + auto const expected = keylet::line(pseudoId, asset.raw().get()).key; + + auto const stored = readReferenceHolding(env, keylet); + BEAST_EXPECT(stored.has_value()); + BEAST_EXPECT(stored && *stored == expected); + // The pointed-to RippleState must actually exist. + BEAST_EXPECT(env.le(keylet::line(pseudoId, asset.raw().get())) != nullptr); + } + + // XRP-backed vaults leave the field absent: XRP has no separate + // holding ledger entry and no transferability concept to inherit. + { + testcase("sfReferenceHolding: XRP-backed vault, field absent"); + Env env{*this, testableAmendments()}; + Account const owner{"owner"}; + env.fund(XRP(10'000), owner); + env.close(); + + PrettyAsset const asset{xrpIssue(), 1'000'000}; + Vault const vault{env}; + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + env(tx); + env.close(); + + BEAST_EXPECT(!readReferenceHolding(env, keylet).has_value()); + } + + // Pre-fixCleanup3_2_0: vault share has the field absent regardless + // of underlying type. + { + testcase("sfReferenceHolding: vault share, pre-amendment"); + Env env{*this, testableAmendments() - fixCleanup3_2_0}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + env.fund(XRP(10'000), issuer, owner); + env.close(); + + MPTTester mptt{env, issuer, kMptInitNoFund}; + mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); + PrettyAsset const asset = mptt.issuanceID(); + mptt.authorize({.account = owner}); + + Vault const vault{env}; + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + env(tx); + env.close(); + + BEAST_EXPECT(!readReferenceHolding(env, keylet).has_value()); + } + + // Plain MPTokenIssuanceCreate (not a vault share) must never + // populate the field. Only the post-amendment case is + // interesting; pre-amendment nothing writes the field at all. + { + testcase("sfReferenceHolding: plain MPT issuance never set"); + Env env{*this, testableAmendments()}; + Account const issuer{"issuer"}; + env.fund(XRP(10'000), issuer); + env.close(); + + MPTTester mptt{env, issuer, kMptInitNoFund}; + mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); + env.close(); + + auto const sleIssuance = env.le(keylet::mptIssuance(mptt.issuanceID())); + if (BEAST_EXPECT(sleIssuance)) + BEAST_EXPECT(!sleIssuance->isFieldPresent(sfReferenceHolding)); + } + } + + // Probe every transactor surface that might delete the vault pseudo- + // account's underlying holding (the MPToken or RippleState pointed to + // by sfReferenceHolding). Each scenario asserts either that the + // existing pseudo-account guards stop the deletion at preclaim, or + // that the ledger leaves the holding intact afterwards. This is a + // regression guard: if any of these guards regresses, the share's + // sfReferenceHolding pointer would dangle and the new ValidMPTIssuance + // invariant would catch it - but we want to fail much earlier, at + // the transactor's preclaim / doApply, not at invariant time. + void + testHoldingDeletionBlocked() + { + using namespace test::jtx; + + // Helper: read the share's referenced holding and confirm the + // pointed-to SLE still exists after the probe. + auto referencedHoldingExists = [&](Env const& env, Keylet const& vaultKeylet) -> bool { + auto const sleVault = env.le(vaultKeylet); + if (!sleVault) + return false; + auto const sleIssuance = env.le(keylet::mptIssuance(sleVault->at(sfShareMPTID))); + if (!sleIssuance || !sleIssuance->isFieldPresent(sfReferenceHolding)) + return false; + auto const holdingKey = sleIssuance->getFieldH256(sfReferenceHolding); + return env.le(keylet::unchecked(holdingKey)) != nullptr; + }; + + // ---- MPT-backed vault ---------------------------------------- + { + testcase("vault pseudo MPToken: Clawback blocked by tecPSEUDO_ACCOUNT"); + Env env{*this, testableAmendments()}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + Account const depositor{"depositor"}; + env.fund(XRP(10'000), issuer, owner, depositor); + env.close(); + + MPTTester mptt{env, issuer, kMptInitNoFund}; + mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanClawback}); + PrettyAsset const asset = mptt.issuanceID(); + mptt.authorize({.account = owner}); + mptt.authorize({.account = depositor}); + env(pay(issuer, depositor, asset(1'000))); + env.close(); + + Vault const vault{env}; + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + env(tx); + env.close(); + + env(vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(500)})); + env.close(); + + BEAST_EXPECT(referencedHoldingExists(env, keylet)); + + Account const pseudoAccount{"vault-pseudo", env.le(keylet)->at(sfAccount)}; + // Issuer attempts to claw back the FULL underlying balance + // (500) directly from the vault pseudo-account. With the + // full amount, the doApply path would drain the pseudo's + // MPToken to zero and removeEmptyHolding would erase it - + // if doApply ever ran. SAV's pseudo-account guard at + // Clawback.cpp:201 refuses at preclaim with + // tecPSEUDO_ACCOUNT before any state change. + env(claw(issuer, asset(500), pseudoAccount), Ter{tecPSEUDO_ACCOUNT}); + env.close(); + BEAST_EXPECT(referencedHoldingExists(env, keylet)); + // Sanity: pseudo's full balance is intact. + BEAST_EXPECT(env.balance(pseudoAccount, asset).number() == 500); + } + + { + testcase("vault pseudo MPToken: Issuer cannot Unauthorize pseudo"); + Env env{*this, testableAmendments()}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + env.fund(XRP(10'000), issuer, owner); + env.close(); + + MPTTester mptt{env, issuer, kMptInitNoFund}; + mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTRequireAuth}); + PrettyAsset const asset = mptt.issuanceID(); + mptt.authorize({.account = owner}); + mptt.authorize({.account = issuer, .holder = owner}); + env.close(); + + Vault const vault{env}; + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + env(tx); + env.close(); + + BEAST_EXPECT(referencedHoldingExists(env, keylet)); + + auto const pseudoId = env.le(keylet)->at(sfAccount); + // Issuer attempts MPTokenAuthorize against the pseudo with + // tfMPTUnauthorize. MPTokenAuthorize.cpp blocks pseudo + // accounts via isPseudoAccount; the pseudo's MPToken is + // preserved. Construct the tx manually since the pseudo + // lacks a signing key, and the issuer-driven flavour is + // expressed via sfHolder. + json::Value jv; + jv[sfAccount] = issuer.human(); + jv[sfHolder] = toBase58(pseudoId); + jv[sfMPTokenIssuanceID] = to_string(mptt.issuanceID()); + jv[sfFlags] = tfMPTUnauthorize; + jv[sfTransactionType] = jss::MPTokenAuthorize; + env(jv, Ter{tecNO_PERMISSION}); + env.close(); + BEAST_EXPECT(referencedHoldingExists(env, keylet)); + } + + { + testcase("vault pseudo MPToken: MPTokenIssuanceDestroy blocked while vault holds"); + Env env{*this, testableAmendments()}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + Account const depositor{"depositor"}; + env.fund(XRP(10'000), issuer, owner, depositor); + env.close(); + + MPTTester mptt{env, issuer, kMptInitNoFund}; + mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); + PrettyAsset const asset = mptt.issuanceID(); + mptt.authorize({.account = owner}); + mptt.authorize({.account = depositor}); + env(pay(issuer, depositor, asset(1'000))); + env.close(); + + Vault const vault{env}; + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + env(tx); + env.close(); + + env(vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(500)})); + env.close(); + + BEAST_EXPECT(referencedHoldingExists(env, keylet)); + + // While the vault holds outstanding underlying, the issuer + // cannot destroy the issuance. tecHAS_OBLIGATIONS confirms + // the protection - and as a side effect, the share's + // sfReferenceHolding pointer cannot be left pointing at a + // ghost issuance. + mptt.destroy({.id = mptt.issuanceID(), .err = tecHAS_OBLIGATIONS}); + env.close(); + BEAST_EXPECT(referencedHoldingExists(env, keylet)); + } + + // ---- IOU-backed vault ---------------------------------------- + { + testcase("vault pseudo trust line: Clawback blocked by tecPSEUDO_ACCOUNT"); + Env env{*this, testableAmendments()}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + env.fund(XRP(10'000), issuer, owner); + env(fset(issuer, asfAllowTrustLineClawback)); + env.close(); + + PrettyAsset const asset = issuer["IOU"]; + env.trust(asset(1'000'000), owner); + env(pay(issuer, owner, asset(1'000))); + env.close(); + + Vault const vault{env}; + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + env(tx); + env.close(); + + env(vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(500)})); + env.close(); + + BEAST_EXPECT(referencedHoldingExists(env, keylet)); + + Account const pseudoAccount{"vault-pseudo", env.le(keylet)->at(sfAccount)}; + // Issuer attempts to claw back the FULL IOU balance (500) + // directly from the vault pseudo. With the full amount, the + // doApply path would drain the trust line to zero and (if + // both reserve flags clear) trustDelete would erase it - if + // doApply ever ran. The same SAV pseudo-account guard + // refuses at preclaim with tecPSEUDO_ACCOUNT. The amount's + // STAmount issuer field is the holder, per IOU clawback + // convention. + env(claw(issuer, pseudoAccount["IOU"](500)), Ter{tecPSEUDO_ACCOUNT}); + env.close(); + BEAST_EXPECT(referencedHoldingExists(env, keylet)); + // Sanity: pseudo's full balance is intact. + BEAST_EXPECT(env.balance(pseudoAccount, asset).number() == 500); + } + + { + testcase("vault pseudo trust line: TrustSet limit=0 from issuer preserves line"); + Env env{*this, testableAmendments()}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + env.fund(XRP(10'000), issuer, owner); + env(fset(issuer, asfDefaultRipple)); + env.close(); + + PrettyAsset const asset = issuer["IOU"]; + env.trust(asset(1'000'000), owner); + env(pay(issuer, owner, asset(1'000))); + env.close(); + + Vault const vault{env}; + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + env(tx); + env.close(); + + env(vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(500)})); + env.close(); + + BEAST_EXPECT(referencedHoldingExists(env, keylet)); + + // Issuer submits TrustSet with limit=0 against the vault + // pseudo. The pseudo's side of the line still has the + // original (non-zero) limit and a non-zero balance, so the + // line is preserved - even though the issuer cleared its + // own side. trustDelete only fires when both limits clear + // and the balance is zero. + Account const pseudoAccount{"vault-pseudo", env.le(keylet)->at(sfAccount)}; + env(trust(issuer, pseudoAccount["IOU"](0))); + env.close(); + BEAST_EXPECT(referencedHoldingExists(env, keylet)); + } + + // ---- Positive control: VaultDelete is the only legitimate path + { + testcase("vault pseudo holding: VaultDelete is the legitimate cleanup path"); + Env env{*this, testableAmendments()}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + env.fund(XRP(10'000), issuer, owner); + env.close(); + + MPTTester mptt{env, issuer, kMptInitNoFund}; + mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock}); + PrettyAsset const asset = mptt.issuanceID(); + mptt.authorize({.account = owner}); + + Vault const vault{env}; + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + env(tx); + env.close(); + + BEAST_EXPECT(referencedHoldingExists(env, keylet)); + auto const pseudoId = env.le(keylet)->at(sfAccount); + auto const sharedMptId = env.le(keylet)->at(sfShareMPTID); + auto const holdingKeylet = keylet::mptoken(mptt.issuanceID(), pseudoId); + + // VaultDelete tears down the vault pseudo's holding, the + // share issuance, and the pseudo-account itself. Invariant + // permits this because the tx is ttVAULT_DELETE. + env(vault.del({.owner = owner, .id = keylet.key})); + env.close(); + + BEAST_EXPECT(env.le(keylet) == nullptr); + BEAST_EXPECT(env.le(holdingKeylet) == nullptr); + BEAST_EXPECT(env.le(keylet::mptIssuance(sharedMptId)) == nullptr); + } + } + // VaultDeposit::preclaim uses accountHolds(..., SpendableHandling:: // shFULL_BALANCE), which for an IOU asset adds the counterparty's // LowLimit/HighLimit to the depositor's raw balance (TokenHelpers.cpp: @@ -6243,6 +6881,8 @@ public: testAssetsMaximum(); testBug6LimitBypassWithShares(); testRemoveEmptyHoldingLockedAmount(); + testReferenceHolding(); + testHoldingDeletionBlocked(); } }; diff --git a/src/tests/libxrpl/protocol_autogen/ledger_entries/MPTokenIssuanceTests.cpp b/src/tests/libxrpl/protocol_autogen/ledger_entries/MPTokenIssuanceTests.cpp index e74af94a5f..7479f0c63c 100644 --- a/src/tests/libxrpl/protocol_autogen/ledger_entries/MPTokenIssuanceTests.cpp +++ b/src/tests/libxrpl/protocol_autogen/ledger_entries/MPTokenIssuanceTests.cpp @@ -33,6 +33,7 @@ TEST(MPTokenIssuanceTests, BuilderSettersRoundTrip) auto const previousTxnLgrSeqValue = canonical_UINT32(); auto const domainIDValue = canonical_UINT256(); auto const mutableFlagsValue = canonical_UINT32(); + auto const referenceHoldingValue = canonical_UINT256(); MPTokenIssuanceBuilder builder{ issuerValue, @@ -50,6 +51,7 @@ TEST(MPTokenIssuanceTests, BuilderSettersRoundTrip) builder.setMPTokenMetadata(mPTokenMetadataValue); builder.setDomainID(domainIDValue); builder.setMutableFlags(mutableFlagsValue); + builder.setReferenceHolding(referenceHoldingValue); builder.setLedgerIndex(index); builder.setFlags(0x1u); @@ -152,6 +154,14 @@ TEST(MPTokenIssuanceTests, BuilderSettersRoundTrip) EXPECT_TRUE(entry.hasMutableFlags()); } + { + auto const& expected = referenceHoldingValue; + auto const actualOpt = entry.getReferenceHolding(); + ASSERT_TRUE(actualOpt.has_value()); + expectEqualField(expected, *actualOpt, "sfReferenceHolding"); + EXPECT_TRUE(entry.hasReferenceHolding()); + } + EXPECT_TRUE(entry.hasLedgerIndex()); auto const ledgerIndex = entry.getLedgerIndex(); ASSERT_TRUE(ledgerIndex.has_value()); @@ -178,6 +188,7 @@ TEST(MPTokenIssuanceTests, BuilderFromSleRoundTrip) auto const previousTxnLgrSeqValue = canonical_UINT32(); auto const domainIDValue = canonical_UINT256(); auto const mutableFlagsValue = canonical_UINT32(); + auto const referenceHoldingValue = canonical_UINT256(); auto sle = std::make_shared(MPTokenIssuance::entryType, index); @@ -194,6 +205,7 @@ TEST(MPTokenIssuanceTests, BuilderFromSleRoundTrip) sle->at(sfPreviousTxnLgrSeq) = previousTxnLgrSeqValue; sle->at(sfDomainID) = domainIDValue; sle->at(sfMutableFlags) = mutableFlagsValue; + sle->at(sfReferenceHolding) = referenceHoldingValue; MPTokenIssuanceBuilder builderFromSle{sle}; EXPECT_TRUE(builderFromSle.validate()); @@ -355,6 +367,19 @@ TEST(MPTokenIssuanceTests, BuilderFromSleRoundTrip) expectEqualField(expected, *fromBuilderOpt, "sfMutableFlags"); } + { + auto const& expected = referenceHoldingValue; + + auto const fromSleOpt = entryFromSle.getReferenceHolding(); + auto const fromBuilderOpt = entryFromBuilder.getReferenceHolding(); + + ASSERT_TRUE(fromSleOpt.has_value()); + ASSERT_TRUE(fromBuilderOpt.has_value()); + + expectEqualField(expected, *fromSleOpt, "sfReferenceHolding"); + expectEqualField(expected, *fromBuilderOpt, "sfReferenceHolding"); + } + EXPECT_EQ(entryFromSle.getKey(), index); EXPECT_EQ(entryFromBuilder.getKey(), index); } @@ -433,5 +458,7 @@ TEST(MPTokenIssuanceTests, OptionalFieldsReturnNullopt) EXPECT_FALSE(entry.getDomainID().has_value()); EXPECT_FALSE(entry.hasMutableFlags()); EXPECT_FALSE(entry.getMutableFlags().has_value()); + EXPECT_FALSE(entry.hasReferenceHolding()); + EXPECT_FALSE(entry.getReferenceHolding().has_value()); } } From a5d238e7d4fa6ef2b539b759d58744d0a1c33c0c Mon Sep 17 00:00:00 2001 From: box4wangjing Date: Thu, 21 May 2026 04:46:45 +0900 Subject: [PATCH 11/17] docs: Fix some comments to improve readability (#7122) Signed-off-by: box4wangjing Co-authored-by: Mayukha Vadari --- include/xrpl/json/Writer.h | 2 +- include/xrpl/protocol/detail/ledger_entries.macro | 2 +- include/xrpl/shamap/README.md | 2 +- src/libxrpl/protocol/STAmount.cpp | 2 +- src/test/app/NFTokenBurn_test.cpp | 4 ++-- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/include/xrpl/json/Writer.h b/include/xrpl/json/Writer.h index 664a2a75c1..87e3e99c7e 100644 --- a/include/xrpl/json/Writer.h +++ b/include/xrpl/json/Writer.h @@ -161,7 +161,7 @@ public: * While the JSON spec doesn't explicitly disallow this, you should avoid * calling this method twice with the same tag for the same object. * - * If CHECK_JSON_WRITER is defined, this function throws an exception if if + * If CHECK_JSON_WRITER is defined, this function throws an exception if * the tag you use has already been used in this object. */ template diff --git a/include/xrpl/protocol/detail/ledger_entries.macro b/include/xrpl/protocol/detail/ledger_entries.macro index 19b8b44fe6..632038a9c5 100644 --- a/include/xrpl/protocol/detail/ledger_entries.macro +++ b/include/xrpl/protocol/detail/ledger_entries.macro @@ -592,7 +592,7 @@ LEDGER_ENTRY(ltLOAN, 0x0089, Loan, loan, ({ // LoanBroker.ManagementFeeRate // The unrounded true total fee still owed to the broker. // - // Note the the "True" values may differ significantly from the tracked + // Note the "True" values may differ significantly from the tracked // rounded values. {sfPaymentRemaining, SoeDefault}, {sfPeriodicPayment, SoeRequired}, diff --git a/include/xrpl/shamap/README.md b/include/xrpl/shamap/README.md index ae37d23ac3..8931a1b50c 100644 --- a/include/xrpl/shamap/README.md +++ b/include/xrpl/shamap/README.md @@ -231,7 +231,7 @@ The `fetchNodeNT()` method goes through three phases: will be 0. 2. If the node is not in the TreeNodeCache, we attempt to locate the node - in the historic data stored by the data base. The call to to + in the historic data stored by the data base. The call to `fetchNodeFromDB(hash)` does that work for us. 3. Finally if a filter exists, we check if it can supply the node. This is diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index 3cbf03575b..2282488fb6 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -1505,7 +1505,7 @@ roundToScale(STAmount const& value, std::int32_t scale, Number::RoundingMode rou STAmount const referenceValue{value.asset(), STAmount::kMinValue, scale, value.negative()}; NumberRoundModeGuard const mg(rounding); - // With an IOU, the the result of addition will be truncated to the + // With an IOU, the result of addition will be truncated to the // precision of the larger value, which in this case is referenceValue. Then // remove the reference value via subtraction, and we're left with the // rounded value. diff --git a/src/test/app/NFTokenBurn_test.cpp b/src/test/app/NFTokenBurn_test.cpp index f08793da72..482d275d51 100644 --- a/src/test/app/NFTokenBurn_test.cpp +++ b/src/test/app/NFTokenBurn_test.cpp @@ -515,7 +515,7 @@ class NFTokenBurn_test : public beast::unit_test::Suite { // Removing the last token from the last page deletes the // _previous_ page because we need to preserve that last - // page an an anchor. The contents of the next-to-last page + // page as an anchor. The contents of the next-to-last page // are moved into the last page. lastNFTokenPage = env.le(keylet::nftpageMax(alice)); BEAST_EXPECT(lastNFTokenPage); @@ -694,7 +694,7 @@ class NFTokenBurn_test : public beast::unit_test::Suite { // Removing the last token from the last page deletes the // _previous_ page because we need to preserve that last - // page an an anchor. The contents of the next-to-last page + // page as an anchor. The contents of the next-to-last page // are moved into the last page. lastNFTokenPage = env.le(keylet::nftpageMax(alice)); BEAST_EXPECT(lastNFTokenPage); From 242ce3e9e4280aa7f9e6292062117c8ccd8861c8 Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Wed, 20 May 2026 15:47:59 -0400 Subject: [PATCH 12/17] refactor: Fix `sfGeneric` and `sfInvalid` field names (#7300) --- include/xrpl/protocol/SField.h | 4 +-- include/xrpl/protocol/STBlob.h | 2 +- src/libxrpl/protocol/SField.cpp | 8 ++--- src/libxrpl/protocol/STAmount.cpp | 2 +- src/libxrpl/protocol/STBase.cpp | 2 +- src/libxrpl/protocol/STParsedJSON.cpp | 12 +++---- src/libxrpl/protocol/XChainAttestations.cpp | 4 +-- src/libxrpl/server/Manifest.cpp | 10 +++--- src/test/app/Manifest_test.cpp | 18 +++++------ src/test/app/Path_test.cpp | 6 ++-- src/test/app/ValidatorList_test.cpp | 4 +-- src/test/jtx/TrustedPublisherServer.h | 2 +- src/test/jtx/impl/TestHelpers.cpp | 6 ++-- src/test/overlay/compression_test.cpp | 6 ++-- src/test/protocol/Hooks_test.cpp | 6 ++-- src/test/protocol/STAmount_test.cpp | 2 +- src/test/protocol/STObject_test.cpp | 32 +++++++++---------- src/test/protocol/STTx_test.cpp | 2 +- src/test/rpc/Simulate_test.cpp | 4 +-- .../libxrpl/protocol_autogen/TestHelpers.h | 2 +- .../rpc/handlers/transaction/Simulate.cpp | 2 +- 21 files changed, 68 insertions(+), 68 deletions(-) diff --git a/include/xrpl/protocol/SField.h b/include/xrpl/protocol/SField.h index 1d4e4e69a0..34fb66ce00 100644 --- a/include/xrpl/protocol/SField.h +++ b/include/xrpl/protocol/SField.h @@ -365,8 +365,8 @@ using SF_XCHAIN_BRIDGE = TypedField; #define UNTYPED_SFIELD(sfName, stiSuffix, fieldValue, ...) extern SField const sfName; #define TYPED_SFIELD(sfName, stiSuffix, fieldValue, ...) extern SF_##stiSuffix const sfName; -extern SField const kSfInvalid; -extern SField const kSfGeneric; +extern SField const sfInvalid; // NOLINT(readability-identifier-naming) +extern SField const sfGeneric; // NOLINT(readability-identifier-naming) #include diff --git a/include/xrpl/protocol/STBlob.h b/include/xrpl/protocol/STBlob.h index c9110a367e..0667c54e30 100644 --- a/include/xrpl/protocol/STBlob.h +++ b/include/xrpl/protocol/STBlob.h @@ -24,7 +24,7 @@ public: STBlob(SField const& f, void const* data, std::size_t size); STBlob(SField const& f, Buffer&& b); STBlob(SField const& n); - STBlob(SerialIter&, SField const& name = kSfGeneric); + STBlob(SerialIter&, SField const& name = sfGeneric); [[nodiscard]] std::size_t size() const; diff --git a/src/libxrpl/protocol/SField.cpp b/src/libxrpl/protocol/SField.cpp index f2a523db49..a2d4903c6a 100644 --- a/src/libxrpl/protocol/SField.cpp +++ b/src/libxrpl/protocol/SField.cpp @@ -53,8 +53,8 @@ TypedField::TypedField(PrivateAccessTagT pat, Args&&... args) ##__VA_ARGS__); // SFields which, for historical reasons, do not follow naming conventions. -SField const kSfInvalid(access, -1, ""); -SField const kSfGeneric(access, 0, "Generic"); +SField const sfInvalid(access, -1, ""); +SField const sfGeneric(access, 0, "Generic"); // The following two fields aren't used anywhere, but they break tests/have // downstream effects. SField const kSfHash(access, STI_UINT256, 257, "hash"); @@ -121,7 +121,7 @@ SField::getField(int code) { return *(it->second); } - return kSfInvalid; + return sfInvalid; } int @@ -149,7 +149,7 @@ SField::getField(std::string const& fieldName) { return *(it->second); } - return kSfInvalid; + return sfInvalid; } } // namespace xrpl diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index 2282488fb6..2d051722bf 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -1151,7 +1151,7 @@ amountFromJsonNoThrow(STAmount& result, json::Value const& jvSource) { try { - result = amountFromJson(kSfGeneric, jvSource); + result = amountFromJson(sfGeneric, jvSource); return true; } catch (std::exception const& e) diff --git a/src/libxrpl/protocol/STBase.cpp b/src/libxrpl/protocol/STBase.cpp index d1ae1e5aa8..f029f10e75 100644 --- a/src/libxrpl/protocol/STBase.cpp +++ b/src/libxrpl/protocol/STBase.cpp @@ -12,7 +12,7 @@ namespace xrpl { -STBase::STBase() : fName_(&kSfGeneric) +STBase::STBase() : fName_(&sfGeneric) { } diff --git a/src/libxrpl/protocol/STParsedJSON.cpp b/src/libxrpl/protocol/STParsedJSON.cpp index 7b9989afac..64c4dfd1be 100644 --- a/src/libxrpl/protocol/STParsedJSON.cpp +++ b/src/libxrpl/protocol/STParsedJSON.cpp @@ -258,7 +258,7 @@ parseUInt16( safeCast(static_cast( TxFormats::getInstance().findTypeByName(strValue)))); - if (*name == kSfGeneric) + if (*name == sfGeneric) name = &sfTransaction; } else if (field == sfLedgerEntryType) @@ -268,7 +268,7 @@ parseUInt16( safeCast(static_cast( LedgerFormats::getInstance().findTypeByName(strValue)))); - if (*name == kSfGeneric) + if (*name == sfGeneric) name = &sfLedgerEntry; } else @@ -361,7 +361,7 @@ parseLeaf( auto const& field = SField::getField(fieldName); // checked in parseObject - if (field == kSfInvalid) + if (field == sfInvalid) { // LCOV_EXCL_START error = unknownField(jsonName, fieldName); @@ -1013,7 +1013,7 @@ parseObject( json::Value const& value = json[fieldName]; auto const& field = SField::getField(fieldName); - if (field == kSfInvalid) + if (field == sfInvalid) { error = unknownField(jsonName, fieldName); return std::nullopt; @@ -1144,7 +1144,7 @@ parseArray( std::string const memberName(json[i].getMemberNames()[0]); auto const& nameField(SField::getField(memberName)); - if (nameField == kSfInvalid) + if (nameField == sfInvalid) { error = unknownField(jsonName, memberName); return std::nullopt; @@ -1189,7 +1189,7 @@ parseArray( STParsedJSONObject::STParsedJSONObject(std::string const& name, json::Value const& json) { using namespace STParsedJSONDetail; - object = parseObject(name, json, kSfGeneric, 0, error); + object = parseObject(name, json, sfGeneric, 0, error); } } // namespace xrpl diff --git a/src/libxrpl/protocol/XChainAttestations.cpp b/src/libxrpl/protocol/XChainAttestations.cpp index e41e5f3d61..805d08c097 100644 --- a/src/libxrpl/protocol/XChainAttestations.cpp +++ b/src/libxrpl/protocol/XChainAttestations.cpp @@ -195,7 +195,7 @@ AttestationClaim::message( std::uint64_t claimID, std::optional const& dst) { - STObject o{kSfGeneric}; + STObject o{sfGeneric}; // Serialize in SField order to make python serializers easier to write o[sfXChainClaimID] = claimID; o[sfAmount] = sendingAmount; @@ -332,7 +332,7 @@ AttestationCreateAccount::message( std::uint64_t createCount, AccountID const& dst) { - STObject o{kSfGeneric}; + STObject o{sfGeneric}; // Serialize in SField order to make python serializers easier to write o[sfXChainAccountCreateCount] = createCount; o[sfAmount] = sendingAmount; diff --git a/src/libxrpl/server/Manifest.cpp b/src/libxrpl/server/Manifest.cpp index 1b0493dd9d..b26c67e531 100644 --- a/src/libxrpl/server/Manifest.cpp +++ b/src/libxrpl/server/Manifest.cpp @@ -90,7 +90,7 @@ deserializeManifest(Slice s, beast::Journal journal) try { SerialIter sit{s}; - STObject st{sit, kSfGeneric}; + STObject st{sit, sfGeneric}; st.applyTemplate(kManifestFormat); @@ -193,7 +193,7 @@ logMftAct( bool Manifest::verify() const { - STObject st(kSfGeneric); + STObject st(sfGeneric); SerialIter sit(serialized.data(), serialized.size()); st.set(sit); @@ -213,7 +213,7 @@ Manifest::verify() const uint256 Manifest::hash() const { - STObject st(kSfGeneric); + STObject st(sfGeneric); SerialIter sit(serialized.data(), serialized.size()); st.set(sit); return st.getHash(HashPrefix::Manifest); @@ -240,7 +240,7 @@ Manifest::revoked(std::uint32_t sequence) std::optional Manifest::getSignature() const { - STObject st(kSfGeneric); + STObject st(sfGeneric); SerialIter sit(serialized.data(), serialized.size()); st.set(sit); if (!get(st, sfSignature)) @@ -251,7 +251,7 @@ Manifest::getSignature() const Blob Manifest::getMasterSignature() const { - STObject st(kSfGeneric); + STObject st(sfGeneric); SerialIter sit(serialized.data(), serialized.size()); st.set(sit); return st.getFieldVL(sfMasterSignature); diff --git a/src/test/app/Manifest_test.cpp b/src/test/app/Manifest_test.cpp index 55aa93bf79..d559ecd7b5 100644 --- a/src/test/app/Manifest_test.cpp +++ b/src/test/app/Manifest_test.cpp @@ -115,7 +115,7 @@ public: SecretKey const& ssk, int seq) { - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = seq; st[sfPublicKey] = pk; st[sfSigningPubKey] = spk; @@ -137,7 +137,7 @@ public: { auto const pk = derivePublicKey(type, sk); - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = std::numeric_limits::max(); st[sfPublicKey] = pk; @@ -156,7 +156,7 @@ public: { auto const pk = derivePublicKey(type, sk); - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = std::numeric_limits::max(); st[sfPublicKey] = pk; @@ -186,7 +186,7 @@ public: auto const pk = derivePublicKey(type, sk); auto const spk = derivePublicKey(stype, ssk); - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = seq; st[sfPublicKey] = pk; st[sfSigningPubKey] = spk; @@ -363,7 +363,7 @@ public: auto const kp = randomKeyPair(KeyType::Secp256k1); auto const m = makeManifest(sk, KeyType::Ed25519, kp.second, KeyType::Secp256k1, 0); - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = 0; st[sfPublicKey] = pk; st[sfSigningPubKey] = kp.first; @@ -495,7 +495,7 @@ public: auto const spk = derivePublicKey(KeyType::Secp256k1, ssk); auto buildManifestObject = [&](std::uint16_t version) { - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = 3; st[sfPublicKey] = pk; st[sfSigningPubKey] = spk; @@ -573,7 +573,7 @@ public: std::optional domain, bool noSigningPublic = false, bool noSignature = false) { - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = seq; st[sfPublicKey] = pk; @@ -724,7 +724,7 @@ public: } { // reject matching master & ephemeral keys - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = 314159; st[sfPublicKey] = pk; st[sfSigningPubKey] = pk; @@ -797,7 +797,7 @@ public: auto const pk2 = derivePublicKey(KeyType::Secp256k1, sk2); auto test = [&](std::string domain) { - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = 7; st[sfPublicKey] = pk1; st[sfDomain] = makeSlice(domain); diff --git a/src/test/app/Path_test.cpp b/src/test/app/Path_test.cpp index 22044a2572..1cf8131206 100644 --- a/src/test/app/Path_test.cpp +++ b/src/test/app/Path_test.cpp @@ -216,7 +216,7 @@ public: STAmount da; if (result.isMember(jss::destination_amount)) - da = amountFromJson(kSfGeneric, result[jss::destination_amount]); + da = amountFromJson(sfGeneric, result[jss::destination_amount]); STAmount sa; STPathSet paths; @@ -228,10 +228,10 @@ public: auto const& path = alts[0u]; if (path.isMember(jss::source_amount)) - sa = amountFromJson(kSfGeneric, path[jss::source_amount]); + sa = amountFromJson(sfGeneric, path[jss::source_amount]); if (path.isMember(jss::destination_amount)) - da = amountFromJson(kSfGeneric, path[jss::destination_amount]); + da = amountFromJson(sfGeneric, path[jss::destination_amount]); if (path.isMember(jss::paths_computed)) { diff --git a/src/test/app/ValidatorList_test.cpp b/src/test/app/ValidatorList_test.cpp index 15bd1bc586..1b66dd305d 100644 --- a/src/test/app/ValidatorList_test.cpp +++ b/src/test/app/ValidatorList_test.cpp @@ -81,7 +81,7 @@ private: SecretKey const& ssk, int seq) { - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = seq; st[sfPublicKey] = pk; @@ -104,7 +104,7 @@ private: static std::string makeRevocationString(PublicKey const& pk, SecretKey const& sk) { - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = std::numeric_limits::max(); st[sfPublicKey] = pk; diff --git a/src/test/jtx/TrustedPublisherServer.h b/src/test/jtx/TrustedPublisherServer.h index 4c7528ccc3..9a53a32481 100644 --- a/src/test/jtx/TrustedPublisherServer.h +++ b/src/test/jtx/TrustedPublisherServer.h @@ -101,7 +101,7 @@ public: SecretKey const& ssk, int seq) { - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = seq; st[sfPublicKey] = pk; st[sfSigningPubKey] = spk; diff --git a/src/test/jtx/impl/TestHelpers.cpp b/src/test/jtx/impl/TestHelpers.cpp index 3e65410825..e9ea48fb39 100644 --- a/src/test/jtx/impl/TestHelpers.cpp +++ b/src/test/jtx/impl/TestHelpers.cpp @@ -262,7 +262,7 @@ findPaths( STAmount da; if (result.isMember(jss::destination_amount)) - da = amountFromJson(kSfGeneric, result[jss::destination_amount]); + da = amountFromJson(sfGeneric, result[jss::destination_amount]); STAmount sa; STPathSet paths; @@ -274,10 +274,10 @@ findPaths( auto const& path = alts[0u]; if (path.isMember(jss::source_amount)) - sa = amountFromJson(kSfGeneric, path[jss::source_amount]); + sa = amountFromJson(sfGeneric, path[jss::source_amount]); if (path.isMember(jss::destination_amount)) - da = amountFromJson(kSfGeneric, path[jss::destination_amount]); + da = amountFromJson(sfGeneric, path[jss::destination_amount]); if (path.isMember(jss::paths_computed)) { diff --git a/src/test/overlay/compression_test.cpp b/src/test/overlay/compression_test.cpp index adb3b1b27b..d98ffa9b33 100644 --- a/src/test/overlay/compression_test.cpp +++ b/src/test/overlay/compression_test.cpp @@ -142,7 +142,7 @@ public: { auto master = randomKeyPair(KeyType::Ed25519); auto signing = randomKeyPair(KeyType::Ed25519); - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = i; st[sfPublicKey] = std::get<0>(master); st[sfSigningPubKey] = std::get<0>(signing); @@ -299,7 +299,7 @@ public: auto master = randomKeyPair(KeyType::Ed25519); auto signing = randomKeyPair(KeyType::Ed25519); - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = 0; st[sfPublicKey] = std::get<0>(master); st[sfSigningPubKey] = std::get<0>(signing); @@ -326,7 +326,7 @@ public: auto master = randomKeyPair(KeyType::Ed25519); auto signing = randomKeyPair(KeyType::Ed25519); - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfSequence] = 0; st[sfPublicKey] = std::get<0>(master); st[sfSigningPubKey] = std::get<0>(signing); diff --git a/src/test/protocol/Hooks_test.cpp b/src/test/protocol/Hooks_test.cpp index 20fe205579..082507aca7 100644 --- a/src/test/protocol/Hooks_test.cpp +++ b/src/test/protocol/Hooks_test.cpp @@ -73,7 +73,7 @@ class Hooks_test : public beast::unit_test::Suite { SField const& f = rf.get(); - STObject dummy{kSfGeneric}; + STObject dummy{sfGeneric}; BEAST_EXPECT(!dummy.isFieldPresent(f)); @@ -161,8 +161,8 @@ class Hooks_test : public beast::unit_test::Suite case STI_ARRAY: { STArray dummy2{f, 2}; - dummy2.pushBack(STObject{kSfGeneric}); - dummy2.pushBack(STObject{kSfGeneric}); + dummy2.pushBack(STObject{sfGeneric}); + dummy2.pushBack(STObject{sfGeneric}); dummy.setFieldArray(f, dummy2); BEAST_EXPECT(dummy.getFieldArray(f) == dummy2); BEAST_EXPECT(dummy.isFieldPresent(f)); diff --git a/src/test/protocol/STAmount_test.cpp b/src/test/protocol/STAmount_test.cpp index b387c361cb..322d51f84d 100644 --- a/src/test/protocol/STAmount_test.cpp +++ b/src/test/protocol/STAmount_test.cpp @@ -37,7 +37,7 @@ public: s.add(ser); SerialIter sit(ser.slice()); - return STAmount(sit, kSfGeneric); + return STAmount(sit, sfGeneric); } //-------------------------------------------------------------------------- diff --git a/src/test/protocol/STObject_test.cpp b/src/test/protocol/STObject_test.cpp index 59b78d213d..801eebbe63 100644 --- a/src/test/protocol/STObject_test.cpp +++ b/src/test/protocol/STObject_test.cpp @@ -36,19 +36,19 @@ public: { testcase("serialization"); - unexpected(kSfGeneric.isUseful(), "sfGeneric must not be useful"); + unexpected(sfGeneric.isUseful(), "sfGeneric must not be useful"); { // Try to put sfGeneric in an SOTemplate. except( - [&]() { SOTemplate const elements{{kSfGeneric, SoeRequired}}; }); + [&]() { SOTemplate const elements{{sfGeneric, SoeRequired}}; }); } - unexpected(kSfInvalid.isUseful(), "sfInvalid must not be useful"); + unexpected(sfInvalid.isUseful(), "sfInvalid must not be useful"); { // Test return of sfInvalid. auto testInvalid = [this](SerializedTypeID tid, int fv) { SField const& shouldBeInvalid{SField::getField(tid, fv)}; - BEAST_EXPECT(shouldBeInvalid == kSfInvalid); + BEAST_EXPECT(shouldBeInvalid == sfInvalid); }; testInvalid(STI_VL, 255); testInvalid(STI_UINT256, 255); @@ -59,7 +59,7 @@ public: { // Try to put sfInvalid in an SOTemplate. except( - [&]() { SOTemplate const elements{{kSfInvalid, SoeRequired}}; }); + [&]() { SOTemplate const elements{{sfInvalid, SoeRequired}}; }); } { // Try to put the same SField into an SOTemplate twice. @@ -188,7 +188,7 @@ public: { auto const st = [&]() { - STObject s(kSfGeneric); + STObject s(sfGeneric); s.setFieldU32(sf1Outer, 1); s.setFieldU32(sf2Outer, 2); return s; @@ -219,7 +219,7 @@ public: { auto const st = [&]() { - STObject s(sotOuter, kSfGeneric); + STObject s(sotOuter, sfGeneric); s.setFieldU32(sf1Outer, 1); s.setFieldU32(sf2Outer, 2); return s; @@ -239,7 +239,7 @@ public: // write free object { - STObject st(kSfGeneric); + STObject st(sfGeneric); unexcept([&]() { st[sf1Outer]; }); except([&]() { return st[sf1Outer] == 0; }); BEAST_EXPECT(st[~sf1Outer] == std::nullopt); @@ -295,7 +295,7 @@ public: // Write templated object { - STObject st(sotOuter, kSfGeneric); + STObject st(sotOuter, sfGeneric); BEAST_EXPECT(!!st[~sf1Outer]); BEAST_EXPECT(st[~sf1Outer] != std::nullopt); BEAST_EXPECT(st[sf1Outer] == 0); @@ -353,7 +353,7 @@ public: // coercion operator to std::optional { - STObject st(kSfGeneric); + STObject st(sfGeneric); auto const v = ~st[~sf1Outer]; static_assert( std::is_same_v, std::optional>, ""); @@ -362,7 +362,7 @@ public: // UDT scalar fields { - STObject st(kSfGeneric); + STObject st(sfGeneric); st[sfAmount] = STAmount{}; st[sfAccount] = AccountID{}; st[sfDigest] = uint256{}; @@ -375,7 +375,7 @@ public: { { - STObject st(kSfGeneric); + STObject st(sfGeneric); Buffer b(1); BEAST_EXPECT(!b.empty()); st[sf4] = std::move(b); @@ -392,7 +392,7 @@ public: BEAST_EXPECT(Slice(st[sf5]).size() == 2); } { - STObject st(sotOuter, kSfGeneric); + STObject st(sotOuter, sfGeneric); BEAST_EXPECT(st[sf5] == Slice{}); BEAST_EXPECT(!!st[~sf5]); BEAST_EXPECT(!!~st[~sf5]); @@ -408,7 +408,7 @@ public: // UDT blobs { - STObject st(kSfGeneric); + STObject st(sfGeneric); BEAST_EXPECT(!st[~sf5]); auto const kp = generateKeyPair(KeyType::Secp256k1, generateSeed("masterpassphrase")); st[sf5] = kp.first; @@ -419,7 +419,7 @@ public: { auto const& sf = sfIndexes; - STObject st(kSfGeneric); + STObject st(sfGeneric); std::vector v; v.emplace_back(1); v.emplace_back(2); @@ -446,7 +446,7 @@ public: {sf3, SoeDefault}, }; - STObject st(sot, kSfGeneric); + STObject st(sot, sfGeneric); auto const& cst(st); BEAST_EXPECT(cst[sf1].empty()); BEAST_EXPECT(!cst[~sf2]); diff --git a/src/test/protocol/STTx_test.cpp b/src/test/protocol/STTx_test.cpp index 42cb2bb9a7..21518d1406 100644 --- a/src/test/protocol/STTx_test.cpp +++ b/src/test/protocol/STTx_test.cpp @@ -1390,7 +1390,7 @@ public: // Lambda that returns a Payment STObject. auto getPayment = [kp1, id1, id2]() { // Account id1 pays account id2 10,000 XRP. - STObject payment(kSfGeneric); + STObject payment(sfGeneric); payment.setFieldU16(sfTransactionType, ttPAYMENT); payment.setAccountID(sfAccount, id1); payment.setAccountID(sfDestination, id2); diff --git a/src/test/rpc/Simulate_test.cpp b/src/test/rpc/Simulate_test.cpp index b66b3dfe9f..60452e386a 100644 --- a/src/test/rpc/Simulate_test.cpp +++ b/src/test/rpc/Simulate_test.cpp @@ -66,7 +66,7 @@ class Simulate_test : public beast::unit_test::Suite { auto const unHexed = strUnHex(result[jss::tx_blob].asString()); SerialIter sitTrans(makeSlice(*unHexed)); // NOLINT(bugprone-unchecked-optional-access) - txJson = STObject(std::ref(sitTrans), kSfGeneric).getJson(JsonOptions::Values::None); + txJson = STObject(std::ref(sitTrans), sfGeneric).getJson(JsonOptions::Values::None); } BEAST_EXPECT(txJson[jss::TransactionType] == tx[jss::TransactionType]); BEAST_EXPECT(txJson[jss::Account] == tx[jss::Account]); @@ -162,7 +162,7 @@ class Simulate_test : public beast::unit_test::Suite { auto unHexed = strUnHex(txResult[jss::meta_blob].asString()); SerialIter sitTrans(makeSlice(*unHexed)); // NOLINT(bugprone-unchecked-optional-access) - return STObject(std::ref(sitTrans), kSfGeneric).getJson(JsonOptions::Values::None); + return STObject(std::ref(sitTrans), sfGeneric).getJson(JsonOptions::Values::None); } return txResult[jss::meta]; diff --git a/src/tests/libxrpl/protocol_autogen/TestHelpers.h b/src/tests/libxrpl/protocol_autogen/TestHelpers.h index b8449f2bca..a32ab5e20c 100644 --- a/src/tests/libxrpl/protocol_autogen/TestHelpers.h +++ b/src/tests/libxrpl/protocol_autogen/TestHelpers.h @@ -159,7 +159,7 @@ canonical_ARRAY() inline STObject canonical_OBJECT() { - return STObject{kSfGeneric}; + return STObject{sfGeneric}; } inline STPathSet diff --git a/src/xrpld/rpc/handlers/transaction/Simulate.cpp b/src/xrpld/rpc/handlers/transaction/Simulate.cpp index ba108eb5b2..7a11b728ce 100644 --- a/src/xrpld/rpc/handlers/transaction/Simulate.cpp +++ b/src/xrpld/rpc/handlers/transaction/Simulate.cpp @@ -194,7 +194,7 @@ getTxJsonFromParams(json::Value const& params) try { SerialIter sitTrans(makeSlice(*unHexed)); - txJson = STObject(std::ref(sitTrans), kSfGeneric).getJson(JsonOptions::Values::None); + txJson = STObject(std::ref(sitTrans), sfGeneric).getJson(JsonOptions::Values::None); } catch (std::runtime_error const&) { From 9cb07406735a6bb967015495c33668d904d9ddee Mon Sep 17 00:00:00 2001 From: yinyiqian1 Date: Wed, 20 May 2026 16:24:09 -0400 Subject: [PATCH 13/17] fix: Fix multisign and signfor to check for delegate (#7064) --- src/libxrpl/protocol/STTx.cpp | 4 +- src/test/app/Delegate_test.cpp | 146 +++++++++++++++++++++++ src/xrpld/rpc/detail/TransactionSign.cpp | 8 +- 3 files changed, 155 insertions(+), 3 deletions(-) diff --git a/src/libxrpl/protocol/STTx.cpp b/src/libxrpl/protocol/STTx.cpp index 878aa296dd..8636c99284 100644 --- a/src/libxrpl/protocol/STTx.cpp +++ b/src/libxrpl/protocol/STTx.cpp @@ -535,8 +535,10 @@ STTx::checkMultiSign(Rules const& rules, STObject const& sigObject) const { // Used inside the loop in multiSignHelper to enforce that // the account owner may not multisign for themselves. + // For delegated transactions sfDelegate is the account whose signer list is checked, + // the delegate account itself can not be among the signers. auto const txnAccountID = - &sigObject != this ? std::nullopt : std::optional(getAccountID(sfAccount)); + &sigObject != this ? std::nullopt : std::optional(getFeePayer()); // We can ease the computational load inside the loop a bit by // pre-constructing part of the data that we hash. Fill a Serializer diff --git a/src/test/app/Delegate_test.cpp b/src/test/app/Delegate_test.cpp index 06884e9931..588aeee634 100644 --- a/src/test/app/Delegate_test.cpp +++ b/src/test/app/Delegate_test.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -1879,6 +1880,149 @@ class Delegate_test : public beast::unit_test::Suite BEAST_EXPECT(env.balance(edward) == edwardBalance); } + void + testMultiSignDelegatorAsSigner() + { + // checkMultiSign disallows the owner of the account to + // be part of the multisigner list. When it is a delegated transaction, + // the delegate account should not be part of the multisigner list. + testcase("test delegator as multisigner in delegate's signer list"); + using namespace jtx; + + Env env(*this); + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; + Account const daria{"daria"}; + env.fund(XRP(100000), alice, bob, carol, daria); + env.close(); + + env(delegate::set(alice, bob, {"Payment"})); + env.close(); + + // bob's signer list includes the delegator alice and daria + env(signers(bob, 2, {{alice, 1}, {daria, 1}})); + env.close(); + + auto aliceBalance = env.balance(alice); + auto bobBalance = env.balance(bob); + auto carolBalance = env.balance(carol); + auto const amt = 100; + + // alice can sign as a multisigner for bob + env(pay(alice, carol, XRP(100)), Fee(XRP(10)), delegate::As(bob), Msig(alice, daria)); + env.close(); + + BEAST_EXPECT(env.balance(alice) == aliceBalance - XRP(amt)); + BEAST_EXPECT(env.balance(bob) == bobBalance - XRP(10)); + BEAST_EXPECT(env.balance(carol) == carolBalance + XRP(amt)); + + // alice can not sign as a multisigner if she sent the transaction by herself. + env(pay(alice, carol, XRP(100)), Fee(XRP(10)), Msig(alice, daria), Ter(telENV_RPC_FAILED)); + env.close(); + + // Get new balances + aliceBalance = env.balance(alice); + bobBalance = env.balance(bob); + carolBalance = env.balance(carol); + + // bob (the delegate) should not appear as a multisigner in his transaction sent on behalf + // of alice. STTx::checkMultiSign catches this at the local-check stage, so the jtx + // framework returns telENV_RPC_FAILED. + env(pay(alice, carol, XRP(50)), + Fee(XRP(10)), + delegate::As(bob), + Msig(alice, bob), + Ter(telENV_RPC_FAILED)); + env.close(); + BEAST_EXPECT(env.balance(alice) == aliceBalance); + BEAST_EXPECT(env.balance(bob) == bobBalance); + BEAST_EXPECT(env.balance(carol) == carolBalance); + } + + void + testSignForDelegated() + { + // In sortAndValidateSigners, if it is a delegated transaction, the delegate account is + // the forbidden account from appearing in its own Signers array. + testcase("test sign_for with delegated transaction"); + using namespace jtx; + + Env env(*this); + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; + Account const daria{"daria"}; + env.fund(XRP(100000), alice, bob, carol, daria); + env.close(); + + env(delegate::set(alice, bob, {"Payment"})); + env.close(); + + // bob's signer list includes the delegator alice and daria + env(signers(bob, 2, {{alice, 1}, {daria, 1}})); + env.close(); + + auto const baseFee = env.current()->fees().base; + + auto const sendAmt = 1'000'000; + auto makeDelegateTx = [&]() -> json::Value { + json::Value jv; + jv[jss::tx_json][jss::Account] = alice.human(); + jv[jss::tx_json][sfDelegate.jsonName] = bob.human(); + jv[jss::tx_json][jss::TransactionType] = jss::Payment; + jv[jss::tx_json][jss::Destination] = carol.human(); + jv[jss::tx_json][jss::Amount] = sendAmt; + jv[jss::tx_json][jss::Fee] = std::to_string((10 * baseFee).drops()); + jv[jss::tx_json][jss::Sequence] = env.seq(alice); + jv[jss::tx_json][jss::SigningPubKey] = ""; + return jv; + }; + + // The delegator alice and daria both sign via sign_for, which is valid + { + auto const aliceBalance = env.balance(alice); + auto const bobBalance = env.balance(bob); + auto const dariaBalance = env.balance(daria); + auto const carolBalance = env.balance(carol); + + json::Value jv = makeDelegateTx(); + jv[jss::account] = alice.human(); + jv[jss::secret] = alice.name(); + auto jrr = env.rpc("json", "sign_for", to_string(jv))[jss::result]; + BEAST_EXPECT(jrr[jss::status] == "success"); + + json::Value jv2; + jv2[jss::tx_json] = jrr[jss::tx_json]; + jv2[jss::account] = daria.human(); + jv2[jss::secret] = daria.name(); + jrr = env.rpc("json", "sign_for", to_string(jv2))[jss::result]; + BEAST_EXPECT(jrr[jss::status] == "success"); + + json::Value jvSubmit; + jvSubmit[jss::tx_json] = jrr[jss::tx_json]; + jrr = env.rpc("json", "submit_multisigned", to_string(jvSubmit))[jss::result]; + BEAST_EXPECT(jrr[jss::status] == "success"); + env.close(); + BEAST_EXPECT(env.balance(alice) == aliceBalance - XRPAmount(sendAmt)); + BEAST_EXPECT(env.balance(bob) == bobBalance - (10 * baseFee)); + BEAST_EXPECT(env.balance(daria) == dariaBalance); + BEAST_EXPECT(env.balance(carol) == carolBalance + XRPAmount(sendAmt)); + } + + // The delegated account bob attempts sign_for, will be rejected. + { + json::Value jv = makeDelegateTx(); + jv[jss::account] = bob.human(); + jv[jss::secret] = bob.name(); + 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); + } + } + void testPermissionValue(FeatureBitset features) { @@ -2086,6 +2230,8 @@ class Delegate_test : public beast::unit_test::Suite testSingleSignBadSecret(); testMultiSign(); testMultiSignQuorumNotMet(); + testMultiSignDelegatorAsSigner(); + testSignForDelegated(); testPermissionValue(all); testTxRequireFeatures(all); testTxDelegableCount(); diff --git a/src/xrpld/rpc/detail/TransactionSign.cpp b/src/xrpld/rpc/detail/TransactionSign.cpp index 4c47914d66..9faa82dfe8 100644 --- a/src/xrpld/rpc/detail/TransactionSign.cpp +++ b/src/xrpld/rpc/detail/TransactionSign.cpp @@ -1255,7 +1255,9 @@ transactionSignFor( signers.emplaceBack(std::move(signer)); // The array must be sorted and validated. - auto err = sortAndValidateSigners(signers, (*sttx)[sfAccount]); + // For delegated transactions, the delegate account is + // the one forbidden from appearing in its own Signers array. + auto err = sortAndValidateSigners(signers, sttx->getFeePayer()); if (RPC::containsError(err)) return err; } @@ -1422,7 +1424,9 @@ transactionSubmitMultiSigned( } // The array must be sorted and validated. - auto err = sortAndValidateSigners(signers, srcAddressID); + // For delegated transactions, getFeePayer() returns sfDelegate, + // that account is the one forbidden from appearing in its own Signers array. + auto err = sortAndValidateSigners(signers, stTx->getFeePayer()); if (RPC::containsError(err)) return err; From 8c0080020f2a9c2d4b4dc7f6e059bf49b82ee867 Mon Sep 17 00:00:00 2001 From: Shawn Xie <35279399+shawnxie999@users.noreply.github.com> Date: Wed, 20 May 2026 17:10:04 -0400 Subject: [PATCH 14/17] fix: Update pDEX invariant firing under a valid offer deletion (#7118) Co-authored-by: Peter Chen --- .../tx/invariants/PermissionedDEXInvariant.h | 7 ++- .../invariants/PermissionedDEXInvariant.cpp | 10 +++- src/test/app/PermissionedDEX_test.cpp | 55 +++++++++++++++++++ 3 files changed, 66 insertions(+), 6 deletions(-) diff --git a/include/xrpl/tx/invariants/PermissionedDEXInvariant.h b/include/xrpl/tx/invariants/PermissionedDEXInvariant.h index 3784a32840..654ed3e009 100644 --- a/include/xrpl/tx/invariants/PermissionedDEXInvariant.h +++ b/include/xrpl/tx/invariants/PermissionedDEXInvariant.h @@ -10,9 +10,10 @@ namespace xrpl { class ValidPermissionedDEX { - bool regularOffers_ = false; - bool badHybridsOld_ = false; // pre-fixCleanup3_1_3: missing field/domain or size > 1 - bool badHybrids_ = false; // post-fixCleanup3_1_3: also catches size == 0 (size != 1) + bool regularOffersOld_ = false; // pre-fixCleanup3_2_0: also flags deleted offers + bool regularOffers_ = false; // post-fixCleanup3_2_0: excludes deleted offers + bool badHybridsOld_ = false; // pre-fixCleanup3_1_3: missing field/domain or size > 1 + bool badHybrids_ = false; // post-fixCleanup3_1_3: also catches size == 0 (size != 1) hash_set domains_; public: diff --git a/src/libxrpl/tx/invariants/PermissionedDEXInvariant.cpp b/src/libxrpl/tx/invariants/PermissionedDEXInvariant.cpp index b480b90a31..282df85302 100644 --- a/src/libxrpl/tx/invariants/PermissionedDEXInvariant.cpp +++ b/src/libxrpl/tx/invariants/PermissionedDEXInvariant.cpp @@ -20,7 +20,7 @@ namespace xrpl { void ValidPermissionedDEX::visitEntry( - bool, + bool isDelete, std::shared_ptr const& before, std::shared_ptr const& after) { @@ -38,7 +38,9 @@ ValidPermissionedDEX::visitEntry( } else { - regularOffers_ = true; + regularOffersOld_ = true; + if (!isDelete) + regularOffers_ = true; } // pre-fixCleanup3_1_3: hybrid offer missing domain, missing @@ -100,7 +102,9 @@ ValidPermissionedDEX::finalize( } } - if (regularOffers_) + bool const hasRegularOffers = + view.rules().enabled(fixCleanup3_2_0) ? regularOffers_ : regularOffersOld_; + if (hasRegularOffers) { JLOG(j.fatal()) << "Invariant failed: domain transaction" " affected regular offers"; diff --git a/src/test/app/PermissionedDEX_test.cpp b/src/test/app/PermissionedDEX_test.cpp index be377c0c1d..3a95fb2f92 100644 --- a/src/test/app/PermissionedDEX_test.cpp +++ b/src/test/app/PermissionedDEX_test.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include // IWYU pragma: keep #include @@ -34,6 +35,7 @@ #include #include #include +#include #include #include @@ -1455,6 +1457,54 @@ class PermissionedDEX_test : public beast::unit_test::Suite } } + void + testCancelRegularOfferWithDomainCreate(FeatureBitset features) + { + bool const fixEnabled = features[fixCleanup3_2_0]; + + testcase << "Cancel regular offer via domain OfferCreate" + << (fixEnabled ? " (fixCleanup3_2_0 enabled)" : " (fixCleanup3_2_0 disabled)"); + + // An OfferCreate with sfDomainID and sfOfferSequence pointing to + // the user's own non-domain offer should atomically cancel the + // regular offer and place the new domain offer. + // + // Pre-fixCleanup3_2_0: ValidPermissionedDEX flagged the deleted + // regular offer, so the transaction failed with tecINVARIANT_FAILED. + // Post-fixCleanup3_2_0: the invariant ignores deletions and the + // transaction succeeds. + + Env env(*this, features); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); + + auto const regularSeq = env.seq(bob); + env(offer(bob, XRP(10), USD(10))); + env.close(); + BEAST_EXPECT(checkOffer(env, bob, regularSeq, XRP(10), USD(10), 0, false)); + + auto const domainSeq = env.seq(bob); + if (fixEnabled) + { + env(offer(bob, XRP(20), USD(20)), + Domain(domainID), + Json(jss::OfferSequence, regularSeq)); + env.close(); + BEAST_EXPECT(!offerExists(env, bob, regularSeq)); + BEAST_EXPECT(checkOffer(env, bob, domainSeq, XRP(20), USD(20), 0, true)); + } + else + { + env(offer(bob, XRP(20), USD(20)), + Domain(domainID), + Json(jss::OfferSequence, regularSeq), + Ter(tecINVARIANT_FAILED)); + env.close(); + BEAST_EXPECT(offerExists(env, bob, regularSeq)); + BEAST_EXPECT(!offerExists(env, bob, domainSeq)); + } + } + public: void run() override @@ -1478,6 +1528,11 @@ public: testHybridOfferDirectories(all); testHybridMalformedOffer(all); testHybridMalformedOffer(all - fixCleanup3_1_3); + + // Cancelling a regular offer in a domain OfferCreate is allowed + // only after fixCleanup3_2_0. + testCancelRegularOfferWithDomainCreate(all); + testCancelRegularOfferWithDomainCreate(all - fixCleanup3_2_0); } }; From a830ab10efed8d3e59ef2fc15d66efdf9c6bb0d8 Mon Sep 17 00:00:00 2001 From: Alex Kremer Date: Wed, 20 May 2026 22:31:15 +0100 Subject: [PATCH 15/17] style: More clang-tidy identifier renaming (#7290) --- .clang-tidy | 3 + include/xrpl/basics/TaggedCache.h | 22 +- include/xrpl/basics/TaggedCache.ipp | 44 +-- include/xrpl/basics/scope.h | 58 ++-- include/xrpl/beast/unit_test/reporter.h | 22 +- include/xrpl/core/Coro.ipp | 10 +- include/xrpl/core/Job.h | 2 +- include/xrpl/core/JobQueue.h | 4 +- include/xrpl/ledger/BookDirs.h | 8 +- include/xrpl/ledger/OpenView.h | 2 +- include/xrpl/ledger/detail/RawStateTable.h | 10 +- include/xrpl/net/HTTPClientSSLContext.h | 12 +- include/xrpl/protocol/Book.h | 18 +- include/xrpl/protocol/ErrorCodes.h | 8 +- include/xrpl/protocol/STPathSet.h | 28 +- include/xrpl/protocol/STTx.h | 4 +- include/xrpl/resource/detail/Entry.h | 10 +- include/xrpl/resource/detail/Key.h | 4 +- include/xrpl/resource/detail/Logic.h | 32 +- include/xrpl/server/Handoff.h | 2 +- include/xrpl/server/Port.h | 48 +-- include/xrpl/server/detail/BaseHTTPPeer.h | 30 +- include/xrpl/server/detail/BasePeer.h | 4 +- include/xrpl/server/detail/BaseWSPeer.h | 40 +-- include/xrpl/server/detail/Door.h | 36 +-- include/xrpl/server/detail/PlainHTTPPeer.h | 12 +- include/xrpl/server/detail/SSLHTTPPeer.h | 22 +- include/xrpl/server/detail/SSLWSPeer.h | 6 +- include/xrpl/server/detail/ServerImpl.h | 12 +- src/libxrpl/basics/ResolverAsio.cpp | 30 +- src/libxrpl/beast/insight/StatsDCollector.cpp | 24 +- src/libxrpl/core/detail/Job.cpp | 4 +- src/libxrpl/core/detail/JobQueue.cpp | 4 +- src/libxrpl/ledger/BookDirs.cpp | 18 +- src/libxrpl/ledger/OpenView.cpp | 12 +- src/libxrpl/protocol/ErrorCodes.cpp | 2 +- src/libxrpl/protocol/STTx.cpp | 14 +- src/libxrpl/server/Port.cpp | 49 ++-- src/test/app/AMMMPT_test.cpp | 50 ++-- src/test/app/AMM_test.cpp | 6 +- src/test/app/FeeVote_test.cpp | 82 +++--- src/test/app/LedgerHistory_test.cpp | 2 +- src/test/app/LedgerLoad_test.cpp | 6 +- src/test/app/LedgerMaster_test.cpp | 4 +- src/test/app/LedgerReplay_test.cpp | 8 +- src/test/app/LoadFeeTrack_test.cpp | 6 +- src/test/app/MPToken_test.cpp | 2 +- src/test/app/NetworkID_test.cpp | 2 +- src/test/app/PathMPT_test.cpp | 6 +- src/test/app/Path_test.cpp | 6 +- src/test/app/RCLValidations_test.cpp | 4 +- src/test/app/Regression_test.cpp | 4 +- src/test/app/SHAMapStore_test.cpp | 2 +- src/test/app/Transaction_ordering_test.cpp | 4 +- src/test/app/TxQ_test.cpp | 8 +- src/test/app/ValidatorList_test.cpp | 4 +- src/test/app/XChain_test.cpp | 230 ++++++++------- src/test/consensus/Consensus_test.cpp | 4 +- src/test/consensus/NegativeUNL_test.cpp | 152 +++++----- src/test/consensus/Validations_test.cpp | 24 +- src/test/core/Config_test.cpp | 114 ++++---- src/test/core/Coroutine_test.cpp | 4 +- src/test/csf/Scheduler.h | 14 +- src/test/jtx/impl/AMMTest.cpp | 6 +- src/test/jtx/impl/Env.cpp | 2 +- src/test/jtx/impl/JSONRPCClient.cpp | 8 +- src/test/jtx/impl/TestHelpers.cpp | 6 +- src/test/jtx/impl/WSClient.cpp | 8 +- src/test/jtx/impl/envconfig.cpp | 12 +- src/test/jtx/impl/permissioned_dex.cpp | 6 +- src/test/jtx/impl/xchain_bridge.cpp | 23 +- src/test/jtx/permissioned_dex.h | 2 +- src/test/jtx/xchain_bridge.h | 18 +- src/test/ledger/SkipList_test.cpp | 2 +- src/test/ledger/View_test.cpp | 8 +- src/test/nodestore/Database_test.cpp | 6 +- src/test/nodestore/Timing_test.cpp | 24 +- src/test/overlay/compression_test.cpp | 21 +- src/test/overlay/reduce_relay_test.cpp | 44 ++- src/test/overlay/short_read_test.cpp | 22 +- src/test/overlay/tx_reduce_relay_test.cpp | 16 +- src/test/peerfinder/PeerFinder_test.cpp | 4 +- src/test/rpc/AccountTx_test.cpp | 4 +- src/test/rpc/Book_test.cpp | 4 +- src/test/rpc/DeliveredAmount_test.cpp | 4 +- src/test/rpc/JSONRPC_test.cpp | 4 +- src/test/rpc/KeyGeneration_test.cpp | 104 +++---- src/test/rpc/LedgerClosed_test.cpp | 2 +- src/test/rpc/LedgerEntry_test.cpp | 6 +- src/test/rpc/LedgerRPC_test.cpp | 4 +- src/test/rpc/LedgerRequest_test.cpp | 6 +- src/test/rpc/NoRippleCheck_test.cpp | 2 +- src/test/rpc/RPCCall_test.cpp | 2 +- src/test/rpc/Simulate_test.cpp | 6 +- src/test/rpc/Subscribe_test.cpp | 4 +- src/test/rpc/TransactionEntry_test.cpp | 4 +- src/test/rpc/Transaction_test.cpp | 6 +- src/test/rpc/Version_test.cpp | 12 +- src/test/server/ServerStatus_test.cpp | 6 +- src/test/server/Server_test.cpp | 8 +- src/test/unit_test/multi_runner.cpp | 114 ++++---- src/test/unit_test/multi_runner.h | 40 +-- src/xrpld/app/ledger/LedgerHistory.cpp | 43 ++- src/xrpld/app/ledger/LedgerHistory.h | 12 +- src/xrpld/app/ledger/LedgerMaster.h | 12 +- src/xrpld/app/ledger/OpenLedger.h | 4 +- src/xrpld/app/ledger/detail/LedgerCleaner.cpp | 2 +- src/xrpld/app/ledger/detail/LedgerMaster.cpp | 41 ++- src/xrpld/app/ledger/detail/OpenLedger.cpp | 12 +- src/xrpld/app/main/Application.cpp | 64 ++-- src/xrpld/app/main/BasicApp.cpp | 4 +- src/xrpld/app/main/BasicApp.h | 4 +- src/xrpld/app/main/Main.cpp | 34 +-- src/xrpld/app/misc/FeeVoteImpl.cpp | 21 +- src/xrpld/app/misc/NetworkOPs.cpp | 99 ++++--- src/xrpld/app/misc/SHAMapStoreImp.cpp | 24 +- src/xrpld/app/misc/SHAMapStoreImp.h | 6 +- src/xrpld/app/misc/ValidatorSite.h | 8 +- src/xrpld/app/misc/detail/ValidatorSite.cpp | 32 +- src/xrpld/app/misc/detail/WorkSSL.cpp | 6 +- src/xrpld/consensus/Consensus.cpp | 26 +- src/xrpld/consensus/Consensus.h | 22 +- src/xrpld/consensus/ConsensusParms.h | 28 +- src/xrpld/consensus/DisputedTx.h | 12 +- src/xrpld/consensus/Validations.h | 24 +- src/xrpld/core/Config.h | 130 ++++----- src/xrpld/core/detail/Config.cpp | 276 +++++++++--------- src/xrpld/overlay/Message.h | 2 +- src/xrpld/overlay/Slot.h | 4 +- src/xrpld/overlay/detail/ConnectAttempt.cpp | 8 +- src/xrpld/overlay/detail/Handshake.cpp | 12 +- src/xrpld/overlay/detail/Message.cpp | 2 +- src/xrpld/overlay/detail/OverlayImpl.cpp | 48 +-- src/xrpld/overlay/detail/OverlayImpl.h | 6 +- src/xrpld/overlay/detail/PeerImp.cpp | 32 +- src/xrpld/overlay/detail/PeerImp.h | 20 +- src/xrpld/overlay/detail/ProtocolMessage.h | 66 ++--- src/xrpld/overlay/detail/TxMetrics.cpp | 6 +- src/xrpld/overlay/detail/TxMetrics.h | 2 +- src/xrpld/peerfinder/detail/Counts.h | 54 ++-- .../peerfinder/detail/PeerfinderConfig.cpp | 14 +- src/xrpld/peerfinder/detail/SlotImp.cpp | 10 +- src/xrpld/peerfinder/detail/SlotImp.h | 24 +- src/xrpld/rpc/ServerHandler.h | 10 +- src/xrpld/rpc/detail/AssetCache.h | 8 +- src/xrpld/rpc/detail/PathRequest.cpp | 56 ++-- src/xrpld/rpc/detail/PathRequest.h | 6 +- src/xrpld/rpc/detail/Pathfinder.cpp | 12 +- src/xrpld/rpc/detail/Pathfinder.h | 2 +- src/xrpld/rpc/detail/RPCCall.cpp | 14 +- src/xrpld/rpc/detail/RPCHandler.cpp | 2 +- src/xrpld/rpc/detail/RPCSub.cpp | 6 +- src/xrpld/rpc/detail/Role.cpp | 12 +- src/xrpld/rpc/detail/ServerHandler.cpp | 56 ++-- src/xrpld/rpc/detail/TransactionSign.cpp | 18 +- src/xrpld/rpc/detail/WSInfoSub.h | 4 +- src/xrpld/rpc/handlers/orderbook/PathFind.cpp | 2 +- .../rpc/handlers/orderbook/RipplePathFind.cpp | 2 +- src/xrpld/rpc/handlers/server_info/Version.h | 2 +- src/xrpld/rpc/json_body.h | 6 +- 160 files changed, 1726 insertions(+), 1746 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index a444957a0e..ee6bde6eba 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -191,8 +191,11 @@ CheckOptions: readability-identifier-naming.ParameterCase: camelBack readability-identifier-naming.FunctionCase: camelBack readability-identifier-naming.MemberCase: camelBack + readability-identifier-naming.PrivateMemberCase: camelBack readability-identifier-naming.PrivateMemberSuffix: _ + readability-identifier-naming.ProtectedMemberCase: camelBack readability-identifier-naming.ProtectedMemberSuffix: _ + readability-identifier-naming.PublicMemberCase: camelBack readability-identifier-naming.PublicMemberSuffix: "" readability-identifier-naming.GlobalFunctionIgnoredRegexp: "^(to_string|hash_append|tuple_hash)$" diff --git a/include/xrpl/basics/TaggedCache.h b/include/xrpl/basics/TaggedCache.h index 52b866cdad..fca9eabde2 100644 --- a/include/xrpl/basics/TaggedCache.h +++ b/include/xrpl/basics/TaggedCache.h @@ -181,14 +181,14 @@ private: beast::insight::Collector::ptr const& collector) : hook(collector->makeHook(handler)) , size(collector->makeGauge(prefix, "size")) - , hit_rate(collector->makeGauge(prefix, "hit_rate")) + , hitRate(collector->makeGauge(prefix, "hit_rate")) { } beast::insight::Hook hook; beast::insight::Gauge size; - beast::insight::Gauge hit_rate; + beast::insight::Gauge hitRate; std::size_t hits{0}; std::size_t misses{0}; @@ -197,16 +197,16 @@ private: class KeyOnlyEntry { public: - clock_type::time_point last_access; + clock_type::time_point lastAccess; - explicit KeyOnlyEntry(clock_type::time_point const& lastAccess) : last_access(lastAccess) + explicit KeyOnlyEntry(clock_type::time_point const& lastAccess) : lastAccess(lastAccess) { } void touch(clock_type::time_point const& now) { - last_access = now; + lastAccess = now; } }; @@ -214,10 +214,10 @@ private: { public: shared_weak_combo_pointer_type ptr; - clock_type::time_point last_access; + clock_type::time_point lastAccess; ValueEntry(clock_type::time_point const& lastAccess, shared_pointer_type const& ptr) - : ptr(ptr), last_access(lastAccess) + : ptr(ptr), lastAccess(lastAccess) { } @@ -246,7 +246,7 @@ private: void touch(clock_type::time_point const& now) { - last_access = now; + lastAccess = now; } }; @@ -286,13 +286,13 @@ private: std::string name_; // Desired number of cache entries (0 = ignore) - int const target_size_; + int const targetSize_; // Desired maximum cache age - clock_type::duration const target_age_; + clock_type::duration const targetAge_; // Number of items cached - int cache_count_{0}; + int cacheCount_{0}; cache_type cache_; // Hold strong reference to recent objects std::uint64_t hits_{0}; std::uint64_t misses_{0}; diff --git a/include/xrpl/basics/TaggedCache.ipp b/include/xrpl/basics/TaggedCache.ipp index 8ef9e16570..cee02749c6 100644 --- a/include/xrpl/basics/TaggedCache.ipp +++ b/include/xrpl/basics/TaggedCache.ipp @@ -34,8 +34,8 @@ inline TaggedCache< , clock_(clock) , stats_(name, std::bind(&TaggedCache::collectMetrics, this), collector) , name_(name) - , target_size_(size) - , target_age_(expiration) + , targetSize_(size) + , targetAge_(expiration) { } @@ -86,7 +86,7 @@ TaggedCache(cache_.size()) <= target_size_)) + if (targetSize_ == 0 || (static_cast(cache_.size()) <= targetSize_)) { - whenExpire = now - target_age_; + whenExpire = now - targetAge_; } else { - whenExpire = now - (target_age_ * target_size_ / cache_.size()); + whenExpire = now - (targetAge_ * targetSize_ / cache_.size()); clock_type::duration const minimumAge(std::chrono::seconds(1)); if (whenExpire > (now - minimumAge)) whenExpire = now - minimumAge; JLOG(journal_.trace()) - << name_ << " is growing fast " << cache_.size() << " of " << target_size_ - << " aging at " << (now - whenExpire).count() << " of " << target_age_.count(); + << name_ << " is growing fast " << cache_.size() << " of " << targetSize_ + << " aging at " << (now - whenExpire).count() << " of " << targetAge_.count(); } std::vector workers; @@ -242,7 +242,7 @@ TaggedCachesecond.last_access = now; + it->second.lastAccess = now; return inserted; } @@ -626,7 +626,7 @@ TaggedCachesecond.last_access <= whenExpire) + else if (cit->second.lastAccess <= whenExpire) { // strong, expired ++cacheRemovals; @@ -773,12 +773,12 @@ TaggedCachesecond.last_access > now) + if (cit->second.lastAccess > now) { - cit->second.last_access = now; + cit->second.lastAccess = now; ++cit; } - else if (cit->second.last_access <= whenExpire) + else if (cit->second.lastAccess <= whenExpire) { cit = partition.erase(cit); } diff --git a/include/xrpl/basics/scope.h b/include/xrpl/basics/scope.h index cd2a5299b2..cfd21e6e30 100644 --- a/include/xrpl/basics/scope.h +++ b/include/xrpl/basics/scope.h @@ -24,20 +24,20 @@ namespace xrpl { template class ScopeExit { - EF exit_function_; - bool execute_on_destruction_{true}; + EF exitFunction_; + bool executeOnDestruction_{true}; public: ~ScopeExit() { - if (execute_on_destruction_) - exit_function_(); + if (executeOnDestruction_) + exitFunction_(); } ScopeExit(ScopeExit&& rhs) noexcept( std::is_nothrow_move_constructible_v || std::is_nothrow_copy_constructible_v) - : exit_function_{std::forward(rhs.exit_function_)} - , execute_on_destruction_{rhs.execute_on_destruction_} + : exitFunction_{std::forward(rhs.exitFunction_)} + , executeOnDestruction_{rhs.executeOnDestruction_} { rhs.release(); } @@ -51,7 +51,7 @@ public: std::enable_if_t< !std::is_same_v, ScopeExit> && std::is_constructible_v>* = 0) noexcept - : exit_function_{std::forward(f)} + : exitFunction_{std::forward(f)} { static_assert(std::is_nothrow_constructible_v(f))>); } @@ -59,7 +59,7 @@ public: void release() noexcept { - execute_on_destruction_ = false; + executeOnDestruction_ = false; } }; @@ -69,22 +69,22 @@ ScopeExit(EF) -> ScopeExit; template class ScopeFail { - EF exit_function_; - bool execute_on_destruction_{true}; - int uncaught_on_creation_{std::uncaught_exceptions()}; + EF exitFunction_; + bool executeOnDestruction_{true}; + int uncaughtOnCreation_{std::uncaught_exceptions()}; public: ~ScopeFail() { - if (execute_on_destruction_ && std::uncaught_exceptions() > uncaught_on_creation_) - exit_function_(); + if (executeOnDestruction_ && std::uncaught_exceptions() > uncaughtOnCreation_) + exitFunction_(); } ScopeFail(ScopeFail&& rhs) noexcept( std::is_nothrow_move_constructible_v || std::is_nothrow_copy_constructible_v) - : exit_function_{std::forward(rhs.exit_function_)} - , execute_on_destruction_{rhs.execute_on_destruction_} - , uncaught_on_creation_{rhs.uncaught_on_creation_} + : exitFunction_{std::forward(rhs.exitFunction_)} + , executeOnDestruction_{rhs.executeOnDestruction_} + , uncaughtOnCreation_{rhs.uncaughtOnCreation_} { rhs.release(); } @@ -98,7 +98,7 @@ public: std::enable_if_t< !std::is_same_v, ScopeFail> && std::is_constructible_v>* = 0) noexcept - : exit_function_{std::forward(f)} + : exitFunction_{std::forward(f)} { static_assert(std::is_nothrow_constructible_v(f))>); } @@ -106,7 +106,7 @@ public: void release() noexcept { - execute_on_destruction_ = false; + executeOnDestruction_ = false; } }; @@ -116,22 +116,22 @@ ScopeFail(EF) -> ScopeFail; template class ScopeSuccess { - EF exit_function_; - bool execute_on_destruction_{true}; - int uncaught_on_creation_{std::uncaught_exceptions()}; + EF exitFunction_; + bool executeOnDestruction_{true}; + int uncaughtOnCreation_{std::uncaught_exceptions()}; public: - ~ScopeSuccess() noexcept(noexcept(exit_function_())) + ~ScopeSuccess() noexcept(noexcept(exitFunction_())) { - if (execute_on_destruction_ && std::uncaught_exceptions() <= uncaught_on_creation_) - exit_function_(); + if (executeOnDestruction_ && std::uncaught_exceptions() <= uncaughtOnCreation_) + exitFunction_(); } ScopeSuccess(ScopeSuccess&& rhs) noexcept( std::is_nothrow_move_constructible_v || std::is_nothrow_copy_constructible_v) - : exit_function_{std::forward(rhs.exit_function_)} - , execute_on_destruction_{rhs.execute_on_destruction_} - , uncaught_on_creation_{rhs.uncaught_on_creation_} + : exitFunction_{std::forward(rhs.exitFunction_)} + , executeOnDestruction_{rhs.executeOnDestruction_} + , uncaughtOnCreation_{rhs.uncaughtOnCreation_} { rhs.release(); } @@ -146,14 +146,14 @@ public: !std::is_same_v, ScopeSuccess> && std::is_constructible_v>* = 0) noexcept(std::is_nothrow_constructible_v || std::is_nothrow_constructible_v) - : exit_function_{std::forward(f)} + : exitFunction_{std::forward(f)} { } void release() noexcept { - execute_on_destruction_ = false; + executeOnDestruction_ = false; } }; diff --git a/include/xrpl/beast/unit_test/reporter.h b/include/xrpl/beast/unit_test/reporter.h index b4b6c69fa4..1fdbb451a6 100644 --- a/include/xrpl/beast/unit_test/reporter.h +++ b/include/xrpl/beast/unit_test/reporter.h @@ -77,8 +77,8 @@ private: std::ostream& os_; Results results_; - SuiteResults suite_results_; - CaseResults case_results_; + SuiteResults suiteResults_; + CaseResults caseResults_; public: Reporter(Reporter const&) = delete; @@ -196,22 +196,22 @@ template void Reporter::onSuiteBegin(SuiteInfo const& info) { - suite_results_ = SuiteResults{info.fullName()}; + suiteResults_ = SuiteResults{info.fullName()}; } template void Reporter::onSuiteEnd() { - results_.add(suite_results_); + results_.add(suiteResults_); } template void Reporter::onCaseBegin(std::string const& name) { - case_results_ = CaseResults(name); - os_ << suite_results_.name << (case_results_.name.empty() ? "" : (" " + case_results_.name)) + caseResults_ = CaseResults(name); + os_ << suiteResults_.name << (caseResults_.name.empty() ? "" : (" " + caseResults_.name)) << std::endl; } @@ -219,23 +219,23 @@ template void Reporter::onCaseEnd() { - suite_results_.add(case_results_); + suiteResults_.add(caseResults_); } template void Reporter::onPass() { - ++case_results_.total; + ++caseResults_.total; } template void Reporter::onFail(std::string const& reason) { - ++case_results_.failed; - ++case_results_.total; - os_ << "#" << case_results_.total << " failed" << (reason.empty() ? "" : ": ") << reason + ++caseResults_.failed; + ++caseResults_.total; + os_ << "#" << caseResults_.total << " failed" << (reason.empty() ? "" : ": ") << reason << std::endl; } diff --git a/include/xrpl/core/Coro.ipp b/include/xrpl/core/Coro.ipp index 90fa965038..133caf37a9 100644 --- a/include/xrpl/core/Coro.ipp +++ b/include/xrpl/core/Coro.ipp @@ -47,7 +47,7 @@ inline bool JobQueue::Coro::post() { { - std::scoped_lock const lk(mutex_run_); + std::scoped_lock const lk(mutexRun_); running_ = true; } @@ -58,7 +58,7 @@ JobQueue::Coro::post() } // The coroutine will not run. Clean up running_. - std::scoped_lock const lk(mutex_run_); + std::scoped_lock const lk(mutexRun_); running_ = false; cv_.notify_all(); return false; @@ -68,7 +68,7 @@ inline void JobQueue::Coro::resume() { { - std::scoped_lock const lk(mutex_run_); + std::scoped_lock const lk(mutexRun_); running_ = true; } { @@ -92,7 +92,7 @@ JobQueue::Coro::resume() } detail::getLocalValues().release(); detail::getLocalValues().reset(saved); - std::scoped_lock const lk(mutex_run_); + std::scoped_lock const lk(mutexRun_); running_ = false; cv_.notify_all(); } @@ -127,7 +127,7 @@ JobQueue::Coro::expectEarlyExit() inline void JobQueue::Coro::join() { - std::unique_lock lk(mutex_run_); + std::unique_lock lk(mutexRun_); cv_.wait(lk, [this]() { return !running_; }); } diff --git a/include/xrpl/core/Job.h b/include/xrpl/core/Job.h index b62488dec6..6af32eb2d8 100644 --- a/include/xrpl/core/Job.h +++ b/include/xrpl/core/Job.h @@ -127,7 +127,7 @@ private: std::function job_; std::shared_ptr loadEvent_; std::string name_; - clock_type::time_point queue_time_; + clock_type::time_point queueTime_; }; using JobCounter = ClosureCounter; diff --git a/include/xrpl/core/JobQueue.h b/include/xrpl/core/JobQueue.h index 2a96ea45fa..fc15e9a064 100644 --- a/include/xrpl/core/JobQueue.h +++ b/include/xrpl/core/JobQueue.h @@ -52,7 +52,7 @@ public: std::string name_; bool running_{false}; std::mutex mutex_; - std::mutex mutex_run_; + std::mutex mutexRun_; std::condition_variable cv_; boost::coroutines2::coroutine::push_type* yield_{}; boost::coroutines2::coroutine::pull_type coro_; @@ -246,7 +246,7 @@ private: // Statistics tracking perf::PerfLog& perfLog_; beast::insight::Collector::ptr collector_; - beast::insight::Gauge job_count_; + beast::insight::Gauge jobCount_; beast::insight::Hook hook_; std::condition_variable cv_; diff --git a/include/xrpl/ledger/BookDirs.h b/include/xrpl/ledger/BookDirs.h index afde6ee7b3..7eaede14ec 100644 --- a/include/xrpl/ledger/BookDirs.h +++ b/include/xrpl/ledger/BookDirs.h @@ -9,7 +9,7 @@ class BookDirs private: ReadView const* view_ = nullptr; uint256 const root_; - uint256 const next_quality_; + uint256 const nextQuality_; uint256 const key_; std::shared_ptr sle_ = nullptr; unsigned int entry_ = 0; @@ -67,15 +67,15 @@ private: friend class BookDirs; const_iterator(ReadView const& view, uint256 const& root, uint256 const& dirKey) - : view_(&view), root_(root), key_(dirKey), cur_key_(dirKey) + : view_(&view), root_(root), key_(dirKey), curKey_(dirKey) { } ReadView const* view_ = nullptr; uint256 root_; - uint256 next_quality_; + uint256 nextQuality_; uint256 key_; - uint256 cur_key_; + uint256 curKey_; std::shared_ptr sle_; unsigned int entry_ = 0; uint256 index_; diff --git a/include/xrpl/ledger/OpenView.h b/include/xrpl/ledger/OpenView.h index c7f80ee321..18d1a9399c 100644 --- a/include/xrpl/ledger/OpenView.h +++ b/include/xrpl/ledger/OpenView.h @@ -76,7 +76,7 @@ private: // monotonic_resource_ must outlive `items_`. Make a pointer so it may be // easily moved. - std::unique_ptr monotonic_resource_; + std::unique_ptr monotonicResource_; txs_map txs_; Rules rules_; LedgerHeader header_; diff --git a/include/xrpl/ledger/detail/RawStateTable.h b/include/xrpl/ledger/detail/RawStateTable.h index 53532ee5ec..e4329bf6fc 100644 --- a/include/xrpl/ledger/detail/RawStateTable.h +++ b/include/xrpl/ledger/detail/RawStateTable.h @@ -22,14 +22,14 @@ public: static constexpr size_t kInitialBufferSize = kilobytes(256); RawStateTable() - : monotonic_resource_{std::make_unique( + : monotonicResource_{std::make_unique( kInitialBufferSize)} - , items_{monotonic_resource_.get()} {}; + , items_{monotonicResource_.get()} {}; RawStateTable(RawStateTable const& rhs) - : monotonic_resource_{std::make_unique( + : monotonicResource_{std::make_unique( kInitialBufferSize)} - , items_{rhs.items_, monotonic_resource_.get()} + , items_{rhs.items_, monotonicResource_.get()} , dropsDestroyed_{rhs.dropsDestroyed_} {}; RawStateTable(RawStateTable&&) = default; @@ -101,7 +101,7 @@ private: boost::container::pmr::polymorphic_allocator>>; // monotonic_resource_ must outlive `items_`. Make a pointer so it may be // easily moved. - std::unique_ptr monotonic_resource_; + std::unique_ptr monotonicResource_; items_t items_; XRPAmount dropsDestroyed_{0}; diff --git a/include/xrpl/net/HTTPClientSSLContext.h b/include/xrpl/net/HTTPClientSSLContext.h index d1744bbce4..ca1983f141 100644 --- a/include/xrpl/net/HTTPClientSSLContext.h +++ b/include/xrpl/net/HTTPClientSSLContext.h @@ -21,13 +21,13 @@ public: bool sslVerify, beast::Journal j, boost::asio::ssl::context_base::method method = boost::asio::ssl::context::sslv23) - : ssl_context_{method}, j_(j), verify_{sslVerify} + : sslContext_{method}, j_(j), verify_{sslVerify} { boost::system::error_code ec; if (sslVerifyFile.empty()) { - registerSSLCerts(ssl_context_, ec, j_); + registerSSLCerts(sslContext_, ec, j_); if (ec && sslVerifyDir.empty()) { @@ -37,12 +37,12 @@ public: } else { - ssl_context_.load_verify_file(sslVerifyFile); + sslContext_.load_verify_file(sslVerifyFile); } if (!sslVerifyDir.empty()) { - ssl_context_.add_verify_path(sslVerifyDir, ec); + sslContext_.add_verify_path(sslVerifyDir, ec); if (ec) { @@ -55,7 +55,7 @@ public: boost::asio::ssl::context& context() { - return ssl_context_; + return sslContext_; } [[nodiscard]] bool @@ -153,7 +153,7 @@ public: } private: - boost::asio::ssl::context ssl_context_; + boost::asio::ssl::context sslContext_; beast::Journal const j_; bool const verify_; }; diff --git a/include/xrpl/protocol/Book.h b/include/xrpl/protocol/Book.h index fc36abddc4..01dc40075b 100644 --- a/include/xrpl/protocol/Book.h +++ b/include/xrpl/protocol/Book.h @@ -140,8 +140,8 @@ private: using issue_hasher = std::hash; using mptissue_hasher = std::hash; - issue_hasher m_issue_hasher_; - mptissue_hasher m_mptissue_hasher_; + issue_hasher mIssueHasher_; + mptissue_hasher mMptissueHasher_; public: explicit hash() = default; @@ -151,11 +151,11 @@ public: { return asset.visit( [&](xrpl::Issue const& issue) { - value_type const result(m_issue_hasher_(issue)); + value_type const result(mIssueHasher_(issue)); return result; }, [&](xrpl::MPTIssue const& issue) { - value_type const result(m_mptissue_hasher_(issue)); + value_type const result(mMptissueHasher_(issue)); return result; }); } @@ -170,8 +170,8 @@ private: using asset_hasher = std::hash; using uint256_hasher = xrpl::uint256::hasher; - asset_hasher issue_hasher_; - uint256_hasher uint256_hasher_; + asset_hasher issueHasher_; + uint256_hasher uint256Hasher_; public: hash() = default; @@ -182,11 +182,11 @@ public: value_type operator()(argument_type const& value) const { - value_type result(issue_hasher_(value.in)); - boost::hash_combine(result, issue_hasher_(value.out)); + value_type result(issueHasher_(value.in)); + boost::hash_combine(result, issueHasher_(value.out)); if (value.domain) - boost::hash_combine(result, uint256_hasher_(*value.domain)); + boost::hash_combine(result, uint256Hasher_(*value.domain)); return result; } diff --git a/include/xrpl/protocol/ErrorCodes.h b/include/xrpl/protocol/ErrorCodes.h index a91adfc55a..f5e67fd572 100644 --- a/include/xrpl/protocol/ErrorCodes.h +++ b/include/xrpl/protocol/ErrorCodes.h @@ -172,24 +172,24 @@ struct ErrorInfo { // Default ctor needed to produce an empty std::array during constexpr eval. constexpr ErrorInfo() - : code(RpcUnknown), token("unknown"), message("An unknown error code."), http_status(200) + : code(RpcUnknown), token("unknown"), message("An unknown error code."), httpStatus(200) { } constexpr ErrorInfo(ErrorCodeI code, char const* token, char const* message) - : code(code), token(token), message(message), http_status(200) + : code(code), token(token), message(message), httpStatus(200) { } constexpr ErrorInfo(ErrorCodeI code, char const* token, char const* message, int httpStatus) - : code(code), token(token), message(message), http_status(httpStatus) + : code(code), token(token), message(message), httpStatus(httpStatus) { } ErrorCodeI code; json::StaticString token; json::StaticString message; - int http_status; + int httpStatus; }; /** Returns an ErrorInfo that reflects the error code. */ diff --git a/include/xrpl/protocol/STPathSet.h b/include/xrpl/protocol/STPathSet.h index a1891164f6..1508dcb727 100644 --- a/include/xrpl/protocol/STPathSet.h +++ b/include/xrpl/protocol/STPathSet.h @@ -21,8 +21,8 @@ class STPathElement final : public CountedObject PathAsset assetID_; AccountID issuerID_; - bool is_offer_; - std::size_t hash_value_; + bool isOffer_; + std::size_t hashValue_; public: // Bitwise values (typeCurrency | typeMPT) @@ -235,9 +235,9 @@ private: // ------------ STPathElement ------------ -inline STPathElement::STPathElement() : type_(TypeNone), is_offer_(true) +inline STPathElement::STPathElement() : type_(TypeNone), isOffer_(true) { - hash_value_ = getHash(*this); + hashValue_ = getHash(*this); } inline STPathElement::STPathElement( @@ -248,11 +248,11 @@ inline STPathElement::STPathElement( { if (!account) { - is_offer_ = true; + isOffer_ = true; } else { - is_offer_ = false; + isOffer_ = false; accountID_ = *account; type_ |= TypeAccount; XRPL_ASSERT( @@ -272,7 +272,7 @@ inline STPathElement::STPathElement( XRPL_ASSERT(issuerID_ != noAccount(), "xrpl::STPathElement::STPathElement : issuer is set"); } - hash_value_ = getHash(*this); + hashValue_ = getHash(*this); } inline STPathElement::STPathElement( @@ -284,9 +284,9 @@ inline STPathElement::STPathElement( , accountID_(account) , assetID_(asset) , issuerID_(issuer) - , is_offer_(isXRP(accountID_)) + , isOffer_(isXRP(accountID_)) { - if (!is_offer_) + if (!isOffer_) type_ |= TypeAccount; if (forceAsset || !isXRP(assetID_)) @@ -295,7 +295,7 @@ inline STPathElement::STPathElement( if (!isXRP(issuer)) type_ |= TypeIssuer; - hash_value_ = getHash(*this); + hashValue_ = getHash(*this); } inline STPathElement::STPathElement( @@ -307,12 +307,12 @@ inline STPathElement::STPathElement( , accountID_(account) , assetID_(asset) , issuerID_(issuer) - , is_offer_(isXRP(accountID_)) + , isOffer_(isXRP(accountID_)) { assetID_.visit( [&](Currency const&) { type_ = type_ & (~Type::TypeMpt); }, [&](MPTID const&) { type_ = type_ & (~Type::TypeCurrency); }); - hash_value_ = getHash(*this); + hashValue_ = getHash(*this); } inline auto @@ -324,7 +324,7 @@ STPathElement::getNodeType() const inline bool STPathElement::isOffer() const { - return is_offer_; + return isOffer_; } inline bool @@ -404,7 +404,7 @@ STPathElement::getIssuerID() const inline bool STPathElement::operator==(STPathElement const& t) const { - return (type_ & TypeAccount) == (t.type_ & TypeAccount) && hash_value_ == t.hash_value_ && + return (type_ & TypeAccount) == (t.type_ & TypeAccount) && hashValue_ == t.hashValue_ && accountID_ == t.accountID_ && assetID_ == t.assetID_ && issuerID_ == t.issuerID_; } diff --git a/include/xrpl/protocol/STTx.h b/include/xrpl/protocol/STTx.h index 5aa70d1299..4deedfafb7 100644 --- a/include/xrpl/protocol/STTx.h +++ b/include/xrpl/protocol/STTx.h @@ -27,7 +27,7 @@ enum class TxnSql : char { class STTx final : public STObject, public CountedObject { uint256 tid_; - TxType tx_type_; + TxType txType_; public: static constexpr std::size_t kMinMultiSigners = 1; @@ -187,7 +187,7 @@ inline STTx::STTx(SerialIter&& sit) // NOLINT(cppcoreguidelines-rvalue-referenc inline TxType STTx::getTxnType() const { - return tx_type_; + return txType_; } inline Blob diff --git a/include/xrpl/resource/detail/Entry.h b/include/xrpl/resource/detail/Entry.h index b12bbf36ae..361c8409c8 100644 --- a/include/xrpl/resource/detail/Entry.h +++ b/include/xrpl/resource/detail/Entry.h @@ -21,7 +21,7 @@ struct Entry : public beast::List::Node @param now Construction time of Entry. */ explicit Entry(clock_type::time_point const now) - : refcount(0), local_balance(now), remote_balance(0) + : refcount(0), localBalance(now), remoteBalance(0) { } @@ -46,7 +46,7 @@ struct Entry : public beast::List::Node int balance(clock_type::time_point const now) { - return local_balance.value(now) + remote_balance; + return localBalance.value(now) + remoteBalance; } // Add a charge and return normalized balance @@ -54,7 +54,7 @@ struct Entry : public beast::List::Node int add(int charge, clock_type::time_point const now) { - return local_balance.add(charge, now) + remote_balance; + return localBalance.add(charge, now) + remoteBalance; } // The public key of the peer @@ -67,10 +67,10 @@ struct Entry : public beast::List::Node int refcount; // Exponentially decaying balance of resource consumption - DecayingSample local_balance; + DecayingSample localBalance; // Normalized balance contribution from imports - int remote_balance; + int remoteBalance; // Time of the last warning clock_type::time_point lastWarningTime; diff --git a/include/xrpl/resource/detail/Key.h b/include/xrpl/resource/detail/Key.h index 935d44425e..7d24b33955 100644 --- a/include/xrpl/resource/detail/Key.h +++ b/include/xrpl/resource/detail/Key.h @@ -25,11 +25,11 @@ struct Key std::size_t operator()(Key const& v) const { - return addr_hash_(v.address); + return addrHash_(v.address); } private: - beast::Uhash<> addr_hash_; + beast::Uhash<> addrHash_; }; struct KeyEqual diff --git a/include/xrpl/resource/detail/Logic.h b/include/xrpl/resource/detail/Logic.h index 7e63baca6c..b11ac100f5 100644 --- a/include/xrpl/resource/detail/Logic.h +++ b/include/xrpl/resource/detail/Logic.h @@ -194,34 +194,34 @@ public: for (auto& inboundEntry : inbound_) { - int const localBalance = inboundEntry.local_balance.value(now); - if ((localBalance + inboundEntry.remote_balance) >= threshold) + int const localBalance = inboundEntry.localBalance.value(now); + if ((localBalance + inboundEntry.remoteBalance) >= threshold) { json::Value& entry = (ret[inboundEntry.toString()] = json::ValueType::Object); entry[jss::local] = localBalance; - entry[jss::remote] = inboundEntry.remote_balance; + entry[jss::remote] = inboundEntry.remoteBalance; entry[jss::type] = "inbound"; } } for (auto& outboundEntry : outbound_) { - int const localBalance = outboundEntry.local_balance.value(now); - if ((localBalance + outboundEntry.remote_balance) >= threshold) + int const localBalance = outboundEntry.localBalance.value(now); + if ((localBalance + outboundEntry.remoteBalance) >= threshold) { json::Value& entry = (ret[outboundEntry.toString()] = json::ValueType::Object); entry[jss::local] = localBalance; - entry[jss::remote] = outboundEntry.remote_balance; + entry[jss::remote] = outboundEntry.remoteBalance; entry[jss::type] = "outbound"; } } for (auto& adminEntry : admin_) { - int const localBalance = adminEntry.local_balance.value(now); - if ((localBalance + adminEntry.remote_balance) >= threshold) + int const localBalance = adminEntry.localBalance.value(now); + if ((localBalance + adminEntry.remoteBalance) >= threshold) { json::Value& entry = (ret[adminEntry.toString()] = json::ValueType::Object); entry[jss::local] = localBalance; - entry[jss::remote] = adminEntry.remote_balance; + entry[jss::remote] = adminEntry.remoteBalance; entry[jss::type] = "admin"; } } @@ -242,7 +242,7 @@ public: for (auto& inboundEntry : inbound_) { Gossip::Item item; - item.balance = inboundEntry.local_balance.value(now); + item.balance = inboundEntry.localBalance.value(now); if (item.balance >= kMinimumGossipBalance) { item.address = inboundEntry.key->address; @@ -278,7 +278,7 @@ public: Import::Item item; item.balance = gossipItem.balance; item.consumer = newInboundEndpoint(gossipItem.address); - item.consumer.entry().remote_balance += item.balance; + item.consumer.entry().remoteBalance += item.balance; next.items.push_back(item); } } @@ -295,14 +295,14 @@ public: Import::Item item; item.balance = gossipItem.balance; item.consumer = newInboundEndpoint(gossipItem.address); - item.consumer.entry().remote_balance += item.balance; + item.consumer.entry().remoteBalance += item.balance; next.items.push_back(item); } Import& prev(resultIt->second); for (auto& item : prev.items) { - item.consumer.entry().remote_balance -= item.balance; + item.consumer.entry().remoteBalance -= item.balance; } std::swap(next, prev); @@ -345,7 +345,7 @@ public: for (auto itemIter(import.items.begin()); itemIter != import.items.end(); ++itemIter) { - itemIter->consumer.entry().remote_balance -= itemIter->balance; + itemIter->consumer.entry().remoteBalance -= itemIter->balance; } iter = importTable_.erase(iter); @@ -520,8 +520,8 @@ public: item["count"] = entry.refcount; item["name"] = entry.toString(); item["balance"] = entry.balance(now); - if (entry.remote_balance != 0) - item["remote_balance"] = entry.remote_balance; + if (entry.remoteBalance != 0) + item["remote_balance"] = entry.remoteBalance; } } diff --git a/include/xrpl/server/Handoff.h b/include/xrpl/server/Handoff.h index eba8c6c4de..b80a9c5745 100644 --- a/include/xrpl/server/Handoff.h +++ b/include/xrpl/server/Handoff.h @@ -21,7 +21,7 @@ struct Handoff bool moved = false; // If response is set, this determines the keep alive - bool keep_alive = false; + bool keepAlive = false; // When set, this will be sent back std::shared_ptr response; diff --git a/include/xrpl/server/Port.h b/include/xrpl/server/Port.h index 9207e0552b..ac9b855cf0 100644 --- a/include/xrpl/server/Port.h +++ b/include/xrpl/server/Port.h @@ -30,19 +30,19 @@ struct Port boost::asio::ip::address ip; std::uint16_t port = 0; std::set protocol; - std::vector admin_nets_v4; - std::vector admin_nets_v6; - std::vector secure_gateway_nets_v4; - std::vector secure_gateway_nets_v6; + std::vector adminNetsV4; + std::vector adminNetsV6; + std::vector secureGatewayNetsV4; + std::vector secureGatewayNetsV6; std::string user; std::string password; - std::string admin_user; - std::string admin_password; - std::string ssl_key; - std::string ssl_cert; - std::string ssl_chain; - std::string ssl_ciphers; - boost::beast::websocket::permessage_deflate pmd_options; + std::string adminUser; + std::string adminPassword; + std::string sslKey; + std::string sslCert; + std::string sslChain; + std::string sslCiphers; + boost::beast::websocket::permessage_deflate pmdOptions; std::shared_ptr context; // How many incoming connections are allowed on this @@ -50,7 +50,7 @@ struct Port int limit = 0; // Websocket disconnects if send queue exceeds this limit - std::uint16_t ws_queue_limit{}; + std::uint16_t wsQueueLimit{}; // Returns `true` if any websocket protocols are specified [[nodiscard]] bool @@ -78,22 +78,22 @@ struct ParsedPort std::set protocol; std::string user; std::string password; - std::string admin_user; - std::string admin_password; - std::string ssl_key; - std::string ssl_cert; - std::string ssl_chain; - std::string ssl_ciphers; - boost::beast::websocket::permessage_deflate pmd_options; + std::string adminUser; + std::string adminPassword; + std::string sslKey; + std::string sslCert; + std::string sslChain; + std::string sslCiphers; + boost::beast::websocket::permessage_deflate pmdOptions; int limit = 0; - std::uint16_t ws_queue_limit{}; + std::uint16_t wsQueueLimit{}; std::optional ip; std::optional port; - std::vector admin_nets_v4; - std::vector admin_nets_v6; - std::vector secure_gateway_nets_v4; - std::vector secure_gateway_nets_v6; + std::vector adminNetsV4; + std::vector adminNetsV6; + std::vector secureGatewayNetsV4; + std::vector secureGatewayNetsV6; }; void diff --git a/include/xrpl/server/detail/BaseHTTPPeer.h b/include/xrpl/server/detail/BaseHTTPPeer.h index 04ec4862c6..d26817bc45 100644 --- a/include/xrpl/server/detail/BaseHTTPPeer.h +++ b/include/xrpl/server/detail/BaseHTTPPeer.h @@ -58,13 +58,13 @@ protected: Handler& handler_; boost::asio::executor_work_guard work_; boost::asio::strand strand_; - endpoint_type remote_address_; + endpoint_type remoteAddress_; beast::Journal const journal_; std::string id_; std::size_t nid_; - boost::asio::streambuf read_buf_; + boost::asio::streambuf readBuf_; http_request_type message_; std::vector wq_; std::vector wq2_; @@ -73,9 +73,9 @@ protected: bool complete_ = false; boost::system::error_code ec_; - int request_count_ = 0; - std::size_t bytes_in_ = 0; - std::size_t bytes_out_ = 0; + int requestCount_ = 0; + std::size_t bytesIn_ = 0; + std::size_t bytesOut_ = 0; //-------------------------------------------------------------------------- @@ -151,7 +151,7 @@ protected: beast::IP::Endpoint remoteAddress() override { - return beast::IPAddressConversion::fromAsio(remote_address_); + return beast::IPAddressConversion::fromAsio(remoteAddress_); } http_request_type& @@ -191,23 +191,23 @@ BaseHTTPPeer::BaseHTTPPeer( , handler_(handler) , work_(boost::asio::make_work_guard(executor)) , strand_(boost::asio::make_strand(executor)) - , remote_address_(std::move(remoteAddress)) + , remoteAddress_(std::move(remoteAddress)) , journal_(journal) { - read_buf_.commit( - boost::asio::buffer_copy(read_buf_.prepare(boost::asio::buffer_size(buffers)), buffers)); + readBuf_.commit( + boost::asio::buffer_copy(readBuf_.prepare(boost::asio::buffer_size(buffers)), buffers)); static std::atomic kSid; nid_ = ++kSid; id_ = std::string("#") + std::to_string(nid_) + " "; - JLOG(journal_.trace()) << id_ << "accept: " << remote_address_.address(); + JLOG(journal_.trace()) << id_ << "accept: " << remoteAddress_.address(); } template BaseHTTPPeer::~BaseHTTPPeer() { handler_.onClose(session(), ec_); - JLOG(journal_.trace()) << id_ << "destroyed: " << request_count_ - << ((request_count_ == 1) ? " request" : " requests"); + JLOG(journal_.trace()) << id_ << "destroyed: " << requestCount_ + << ((requestCount_ == 1) ? " request" : " requests"); } template @@ -245,7 +245,7 @@ BaseHTTPPeer::startTimer() boost::beast::get_lowest_layer(impl().stream_) .expires_after( std::chrono::seconds( - remote_address_.address().is_loopback() ? kTimeoutSecondsLocal : kTimeoutSeconds)); + remoteAddress_.address().is_loopback() ? kTimeoutSecondsLocal : kTimeoutSeconds)); } // Convenience for discarding the error code @@ -274,7 +274,7 @@ BaseHTTPPeer::doRead(yield_context doYield) complete_ = false; error_code ec; startTimer(); - boost::beast::http::async_read(impl().stream_, read_buf_, message_, doYield[ec]); + boost::beast::http::async_read(impl().stream_, readBuf_, message_, doYield[ec]); cancelTimer(); if (ec == boost::beast::http::error::end_of_stream) return doClose(); @@ -296,7 +296,7 @@ BaseHTTPPeer::onWrite(error_code const& ec, std::size_t bytesTran return onTimer(); if (ec) return fail(ec, "write"); - bytes_out_ += bytesTransferred; + bytesOut_ += bytesTransferred; { std::scoped_lock const lock(mutex_); wq2_.clear(); diff --git a/include/xrpl/server/detail/BasePeer.h b/include/xrpl/server/detail/BasePeer.h index 3705ef448e..edde28981c 100644 --- a/include/xrpl/server/detail/BasePeer.h +++ b/include/xrpl/server/detail/BasePeer.h @@ -27,7 +27,7 @@ protected: Port const& port_; Handler& handler_; - endpoint_type remote_address_; + endpoint_type remoteAddress_; beast::WrappedSink sink_; beast::Journal const j_; @@ -65,7 +65,7 @@ BasePeer::BasePeer( beast::Journal journal) : port_(port) , handler_(handler) - , remote_address_(std::move(remoteAddress)) + , remoteAddress_(std::move(remoteAddress)) , sink_( journal.sink(), [] { diff --git a/include/xrpl/server/detail/BaseWSPeer.h b/include/xrpl/server/detail/BaseWSPeer.h index 181cf41f81..13225dcba1 100644 --- a/include/xrpl/server/detail/BaseWSPeer.h +++ b/include/xrpl/server/detail/BaseWSPeer.h @@ -42,15 +42,15 @@ private: /// The socket has been closed, or will close after the next write /// finishes. Do not do any more writes, and don't try to close /// again. - bool do_close_ = false; + bool doClose_ = false; boost::beast::websocket::close_reason cr_; waitable_timer timer_; - bool close_on_timer_ = false; - bool ping_active_ = false; + bool closeOnTimer_ = false; + bool pingActive_ = false; boost::beast::websocket::ping_data payload_; error_code ec_; std::function - control_callback_; + controlCallback_; public: template @@ -85,7 +85,7 @@ public: [[nodiscard]] boost::asio::ip::tcp::endpoint const& remoteEndpoint() const override { - return this->remote_address_; + return this->remoteAddress_; } void @@ -173,14 +173,14 @@ BaseWSPeer::run() { if (!strand_.running_in_this_thread()) return post(strand_, std::bind(&BaseWSPeer::run, impl().shared_from_this())); - impl().ws_.set_option(port().pmd_options); + impl().ws_.set_option(port().pmdOptions); // Must manage the control callback memory outside of the `control_callback` // function - control_callback_ = + controlCallback_ = std::bind(&BaseWSPeer::onPingPong, this, std::placeholders::_1, std::placeholders::_2); - impl().ws_.control_callback(control_callback_); + impl().ws_.control_callback(controlCallback_); startTimer(); - close_on_timer_ = true; + closeOnTimer_ = true; impl().ws_.set_option(boost::beast::websocket::stream_base::decorator([](auto& res) { res.set(boost::beast::http::field::server, BuildInfo::getFullVersionString()); })); @@ -198,9 +198,9 @@ BaseWSPeer::send(std::shared_ptr w) { if (!strand_.running_in_this_thread()) return post(strand_, std::bind(&BaseWSPeer::send, impl().shared_from_this(), std::move(w))); - if (do_close_) + if (doClose_) return; - if (wq_.size() > port().ws_queue_limit) + if (wq_.size() > port().wsQueueLimit) { cr_.code = safeCast(boost::beast::websocket::close_code::policy_error); cr_.reason = "Policy error: client is too slow."; @@ -227,9 +227,9 @@ BaseWSPeer::close(boost::beast::websocket::close_reason const& re { if (!strand_.running_in_this_thread()) return post(strand_, [self = impl().shared_from_this(), reason] { self->close(reason); }); - if (do_close_) + if (doClose_) return; - do_close_ = true; + doClose_ = true; if (wq_.empty()) { impl().ws_.async_close( @@ -260,7 +260,7 @@ BaseWSPeer::onWsHandshake(error_code const& ec) { if (ec) return fail(ec, "on_ws_handshake"); - close_on_timer_ = false; + closeOnTimer_ = false; doRead(); } @@ -313,7 +313,7 @@ BaseWSPeer::onWriteFin(error_code const& ec) if (ec) return fail(ec, "write_fin"); wq_.pop_front(); - if (do_close_) + if (doClose_) { impl().ws_.async_close( cr_, @@ -409,7 +409,7 @@ BaseWSPeer::onPing(error_code const& ec) { if (ec == boost::asio::error::operation_aborted) return; - ping_active_ = false; + pingActive_ = false; if (!ec) return; fail(ec, "on_ping"); @@ -426,7 +426,7 @@ BaseWSPeer::onPingPong( boost::beast::string_view const p(payload_.begin()); if (payload == p) { - close_on_timer_ = false; + closeOnTimer_ = false; JLOG(this->j_.trace()) << "got matching pong"; } else @@ -444,11 +444,11 @@ BaseWSPeer::onTimer(error_code ec) return; if (!ec) { - if (!close_on_timer_ || !ping_active_) + if (!closeOnTimer_ || !pingActive_) { startTimer(); - close_on_timer_ = true; - ping_active_ = true; + closeOnTimer_ = true; + pingActive_ = true; // cryptographic is probably overkill.. beast::rngfill(payload_.begin(), payload_.size(), cryptoPrng()); impl().ws_.async_ping( diff --git a/include/xrpl/server/detail/Door.h b/include/xrpl/server/detail/Door.h index d3fff8b476..e273ca791f 100644 --- a/include/xrpl/server/detail/Door.h +++ b/include/xrpl/server/detail/Door.h @@ -61,7 +61,7 @@ private: boost::asio::io_context& ioc_; stream_type stream_; socket_type& socket_; - endpoint_type remote_address_; + endpoint_type remoteAddress_; boost::asio::strand strand_; beast::Journal const j_; @@ -97,8 +97,8 @@ private: (port_.protocol.count("ws2") != 0u)}; static constexpr std::chrono::milliseconds kInitialAcceptDelay{50}; static constexpr std::chrono::milliseconds kMaxAcceptDelay{2000}; - std::chrono::milliseconds accept_delay_{kInitialAcceptDelay}; - boost::asio::steady_timer backoff_timer_; + std::chrono::milliseconds acceptDelay_{kInitialAcceptDelay}; + boost::asio::steady_timer backoffTimer_; static constexpr double kFreeFdThreshold = 0.70; struct FDStats @@ -164,7 +164,7 @@ Door::Detector::Detector( , ioc_(ioc) , stream_(std::move(stream)) , socket_(stream_.socket()) - , remote_address_(std::move(remoteAddress)) + , remoteAddress_(std::move(remoteAddress)) , strand_(boost::asio::make_strand(ioc_)) , j_(j) { @@ -199,18 +199,18 @@ Door::Detector::doDetect(boost::asio::yield_context doYield) if (ssl) { if (auto sp = ios().template emplace>( - port_, handler_, ioc_, j_, remote_address_, buf.data(), std::move(stream_))) + port_, handler_, ioc_, j_, remoteAddress_, buf.data(), std::move(stream_))) sp->run(); return; } if (auto sp = ios().template emplace>( - port_, handler_, ioc_, j_, remote_address_, buf.data(), std::move(stream_))) + port_, handler_, ioc_, j_, remoteAddress_, buf.data(), std::move(stream_))) sp->run(); return; } if (ec != boost::asio::error::operation_aborted) { - JLOG(j_.trace()) << "Error detecting ssl: " << ec.message() << " from " << remote_address_; + JLOG(j_.trace()) << "Error detecting ssl: " << ec.message() << " from " << remoteAddress_; } } @@ -279,7 +279,7 @@ Door::Door( , ioc_(ioContext) , acceptor_(ioContext) , strand_(boost::asio::make_strand(ioContext)) - , backoff_timer_(ioContext) + , backoffTimer_(ioContext) { reOpen(); } @@ -302,7 +302,7 @@ Door::close() return boost::asio::post( strand_, std::bind(&Door::close, this->shared_from_this())); } - backoff_timer_.cancel(); + backoffTimer_.cancel(); error_code ec; acceptor_.close(ec); } @@ -338,11 +338,11 @@ Door::doAccept(boost::asio::yield_context doYield) { if (shouldThrottleForFds()) { - backoff_timer_.expires_after(accept_delay_); + backoffTimer_.expires_after(acceptDelay_); boost::system::error_code tec; - backoff_timer_.async_wait(doYield[tec]); - accept_delay_ = std::min(accept_delay_ * 2, kMaxAcceptDelay); - JLOG(j_.warn()) << "Throttling do_accept for " << accept_delay_.count() << "ms."; + backoffTimer_.async_wait(doYield[tec]); + acceptDelay_ = std::min(acceptDelay_ * 2, kMaxAcceptDelay); + JLOG(j_.warn()) << "Throttling do_accept for " << acceptDelay_.count() << "ms."; continue; } @@ -360,13 +360,13 @@ Door::doAccept(boost::asio::yield_context doYield) ec == boost::asio::error::no_buffer_space) { JLOG(j_.warn()) << "accept: Too many open files. Pausing for " - << accept_delay_.count() << "ms."; + << acceptDelay_.count() << "ms."; - backoff_timer_.expires_after(accept_delay_); + backoffTimer_.expires_after(acceptDelay_); boost::system::error_code tec; - backoff_timer_.async_wait(doYield[tec]); + backoffTimer_.async_wait(doYield[tec]); - accept_delay_ = std::min(accept_delay_ * 2, kMaxAcceptDelay); + acceptDelay_ = std::min(acceptDelay_ * 2, kMaxAcceptDelay); } else { @@ -375,7 +375,7 @@ Door::doAccept(boost::asio::yield_context doYield) continue; } - accept_delay_ = kInitialAcceptDelay; + acceptDelay_ = kInitialAcceptDelay; if (ssl_ && plain_) { diff --git a/include/xrpl/server/detail/PlainHTTPPeer.h b/include/xrpl/server/detail/PlainHTTPPeer.h index 40f7fe2571..791ab91acf 100644 --- a/include/xrpl/server/detail/PlainHTTPPeer.h +++ b/include/xrpl/server/detail/PlainHTTPPeer.h @@ -82,7 +82,7 @@ template void PlainHTTPPeer::run() { - if (!this->handler_.onAccept(this->session(), this->remote_address_)) + if (!this->handler_.onAccept(this->session(), this->remoteAddress_)) { util::spawn(this->strand_, std::bind(&PlainHTTPPeer::doClose, this->shared_from_this())); return; @@ -103,7 +103,7 @@ PlainHTTPPeer::websocketUpgrade() auto ws = this->ios().template emplace>( this->port_, this->handler_, - this->remote_address_, + this->remoteAddress_, std::move(this->message_), std::move(stream_), this->journal_); @@ -114,20 +114,20 @@ template void PlainHTTPPeer::doRequest() { - ++this->request_count_; + ++this->requestCount_; auto const what = - this->handler_.onHandoff(this->session(), std::move(this->message_), this->remote_address_); + this->handler_.onHandoff(this->session(), std::move(this->message_), this->remoteAddress_); if (what.moved) return; boost::system::error_code ec; if (what.response) { // half-close on Connection: close - if (!what.keep_alive) + if (!what.keepAlive) socket_.shutdown(socket_type::shutdown_receive, ec); if (ec) return this->fail(ec, "request"); - return this->write(what.response, what.keep_alive); + return this->write(what.response, what.keepAlive); } // Perform half-close when Connection: close and not SSL diff --git a/include/xrpl/server/detail/SSLHTTPPeer.h b/include/xrpl/server/detail/SSLHTTPPeer.h index 2eec8ed60f..f3b047150f 100644 --- a/include/xrpl/server/detail/SSLHTTPPeer.h +++ b/include/xrpl/server/detail/SSLHTTPPeer.h @@ -26,7 +26,7 @@ private: using yield_context = boost::asio::yield_context; using error_code = boost::system::error_code; - std::unique_ptr stream_ptr_; + std::unique_ptr streamPtr_; stream_type& stream_; socket_type& socket_; @@ -80,8 +80,8 @@ SSLHTTPPeer::SSLHTTPPeer( journal, remoteAddress, buffers) - , stream_ptr_(std::make_unique(middle_type(std::move(stream)), *port.context)) - , stream_(*stream_ptr_) + , streamPtr_(std::make_unique(middle_type(std::move(stream)), *port.context)) + , stream_(*streamPtr_) , socket_(stream_.next_layer().socket()) { } @@ -91,7 +91,7 @@ template void SSLHTTPPeer::run() { - if (!this->handler_.onAccept(this->session(), this->remote_address_)) + if (!this->handler_.onAccept(this->session(), this->remoteAddress_)) { util::spawn(this->strand_, std::bind(&SSLHTTPPeer::doClose, this->shared_from_this())); return; @@ -110,9 +110,9 @@ SSLHTTPPeer::websocketUpgrade() auto ws = this->ios().template emplace>( this->port_, this->handler_, - this->remote_address_, + this->remoteAddress_, std::move(this->message_), - std::move(this->stream_ptr_), + std::move(this->streamPtr_), this->journal_); return ws; } @@ -124,8 +124,8 @@ SSLHTTPPeer::doHandshake(yield_context doYield) boost::system::error_code ec; stream_.set_verify_mode(boost::asio::ssl::verify_none); this->startTimer(); - this->read_buf_.consume( - stream_.async_handshake(stream_type::server, this->read_buf_.data(), doYield[ec])); + this->readBuf_.consume( + stream_.async_handshake(stream_type::server, this->readBuf_.data(), doYield[ec])); this->cancelTimer(); if (ec == boost::beast::error::timeout) return this->onTimer(); @@ -148,13 +148,13 @@ template void SSLHTTPPeer::doRequest() { - ++this->request_count_; + ++this->requestCount_; auto const what = this->handler_.onHandoff( - this->session(), std::move(stream_ptr_), std::move(this->message_), this->remote_address_); + this->session(), std::move(streamPtr_), std::move(this->message_), this->remoteAddress_); if (what.moved) return; if (what.response) - return this->write(what.response, what.keep_alive); + return this->write(what.response, what.keepAlive); // legacy this->handler_.onRequest(this->session()); } diff --git a/include/xrpl/server/detail/SSLWSPeer.h b/include/xrpl/server/detail/SSLWSPeer.h index 19b77ea932..cb03d5a796 100644 --- a/include/xrpl/server/detail/SSLWSPeer.h +++ b/include/xrpl/server/detail/SSLWSPeer.h @@ -28,7 +28,7 @@ class SSLWSPeer : public BaseWSPeer>, using stream_type = boost::beast::ssl_stream; using waitable_timer = boost::asio::basic_waitable_timer; - std::unique_ptr stream_ptr_; + std::unique_ptr streamPtr_; boost::beast::websocket::stream ws_; public: @@ -61,8 +61,8 @@ SSLWSPeer::SSLWSPeer( remoteEndpoint, std::move(request), journal) - , stream_ptr_(std::move(streamPtr)) - , ws_(*stream_ptr_) + , streamPtr_(std::move(streamPtr)) + , ws_(*streamPtr_) { } diff --git a/include/xrpl/server/detail/ServerImpl.h b/include/xrpl/server/detail/ServerImpl.h index df9a2dd3e8..48ffa26cfe 100644 --- a/include/xrpl/server/detail/ServerImpl.h +++ b/include/xrpl/server/detail/ServerImpl.h @@ -66,7 +66,7 @@ private: Handler& handler_; beast::Journal const j_; - boost::asio::io_context& io_context_; + boost::asio::io_context& ioContext_; boost::asio::strand strand_; std::optional> work_; @@ -104,7 +104,7 @@ public: boost::asio::io_context& getIoContext() { - return io_context_; + return ioContext_; } bool @@ -122,9 +122,9 @@ ServerImpl::ServerImpl( beast::Journal journal) : handler_(handler) , j_(journal) - , io_context_(ioContext) - , strand_(boost::asio::make_strand(io_context_)) - , work_(std::in_place, boost::asio::make_work_guard(io_context_)) + , ioContext_(ioContext) + , strand_(boost::asio::make_strand(ioContext_)) + , work_(std::in_place, boost::asio::make_work_guard(ioContext_)) { } @@ -150,7 +150,7 @@ ServerImpl::ports(std::vector const& ports) { ports_.push_back(port); auto& internalPort = ports_.back(); - if (auto sp = ios_.emplace>(handler_, io_context_, internalPort, j_)) + if (auto sp = ios_.emplace>(handler_, ioContext_, internalPort, j_)) { list_.push_back(sp); diff --git a/src/libxrpl/basics/ResolverAsio.cpp b/src/libxrpl/basics/ResolverAsio.cpp index 4a5ceb3d8d..ddf006b681 100644 --- a/src/libxrpl/basics/ResolverAsio.cpp +++ b/src/libxrpl/basics/ResolverAsio.cpp @@ -108,7 +108,7 @@ public: beast::Journal journal; - boost::asio::io_context& io_context; + boost::asio::io_context& ioContext; boost::asio::strand strand; boost::asio::ip::tcp::resolver resolver; @@ -116,7 +116,7 @@ public: std::mutex mut; bool asyncHandlersCompleted{true}; - std::atomic stop_called; + std::atomic stopCalled; std::atomic stopped; // Represents a unit of work for the resolver to do @@ -138,10 +138,10 @@ public: ResolverAsioImpl(boost::asio::io_context& ioContext, beast::Journal journal) : journal(journal) - , io_context(ioContext) + , ioContext(ioContext) , strand(boost::asio::make_strand(ioContext)) , resolver(ioContext) - , stop_called(false) + , stopCalled(false) , stopped(true) { } @@ -172,7 +172,7 @@ public: start() override { XRPL_ASSERT(stopped == true, "xrpl::ResolverAsioImpl::start : stopped"); - XRPL_ASSERT(stop_called == false, "xrpl::ResolverAsioImpl::start : not stopping"); + XRPL_ASSERT(stopCalled == false, "xrpl::ResolverAsioImpl::start : not stopping"); if (stopped.exchange(false)) { @@ -187,10 +187,10 @@ public: void stopAsync() override { - if (!stop_called.exchange(true)) + if (!stopCalled.exchange(true)) { boost::asio::dispatch( - io_context, + ioContext, boost::asio::bind_executor( strand, std::bind(&ResolverAsioImpl::doStop, this, CompletionCounter(this)))); @@ -213,13 +213,13 @@ public: void resolve(std::vector const& names, HandlerType const& handler) override { - XRPL_ASSERT(stop_called == false, "xrpl::ResolverAsioImpl::resolve : not stopping"); + XRPL_ASSERT(stopCalled == false, "xrpl::ResolverAsioImpl::resolve : not stopping"); XRPL_ASSERT(!names.empty(), "xrpl::ResolverAsioImpl::resolve : names non-empty"); // TODO NIKB use rvalue references to construct and move // reducing cost. boost::asio::dispatch( - io_context, + ioContext, boost::asio::bind_executor( strand, std::bind( @@ -231,7 +231,7 @@ public: void doStop(CompletionCounter) { - XRPL_ASSERT(stop_called == true, "xrpl::ResolverAsioImpl::doStop : stopping"); + XRPL_ASSERT(stopCalled == true, "xrpl::ResolverAsioImpl::doStop : stopping"); if (!stopped.exchange(true)) { @@ -270,7 +270,7 @@ public: handler(name, addresses); boost::asio::post( - io_context, + ioContext, boost::asio::bind_executor( strand, std::bind(&ResolverAsioImpl::doWork, this, CompletionCounter(this)))); } @@ -324,7 +324,7 @@ public: void doWork(CompletionCounter) { - if (stop_called) + if (stopCalled) return; // We don't have any work to do at this time @@ -346,7 +346,7 @@ public: JLOG(journal.error()) << "Unable to parse '" << name << "'"; boost::asio::post( - io_context, + ioContext, boost::asio::bind_executor( strand, std::bind(&ResolverAsioImpl::doWork, this, CompletionCounter(this)))); @@ -371,7 +371,7 @@ public: { XRPL_ASSERT(!names.empty(), "xrpl::ResolverAsioImpl::doResolve : names non-empty"); - if (!stop_called) + if (!stopCalled) { work.emplace_back(names, handler); @@ -381,7 +381,7 @@ public: if (!work.empty()) { boost::asio::post( - io_context, + ioContext, boost::asio::bind_executor( strand, std::bind(&ResolverAsioImpl::doWork, this, CompletionCounter(this)))); diff --git a/src/libxrpl/beast/insight/StatsDCollector.cpp b/src/libxrpl/beast/insight/StatsDCollector.cpp index 7d460d54ef..88f52c26de 100644 --- a/src/libxrpl/beast/insight/StatsDCollector.cpp +++ b/src/libxrpl/beast/insight/StatsDCollector.cpp @@ -164,7 +164,7 @@ public: private: std::shared_ptr impl_; std::string name_; - GaugeImpl::value_type last_value_{0}; + GaugeImpl::value_type lastValue_{0}; GaugeImpl::value_type value_{0}; bool dirty_{false}; }; @@ -209,7 +209,7 @@ private: Journal journal_; IP::Endpoint address_; std::string prefix_; - boost::asio::io_context io_context_; + boost::asio::io_context ioContext_; std::optional> work_; boost::asio::strand strand_; boost::asio::basic_waitable_timer timer_; @@ -232,10 +232,10 @@ public: : journal_(journal) , address_(std::move(address)) , prefix_(std::move(prefix)) - , work_(boost::asio::make_work_guard(io_context_)) - , strand_(boost::asio::make_strand(io_context_)) - , timer_(io_context_) - , socket_(io_context_) + , work_(boost::asio::make_work_guard(ioContext_)) + , strand_(boost::asio::make_strand(ioContext_)) + , timer_(ioContext_) + , socket_(ioContext_) , thread_(&StatsDCollectorImp::run, this) { } @@ -306,7 +306,7 @@ public: boost::asio::io_context& getIoContext() { - return io_context_; + return ioContext_; } std::string const& @@ -325,7 +325,7 @@ public: postBuffer(std::string&& buffer) { boost::asio::dispatch( - io_context_, + ioContext_, boost::asio::bind_executor( strand_, std::bind(&StatsDCollectorImp::doPostBuffer, this, std::move(buffer)))); } @@ -465,14 +465,14 @@ public: setTimer(); - io_context_.run(); + ioContext_.run(); // NOLINTNEXTLINE(bugprone-unused-return-value) socket_.shutdown(boost::asio::ip::udp::socket::shutdown_send, ec); socket_.close(); - io_context_.poll(); + ioContext_.poll(); } }; @@ -628,9 +628,9 @@ StatsDGaugeImpl::doSet(GaugeImpl::value_type value) { value_ = value; - if (value_ != last_value_) + if (value_ != lastValue_) { - last_value_ = value_; + lastValue_ = value_; dirty_ = true; } } diff --git a/src/libxrpl/core/detail/Job.cpp b/src/libxrpl/core/detail/Job.cpp index a1b88864d7..89fe42db05 100644 --- a/src/libxrpl/core/detail/Job.cpp +++ b/src/libxrpl/core/detail/Job.cpp @@ -25,7 +25,7 @@ Job::Job( std::uint64_t index, LoadMonitor& lm, std::function const& job) - : type_(type), jobIndex_(index), job_(job), name_(name), queue_time_(clock_type::now()) + : type_(type), jobIndex_(index), job_(job), name_(name), queueTime_(clock_type::now()) { loadEvent_ = std::make_shared(std::ref(lm), name, false); } @@ -39,7 +39,7 @@ Job::getType() const Job::clock_type::time_point const& Job::queueTime() const { - return queue_time_; + return queueTime_; } void diff --git a/src/libxrpl/core/detail/JobQueue.cpp b/src/libxrpl/core/detail/JobQueue.cpp index 50f95dcdbf..5c07bf68cc 100644 --- a/src/libxrpl/core/detail/JobQueue.cpp +++ b/src/libxrpl/core/detail/JobQueue.cpp @@ -36,7 +36,7 @@ JobQueue::JobQueue( JLOG(journal_.info()) << "Using " << threadCount << " threads"; hook_ = collector_->makeHook(std::bind(&JobQueue::collect, this)); - job_count_ = collector_->makeGauge("job_count"); + jobCount_ = collector_->makeGauge("job_count"); { std::scoped_lock const lock(mutex_); @@ -66,7 +66,7 @@ void JobQueue::collect() { std::scoped_lock const lock(mutex_); - job_count_ = jobSet_.size(); + jobCount_ = jobSet_.size(); } bool diff --git a/src/libxrpl/ledger/BookDirs.cpp b/src/libxrpl/ledger/BookDirs.cpp index f3e41e4f58..099fec99e1 100644 --- a/src/libxrpl/ledger/BookDirs.cpp +++ b/src/libxrpl/ledger/BookDirs.cpp @@ -14,8 +14,8 @@ namespace xrpl { BookDirs::BookDirs(ReadView const& view, Book const& book) : view_(&view) , root_(keylet::page(getBookBase(book)).key) - , next_quality_(getQualityNext(root_)) - , key_(view_->succ(root_, next_quality_).value_or(beast::kZero)) + , nextQuality_(getQualityNext(root_)) + , key_(view_->succ(root_, nextQuality_).value_or(beast::kZero)) { XRPL_ASSERT(root_ != beast::kZero, "xrpl::BookDirs::BookDirs : nonzero root"); if (key_ != beast::kZero) @@ -35,7 +35,7 @@ BookDirs::begin() const -> BookDirs::const_iterator auto it = BookDirs::const_iterator(*view_, root_, key_); if (key_ != beast::kZero) { - it.next_quality_ = next_quality_; + it.nextQuality_ = nextQuality_; it.sle_ = sle_; it.entry_ = entry_; it.index_ = index_; @@ -59,7 +59,7 @@ BookDirs::const_iterator::operator==(BookDirs::const_iterator const& other) cons view_ == other.view_ && root_ == other.root_, "xrpl::BookDirs::const_iterator::operator== : views and roots are " "matching"); - return entry_ == other.entry_ && cur_key_ == other.cur_key_ && index_ == other.index_; + return entry_ == other.entry_ && curKey_ == other.curKey_ && index_ == other.index_; } BookDirs::const_iterator::reference @@ -78,18 +78,18 @@ BookDirs::const_iterator::operator++() using beast::kZero; XRPL_ASSERT(index_ != kZero, "xrpl::BookDirs::const_iterator::operator++ : nonzero index"); - if (!cdirNext(*view_, cur_key_, sle_, entry_, index_)) + if (!cdirNext(*view_, curKey_, sle_, entry_, index_)) { if (index_ == 0) - cur_key_ = view_->succ(++cur_key_, next_quality_).value_or(kZero); + curKey_ = view_->succ(++curKey_, nextQuality_).value_or(kZero); - if (index_ != 0 || cur_key_ == kZero) + if (index_ != 0 || curKey_ == kZero) { - cur_key_ = key_; + curKey_ = key_; entry_ = 0; index_ = kZero; } - else if (!cdirFirst(*view_, cur_key_, sle_, entry_, index_)) + else if (!cdirFirst(*view_, curKey_, sle_, entry_, index_)) { // LCOV_EXCL_START UNREACHABLE("xrpl::BookDirs::const_iterator::operator++ : directory is empty"); diff --git a/src/libxrpl/ledger/OpenView.cpp b/src/libxrpl/ledger/OpenView.cpp index c5bda2d0c8..40b411fcc0 100644 --- a/src/libxrpl/ledger/OpenView.cpp +++ b/src/libxrpl/ledger/OpenView.cpp @@ -78,9 +78,9 @@ public: OpenView::OpenView(OpenView const& rhs) : ReadView(rhs) , TxsRawView(rhs) - , monotonic_resource_{std::make_unique( + , monotonicResource_{std::make_unique( kInitialBufferSize)} - , txs_{rhs.txs_, monotonic_resource_.get()} + , txs_{rhs.txs_, monotonicResource_.get()} , rules_{rhs.rules_} , header_{rhs.header_} , base_{rhs.base_} @@ -89,9 +89,9 @@ OpenView::OpenView(OpenView const& rhs) , open_{rhs.open_} {}; OpenView::OpenView(OpenLedgerT, ReadView const* base, Rules rules, std::shared_ptr hold) - : monotonic_resource_{ + : monotonicResource_{ std::make_unique(kInitialBufferSize)} - , txs_{monotonic_resource_.get()} + , txs_{monotonicResource_.get()} , rules_(std::move(rules)) , header_(base->header()) , base_(base) @@ -105,9 +105,9 @@ OpenView::OpenView(OpenLedgerT, ReadView const* base, Rules rules, std::shared_p } OpenView::OpenView(ReadView const* base, std::shared_ptr hold) - : monotonic_resource_{ + : monotonicResource_{ std::make_unique(kInitialBufferSize)} - , txs_{monotonic_resource_.get()} + , txs_{monotonicResource_.get()} , rules_(base->rules()) , header_(base->header()) , base_(base) diff --git a/src/libxrpl/protocol/ErrorCodes.cpp b/src/libxrpl/protocol/ErrorCodes.cpp index 25c5fbe033..87761ce13e 100644 --- a/src/libxrpl/protocol/ErrorCodes.cpp +++ b/src/libxrpl/protocol/ErrorCodes.cpp @@ -212,7 +212,7 @@ containsError(json::Value const& json) int errorCodeHttpStatus(ErrorCodeI code) { - return getErrorInfo(code).http_status; + return getErrorInfo(code).httpStatus; } } // namespace RPC diff --git a/src/libxrpl/protocol/STTx.cpp b/src/libxrpl/protocol/STTx.cpp index 8636c99284..2777981fd7 100644 --- a/src/libxrpl/protocol/STTx.cpp +++ b/src/libxrpl/protocol/STTx.cpp @@ -69,8 +69,8 @@ getTxFormat(TxType type) STTx::STTx(STObject&& object) : STObject(std::move(object)) { - tx_type_ = safeCast(getFieldU16(sfTransactionType)); - applyTemplate(getTxFormat(tx_type_)->getSOTemplate()); // may throw + txType_ = safeCast(getFieldU16(sfTransactionType)); + applyTemplate(getTxFormat(txType_)->getSOTemplate()); // may throw tid_ = getHash(HashPrefix::TransactionId); } @@ -84,9 +84,9 @@ STTx::STTx(SerialIter& sit) : STObject(sfTransaction) if (set(sit)) Throw("Transaction contains an object terminator"); - tx_type_ = safeCast(getFieldU16(sfTransactionType)); + txType_ = safeCast(getFieldU16(sfTransactionType)); - applyTemplate(getTxFormat(tx_type_)->getSOTemplate()); // May throw + applyTemplate(getTxFormat(txType_)->getSOTemplate()); // May throw tid_ = getHash(HashPrefix::TransactionId); } @@ -99,9 +99,9 @@ STTx::STTx(TxType type, std::function assembler) : STObject(sfT assembler(*this); - tx_type_ = safeCast(getFieldU16(sfTransactionType)); + txType_ = safeCast(getFieldU16(sfTransactionType)); - if (tx_type_ != type) + if (txType_ != type) logicError("Transaction type was mutated during assembly"); tid_ = getHash(HashPrefix::TransactionId); @@ -380,7 +380,7 @@ STTx::getMetaSQL( static boost::format const kBfTrans("('%s', '%s', '%s', '%d', '%d', '%c', %s, %s)"); std::string rTxn = sqlBlobLiteral(rawTxn.peekData()); - auto format = TxFormats::getInstance().findByType(tx_type_); + auto format = TxFormats::getInstance().findByType(txType_); XRPL_ASSERT(format, "xrpl::STTx::getMetaSQL : non-null type format"); return str( diff --git a/src/libxrpl/server/Port.cpp b/src/libxrpl/server/Port.cpp index 9a6b6dce35..00c10b2b55 100644 --- a/src/libxrpl/server/Port.cpp +++ b/src/libxrpl/server/Port.cpp @@ -44,30 +44,30 @@ operator<<(std::ostream& os, Port const& p) { os << "'" << p.name << "' (ip=" << p.ip << ":" << p.port << ", "; - if (!p.admin_nets_v4.empty() || !p.admin_nets_v6.empty()) + if (!p.adminNetsV4.empty() || !p.adminNetsV6.empty()) { os << "admin nets:"; - for (auto const& net : p.admin_nets_v4) + for (auto const& net : p.adminNetsV4) { os << net.to_string(); os << ", "; } - for (auto const& net : p.admin_nets_v6) + for (auto const& net : p.adminNetsV6) { os << net.to_string(); os << ", "; } } - if (!p.secure_gateway_nets_v4.empty() || !p.secure_gateway_nets_v6.empty()) + if (!p.secureGatewayNetsV4.empty() || !p.secureGatewayNetsV6.empty()) { os << "secure_gateway nets:"; - for (auto const& net : p.secure_gateway_nets_v4) + for (auto const& net : p.secureGatewayNetsV4) { os << net.to_string(); os << ", "; } - for (auto const& net : p.secure_gateway_nets_v6) + for (auto const& net : p.secureGatewayNetsV6) { os << net.to_string(); os << ", "; @@ -265,10 +265,10 @@ parsePort(ParsedPort& port, Section const& section, std::ostream& log) { try { - port.ws_queue_limit = beast::lexicalCastThrow(*optResult); + port.wsQueueLimit = beast::lexicalCastThrow(*optResult); // Queue must be greater than 0 - if (port.ws_queue_limit == 0) + if (port.wsQueueLimit == 0) Throw(); } catch (std::exception const&) @@ -281,32 +281,31 @@ parsePort(ParsedPort& port, Section const& section, std::ostream& log) else { // Default Websocket send queue size limit - port.ws_queue_limit = 100; + port.wsQueueLimit = 100; } } - populate(section, "admin", log, port.admin_nets_v4, port.admin_nets_v6); - populate( - section, "secure_gateway", log, port.secure_gateway_nets_v4, port.secure_gateway_nets_v6); + populate(section, "admin", log, port.adminNetsV4, port.adminNetsV6); + populate(section, "secure_gateway", log, port.secureGatewayNetsV4, port.secureGatewayNetsV6); set(port.user, "user", section); set(port.password, "password", section); - set(port.admin_user, "admin_user", section); - set(port.admin_password, "admin_password", section); - set(port.ssl_key, "ssl_key", section); - set(port.ssl_cert, "ssl_cert", section); - set(port.ssl_chain, "ssl_chain", section); - set(port.ssl_ciphers, "ssl_ciphers", 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); - port.pmd_options.server_enable = section.valueOr("permessage_deflate", true); - port.pmd_options.client_max_window_bits = section.valueOr("client_max_window_bits", 15); - port.pmd_options.server_max_window_bits = section.valueOr("server_max_window_bits", 15); - port.pmd_options.client_no_context_takeover = + 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.client_no_context_takeover = section.valueOr("client_no_context_takeover", false); - port.pmd_options.server_no_context_takeover = + port.pmdOptions.server_no_context_takeover = section.valueOr("server_no_context_takeover", false); - port.pmd_options.compLevel = section.valueOr("compress_level", 8); - port.pmd_options.memLevel = section.valueOr("memory_level", 4); + port.pmdOptions.compLevel = section.valueOr("compress_level", 8); + port.pmdOptions.memLevel = section.valueOr("memory_level", 4); } } // namespace xrpl diff --git a/src/test/app/AMMMPT_test.cpp b/src/test/app/AMMMPT_test.cpp index eba388e5fd..cfb8edc60b 100644 --- a/src/test/app/AMMMPT_test.cpp +++ b/src/test/app/AMMMPT_test.cpp @@ -6299,9 +6299,9 @@ private: struct MPTList { - MPTTester const USD; - MPTTester const ETH; - MPTTester const CAN; + MPTTester const usd; + MPTTester const eth; + MPTTester const can; }; auto prep = [&](Env& env, uint16_t gwTransferFee, uint16_t gw1TransferFee) -> MPTList { @@ -6330,9 +6330,9 @@ private: env.close(); return MPTList{ - .USD = std::move(usd), - .ETH = std::move(eth), - .CAN = std::move(can), + .usd = std::move(usd), + .eth = std::move(eth), + .can = std::move(can), }; }; @@ -6357,9 +6357,9 @@ private: { Env env(*this, features); auto mpts = prep(env, rates.first, rates.second); - auto usd = mpts.USD; - auto eth = mpts.ETH; - auto can = mpts.CAN; + auto usd = mpts.usd; + auto eth = mpts.eth; + auto can = mpts.can; std::optional amm; if (i == 0 || i == 2) @@ -6402,9 +6402,9 @@ private: { Env env(*this, features); auto mpts = prep(env, rates.first, rates.second); - auto usd = mpts.USD; - auto eth = mpts.ETH; - auto can = mpts.CAN; + auto usd = mpts.usd; + auto eth = mpts.eth; + auto can = mpts.can; std::optional amm; if (i == 0 || i == 2) { @@ -6447,9 +6447,9 @@ private: { Env env(*this, features); auto mpts = prep(env, rates.first, rates.second); - auto usd = mpts.USD; - auto eth = mpts.ETH; - auto can = mpts.CAN; + auto usd = mpts.usd; + auto eth = mpts.eth; + auto can = mpts.can; std::optional amm; if (i == 0 || i == 2) { @@ -6513,9 +6513,9 @@ private: { Env env(*this, features); auto mpts = prep(env, rates.first, rates.second); - auto usd = mpts.USD; - auto eth = mpts.ETH; - auto can = mpts.CAN; + auto usd = mpts.usd; + auto eth = mpts.eth; + auto can = mpts.can; std::optional amm; if (i == 0 || i == 2) { @@ -6591,9 +6591,9 @@ private: { Env env(*this, features); auto mpts = prep(env, rates.first, rates.second); - auto usd = mpts.USD; - auto eth = mpts.ETH; - auto can = mpts.CAN; + auto usd = mpts.usd; + auto eth = mpts.eth; + auto can = mpts.can; std::optional amm; if (i == 0 || i == 2) @@ -6929,7 +6929,7 @@ private: Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = XRPAmount(1); + cfg->fees.referenceFee = XRPAmount(1); return cfg; }), all); @@ -6983,7 +6983,7 @@ private: Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = XRPAmount(1); + cfg->fees.referenceFee = XRPAmount(1); return cfg; }), all); @@ -7018,7 +7018,7 @@ private: Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = XRPAmount(1); + cfg->fees.referenceFee = XRPAmount(1); return cfg; }), all); @@ -7042,7 +7042,7 @@ private: Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = XRPAmount(1); + cfg->fees.referenceFee = XRPAmount(1); return cfg; }), all); diff --git a/src/test/app/AMM_test.cpp b/src/test/app/AMM_test.cpp index 68ebdbcf60..17f959ae3c 100644 --- a/src/test/app/AMM_test.cpp +++ b/src/test/app/AMM_test.cpp @@ -5093,7 +5093,7 @@ private: Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = XRPAmount(1); + cfg->fees.referenceFee = XRPAmount(1); return cfg; }), all); @@ -5151,7 +5151,7 @@ private: Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = XRPAmount(1); + cfg->fees.referenceFee = XRPAmount(1); return cfg; }), all); @@ -7090,7 +7090,7 @@ private: Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = XRPAmount(1); + cfg->fees.referenceFee = XRPAmount(1); return cfg; }), features); diff --git a/src/test/app/FeeVote_test.cpp b/src/test/app/FeeVote_test.cpp index 4fb97a0b74..22e8322bb5 100644 --- a/src/test/app/FeeVote_test.cpp +++ b/src/test/app/FeeVote_test.cpp @@ -213,18 +213,18 @@ class FeeVote_test : public beast::unit_test::Suite // defaults Section const config; auto setup = setupFeeVote(config); - BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); - BEAST_EXPECT(setup.account_reserve == defaultSetup.account_reserve); - BEAST_EXPECT(setup.owner_reserve == defaultSetup.owner_reserve); + BEAST_EXPECT(setup.referenceFee == defaultSetup.referenceFee); + BEAST_EXPECT(setup.accountReserve == defaultSetup.accountReserve); + BEAST_EXPECT(setup.ownerReserve == defaultSetup.ownerReserve); } { Section config; config.append( {"reference_fee = 50", "account_reserve = 1234567", "owner_reserve = 1234"}); auto setup = setupFeeVote(config); - BEAST_EXPECT(setup.reference_fee == 50); - BEAST_EXPECT(setup.account_reserve == 1234567); - BEAST_EXPECT(setup.owner_reserve == 1234); + BEAST_EXPECT(setup.referenceFee == 50); + BEAST_EXPECT(setup.accountReserve == 1234567); + BEAST_EXPECT(setup.ownerReserve == 1234); } { Section config; @@ -232,9 +232,9 @@ class FeeVote_test : public beast::unit_test::Suite {"reference_fee = blah", "account_reserve = yada", "owner_reserve = foo"}); // Illegal values are ignored, and the defaults left unchanged auto setup = setupFeeVote(config); - BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); - BEAST_EXPECT(setup.account_reserve == defaultSetup.account_reserve); - BEAST_EXPECT(setup.owner_reserve == defaultSetup.owner_reserve); + BEAST_EXPECT(setup.referenceFee == defaultSetup.referenceFee); + BEAST_EXPECT(setup.accountReserve == defaultSetup.accountReserve); + BEAST_EXPECT(setup.ownerReserve == defaultSetup.ownerReserve); } { Section config; @@ -242,9 +242,9 @@ class FeeVote_test : public beast::unit_test::Suite {"reference_fee = -50", "account_reserve = -1234567", "owner_reserve = -1234"}); // Illegal values are ignored, and the defaults left unchanged auto setup = setupFeeVote(config); - BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); - BEAST_EXPECT(setup.account_reserve == static_cast(-1234567)); - BEAST_EXPECT(setup.owner_reserve == static_cast(-1234)); + BEAST_EXPECT(setup.referenceFee == defaultSetup.referenceFee); + BEAST_EXPECT(setup.accountReserve == static_cast(-1234567)); + BEAST_EXPECT(setup.ownerReserve == static_cast(-1234)); } { auto const big64 = std::to_string( @@ -256,9 +256,9 @@ class FeeVote_test : public beast::unit_test::Suite "owner_reserve = " + big64}); // Illegal values are ignored, and the defaults left unchanged auto setup = setupFeeVote(config); - BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); - BEAST_EXPECT(setup.account_reserve == defaultSetup.account_reserve); - BEAST_EXPECT(setup.owner_reserve == defaultSetup.owner_reserve); + BEAST_EXPECT(setup.referenceFee == defaultSetup.referenceFee); + BEAST_EXPECT(setup.accountReserve == defaultSetup.accountReserve); + BEAST_EXPECT(setup.ownerReserve == defaultSetup.ownerReserve); } } @@ -273,7 +273,7 @@ class FeeVote_test : public beast::unit_test::Suite auto ledger = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -303,7 +303,7 @@ class FeeVote_test : public beast::unit_test::Suite auto ledger = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -336,7 +336,7 @@ class FeeVote_test : public beast::unit_test::Suite auto ledger = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -358,7 +358,7 @@ class FeeVote_test : public beast::unit_test::Suite auto ledger = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -385,7 +385,7 @@ class FeeVote_test : public beast::unit_test::Suite auto ledger = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -424,7 +424,7 @@ class FeeVote_test : public beast::unit_test::Suite auto ledger = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -472,7 +472,7 @@ class FeeVote_test : public beast::unit_test::Suite auto ledger = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -503,7 +503,7 @@ class FeeVote_test : public beast::unit_test::Suite auto ledger = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -549,7 +549,7 @@ class FeeVote_test : public beast::unit_test::Suite auto ledger = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -578,9 +578,9 @@ class FeeVote_test : public beast::unit_test::Suite using namespace jtx; FeeSetup setup; - setup.reference_fee = 42; - setup.account_reserve = 1234567; - setup.owner_reserve = 7654321; + setup.referenceFee = 42; + setup.accountReserve = 1234567; + setup.ownerReserve = 7654321; // Test with XRPFees enabled { @@ -590,7 +590,7 @@ class FeeVote_test : public beast::unit_test::Suite auto ledger = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -609,7 +609,7 @@ class FeeVote_test : public beast::unit_test::Suite feeVote->doValidation(currentFees, ledger->rules(), *val); BEAST_EXPECT(val->isFieldPresent(sfBaseFeeDrops)); - BEAST_EXPECT(val->getFieldAmount(sfBaseFeeDrops) == XRPAmount(setup.reference_fee)); + BEAST_EXPECT(val->getFieldAmount(sfBaseFeeDrops) == XRPAmount(setup.referenceFee)); } // Test with XRPFees disabled (legacy format) @@ -620,7 +620,7 @@ class FeeVote_test : public beast::unit_test::Suite auto ledger = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -638,7 +638,7 @@ class FeeVote_test : public beast::unit_test::Suite // In legacy mode, should vote using legacy fields BEAST_EXPECT(val->isFieldPresent(sfBaseFee)); - BEAST_EXPECT(val->getFieldU64(sfBaseFee) == setup.reference_fee); + BEAST_EXPECT(val->getFieldU64(sfBaseFee) == setup.referenceFee); } } @@ -650,9 +650,9 @@ class FeeVote_test : public beast::unit_test::Suite using namespace jtx; FeeSetup setup; - setup.reference_fee = 42; - setup.account_reserve = 1234567; - setup.owner_reserve = 7654321; + setup.referenceFee = 42; + setup.accountReserve = 1234567; + setup.ownerReserve = 7654321; Env env(*this, testableAmendments() | featureXRPFees); @@ -665,7 +665,7 @@ class FeeVote_test : public beast::unit_test::Suite auto ledger = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -689,9 +689,9 @@ class FeeVote_test : public beast::unit_test::Suite env.app().getTimeKeeper().now(), pub, sec, calcNodeID(pub), [&](STValidation& v) { v.setFieldU32(sfLedgerSequence, ledger->seq()); // Vote for different fees than current - v.setFieldAmount(sfBaseFeeDrops, XRPAmount{setup.reference_fee}); - v.setFieldAmount(sfReserveBaseDrops, XRPAmount{setup.account_reserve}); - v.setFieldAmount(sfReserveIncrementDrops, XRPAmount{setup.owner_reserve}); + v.setFieldAmount(sfBaseFeeDrops, XRPAmount{setup.referenceFee}); + v.setFieldAmount(sfReserveBaseDrops, XRPAmount{setup.accountReserve}); + v.setFieldAmount(sfReserveIncrementDrops, XRPAmount{setup.ownerReserve}); }); if ((i % 2) != 0) val->setTrusted(); @@ -723,10 +723,10 @@ class FeeVote_test : public beast::unit_test::Suite BEAST_EXPECT(!feeTx.isFieldPresent(sfReferenceFeeUnits)); // Check the values - BEAST_EXPECT(feeTx.getFieldAmount(sfBaseFeeDrops) == XRPAmount{setup.reference_fee}); - BEAST_EXPECT(feeTx.getFieldAmount(sfReserveBaseDrops) == XRPAmount{setup.account_reserve}); + BEAST_EXPECT(feeTx.getFieldAmount(sfBaseFeeDrops) == XRPAmount{setup.referenceFee}); + BEAST_EXPECT(feeTx.getFieldAmount(sfReserveBaseDrops) == XRPAmount{setup.accountReserve}); BEAST_EXPECT( - feeTx.getFieldAmount(sfReserveIncrementDrops) == XRPAmount{setup.owner_reserve}); + feeTx.getFieldAmount(sfReserveIncrementDrops) == XRPAmount{setup.ownerReserve}); } void diff --git a/src/test/app/LedgerHistory_test.cpp b/src/test/app/LedgerHistory_test.cpp index e464962258..3d0e546678 100644 --- a/src/test/app/LedgerHistory_test.cpp +++ b/src/test/app/LedgerHistory_test.cpp @@ -50,7 +50,7 @@ public: return std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); } diff --git a/src/test/app/LedgerLoad_test.cpp b/src/test/app/LedgerLoad_test.cpp index fa2c8f9047..ee3bfe5192 100644 --- a/src/test/app/LedgerLoad_test.cpp +++ b/src/test/app/LedgerLoad_test.cpp @@ -40,9 +40,9 @@ class LedgerLoad_test : public beast::unit_test::Suite StartUpType type, std::optional trapTxHash) { - cfg->START_LEDGER = ledger; - cfg->START_UP = type; - cfg->TRAP_TX_HASH = trapTxHash; + cfg->startLedger = ledger; + cfg->startUp = type; + cfg->trapTxHash = trapTxHash; assert(!dbPath.empty()); cfg->legacy("database_path", dbPath); return cfg; diff --git a/src/test/app/LedgerMaster_test.cpp b/src/test/app/LedgerMaster_test.cpp index ee14a93d07..3cf9b3a9d9 100644 --- a/src/test/app/LedgerMaster_test.cpp +++ b/src/test/app/LedgerMaster_test.cpp @@ -27,9 +27,9 @@ class LedgerMaster_test : public beast::unit_test::Suite { using namespace jtx; return envconfig([&](std::unique_ptr cfg) { - cfg->NETWORK_ID = networkID; + cfg->networkId = networkID; // This test relies on ledger hash so must lock it to fee 10. - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; return cfg; }); } diff --git a/src/test/app/LedgerReplay_test.cpp b/src/test/app/LedgerReplay_test.cpp index 4b1e4510d6..1978d04fe1 100644 --- a/src/test/app/LedgerReplay_test.cpp +++ b/src/test/app/LedgerReplay_test.cpp @@ -1062,7 +1062,7 @@ struct LedgerReplayer_test : public beast::unit_test::Suite testcase("config test"); { Config const c; - BEAST_EXPECT(c.LEDGER_REPLAY == false); + BEAST_EXPECT(c.ledgerReplay == false); } { @@ -1072,7 +1072,7 @@ struct LedgerReplayer_test : public beast::unit_test::Suite 1 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.LEDGER_REPLAY == true); + BEAST_EXPECT(c.ledgerReplay == true); } { @@ -1082,7 +1082,7 @@ struct LedgerReplayer_test : public beast::unit_test::Suite 0 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.LEDGER_REPLAY == false); + BEAST_EXPECT(c.ledgerReplay == false); } } @@ -1101,7 +1101,7 @@ struct LedgerReplayer_test : public beast::unit_test::Suite beast::IP::Address const addr = boost::asio::ip::make_address("172.1.1.100"); jtx::Env serverEnv(*this); - serverEnv.app().config().LEDGER_REPLAY = server; + serverEnv.app().config().ledgerReplay = server; auto httpResp = xrpl::makeResponse( true, httpRequest, addr, addr, uint256{1}, 1, {1, 0}, serverEnv.app()); auto const clientResult = peerFeatureEnabled(httpResp, kFeatureLedgerReplay, client); diff --git a/src/test/app/LoadFeeTrack_test.cpp b/src/test/app/LoadFeeTrack_test.cpp index 528e90321b..aba0b35062 100644 --- a/src/test/app/LoadFeeTrack_test.cpp +++ b/src/test/app/LoadFeeTrack_test.cpp @@ -17,7 +17,7 @@ public: { Fees const fees = [&]() { Fees f; - f.base = d.FEES.reference_fee; + f.base = d.fees.referenceFee; f.reserve = 200 * kDropsPerXrp; f.increment = 50 * kDropsPerXrp; return f; @@ -30,7 +30,7 @@ public: { Fees const fees = [&]() { Fees f; - f.base = d.FEES.reference_fee * 10; + f.base = d.fees.referenceFee * 10; f.reserve = 200 * kDropsPerXrp; f.increment = 50 * kDropsPerXrp; return f; @@ -43,7 +43,7 @@ public: { Fees const fees = [&]() { Fees f; - f.base = d.FEES.reference_fee; + f.base = d.fees.referenceFee; f.reserve = 200 * kDropsPerXrp; f.increment = 50 * kDropsPerXrp; return f; diff --git a/src/test/app/MPToken_test.cpp b/src/test/app/MPToken_test.cpp index 0e48db6080..74bdc656df 100644 --- a/src/test/app/MPToken_test.cpp +++ b/src/test/app/MPToken_test.cpp @@ -2125,7 +2125,7 @@ class MPToken_test : public beast::unit_test::Suite Account const alice{"alice"}; auto cfg = envconfig(); - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; Env env{*this, std::move(cfg), features}; MPTTester mptAlice(env, alice); diff --git a/src/test/app/NetworkID_test.cpp b/src/test/app/NetworkID_test.cpp index a98fbd6b4f..677d8f166d 100644 --- a/src/test/app/NetworkID_test.cpp +++ b/src/test/app/NetworkID_test.cpp @@ -37,7 +37,7 @@ public: { using namespace jtx; return envconfig([&](std::unique_ptr cfg) { - cfg->NETWORK_ID = networkID; + cfg->networkId = networkID; return cfg; }); } diff --git a/src/test/app/PathMPT_test.cpp b/src/test/app/PathMPT_test.cpp index da5597cf05..3ba67b58a6 100644 --- a/src/test/app/PathMPT_test.cpp +++ b/src/test/app/PathMPT_test.cpp @@ -87,9 +87,9 @@ class PathMPT_test : public beast::unit_test::Suite // with the search parameters that the tests were written for. using namespace jtx; return Env(*this, envconfig([](std::unique_ptr cfg) { - cfg->PATH_SEARCH_OLD = 7; - cfg->PATH_SEARCH = 7; - cfg->PATH_SEARCH_MAX = 10; + cfg->pathSearchOld = 7; + cfg->pathSearch = 7; + cfg->pathSearchMax = 10; return cfg; })); } diff --git a/src/test/app/Path_test.cpp b/src/test/app/Path_test.cpp index 1cf8131206..4cfe938798 100644 --- a/src/test/app/Path_test.cpp +++ b/src/test/app/Path_test.cpp @@ -101,9 +101,9 @@ class Path_test : public beast::unit_test::Suite // with the search parameters that the tests were written for. using namespace jtx; return Env(*this, envconfig([](std::unique_ptr cfg) { - cfg->PATH_SEARCH_OLD = 7; - cfg->PATH_SEARCH = 7; - cfg->PATH_SEARCH_MAX = 10; + cfg->pathSearchOld = 7; + cfg->pathSearch = 7; + cfg->pathSearchMax = 10; return cfg; })); } diff --git a/src/test/app/RCLValidations_test.cpp b/src/test/app/RCLValidations_test.cpp index df8e873c75..c3b0ddea9c 100644 --- a/src/test/app/RCLValidations_test.cpp +++ b/src/test/app/RCLValidations_test.cpp @@ -71,7 +71,7 @@ class RCLValidations_test : public beast::unit_test::Suite auto prev = std::make_shared( kCreateGenesis, Rules{config.features}, - config.FEES.toFees(), + config.fees.toFees(), std::vector{}, env.app().getNodeFamily()); history.push_back(prev); @@ -237,7 +237,7 @@ class RCLValidations_test : public beast::unit_test::Suite auto prev = std::make_shared( kCreateGenesis, Rules{config.features}, - config.FEES.toFees(), + config.fees.toFees(), std::vector{}, env.app().getNodeFamily()); history.push_back(prev); diff --git a/src/test/app/Regression_test.cpp b/src/test/app/Regression_test.cpp index ee3e25e2f4..1c83e97e61 100644 --- a/src/test/app/Regression_test.cpp +++ b/src/test/app/Regression_test.cpp @@ -87,7 +87,7 @@ struct Regression_test : public beast::unit_test::Suite auto closed = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); auto expectedDrops = kInitialXrp; @@ -194,7 +194,7 @@ struct Regression_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->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; return cfg; })); EnvSs envs(env); diff --git a/src/test/app/SHAMapStore_test.cpp b/src/test/app/SHAMapStore_test.cpp index f03fabd92c..fc5ef02465 100644 --- a/src/test/app/SHAMapStore_test.cpp +++ b/src/test/app/SHAMapStore_test.cpp @@ -41,7 +41,7 @@ class SHAMapStore_test : public beast::unit_test::Suite static auto onlineDelete(std::unique_ptr cfg) { - cfg->LEDGER_HISTORY = kDeleteInterval; + cfg->ledgerHistory = kDeleteInterval; auto& section = cfg->section(ConfigSection::nodeDatabase()); section.set("online_delete", std::to_string(kDeleteInterval)); return cfg; diff --git a/src/test/app/Transaction_ordering_test.cpp b/src/test/app/Transaction_ordering_test.cpp index 6672b3f834..7c0721cde3 100644 --- a/src/test/app/Transaction_ordering_test.cpp +++ b/src/test/app/Transaction_ordering_test.cpp @@ -64,7 +64,7 @@ struct Transaction_ordering_test : public beast::unit_test::Suite testcase("Incorrect order"); Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->FORCE_MULTI_THREAD = false; + cfg->forceMultiThread = false; return cfg; })); @@ -102,7 +102,7 @@ struct Transaction_ordering_test : public beast::unit_test::Suite testcase("Incorrect order multiple intermediaries"); Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->FORCE_MULTI_THREAD = true; + cfg->forceMultiThread = true; return cfg; })); diff --git a/src/test/app/TxQ_test.cpp b/src/test/app/TxQ_test.cpp index d8882cf346..8333fce3b3 100644 --- a/src/test/app/TxQ_test.cpp +++ b/src/test/app/TxQ_test.cpp @@ -1259,7 +1259,7 @@ public: testcase("tie breaking"); auto cfg = makeConfig({{"minimum_txn_in_ledger_standalone", "4"}}); - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; Env env(*this, std::move(cfg)); auto alice = Account("alice"); @@ -2653,7 +2653,7 @@ public: {{"minimum_txn_in_ledger_standalone", "1"}, {"ledgers_in_queue", "10"}, {"maximum_txn_per_account", "11"}}); - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; Env env(*this, std::move(cfg)); auto const baseFee = env.current()->fees().base.drops(); @@ -4069,9 +4069,9 @@ public: {{"account_reserve", "1000"}, {"owner_reserve", "50"}}); auto& votingSection = cfg->section("voting"); - votingSection.set("account_reserve", std::to_string(cfg->FEES.reference_fee.drops() * 100)); + votingSection.set("account_reserve", std::to_string(cfg->fees.referenceFee.drops() * 100)); - votingSection.set("reference_fee", std::to_string(cfg->FEES.reference_fee.drops())); + votingSection.set("reference_fee", std::to_string(cfg->fees.referenceFee.drops())); Env env(*this, std::move(cfg)); diff --git a/src/test/app/ValidatorList_test.cpp b/src/test/app/ValidatorList_test.cpp index 1b66dd305d..20a3557db5 100644 --- a/src/test/app/ValidatorList_test.cpp +++ b/src/test/app/ValidatorList_test.cpp @@ -2257,7 +2257,7 @@ private: auto extractProtocolMessage1 = [this, &extractHeader](Message& message) { auto [header, buffers] = extractHeader(message); if (BEAST_EXPECT(header) && - BEAST_EXPECT(header->message_type == protocol::mtVALIDATOR_LIST)) + BEAST_EXPECT(header->messageType == protocol::mtVALIDATOR_LIST)) { auto const msg = detail::parseMessageContent(*header, buffers.data()); @@ -2269,7 +2269,7 @@ private: auto extractProtocolMessage2 = [this, &extractHeader](Message& message) { auto [header, buffers] = extractHeader(message); if (BEAST_EXPECT(header) && - BEAST_EXPECT(header->message_type == protocol::mtVALIDATOR_LIST_COLLECTION)) + BEAST_EXPECT(header->messageType == protocol::mtVALIDATOR_LIST_COLLECTION)) { auto const msg = detail::parseMessageContent( *header, buffers.data()); diff --git a/src/test/app/XChain_test.cpp b/src/test/app/XChain_test.cpp index 6266d5870d..0198a36e96 100644 --- a/src/test/app/XChain_test.cpp +++ b/src/test/app/XChain_test.cpp @@ -266,8 +266,8 @@ struct BalanceTransfer balance from; balance to; - balance payer; // pays the rewards - std::vector reward_accounts; // receives the reward + balance payer; // pays the rewards + std::vector rewardAccounts; // receives the reward XRPAmount txFees; BalanceTransfer( @@ -281,7 +281,7 @@ struct BalanceTransfer : from(env, fromAcct) , to(env, toAcct) , payer(env, payer) - , reward_accounts([&]() { + , rewardAccounts([&]() { std::vector r; r.reserve(numPayees); for (size_t i = 0; i < numPayees; ++i) @@ -306,7 +306,7 @@ struct BalanceTransfer [[nodiscard]] bool payeesReceived(STAmount const& reward) const { - return std::all_of(reward_accounts.begin(), reward_accounts.end(), [&](balance const& b) { + return std::all_of(rewardAccounts.begin(), rewardAccounts.end(), [&](balance const& b) { return b.diff() == reward; }); } @@ -320,7 +320,7 @@ struct BalanceTransfer bool hasHappened(STAmount const& amt, STAmount const& reward, bool checkPayer = true) { - auto rewardCost = multiply(reward, STAmount(reward_accounts.size()), reward.asset()); + auto rewardCost = multiply(reward, STAmount(rewardAccounts.size()), reward.asset()); return checkMostBalances(amt, reward) && (!checkPayer || payer.diff() == -(rewardCost + txFees)); } @@ -1007,7 +1007,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj scEnv.tx(xchainClaim(scAlice, jvb, claimID, amt, scBob)).close(); } - BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum)); + BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum)); } // Check that the reward paid from a claim Id was the reward when @@ -1059,7 +1059,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // make sure the reward accounts indeed received the original // split reward (1 split 5 ways) instead of the updated 2 XRP. - BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum)); + BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum)); } // Check that the signatures used to verify attestations and decide @@ -1086,7 +1086,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // change signers - claim should not be processed is the batch // is signed by original signers - scEnv.tx(jtx::signers(Account::kMaster, quorum, alt_signers)).close(); + scEnv.tx(jtx::signers(Account::kMaster, quorum, altSigners)).close(); BalanceTransfer transfer( scEnv, @@ -1120,7 +1120,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // submit claim using current signers - should succeed scEnv .multiTx(claimAttestations( - scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, alt_signers)) + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, altSigners)) .close(); if (withClaim) { @@ -1132,7 +1132,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // make sure the transfer went through as we sent attestations // using new signers - BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum, false)); + BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum, false)); } // coverage test: bridge_modify transaction with incorrect flag @@ -1220,7 +1220,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // Creating the new object would put the account below the reserve XEnv(*this, true) .tx(createBridge(Account::kMaster, jvb)) - .fund(res1 - xrp_dust, scuAlice) // barely not enough + .fund(res1 - xrpDust, scuAlice) // barely not enough .close() .tx(xchainCreateClaimId(scuAlice, jvb, reward, mcAlice), Ter(tecINSUFFICIENT_RESERVE)) .close(); @@ -1231,7 +1231,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj XEnv(*this, true) .tx(createBridge(Account::kMaster, jvb)) .close() - .tx(xchainCreateClaimId(scAlice, jvb, split_reward_quorum, mcAlice), + .tx(xchainCreateClaimId(scAlice, jvb, splitRewardQuorum, mcAlice), Ter(tecXCHAIN_REWARD_MISMATCH)) .close(); @@ -1273,7 +1273,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj testcase("Commit"); // Commit to a non-existent bridge - XEnv(*this).tx(xchainCommit(mcAlice, jvb, 1, one_xrp, scBob), Ter(tecNO_ENTRY)); + XEnv(*this).tx(xchainCommit(mcAlice, jvb, 1, oneXrp, scBob), Ter(tecNO_ENTRY)); // check that reward not deducted when doing the commit { @@ -1309,17 +1309,17 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // reserve (if XRP) XEnv(*this) .tx(createBridge(mcDoor, jvb)) - .fund(res0 + one_xrp - xrp_dust, mcuAlice) // barely not enough + .fund(res0 + oneXrp - xrpDust, mcuAlice) // barely not enough .close() - .tx(xchainCommit(mcuAlice, jvb, 1, one_xrp, scBob), Ter(tecUNFUNDED_PAYMENT)); + .tx(xchainCommit(mcuAlice, jvb, 1, oneXrp, scBob), Ter(tecUNFUNDED_PAYMENT)); XEnv(*this) .tx(createBridge(mcDoor, jvb)) .fund( - res0 + one_xrp + xrp_dust, // "xrp_dust" for tx fees - mcuAlice) // exactly enough => should succeed + res0 + oneXrp + xrpDust, // "xrp_dust" for tx fees + mcuAlice) // exactly enough => should succeed .close() - .tx(xchainCommit(mcuAlice, jvb, 1, one_xrp, scBob)); + .tx(xchainCommit(mcuAlice, jvb, 1, oneXrp, scBob)); // Commit an amount above the account's balance (for both XRP and // IOUs) @@ -1327,7 +1327,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj .tx(createBridge(mcDoor, jvb)) .fund(res0, mcuAlice) // barely not enough .close() - .tx(xchainCommit(mcuAlice, jvb, 1, res0 + one_xrp, scBob), Ter(tecUNFUNDED_PAYMENT)); + .tx(xchainCommit(mcuAlice, jvb, 1, res0 + oneXrp, scBob), Ter(tecUNFUNDED_PAYMENT)); auto jvbUsd = bridge(mcDoor, mcUSD, scGw, scUSD); @@ -1377,7 +1377,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj XEnv(*this) .tx(createBridge(mcDoor)) .close() - .tx(xchainCommit(mcAlice, jvb, 1, one_xrp, scBob), + .tx(xchainCommit(mcAlice, jvb, 1, oneXrp, scBob), Txflags(tfFillOrKill), Ter(temINVALID_FLAG)); @@ -1387,7 +1387,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj .tx(createBridge(mcDoor)) .disableFeature(featureXChainBridge) .close() - .tx(xchainCommit(mcAlice, jvb, 1, one_xrp, scBob), Ter(temDISABLED)); + .tx(xchainCommit(mcAlice, jvb, 1, oneXrp, scBob), Ter(temDISABLED)); } void @@ -1467,7 +1467,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj BEAST_EXPECT(scEnv.claimID(jvb) == claimID); } - BEAST_EXPECT(transfer.hasHappened(amt, split_reward_everyone)); + BEAST_EXPECT(transfer.hasHappened(amt, splitRewardEveryone)); } // Test that signature weights are correctly handled. Assign @@ -2208,12 +2208,12 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj std::uint32_t const claimID = 1; for (auto i = 0; i < kUtXchainDefaultNumSigners - 2; ++i) - scEnv.fund(amt, alt_signers[i].account); + scEnv.fund(amt, altSigners[i].account); mcEnv.tx(createBridge(mcDoor, jvb)).close(); scEnv.tx(createBridge(Account::kMaster, jvb)) - .tx(jtx::signers(Account::kMaster, quorum, alt_signers)) + .tx(jtx::signers(Account::kMaster, quorum, altSigners)) .close() .tx(xchainCreateClaimId(scAlice, jvb, reward, mcAlice)) .close(); @@ -2225,24 +2225,24 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj { // G1: master key auto att = claimAttestation( - scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, alt_signers[0]); + scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, altSigners[0]); scEnv.tx(att).close(); } { // G2: regular key // alt_signers[0] is the regular key of alt_signers[1] // There should be 2 attestations after the transaction - scEnv.tx(jtx::regkey(alt_signers[1].account, alt_signers[0].account)).close(); + scEnv.tx(jtx::regkey(altSigners[1].account, altSigners[0].account)).close(); auto att = claimAttestation( - scAttester, jvb, mcAlice, amt, payees[1], true, claimID, dst, alt_signers[0]); - att[sfAttestationSignerAccount.getJsonName()] = alt_signers[1].account.human(); + scAttester, jvb, mcAlice, amt, payees[1], true, claimID, dst, altSigners[0]); + att[sfAttestationSignerAccount.getJsonName()] = altSigners[1].account.human(); scEnv.tx(att).close(); } { // B3: public key and non-exist (unfunded) account mismatch // G3: public key and non-exist (unfunded) account match - auto const unfundedSigner1 = alt_signers[kUtXchainDefaultNumSigners - 1]; - auto const unfundedSigner2 = alt_signers[kUtXchainDefaultNumSigners - 2]; + auto const unfundedSigner1 = altSigners[kUtXchainDefaultNumSigners - 1]; + auto const unfundedSigner2 = altSigners[kUtXchainDefaultNumSigners - 2]; auto att = claimAttestation( scAttester, jvb, @@ -2261,7 +2261,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj { // B2: single item signer list std::vector tempSignerList = {signers[0]}; - scEnv.tx(jtx::signers(alt_signers[2].account, 1, tempSignerList)); + scEnv.tx(jtx::signers(altSigners[2].account, 1, tempSignerList)); auto att = claimAttestation( scAttester, jvb, @@ -2272,14 +2272,14 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj claimID, dst, tempSignerList.front()); - att[sfAttestationSignerAccount.getJsonName()] = alt_signers[2].account.human(); + att[sfAttestationSignerAccount.getJsonName()] = altSigners[2].account.human(); scEnv.tx(att, Ter(tecXCHAIN_BAD_PUBLIC_KEY_ACCOUNT_PAIR)).close(); } { // B1: disabled master key - scEnv.tx(fset(alt_signers[2].account, asfDisableMaster, 0)).close(); + scEnv.tx(fset(altSigners[2].account, asfDisableMaster, 0)).close(); auto att = claimAttestation( - scAttester, jvb, mcAlice, amt, payees[2], true, claimID, dst, alt_signers[2]); + scAttester, jvb, mcAlice, amt, payees[2], true, claimID, dst, altSigners[2]); scEnv.tx(att, Ter(tecXCHAIN_BAD_PUBLIC_KEY_ACCOUNT_PAIR)).close(); } { @@ -2292,11 +2292,11 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // --B5: missing sfAttestationSignerAccount field // Then submit the one with the field. Should reach quorum. auto att = claimAttestation( - scAttester, jvb, mcAlice, amt, payees[3], true, claimID, dst, alt_signers[3]); + scAttester, jvb, mcAlice, amt, payees[3], true, claimID, dst, altSigners[3]); att.removeMember(sfAttestationSignerAccount.getJsonName()); scEnv.tx(att, Ter(temMALFORMED)).close(); BEAST_EXPECT(dstStartBalance == scEnv.env.balance(dst)); - att[sfAttestationSignerAccount.getJsonName()] = alt_signers[3].account.human(); + att[sfAttestationSignerAccount.getJsonName()] = altSigners[3].account.human(); scEnv.tx(att).close(); BEAST_EXPECT(dstStartBalance + amt == scEnv.env.balance(dst)); } @@ -2431,7 +2431,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj scEnv.tx(xchainClaim(scAlice, jvb, claimID, amt, scBob)).close(); } - BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum)); + BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum)); } // Claim with just one attestation signed by the Master key @@ -2641,7 +2641,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj } else { - BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum)); + BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum)); } } @@ -3180,7 +3180,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // claim wrong amount scEnv - .tx(xchainClaim(scAlice, jvb, claimID, one_xrp, scBob), + .tx(xchainClaim(scAlice, jvb, claimID, oneXrp, scBob), Ter(tecXCHAIN_CLAIM_NO_QUORUM)) .close(); } @@ -3232,7 +3232,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj claimCost += fee; } - BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum)); + BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum)); BEAST_EXPECT(scAliceBal.diff() == -claimCost); // because reward % 4 == 0 } @@ -3244,12 +3244,12 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj XEnv mcEnv(*this); XEnv scEnv(*this, true); - mcEnv.tx(createBridge(mcDoor, jvb, tiny_reward)).close(); + mcEnv.tx(createBridge(mcDoor, jvb, tinyReward)).close(); - scEnv.tx(createBridge(Account::kMaster, jvb, tiny_reward)) + scEnv.tx(createBridge(Account::kMaster, jvb, tinyReward)) .tx(jtx::signers(Account::kMaster, quorum, signers)) .close() - .tx(xchainCreateClaimId(scAlice, jvb, tiny_reward, mcAlice)) + .tx(xchainCreateClaimId(scAlice, jvb, tinyReward, mcAlice)) .close(); auto dst(withClaim ? std::nullopt : std::optional{scBob}); @@ -3268,7 +3268,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj test::Balance const scAliceBal(scEnv, scAlice); scEnv.multiTx(claimAttestations( scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); - STAmount claimCost = tiny_reward; + STAmount claimCost = tinyReward; if (withClaim) { @@ -3279,8 +3279,8 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj claimCost += fee; } - BEAST_EXPECT(transfer.hasHappened(amt, tiny_reward_split)); - BEAST_EXPECT(scAliceBal.diff() == -(claimCost - tiny_reward_remainder)); + BEAST_EXPECT(transfer.hasHappened(amt, tinyRewardSplit)); + BEAST_EXPECT(scAliceBal.diff() == -(claimCost - tinyRewardRemainder)); } // If a reward distribution fails for one of the reward accounts @@ -3331,7 +3331,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // this also checks that only 3 * split_reward was deducted from // scAlice (the payer account), since we passed alt_payees to // BalanceTransfer - BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum)); + BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum)); } for (auto withClaim : {false, true}) @@ -3381,7 +3381,7 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // this also checks that only 3 * split_reward was deducted from // scAlice (the payer account), since we passed payees.size() - // 1 to BalanceTransfer - BEAST_EXPECT(transfer.hasHappened(amt, split_reward_quorum)); + BEAST_EXPECT(transfer.hasHappened(amt, splitRewardQuorum)); // and make sure the account with deposit auth received nothing BEAST_EXPECT(lastSigner.diff() == STAmount(0)); @@ -3578,17 +3578,17 @@ struct XChain_test : public beast::unit_test::Suite, public jtx::XChainBridgeObj // commit where the fee dips into the reserve, this should succeed XEnv(*this) .tx(createBridge(mcDoor, jvb)) - .fund(res0 + one_xrp + fee - drops(1), mcuAlice) + .fund(res0 + oneXrp + fee - drops(1), mcuAlice) .close() - .tx(xchainCommit(mcuAlice, jvb, 1, one_xrp, scBob), Ter(tesSUCCESS)); + .tx(xchainCommit(mcuAlice, jvb, 1, oneXrp, scBob), Ter(tesSUCCESS)); // commit where the commit amount drips into the reserve, this should // fail XEnv(*this) .tx(createBridge(mcDoor, jvb)) - .fund(res0 + one_xrp - drops(1), mcuAlice) + .fund(res0 + oneXrp - drops(1), mcuAlice) .close() - .tx(xchainCommit(mcuAlice, jvb, 1, one_xrp, scBob), Ter(tecUNFUNDED_PAYMENT)); + .tx(xchainCommit(mcuAlice, jvb, 1, oneXrp, scBob), Ter(tecUNFUNDED_PAYMENT)); auto const minAccountCreate = XRP(20); @@ -3757,8 +3757,8 @@ private: jtx::Account finaldest; STAmount amt; bool a2b; // direction of transfer - WithClaim with_claim{WithClaim::No}; - uint32_t claim_id{0}; + WithClaim withClaim{WithClaim::No}; + uint32_t claimId{0}; std::array attested{}; }; @@ -3769,7 +3769,7 @@ private: STAmount amt; STAmount reward; bool a2b; - uint32_t claim_id{0}; + uint32_t claimId{0}; std::array attested{}; }; @@ -3806,7 +3806,7 @@ private: using CreateClaimVec = jtx::JValueVec; using CreateClaimMap = std::map; - ChainStateTrack(ENV& env) : env(env), tx_fee(env.env.current()->fees().base) + ChainStateTrack(ENV& env) : env(env), txFee(env.env.current()->fees().base) { } @@ -3851,31 +3851,30 @@ private: { callbackCalled = false; // cspell: ignore attns - for (size_t i = 0; i < signers_attns.size(); ++i) + for (size_t i = 0; i < signersAttns.size(); ++i) { - for (auto& [bridge, claims] : signers_attns[i]) + for (auto& [bridge, claims] : signersAttns[i]) { - sendAttestations(i, bridge, claims.xfer_claims); + sendAttestations(i, bridge, claims.xferClaims); auto& c = counters[bridge]; - auto& createClaims = claims.create_claims[c.claim_count]; + auto& createClaims = claims.createClaims[c.claimCount]; auto numAttns = createClaims.size(); if (numAttns != 0u) { - c.num_create_attn_sent += - sendCreateAttestations(i, bridge, createClaims); + c.numCreateAttnSent += sendCreateAttestations(i, bridge, createClaims); } - assert(claims.create_claims[c.claim_count].empty()); + assert(claims.createClaims[c.claimCount].empty()); } } for (auto& [bridge, c] : counters) { - if (c.num_create_attn_sent >= bridge->quorum) + if (c.numCreateAttnSent >= bridge->quorum) { callbackCalled = true; - c.create_callbacks[c.claim_count](c.signers); - ++c.claim_count; - c.num_create_attn_sent = 0; + c.createCallbacks[c.claimCount](c.signers); + ++c.claimCount; + c.numCreateAttnSent = 0; c.signers.clear(); } } @@ -3926,7 +3925,7 @@ private: void spendFee(jtx::Account const& acct, size_t times = 1) { - spend(acct, tx_fee, times); + spend(acct, txFee, times); } [[nodiscard]] bool @@ -3944,20 +3943,20 @@ private: { using complete_cb = std::function const& signers)>; - uint32_t claim_id{0}; - uint32_t create_count{0}; // for account create. First should be 1 - uint32_t claim_count{0}; // for account create. Increments after quorum for - // current create_count (starts at 1) is reached. + uint32_t claimId{0}; + uint32_t createCount{0}; // for account create. First should be 1 + uint32_t claimCount{0}; // for account create. Increments after quorum for + // current createCount (starts at 1) is reached. - uint32_t num_create_attn_sent{0}; // for current claim_count + uint32_t numCreateAttnSent{0}; // for current claimCount std::vector signers; - std::vector create_callbacks; + std::vector createCallbacks; }; struct Claims { - ClaimVec xfer_claims; - CreateClaimMap create_claims; + ClaimVec xferClaims; + CreateClaimMap createClaims; }; using SignerAttns = std::unordered_map; @@ -3965,9 +3964,9 @@ private: ENV& env; std::map accounts; - SignersAttns signers_attns; + SignersAttns signersAttns; std::map counters; - STAmount tx_fee; + STAmount txFee; }; struct ChainStateTracker @@ -4086,7 +4085,7 @@ private: st.transfer(cr_.from, srcdoor, cr_.amt); st.transfer(cr_.from, srcdoor, cr_.reward); - return ++st.counters[&bridge_].create_count; + return ++st.counters[&bridge_].createCount; } void @@ -4105,9 +4104,8 @@ private: // enqueue one attestation for this signer cr_.attested[signerIdx] = true; - st.signers_attns[signerIdx][&bridge_] - .create_claims[cr_.claim_id - 1] - .emplace_back(createAccountAttestation( + st.signersAttns[signerIdx][&bridge_].createClaims[cr_.claimId - 1].emplace_back( + createAccountAttestation( bridge_.signers[signerIdx].account, bridge_.jvb, cr_.from, @@ -4115,7 +4113,7 @@ private: cr_.reward, bridge_.signers[signerIdx].account, cr_.a2b, - cr_.claim_id, + cr_.claimId, cr_.to, bridge_.signers[signerIdx])); break; @@ -4126,15 +4124,15 @@ private: return; // did not attest auto& counters = st.counters[&bridge_]; - if (counters.create_callbacks.size() < cr_.claim_id) - counters.create_callbacks.resize(cr_.claim_id); + if (counters.createCallbacks.size() < cr_.claimId) + counters.createCallbacks.resize(cr_.claimId); auto completeCb = [&](std::vector const& signers) { auto numAttestors = signers.size(); st.env.close(); assert(numAttestors <= std::count(cr_.attested.begin(), cr_.attested.end(), true)); assert(numAttestors >= bridge_.quorum); - assert(cr_.claim_id - 1 == counters.claim_count); + assert(cr_.claimId - 1 == counters.claimCount); auto r = cr_.reward; auto reward = divide(r, STAmount(numAttestors), r.asset()); @@ -4145,20 +4143,20 @@ private: st.spend(dstDoor(), reward, numAttestors); st.transfer(dstDoor(), cr_.to, cr_.amt); st.env.env.memoize(cr_.to); - sm_state_ = SmState::Completed; + smState_ = SmState::Completed; }; - counters.create_callbacks[cr_.claim_id - 1] = std::move(completeCb); + counters.createCallbacks[cr_.claimId - 1] = std::move(completeCb); } SmState advance(uint64_t time, uint32_t rnd) { - switch (sm_state_) + switch (smState_) { case SmState::Initial: - cr_.claim_id = issueAccountCreate(); - sm_state_ = SmState::Attesting; + cr_.claimId = issueAccountCreate(); + smState_ = SmState::Attesting; break; case SmState::Attesting: @@ -4172,11 +4170,11 @@ private: case SmState::Completed: break; // will get this once } - return sm_state_; + return smState_; } private: - SmState sm_state_{SmState::Initial}; + SmState smState_{SmState::Initial}; AccountCreate cr_; }; @@ -4209,7 +4207,7 @@ private: .close(); // needed for claim_id sequence to be // correct' st.spendFee(xfer_.to); - return ++st.counters[&bridge_].claim_id; + return ++st.counters[&bridge_].claimId; } void @@ -4226,10 +4224,10 @@ private: st.env.tx(xchainCommit( xfer_.from, bridge_.jvb, - xfer_.claim_id, + xfer_.claimId, xfer_.amt, - xfer_.with_claim == WithClaim::Yes ? std::nullopt - : std::optional(xfer_.finaldest))); + xfer_.withClaim == WithClaim::Yes ? std::nullopt + : std::optional(xfer_.finaldest))); st.spendFee(xfer_.from); st.transfer(xfer_.from, srcdoor, xfer_.amt); } @@ -4262,15 +4260,15 @@ private: // enqueue one attestation for this signer xfer_.attested[signerIdx] = true; - st.signers_attns[signerIdx][&bridge_].xfer_claims.emplace_back(claimAttestation( + st.signersAttns[signerIdx][&bridge_].xferClaims.emplace_back(claimAttestation( bridge_.signers[signerIdx].account, bridge_.jvb, xfer_.from, xfer_.amt, bridge_.signers[signerIdx].account, xfer_.a2b, - xfer_.claim_id, - xfer_.with_claim == WithClaim::Yes + xfer_.claimId, + xfer_.withClaim == WithClaim::Yes ? std::nullopt : std::optional(xfer_.finaldest), bridge_.signers[signerIdx])); @@ -4281,7 +4279,7 @@ private: // return true if quorum was reached, false otherwise bool const quorum = std::count(xfer_.attested.begin(), xfer_.attested.end(), true) >= bridge_.quorum; - if (quorum && xfer_.with_claim == WithClaim::No) + if (quorum && xfer_.withClaim == WithClaim::No) { distributeReward(st); st.transfer(dstDoor(), xfer_.finaldest, xfer_.amt); @@ -4294,7 +4292,7 @@ private: { ChainStateTrack& st = destState(); st.env.tx( - xchainClaim(xfer_.to, bridge_.jvb, xfer_.claim_id, xfer_.amt, xfer_.finaldest)); + xchainClaim(xfer_.to, bridge_.jvb, xfer_.claimId, xfer_.amt, xfer_.finaldest)); distributeReward(st); st.transfer(dstDoor(), xfer_.finaldest, xfer_.amt); st.spendFee(xfer_.to); @@ -4303,34 +4301,34 @@ private: SmState advance(uint64_t time, uint32_t rnd) { - switch (sm_state_) + switch (smState_) { case SmState::Initial: - xfer_.claim_id = createClaimId(); - sm_state_ = SmState::ClaimIdCreated; + xfer_.claimId = createClaimId(); + smState_ = SmState::ClaimIdCreated; break; case SmState::ClaimIdCreated: commit(); - sm_state_ = SmState::Attesting; + smState_ = SmState::Attesting; break; case SmState::Attesting: if (attest(time, rnd)) { - sm_state_ = xfer_.with_claim == WithClaim::Yes ? SmState::Attested - : SmState::Completed; + smState_ = xfer_.withClaim == WithClaim::Yes ? SmState::Attested + : SmState::Completed; } else { - sm_state_ = SmState::Attesting; + smState_ = SmState::Attesting; } break; case SmState::Attested: - assert(xfer_.with_claim == WithClaim::Yes); + assert(xfer_.withClaim == WithClaim::Yes); claim(); - sm_state_ = SmState::Completed; + smState_ = SmState::Completed; break; default: @@ -4338,12 +4336,12 @@ private: assert(0); // should have been removed break; } - return sm_state_; + return smState_; } private: Transfer xfer_; - SmState sm_state_{SmState::Initial}; + SmState smState_{SmState::Initial}; }; // -------------------------------------------------- @@ -4573,7 +4571,7 @@ public: .finaldest = a[1], .amt = XRP(6), .a2b = true, - .with_claim = WithClaim::No}); + .withClaim = WithClaim::No}); xfer( 1, st, @@ -4583,7 +4581,7 @@ public: .finaldest = a[1], .amt = XRP(8), .a2b = false, - .with_claim = WithClaim::No}); + .withClaim = WithClaim::No}); xfer( 1, st, xrpB, {.from = a[1], .to = a[1], .finaldest = a[1], .amt = XRP(1), .a2b = true}); xfer( @@ -4605,7 +4603,7 @@ public: .finaldest = a[1], .amt = XRP(7), .a2b = false, - .with_claim = WithClaim::No}); + .withClaim = WithClaim::No}); xfer( 2, st, xrpB, {.from = a[1], .to = a[1], .finaldest = a[1], .amt = XRP(9), .a2b = true}); runSimulation(st); diff --git a/src/test/consensus/Consensus_test.cpp b/src/test/consensus/Consensus_test.cpp index b8fed1d981..6cc8d4fde1 100644 --- a/src/test/consensus/Consensus_test.cpp +++ b/src/test/consensus/Consensus_test.cpp @@ -453,7 +453,7 @@ public: // Vary the time it takes to process validations to exercise detecting // the wrong LCL at different phases of consensus - for (auto validationDelay : {0ms, parms.ledgerMIN_CLOSE}) + for (auto validationDelay : {0ms, parms.ledgerMinClose}) { // Consider 10 peers: // 0 1 2 3 4 5 6 7 8 9 @@ -492,7 +492,7 @@ public: CollectByNode jumps; sim.collectors.add(jumps); - BEAST_EXPECT(sim.trustGraph.canFork(parms.minCONSENSUS_PCT / 100.)); + BEAST_EXPECT(sim.trustGraph.canFork(parms.minConsensusPct / 100.)); // initial round to set prior state sim.run(1); diff --git a/src/test/consensus/NegativeUNL_test.cpp b/src/test/consensus/NegativeUNL_test.cpp index 05dc3f0e2f..142077a42f 100644 --- a/src/test/consensus/NegativeUNL_test.cpp +++ b/src/test/consensus/NegativeUNL_test.cpp @@ -239,7 +239,7 @@ class NegativeUNL_test : public beast::unit_test::Suite auto l = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -554,12 +554,12 @@ struct NetworkHistory createNodes() { assert(param.numNodes <= 256); - UNLKeys = createPublicKeys(param.numNodes); + unlKeys = createPublicKeys(param.numNodes); for (int i = 0; i < param.numNodes; ++i) { - UNLKeySet.insert(UNLKeys[i]); - UNLNodeIDs.push_back(calcNodeID(UNLKeys[i])); - UNLNodeIDSet.insert(UNLNodeIDs.back()); + unlKeySet.insert(unlKeys[i]); + unlNodeIDs.push_back(calcNodeID(unlKeys[i])); + unlNodeIdSet.insert(unlNodeIDs.back()); } } @@ -574,7 +574,7 @@ struct NetworkHistory auto l = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{kFakeAmendment++}, env.app().getNodeFamily()); history.push_back(l); @@ -593,7 +593,7 @@ struct NetworkHistory OpenView accum(&*l); if (l->negativeUNL().size() < param.negUNLSize) { - auto tx = createTx(true, l->seq(), UNLKeys[nidx]); + auto tx = createTx(true, l->seq(), unlKeys[nidx]); if (!applyAndTestResult(env, accum, tx, true)) break; ++nidx; @@ -602,14 +602,14 @@ struct NetworkHistory { if (param.hasToDisable) { - auto tx = createTx(true, l->seq(), UNLKeys[nidx]); + auto tx = createTx(true, l->seq(), unlKeys[nidx]); if (!applyAndTestResult(env, accum, tx, true)) break; ++nidx; } if (param.hasToReEnable) { - auto tx = createTx(false, l->seq(), UNLKeys[0]); + auto tx = createTx(false, l->seq(), unlKeys[0]); if (!applyAndTestResult(env, accum, tx, true)) break; } @@ -665,9 +665,9 @@ struct NetworkHistory { if (needVal(history[curr], i)) { - RCLValidation v(createSTVal(history[curr], UNLNodeIDs[i])); + RCLValidation v(createSTVal(history[curr], unlNodeIDs[i])); v.setTrusted(); - validations.add(UNLNodeIDs[i], v); + validations.add(unlNodeIDs[i], v); } } } @@ -682,10 +682,10 @@ struct NetworkHistory jtx::Env env; Parameter param; RCLValidations& validations; - std::vector UNLKeys; - hash_set UNLKeySet; - std::vector UNLNodeIDs; - hash_set UNLNodeIDSet; + std::vector unlKeys; + hash_set unlKeySet; + std::vector unlNodeIDs; + hash_set unlNodeIdSet; LedgerHistory history; bool goodHistory; }; @@ -714,7 +714,7 @@ voteAndCheck( pre(vote); auto txSet = std::make_shared(SHAMapType::TRANSACTION, history.env.app().getNodeFamily()); - vote.doVoting(history.lastLedger(), history.UNLKeySet, history.validations, txSet); + vote.doVoting(history.lastLedger(), history.unlKeySet, history.validations, txSet); return countTx(txSet) == expect; } @@ -795,9 +795,9 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { - NegativeUNLVote vote(history.UNLNodeIDs[3], history.env.journal); + NegativeUNLVote vote(history.unlNodeIDs[3], history.env.journal); BEAST_EXPECT(!vote.buildScoreTable( - history.lastLedger(), history.UNLNodeIDSet, history.validations)); + history.lastLedger(), history.unlNodeIdSet, history.validations)); } } @@ -813,9 +813,9 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { - NegativeUNLVote vote(history.UNLNodeIDs[3], history.env.journal); + NegativeUNLVote vote(history.unlNodeIDs[3], history.env.journal); BEAST_EXPECT(!vote.buildScoreTable( - history.lastLedger(), history.UNLNodeIDSet, history.validations)); + history.lastLedger(), history.unlNodeIdSet, history.validations)); } } @@ -831,15 +831,15 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { - NodeID myId = history.UNLNodeIDs[3]; + NodeID myId = history.unlNodeIDs[3]; history.walkHistoryAndAddValidations( [&](std::shared_ptr const& l, std::size_t idx) -> bool { // skip half my validations. - return history.UNLNodeIDs[idx] != myId || l->seq() % 2 != 0; + return history.unlNodeIDs[idx] != myId || l->seq() % 2 != 0; }); NegativeUNLVote vote(myId, history.env.journal); BEAST_EXPECT(!vote.buildScoreTable( - history.lastLedger(), history.UNLNodeIDSet, history.validations)); + history.lastLedger(), history.unlNodeIdSet, history.validations)); } } @@ -864,12 +864,12 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite if (history.goodHistory && wrongChainSuccess) { - NodeID myId = history.UNLNodeIDs[3]; - NodeID const badNode = history.UNLNodeIDs[4]; + NodeID myId = history.unlNodeIDs[3]; + NodeID const badNode = history.unlNodeIDs[4]; history.walkHistoryAndAddValidations( [&](std::shared_ptr const& l, std::size_t idx) -> bool { // everyone but me - return !(history.UNLNodeIDs[idx] == myId); + return !(history.unlNodeIDs[idx] == myId); }); // local node validate wrong chain @@ -887,7 +887,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite // local node still on wrong chain, can build a scoreTable, // but all other nodes' scores are zero auto scoreTable = vote.buildScoreTable( - wrongChain.back(), history.UNLNodeIDSet, history.validations); + wrongChain.back(), history.unlNodeIdSet, history.validations); BEAST_EXPECT(scoreTable); if (scoreTable) { @@ -907,7 +907,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite // if local node switched to right history, but cannot build // scoreTable because not enough local validations BEAST_EXPECT(!vote.buildScoreTable( - history.lastLedger(), history.UNLNodeIDSet, history.validations)); + history.lastLedger(), history.unlNodeIdSet, history.validations)); } } @@ -927,9 +927,9 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); - NegativeUNLVote vote(history.UNLNodeIDs[3], history.env.journal); + NegativeUNLVote vote(history.unlNodeIDs[3], history.env.journal); auto scoreTable = vote.buildScoreTable( - history.lastLedger(), history.UNLNodeIDSet, history.validations); + history.lastLedger(), history.unlNodeIdSet, history.validations); BEAST_EXPECT(scoreTable); if (scoreTable) { @@ -1001,35 +1001,35 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite hash_set negUnl012; for (std::uint32_t i = 0; i < 3; ++i) - negUnl012.insert(history.UNLNodeIDs[i]); + negUnl012.insert(history.unlNodeIDs[i]); // build a good scoreTable to use, or copy and modify hash_map goodScoreTable; - for (auto const& n : history.UNLNodeIDs) + for (auto const& n : history.unlNodeIDs) goodScoreTable[n] = NegativeUNLVote::kNegativeUnlHighWaterMark + 1; - NegativeUNLVote vote(history.UNLNodeIDs[0], history.env.journal); + NegativeUNLVote vote(history.unlNodeIDs[0], history.env.journal); { // all good scores BEAST_EXPECT( - checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl012, goodScoreTable, 0, 3)); + checkCandidateSizes(vote, history.unlNodeIdSet, negUnl012, goodScoreTable, 0, 3)); } { // all bad scores hash_map scoreTable; - for (auto& n : history.UNLNodeIDs) + for (auto& n : history.unlNodeIDs) scoreTable[n] = NegativeUNLVote::kNegativeUnlLowWaterMark - 1; BEAST_EXPECT( - checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl012, scoreTable, 35 - 3, 0)); + checkCandidateSizes(vote, history.unlNodeIdSet, negUnl012, scoreTable, 35 - 3, 0)); } { // all between watermarks hash_map scoreTable; - for (auto& n : history.UNLNodeIDs) + for (auto& n : history.unlNodeIDs) scoreTable[n] = NegativeUNLVote::kNegativeUnlLowWaterMark + 1; BEAST_EXPECT( - checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl012, scoreTable, 0, 0)); + checkCandidateSizes(vote, history.unlNodeIdSet, negUnl012, scoreTable, 0, 0)); } { @@ -1037,36 +1037,36 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite auto scoreTable = goodScoreTable; scoreTable[*negUnl012.begin()] = NegativeUNLVote::kNegativeUnlLowWaterMark + 1; BEAST_EXPECT( - checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl012, scoreTable, 0, 2)); + checkCandidateSizes(vote, history.unlNodeIdSet, negUnl012, scoreTable, 0, 2)); } { // 2 bad scorers not in negUnl auto scoreTable = goodScoreTable; - scoreTable[history.UNLNodeIDs[11]] = NegativeUNLVote::kNegativeUnlLowWaterMark - 1; - scoreTable[history.UNLNodeIDs[12]] = NegativeUNLVote::kNegativeUnlLowWaterMark - 1; + scoreTable[history.unlNodeIDs[11]] = NegativeUNLVote::kNegativeUnlLowWaterMark - 1; + scoreTable[history.unlNodeIDs[12]] = NegativeUNLVote::kNegativeUnlLowWaterMark - 1; BEAST_EXPECT( - checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl012, scoreTable, 2, 3)); + checkCandidateSizes(vote, history.unlNodeIdSet, negUnl012, scoreTable, 2, 3)); } { // 2 in negUnl but not in unl, have a remove candidate from score // table - hash_set unlTemp = history.UNLNodeIDSet; - unlTemp.erase(history.UNLNodeIDs[0]); - unlTemp.erase(history.UNLNodeIDs[1]); + hash_set unlTemp = history.unlNodeIdSet; + unlTemp.erase(history.unlNodeIDs[0]); + unlTemp.erase(history.unlNodeIDs[1]); BEAST_EXPECT(checkCandidateSizes(vote, unlTemp, negUnl012, goodScoreTable, 0, 3)); } { // 2 in negUnl but not in unl, no remove candidate from score table auto scoreTable = goodScoreTable; - scoreTable.erase(history.UNLNodeIDs[0]); - scoreTable.erase(history.UNLNodeIDs[1]); - scoreTable[history.UNLNodeIDs[2]] = NegativeUNLVote::kNegativeUnlLowWaterMark + 1; - hash_set unlTemp = history.UNLNodeIDSet; - unlTemp.erase(history.UNLNodeIDs[0]); - unlTemp.erase(history.UNLNodeIDs[1]); + scoreTable.erase(history.unlNodeIDs[0]); + scoreTable.erase(history.unlNodeIDs[1]); + scoreTable[history.unlNodeIDs[2]] = NegativeUNLVote::kNegativeUnlLowWaterMark + 1; + hash_set unlTemp = history.unlNodeIdSet; + unlTemp.erase(history.unlNodeIDs[0]); + unlTemp.erase(history.unlNodeIDs[1]); BEAST_EXPECT(checkCandidateSizes(vote, unlTemp, negUnl012, scoreTable, 0, 2)); } @@ -1075,7 +1075,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::Suite NodeID const new1(0xbead); NodeID const new2(0xbeef); hash_set const nowTrusted = {new1, new2}; - hash_set unlTemp = history.UNLNodeIDSet; + hash_set unlTemp = history.unlNodeIdSet; unlTemp.insert(new1); unlTemp.insert(new2); vote.newValidators(256, nowTrusted); @@ -1381,7 +1381,7 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::Suite BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { - NodeID myId = history.UNLNodeIDs[3]; + NodeID myId = history.unlNodeIDs[3]; history.walkHistoryAndAddValidations( [&](std::shared_ptr const& l, std::size_t idx) -> bool { std::size_t k = 0; @@ -1400,19 +1400,19 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::Suite bool const add50 = scorePattern[sp][k] == 50 && l->seq() % 2 == 0; bool const add100 = scorePattern[sp][k] == 100; - bool const addMe = history.UNLNodeIDs[idx] == myId; + bool const addMe = history.unlNodeIDs[idx] == myId; return add50 || add100 || addMe; }); NegativeUNLVote vote(myId, history.env.journal); auto scoreTable = vote.buildScoreTable( - history.lastLedger(), history.UNLNodeIDSet, history.validations); + history.lastLedger(), history.unlNodeIdSet, history.validations); BEAST_EXPECT(scoreTable); if (scoreTable) { std::uint32_t i = 0; // looping unl auto checkScores = [&](std::uint32_t score, std::uint32_t k) -> bool { - if (history.UNLNodeIDs[i] == myId) + if (history.unlNodeIDs[i] == myId) return score == 256; if (scorePattern[sp][k] == 0) return score == 0; @@ -1427,15 +1427,15 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::Suite }; for (; i < 2; ++i) { - BEAST_EXPECT(checkScores((*scoreTable)[history.UNLNodeIDs[i]], 0)); + BEAST_EXPECT(checkScores((*scoreTable)[history.unlNodeIDs[i]], 0)); } for (; i < 4; ++i) { - BEAST_EXPECT(checkScores((*scoreTable)[history.UNLNodeIDs[i]], 1)); + BEAST_EXPECT(checkScores((*scoreTable)[history.unlNodeIDs[i]], 1)); } for (; i < unlSize; ++i) { - BEAST_EXPECT(checkScores((*scoreTable)[history.UNLNodeIDs[i]], 2)); + BEAST_EXPECT(checkScores((*scoreTable)[history.unlNodeIDs[i]], 2)); } } } @@ -1506,7 +1506,7 @@ class NegativeUNLVoteGoodScore_test : public beast::unit_test::Suite [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); - BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 0)); + BEAST_EXPECT(voteAndCheck(history, history.unlNodeIDs[0], 0)); } } @@ -1527,7 +1527,7 @@ class NegativeUNLVoteGoodScore_test : public beast::unit_test::Suite [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); - BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 1)); + BEAST_EXPECT(voteAndCheck(history, history.unlNodeIDs[0], 1)); } } } @@ -1564,7 +1564,7 @@ class NegativeUNLVoteOffline_test : public beast::unit_test::Suite // skip node 0 and node 1 return idx > 1; }); - BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs.back(), 1)); + BEAST_EXPECT(voteAndCheck(history, history.unlNodeIDs.back(), 1)); } } @@ -1587,9 +1587,9 @@ class NegativeUNLVoteOffline_test : public beast::unit_test::Suite history.walkHistoryAndAddValidations( [&](std::shared_ptr const& l, std::size_t idx) -> bool { // skip node 0 and node 1 - return history.UNLNodeIDs[idx] != n1 && history.UNLNodeIDs[idx] != n2; + return history.unlNodeIDs[idx] != n1 && history.unlNodeIDs[idx] != n2; }); - BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs.back(), 0)); + BEAST_EXPECT(voteAndCheck(history, history.unlNodeIDs.back(), 0)); } } } @@ -1626,7 +1626,7 @@ class NegativeUNLVoteMaxListed_test : public beast::unit_test::Suite // skip node 0 ~ 10 return idx > 10; }); - BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs.back(), 0)); + BEAST_EXPECT(voteAndCheck(history, history.unlNodeIDs.back(), 0)); } } } @@ -1662,7 +1662,7 @@ class NegativeUNLVoteRetiredValidator_test : public beast::unit_test::Suite [&](std::shared_ptr const& l, std::size_t idx) -> bool { return idx > 1; }); - BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 0)); + BEAST_EXPECT(voteAndCheck(history, history.unlNodeIDs[0], 0)); } } @@ -1705,9 +1705,9 @@ class NegativeUNLVoteRetiredValidator_test : public beast::unit_test::Suite return idx > 1; }); BEAST_EXPECT( - voteAndCheck(history, history.UNLNodeIDs.back(), 1, [&](NegativeUNLVote& vote) { - history.UNLKeySet.erase(history.UNLKeys[0]); - history.UNLKeySet.erase(history.UNLKeys[1]); + voteAndCheck(history, history.unlNodeIDs.back(), 1, [&](NegativeUNLVote& vote) { + history.unlKeySet.erase(history.unlKeys[0]); + history.unlKeySet.erase(history.unlKeys[1]); })); } } @@ -1745,11 +1745,11 @@ class NegativeUNLVoteNewValidator_test : public beast::unit_test::Suite return true; }); BEAST_EXPECT( - voteAndCheck(history, history.UNLNodeIDs[0], 0, [&](NegativeUNLVote& vote) { + voteAndCheck(history, history.unlNodeIDs[0], 0, [&](NegativeUNLVote& vote) { auto extraKey1 = randomKeyPair(KeyType::Ed25519).first; auto extraKey2 = randomKeyPair(KeyType::Ed25519).first; - history.UNLKeySet.insert(extraKey1); - history.UNLKeySet.insert(extraKey2); + history.unlKeySet.insert(extraKey1); + history.unlKeySet.insert(extraKey2); hash_set nowTrusted; nowTrusted.insert(calcNodeID(extraKey1)); nowTrusted.insert(calcNodeID(extraKey2)); @@ -1776,11 +1776,11 @@ class NegativeUNLVoteNewValidator_test : public beast::unit_test::Suite return true; }); BEAST_EXPECT( - voteAndCheck(history, history.UNLNodeIDs[0], 1, [&](NegativeUNLVote& vote) { + voteAndCheck(history, history.unlNodeIDs[0], 1, [&](NegativeUNLVote& vote) { auto extraKey1 = randomKeyPair(KeyType::Ed25519).first; auto extraKey2 = randomKeyPair(KeyType::Ed25519).first; - history.UNLKeySet.insert(extraKey1); - history.UNLKeySet.insert(extraKey2); + history.unlKeySet.insert(extraKey1); + history.unlKeySet.insert(extraKey2); hash_set nowTrusted; nowTrusted.insert(calcNodeID(extraKey1)); nowTrusted.insert(calcNodeID(extraKey2)); @@ -1807,7 +1807,7 @@ class NegativeUNLVoteFilterValidations_test : public beast::unit_test::Suite auto l = std::make_shared( kCreateGenesis, Rules{env.app().config().features}, - env.app().config().FEES.toFees(), + env.app().config().fees.toFees(), std::vector{}, env.app().getNodeFamily()); diff --git a/src/test/consensus/Validations_test.cpp b/src/test/consensus/Validations_test.cpp index fb453b0791..606c6f2824 100644 --- a/src/test/consensus/Validations_test.cpp +++ b/src/test/consensus/Validations_test.cpp @@ -324,15 +324,15 @@ class Validations_test : public beast::unit_test::Suite BEAST_EXPECT( ValStatus::Stale == - harness.add(n.validate(ledgerA, -harness.parms().validationCURRENT_EARLY, 0s))); + harness.add(n.validate(ledgerA, -harness.parms().validationCurrentEarly, 0s))); BEAST_EXPECT( ValStatus::Stale == - harness.add(n.validate(ledgerA, harness.parms().validationCURRENT_WALL, 0s))); + harness.add(n.validate(ledgerA, harness.parms().validationCurrentWall, 0s))); BEAST_EXPECT( ValStatus::Stale == - harness.add(n.validate(ledgerA, 0s, harness.parms().validationCURRENT_LOCAL))); + harness.add(n.validate(ledgerA, 0s, harness.parms().validationCurrentLocal))); } { @@ -357,7 +357,7 @@ class Validations_test : public beast::unit_test::Suite // If we advance far enough for AB to expire, we can fully // validate or partially validate that sequence number again BEAST_EXPECT(ValStatus::Conflicting == process(ledgerAZ)); - harness.clock().advance(harness.parms().validationSET_EXPIRES + 1ms); + harness.clock().advance(harness.parms().validationSetExpires + 1ms); BEAST_EXPECT(ValStatus::Current == process(ledgerAZ)); } } @@ -392,7 +392,7 @@ class Validations_test : public beast::unit_test::Suite BEAST_EXPECT( harness.vals().getPreferred(genesisLedger_) == std::make_pair(ledgerAB.seq(), ledgerAB.id())); - harness.clock().advance(harness.parms().validationCURRENT_LOCAL); + harness.clock().advance(harness.parms().validationCurrentLocal); // trigger check for stale trigger(harness.vals()); @@ -487,7 +487,7 @@ class Validations_test : public beast::unit_test::Suite BEAST_EXPECT(harness.vals().currentTrusted()[0].seq() == ledgerAC.seq()); // Pass enough time for it to go stale - harness.clock().advance(harness.parms().validationCURRENT_LOCAL); + harness.clock().advance(harness.parms().validationCurrentLocal); BEAST_EXPECT(harness.vals().currentTrusted().empty()); } @@ -528,7 +528,7 @@ class Validations_test : public beast::unit_test::Suite } // Pass enough time for them to go stale - harness.clock().advance(harness.parms().validationCURRENT_LOCAL); + harness.clock().advance(harness.parms().validationCurrentLocal); BEAST_EXPECT(harness.vals().getCurrentNodeIDs().empty()); } @@ -657,7 +657,7 @@ class Validations_test : public beast::unit_test::Suite BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerA.id()) == 1); harness.vals().expire(j); BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerA.id()) == 1); - harness.clock().advance(harness.parms().validationSET_EXPIRES); + harness.clock().advance(harness.parms().validationSetExpires); harness.vals().expire(j); BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerA.id()) == 0); @@ -666,14 +666,14 @@ class Validations_test : public beast::unit_test::Suite BEAST_EXPECT(ValStatus::Current == harness.add(a.validate(ledgerB))); BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerB.id()) == 1); harness.vals().setSeqToKeep(ledgerB.seq(), ledgerB.seq() + kOne); - harness.clock().advance(harness.parms().validationSET_EXPIRES); + harness.clock().advance(harness.parms().validationSetExpires); harness.vals().expire(j); BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerB.id()) == 1); // change toKeep harness.vals().setSeqToKeep(ledgerB.seq() + kOne, ledgerB.seq() + kTwo); // advance clock slowly int const loops = - harness.parms().validationSET_EXPIRES / harness.parms().validationFRESHNESS + 1; + harness.parms().validationSetExpires / harness.parms().validationFRESHNESS + 1; for (int i = 0; i < loops; ++i) { harness.clock().advance(harness.parms().validationFRESHNESS); @@ -686,7 +686,7 @@ class Validations_test : public beast::unit_test::Suite BEAST_EXPECT(ValStatus::Current == harness.add(a.validate(ledgerC))); BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerC.id()) == 1); harness.vals().setSeqToKeep(ledgerC.seq() - kOne, ledgerC.seq()); - harness.clock().advance(harness.parms().validationSET_EXPIRES); + harness.clock().advance(harness.parms().validationSetExpires); harness.vals().expire(j); BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerC.id()) == 0); } @@ -934,7 +934,7 @@ class Validations_test : public beast::unit_test::Suite BEAST_EXPECT(enforcer(clock.now(), Seq{10}, p)); BEAST_EXPECT(!enforcer(clock.now(), Seq{5}, p)); BEAST_EXPECT(!enforcer(clock.now(), Seq{9}, p)); - clock.advance(p.validationSET_EXPIRES - 1ms); + clock.advance(p.validationSetExpires - 1ms); BEAST_EXPECT(!enforcer(clock.now(), Seq{1}, p)); clock.advance(2ms); BEAST_EXPECT(enforcer(clock.now(), Seq{1}, p)); diff --git a/src/test/core/Config_test.cpp b/src/test/core/Config_test.cpp index 3e6495bc2f..ce6774827e 100644 --- a/src/test/core/Config_test.cpp +++ b/src/test/core/Config_test.cpp @@ -550,7 +550,7 @@ main } BEAST_EXPECT(error.empty()); - BEAST_EXPECT(c.NETWORK_ID == 0); + BEAST_EXPECT(c.networkId == 0); try { @@ -563,7 +563,7 @@ main } BEAST_EXPECT(error.empty()); - BEAST_EXPECT(c.NETWORK_ID == 0); + BEAST_EXPECT(c.networkId == 0); try { @@ -578,7 +578,7 @@ main } BEAST_EXPECT(error.empty()); - BEAST_EXPECT(c.NETWORK_ID == 255); + BEAST_EXPECT(c.networkId == 255); try { @@ -593,7 +593,7 @@ main } BEAST_EXPECT(error.empty()); - BEAST_EXPECT(c.NETWORK_ID == 10000); + BEAST_EXPECT(c.networkId == 10000); } void @@ -655,7 +655,7 @@ nHBu9PTL9dn2GuZtdW4U2WzBwffyX9qsQCd9CNU4Z5YG3PQfViM8 c.loadFromString(toLoad); BEAST_EXPECT(c.legacy("validators_file").empty()); BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 5); - BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == std::nullopt); + BEAST_EXPECT(c.validatorListThreshold == std::nullopt); } { // load validator list sites and keys from config @@ -685,7 +685,7 @@ trust-these-validators.gov "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.VALIDATOR_LIST_THRESHOLD == std::size_t(1)); + BEAST_EXPECT(c.validatorListThreshold == std::size_t(1)); } { // load validator list sites and keys from config @@ -715,7 +715,7 @@ trust-these-validators.gov "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.VALIDATOR_LIST_THRESHOLD == std::nullopt); + BEAST_EXPECT(c.validatorListThreshold == std::nullopt); } { // load should throw if [validator_list_threshold] is greater than @@ -836,7 +836,7 @@ trust-these-validators.gov 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.VALIDATOR_LIST_THRESHOLD == 2); + BEAST_EXPECT(c.validatorListThreshold == 2); } { // load from specified [validators_file] file name @@ -853,7 +853,7 @@ trust-these-validators.gov 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.VALIDATOR_LIST_THRESHOLD == 2); + BEAST_EXPECT(c.validatorListThreshold == 2); } { // load from specified [validators_file] relative path @@ -870,7 +870,7 @@ trust-these-validators.gov 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.VALIDATOR_LIST_THRESHOLD == 2); + BEAST_EXPECT(c.validatorListThreshold == 2); } { // load from validators file in default location @@ -885,7 +885,7 @@ trust-these-validators.gov 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.VALIDATOR_LIST_THRESHOLD == 2); + BEAST_EXPECT(c.validatorListThreshold == 2); } { // load from specified [validators_file] instead @@ -904,7 +904,7 @@ trust-these-validators.gov 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.VALIDATOR_LIST_THRESHOLD == 2); + BEAST_EXPECT(c.validatorListThreshold == 2); } { @@ -940,7 +940,7 @@ trust-these-validators.gov 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.VALIDATOR_LIST_THRESHOLD == 2); + BEAST_EXPECT(c.validatorListThreshold == 2); } { // load should throw if [validator_list_threshold] is present both @@ -1017,7 +1017,7 @@ trust-these-validators.gov BEAST_EXPECT(!config.quiet()); BEAST_EXPECT(!config.silent()); BEAST_EXPECT(!config.standalone()); - BEAST_EXPECT(config.LEDGER_HISTORY == 256); + BEAST_EXPECT(config.ledgerHistory == 256); BEAST_EXPECT(!config.legacy("database_path").empty()); } { @@ -1030,7 +1030,7 @@ trust-these-validators.gov BEAST_EXPECT(config.quiet()); BEAST_EXPECT(!config.silent()); BEAST_EXPECT(!config.standalone()); - BEAST_EXPECT(config.LEDGER_HISTORY == 256); + BEAST_EXPECT(config.ledgerHistory == 256); BEAST_EXPECT(!config.legacy("database_path").empty()); } { @@ -1043,7 +1043,7 @@ trust-these-validators.gov BEAST_EXPECT(config.quiet()); BEAST_EXPECT(config.silent()); BEAST_EXPECT(!config.standalone()); - BEAST_EXPECT(config.LEDGER_HISTORY == 256); + BEAST_EXPECT(config.ledgerHistory == 256); BEAST_EXPECT(!config.legacy("database_path").empty()); } { @@ -1056,7 +1056,7 @@ trust-these-validators.gov BEAST_EXPECT(config.quiet()); BEAST_EXPECT(config.silent()); BEAST_EXPECT(!config.standalone()); - BEAST_EXPECT(config.LEDGER_HISTORY == 256); + BEAST_EXPECT(config.ledgerHistory == 256); BEAST_EXPECT(!config.legacy("database_path").empty()); } { @@ -1069,7 +1069,7 @@ trust-these-validators.gov BEAST_EXPECT(!config.quiet()); BEAST_EXPECT(!config.silent()); BEAST_EXPECT(config.standalone()); - BEAST_EXPECT(config.LEDGER_HISTORY == 0); + BEAST_EXPECT(config.ledgerHistory == 0); BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); } { @@ -1082,7 +1082,7 @@ trust-these-validators.gov BEAST_EXPECT(config.quiet()); BEAST_EXPECT(!config.silent()); BEAST_EXPECT(config.standalone()); - BEAST_EXPECT(config.LEDGER_HISTORY == 0); + BEAST_EXPECT(config.ledgerHistory == 0); BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); } { @@ -1095,7 +1095,7 @@ trust-these-validators.gov BEAST_EXPECT(config.quiet()); BEAST_EXPECT(config.silent()); BEAST_EXPECT(config.standalone()); - BEAST_EXPECT(config.LEDGER_HISTORY == 0); + BEAST_EXPECT(config.ledgerHistory == 0); BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); } { @@ -1108,7 +1108,7 @@ trust-these-validators.gov BEAST_EXPECT(config.quiet()); BEAST_EXPECT(config.silent()); BEAST_EXPECT(config.standalone()); - BEAST_EXPECT(config.LEDGER_HISTORY == 0); + BEAST_EXPECT(config.ledgerHistory == 0); BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); } } @@ -1125,11 +1125,11 @@ trust-these-validators.gov ParsedPort rpc; if (!unexcept([&]() { parsePort(rpc, conf["port_rpc"], log); })) return; - BEAST_EXPECT(rpc.admin_nets_v4.size() + rpc.admin_nets_v6.size() == 2); + BEAST_EXPECT(rpc.adminNetsV4.size() + rpc.adminNetsV6.size() == 2); ParsedPort wss; if (!unexcept([&]() { parsePort(wss, conf["port_wss_admin"], log); })) return; - BEAST_EXPECT(wss.admin_nets_v4.size() + wss.admin_nets_v6.size() == 1); + BEAST_EXPECT(wss.adminNetsV4.size() + wss.adminNetsV6.size() == 1); } void @@ -1245,25 +1245,25 @@ r.ripple.com:51235 BEAST_EXPECT( cfg.exists(SECTION_IPS_FIXED) && cfg.section(SECTION_IPS_FIXED).lines().size() == 15 && cfg.section(SECTION_IPS_FIXED).values().size() == 15); - BEAST_EXPECT(cfg.IPS[0] == "r.ripple.com 51235"); + BEAST_EXPECT(cfg.ips[0] == "r.ripple.com 51235"); - BEAST_EXPECT(cfg.IPS_FIXED[0] == "s1.ripple.com 51235"); - BEAST_EXPECT(cfg.IPS_FIXED[1] == "s2.ripple.com 51235"); - BEAST_EXPECT(cfg.IPS_FIXED[2] == "anotherserversansport"); - BEAST_EXPECT(cfg.IPS_FIXED[3] == "anotherserverwithport 12"); - BEAST_EXPECT(cfg.IPS_FIXED[4] == "1.1.1.1 1"); - BEAST_EXPECT(cfg.IPS_FIXED[5] == "1.1.1.1 1"); - BEAST_EXPECT(cfg.IPS_FIXED[6] == "12.34.12.123 12345"); - BEAST_EXPECT(cfg.IPS_FIXED[7] == "12.34.12.123 12345"); + BEAST_EXPECT(cfg.ipsFixed[0] == "s1.ripple.com 51235"); + BEAST_EXPECT(cfg.ipsFixed[1] == "s2.ripple.com 51235"); + BEAST_EXPECT(cfg.ipsFixed[2] == "anotherserversansport"); + BEAST_EXPECT(cfg.ipsFixed[3] == "anotherserverwithport 12"); + BEAST_EXPECT(cfg.ipsFixed[4] == "1.1.1.1 1"); + BEAST_EXPECT(cfg.ipsFixed[5] == "1.1.1.1 1"); + BEAST_EXPECT(cfg.ipsFixed[6] == "12.34.12.123 12345"); + BEAST_EXPECT(cfg.ipsFixed[7] == "12.34.12.123 12345"); // all ipv6 should be ignored by colon replacer, howsoever formatted - BEAST_EXPECT(cfg.IPS_FIXED[8] == "::"); - BEAST_EXPECT(cfg.IPS_FIXED[9] == "2001:db8::"); - BEAST_EXPECT(cfg.IPS_FIXED[10] == "::1"); - BEAST_EXPECT(cfg.IPS_FIXED[11] == "::1:12345"); - BEAST_EXPECT(cfg.IPS_FIXED[12] == "[::1]:12345"); - BEAST_EXPECT(cfg.IPS_FIXED[13] == "2001:db8:3333:4444:5555:6666:7777:8888:12345"); - BEAST_EXPECT(cfg.IPS_FIXED[14] == "[2001:db8:3333:4444:5555:6666:7777:8888]:1"); + BEAST_EXPECT(cfg.ipsFixed[8] == "::"); + BEAST_EXPECT(cfg.ipsFixed[9] == "2001:db8::"); + BEAST_EXPECT(cfg.ipsFixed[10] == "::1"); + BEAST_EXPECT(cfg.ipsFixed[11] == "::1:12345"); + BEAST_EXPECT(cfg.ipsFixed[12] == "[::1]:12345"); + BEAST_EXPECT(cfg.ipsFixed[13] == "2001:db8:3333:4444:5555:6666:7777:8888:12345"); + BEAST_EXPECT(cfg.ipsFixed[14] == "[2001:db8:3333:4444:5555:6666:7777:8888]:1"); } void @@ -1274,51 +1274,51 @@ r.ripple.com:51235 std::string_view line; std::string_view field; std::string_view expect; - bool had_comment; + bool hadComment; }; std::array const tests = { {{.line = "password = aaaa\\#bbbb", .field = "password", .expect = "aaaa#bbbb", - .had_comment = false}, + .hadComment = false}, {.line = "password = aaaa#bbbb", .field = "password", .expect = "aaaa", - .had_comment = true}, + .hadComment = true}, {.line = "password = aaaa #bbbb", .field = "password", .expect = "aaaa", - .had_comment = true}, + .hadComment = true}, // since the value is all comment, this doesn't parse as k=v : {.line = "password = #aaaa #bbbb", .field = "", .expect = "password =", - .had_comment = true}, + .hadComment = true}, {.line = "password = aaaa\\# #bbbb", .field = "password", .expect = "aaaa#", - .had_comment = true}, + .hadComment = true}, {.line = "password = aaaa\\##bbbb", .field = "password", .expect = "aaaa#", - .had_comment = true}, - {.line = "aaaa#bbbb", .field = "", .expect = "aaaa", .had_comment = true}, - {.line = "aaaa\\#bbbb", .field = "", .expect = "aaaa#bbbb", .had_comment = false}, - {.line = "aaaa\\##bbbb", .field = "", .expect = "aaaa#", .had_comment = true}, - {.line = "aaaa #bbbb", .field = "", .expect = "aaaa", .had_comment = true}, - {.line = "1 #comment", .field = "", .expect = "1", .had_comment = true}, - {.line = "#whole thing is comment", .field = "", .expect = "", .had_comment = false}, + .hadComment = true}, + {.line = "aaaa#bbbb", .field = "", .expect = "aaaa", .hadComment = true}, + {.line = "aaaa\\#bbbb", .field = "", .expect = "aaaa#bbbb", .hadComment = false}, + {.line = "aaaa\\##bbbb", .field = "", .expect = "aaaa#", .hadComment = true}, + {.line = "aaaa #bbbb", .field = "", .expect = "aaaa", .hadComment = true}, + {.line = "1 #comment", .field = "", .expect = "1", .hadComment = true}, + {.line = "#whole thing is comment", .field = "", .expect = "", .hadComment = false}, {.line = " #whole comment with space", .field = "", .expect = "", - .had_comment = false}}}; + .hadComment = false}}}; for (auto const& t : tests) { Section s; s.append(std::string(t.line)); - BEAST_EXPECT(s.hadTrailingComments() == t.had_comment); + BEAST_EXPECT(s.hadTrailingComments() == t.hadComment); if (t.field.empty()) { BEAST_EXPECTS(s.legacy() == t.expect, s.legacy()); @@ -1481,7 +1481,7 @@ r.ripple.com:51235 c.loadFromString(toLoad); if (shouldPass) { - BEAST_EXPECT(c.AMENDMENT_MAJORITY_TIME.count() == val * sec); + BEAST_EXPECT(c.amendmentMajorityTime.count() == val * sec); } else { @@ -1512,7 +1512,7 @@ r.ripple.com:51235 { Config c; c.loadFromString("[overlay]\nmax_unknown_time=" + value); - return c.MAX_UNKNOWN_TIME; + return c.maxUnknownTime; } catch (std::runtime_error const&) { @@ -1546,7 +1546,7 @@ r.ripple.com:51235 { Config c; c.loadFromString("[overlay]\nmax_diverged_time=" + value); - return c.MAX_DIVERGED_TIME; + return c.maxDivergedTime; } catch (std::runtime_error const&) { diff --git a/src/test/core/Coroutine_test.cpp b/src/test/core/Coroutine_test.cpp index 103191ec59..bf1d98c779 100644 --- a/src/test/core/Coroutine_test.cpp +++ b/src/test/core/Coroutine_test.cpp @@ -58,7 +58,7 @@ public: testcase("correct order"); Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->FORCE_MULTI_THREAD = true; + cfg->forceMultiThread = true; return cfg; })); @@ -85,7 +85,7 @@ public: testcase("incorrect order"); Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->FORCE_MULTI_THREAD = true; + cfg->forceMultiThread = true; return cfg; })); diff --git a/src/test/csf/Scheduler.h b/src/test/csf/Scheduler.h index c70b7d4854..ede43be854 100644 --- a/src/test/csf/Scheduler.h +++ b/src/test/csf/Scheduler.h @@ -91,7 +91,7 @@ private: make_multiset>::type; // alloc_ is owned by the scheduler boost::container::pmr::monotonic_buffer_resource* alloc_; - by_when_set by_when_; + by_when_set byWhen_; public: using iterator = typename by_when_set::iterator; @@ -258,7 +258,7 @@ inline Scheduler::QueueType::QueueType(boost::container::pmr::monotonic_buffer_r inline Scheduler::QueueType::~QueueType() { - for (auto iter = by_when_.begin(); iter != by_when_.end();) + for (auto iter = byWhen_.begin(); iter != byWhen_.end();) { auto e = &*iter; ++iter; @@ -270,19 +270,19 @@ inline Scheduler::QueueType::~QueueType() inline bool Scheduler::QueueType::empty() const { - return by_when_.empty(); + return byWhen_.empty(); } inline auto Scheduler::QueueType::begin() -> iterator { - return by_when_.begin(); + return byWhen_.begin(); } inline auto Scheduler::QueueType::end() -> iterator { - return by_when_.end(); + return byWhen_.end(); } template @@ -292,14 +292,14 @@ Scheduler::QueueType::emplace(time_point when, Handler&& h) -> typename by_when_ using event_type = EventImpl>; auto const p = alloc_->allocate(sizeof(event_type)); auto& e = *new (p) event_type(when, std::forward(h)); - return by_when_.insert(e); + return byWhen_.insert(e); } inline auto Scheduler::QueueType::erase(iterator iter) -> typename by_when_set::iterator { auto& e = *iter; - auto next = by_when_.erase(iter); + auto next = byWhen_.erase(iter); e.~Event(); alloc_->deallocate(&e, sizeof(e)); return next; diff --git a/src/test/jtx/impl/AMMTest.cpp b/src/test/jtx/impl/AMMTest.cpp index 5801e8fb44..46c5e44bd3 100644 --- a/src/test/jtx/impl/AMMTest.cpp +++ b/src/test/jtx/impl/AMMTest.cpp @@ -213,9 +213,9 @@ AMMTest::pathTestEnv() // different from the current defaults. This function creates an env // with the search parameters that the tests were written for. return Env(*this, envconfig([](std::unique_ptr cfg) { - cfg->PATH_SEARCH_OLD = 7; - cfg->PATH_SEARCH = 7; - cfg->PATH_SEARCH_MAX = 10; + cfg->pathSearchOld = 7; + cfg->pathSearch = 7; + cfg->pathSearchMax = 10; return cfg; })); } diff --git a/src/test/jtx/impl/Env.cpp b/src/test/jtx/impl/Env.cpp index 1cd4dd1029..4b6955bafb 100644 --- a/src/test/jtx/impl/Env.cpp +++ b/src/test/jtx/impl/Env.cpp @@ -91,7 +91,7 @@ Env::AppBundle::AppBundle( timeKeeper = tk.get(); // Hack so we don't have to call Config::setup HTTPClient::initializeSSLContext( - config->SSL_VERIFY_DIR, config->SSL_VERIFY_FILE, config->SSL_VERIFY, debugLog()); + config->sslVerifyDir, config->sslVerifyFile, config->sslVerify, debugLog()); owned = makeApplication(std::move(config), std::move(logs), std::move(tk)); app = owned.get(); app->getLogs().threshold(thresh); diff --git a/src/test/jtx/impl/JSONRPCClient.cpp b/src/test/jtx/impl/JSONRPCClient.cpp index c8e6326ed2..cf81bfab0c 100644 --- a/src/test/jtx/impl/JSONRPCClient.cpp +++ b/src/test/jtx/impl/JSONRPCClient.cpp @@ -81,11 +81,11 @@ class JSONRPCClient : public AbstractClient boost::asio::ip::tcp::socket stream_; boost::beast::multi_buffer bin_; boost::beast::multi_buffer bout_; - unsigned rpc_version_; + unsigned rpcVersion_; public: explicit JSONRPCClient(Config const& cfg, unsigned rpcVersion) - : ep_(getEndpoint(cfg)), stream_(ios_), rpc_version_(rpcVersion) + : ep_(getEndpoint(cfg)), stream_(ios_), rpcVersion_(rpcVersion) { stream_.connect(ep_); } @@ -116,7 +116,7 @@ public: { json::Value jr; jr[jss::method] = cmd; - if (rpc_version_ == 2) + if (rpcVersion_ == 2) { jr[jss::jsonrpc] = "2.0"; jr[jss::ripplerpc] = "2.0"; @@ -148,7 +148,7 @@ public: [[nodiscard]] unsigned version() const override { - return rpc_version_; + return rpcVersion_; } }; diff --git a/src/test/jtx/impl/TestHelpers.cpp b/src/test/jtx/impl/TestHelpers.cpp index e9ea48fb39..c784c074de 100644 --- a/src/test/jtx/impl/TestHelpers.cpp +++ b/src/test/jtx/impl/TestHelpers.cpp @@ -172,9 +172,9 @@ pathTestEnv(beast::unit_test::Suite& suite) // with the search parameters that the tests were written for. using namespace jtx; return Env(suite, envconfig([](std::unique_ptr cfg) { - cfg->PATH_SEARCH_OLD = 7; - cfg->PATH_SEARCH = 7; - cfg->PATH_SEARCH_MAX = 10; + cfg->pathSearchOld = 7; + cfg->pathSearch = 7; + cfg->pathSearchMax = 10; return cfg; })); } diff --git a/src/test/jtx/impl/WSClient.cpp b/src/test/jtx/impl/WSClient.cpp index ba09647ce7..551fd1404b 100644 --- a/src/test/jtx/impl/WSClient.cpp +++ b/src/test/jtx/impl/WSClient.cpp @@ -120,7 +120,7 @@ class WSClientImpl : public WSClient std::condition_variable cv_; std::list> msgs_; - unsigned rpc_version_; + unsigned rpcVersion_; void cleanup() @@ -157,7 +157,7 @@ public: , thread_([&] { ios_.run(); }) , stream_(ios_) , ws_(stream_) - , rpc_version_(rpcVersion) + , rpcVersion_(rpcVersion) { try { @@ -197,7 +197,7 @@ public: json::Value jp; if (params) jp = params; - if (rpc_version_ == 2) + if (rpcVersion_ == 2) { jp[jss::method] = cmd; jp[jss::jsonrpc] = "2.0"; @@ -284,7 +284,7 @@ public: [[nodiscard]] unsigned version() const override { - return rpc_version_; + return rpcVersion_; } private: diff --git a/src/test/jtx/impl/envconfig.cpp b/src/test/jtx/impl/envconfig.cpp index 648f8e4460..56197e1078 100644 --- a/src/test/jtx/impl/envconfig.cpp +++ b/src/test/jtx/impl/envconfig.cpp @@ -20,12 +20,12 @@ setupConfigForUnitTests(Config& cfg) using namespace jtx; // Default fees to old values, so tests don't have to worry about changes in // Config.h - cfg.FEES.reference_fee = UNIT_TEST_REFERENCE_FEE; - cfg.FEES.account_reserve = XRP(200).value().xrp().drops(); - cfg.FEES.owner_reserve = XRP(50).value().xrp().drops(); + cfg.fees.referenceFee = UNIT_TEST_REFERENCE_FEE; + cfg.fees.accountReserve = XRP(200).value().xrp().drops(); + cfg.fees.ownerReserve = XRP(50).value().xrp().drops(); // The Beta API (currently v2) is always available to tests - cfg.BETA_RPC_API = true; + cfg.betaRpcApi = true; cfg.overwrite(ConfigSection::nodeDatabase(), "type", "memory"); cfg.overwrite(ConfigSection::nodeDatabase(), "path", "main"); @@ -54,7 +54,7 @@ setupConfigForUnitTests(Config& cfg) cfg[PORT_WS].set("admin", getEnvLocalhostAddr()); cfg[PORT_WS].set("port", "0"); cfg[PORT_WS].set("protocol", "ws"); - cfg.SSL_VERIFY = false; + cfg.sslVerify = false; } namespace jtx { @@ -96,7 +96,7 @@ secureGatewayLocalnet(std::unique_ptr cfg) std::unique_ptr singleThreadIo(std::unique_ptr cfg) { - cfg->IO_WORKERS = 1; + cfg->ioWorkers = 1; return cfg; } diff --git a/src/test/jtx/impl/permissioned_dex.cpp b/src/test/jtx/impl/permissioned_dex.cpp index 012932fed5..5c059e9e80 100644 --- a/src/test/jtx/impl/permissioned_dex.cpp +++ b/src/test/jtx/impl/permissioned_dex.cpp @@ -48,7 +48,7 @@ PermissionedDEX::PermissionedDEX(Env& env) , alice("permdex-alice") , bob("permdex-bob") , carol("permdex-carol") - , USD(gw["USD"]) + , usd(gw["USD"]) , credType("permdex-abcde") { // Fund accounts @@ -59,10 +59,10 @@ PermissionedDEX::PermissionedDEX(Env& env) for (auto const& account : {alice, bob, carol, domainOwner}) { - env.trust(USD(1000), account); + env.trust(usd(1000), account); env.close(); - env(pay(gw, account, USD(100))); + env(pay(gw, account, usd(100))); env.close(); } } diff --git a/src/test/jtx/impl/xchain_bridge.cpp b/src/test/jtx/impl/xchain_bridge.cpp index a88535a51e..24669e6d4f 100644 --- a/src/test/jtx/impl/xchain_bridge.cpp +++ b/src/test/jtx/impl/xchain_bridge.cpp @@ -396,7 +396,7 @@ XChainBridgeObjects::XChainBridgeObjects() } return result; }()) - , alt_signers([] { + , altSigners([] { static constexpr int kNumSigners = kUtXchainDefaultNumSigners; std::vector result; result.reserve(kNumSigners); @@ -431,17 +431,16 @@ XChainBridgeObjects::XChainBridgeObjects() return r; }()) , reward(XRP(1)) - , split_reward_quorum(divide(reward, STAmount(kUtXchainDefaultQuorum), reward.get())) - , split_reward_everyone( - divide(reward, STAmount(kUtXchainDefaultNumSigners), reward.get())) - , tiny_reward(drops(37)) - , tiny_reward_split( - (divide(tiny_reward, STAmount(kUtXchainDefaultQuorum), tiny_reward.get()))) - , tiny_reward_remainder( - tiny_reward - - multiply(tiny_reward_split, STAmount(kUtXchainDefaultQuorum), tiny_reward.get())) - , one_xrp(XRP(1)) - , xrp_dust(divide(one_xrp, STAmount(10000), one_xrp.get())) + , splitRewardQuorum(divide(reward, STAmount(kUtXchainDefaultQuorum), reward.get())) + , splitRewardEveryone(divide(reward, STAmount(kUtXchainDefaultNumSigners), reward.get())) + , tinyReward(drops(37)) + , tinyRewardSplit( + (divide(tinyReward, STAmount(kUtXchainDefaultQuorum), tinyReward.get()))) + , tinyRewardRemainder( + tinyReward - + multiply(tinyRewardSplit, STAmount(kUtXchainDefaultQuorum), tinyReward.get())) + , oneXrp(XRP(1)) + , xrpDust(divide(oneXrp, STAmount(10000), oneXrp.get())) { } diff --git a/src/test/jtx/permissioned_dex.h b/src/test/jtx/permissioned_dex.h index 025097116f..b0a4d4e2d5 100644 --- a/src/test/jtx/permissioned_dex.h +++ b/src/test/jtx/permissioned_dex.h @@ -20,7 +20,7 @@ public: Account alice; Account bob; Account carol; - IOU USD; + IOU usd; uint256 domainID; std::string credType; diff --git a/src/test/jtx/xchain_bridge.h b/src/test/jtx/xchain_bridge.h index c20b6f2fc5..e4c012510d 100644 --- a/src/test/jtx/xchain_bridge.h +++ b/src/test/jtx/xchain_bridge.h @@ -165,21 +165,21 @@ struct XChainBridgeObjects FeatureBitset const features; std::vector const signers; - std::vector const alt_signers; + std::vector const altSigners; std::vector const payee; std::vector const payees; std::uint32_t const quorum{kUtXchainDefaultQuorum}; - STAmount const reward; // 1 xrp - STAmount const split_reward_quorum; // 250,000 drops - STAmount const split_reward_everyone; // 200,000 drops + STAmount const reward; // 1 xrp + STAmount const splitRewardQuorum; // 250,000 drops + STAmount const splitRewardEveryone; // 200,000 drops - STAmount const tiny_reward; // 37 drops - STAmount const tiny_reward_split; // 9 drops - STAmount const tiny_reward_remainder; // 1 drops + STAmount const tinyReward; // 37 drops + STAmount const tinyRewardSplit; // 9 drops + STAmount const tinyRewardRemainder; // 1 drops - STAmount const one_xrp; - STAmount const xrp_dust; + STAmount const oneXrp; + STAmount const xrpDust; static constexpr int kDropPerXrp = 1000000; diff --git a/src/test/ledger/SkipList_test.cpp b/src/test/ledger/SkipList_test.cpp index fe671ed128..fd3cc2f214 100644 --- a/src/test/ledger/SkipList_test.cpp +++ b/src/test/ledger/SkipList_test.cpp @@ -25,7 +25,7 @@ class SkipList_test : public beast::unit_test::Suite auto prev = std::make_shared( kCreateGenesis, Rules{config.features}, - config.FEES.toFees(), + config.fees.toFees(), std::vector{}, env.app().getNodeFamily()); history.push_back(prev); diff --git a/src/test/ledger/View_test.cpp b/src/test/ledger/View_test.cpp index 1714702c18..d1c7316588 100644 --- a/src/test/ledger/View_test.cpp +++ b/src/test/ledger/View_test.cpp @@ -153,7 +153,7 @@ class View_test : public beast::unit_test::Suite std::shared_ptr const genesis = std::make_shared( kCreateGenesis, Rules{config.features}, - config.FEES.toFees(), + config.fees.toFees(), std::vector{}, env.app().getNodeFamily()); auto const ledger = @@ -421,7 +421,7 @@ class View_test : public beast::unit_test::Suite std::shared_ptr const genesis = std::make_shared( kCreateGenesis, Rules{config.features}, - config.FEES.toFees(), + config.fees.toFees(), std::vector{}, env.app().getNodeFamily()); auto const ledger = @@ -630,7 +630,7 @@ class View_test : public beast::unit_test::Suite std::shared_ptr const genesis = std::make_shared( kCreateGenesis, Rules{config.features}, - config.FEES.toFees(), + config.fees.toFees(), std::vector{}, env.app().getNodeFamily()); auto const ledger = @@ -1020,7 +1020,7 @@ class View_test : public beast::unit_test::Suite std::shared_ptr const genesis = std::make_shared( kCreateGenesis, Rules{config.features}, - config.FEES.toFees(), + config.fees.toFees(), std::vector{}, env.app().getNodeFamily()); auto const ledger = diff --git a/src/test/nodestore/Database_test.cpp b/src/test/nodestore/Database_test.cpp index 744717659a..50bdfefd4c 100644 --- a/src/test/nodestore/Database_test.cpp +++ b/src/test/nodestore/Database_test.cpp @@ -74,7 +74,7 @@ public: auto& section = p->section("sqlite"); section.set("safety_level", "high"); } - p->LEDGER_HISTORY = 100'000'000; + p->ledgerHistory = 100'000'000; return Env( *this, @@ -103,7 +103,7 @@ public: auto& section = p->section("sqlite"); section.set("safety_level", "low"); } - p->LEDGER_HISTORY = 100'000'000; + p->ledgerHistory = 100'000'000; return Env( *this, @@ -166,7 +166,7 @@ public: section.set("synchronous", "extra"); section.set("temp_store", "default"); } - p->LEDGER_HISTORY = 50'000'000; + p->ledgerHistory = 50'000'000; return Env( *this, diff --git a/src/test/nodestore/Timing_test.cpp b/src/test/nodestore/Timing_test.cpp index d7540f0b3a..67feace198 100644 --- a/src/test/nodestore/Timing_test.cpp +++ b/src/test/nodestore/Timing_test.cpp @@ -84,16 +84,16 @@ private: beast::xor_shift_engine gen_; std::uint8_t prefix_; - std::discrete_distribution d_type_; - std::uniform_int_distribution d_size_; + std::discrete_distribution dType_; + std::uniform_int_distribution dSize_; public: explicit Sequence(std::uint8_t prefix) : prefix_(prefix) // uniform distribution over hotLEDGER - hotTRANSACTION_NODE // but exclude hotTRANSACTION = 2 (removed) - , d_type_({1, 1, 0, 1, 1}) - , d_size_(kMinSize, kMaxSize) + , dType_({1, 1, 0, 1, 1}) + , dSize_(kMinSize, kMaxSize) { } @@ -116,10 +116,10 @@ public: auto const data = static_cast(&*key.begin()); *data = prefix_; rngcpy(data + 1, key.size() - 1, gen_); - Blob value(d_size_(gen_)); + Blob value(dSize_(gen_)); rngcpy(&value[0], value.size(), gen_); return NodeObject::createObject( - safeCast(d_type_(gen_)), std::move(value), key); + safeCast(dType_(gen_)), std::move(value), key); } // returns a batch of NodeObjects starting at n @@ -140,11 +140,11 @@ class Timing_test : public beast::unit_test::Suite public: static constexpr auto kMissingNodePercent = 20; // percent of fetches for missing nodes - std::size_t const default_repeat = 3; + std::size_t const defaultRepeat = 3; #ifndef NDEBUG - std::size_t const default_items = 10000; + std::size_t const defaultItems = 10000; #else - std::size_t const default_items = 100000; // release + std::size_t const defaultItems = 100000; // release #endif using clock_type = std::chrono::steady_clock; @@ -639,7 +639,7 @@ public: { w = std::max::size_type>(w, test.first.size()); } - log << threads << " Thread" << (threads > 1 ? "s" : "") << ", " << default_items + log << threads << " Thread" << (threads > 1 ? "s" : "") << ", " << defaultItems << " Objects" << std::endl; { std::stringstream ss; @@ -655,9 +655,9 @@ public: for (auto const& configString : configStrings) { Params params{}; - params.items = default_items; + params.items = defaultItems; params.threads = threads; - for (auto i = default_repeat; (i--) != 0u;) + for (auto i = defaultRepeat; (i--) != 0u;) { beast::TempDir const tempDir; Section config = parse(configString); diff --git a/src/test/overlay/compression_test.cpp b/src/test/overlay/compression_test.cpp index d98ffa9b33..60cc69a14f 100644 --- a/src/test/overlay/compression_test.cpp +++ b/src/test/overlay/compression_test.cpp @@ -112,16 +112,16 @@ public: return; std::vector decompressed; - decompressed.resize(header->uncompressed_size); + decompressed.resize(header->uncompressedSize); - BEAST_EXPECT(header->payload_wire_size == buffer.size() - header->header_size); + BEAST_EXPECT(header->payloadWireSize == buffer.size() - header->headerSize); ZeroCopyInputStream stream(buffers.data()); - stream.Skip(header->header_size); + stream.Skip(header->headerSize); auto decompressedSize = xrpl::compression::decompress( - stream, header->payload_wire_size, decompressed.data(), header->uncompressed_size); - BEAST_EXPECT(decompressedSize == header->uncompressed_size); + stream, header->payloadWireSize, decompressed.data(), header->uncompressedSize); + BEAST_EXPECT(decompressedSize == header->uncompressedSize); auto const proto1 = std::make_shared(); BEAST_EXPECT(proto1->ParseFromArray(decompressed.data(), decompressedSize)); @@ -408,9 +408,8 @@ public: << enable << "\n"; c.loadFromString(str.str()); auto env = std::make_shared(*this); - env->app().config().COMPRESSION = c.COMPRESSION; - env->app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = - c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE; + env->app().config().compression = c.compression; + env->app().config().vpReduceRelayBaseSquelchEnable = c.vpReduceRelayBaseSquelchEnable; return env; }; auto handshake = [&](int outboundEnable, int inboundEnable) { @@ -419,10 +418,10 @@ public: auto env = getEnv(outboundEnable); auto request = xrpl::makeRequest( true, - env->app().config().COMPRESSION, + env->app().config().compression, false, - env->app().config().TX_REDUCE_RELAY_ENABLE, - env->app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE); + env->app().config().txReduceRelayEnable, + env->app().config().vpReduceRelayBaseSquelchEnable); http_request_type httpRequest; httpRequest.version(request.version()); httpRequest.base() = request.base(); diff --git a/src/test/overlay/reduce_relay_test.cpp b/src/test/overlay/reduce_relay_test.cpp index a0afd01d2a..54d8f555a2 100644 --- a/src/test/overlay/reduce_relay_test.cpp +++ b/src/test/overlay/reduce_relay_test.cpp @@ -973,8 +973,7 @@ protected: auto countingState = network_.overlay().isCountingState(validator); BEAST_EXPECT( countingState == false && - selected.size() == - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); + selected.size() == env_.app().config().vpReduceRelaySquelchMaxSelectedPeers); } // Trigger Link Down or Peer Disconnect event @@ -1163,7 +1162,7 @@ protected: { BEAST_EXPECT( squelched == - kMaxPeers - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); + kMaxPeers - env_.app().config().vpReduceRelaySquelchMaxSelectedPeers); n++; } }, @@ -1172,8 +1171,7 @@ protected: purge, resetClock); auto selected = network_.overlay().getSelected(network_.validator(0)); - BEAST_EXPECT( - selected.size() == env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); + BEAST_EXPECT(selected.size() == env_.app().config().vpReduceRelaySquelchMaxSelectedPeers); BEAST_EXPECT(n == 1); // only one selection round auto res = checkCounting(network_.validator(0), false); BEAST_EXPECT(res); @@ -1234,7 +1232,7 @@ protected: id, [&](PublicKey const& key, PeerWPtr const& peer) { unsquelched++; }); BEAST_EXPECT( unsquelched == - kMaxPeers - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); + kMaxPeers - env_.app().config().vpReduceRelaySquelchMaxSelectedPeers); BEAST_EXPECT(checkCounting(network_.validator(0), true)); }); } @@ -1254,7 +1252,7 @@ protected: auto peers = network_.overlay().getPeers(network_.validator(0)); BEAST_EXPECT( unsquelched == - kMaxPeers - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); + kMaxPeers - env_.app().config().vpReduceRelaySquelchMaxSelectedPeers); BEAST_EXPECT(checkCounting(network_.validator(0), true)); }); } @@ -1293,7 +1291,7 @@ vp_enable=1 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE == true); + BEAST_EXPECT(c.vpReduceRelayBaseSquelchEnable == true); }); doTest("Test Config - squelch disabled (legacy)", log, [&](bool log) { @@ -1305,7 +1303,7 @@ vp_enable=0 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE == false); + BEAST_EXPECT(c.vpReduceRelayBaseSquelchEnable == false); Config c1; @@ -1314,7 +1312,7 @@ vp_enable=0 )xrpldConfig"; c1.loadFromString(toLoad); - BEAST_EXPECT(c1.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE == false); + BEAST_EXPECT(c1.vpReduceRelayBaseSquelchEnable == false); }); doTest("Test Config - squelch enabled", log, [&](bool log) { @@ -1326,7 +1324,7 @@ vp_base_squelch_enable=1 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE == true); + BEAST_EXPECT(c.vpReduceRelayBaseSquelchEnable == true); }); doTest("Test Config - squelch disabled", log, [&](bool log) { @@ -1338,7 +1336,7 @@ vp_base_squelch_enable=0 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE == false); + BEAST_EXPECT(c.vpReduceRelayBaseSquelchEnable == false); }); doTest("Test Config - legacy and new", log, [&](bool log) { @@ -1378,7 +1376,7 @@ vp_enable=0 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS == 5); + BEAST_EXPECT(c.vpReduceRelaySquelchMaxSelectedPeers == 5); Config c1; @@ -1388,7 +1386,7 @@ vp_base_squelch_max_selected_peers=6 )xrpldConfig"; c1.loadFromString(toLoad); - BEAST_EXPECT(c1.VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS == 6); + BEAST_EXPECT(c1.vpReduceRelaySquelchMaxSelectedPeers == 6); Config c2; @@ -1421,7 +1419,7 @@ vp_base_squelch_max_selected_peers=2 doTest("BaseSquelchReady", log, [&](bool log) { ManualClock::reset(); auto createSlots = [&](bool baseSquelchEnabled) -> reduce_relay::Slots { - env_.app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = baseSquelchEnabled; + env_.app().config().vpReduceRelayBaseSquelchEnable = baseSquelchEnabled; return reduce_relay::Slots( env_.app(), network_.overlay(), env_.app().config()); }; @@ -1577,10 +1575,10 @@ vp_base_squelch_max_selected_peers=2 << "[compression]\n" << "1\n"; c.loadFromString(str.str()); - env_.app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = - c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE; + env_.app().config().vpReduceRelayBaseSquelchEnable = + c.vpReduceRelayBaseSquelchEnable; - env_.app().config().COMPRESSION = c.COMPRESSION; + env_.app().config().compression = c.compression; }; auto handshake = [&](int outboundEnable, int inboundEnable) { beast::IP::Address const addr = boost::asio::ip::make_address("172.1.1.100"); @@ -1588,10 +1586,10 @@ vp_base_squelch_max_selected_peers=2 setEnv(outboundEnable); auto request = xrpl::makeRequest( true, - env_.app().config().COMPRESSION, + env_.app().config().compression, false, - env_.app().config().TX_REDUCE_RELAY_ENABLE, - env_.app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE); + env_.app().config().txReduceRelayEnable, + env_.app().config().vpReduceRelayBaseSquelchEnable); http_request_type httpRequest; httpRequest.version(request.version()); httpRequest.base() = request.base(); @@ -1626,8 +1624,8 @@ vp_base_squelch_max_selected_peers=2 public: reduce_relay_test() : env_(*this, jtx::envconfig([](std::unique_ptr cfg) { - cfg->VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = true; - cfg->VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS = 6; + cfg->vpReduceRelayBaseSquelchEnable = true; + cfg->vpReduceRelaySquelchMaxSelectedPeers = 6; return cfg; })) , network_(env_.app()) diff --git a/src/test/overlay/short_read_test.cpp b/src/test/overlay/short_read_test.cpp index 95ab5e8c20..9af632d65c 100644 --- a/src/test/overlay/short_read_test.cpp +++ b/src/test/overlay/short_read_test.cpp @@ -62,7 +62,7 @@ private: using endpoint_type = boost::asio::ip::tcp::endpoint; using address_type = boost::asio::ip::address; - io_context_type io_context_; + io_context_type ioContext_; boost::optional> work_; std::thread thread_; std::shared_ptr context_; @@ -185,10 +185,10 @@ private: , server(server) , test(server.test_) , acceptor( - test.io_context_, + test.ioContext_, endpoint_type(boost::asio::ip::make_address(test::getEnvLocalhostAddr()), 0)) - , socket(test.io_context_) - , strand(boost::asio::make_strand(test.io_context_)) + , socket(test.ioContext_) + , strand(boost::asio::make_strand(test.ioContext_)) { acceptor.listen(); server.endpoint_ = acceptor.local_endpoint(); @@ -261,8 +261,8 @@ private: , test(server.test_) , socket(std::move(inSocket)) , stream(socket, *test.context_) - , strand(boost::asio::make_strand(test.io_context_)) - , timer(test.io_context_) + , strand(boost::asio::make_strand(test.ioContext_)) + , timer(test.ioContext_) { } @@ -450,10 +450,10 @@ private: : Child(client) , client(client) , test(client.test_) - , socket(test.io_context_) + , socket(test.ioContext_) , stream(socket, *test.context_) - , strand(boost::asio::make_strand(test.io_context_)) - , timer(test.io_context_) + , strand(boost::asio::make_strand(test.ioContext_)) + , timer(test.ioContext_) , ep(ep) { } @@ -632,10 +632,10 @@ private: public: short_read_test() - : work_(io_context_.get_executor()) + : work_(ioContext_.get_executor()) , thread_(std::thread([this]() { beast::setCurrentThreadName("io_context"); - this->io_context_.run(); + this->ioContext_.run(); })) , context_(makeSslContext("")) { diff --git a/src/test/overlay/tx_reduce_relay_test.cpp b/src/test/overlay/tx_reduce_relay_test.cpp index e053774108..a0d91d3aed 100644 --- a/src/test/overlay/tx_reduce_relay_test.cpp +++ b/src/test/overlay/tx_reduce_relay_test.cpp @@ -81,10 +81,10 @@ private: { c.loadFromString(str.str()); - BEAST_EXPECT(c.TX_REDUCE_RELAY_ENABLE == enable); - BEAST_EXPECT(c.TX_REDUCE_RELAY_METRICS == metrics); - BEAST_EXPECT(c.TX_REDUCE_RELAY_MIN_PEERS == min); - BEAST_EXPECT(c.TX_RELAY_PERCENTAGE == pct); + BEAST_EXPECT(c.txReduceRelayEnable == enable); + BEAST_EXPECT(c.txReduceRelayMetrics == metrics); + BEAST_EXPECT(c.txReduceRelayMinPeers == min); + BEAST_EXPECT(c.txRelayPercentage == pct); if (success) { pass(); @@ -173,7 +173,7 @@ private: std::uint16_t rid_{1}; shared_context context_; ProtocolVersion protocolVersion_; - boost::beast::multi_buffer read_buf_; + boost::beast::multi_buffer readBuf_; public: tx_reduce_relay_test() : context_(makeSslContext("")), protocolVersion_{1, 7} @@ -232,9 +232,9 @@ private: testcase(test); jtx::Env env(*this); std::vector> peers; - env.app().config().TX_REDUCE_RELAY_ENABLE = txRREnabled; - env.app().config().TX_REDUCE_RELAY_MIN_PEERS = minPeers; - env.app().config().TX_RELAY_PERCENTAGE = relayPercentage; + env.app().config().txReduceRelayEnable = txRREnabled; + env.app().config().txReduceRelayMinPeers = minPeers; + env.app().config().txRelayPercentage = relayPercentage; PeerTest::init(); lid_ = 0; rid_ = 0; diff --git a/src/test/peerfinder/PeerFinder_test.cpp b/src/test/peerfinder/PeerFinder_test.cpp index 2e4ab001b4..c4f129c1a3 100644 --- a/src/test/peerfinder/PeerFinder_test.cpp +++ b/src/test/peerfinder/PeerFinder_test.cpp @@ -421,8 +421,8 @@ public: c.loadFromString(toLoad); BEAST_EXPECT( - (c.PEERS_MAX == max && c.PEERS_IN_MAX == 0 && c.PEERS_OUT_MAX == 0) || - (c.PEERS_IN_MAX == *maxIn && c.PEERS_OUT_MAX == *maxOut)); + (c.peersMax == max && c.peersInMax == 0 && c.peersOutMax == 0) || + (c.peersInMax == *maxIn && c.peersOutMax == *maxOut)); Config const config = Config::makeConfig(c, port, false, 0, true); diff --git a/src/test/rpc/AccountTx_test.cpp b/src/test/rpc/AccountTx_test.cpp index 5d32eac8dc..421f6bd1fa 100644 --- a/src/test/rpc/AccountTx_test.cpp +++ b/src/test/rpc/AccountTx_test.cpp @@ -131,7 +131,7 @@ class AccountTx_test : public beast::unit_test::Suite using namespace test::jtx; Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; return cfg; })); Account const a1{"A1"}; @@ -821,7 +821,7 @@ class AccountTx_test : public beast::unit_test::Suite using namespace std::chrono_literals; auto cfg = makeConfig(); - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; Env env(*this, std::move(cfg)); Account const alice{"alice"}; diff --git a/src/test/rpc/Book_test.cpp b/src/test/rpc/Book_test.cpp index bde55d4985..83f7b64b4b 100644 --- a/src/test/rpc/Book_test.cpp +++ b/src/test/rpc/Book_test.cpp @@ -1593,7 +1593,7 @@ public: auto const carol = permDex.carol; auto const domainID = permDex.domainID; auto const gw = permDex.gw; - auto const usd = permDex.USD; + auto const usd = permDex.usd; auto wsc = makeWSClient(env.app().config()); @@ -1718,7 +1718,7 @@ public: auto const carol = permDex.carol; auto const domainID = permDex.domainID; auto const gw = permDex.gw; - auto const usd = permDex.USD; + auto const usd = permDex.usd; auto wsc = makeWSClient(env.app().config()); diff --git a/src/test/rpc/DeliveredAmount_test.cpp b/src/test/rpc/DeliveredAmount_test.cpp index 7daf05aaf1..ca5df7102e 100644 --- a/src/test/rpc/DeliveredAmount_test.cpp +++ b/src/test/rpc/DeliveredAmount_test.cpp @@ -206,7 +206,7 @@ class DeliveredAmount_test : public beast::unit_test::Suite for (bool const afterSwitchTime : {true, false}) { auto cfg = envconfig(); - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; Env env(*this, std::move(cfg)); env.fund(XRP(10000), alice, bob, carol, gw); env.trust(usd(1000), alice, bob, carol); @@ -297,7 +297,7 @@ class DeliveredAmount_test : public beast::unit_test::Suite for (bool const afterSwitchTime : {true, false}) { auto cfg = envconfig(); - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; Env env(*this, std::move(cfg)); env.fund(XRP(10000), alice, bob, carol, gw); env.trust(usd(1000), alice, bob, carol); diff --git a/src/test/rpc/JSONRPC_test.cpp b/src/test/rpc/JSONRPC_test.cpp index 10e4daf933..1f24d229f2 100644 --- a/src/test/rpc/JSONRPC_test.cpp +++ b/src/test/rpc/JSONRPC_test.cpp @@ -2697,7 +2697,7 @@ public: testcase("autofill NetworkID"); using namespace test::jtx; Env env{*this, envconfig([&](std::unique_ptr cfg) { - cfg->NETWORK_ID = 1025; + cfg->networkId = 1025; return cfg; })}; @@ -2743,7 +2743,7 @@ public: // "c" (phantom signer) is rPcNzota6B8YBokhYtcTNqQVCngtbnWfux. Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; return cfg; })); env.fund(XRP(100000), a, ed, g); diff --git a/src/test/rpc/KeyGeneration_test.cpp b/src/test/rpc/KeyGeneration_test.cpp index bb1f95bef1..aafe6f75a5 100644 --- a/src/test/rpc/KeyGeneration_test.cpp +++ b/src/test/rpc/KeyGeneration_test.cpp @@ -19,15 +19,15 @@ namespace xrpl::RPC { struct KeyStrings { - char const* account_id; - char const* master_key; - char const* master_seed; - char const* master_seed_hex; - char const* public_key; - char const* public_key_hex; - char const* secret_key_hex; + char const* accountId; + char const* masterKey; + char const* masterSeed; + char const* masterSeedHex; + char const* publicKey; + char const* publicKeyHex; + char const* secretKeyHex; char const* passphrase; - char const* passphrase_warning; + char const* passphraseWarning; }; namespace common { @@ -38,45 +38,45 @@ static char const* gMasterSeedHex = "BE6A670A19B209E112146D0A7ED2AAD7"; } // namespace common static KeyStrings const kSecP256K1Strings = { - .account_id = "r4Vtj2jrfmTVZGfSP3gH9hQPMqFPQFin8f", - .master_key = common::gMasterKey, - .master_seed = common::gMasterSeed, - .master_seed_hex = common::gMasterSeedHex, - .public_key = "aBQxK2YFNqzmAaXNczYcjqDjfiKkLsJUizsr1UBf44RCF8FHdrmX", - .public_key_hex = "038AAE247B2344B1837FBED8F57389C8C11774510A3F7D784F2A09F0CB6843236C", - .secret_key_hex = "1949ECD889EA71324BC7A30C8E81F4E93CB73EE19D59E9082111E78CC3DDABC2", + .accountId = "r4Vtj2jrfmTVZGfSP3gH9hQPMqFPQFin8f", + .masterKey = common::gMasterKey, + .masterSeed = common::gMasterSeed, + .masterSeedHex = common::gMasterSeedHex, + .publicKey = "aBQxK2YFNqzmAaXNczYcjqDjfiKkLsJUizsr1UBf44RCF8FHdrmX", + .publicKeyHex = "038AAE247B2344B1837FBED8F57389C8C11774510A3F7D784F2A09F0CB6843236C", + .secretKeyHex = "1949ECD889EA71324BC7A30C8E81F4E93CB73EE19D59E9082111E78CC3DDABC2", .passphrase = common::gPassphrase, - .passphrase_warning = + .passphraseWarning = "This wallet was generated using a user-supplied " "passphrase that has low entropy and is vulnerable " "to brute-force attacks.", }; static KeyStrings const kED25519Strings = { - .account_id = "r4qV6xTXerqaZav3MJfSY79ynmc1BSBev1", - .master_key = common::gMasterKey, - .master_seed = common::gMasterSeed, - .master_seed_hex = common::gMasterSeedHex, - .public_key = "aKEQmgLMyZPMruJFejUuedp169LgW6DbJt1rej1DJ5hWUMH4pHJ7", - .public_key_hex = "ED54C3F5BEDA8BD588B203D23A27398FAD9D20F88A974007D6994659CD7273FE1D", - .secret_key_hex = "77AAED2698D56D6676323629160F4EEF21CFD9EE3D0745CC78FA291461F98278", + .accountId = "r4qV6xTXerqaZav3MJfSY79ynmc1BSBev1", + .masterKey = common::gMasterKey, + .masterSeed = common::gMasterSeed, + .masterSeedHex = common::gMasterSeedHex, + .publicKey = "aKEQmgLMyZPMruJFejUuedp169LgW6DbJt1rej1DJ5hWUMH4pHJ7", + .publicKeyHex = "ED54C3F5BEDA8BD588B203D23A27398FAD9D20F88A974007D6994659CD7273FE1D", + .secretKeyHex = "77AAED2698D56D6676323629160F4EEF21CFD9EE3D0745CC78FA291461F98278", .passphrase = common::gPassphrase, - .passphrase_warning = + .passphraseWarning = "This wallet was generated using a user-supplied " "passphrase that has low entropy and is vulnerable " "to brute-force attacks.", }; static KeyStrings const kStrongBrainStrings = { - .account_id = "rBcvXmNb7KPkNdMkpckdWPpbvkWgcV3nir", - .master_key = "TED AVON CAVE HOUR BRAG JEFF RIFT NEAL TOLD FAT SEW SAN", - .master_seed = "shKdhWka8hS7Es3bpctCZXBiAwfUN", - .master_seed_hex = "74BA8389B44F98CF41E795CD91F9C93F", - .public_key = "aBRL2sqVuzrsM6zikPB4v8UBHGn1aKkrsxhYEffhcQxB2LKyywE5", - .public_key_hex = "03BD334FB9E06C58D69603E9922686528B18A754BC2F2E1ADA095FFE67DE952C64", - .secret_key_hex = "84262FB16AA25BE407174C7EDAB531220C30FA4D8A28AA9D564673FB3D34502C", + .accountId = "rBcvXmNb7KPkNdMkpckdWPpbvkWgcV3nir", + .masterKey = "TED AVON CAVE HOUR BRAG JEFF RIFT NEAL TOLD FAT SEW SAN", + .masterSeed = "shKdhWka8hS7Es3bpctCZXBiAwfUN", + .masterSeedHex = "74BA8389B44F98CF41E795CD91F9C93F", + .publicKey = "aBRL2sqVuzrsM6zikPB4v8UBHGn1aKkrsxhYEffhcQxB2LKyywE5", + .publicKeyHex = "03BD334FB9E06C58D69603E9922686528B18A754BC2F2E1ADA095FFE67DE952C64", + .secretKeyHex = "84262FB16AA25BE407174C7EDAB531220C30FA4D8A28AA9D564673FB3D34502C", .passphrase = "A4yKIRGdzrw0YQ$2%TFKYG9HP*&ok^!sy7E@RwICs", - .passphrase_warning = + .passphraseWarning = "This wallet was generated using a user-supplied " "passphrase. It may be vulnerable to brute-force " "attacks.", @@ -120,11 +120,11 @@ public: json::Value result = walletPropose(params); BEAST_EXPECT(!containsError(result)); - expectEquals(result[jss::account_id], s.account_id); - expectEquals(result[jss::master_seed], s.master_seed); - expectEquals(result[jss::master_seed_hex], s.master_seed_hex); - expectEquals(result[jss::public_key], s.public_key); - expectEquals(result[jss::public_key_hex], s.public_key_hex); + expectEquals(result[jss::account_id], s.accountId); + expectEquals(result[jss::master_seed], s.masterSeed); + expectEquals(result[jss::master_seed_hex], s.masterSeedHex); + expectEquals(result[jss::public_key], s.publicKey); + expectEquals(result[jss::public_key_hex], s.publicKeyHex); expectEquals( result[jss::key_type], params.isMember(jss::key_type) ? params[jss::key_type] : "secp256k1"); @@ -139,7 +139,7 @@ public: json::Value params; if (keyType) params[jss::key_type] = *keyType; - params[jss::seed] = strings.master_seed; + params[jss::seed] = strings.masterSeed; auto const wallet = testSecretWallet(params, strings); BEAST_EXPECT(!wallet.isMember(jss::warning)); @@ -153,7 +153,7 @@ public: json::Value params; if (keyType) params[jss::key_type] = *keyType; - params[jss::seed_hex] = strings.master_seed_hex; + params[jss::seed_hex] = strings.masterSeedHex; auto const wallet = testSecretWallet(params, strings); BEAST_EXPECT(!wallet.isMember(jss::warning)); @@ -173,7 +173,7 @@ public: auto const wallet = testSecretWallet(params, strings); if (value == strings.passphrase) { - BEAST_EXPECT(wallet[jss::warning] == strings.passphrase_warning); + BEAST_EXPECT(wallet[jss::warning] == strings.passphraseWarning); } else { @@ -187,9 +187,9 @@ public: testcase("passphrase"); testLegacyPassphrase(strings.passphrase, keyType, strings); - testLegacyPassphrase(strings.master_key, keyType, strings); - testLegacyPassphrase(strings.master_seed, keyType, strings); - testLegacyPassphrase(strings.master_seed_hex, keyType, strings); + testLegacyPassphrase(strings.masterKey, keyType, strings); + testLegacyPassphrase(strings.masterSeed, keyType, strings); + testLegacyPassphrase(strings.masterSeedHex, keyType, strings); } void @@ -205,8 +205,8 @@ public: json::Value params; if (keyType) params[jss::key_type] = *keyType; - params[jss::seed] = strings.master_seed; - params[jss::seed_hex] = strings.master_seed_hex; + params[jss::seed] = strings.masterSeed; + params[jss::seed_hex] = strings.masterSeedHex; // Secret fields are mutually exclusive. BEAST_EXPECT(containsError(walletPropose(params))); @@ -294,7 +294,7 @@ public: { testcase("keypairForSignature - " + (keyType ? *keyType : "no key_type")); - auto const publicKey = parseBase58(TokenType::AccountPublic, strings.public_key); + auto const publicKey = parseBase58(TokenType::AccountPublic, strings.publicKey); BEAST_EXPECT(publicKey); if (!keyType) @@ -302,7 +302,7 @@ public: { json::Value params; json::Value error; - params[jss::secret] = strings.master_seed; + params[jss::secret] = strings.masterSeed; auto ret = keypairForSignature(params, error); BEAST_EXPECT(!containsError(error)); @@ -316,7 +316,7 @@ public: { json::Value params; json::Value error; - params[jss::secret] = strings.master_seed_hex; + params[jss::secret] = strings.masterSeedHex; auto ret = keypairForSignature(params, error); BEAST_EXPECT(!containsError(error)); @@ -330,7 +330,7 @@ public: { json::Value params; json::Value error; - params[jss::secret] = strings.master_key; + params[jss::secret] = strings.masterKey; auto ret = keypairForSignature(params, error); BEAST_EXPECT(!containsError(error)); @@ -349,7 +349,7 @@ public: json::Value error; params[jss::key_type] = *keyType; - params[jss::seed] = strings.master_seed; + params[jss::seed] = strings.masterSeed; auto ret = keypairForSignature(params, error); BEAST_EXPECT(!containsError(error)); @@ -365,7 +365,7 @@ public: json::Value error; params[jss::key_type] = *keyType; - params[jss::seed_hex] = strings.master_seed_hex; + params[jss::seed_hex] = strings.masterSeedHex; auto ret = keypairForSignature(params, error); BEAST_EXPECT(!containsError(error)); @@ -381,7 +381,7 @@ public: json::Value error; params[jss::key_type] = *keyType; - params[jss::passphrase] = strings.master_key; + params[jss::passphrase] = strings.masterKey; auto ret = keypairForSignature(params, error); BEAST_EXPECT(!containsError(error)); diff --git a/src/test/rpc/LedgerClosed_test.cpp b/src/test/rpc/LedgerClosed_test.cpp index 81919e04d0..f02d23030d 100644 --- a/src/test/rpc/LedgerClosed_test.cpp +++ b/src/test/rpc/LedgerClosed_test.cpp @@ -23,7 +23,7 @@ public: // This test relies on ledger hash so must lock it to fee 10. auto p = envconfig(); - p->FEES.reference_fee = 10; + p->fees.referenceFee = 10; Env env{*this, std::move(p), FeatureBitset{}}; Account const alice{"alice"}; env.fund(XRP(10000), alice); diff --git a/src/test/rpc/LedgerEntry_test.cpp b/src/test/rpc/LedgerEntry_test.cpp index 0f9421beb2..d231a2d4a0 100644 --- a/src/test/rpc/LedgerEntry_test.cpp +++ b/src/test/rpc/LedgerEntry_test.cpp @@ -555,7 +555,7 @@ class LedgerEntry_test : public beast::unit_test::Suite using namespace test::jtx; auto cfg = envconfig(); - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; Env env{*this, std::move(cfg)}; Account const alice{"alice"}; @@ -2237,7 +2237,7 @@ class LedgerEntry_test : public beast::unit_test::Suite Account const bob{"bob"}; Env env{*this, envconfig([](auto cfg) { - cfg->START_UP = StartUpType::Fresh; + cfg->startUp = StartUpType::Fresh; return cfg; })}; @@ -2430,7 +2430,7 @@ class LedgerEntry_test : public beast::unit_test::Suite Account const bob{"bob"}; Env env{*this, envconfig([](auto cfg) { - cfg->START_UP = StartUpType::Fresh; + cfg->startUp = StartUpType::Fresh; return cfg; })}; diff --git a/src/test/rpc/LedgerRPC_test.cpp b/src/test/rpc/LedgerRPC_test.cpp index f8d7901ec0..f35dddffb1 100644 --- a/src/test/rpc/LedgerRPC_test.cpp +++ b/src/test/rpc/LedgerRPC_test.cpp @@ -268,7 +268,7 @@ class LedgerRPC_test : public beast::unit_test::Suite using namespace test::jtx; auto cfg = envconfig(); - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; Env env{*this, std::move(cfg), FeatureBitset{}}; // hashes requested below // assume no amendments env.fund(XRP(10000), "alice"); @@ -437,7 +437,7 @@ class LedgerRPC_test : public beast::unit_test::Suite return cfg; }); - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; Env env(*this, std::move(cfg)); json::Value jv; diff --git a/src/test/rpc/LedgerRequest_test.cpp b/src/test/rpc/LedgerRequest_test.cpp index 0a2b51dc8b..4759256b96 100644 --- a/src/test/rpc/LedgerRequest_test.cpp +++ b/src/test/rpc/LedgerRequest_test.cpp @@ -149,7 +149,7 @@ public: using namespace test::jtx; auto cfg = envconfig(); - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; Env env{*this, std::move(cfg), FeatureBitset{}}; // the hashes being checked below // assume no amendments Account const gw{"gateway"}; @@ -301,8 +301,8 @@ public: using namespace test::jtx; using namespace std::chrono_literals; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = 10; - cfg->NODE_SIZE = 0; + cfg->fees.referenceFee = 10; + cfg->nodeSize = 0; return cfg; })}; Account const gw{"gateway"}; diff --git a/src/test/rpc/NoRippleCheck_test.cpp b/src/test/rpc/NoRippleCheck_test.cpp index 3793efffcd..9c17d291a1 100644 --- a/src/test/rpc/NoRippleCheck_test.cpp +++ b/src/test/rpc/NoRippleCheck_test.cpp @@ -296,7 +296,7 @@ class NoRippleCheckLimits_test : public beast::unit_test::Suite if (c.balance() > kWarningThreshold) { using ct = beast::AbstractClock; - c.entry().local_balance = + c.entry().localBalance = DecayingSample{steady_clock::now()}; } }; diff --git a/src/test/rpc/RPCCall_test.cpp b/src/test/rpc/RPCCall_test.cpp index 66ddfde8e2..cd3cd3cb41 100644 --- a/src/test/rpc/RPCCall_test.cpp +++ b/src/test/rpc/RPCCall_test.cpp @@ -5843,7 +5843,7 @@ makeNetworkConfig(uint32_t networkID) { using namespace test::jtx; return envconfig([&](std::unique_ptr cfg) { - cfg->NETWORK_ID = networkID; + cfg->networkId = networkID; return cfg; }); } diff --git a/src/test/rpc/Simulate_test.cpp b/src/test/rpc/Simulate_test.cpp index 60452e386a..9206bf42ac 100644 --- a/src/test/rpc/Simulate_test.cpp +++ b/src/test/rpc/Simulate_test.cpp @@ -492,7 +492,7 @@ class Simulate_test : public beast::unit_test::Suite using namespace jtx; Env env{*this, envconfig([&](std::unique_ptr cfg) { - cfg->NETWORK_ID = 0; + cfg->networkId = 0; return cfg; })}; static auto const kNewDomain = "123ABC"; @@ -1032,7 +1032,7 @@ class Simulate_test : public beast::unit_test::Suite using namespace jtx; Env env{*this, envconfig([&](std::unique_ptr cfg) { - cfg->NETWORK_ID = 1025; + cfg->networkId = 1025; return cfg; })}; static auto const kNewDomain = "123ABC"; @@ -1097,7 +1097,7 @@ class Simulate_test : public beast::unit_test::Suite using namespace jtx; using namespace std::chrono_literals; Env env{*this, envconfig([&](std::unique_ptr cfg) { - cfg->NETWORK_ID = 1025; + cfg->networkId = 1025; return cfg; })}; diff --git a/src/test/rpc/Subscribe_test.cpp b/src/test/rpc/Subscribe_test.cpp index 3011eb4170..090a599e7c 100644 --- a/src/test/rpc/Subscribe_test.cpp +++ b/src/test/rpc/Subscribe_test.cpp @@ -321,7 +321,7 @@ public: using namespace std::chrono_literals; using namespace jtx; Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; cfg = singleThreadIo(std::move(cfg)); return cfg; })); @@ -1319,7 +1319,7 @@ public: auto const carol = permDex.carol; auto const domainID = permDex.domainID; auto const gw = permDex.gw; - auto const usd = permDex.USD; + auto const usd = permDex.usd; auto wsc = makeWSClient(env.app().config()); diff --git a/src/test/rpc/TransactionEntry_test.cpp b/src/test/rpc/TransactionEntry_test.cpp index c5f562b2b2..8724e2974d 100644 --- a/src/test/rpc/TransactionEntry_test.cpp +++ b/src/test/rpc/TransactionEntry_test.cpp @@ -32,7 +32,7 @@ class TransactionEntry_test : public beast::unit_test::Suite testcase("Invalid request params"); using namespace test::jtx; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; return cfg; })}; @@ -139,7 +139,7 @@ class TransactionEntry_test : public beast::unit_test::Suite testcase("Basic request API version " + std::to_string(apiVersion)); using namespace test::jtx; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; return cfg; })}; diff --git a/src/test/rpc/Transaction_test.cpp b/src/test/rpc/Transaction_test.cpp index 47cc3687b0..8c50736b85 100644 --- a/src/test/rpc/Transaction_test.cpp +++ b/src/test/rpc/Transaction_test.cpp @@ -47,7 +47,7 @@ class Transaction_test : public beast::unit_test::Suite { using namespace test::jtx; return envconfig([&](std::unique_ptr cfg) { - cfg->NETWORK_ID = networkID; + cfg->networkId = networkID; return cfg; }); } @@ -749,7 +749,7 @@ class Transaction_test : public beast::unit_test::Suite using std::to_string; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; return cfg; })}; Account const alice{"alice"}; @@ -827,7 +827,7 @@ class Transaction_test : public beast::unit_test::Suite using std::to_string; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->FEES.reference_fee = 10; + cfg->fees.referenceFee = 10; return cfg; })}; Account const alice{"alice"}; diff --git a/src/test/rpc/Version_test.cpp b/src/test/rpc/Version_test.cpp index 75d74b4155..20740bfe53 100644 --- a/src/test/rpc/Version_test.cpp +++ b/src/test/rpc/Version_test.cpp @@ -65,7 +65,7 @@ class Version_test : public beast::unit_test::Suite "{\"api_version\": " + std::to_string(RPC::kApiMinimumSupportedVersion - 1) + "}"); BEAST_EXPECT(badVersion(re)); - BEAST_EXPECT(env.app().config().BETA_RPC_API); + BEAST_EXPECT(env.app().config().betaRpcApi); re = env.rpc( "json", "version", @@ -160,7 +160,7 @@ class Version_test : public beast::unit_test::Suite using namespace test::jtx; Env env{*this}; - BEAST_EXPECT(env.app().config().BETA_RPC_API); + BEAST_EXPECT(env.app().config().betaRpcApi); auto const withoutApiVerion = std::string("{ ") + "\"jsonrpc\": \"2.0\", " "\"ripplerpc\": \"2.0\", " @@ -194,19 +194,19 @@ class Version_test : public beast::unit_test::Suite testcase("config test"); { Config const c; - BEAST_EXPECT(c.BETA_RPC_API == false); + BEAST_EXPECT(c.betaRpcApi == false); } { Config c; c.loadFromString("\n[beta_rpc_api]\n1\n"); - BEAST_EXPECT(c.BETA_RPC_API == true); + BEAST_EXPECT(c.betaRpcApi == true); } { Config c; c.loadFromString("\n[beta_rpc_api]\n0\n"); - BEAST_EXPECT(c.BETA_RPC_API == false); + BEAST_EXPECT(c.betaRpcApi == false); } } @@ -220,7 +220,7 @@ class Version_test : public beast::unit_test::Suite c->loadFromString("\n[beta_rpc_api]\n1\n"); return c; })}; - if (!BEAST_EXPECT(env.app().config().BETA_RPC_API == true)) + if (!BEAST_EXPECT(env.app().config().betaRpcApi == true)) return; auto jrr = env.rpc( diff --git a/src/test/server/ServerStatus_test.cpp b/src/test/server/ServerStatus_test.cpp index eba36462b6..6569a2d2a4 100644 --- a/src/test/server/ServerStatus_test.cpp +++ b/src/test/server/ServerStatus_test.cpp @@ -843,7 +843,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); // with ELB_SUPPORT, status still does not indicate a problem - env.app().config().ELB_SUPPORT = true; + env.app().config().elbSupport = true; doRequest( yield, @@ -973,7 +973,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); - env.app().config().ELB_SUPPORT = true; + env.app().config().elbSupport = true; doRequest( yield, @@ -1111,7 +1111,7 @@ 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->ELB_SUPPORT = true; + cfg->elbSupport = true; return cfg; })}; diff --git a/src/test/server/Server_test.cpp b/src/test/server/Server_test.cpp index 1dc40f6337..263fb9451f 100644 --- a/src/test/server/Server_test.cpp +++ b/src/test/server/Server_test.cpp @@ -48,15 +48,15 @@ public: class TestThread { private: - boost::asio::io_context io_context_; + boost::asio::io_context ioContext_; std::optional> work_; std::thread thread_; public: TestThread() - : work_(std::in_place, boost::asio::make_work_guard(io_context_)) - , thread_([&]() { this->io_context_.run(); }) + : work_(std::in_place, boost::asio::make_work_guard(ioContext_)) + , thread_([&]() { this->ioContext_.run(); }) { } @@ -69,7 +69,7 @@ public: boost::asio::io_context& getIoContext() { - return io_context_; + return ioContext_; } }; diff --git a/src/test/unit_test/multi_runner.cpp b/src/test/unit_test/multi_runner.cpp index 60e979299d..3a56d22654 100644 --- a/src/test/unit_test/multi_runner.cpp +++ b/src/test/unit_test/multi_runner.cpp @@ -139,28 +139,28 @@ template std::size_t MultiRunnerBase::Inner::checkoutJobIndex() { - return job_index++; + return jobIndex++; } template std::size_t MultiRunnerBase::Inner::checkoutTestIndex() { - return test_index++; + return testIndex++; } template bool MultiRunnerBase::Inner::anyFailed() const { - return any_failed; + return anyFailedFlag; } template void MultiRunnerBase::Inner::anyFailed(bool v) { - any_failed = any_failed || v; + anyFailedFlag = anyFailedFlag || v; } template @@ -183,14 +183,14 @@ template void MultiRunnerBase::Inner::incKeepAliveCount() { - ++keep_alive; + ++keepAlive; } template std::size_t MultiRunnerBase::Inner::getKeepAliveCount() { - return keep_alive; + return keepAlive; } template @@ -222,7 +222,7 @@ MultiRunnerBase::MultiRunnerBase() boost::interprocess::message_queue::remove(kMessageQueueName); } - shared_mem_ = boost::interprocess::shared_memory_object{ + sharedMem_ = boost::interprocess::shared_memory_object{ std::conditional_t< IsParent, boost::interprocess::create_only_t, @@ -232,8 +232,8 @@ MultiRunnerBase::MultiRunnerBase() if (IsParent) { - shared_mem_.truncate(sizeof(Inner)); - message_queue_ = std::make_unique( + sharedMem_.truncate(sizeof(Inner)); + messageQueue_ = std::make_unique( boost::interprocess::create_only, kMessageQueueName, /*max messages*/ 16, @@ -241,11 +241,11 @@ MultiRunnerBase::MultiRunnerBase() } else { - message_queue_ = std::make_unique( + messageQueue_ = std::make_unique( boost::interprocess::open_only, kMessageQueueName); } - region_ = boost::interprocess::mapped_region{shared_mem_, boost::interprocess::read_write}; + region_ = boost::interprocess::mapped_region{sharedMem_, boost::interprocess::read_write}; if (IsParent) { inner_ = new (region_.get_address()) Inner{}; @@ -340,8 +340,8 @@ MultiRunnerBase::messageQueueSend(MessageType mt, std::string const& s { // must use a mutex since the two "sends" must happen in order std::scoped_lock const l{inner_->m}; - message_queue_->send(&mt, sizeof(mt), /*priority*/ 0); - message_queue_->send(s.c_str(), s.size(), /*priority*/ 0); + messageQueue_->send(&mt, sizeof(mt), /*priority*/ 0); + messageQueue_->send(s.c_str(), s.size(), /*priority*/ 0); } template @@ -376,13 +376,13 @@ namespace test { MultiRunnerParent::MultiRunnerParent() : os_(std::cout) { - message_queue_thread_ = std::thread([this] { + messageQueueThread_ = std::thread([this] { std::vector buf(1 << 20); - while (this->continue_message_queue_ || this->message_queue_->get_num_msg()) + while (this->continueMessageQueue_ || this->messageQueue_->get_num_msg()) { // let children know the parent is still alive this->incKeepAliveCount(); - if (!this->message_queue_->get_num_msg()) + if (!this->messageQueue_->get_num_msg()) { // If a child does not see the keep alive count incremented, // it will assume the parent has died. This sleep time needs @@ -395,13 +395,13 @@ MultiRunnerParent::MultiRunnerParent() : os_(std::cout) { std::size_t recvdSize = 0; unsigned int priority = 0; - this->message_queue_->receive(buf.data(), buf.size(), recvdSize, priority); + this->messageQueue_->receive(buf.data(), buf.size(), recvdSize, priority); if (!recvdSize) continue; assert(recvdSize == 1); MessageType const mt{*reinterpret_cast(buf.data())}; - this->message_queue_->receive(buf.data(), buf.size(), recvdSize, priority); + this->messageQueue_->receive(buf.data(), buf.size(), recvdSize, priority); if (recvdSize) { std::string s{buf.data(), recvdSize}; @@ -412,10 +412,10 @@ MultiRunnerParent::MultiRunnerParent() : os_(std::cout) this->os_.flush(); break; case MessageType::TestStart: - running_suites_.insert(std::move(s)); + runningSuites_.insert(std::move(s)); break; case MessageType::TestEnd: - running_suites_.erase(s); + runningSuites_.erase(s); break; default: assert(0); // unknown message type @@ -440,14 +440,14 @@ MultiRunnerParent::~MultiRunnerParent() { using namespace beast::unit_test; - continue_message_queue_ = false; - message_queue_thread_.join(); + continueMessageQueue_ = false; + messageQueueThread_.join(); - addFailures(running_suites_.size()); + addFailures(runningSuites_.size()); printResults(os_); - for (auto const& s : running_suites_) + for (auto const& s : runningSuites_) { os_ << "\nSuite: " << s << " failed to complete. The child process may have crashed.\n"; } @@ -480,16 +480,13 @@ MultiRunnerParent::addFailures(std::size_t failures) //------------------------------------------------------------------------------ MultiRunnerChild::MultiRunnerChild(std::size_t numJobs, bool quiet, bool printLog) - : job_index_{checkoutJobIndex()} - , num_jobs_{numJobs} - , quiet_{quiet} - , print_log_{!quiet || printLog} + : jobIndex_{checkoutJobIndex()}, numJobs_{numJobs}, quiet_{quiet}, printLog_{!quiet || printLog} { - if (num_jobs_ > 1) + if (numJobs_ > 1) { - keep_alive_thread_ = std::thread([this] { + keepAliveThread_ = std::thread([this] { std::size_t lastCount = getKeepAliveCount(); - while (this->continue_keep_alive_) + while (this->continueKeepAlive_) { // Use a small sleep time so in the normal case the child // process may shutdown quickly. However, to protect against @@ -504,7 +501,7 @@ MultiRunnerChild::MultiRunnerChild(std::size_t numJobs, bool quiet, bool printLo if (curCount == lastCount) { // assume parent process is no longer alive - std::cerr << "multi_runner_child " << job_index_ + std::cerr << "multi_runner_child " << jobIndex_ << ": Assuming parent died, exiting.\n"; std::exit(EXIT_FAILURE); } @@ -517,10 +514,10 @@ MultiRunnerChild::MultiRunnerChild(std::size_t numJobs, bool quiet, bool printLo MultiRunnerChild::~MultiRunnerChild() { - if (num_jobs_ > 1) + if (numJobs_ > 1) { - continue_keep_alive_ = false; - keep_alive_thread_.join(); + continueKeepAlive_ = false; + keepAliveThread_.join(); } add(results_); @@ -548,75 +545,74 @@ MultiRunnerChild::addFailures(std::size_t failures) void MultiRunnerChild::onSuiteBegin(beast::unit_test::SuiteInfo const& info) { - suite_results_ = detail::SuiteResults{info.fullName()}; - messageQueueSend(MessageType::TestStart, suite_results_.name); + suiteResults_ = detail::SuiteResults{info.fullName()}; + messageQueueSend(MessageType::TestStart, suiteResults_.name); } void MultiRunnerChild::onSuiteEnd() { - if (print_log_ || suite_results_.failed > 0) + if (printLog_ || suiteResults_.failed > 0) { std::stringstream s; - if (num_jobs_ > 1) - s << job_index_ << "> "; - s << (suite_results_.failed > 0 ? "failed: " : "") << suite_results_.name << " had " - << suite_results_.failed << " failures." << std::endl; + if (numJobs_ > 1) + s << jobIndex_ << "> "; + s << (suiteResults_.failed > 0 ? "failed: " : "") << suiteResults_.name << " had " + << suiteResults_.failed << " failures." << std::endl; messageQueueSend(MessageType::Log, s.str()); } - results_.add(suite_results_); - messageQueueSend(MessageType::TestEnd, suite_results_.name); + results_.add(suiteResults_); + messageQueueSend(MessageType::TestEnd, suiteResults_.name); } void MultiRunnerChild::onCaseBegin(std::string const& name) { - case_results_ = detail::CaseResults(name); + caseResults_ = detail::CaseResults(name); if (quiet_) return; std::stringstream s; - if (num_jobs_ > 1) - s << job_index_ << "> "; - s << suite_results_.name << (case_results_.name.empty() ? "" : (" " + case_results_.name)) - << '\n'; + if (numJobs_ > 1) + s << jobIndex_ << "> "; + s << suiteResults_.name << (caseResults_.name.empty() ? "" : (" " + caseResults_.name)) << '\n'; messageQueueSend(MessageType::Log, s.str()); } void MultiRunnerChild::onCaseEnd() { - suite_results_.add(case_results_); + suiteResults_.add(caseResults_); } void MultiRunnerChild::onPass() { - ++case_results_.total; + ++caseResults_.total; } void MultiRunnerChild::onFail(std::string const& reason) { - ++case_results_.failed; - ++case_results_.total; + ++caseResults_.failed; + ++caseResults_.total; std::stringstream s; - if (num_jobs_ > 1) - s << job_index_ << "> "; - s << "#" << case_results_.total << " failed" << (reason.empty() ? "" : ": ") << reason << '\n'; + if (numJobs_ > 1) + s << jobIndex_ << "> "; + s << "#" << caseResults_.total << " failed" << (reason.empty() ? "" : ": ") << reason << '\n'; messageQueueSend(MessageType::Log, s.str()); } void MultiRunnerChild::onLog(std::string const& msg) { - if (!print_log_) + if (!printLog_) return; std::stringstream s; - if (num_jobs_ > 1) - s << job_index_ << "> "; + if (numJobs_ > 1) + s << jobIndex_ << "> "; s << msg; messageQueueSend(MessageType::Log, s.str()); } diff --git a/src/test/unit_test/multi_runner.h b/src/test/unit_test/multi_runner.h index 5ebc8ec0a8..8b07559e8c 100644 --- a/src/test/unit_test/multi_runner.h +++ b/src/test/unit_test/multi_runner.h @@ -87,14 +87,14 @@ class MultiRunnerBase // way they communicate is through message queues. struct Inner { - std::atomic job_index{0}; - std::atomic test_index{0}; - std::atomic any_failed{false}; - // A parent process will periodically increment `keep_alive_`. The child - // processes will check if `keep_alive_` is being incremented. If it is + std::atomic jobIndex{0}; + std::atomic testIndex{0}; + std::atomic anyFailedFlag{false}; + // A parent process will periodically increment `keepAlive`. The child + // processes will check if `keepAlive` is being incremented. If it is // not incremented for a sufficiently long time, the child will assume // the parent process has died. - std::atomic keep_alive{0}; + std::atomic keepAlive{0}; mutable boost::interprocess::interprocess_mutex m; detail::Results results; @@ -139,11 +139,11 @@ class MultiRunnerBase // `inner_` will be created in shared memory Inner* inner_; // shared memory to use for the `inner` member - boost::interprocess::shared_memory_object shared_mem_; + boost::interprocess::shared_memory_object sharedMem_; boost::interprocess::mapped_region region_; protected: - std::unique_ptr message_queue_; + std::unique_ptr messageQueue_; enum class MessageType : std::uint8_t { TestStart, TestEnd, Log }; void @@ -201,10 +201,10 @@ class MultiRunnerParent : private detail::MultiRunnerBase private: // message_queue_ is used to collect log messages from the children std::ostream& os_; - std::atomic continue_message_queue_{true}; - std::thread message_queue_thread_; + std::atomic continueMessageQueue_{true}; + std::thread messageQueueThread_; // track running suites so if a child crashes the culprit can be flagged - std::set running_suites_; + std::set runningSuites_; public: MultiRunnerParent(MultiRunnerParent const&) = delete; @@ -235,16 +235,16 @@ class MultiRunnerChild : public beast::unit_test::Runner, private detail::MultiRunnerBase { private: - std::size_t job_index_; + std::size_t jobIndex_; detail::Results results_; - detail::SuiteResults suite_results_; - detail::CaseResults case_results_; - std::size_t num_jobs_{0}; + detail::SuiteResults suiteResults_; + detail::CaseResults caseResults_; + std::size_t numJobs_{0}; bool quiet_{false}; - bool print_log_{true}; + bool printLog_{true}; - std::atomic continue_keep_alive_{true}; - std::thread keep_alive_thread_; + std::atomic continueKeepAlive_{true}; + std::thread keepAliveThread_; public: MultiRunnerChild(MultiRunnerChild const&) = delete; @@ -318,12 +318,12 @@ MultiRunnerChild::runMulti(Pred pred) } catch (...) { - if (num_jobs_ <= 1) + if (numJobs_ <= 1) throw; // a single process can die // inform the parent std::stringstream s; - s << job_index_ << "> failed Unhandled exception in test.\n"; + s << jobIndex_ << "> failed Unhandled exception in test.\n"; messageQueueSend(MessageType::Log, s.str()); failed = true; } diff --git a/src/xrpld/app/ledger/LedgerHistory.cpp b/src/xrpld/app/ledger/LedgerHistory.cpp index f251f25620..8520fc941f 100644 --- a/src/xrpld/app/ledger/LedgerHistory.cpp +++ b/src/xrpld/app/ledger/LedgerHistory.cpp @@ -36,14 +36,14 @@ namespace xrpl { LedgerHistory::LedgerHistory(beast::insight::Collector::ptr const& collector, Application& app) : app_(app) , collector_(collector) - , mismatch_counter_(collector->makeCounter("ledger.history", "mismatch")) - , ledgers_by_hash_( + , mismatchCounter_(collector->makeCounter("ledger.history", "mismatch")) + , ledgersByHash_( "LedgerCache", app_.config().getValueFor(SizedItem::LedgerSize), std::chrono::seconds{app_.config().getValueFor(SizedItem::LedgerAge)}, stopwatch(), app_.getJournal("TaggedCache")) - , consensus_validated_( + , consensusValidated_( "ConsensusValidated", 64, std::chrono::minutes{5}, @@ -62,10 +62,9 @@ LedgerHistory::insert(std::shared_ptr const& ledger, bool validate XRPL_ASSERT( ledger->stateMap().getHash().isNonZero(), "xrpl::LedgerHistory::insert : nonzero hash"); - std::unique_lock const sl(ledgers_by_hash_.peekMutex()); + std::unique_lock const sl(ledgersByHash_.peekMutex()); - bool const alreadyHad = - ledgers_by_hash_.canonicalizeReplaceCache(ledger->header().hash, ledger); + bool const alreadyHad = ledgersByHash_.canonicalizeReplaceCache(ledger->header().hash, ledger); if (validated) ledgersByIndex_[ledger->header().seq] = ledger->header().hash; @@ -75,7 +74,7 @@ LedgerHistory::insert(std::shared_ptr const& ledger, bool validate LedgerHash LedgerHistory::getLedgerHash(LedgerIndex index) { - std::unique_lock const sl(ledgers_by_hash_.peekMutex()); + std::unique_lock const sl(ledgersByHash_.peekMutex()); if (auto it = ledgersByIndex_.find(index); it != ledgersByIndex_.end()) return it->second; return {}; @@ -85,7 +84,7 @@ std::shared_ptr LedgerHistory::getLedgerBySeq(LedgerIndex index) { { - std::unique_lock sl(ledgers_by_hash_.peekMutex()); + std::unique_lock sl(ledgersByHash_.peekMutex()); auto it = ledgersByIndex_.find(index); if (it != ledgersByIndex_.end()) @@ -97,7 +96,7 @@ LedgerHistory::getLedgerBySeq(LedgerIndex index) } Rules const rules{app_.config().features}; - Fees const fees = app_.config().FEES.toFees(); + Fees const fees = app_.config().fees.toFees(); std::shared_ptr ret = loadByIndex(index, rules, fees, app_); if (!ret) @@ -108,11 +107,11 @@ LedgerHistory::getLedgerBySeq(LedgerIndex index) { // Add this ledger to the local tracking by index - std::unique_lock const sl(ledgers_by_hash_.peekMutex()); + std::unique_lock const sl(ledgersByHash_.peekMutex()); XRPL_ASSERT( ret->isImmutable(), "xrpl::LedgerHistory::getLedgerBySeq : immutable result ledger"); - ledgers_by_hash_.canonicalizeReplaceClient(ret->header().hash, ret); + ledgersByHash_.canonicalizeReplaceClient(ret->header().hash, ret); ledgersByIndex_[ret->header().seq] = ret->header().hash; return (ret->header().seq == index) ? ret : nullptr; } @@ -121,7 +120,7 @@ LedgerHistory::getLedgerBySeq(LedgerIndex index) std::shared_ptr LedgerHistory::getLedgerByHash(LedgerHash const& hash) { - auto ret = ledgers_by_hash_.fetch(hash); + auto ret = ledgersByHash_.fetch(hash); if (ret) { @@ -137,7 +136,7 @@ LedgerHistory::getLedgerByHash(LedgerHash const& hash) } Rules const rules{app_.config().features}; - Fees const fees = app_.config().FEES.toFees(); + Fees const fees = app_.config().fees.toFees(); ret = loadByHash(hash, rules, fees, app_); if (!ret) @@ -148,7 +147,7 @@ LedgerHistory::getLedgerByHash(LedgerHash const& hash) XRPL_ASSERT( ret->header().hash == hash, "xrpl::LedgerHistory::getLedgerByHash : loaded ledger hash match"); - ledgers_by_hash_.canonicalizeReplaceClient(ret->header().hash, ret); + ledgersByHash_.canonicalizeReplaceClient(ret->header().hash, ret); XRPL_ASSERT( ret->header().hash == hash, "xrpl::LedgerHistory::getLedgerByHash : result hash match"); @@ -319,7 +318,7 @@ LedgerHistory::handleMismatch( json::Value const& consensus) { XRPL_ASSERT(built != valid, "xrpl::LedgerHistory::handleMismatch : unequal hashes"); - ++mismatch_counter_; + ++mismatchCounter_; auto builtLedger = getLedgerByHash(built); auto validLedger = getLedgerByHash(valid); @@ -430,10 +429,10 @@ LedgerHistory::builtLedger( LedgerHash const hash = ledger->header().hash; XRPL_ASSERT(!hash.isZero(), "xrpl::LedgerHistory::builtLedger : nonzero hash"); - std::unique_lock const sl(consensus_validated_.peekMutex()); + std::unique_lock const sl(consensusValidated_.peekMutex()); auto entry = std::make_shared(); - consensus_validated_.canonicalizeReplaceClient(index, entry); + consensusValidated_.canonicalizeReplaceClient(index, entry); if (entry->validated && !entry->built) { @@ -469,10 +468,10 @@ LedgerHistory::validatedLedger( LedgerHash const hash = ledger->header().hash; XRPL_ASSERT(!hash.isZero(), "xrpl::LedgerHistory::validatedLedger : nonzero hash"); - std::unique_lock const sl(consensus_validated_.peekMutex()); + std::unique_lock const sl(consensusValidated_.peekMutex()); auto entry = std::make_shared(); - consensus_validated_.canonicalizeReplaceClient(index, entry); + consensusValidated_.canonicalizeReplaceClient(index, entry); if (entry->built && !entry->validated) { @@ -504,7 +503,7 @@ LedgerHistory::validatedLedger( bool LedgerHistory::fixIndex(LedgerIndex ledgerIndex, LedgerHash const& ledgerHash) { - std::unique_lock const sl(ledgers_by_hash_.peekMutex()); + std::unique_lock const sl(ledgersByHash_.peekMutex()); auto it = ledgersByIndex_.find(ledgerIndex); if ((it != ledgersByIndex_.end()) && (it->second != ledgerHash)) @@ -518,11 +517,11 @@ LedgerHistory::fixIndex(LedgerIndex ledgerIndex, LedgerHash const& ledgerHash) void LedgerHistory::clearLedgerCachePrior(LedgerIndex seq) { - for (LedgerHash const it : ledgers_by_hash_.getKeys()) + for (LedgerHash const it : ledgersByHash_.getKeys()) { auto const ledger = getLedgerByHash(it); if (!ledger || ledger->header().seq < seq) - ledgers_by_hash_.del(it, false); + ledgersByHash_.del(it, false); } } diff --git a/src/xrpld/app/ledger/LedgerHistory.h b/src/xrpld/app/ledger/LedgerHistory.h index 01c88b1517..057de7b1bc 100644 --- a/src/xrpld/app/ledger/LedgerHistory.h +++ b/src/xrpld/app/ledger/LedgerHistory.h @@ -30,7 +30,7 @@ public: float getCacheHitRate() { - return ledgers_by_hash_.getHitRate(); + return ledgersByHash_.getHitRate(); } /** Get a ledger given its sequence number */ @@ -53,8 +53,8 @@ public: void sweep() { - ledgers_by_hash_.sweep(); - consensus_validated_.sweep(); + ledgersByHash_.sweep(); + consensusValidated_.sweep(); } /** Report that we have locally built a particular ledger */ @@ -99,11 +99,11 @@ private: Application& app_; beast::insight::Collector::ptr collector_; - beast::insight::Counter mismatch_counter_; + beast::insight::Counter mismatchCounter_; using LedgersByHash = TaggedCache; - LedgersByHash ledgers_by_hash_; + LedgersByHash ledgersByHash_; // Maps ledger indexes to the corresponding hashes // For debug and logging purposes @@ -121,7 +121,7 @@ private: std::optional consensus; }; using ConsensusValidated = TaggedCache; - ConsensusValidated consensus_validated_; + ConsensusValidated consensusValidated_; // Maps ledger indexes to the corresponding hash. std::map ledgersByIndex_; // validated ledgers diff --git a/src/xrpld/app/ledger/LedgerMaster.h b/src/xrpld/app/ledger/LedgerMaster.h index 0b3310ea79..885ab6db25 100644 --- a/src/xrpld/app/ledger/LedgerMaster.h +++ b/src/xrpld/app/ledger/LedgerMaster.h @@ -347,20 +347,20 @@ private: bool const standalone_; // How many ledgers before the current ledger do we allow peers to request? - std::uint32_t const fetch_depth_; + std::uint32_t const fetchDepth_; // How much history do we want to keep - std::uint32_t const ledger_history_; + std::uint32_t const ledgerHistorySize_; - std::uint32_t const ledger_fetch_size_; + std::uint32_t const ledgerFetchSize_; - TaggedCache fetch_packs_; + TaggedCache fetchPacks_; - std::uint32_t fetch_seq_{0}; + std::uint32_t fetchSeq_{0}; // Try to keep a validator from switching from test to live network // without first wiping the database. - LedgerIndex const max_ledger_difference_{1000000}; + LedgerIndex const maxLedgerDifference_{1000000}; // Time that the previous upgrade warning was issued. TimeKeeper::time_point upgradeWarningPrevTime_; diff --git a/src/xrpld/app/ledger/OpenLedger.h b/src/xrpld/app/ledger/OpenLedger.h index 884b6b02db..02e073bc9a 100644 --- a/src/xrpld/app/ledger/OpenLedger.h +++ b/src/xrpld/app/ledger/OpenLedger.h @@ -33,8 +33,8 @@ class OpenLedger private: beast::Journal const j_; CachedSLEs& cache_; - std::mutex mutable modify_mutex_; - std::mutex mutable current_mutex_; + std::mutex mutable modifyMutex_; + std::mutex mutable currentMutex_; std::shared_ptr current_; public: diff --git a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp index 7613aab85a..9f2db9d2f2 100644 --- a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp +++ b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp @@ -286,7 +286,7 @@ private: } Rules const rules{app_.config().features}; - Fees const fees = app_.config().FEES.toFees(); + Fees const fees = app_.config().fees.toFees(); auto const dbLedger = loadByIndex(ledgerIndex, rules, fees, app_); if (!dbLedger || (dbLedger->header().hash != ledgerHash) || (dbLedger->header().parentHash != nodeLedger->header().parentHash)) diff --git a/src/xrpld/app/ledger/detail/LedgerMaster.cpp b/src/xrpld/app/ledger/detail/LedgerMaster.cpp index 50a3a6289c..9baad0ec90 100644 --- a/src/xrpld/app/ledger/detail/LedgerMaster.cpp +++ b/src/xrpld/app/ledger/detail/LedgerMaster.cpp @@ -127,10 +127,10 @@ LedgerMaster::LedgerMaster( , journal_(journal) , ledgerHistory_(collector, app) , standalone_(app_.config().standalone()) - , fetch_depth_(app_.getSHAMapStore().clampFetchDepth(app_.config().FETCH_DEPTH)) - , ledger_history_(app_.config().LEDGER_HISTORY) - , ledger_fetch_size_(app_.config().getValueFor(SizedItem::LedgerFetch)) - , fetch_packs_( + , fetchDepth_(app_.getSHAMapStore().clampFetchDepth(app_.config().fetchDepth)) + , ledgerHistorySize_(app_.config().ledgerHistory) + , ledgerFetchSize_(app_.config().getValueFor(SizedItem::LedgerFetch)) + , fetchPacks_( "FetchPack", 65536, std::chrono::seconds{45}, @@ -286,9 +286,9 @@ LedgerMaster::setValidLedger(std::shared_ptr const& l) validLedgerSign_ = signTime.time_since_epoch().count(); XRPL_ASSERT( validLedgerSeq_ || !app_.getMaxDisallowedLedger() || - l->header().seq + max_ledger_difference_ > app_.getMaxDisallowedLedger(), + l->header().seq + maxLedgerDifference_ > app_.getMaxDisallowedLedger(), "xrpl::LedgerMaster::setValidLedger : valid ledger sequence"); - (void)max_ledger_difference_; + (void)maxLedgerDifference_; validLedgerSeq_ = l->header().seq; app_.getOPs().updateLocalTx(*l); @@ -629,9 +629,9 @@ LedgerMaster::getEarliestFetch() // unless that creates a larger range than allowed std::uint32_t e = getClosedLedger()->header().seq; - if (e > fetch_depth_) + if (e > fetchDepth_) { - e -= fetch_depth_; + e -= fetchDepth_; } else { @@ -1277,10 +1277,10 @@ LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl ledger = ledgerHistory_.getLedgerByHash(*hash); } - if (!app_.config().LEDGER_REPLAY) + if (!app_.config().ledgerReplay) { // Can we try to acquire the ledger we need? - if (!ledger && (++acqCount < ledger_fetch_size_)) + if (!ledger && (++acqCount < ledgerFetchSize_)) { ledger = app_.getInboundLedgers().acquire( *hash, seq, InboundLedger::Reason::GENERIC); @@ -1304,7 +1304,7 @@ LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl << ex.what(); } - if (app_.config().LEDGER_REPLAY) + if (app_.config().ledgerReplay) { /* Narrow down the gap of ledgers, and try to replay them. * When replaying a ledger gap, if the local node has @@ -1737,7 +1737,7 @@ void LedgerMaster::sweep() { ledgerHistory_.sweep(); - fetch_packs_.sweep(); + fetchPacks_.sweep(); } float @@ -1789,11 +1789,11 @@ LedgerMaster::fetchForHistory( if (!app_.getInboundLedgers().isFailure(*hash)) { ledger = app_.getInboundLedgers().acquire(*hash, missing, reason); - if (!ledger && missing != fetch_seq_ && + if (!ledger && missing != fetchSeq_ && missing > app_.getNodeStore().earliestLedgerSeq()) { JLOG(journal_.trace()) << "fetchForHistory want fetch pack " << missing; - fetch_seq_ = missing; + fetchSeq_ = missing; getFetchPack(missing, reason); } else @@ -1833,8 +1833,7 @@ LedgerMaster::fetchForHistory( // Do not fetch ledger sequences lower // than the earliest ledger sequence fetchSz = app_.getNodeStore().earliestLedgerSeq(); - fetchSz = - missing >= fetchSz ? std::min(ledger_fetch_size_, (missing - fetchSz) + 1) : 0; + fetchSz = missing >= fetchSz ? std::min(ledgerFetchSize_, (missing - fetchSz) + 1) : 0; try { for (std::uint32_t i = 0; i < fetchSz; ++i) @@ -1903,7 +1902,7 @@ LedgerMaster::doAdvance(std::unique_lock& sl) if ((fillInProgress_ == 0 || *missing > fillInProgress_) && shouldAcquire( validLedgerSeq_, - ledger_history_, + ledgerHistorySize_, app_.getSHAMapStore().minimumOnline(), *missing, journal_)) @@ -1962,16 +1961,16 @@ LedgerMaster::doAdvance(std::unique_lock& sl) void LedgerMaster::addFetchPack(uint256 const& hash, std::shared_ptr data) { - fetch_packs_.canonicalizeReplaceClient(hash, data); + fetchPacks_.canonicalizeReplaceClient(hash, data); } std::optional LedgerMaster::getFetchPack(uint256 const& hash) { Blob data; - if (fetch_packs_.retrieve(hash, data)) + if (fetchPacks_.retrieve(hash, data)) { - fetch_packs_.del(hash, false); + fetchPacks_.del(hash, false); if (hash == sha512Half(makeSlice(data))) return data; } @@ -2170,7 +2169,7 @@ LedgerMaster::makeFetchPack( std::size_t LedgerMaster::getFetchPackCacheSize() const { - return fetch_packs_.getCacheSize(); + return fetchPacks_.getCacheSize(); } // Returns the minimum ledger sequence in SQL database, if any. diff --git a/src/xrpld/app/ledger/detail/OpenLedger.cpp b/src/xrpld/app/ledger/detail/OpenLedger.cpp index 0694e425e9..3bee4b9d13 100644 --- a/src/xrpld/app/ledger/detail/OpenLedger.cpp +++ b/src/xrpld/app/ledger/detail/OpenLedger.cpp @@ -48,26 +48,26 @@ OpenLedger::OpenLedger( bool OpenLedger::empty() const { - std::scoped_lock const lock(modify_mutex_); + std::scoped_lock const lock(modifyMutex_); return current_->txCount() == 0; } std::shared_ptr OpenLedger::current() const { - std::scoped_lock const lock(current_mutex_); + std::scoped_lock const lock(currentMutex_); return current_; } bool OpenLedger::modify(modify_type const& f) { - std::scoped_lock const lock1(modify_mutex_); + std::scoped_lock const lock1(modifyMutex_); auto next = std::make_shared(*current_); auto const changed = f(*next, j_); if (changed) { - std::scoped_lock const lock2(current_mutex_); + std::scoped_lock const lock2(currentMutex_); current_ = std::move(next); } return changed; @@ -96,7 +96,7 @@ OpenLedger::accept( // Block calls to modify, otherwise // new tx going into the open ledger // would get lost. - std::scoped_lock const lock1(modify_mutex_); + std::scoped_lock const lock1(modifyMutex_); // Apply tx from the current open view if (!current_->txs.empty()) { @@ -154,7 +154,7 @@ OpenLedger::accept( } // Switch to the new open view - std::scoped_lock const lock2(current_mutex_); + std::scoped_lock const lock2(currentMutex_); current_ = std::move(next); } diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index 23fa9865ed..a18462f0f7 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -286,14 +286,14 @@ public: return 1; #else - if (config.IO_WORKERS > 0) - return config.IO_WORKERS; + if (config.ioWorkers > 0) + return config.ioWorkers; auto const cores = std::thread::hardware_concurrency(); // Use a single thread when running on under-provisioned systems // or if we are configured to use minimal resources. - if ((cores == 1) || ((config.NODE_SIZE == 0) && (cores == 2))) + if ((cores == 1) || ((config.nodeSize == 0) && (cores == 2))) return 1; // Otherwise, prefer six threads. @@ -316,7 +316,7 @@ public: // PerfLog must be started before any other threads are launched. , perfLog_( perf::makePerfLog( - perf::setupPerfLog(config_->section("perf"), config_->CONFIG_DIR), + perf::setupPerfLog(config_->section("perf"), config_->configDir), *this, logs_->journal("PerfLog"), [this] { signalStop("PerfLog"); })) @@ -326,22 +326,22 @@ public: , jobQueue_( std::make_unique( [](std::unique_ptr const& config) { - if (config->standalone() && !config->FORCE_MULTI_THREAD) + if (config->standalone() && !config->forceMultiThread) return 1; - if (config->WORKERS) - return config->WORKERS; + if (config->workers) + return config->workers; auto count = static_cast(std::thread::hardware_concurrency()); // Be more aggressive about the number of threads to use // for the job queue if the server is configured as // "large" or "huge" if there are enough cores. - if (config->NODE_SIZE >= 4 && count >= 16) + if (config->nodeSize >= 4 && count >= 16) { count = 6 + std::min(count, 8); } - else if (config->NODE_SIZE >= 3 && count >= 8) + else if (config->nodeSize >= 3 && count >= 8) { count = 4 + std::min(count, 6); } @@ -370,16 +370,16 @@ public: std::chrono::minutes(1), stopwatch(), logs_->journal("CachedSLEs")) - , networkIDService_(std::make_unique(config_->NETWORK_ID)) + , networkIDService_(std::make_unique(config_->networkId)) , validatorKeys_(*config_, journal_) , resourceManager_( Resource::makeManager(collectorManager_->collector(), logs_->journal("Resource"))) , nodeStore_(shaMapStore_->makeNodeStore( - config_->PREFETCH_WORKERS > 0 ? config_->PREFETCH_WORKERS : 4)) + config_->prefetchWorkers > 0 ? config_->prefetchWorkers : 4)) , nodeFamily_(*this, *collectorManager_) , orderBookDB_(makeOrderBookDb( *this, - {.pathSearchMax = config_->PATH_SEARCH_MAX, .standalone = config_->standalone()})) + {.pathSearchMax = config_->pathSearchMax, .standalone = config_->standalone()})) , pathRequestManager_( std::make_unique( *this, @@ -415,8 +415,8 @@ public: *this, stopwatch(), config_->standalone(), - config_->NETWORK_QUORUM, - config_->START_VALID, + config_->networkQuorum, + config_->startValid, *jobQueue_, *ledgerMaster_, validatorKeys_, @@ -435,7 +435,7 @@ public: *timeKeeper_, config_->legacy("database_path"), logs_->journal("ValidatorList"), - config_->VALIDATION_QUORUM)) + config_->validationQuorum)) , validatorSites_(std::make_unique(*this)) , serverHandler_(makeServerHandler( *this, @@ -918,7 +918,7 @@ public: { using namespace std::chrono; sweepTimer_.expires_after( - seconds{config_->SWEEP_INTERVAL.value_or( + seconds{config_->sweepInterval.value_or( config_->getValueFor(SizedItem::SweepInterval))}); sweepTimer_.async_wait(std::move(*optionalCountedHandler)); } @@ -1226,7 +1226,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) amendmentTable_ = makeAmendmentTable( *this, - config().AMENDMENT_MAJORITY_TIME, + config().amendmentMajorityTime, supported, upVoted, downVoted, @@ -1235,7 +1235,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) Pathfinder::initPathTable(); - auto const startUp = config_->START_UP; + auto const startUp = config_->startUp; JLOG(journal_.debug()) << "startUp: " << startUp; if (startUp == StartUpType::Fresh) { @@ -1250,13 +1250,13 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) JLOG(journal_.info()) << "Loading specified Ledger"; if (!loadOldLedger( - config_->START_LEDGER, + config_->startLedger, startUp == StartUpType::Replay, startUp == StartUpType::LoadFile, - config_->TRAP_TX_HASH)) + config_->trapTxHash)) { JLOG(journal_.error()) << "The specified ledger could not be loaded."; - if (config_->FAST_LOAD) + if (config_->fastLoad) { // Fall back to syncing from the network, such as // when there's no existing data. @@ -1282,7 +1282,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) startGenesisLedger(); } - if (auto const& forcedRange = config().FORCED_LEDGER_RANGE_PRESENT) + if (auto const& forcedRange = config().forcedLedgerRangePresent) { ledgerMaster_->setLedgerRangePresent(forcedRange->first, forcedRange->second); } @@ -1328,7 +1328,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) localSigningKey, config().section(SECTION_VALIDATORS).values(), config().section(SECTION_VALIDATOR_LIST_KEYS).values(), - config().VALIDATOR_LIST_THRESHOLD)) + config().validatorListThreshold)) { JLOG(journal_.fatal()) << "Invalid entry in validator configuration."; return false; @@ -1399,7 +1399,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) { // Should this message be here, conceptually? In theory this sort // of message, if displayed, should be displayed from PeerFinder. - if (config_->PEER_PRIVATE && config_->IPS_FIXED.empty()) + if (config_->peerPrivate && config_->ipsFixed.empty()) { JLOG(journal_.warn()) << "No outbound peer connections will be made"; } @@ -1659,14 +1659,14 @@ ApplicationImp::fdRequired() const void ApplicationImp::startGenesisLedger() { - std::vector const initialAmendments = (config_->START_UP == StartUpType::Fresh) + std::vector const initialAmendments = (config_->startUp == StartUpType::Fresh) ? amendmentTable_->getDesired() : std::vector{}; std::shared_ptr const genesis = std::make_shared( kCreateGenesis, Rules{config_->features}, - config_->FEES.toFees(), + config_->fees.toFees(), initialAmendments, nodeFamily_); ledgerMaster_->storeLedger(genesis); @@ -1690,7 +1690,7 @@ ApplicationImp::getLastFullLedger() try { auto const [ledger, seq, hash] = - getLatestLedger(Rules{config_->features}, config_->FEES.toFees(), *this); + getLatestLedger(Rules{config_->features}, config_->fees.toFees(), *this); if (!ledger) return ledger; @@ -1802,7 +1802,7 @@ ApplicationImp::loadLedgerFromFile(std::string const& name) } auto loadLedger = std::make_shared( - seq, closeTime, Rules{config_->features}, config_->FEES.toFees(), nodeFamily_); + seq, closeTime, Rules{config_->features}, config_->fees.toFees(), nodeFamily_); loadLedger->setTotalDrops(totalDrops); for (json::UInt index = 0; index < ledger.get().size(); ++index) @@ -1883,7 +1883,7 @@ ApplicationImp::loadOldLedger( if (hash.parseHex(ledgerID)) { loadLedger = - loadByHash(hash, Rules{config_->features}, config_->FEES.toFees(), *this); + loadByHash(hash, Rules{config_->features}, config_->fees.toFees(), *this); if (!loadLedger) { @@ -1912,7 +1912,7 @@ ApplicationImp::loadOldLedger( if (beast::lexicalCastChecked(index, ledgerID)) { loadLedger = - loadByIndex(index, Rules{config_->features}, config_->FEES.toFees(), *this); + loadByIndex(index, Rules{config_->features}, config_->fees.toFees(), *this); } } @@ -1931,7 +1931,7 @@ ApplicationImp::loadOldLedger( loadLedger = loadByHash( replayLedger->header().parentHash, Rules{config_->features}, - config_->FEES.toFees(), + config_->fees.toFees(), *this); if (!loadLedger) { @@ -2078,7 +2078,7 @@ ApplicationImp::loadOldLedger( bool ApplicationImp::serverOkay(std::string& reason) { - if (!config().ELB_SUPPORT) + if (!config().elbSupport) return true; if (isStopping()) diff --git a/src/xrpld/app/main/BasicApp.cpp b/src/xrpld/app/main/BasicApp.cpp index 71138c6517..c530c170cb 100644 --- a/src/xrpld/app/main/BasicApp.cpp +++ b/src/xrpld/app/main/BasicApp.cpp @@ -9,14 +9,14 @@ BasicApp::BasicApp(std::size_t numberOfThreads) { - work_.emplace(boost::asio::make_work_guard(io_context_)); + work_.emplace(boost::asio::make_work_guard(ioContext_)); threads_.reserve(numberOfThreads); for (std::size_t i = 0; i < numberOfThreads; ++i) { threads_.emplace_back([this, i]() { beast::setCurrentThreadName("io svc #" + std::to_string(i)); - this->io_context_.run(); + this->ioContext_.run(); }); } } diff --git a/src/xrpld/app/main/BasicApp.h b/src/xrpld/app/main/BasicApp.h index d55ab858db..5ba7c719e3 100644 --- a/src/xrpld/app/main/BasicApp.h +++ b/src/xrpld/app/main/BasicApp.h @@ -12,7 +12,7 @@ class BasicApp private: std::optional> work_; std::vector threads_; - boost::asio::io_context io_context_; + boost::asio::io_context ioContext_; public: BasicApp(std::size_t numberOfThreads); @@ -21,7 +21,7 @@ public: boost::asio::io_context& getIoContext() { - return io_context_; + return ioContext_; } [[nodiscard]] size_t diff --git a/src/xrpld/app/main/Main.cpp b/src/xrpld/app/main/Main.cpp index ed1d3333d8..f470a2d80f 100644 --- a/src/xrpld/app/main/Main.cpp +++ b/src/xrpld/app/main/Main.cpp @@ -627,7 +627,7 @@ run(int argc, char** argv) { throw std::runtime_error("Invalid force_ledger_present_range parameter"); } - config->FORCED_LEDGER_RANGE_PRESENT.emplace(r[0], r[1]); + config->forcedLedgerRangePresent.emplace(r[0], r[1]); } else { @@ -646,7 +646,7 @@ run(int argc, char** argv) if (vm.contains("start")) { - config->START_UP = StartUpType::Fresh; + config->startUp = StartUpType::Fresh; } if (vm.contains("import")) @@ -654,17 +654,17 @@ run(int argc, char** argv) if (vm.contains("ledger")) { - config->START_LEDGER = vm["ledger"].as(); + config->startLedger = vm["ledger"].as(); if (vm.contains("replay")) { - config->START_UP = StartUpType::Replay; + config->startUp = StartUpType::Replay; if (vm.contains("trap_tx_hash")) { uint256 tmp = {}; auto hash = vm["trap_tx_hash"].as(); if (tmp.parseHex(hash)) { - config->TRAP_TX_HASH = tmp; + config->trapTxHash = tmp; } else { @@ -677,17 +677,17 @@ run(int argc, char** argv) } else { - config->START_UP = StartUpType::Load; + config->startUp = StartUpType::Load; } } else if (vm.contains("ledgerfile")) { - config->START_LEDGER = vm["ledgerfile"].as(); - config->START_UP = StartUpType::LoadFile; + config->startLedger = vm["ledgerfile"].as(); + config->startUp = StartUpType::LoadFile; } - else if (vm.contains("load") || config->FAST_LOAD) + else if (vm.contains("load") || config->fastLoad) { - config->START_UP = StartUpType::Load; + config->startUp = StartUpType::Load; } if (vm.contains("trap_tx_hash") && !vm.contains("replay")) @@ -696,20 +696,20 @@ run(int argc, char** argv) return -1; } - if (vm.contains("net") && !config->FAST_LOAD) + if (vm.contains("net") && !config->fastLoad) { - if ((config->START_UP == StartUpType::Load) || (config->START_UP == StartUpType::Replay)) + if ((config->startUp == StartUpType::Load) || (config->startUp == StartUpType::Replay)) { std::cerr << "Net and load/replay options are incompatible" << std::endl; return -1; } - config->START_UP = StartUpType::Network; + config->startUp = StartUpType::Network; } if (vm.contains("valid")) { - config->START_VALID = true; + config->startValid = true; } // Override the RPC destination IP address. This must @@ -747,15 +747,15 @@ run(int argc, char** argv) } } - config->rpc_ip = std::move(*endpoint); + config->rpcIp = std::move(*endpoint); } if (vm.contains("quorum")) { try { - config->VALIDATION_QUORUM = vm["quorum"].as(); - if (config->VALIDATION_QUORUM == std::size_t{}) + config->validationQuorum = vm["quorum"].as(); + if (config->validationQuorum == std::size_t{}) { throw std::domain_error("0"); } diff --git a/src/xrpld/app/misc/FeeVoteImpl.cpp b/src/xrpld/app/misc/FeeVoteImpl.cpp index 0a55c20d29..c4e6c3cdc2 100644 --- a/src/xrpld/app/misc/FeeVoteImpl.cpp +++ b/src/xrpld/app/misc/FeeVoteImpl.cpp @@ -135,13 +135,10 @@ FeeVoteImpl::doValidation(Fees const& lastFees, Rules const& rules, STValidation v[sfield] = target; } }; - vote(lastFees.base, target_.reference_fee, "base fee", sfBaseFeeDrops); - vote(lastFees.reserve, target_.account_reserve, "base reserve", sfReserveBaseDrops); + vote(lastFees.base, target_.referenceFee, "base fee", sfBaseFeeDrops); + vote(lastFees.reserve, target_.accountReserve, "base reserve", sfReserveBaseDrops); vote( - lastFees.increment, - target_.owner_reserve, - "reserve increment", - sfReserveIncrementDrops); + lastFees.increment, target_.ownerReserve, "reserve increment", sfReserveIncrementDrops); } else { @@ -162,11 +159,11 @@ FeeVoteImpl::doValidation(Fees const& lastFees, Rules const& rules, STValidation } }; - vote(lastFees.base, target_.reference_fee, to64, "base fee", sfBaseFee); - vote(lastFees.reserve, target_.account_reserve, to32, "base reserve", sfReserveBase); + vote(lastFees.base, target_.referenceFee, to64, "base fee", sfBaseFee); + vote(lastFees.reserve, target_.accountReserve, to32, "base reserve", sfReserveBase); vote( lastFees.increment, - target_.owner_reserve, + target_.ownerReserve, to32, "reserve increment", sfReserveIncrement); @@ -184,11 +181,11 @@ FeeVoteImpl::doVoting( lastClosedLedger && isFlagLedger(lastClosedLedger->seq()), "xrpl::FeeVoteImpl::doVoting : has a flag ledger"); - detail::VotableValue baseFeeVote(lastClosedLedger->fees().base, target_.reference_fee); + detail::VotableValue baseFeeVote(lastClosedLedger->fees().base, target_.referenceFee); - detail::VotableValue baseReserveVote(lastClosedLedger->fees().reserve, target_.account_reserve); + detail::VotableValue baseReserveVote(lastClosedLedger->fees().reserve, target_.accountReserve); - detail::VotableValue incReserveVote(lastClosedLedger->fees().increment, target_.owner_reserve); + detail::VotableValue incReserveVote(lastClosedLedger->fees().increment, target_.ownerReserve); auto const& rules = lastClosedLedger->rules(); if (rules.enabled(featureXRPFees)) diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index d6f9d10f05..12c79b821c 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -327,7 +327,7 @@ public: validatorKeys.keys ? validatorKeys.keys->masterPublicKey : decltype(validatorMasterPK_){}) , ledgerMaster_(ledgerMaster) - , job_queue_(jobQueue) + , jobQueue_(jobQueue) , standalone_(standalone) , minPeerCount_(startValid ? 0 : minPeerCount) , stats_(std::bind(&NetworkOPsImp::collectMetrics, this), collector) @@ -828,7 +828,7 @@ private: ServerFeeSummary lastFeeSummary_; - JobQueue& job_queue_; + JobQueue& jobQueue_; // Whether we are in standalone mode. bool const standalone_; @@ -853,34 +853,34 @@ private: template Stats(Handler const& handler, beast::insight::Collector::ptr const& collector) : hook(collector->makeHook(handler)) - , disconnected_duration( + , disconnectedDuration( collector->makeGauge("State_Accounting", "Disconnected_duration")) - , connected_duration(collector->makeGauge("State_Accounting", "Connected_duration")) - , syncing_duration(collector->makeGauge("State_Accounting", "Syncing_duration")) - , tracking_duration(collector->makeGauge("State_Accounting", "Tracking_duration")) - , full_duration(collector->makeGauge("State_Accounting", "Full_duration")) - , disconnected_transitions( + , connectedDuration(collector->makeGauge("State_Accounting", "Connected_duration")) + , syncingDuration(collector->makeGauge("State_Accounting", "Syncing_duration")) + , trackingDuration(collector->makeGauge("State_Accounting", "Tracking_duration")) + , fullDuration(collector->makeGauge("State_Accounting", "Full_duration")) + , disconnectedTransitions( collector->makeGauge("State_Accounting", "Disconnected_transitions")) - , connected_transitions( + , connectedTransitions( collector->makeGauge("State_Accounting", "Connected_transitions")) - , syncing_transitions(collector->makeGauge("State_Accounting", "Syncing_transitions")) - , tracking_transitions(collector->makeGauge("State_Accounting", "Tracking_transitions")) - , full_transitions(collector->makeGauge("State_Accounting", "Full_transitions")) + , syncingTransitions(collector->makeGauge("State_Accounting", "Syncing_transitions")) + , trackingTransitions(collector->makeGauge("State_Accounting", "Tracking_transitions")) + , fullTransitions(collector->makeGauge("State_Accounting", "Full_transitions")) { } beast::insight::Hook hook; - beast::insight::Gauge disconnected_duration; - beast::insight::Gauge connected_duration; - beast::insight::Gauge syncing_duration; - beast::insight::Gauge tracking_duration; - beast::insight::Gauge full_duration; + beast::insight::Gauge disconnectedDuration; + beast::insight::Gauge connectedDuration; + beast::insight::Gauge syncingDuration; + beast::insight::Gauge trackingDuration; + beast::insight::Gauge fullDuration; - beast::insight::Gauge disconnected_transitions; - beast::insight::Gauge connected_transitions; - beast::insight::Gauge syncing_transitions; - beast::insight::Gauge tracking_transitions; - beast::insight::Gauge full_transitions; + beast::insight::Gauge disconnectedTransitions; + beast::insight::Gauge connectedTransitions; + beast::insight::Gauge syncingTransitions; + beast::insight::Gauge trackingTransitions; + beast::insight::Gauge fullTransitions; }; std::mutex statsMutex_; // Mutex to lock stats_ @@ -990,7 +990,7 @@ NetworkOPsImp::setTimer( // Only start the timer if waitHandlerCounter_ is not yet joined. if (auto optionalCountedHandler = waitHandlerCounter_.wrap([this, onExpire, onError](boost::system::error_code const& e) { - if ((e.value() == boost::system::errc::success) && (!job_queue_.isStopped())) + if ((e.value() == boost::system::errc::success) && (!jobQueue_.isStopped())) { onExpire(); } @@ -1017,7 +1017,7 @@ NetworkOPsImp::setHeartbeatTimer() heartbeatTimer_, consensus_.parms().ledgerGRANULARITY, [this]() { - job_queue_.addJob(JtNetopTimer, "NetHeart", [this]() { processHeartbeatTimer(); }); + jobQueue_.addJob(JtNetopTimer, "NetHeart", [this]() { processHeartbeatTimer(); }); }, [this]() { setHeartbeatTimer(); }); } @@ -1031,7 +1031,7 @@ NetworkOPsImp::setClusterTimer() clusterTimer_, 10s, [this]() { - job_queue_.addJob(JtNetopCluster, "NetCluster", [this]() { processClusterTimer(); }); + jobQueue_.addJob(JtNetopCluster, "NetCluster", [this]() { processClusterTimer(); }); }, [this]() { setClusterTimer(); }); } @@ -1247,7 +1247,7 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) auto tx = std::make_shared(trans, reason, registry_.get().getApp()); - job_queue_.addJob(JtTransaction, "SubmitTxn", [this, tx]() { + jobQueue_.addJob(JtTransaction, "SubmitTxn", [this, tx]() { auto t = tx; processTransaction(t, false, false, FailHard::No); }); @@ -1312,7 +1312,7 @@ NetworkOPsImp::processTransaction( bool bLocal, FailHard failType) { - auto ev = job_queue_.makeLoadEvent(JtTxnProc, "ProcessTXN"); + auto ev = jobQueue_.makeLoadEvent(JtTxnProc, "ProcessTXN"); // preProcessTransaction can change our pointer if (!preProcessTransaction(transaction)) @@ -1344,7 +1344,7 @@ NetworkOPsImp::doTransactionAsync( if (dispatchState_ == DispatchState::None) { - if (job_queue_.addJob(JtBatch, "TxBatchAsync", [this]() { transactionBatch(); })) + if (jobQueue_.addJob(JtBatch, "TxBatchAsync", [this]() { transactionBatch(); })) { dispatchState_ = DispatchState::Scheduled; } @@ -1389,7 +1389,7 @@ NetworkOPsImp::doTransactionSyncBatch( if (!transactions_.empty()) { // More transactions need to be applied, but by another job. - if (job_queue_.addJob(JtBatch, "TxBatchSync", [this]() { transactionBatch(); })) + if (jobQueue_.addJob(JtBatch, "TxBatchSync", [this]() { transactionBatch(); })) { dispatchState_ = DispatchState::Scheduled; } @@ -1401,7 +1401,7 @@ NetworkOPsImp::doTransactionSyncBatch( void NetworkOPsImp::processTransactionSet(CanonicalTXSet const& set) { - auto ev = job_queue_.makeLoadEvent(JtTxnProc, "ProcessTXNSet"); + auto ev = jobQueue_.makeLoadEvent(JtTxnProc, "ProcessTXNSet"); std::vector> candidates; candidates.reserve(set.size()); for (auto const& [_, tx] : set) @@ -2571,7 +2571,7 @@ NetworkOPsImp::recvValidation(std::shared_ptr const& val, std::str // We will always relay trusted validations; if configured, we will // also relay all untrusted validations. - return registry_.get().getApp().config().RELAY_UNTRUSTED_VALIDATIONS == 1 || val->isTrusted(); + return registry_.get().getApp().config().relayUntrustedValidations == 1 || val->isTrusted(); } json::Value @@ -2631,8 +2631,8 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) info[jss::hostid] = getHostId(admin); // domain: if configured with a domain, report it: - if (!registry_.get().getApp().config().SERVER_DOMAIN.empty()) - info[jss::server_domain] = registry_.get().getApp().config().SERVER_DOMAIN; + if (!registry_.get().getApp().config().serverDomain.empty()) + info[jss::server_domain] = registry_.get().getApp().config().serverDomain; info[jss::build_version] = BuildInfo::getVersionString(); @@ -2652,7 +2652,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) // Note: By default the node size is "tiny". When parsing it's an error if the final // NODE_SIZE is over 4 so below code should be safe. // NOLINTNEXTLINE(bugprone-switch-missing-default-case) - switch (registry_.get().getApp().config().NODE_SIZE) + switch (registry_.get().getApp().config().nodeSize) { case 0: info[jss::node_size] = "tiny"; @@ -2787,7 +2787,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) // info[jss::consensus] = consensus_.getJson(); if (admin) - info[jss::load] = job_queue_.getJson(); + info[jss::load] = jobQueue_.getJson(); if (auto const netid = registry_.get().getOverlay().networkID()) info[jss::network_id] = static_cast(*netid); @@ -2952,8 +2952,8 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) { // Don't publish admin ports for non-admin users if (!admin && - !(port.admin_nets_v4.empty() && port.admin_nets_v6.empty() && - port.admin_user.empty() && port.admin_password.empty())) + !(port.adminNetsV4.empty() && port.adminNetsV6.empty() && port.adminUser.empty() && + port.adminPassword.empty())) continue; std::vector proto; // NOLINTNEXTLINE(modernize-use-ranges) @@ -3170,14 +3170,14 @@ NetworkOPsImp::reportFeeChange() // only schedule the job if something has changed if (f != lastFeeSummary_) { - job_queue_.addJob(JtClientFeeChange, "PubFee", [this]() { pubServer(); }); + jobQueue_.addJob(JtClientFeeChange, "PubFee", [this]() { pubServer(); }); } } void NetworkOPsImp::reportConsensusStateChange(ConsensusPhase phase) { - job_queue_.addJob(JtClientConsensus, "PubCons", [this, phase]() { pubConsensus(phase); }); + jobQueue_.addJob(JtClientConsensus, "PubCons", [this, phase]() { pubConsensus(phase); }); } inline void @@ -4626,26 +4626,25 @@ NetworkOPsImp::collectMetrics() counters[static_cast(mode)].dur += current; std::scoped_lock const lock(statsMutex_); - stats_.disconnected_duration.set( + stats_.disconnectedDuration.set( counters[static_cast(OperatingMode::DISCONNECTED)].dur.count()); - stats_.connected_duration.set( + stats_.connectedDuration.set( counters[static_cast(OperatingMode::CONNECTED)].dur.count()); - stats_.syncing_duration.set( + stats_.syncingDuration.set( counters[static_cast(OperatingMode::SYNCING)].dur.count()); - stats_.tracking_duration.set( + stats_.trackingDuration.set( counters[static_cast(OperatingMode::TRACKING)].dur.count()); - stats_.full_duration.set(counters[static_cast(OperatingMode::FULL)].dur.count()); + stats_.fullDuration.set(counters[static_cast(OperatingMode::FULL)].dur.count()); - stats_.disconnected_transitions.set( + stats_.disconnectedTransitions.set( counters[static_cast(OperatingMode::DISCONNECTED)].transitions); - stats_.connected_transitions.set( + stats_.connectedTransitions.set( counters[static_cast(OperatingMode::CONNECTED)].transitions); - stats_.syncing_transitions.set( + stats_.syncingTransitions.set( counters[static_cast(OperatingMode::SYNCING)].transitions); - stats_.tracking_transitions.set( + stats_.trackingTransitions.set( counters[static_cast(OperatingMode::TRACKING)].transitions); - stats_.full_transitions.set( - counters[static_cast(OperatingMode::FULL)].transitions); + stats_.fullTransitions.set(counters[static_cast(OperatingMode::FULL)].transitions); } void diff --git a/src/xrpld/app/misc/SHAMapStoreImp.cpp b/src/xrpld/app/misc/SHAMapStoreImp.cpp index 556c6f9239..fc3f71c0cc 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.cpp +++ b/src/xrpld/app/misc/SHAMapStoreImp.cpp @@ -116,7 +116,7 @@ SHAMapStoreImp::SHAMapStoreImp( section.set("cache_mb", std::to_string(config.getValueFor(SizedItem::HashNodeDbCache))); } - if (!section.exists("filter_bits") && (config.NODE_SIZE >= 2)) + if (!section.exists("filter_bits") && (config.nodeSize >= 2)) section.set("filter_bits", "10"); } @@ -148,15 +148,15 @@ SHAMapStoreImp::SHAMapStoreImp( "online_delete must be at least " + std::to_string(minInterval)); } - if (config.LEDGER_HISTORY > deleteInterval_) + if (config.ledgerHistory > deleteInterval_) { Throw( "online_delete must not be less than ledger_history " "(currently " + - std::to_string(config.LEDGER_HISTORY) + ")"); + std::to_string(config.ledgerHistory) + ")"); } - state_db_.init(config, dbName_); + stateDb_.init(config, dbName_); dbPaths(); } } @@ -169,14 +169,14 @@ SHAMapStoreImp::makeNodeStore(int readThreads) if (deleteInterval_ != 0u) { - SavedState state = state_db_.getState(); + SavedState state = stateDb_.getState(); auto writableBackend = makeBackendRotating(state.writableDb); auto archiveBackend = makeBackendRotating(state.archiveDb); if (state.writableDb.empty()) { state.writableDb = writableBackend->getName(); state.archiveDb = archiveBackend->getName(); - state_db_.setState(state); + stateDb_.setState(state); } // Create NodeStore with two backends to allow online deletion of @@ -251,12 +251,12 @@ void SHAMapStoreImp::run() { beast::setCurrentThreadName("SHAMapStore"); - LedgerIndex lastRotated = state_db_.getState().lastRotated; + LedgerIndex lastRotated = stateDb_.getState().lastRotated; netOPs_ = &app_.getOPs(); ledgerMaster_ = &app_.getLedgerMaster(); if (advisoryDelete_) - canDelete_ = state_db_.getCanDelete(); + canDelete_ = stateDb_.getCanDelete(); while (true) { @@ -286,7 +286,7 @@ SHAMapStoreImp::run() if (lastRotated == 0u) { lastRotated = validatedSeq; - state_db_.setLastRotated(lastRotated); + stateDb_.setLastRotated(lastRotated); } bool const readyToRotate = validatedSeq >= lastRotated + deleteInterval_ && @@ -354,7 +354,7 @@ SHAMapStoreImp::run() savedState.writableDb = writableName; savedState.archiveDb = archiveName; savedState.lastRotated = lastRotated; - state_db_.setState(savedState); + stateDb_.setState(savedState); clearCaches(validatedSeq); }); @@ -383,7 +383,7 @@ SHAMapStoreImp::dbPaths() boost::filesystem::create_directories(dbPath); } - SavedState state = state_db_.getState(); + SavedState state = stateDb_.getState(); { auto update = [&dbPath](std::string& sPath) { @@ -403,7 +403,7 @@ SHAMapStoreImp::dbPaths() if (update(state.writableDb)) { update(state.archiveDb); - state_db_.setState(state); + stateDb_.setState(state); } } diff --git a/src/xrpld/app/misc/SHAMapStoreImp.h b/src/xrpld/app/misc/SHAMapStoreImp.h index 1eb2beb561..4f0ce04e0d 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.h +++ b/src/xrpld/app/misc/SHAMapStoreImp.h @@ -66,7 +66,7 @@ private: NodeStore::Scheduler& scheduler_; beast::Journal const journal_; NodeStore::DatabaseRotating* dbRotating_ = nullptr; - SavedStateDB state_db_; + SavedStateDB stateDb_; std::thread thread_; bool stop_ = false; bool healthy_ = true; @@ -113,7 +113,7 @@ public: { if (advisoryDelete_) canDelete_ = seq; - return state_db_.setCanDelete(seq); + return stateDb_.setCanDelete(seq); } bool @@ -127,7 +127,7 @@ public: LedgerIndex getLastRotated() override { - return state_db_.getState().lastRotated; + return stateDb_.getState().lastRotated; } // All ledgers before and including this are unprotected diff --git a/src/xrpld/app/misc/ValidatorSite.h b/src/xrpld/app/misc/ValidatorSite.h index c4d2545217..55f060baf1 100644 --- a/src/xrpld/app/misc/ValidatorSite.h +++ b/src/xrpld/app/misc/ValidatorSite.h @@ -96,10 +96,10 @@ private: Application& app_; beast::Journal const j_; - // If both mutex are to be locked at the same time, `sites_mutex_` must be - // locked before `state_mutex_` or we may deadlock. - std::mutex mutable sites_mutex_; - std::mutex mutable state_mutex_; + // If both mutex are to be locked at the same time, `sitesMutex_` must be + // locked before `stateMutex_` or we may deadlock. + std::mutex mutable sitesMutex_; + std::mutex mutable stateMutex_; std::condition_variable cv_; std::weak_ptr work_; diff --git a/src/xrpld/app/misc/detail/ValidatorSite.cpp b/src/xrpld/app/misc/detail/ValidatorSite.cpp index 7b5d7ee951..76fd078174 100644 --- a/src/xrpld/app/misc/detail/ValidatorSite.cpp +++ b/src/xrpld/app/misc/detail/ValidatorSite.cpp @@ -114,7 +114,7 @@ ValidatorSite::ValidatorSite( ValidatorSite::~ValidatorSite() { - std::unique_lock lock{state_mutex_}; + std::unique_lock lock{stateMutex_}; if (timer_.expiry() > clock_type::time_point{}) { if (!stopping_) @@ -141,7 +141,7 @@ ValidatorSite::load(std::vector const& siteURIs) { JLOG(j_.debug()) << "Loading configured validator list sites"; - std::scoped_lock const lock{sites_mutex_}; + std::scoped_lock const lock{sitesMutex_}; return load(siteURIs, lock); } @@ -178,8 +178,8 @@ ValidatorSite::load( void ValidatorSite::start() { - std::scoped_lock const l0{sites_mutex_}; - std::scoped_lock const l1{state_mutex_}; + std::scoped_lock const l0{sitesMutex_}; + std::scoped_lock const l1{stateMutex_}; if (timer_.expiry() == clock_type::time_point{}) setTimer(l0, l1); } @@ -187,14 +187,14 @@ ValidatorSite::start() void ValidatorSite::join() { - std::unique_lock lock{state_mutex_}; + std::unique_lock lock{stateMutex_}; cv_.wait(lock, [&] { return !pending_; }); } void ValidatorSite::stop() { - std::unique_lock lock{state_mutex_}; + std::unique_lock lock{stateMutex_}; stopping_ = true; // work::cancel() must be called before the // cv wait in order to kick any asio async operations @@ -246,7 +246,7 @@ ValidatorSite::makeRequest( sites_[siteIdx].activeResource = resource; std::shared_ptr sp; auto timeoutCancel = [this]() { - std::scoped_lock const lockState{state_mutex_}; + std::scoped_lock const lockState{stateMutex_}; // docs indicate cancel_one() can throw, but this // should be reconsidered if it changes to noexcept try @@ -312,7 +312,7 @@ ValidatorSite::makeRequest( sp->run(); // start a timer for the request, which shouldn't take more // than requestTimeout_ to complete - std::scoped_lock const lockState{state_mutex_}; + std::scoped_lock const lockState{stateMutex_}; timer_.expires_after(requestTimeout_); timer_.async_wait([this, siteIdx](boost::system::error_code const& ec) { this->onRequestTimeout(siteIdx, ec); @@ -326,7 +326,7 @@ ValidatorSite::onRequestTimeout(std::size_t siteIdx, error_code const& ec) return; { - std::scoped_lock const lockSite{sites_mutex_}; + std::scoped_lock const lockSite{sitesMutex_}; // In some circumstances, both this function and the response // handler (onSiteFetch or onTextFetch) can get queued and // processed. In all observed cases, the response handler @@ -343,7 +343,7 @@ ValidatorSite::onRequestTimeout(std::size_t siteIdx, error_code const& ec) "already been processed"; } - std::scoped_lock const lockState{state_mutex_}; + std::scoped_lock const lockState{stateMutex_}; if (auto sp = work_.lock()) sp->cancel(); } @@ -362,7 +362,7 @@ ValidatorSite::onTimer(std::size_t siteIdx, error_code const& ec) try { - std::scoped_lock const lock{sites_mutex_}; + std::scoped_lock const lock{sitesMutex_}; sites_[siteIdx].nextRefresh = clock_type::now() + sites_[siteIdx].refreshInterval; sites_[siteIdx].redirCount = 0; // the WorkSSL client ctor can throw if SSL init fails @@ -545,7 +545,7 @@ ValidatorSite::onSiteFetch( detail::response_type const& res, std::size_t siteIdx) { - std::scoped_lock lockSites{sites_mutex_}; + std::scoped_lock lockSites{sitesMutex_}; { if (endpoint != endpoint_type{}) sites_[siteIdx].lastRequestEndpoint = endpoint; @@ -617,7 +617,7 @@ ValidatorSite::onSiteFetch( sites_[siteIdx].activeResource.reset(); } - std::scoped_lock const lockState{state_mutex_}; + std::scoped_lock const lockState{stateMutex_}; fetching_ = false; if (!stopping_) setTimer(lockSites, lockState); @@ -630,7 +630,7 @@ ValidatorSite::onTextFetch( std::string const& res, std::size_t siteIdx) { - std::scoped_lock const lockSites{sites_mutex_}; + std::scoped_lock const lockSites{sitesMutex_}; { try { @@ -657,7 +657,7 @@ ValidatorSite::onTextFetch( sites_[siteIdx].activeResource.reset(); } - std::scoped_lock const lockState{state_mutex_}; + std::scoped_lock const lockState{stateMutex_}; fetching_ = false; if (!stopping_) setTimer(lockSites, lockState); @@ -673,7 +673,7 @@ ValidatorSite::getJson() const json::Value jrr(json::ValueType::Object); json::Value& jSites = (jrr[jss::validator_sites] = json::ValueType::Array); { - std::scoped_lock const lock{sites_mutex_}; + std::scoped_lock const lock{sitesMutex_}; for (Site const& site : sites_) { json::Value& v = jSites.append(json::ValueType::Object); diff --git a/src/xrpld/app/misc/detail/WorkSSL.cpp b/src/xrpld/app/misc/detail/WorkSSL.cpp index 0a8d53b1a2..e1b864e81f 100644 --- a/src/xrpld/app/misc/detail/WorkSSL.cpp +++ b/src/xrpld/app/misc/detail/WorkSSL.cpp @@ -30,9 +30,9 @@ WorkSSL::WorkSSL( callback_type cb) : WorkBase(host, path, port, ios, lastEndpoint, lastStatus, cb) , context_( - config.SSL_VERIFY_DIR, - config.SSL_VERIFY_FILE, - config.SSL_VERIFY, + config.sslVerifyDir, + config.sslVerifyFile, + config.sslVerify, j, boost::asio::ssl::context::tlsv12_client) , stream_(socket_, context_.context()) diff --git a/src/xrpld/consensus/Consensus.cpp b/src/xrpld/consensus/Consensus.cpp index 5498f7cf79..d529ab2e44 100644 --- a/src/xrpld/consensus/Consensus.cpp +++ b/src/xrpld/consensus/Consensus.cpp @@ -35,7 +35,7 @@ shouldCloseLedger( << ", timeSincePrevClose: " << timeSincePrevClose.count() << "ms" << ", openTime: " << openTime.count() << "ms" << ", idleInterval: " << idleInterval.count() << "ms" - << ", ledgerMIN_CLOSE: " << parms.ledgerMIN_CLOSE.count() << "ms" + << ", ledgerMIN_CLOSE: " << parms.ledgerMinClose.count() << "ms" << ". "; using namespace std::chrono_literals; if ((prevRoundTime < -1s) || (prevRoundTime > 10min) || (timeSincePrevClose > 10min)) @@ -67,7 +67,7 @@ shouldCloseLedger( } // Preserve minimum ledger open time - if (openTime < parms.ledgerMIN_CLOSE) + if (openTime < parms.ledgerMinClose) { JLOG(j.debug()) << "Must wait minimum time before closing"; CLOG(clog) << "not closing because under ledgerMIN_CLOSE. "; @@ -175,12 +175,12 @@ checkConsensus( << " agree=" << currentAgree << " validated=" << currentFinished << " time=" << currentAgreeTime.count() << "/" << previousAgreeTime.count() << " proposing? " << proposing - << " minimum duration to reach consensus: " << parms.ledgerMIN_CONSENSUS.count() + << " minimum duration to reach consensus: " << parms.ledgerMinConsensus.count() << "ms" - << " max consensus time " << parms.ledgerMAX_CONSENSUS.count() << "ms" - << " minimum consensus percentage: " << parms.minCONSENSUS_PCT << ". "; + << " max consensus time " << parms.ledgerMaxConsensus.count() << "ms" + << " minimum consensus percentage: " << parms.minConsensusPct << ". "; - if (currentAgreeTime <= parms.ledgerMIN_CONSENSUS) + if (currentAgreeTime <= parms.ledgerMinConsensus) { CLOG(clog) << "Not reached. "; return ConsensusState::No; @@ -190,7 +190,7 @@ checkConsensus( { // Less than 3/4 of the last ledger's proposers are present; don't // rush: we may need more time. - if (currentAgreeTime < (previousAgreeTime + parms.ledgerMIN_CONSENSUS)) + if (currentAgreeTime < (previousAgreeTime + parms.ledgerMinConsensus)) { JLOG(j.trace()) << "too fast, not enough proposers"; CLOG(clog) << "Too fast, not enough proposers. Not reached. "; @@ -204,8 +204,8 @@ checkConsensus( currentAgree, currentProposers, proposing, - parms.minCONSENSUS_PCT, - currentAgreeTime > parms.ledgerMAX_CONSENSUS, + parms.minConsensusPct, + currentAgreeTime > parms.ledgerMaxConsensus, stalled, clog)) { @@ -221,8 +221,8 @@ checkConsensus( currentFinished, currentProposers, false, - parms.minCONSENSUS_PCT, - currentAgreeTime > parms.ledgerMAX_CONSENSUS, + parms.minConsensusPct, + currentAgreeTime > parms.ledgerMaxConsensus, false, clog)) { @@ -232,9 +232,9 @@ checkConsensus( } std::chrono::milliseconds const maxAgreeTime = - previousAgreeTime * parms.ledgerABANDON_CONSENSUS_FACTOR; + previousAgreeTime * parms.ledgerAbandonConsensusFactor; if (currentAgreeTime > - std::clamp(maxAgreeTime, parms.ledgerMAX_CONSENSUS, parms.ledgerABANDON_CONSENSUS)) + std::clamp(maxAgreeTime, parms.ledgerMaxConsensus, parms.ledgerAbandonConsensus)) { JLOG(j.warn()) << "consensus taken too long"; CLOG(clog) << "Consensus taken too long. "; diff --git a/src/xrpld/consensus/Consensus.h b/src/xrpld/consensus/Consensus.h index 8b4e971440..131db30ce0 100644 --- a/src/xrpld/consensus/Consensus.h +++ b/src/xrpld/consensus/Consensus.h @@ -625,7 +625,7 @@ Consensus::startRound( if (firstRound_) { // take our initial view of closeTime_ from the seed ledger - prevRoundTime_ = adaptor_.parms().ledgerIDLE_INTERVAL; + prevRoundTime_ = adaptor_.parms().ledgerIdleInterval; prevCloseTime_ = prevLedger.closeTime(); firstRound_ = false; } @@ -1169,9 +1169,9 @@ Consensus::phaseOpen(std::unique_ptr const& clog) } auto const idleInterval = std::max( - adaptor_.parms().ledgerIDLE_INTERVAL, 2 * previousLedger_.closeTimeResolution()); + adaptor_.parms().ledgerIdleInterval, 2 * previousLedger_.closeTimeResolution()); CLOG(clog) << "idle interval set to " << idleInterval.count() << "ms based on " - << "ledgerIDLE_INTERVAL: " << adaptor_.parms().ledgerIDLE_INTERVAL.count() + << "ledgerIDLE_INTERVAL: " << adaptor_.parms().ledgerIdleInterval.count() << ", previous ledger close time resolution: " << previousLedger_.closeTimeResolution().count() << "ms. "; @@ -1218,7 +1218,7 @@ Consensus::shouldPause(std::unique_ptr const& clog) << "roundTime: " << result_->roundTime.read().count() << ", " // NOLINTEND(bugprone-unchecked-optional-access) - << "max consensus time: " << parms.ledgerMAX_CONSENSUS.count() << ", " + << "max consensus time: " << parms.ledgerMaxConsensus.count() << ", " << "validators: " << totalValidators << ", " << "laggards: " << laggards << ", " << "offline: " << offline << ", " @@ -1227,7 +1227,7 @@ Consensus::shouldPause(std::unique_ptr const& clog) if ((ahead == 0u) || (laggards == 0u) || (totalValidators == 0u) || !adaptor_.validator() || !adaptor_.haveValidated() || // NOLINTNEXTLINE(bugprone-unchecked-optional-access) result_ set as shouldPause called - result_->roundTime.read() > parms.ledgerMAX_CONSENSUS) + result_->roundTime.read() > parms.ledgerMaxConsensus) { j_.debug() << "not pausing (early)" << vars.str(); CLOG(clog) << "Not pausing (early). "; @@ -1337,17 +1337,17 @@ Consensus::phaseEstablish(std::unique_ptr const& clo result_->proposers = currPeerPositions_.size(); convergePercent_ = result_->roundTime.read() * 100 / - std::max(prevRoundTime_, parms.avMIN_CONSENSUS_TIME); + std::max(prevRoundTime_, parms.avMinConsensusTime); CLOG(clog) << "convergePercent_ " << convergePercent_ << " is based on round duration so far: " << result_->roundTime.read().count() << "ms, " << "previous round duration: " << prevRoundTime_.count() << "ms, " - << "avMIN_CONSENSUS_TIME: " << parms.avMIN_CONSENSUS_TIME.count() << "ms. "; + << "avMIN_CONSENSUS_TIME: " << parms.avMinConsensusTime.count() << "ms. "; // Give everyone a chance to take an initial position - if (result_->roundTime.read() < parms.ledgerMIN_CONSENSUS) + if (result_->roundTime.read() < parms.ledgerMinConsensus) { - CLOG(clog) << "ledgerMIN_CONSENSUS not reached: " << parms.ledgerMIN_CONSENSUS.count() + CLOG(clog) << "ledgerMIN_CONSENSUS not reached: " << parms.ledgerMinConsensus.count() << "ms. "; return; } @@ -1542,7 +1542,7 @@ Consensus::updateOurPositions(std::unique_ptr const& int threshVote = participantsNeeded(participants, neededWeight); // Threshold to declare consensus - int const threshConsensus = participantsNeeded(participants, parms.avCT_CONSENSUS_PCT); + int const threshConsensus = participantsNeeded(participants, parms.avCtConsensusPct); std::stringstream ss; ss << "Proposers:" << currPeerPositions_.size() << " nw:" << neededWeight @@ -1696,7 +1696,7 @@ Consensus::haveConsensus(std::unique_ptr const& clog // Consensus has taken far too long. Drop out of the round. if (result_->state == ConsensusState::Expired) { - static auto const kMinimumCounter = parms.avalancheCutoffs.size() * parms.avMIN_ROUNDS; + static auto const kMinimumCounter = parms.avalancheCutoffs.size() * parms.avMinRounds; std::stringstream ss; if (establishCounter_ < kMinimumCounter) { diff --git a/src/xrpld/consensus/ConsensusParms.h b/src/xrpld/consensus/ConsensusParms.h index 88a6318b3c..e6dd7f046e 100644 --- a/src/xrpld/consensus/ConsensusParms.h +++ b/src/xrpld/consensus/ConsensusParms.h @@ -28,7 +28,7 @@ struct ConsensusParms This is a safety to protect against very old validations and the time it takes to adjust the close time accuracy window. */ - std::chrono::seconds const validationVALID_WALL = std::chrono::minutes{5}; + std::chrono::seconds const validationValidWall = std::chrono::minutes{5}; /** Duration a validation remains current after first observed. @@ -36,14 +36,14 @@ struct ConsensusParms first saw it. This provides faster recovery in very rare cases where the number of validations produced by the network is lower than normal */ - std::chrono::seconds const validationVALID_LOCAL = std::chrono::minutes{3}; + std::chrono::seconds const validationValidLocal = std::chrono::minutes{3}; /** Duration pre-close in which validations are acceptable. The number of seconds before a close time that we consider a validation acceptable. This protects against extreme clock errors */ - std::chrono::seconds const validationVALID_EARLY = std::chrono::minutes{3}; + std::chrono::seconds const validationValidEarly = std::chrono::minutes{3}; //! How long we consider a proposal fresh std::chrono::seconds const proposeFRESHNESS = std::chrono::seconds{20}; @@ -56,13 +56,13 @@ struct ConsensusParms // millisecond resolution. //! The percentage threshold above which we can declare consensus. - std::size_t const minCONSENSUS_PCT = 80; + std::size_t const minConsensusPct = 80; //! The duration a ledger may remain idle before closing - std::chrono::milliseconds const ledgerIDLE_INTERVAL = std::chrono::seconds{15}; + std::chrono::milliseconds const ledgerIdleInterval = std::chrono::seconds{15}; //! The number of seconds we wait minimum to ensure participation - std::chrono::milliseconds const ledgerMIN_CONSENSUS = std::chrono::milliseconds{1950}; + std::chrono::milliseconds const ledgerMinConsensus = std::chrono::milliseconds{1950}; /** The maximum amount of time to spend pausing for laggards. * @@ -70,16 +70,16 @@ struct ConsensusParms * validators don't appear to be offline that are merely waiting for * laggards. */ - std::chrono::milliseconds const ledgerMAX_CONSENSUS = std::chrono::seconds{15}; + std::chrono::milliseconds const ledgerMaxConsensus = std::chrono::seconds{15}; //! Minimum number of seconds to wait to ensure others have computed the LCL - std::chrono::milliseconds const ledgerMIN_CLOSE = std::chrono::seconds{2}; + std::chrono::milliseconds const ledgerMinClose = std::chrono::seconds{2}; //! How often we check state or change positions std::chrono::milliseconds const ledgerGRANULARITY = std::chrono::seconds{1}; //! How long to wait before completely abandoning consensus - std::size_t const ledgerABANDON_CONSENSUS_FACTOR = 10; + std::size_t const ledgerAbandonConsensusFactor = 10; /** * Maximum amount of time to give a consensus round @@ -87,7 +87,7 @@ struct ConsensusParms * Does not include the time to build the LCL, so there is no reason for a * round to go this long, regardless of how big the ledger is. */ - std::chrono::milliseconds const ledgerABANDON_CONSENSUS = std::chrono::seconds{120}; + std::chrono::milliseconds const ledgerAbandonConsensus = std::chrono::seconds{120}; /** The minimum amount of time to consider the previous round to have taken. @@ -99,7 +99,7 @@ struct ConsensusParms twice the interval between proposals (0.7s) divided by the interval between mid and late consensus ([85-50]/100). */ - std::chrono::milliseconds const avMIN_CONSENSUS_TIME = std::chrono::seconds{5}; + std::chrono::milliseconds const avMinConsensusTime = std::chrono::seconds{5}; //------------------------------------------------------------------------------ // Avalanche tuning @@ -136,16 +136,16 @@ struct ConsensusParms }; //! Percentage of nodes required to reach agreement on ledger close time - std::size_t const avCT_CONSENSUS_PCT = 75; + std::size_t const avCtConsensusPct = 75; //! Number of rounds before certain actions can happen. // (Moving to the next avalanche level, considering that votes are stalled // without consensus.) - std::size_t const avMIN_ROUNDS = 2; + std::size_t const avMinRounds = 2; //! Number of rounds before a stuck vote is considered unlikely to change //! because voting stalled - std::size_t const avSTALLED_ROUNDS = 4; + std::size_t const avStalledRounds = 4; }; inline std::pair> diff --git a/src/xrpld/consensus/DisputedTx.h b/src/xrpld/consensus/DisputedTx.h index e888b95ed6..1c85a3537d 100644 --- a/src/xrpld/consensus/DisputedTx.h +++ b/src/xrpld/consensus/DisputedTx.h @@ -79,20 +79,20 @@ public: // enough, so there's room for change. Check the times in case the state // machine is altered to allow states to loop. if (nextCutoff.consensusTime > currentCutoff.consensusTime || - avalancheCounter_ < p.avMIN_ROUNDS) + avalancheCounter_ < p.avMinRounds) return false; // We've haven't had this vote for minimum rounds yet. Things could // change. - if (proposing && currentVoteCounter_ < p.avMIN_ROUNDS) + if (proposing && currentVoteCounter_ < p.avMinRounds) return false; // If we or any peers have changed a vote in several rounds, then // things could still change. But if _either_ has not changed in that // long, we're unlikely to change our vote any time soon. (This prevents // a malicious peer from flip-flopping a vote to prevent consensus.) - if (peersUnchanged < p.avSTALLED_ROUNDS && - (proposing && currentVoteCounter_ < p.avSTALLED_ROUNDS)) + if (peersUnchanged < p.avStalledRounds && + (proposing && currentVoteCounter_ < p.avStalledRounds)) return false; // Does this transaction have more than 80% agreement @@ -108,7 +108,7 @@ public: int const weight = support / total; // Returns true if the tx has more than minCONSENSUS_PCT (80) percent // agreement. Either voting for _or_ voting against the tx. - bool const stalled = weight > p.minCONSENSUS_PCT || weight < (100 - p.minCONSENSUS_PCT); + bool const stalled = weight > p.minConsensusPct || weight < (100 - p.minConsensusPct); if (stalled) { @@ -276,7 +276,7 @@ DisputedTx::updateVote(int percentTime, bool proposing, ConsensusPar // Proposing or not, we need to keep track of which state we've reached so // we can determine if the vote has stalled. auto const [requiredPct, newState] = - getNeededWeight(p, avalancheState_, percentTime, ++avalancheCounter_, p.avMIN_ROUNDS); + getNeededWeight(p, avalancheState_, percentTime, ++avalancheCounter_, p.avMinRounds); if (newState) { avalancheState_ = *newState; diff --git a/src/xrpld/consensus/Validations.h b/src/xrpld/consensus/Validations.h index fd32b52518..7be578060e 100644 --- a/src/xrpld/consensus/Validations.h +++ b/src/xrpld/consensus/Validations.h @@ -33,7 +33,7 @@ struct ValidationParms This is a safety to protect against very old validations and the time it takes to adjust the close time accuracy window. */ - std::chrono::seconds validationCURRENT_WALL = std::chrono::minutes{5}; + std::chrono::seconds validationCurrentWall = std::chrono::minutes{5}; /** Duration a validation remains current after first observed. @@ -41,14 +41,14 @@ struct ValidationParms first saw it. This provides faster recovery in very rare cases where the number of validations produced by the network is lower than normal */ - std::chrono::seconds validationCURRENT_LOCAL = std::chrono::minutes{3}; + std::chrono::seconds validationCurrentLocal = std::chrono::minutes{3}; /** Duration pre-close in which validations are acceptable. The number of seconds before a close time that we consider a validation acceptable. This protects against extreme clock errors */ - std::chrono::seconds validationCURRENT_EARLY = std::chrono::minutes{3}; + std::chrono::seconds validationCurrentEarly = std::chrono::minutes{3}; /** Duration a set of validations for a given ledger hash remain valid @@ -56,7 +56,7 @@ struct ValidationParms hash can expire. This keeps validations for recent ledgers available for a reasonable interval. */ - std::chrono::seconds validationSET_EXPIRES = std::chrono::minutes{10}; + std::chrono::seconds validationSetExpires = std::chrono::minutes{10}; /** How long we consider a validation fresh. * @@ -98,7 +98,7 @@ public: bool operator()(time_point now, Seq s, ValidationParms const& p) { - if (now > (when_ + p.validationSET_EXPIRES)) + if (now > (when_ + p.validationSetExpires)) seq_ = Seq{0}; if (s <= seq_) return false; @@ -139,9 +139,9 @@ isCurrent( // promoted from unsigned 32 bit to signed 64 bit prior // to computation. - return (signTime > (now - p.validationCURRENT_EARLY)) && - (signTime < (now + p.validationCURRENT_WALL)) && - ((seenTime == NetClock::time_point{}) || (seenTime < (now + p.validationCURRENT_LOCAL))); + return (signTime > (now - p.validationCurrentEarly)) && + (signTime < (now + p.validationCurrentWall)) && + ((seenTime == NetClock::time_point{}) || (seenTime < (now + p.validationCurrentLocal))); } /** Status of validation we received */ @@ -610,7 +610,7 @@ public: auto const diff = std::max(seqit->second.signTime(), val.signTime()) - std::min(seqit->second.signTime(), val.signTime()); - if (diff > parms_.validationCURRENT_WALL && + if (diff > parms_.validationCurrentWall && val.signTime() > seqit->second.signTime()) seqit->second = val; } @@ -707,7 +707,7 @@ public: { // The next refresh time is shortly before the expiration // time from now. - kRefreshTime = now + parms_.validationSET_EXPIRES - parms_.validationFRESHNESS; + kRefreshTime = now + parms_.validationSetExpires - parms_.validationFRESHNESS; for (auto i = byLedger_.begin(); i != byLedger_.end(); ++i) { @@ -732,8 +732,8 @@ public: } } - beast::expire(byLedger_, parms_.validationSET_EXPIRES); - beast::expire(bySequence_, parms_.validationSET_EXPIRES); + beast::expire(byLedger_, parms_.validationSetExpires); + beast::expire(bySequence_, parms_.validationSetExpires); } JLOG(j.debug()) << "Validations sets sweep lock duration " << std::chrono::duration_cast( diff --git a/src/xrpld/core/Config.h b/src/xrpld/core/Config.h index 322683e119..a18b68a508 100644 --- a/src/xrpld/core/Config.h +++ b/src/xrpld/core/Config.h @@ -48,13 +48,13 @@ A default-constructed Setup contains recommended values. struct FeeSetup { /** The cost of a reference transaction in drops. */ - XRPAmount reference_fee{10}; + XRPAmount referenceFee{10}; /** The account reserve requirement in drops. */ - XRPAmount account_reserve{10 * kDropsPerXrp}; + XRPAmount accountReserve{10 * kDropsPerXrp}; /** The per-owned item reserve requirement in drops. */ - XRPAmount owner_reserve{2 * kDropsPerXrp}; + XRPAmount ownerReserve{2 * kDropsPerXrp}; /* (Remember to update the example cfg files when changing any of these * values.) */ @@ -63,7 +63,7 @@ struct FeeSetup [[nodiscard]] Fees toFees() const { - return Fees{reference_fee, account_reserve, owner_reserve}; + return Fees{referenceFee, accountReserve, ownerReserve}; } }; @@ -86,20 +86,20 @@ public: getDebugLogFile() const; private: - boost::filesystem::path CONFIG_FILE_; + boost::filesystem::path configFile_; public: - boost::filesystem::path CONFIG_DIR; + boost::filesystem::path configDir; private: - boost::filesystem::path DEBUG_LOGFILE_; + boost::filesystem::path debugLogfile_; void load(); beast::Journal const j_; - bool QUIET_ = false; // Minimize logging verbosity. - bool SILENT_ = false; // No output to console after startup. + bool quiet_ = false; // Minimize logging verbosity. + bool silent_ = false; // No output to console after startup. /** Operate in stand-alone mode. In stand alone mode: @@ -109,9 +109,9 @@ private: - If no ledger is loaded, the default ledger with the root account is created. */ - bool RUN_STANDALONE_ = false; + bool runStandalone_ = false; - bool USE_TX_TABLES_ = true; + bool useTxTables_ = true; /** Determines if the server will sign a tx, given an account's secret seed. @@ -126,45 +126,45 @@ private: public: bool doImport = false; - bool ELB_SUPPORT = false; + bool elbSupport = false; // Entries from [ips] config stanza - std::vector IPS; + std::vector ips; // Entries from [ips_fixed] config stanza - std::vector IPS_FIXED; + std::vector ipsFixed; - StartUpType START_UP = StartUpType::Normal; + StartUpType startUp = StartUpType::Normal; - bool START_VALID = false; + bool startValid = false; - std::string START_LEDGER; + std::string startLedger; - std::optional TRAP_TX_HASH; + std::optional trapTxHash; // Network parameters - uint32_t NETWORK_ID = 0; + uint32_t networkId = 0; // Note: The following parameters do not relate to the UNL or trust at all // Minimum number of nodes to consider the network present - std::size_t NETWORK_QUORUM = 1; + std::size_t networkQuorum = 1; // Peer networking parameters // 1 = relay, 0 = do not relay (but process), -1 = drop completely (do NOT // process) - int RELAY_UNTRUSTED_VALIDATIONS = 1; - int RELAY_UNTRUSTED_PROPOSALS = 0; + int relayUntrustedValidations = 1; + int relayUntrustedProposals = 0; // True to ask peers not to relay current IP. - bool PEER_PRIVATE = false; + bool peerPrivate = false; // peers_max is a legacy configuration, which is going to be replaced // with individual inbound peers peers_in_max and outbound peers // peers_out_max configuration. for now we support both the legacy and // the new configuration. if peers_max is configured then peers_in_max and // peers_out_max are ignored. - std::size_t PEERS_MAX = 0; - std::size_t PEERS_OUT_MAX = 0; - std::size_t PEERS_IN_MAX = 0; + std::size_t peersMax = 0; + std::size_t peersOutMax = 0; + std::size_t peersInMax = 0; // Path searching: these were reasonable default values at some point but // further research is needed to decide if they still are @@ -178,110 +178,110 @@ public: // Servers operating as validators disable path finding by // default by setting the `PATH_SEARCH_MAX` option to 0 // unless it is explicitly set in the configuration file. - int PATH_SEARCH_OLD = 2; - int PATH_SEARCH = 2; - int PATH_SEARCH_FAST = 2; - int PATH_SEARCH_MAX = 3; + int pathSearchOld = 2; + int pathSearch = 2; + int pathSearchFast = 2; + int pathSearchMax = 3; // Validation - std::optional VALIDATION_QUORUM; // validations to consider ledger authoritative + std::optional validationQuorum; // validations to consider ledger authoritative - FeeSetup FEES; + FeeSetup fees; // Node storage configuration - std::uint32_t LEDGER_HISTORY = 256; - std::uint32_t FETCH_DEPTH = 1000000000; + std::uint32_t ledgerHistory = 256; + std::uint32_t fetchDepth = 1000000000; // Tunable that adjusts various parameters, typically associated // with hardware parameters (RAM size and CPU cores). The default // is 'tiny'. - std::size_t NODE_SIZE = 0; + std::size_t nodeSize = 0; - bool SSL_VERIFY = true; - std::string SSL_VERIFY_FILE; - std::string SSL_VERIFY_DIR; + bool sslVerify = true; + std::string sslVerifyFile; + std::string sslVerifyDir; // Compression - bool COMPRESSION = false; + bool compression = false; // Enable the experimental Ledger Replay functionality - bool LEDGER_REPLAY = false; + bool ledgerReplay = false; // Work queue limits - int MAX_TRANSACTIONS = 250; + int maxTransactions = 250; static constexpr int kMaxJobQueueTx = 1000; static constexpr int kMinJobQueueTx = 100; // Amendment majority time - std::chrono::seconds AMENDMENT_MAJORITY_TIME = kDefaultAmendmentMajorityTime; + std::chrono::seconds amendmentMajorityTime = kDefaultAmendmentMajorityTime; // Thread pool configuration (0 = choose for me) - int WORKERS = 0; // jobqueue thread count. default: upto 6 - int IO_WORKERS = 0; // io svc thread count. default: 2 - int PREFETCH_WORKERS = 0; // prefetch thread count. default: 4 + int workers = 0; // jobqueue thread count. default: upto 6 + int ioWorkers = 0; // io svc thread count. default: 2 + int prefetchWorkers = 0; // prefetch thread count. default: 4 // Can only be set in code, specifically unit tests - bool FORCE_MULTI_THREAD = false; + bool forceMultiThread = false; // Normally the sweep timer is automatically deduced based on the node // size, but we allow admins to explicitly set it in the config. - std::optional SWEEP_INTERVAL; + std::optional sweepInterval; // Reduce-relay - Experimental parameters to control p2p routing algorithms // Enable base squelching of duplicate validation/proposal messages - bool VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = false; + bool vpReduceRelayBaseSquelchEnable = false; ///////////////////// !!TEMPORARY CODE BLOCK!! //////////////////////// // 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 // - std::size_t VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS = 5; + std::size_t vpReduceRelaySquelchMaxSelectedPeers = 5; ///////////////// END OF TEMPORARY CODE BLOCK ///////////////////// // Transaction reduce-relay feature - bool TX_REDUCE_RELAY_ENABLE = false; + bool txReduceRelayEnable = false; // If tx reduce-relay feature is disabled // and this flag is enabled then some // tx-related metrics is collected. It // is ignored if tx reduce-relay feature is // enabled. It is used in debugging to compare // metrics with the feature disabled/enabled. - bool TX_REDUCE_RELAY_METRICS = false; + bool txReduceRelayMetrics = false; // Minimum peers a server should have before // selecting random peers - std::size_t TX_REDUCE_RELAY_MIN_PEERS = 20; + std::size_t txReduceRelayMinPeers = 20; // Percentage of peers with the tx reduce-relay feature enabled // to relay to out of total active peers - std::size_t TX_RELAY_PERCENTAGE = 25; + std::size_t txRelayPercentage = 25; // These override the command line client settings - std::optional rpc_ip; + std::optional rpcIp; std::unordered_set> features; - std::string SERVER_DOMAIN; + std::string serverDomain; // How long can a peer remain in the "unknown" state - std::chrono::seconds MAX_UNKNOWN_TIME{600}; + std::chrono::seconds maxUnknownTime{600}; // How long can a peer remain in the "diverged" state - std::chrono::seconds MAX_DIVERGED_TIME{300}; + std::chrono::seconds maxDivergedTime{300}; // Enable the beta API version - bool BETA_RPC_API = false; + bool betaRpcApi = false; // First, attempt to load the latest ledger directly from disk. - bool FAST_LOAD = false; + bool fastLoad = false; // When starting xrpld with existing database it do not know it has those // ledgers locally until the server naturally tries to backfill. This makes // is difficult to test some functionality (in particular performance // testing sidechains). With this variable the user is able to force xrpld // to consider the ledger range to be present. It should be used for testing // only. - std::optional> FORCED_LEDGER_RANGE_PRESENT; + std::optional> forcedLedgerRangePresent; - std::optional VALIDATOR_LIST_THRESHOLD; + std::optional validatorListThreshold; public: Config(); @@ -305,23 +305,23 @@ public: [[nodiscard]] bool quiet() const { - return QUIET_; + return quiet_; } [[nodiscard]] bool silent() const { - return SILENT_; + return silent_; } [[nodiscard]] bool standalone() const { - return RUN_STANDALONE_; + return runStandalone_; } [[nodiscard]] bool useTxTables() const { - return USE_TX_TABLES_; + return useTxTables_; } [[nodiscard]] bool diff --git a/src/xrpld/core/detail/Config.cpp b/src/xrpld/core/detail/Config.cpp index d8789795c0..6eedc43edd 100644 --- a/src/xrpld/core/detail/Config.cpp +++ b/src/xrpld/core/detail/Config.cpp @@ -272,11 +272,11 @@ Config::Config() void Config::setupControl(bool bQuiet, bool bSilent, bool bStandalone) { - XRPL_ASSERT(NODE_SIZE == 0, "xrpl::Config::setupControl : node size not set"); + XRPL_ASSERT(nodeSize == 0, "xrpl::Config::setupControl : node size not set"); - QUIET_ = bQuiet || bSilent; - SILENT_ = bSilent; - RUN_STANDALONE_ = bStandalone; + quiet_ = bQuiet || bSilent; + silent_ = bSilent; + runStandalone_ = bStandalone; // We try to autodetect the appropriate node size by checking available // RAM and CPU resources. We default to "tiny" for standalone mode. @@ -293,15 +293,15 @@ Config::setupControl(bool bQuiet, bool bSilent, bool bStandalone) XRPL_ASSERT(ns != threshold.second.end(), "xrpl::Config::setupControl : valid node size"); if (ns != threshold.second.end()) - NODE_SIZE = std::distance(threshold.second.begin(), ns); + nodeSize = std::distance(threshold.second.begin(), ns); // Adjust the size based on the number of hardware threads of // execution available to us: if (auto const hc = std::thread::hardware_concurrency(); hc != 0) - NODE_SIZE = std::min(hc / 2, NODE_SIZE); + nodeSize = std::min(hc / 2, nodeSize); } - XRPL_ASSERT(NODE_SIZE <= 4, "xrpl::Config::setupControl : node size is set"); + XRPL_ASSERT(nodeSize <= 4, "xrpl::Config::setupControl : node size is set"); } void @@ -319,10 +319,10 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand if (!strConf.empty()) { // --conf= : everything is relative that file. - CONFIG_FILE_ = strConf; - CONFIG_DIR = boost::filesystem::absolute(CONFIG_FILE_); - CONFIG_DIR.remove_filename(); - dataDir = CONFIG_DIR / kDatabaseDirName; + configFile_ = strConf; + configDir = boost::filesystem::absolute(configFile_); + configDir.remove_filename(); + dataDir = configDir / kDatabaseDirName; } else { @@ -331,13 +331,13 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand // Check if either of the config files exist in the current working // directory, in which case the databases will be stored in a // subdirectory. - CONFIG_DIR = boost::filesystem::current_path(); - dataDir = CONFIG_DIR / kDatabaseDirName; - CONFIG_FILE_ = CONFIG_DIR / kConfigFileName; - if (boost::filesystem::exists(CONFIG_FILE_)) + configDir = boost::filesystem::current_path(); + dataDir = configDir / kDatabaseDirName; + configFile_ = configDir / kConfigFileName; + if (boost::filesystem::exists(configFile_)) break; - CONFIG_FILE_ = CONFIG_DIR / kConfigLegacyName; - if (boost::filesystem::exists(CONFIG_FILE_)) + configFile_ = configDir / kConfigLegacyName; + if (boost::filesystem::exists(configFile_)) break; // Check if the home directory is set, and optionally the XDG config @@ -362,22 +362,22 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand // Check if either of the config files exist in the XDG config // dir. dataDir = strXdgDataHome + "/" + systemName(); - CONFIG_DIR = strXdgConfigHome + "/" + systemName(); - CONFIG_FILE_ = CONFIG_DIR / kConfigFileName; - if (boost::filesystem::exists(CONFIG_FILE_)) + configDir = strXdgConfigHome + "/" + systemName(); + configFile_ = configDir / kConfigFileName; + if (boost::filesystem::exists(configFile_)) break; - CONFIG_FILE_ = CONFIG_DIR / kConfigLegacyName; - if (boost::filesystem::exists(CONFIG_FILE_)) + configFile_ = configDir / kConfigLegacyName; + if (boost::filesystem::exists(configFile_)) break; } // As a last resort, check the system config directory. dataDir = "/var/lib/" + systemName(); - CONFIG_DIR = "/etc/" + systemName(); - CONFIG_FILE_ = CONFIG_DIR / kConfigFileName; - if (boost::filesystem::exists(CONFIG_FILE_)) + configDir = "/etc/" + systemName(); + configFile_ = configDir / kConfigFileName; + if (boost::filesystem::exists(configFile_)) break; - CONFIG_FILE_ = CONFIG_DIR / kConfigLegacyName; + configFile_ = configDir / kConfigLegacyName; } while (false); } @@ -390,7 +390,7 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand { dataDir = boost::filesystem::path(dbPath); } - else if (RUN_STANDALONE_) + else if (runStandalone_) { dataDir.clear(); } @@ -407,17 +407,16 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand legacy("database_path", boost::filesystem::absolute(dataDir).string()); } - HTTPClient::initializeSSLContext( - this->SSL_VERIFY_DIR, this->SSL_VERIFY_FILE, this->SSL_VERIFY, j_); + HTTPClient::initializeSSLContext(this->sslVerifyDir, this->sslVerifyFile, this->sslVerify, j_); - if (RUN_STANDALONE_) - LEDGER_HISTORY = 0; + if (runStandalone_) + ledgerHistory = 0; Section const ledgerTxTablesSection = section("ledger_tx_tables"); - getIfExists(ledgerTxTablesSection, "use_tx_tables", USE_TX_TABLES_); + getIfExists(ledgerTxTablesSection, "use_tx_tables", useTxTables_); Section const& nodeDbSection{section(ConfigSection::nodeDatabase())}; - getIfExists(nodeDbSection, "fast_load", FAST_LOAD); + getIfExists(nodeDbSection, "fast_load", fastLoad); } // 0 ports are allowed for unit tests, but still not allowed to be present in @@ -454,16 +453,16 @@ Config::load() // NOTE: this writes to cerr because we want cout to be reserved // for the writing of the json response (so that stdout can be part of a // pipeline, for instance) - if (!QUIET_) - std::cerr << "Loading: " << CONFIG_FILE_ << "\n"; + if (!quiet_) + std::cerr << "Loading: " << configFile_ << "\n"; boost::system::error_code ec; - auto const fileContents = getFileContents(ec, CONFIG_FILE_); + auto const fileContents = getFileContents(ec, configFile_); if (ec) { - std::cerr << "Failed to read '" << CONFIG_FILE_ << "'." << ec.value() << ": " - << ec.message() << std::endl; + std::cerr << "Failed to read '" << configFile_ << "'." << ec.value() << ": " << ec.message() + << std::endl; return; } @@ -479,10 +478,10 @@ Config::loadFromString(std::string const& fileContents) build(secConfig); if (auto s = getIniFileSection(secConfig, SECTION_IPS)) - IPS = *s; + ips = *s; if (auto s = getIniFileSection(secConfig, SECTION_IPS_FIXED)) - IPS_FIXED = *s; + ipsFixed = *s; // if the user has specified ip:port then replace : with a space. { @@ -502,8 +501,8 @@ Config::loadFromString(std::string const& fileContents) } }; - replaceColons(IPS_FIXED); - replaceColons(IPS); + replaceColons(ipsFixed); + replaceColons(ips); } { @@ -521,47 +520,47 @@ Config::loadFromString(std::string const& fileContents) { if (strTemp == "main") { - NETWORK_ID = 0; + networkId = 0; } else if (strTemp == "testnet") { - NETWORK_ID = 1; + networkId = 1; } else if (strTemp == "devnet") { - NETWORK_ID = 2; + networkId = 2; } else { - NETWORK_ID = beast::lexicalCastThrow(strTemp); + networkId = beast::lexicalCastThrow(strTemp); } } if (getSingleSection(secConfig, SECTION_PEER_PRIVATE, strTemp, j_)) - PEER_PRIVATE = beast::lexicalCastThrow(strTemp); + peerPrivate = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_PEERS_MAX, strTemp, j_)) { - PEERS_MAX = beast::lexicalCastThrow(strTemp); + peersMax = beast::lexicalCastThrow(strTemp); } else { - std::optional peersInMax{}; + std::optional peersInMaxOpt{}; if (getSingleSection(secConfig, SECTION_PEERS_IN_MAX, strTemp, j_)) { - peersInMax = beast::lexicalCastThrow(strTemp); - if (*peersInMax > 1000) + 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"); } } - std::optional peersOutMax{}; + std::optional peersOutMaxOpt{}; if (getSingleSection(secConfig, SECTION_PEERS_OUT_MAX, strTemp, j_)) { - peersOutMax = beast::lexicalCastThrow(strTemp); - if (*peersOutMax < 10 || *peersOutMax > 1000) + 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"); @@ -569,17 +568,17 @@ Config::loadFromString(std::string const& fileContents) } // if one section is configured then the other must be configured too - if ((peersInMax && !peersOutMax) || (peersOutMax && !peersInMax)) + if ((peersInMaxOpt && !peersOutMaxOpt) || (peersOutMaxOpt && !peersInMaxOpt)) { Throw("Both sections [" SECTION_PEERS_IN_MAX "]" "and [" SECTION_PEERS_OUT_MAX "] must be configured"); } - if (peersInMax && peersOutMax) + if (peersInMaxOpt && peersOutMaxOpt) { - PEERS_IN_MAX = *peersInMax; - PEERS_OUT_MAX = *peersOutMax; + peersInMax = *peersInMaxOpt; + peersOutMax = *peersOutMaxOpt; } } @@ -587,27 +586,27 @@ Config::loadFromString(std::string const& fileContents) { if (boost::iequals(strTemp, "tiny")) { - NODE_SIZE = 0; + nodeSize = 0; } else if (boost::iequals(strTemp, "small")) { - NODE_SIZE = 1; + nodeSize = 1; } else if (boost::iequals(strTemp, "medium")) { - NODE_SIZE = 2; + nodeSize = 2; } else if (boost::iequals(strTemp, "large")) { - NODE_SIZE = 3; + nodeSize = 3; } else if (boost::iequals(strTemp, "huge")) { - NODE_SIZE = 4; + nodeSize = 4; } else { - NODE_SIZE = std::min(4, beast::lexicalCastThrow(strTemp)); + nodeSize = std::min(4, beast::lexicalCastThrow(strTemp)); } } @@ -615,27 +614,27 @@ Config::loadFromString(std::string const& fileContents) signingEnabled_ = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_ELB_SUPPORT, strTemp, j_)) - ELB_SUPPORT = beast::lexicalCastThrow(strTemp); + elbSupport = beast::lexicalCastThrow(strTemp); - getSingleSection(secConfig, SECTION_SSL_VERIFY_FILE, SSL_VERIFY_FILE, j_); - getSingleSection(secConfig, SECTION_SSL_VERIFY_DIR, SSL_VERIFY_DIR, j_); + getSingleSection(secConfig, SECTION_SSL_VERIFY_FILE, sslVerifyFile, j_); + getSingleSection(secConfig, SECTION_SSL_VERIFY_DIR, sslVerifyDir, j_); if (getSingleSection(secConfig, SECTION_SSL_VERIFY, strTemp, j_)) - SSL_VERIFY = beast::lexicalCastThrow(strTemp); + sslVerify = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_RELAY_VALIDATIONS, strTemp, j_)) { if (boost::iequals(strTemp, "all")) { - RELAY_UNTRUSTED_VALIDATIONS = 1; + relayUntrustedValidations = 1; } else if (boost::iequals(strTemp, "trusted")) { - RELAY_UNTRUSTED_VALIDATIONS = 0; + relayUntrustedValidations = 0; } else if (boost::iequals(strTemp, "drop_untrusted")) { - RELAY_UNTRUSTED_VALIDATIONS = -1; + relayUntrustedValidations = -1; } else { @@ -648,15 +647,15 @@ Config::loadFromString(std::string const& fileContents) { if (boost::iequals(strTemp, "all")) { - RELAY_UNTRUSTED_PROPOSALS = 1; + relayUntrustedProposals = 1; } else if (boost::iequals(strTemp, "trusted")) { - RELAY_UNTRUSTED_PROPOSALS = 0; + relayUntrustedProposals = 0; } else if (boost::iequals(strTemp, "drop_untrusted")) { - RELAY_UNTRUSTED_PROPOSALS = -1; + relayUntrustedProposals = -1; } else { @@ -672,28 +671,28 @@ Config::loadFromString(std::string const& fileContents) } if (getSingleSection(secConfig, SECTION_NETWORK_QUORUM, strTemp, j_)) - NETWORK_QUORUM = beast::lexicalCastThrow(strTemp); + networkQuorum = beast::lexicalCastThrow(strTemp); - FEES = setupFeeVote(section("voting")); + fees = setupFeeVote(section("voting")); /* [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_)) - FEES.reference_fee = beast::lexicalCastThrow(strTemp); + fees.referenceFee = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_LEDGER_HISTORY, strTemp, j_)) { if (boost::iequals(strTemp, "full")) { - LEDGER_HISTORY = std::numeric_limits::max(); + ledgerHistory = std::numeric_limits::max(); } else if (boost::iequals(strTemp, "none")) { - LEDGER_HISTORY = 0; + ledgerHistory = 0; } else { - LEDGER_HISTORY = beast::lexicalCastThrow(strTemp); + ledgerHistory = beast::lexicalCastThrow(strTemp); } } @@ -701,42 +700,42 @@ Config::loadFromString(std::string const& fileContents) { if (boost::iequals(strTemp, "none")) { - FETCH_DEPTH = 0; + fetchDepth = 0; } else if (boost::iequals(strTemp, "full")) { - FETCH_DEPTH = std::numeric_limits::max(); + fetchDepth = std::numeric_limits::max(); } else { - FETCH_DEPTH = beast::lexicalCastThrow(strTemp); + fetchDepth = beast::lexicalCastThrow(strTemp); } - FETCH_DEPTH = std::max(FETCH_DEPTH, 10); + fetchDepth = std::max(fetchDepth, 10); } // 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)) - PATH_SEARCH_MAX = 0; + pathSearchMax = 0; if (getSingleSection(secConfig, SECTION_PATH_SEARCH_OLD, strTemp, j_)) - PATH_SEARCH_OLD = beast::lexicalCastThrow(strTemp); + pathSearchOld = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_PATH_SEARCH, strTemp, j_)) - PATH_SEARCH = beast::lexicalCastThrow(strTemp); + pathSearch = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_PATH_SEARCH_FAST, strTemp, j_)) - PATH_SEARCH_FAST = beast::lexicalCastThrow(strTemp); + pathSearchFast = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_PATH_SEARCH_MAX, strTemp, j_)) - PATH_SEARCH_MAX = beast::lexicalCastThrow(strTemp); + pathSearchMax = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_DEBUG_LOGFILE, strTemp, j_)) - DEBUG_LOGFILE_ = strTemp; + debugLogfile_ = strTemp; if (getSingleSection(secConfig, SECTION_SWEEP_INTERVAL, strTemp, j_)) { - SWEEP_INTERVAL = beast::lexicalCastThrow(strTemp); + sweepInterval = beast::lexicalCastThrow(strTemp); - if (SWEEP_INTERVAL < 10 || SWEEP_INTERVAL > 600) + if (sweepInterval < 10 || sweepInterval > 600) { Throw("Invalid " SECTION_SWEEP_INTERVAL ": must be between 10 and 600 inclusive"); @@ -745,9 +744,9 @@ Config::loadFromString(std::string const& fileContents) if (getSingleSection(secConfig, SECTION_WORKERS, strTemp, j_)) { - WORKERS = beast::lexicalCastThrow(strTemp); + workers = beast::lexicalCastThrow(strTemp); - if (WORKERS < 1 || WORKERS > 1024) + if (workers < 1 || workers > 1024) { Throw("Invalid " SECTION_WORKERS ": must be between 1 and 1024 inclusive."); @@ -756,9 +755,9 @@ Config::loadFromString(std::string const& fileContents) if (getSingleSection(secConfig, SECTION_IO_WORKERS, strTemp, j_)) { - IO_WORKERS = beast::lexicalCastThrow(strTemp); + ioWorkers = beast::lexicalCastThrow(strTemp); - if (IO_WORKERS < 1 || IO_WORKERS > 1024) + if (ioWorkers < 1 || ioWorkers > 1024) { Throw("Invalid " SECTION_IO_WORKERS ": must be between 1 and 1024 inclusive."); @@ -767,9 +766,9 @@ Config::loadFromString(std::string const& fileContents) if (getSingleSection(secConfig, SECTION_PREFETCH_WORKERS, strTemp, j_)) { - PREFETCH_WORKERS = beast::lexicalCastThrow(strTemp); + prefetchWorkers = beast::lexicalCastThrow(strTemp); - if (PREFETCH_WORKERS < 1 || PREFETCH_WORKERS > 1024) + if (prefetchWorkers < 1 || prefetchWorkers > 1024) { Throw("Invalid " SECTION_PREFETCH_WORKERS ": must be between 1 and 1024 inclusive."); @@ -777,10 +776,10 @@ Config::loadFromString(std::string const& fileContents) } if (getSingleSection(secConfig, SECTION_COMPRESSION, strTemp, j_)) - COMPRESSION = beast::lexicalCastThrow(strTemp); + compression = beast::lexicalCastThrow(strTemp); if (getSingleSection(secConfig, SECTION_LEDGER_REPLAY, strTemp, j_)) - LEDGER_REPLAY = beast::lexicalCastThrow(strTemp); + ledgerReplay = beast::lexicalCastThrow(strTemp); if (exists(SECTION_REDUCE_RELAY)) { @@ -803,15 +802,15 @@ Config::loadFromString(std::string const& fileContents) if (sec.exists("vp_base_squelch_enable")) { - VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = sec.valueOr("vp_base_squelch_enable", false); + vpReduceRelayBaseSquelchEnable = sec.valueOr("vp_base_squelch_enable", false); } else if (sec.exists("vp_enable")) { - VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = sec.valueOr("vp_enable", false); + vpReduceRelayBaseSquelchEnable = sec.valueOr("vp_enable", false); } else { - VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = false; + vpReduceRelayBaseSquelchEnable = false; } ///////////////// !!END OF TEMPORARY CODE BLOCK!! ///////////////////// @@ -819,9 +818,8 @@ 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. // - VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS = - sec.valueOr("vp_base_squelch_max_selected_peers", 5); - if (VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS < 3) + vpReduceRelaySquelchMaxSelectedPeers = sec.valueOr("vp_base_squelch_max_selected_peers", 5); + if (vpReduceRelaySquelchMaxSelectedPeers < 3) { Throw("Invalid " SECTION_REDUCE_RELAY " vp_base_squelch_max_selected_peers must be " @@ -829,11 +827,11 @@ Config::loadFromString(std::string const& fileContents) } ///////////////// !!END OF TEMPORARY CODE BLOCK!! ///////////////////// - TX_REDUCE_RELAY_ENABLE = sec.valueOr("tx_enable", false); - TX_REDUCE_RELAY_METRICS = sec.valueOr("tx_metrics", false); - TX_REDUCE_RELAY_MIN_PEERS = sec.valueOr("tx_min_peers", 20); - TX_RELAY_PERCENTAGE = sec.valueOr("tx_relay_percentage", 25); - if (TX_RELAY_PERCENTAGE < 10 || TX_RELAY_PERCENTAGE > 100 || TX_REDUCE_RELAY_MIN_PEERS < 10) + 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); + if (txRelayPercentage < 10 || txRelayPercentage > 100 || txReduceRelayMinPeers < 10) { Throw("Invalid " SECTION_REDUCE_RELAY ", tx_min_peers must be greater than or equal to 10" @@ -844,7 +842,7 @@ Config::loadFromString(std::string const& fileContents) if (getSingleSection(secConfig, SECTION_MAX_TRANSACTIONS, strTemp, j_)) { - MAX_TRANSACTIONS = + maxTransactions = std::clamp(beast::lexicalCastThrow(strTemp), kMinJobQueueTx, kMaxJobQueueTx); } @@ -857,7 +855,7 @@ Config::loadFromString(std::string const& fileContents) ": the domain name does not appear to meet the requirements."); } - SERVER_DOMAIN = strTemp; + serverDomain = strTemp; } if (exists(SECTION_OVERLAY)) @@ -869,7 +867,7 @@ Config::loadFromString(std::string const& fileContents) try { if (auto val = sec.get("max_unknown_time")) - MAX_UNKNOWN_TIME = seconds{beast::lexicalCastThrow(*val)}; + maxUnknownTime = seconds{beast::lexicalCastThrow(*val)}; } catch (...) { @@ -877,7 +875,7 @@ Config::loadFromString(std::string const& fileContents) ": must be of the form '' representing seconds."); } - if (MAX_UNKNOWN_TIME < seconds{300} || MAX_UNKNOWN_TIME > seconds{1800}) + if (maxUnknownTime < seconds{300} || maxUnknownTime > seconds{1800}) { Throw( "Invalid value 'max_unknown_time' in " SECTION_OVERLAY @@ -887,7 +885,7 @@ Config::loadFromString(std::string const& fileContents) try { if (auto val = sec.get("max_diverged_time")) - MAX_DIVERGED_TIME = seconds{beast::lexicalCastThrow(*val)}; + maxDivergedTime = seconds{beast::lexicalCastThrow(*val)}; } catch (...) { @@ -895,7 +893,7 @@ Config::loadFromString(std::string const& fileContents) ": must be of the form '' representing seconds."); } - if (MAX_DIVERGED_TIME < seconds{60} || MAX_DIVERGED_TIME > seconds{900}) + 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."); @@ -917,22 +915,22 @@ Config::loadFromString(std::string const& fileContents) if (boost::iequals(match[2], "minutes")) { - AMENDMENT_MAJORITY_TIME = minutes(duration); + amendmentMajorityTime = minutes(duration); } else if (boost::iequals(match[2], "hours")) { - AMENDMENT_MAJORITY_TIME = hours(duration); + amendmentMajorityTime = hours(duration); } else if (boost::iequals(match[2], "days")) { - AMENDMENT_MAJORITY_TIME = days(duration); + amendmentMajorityTime = days(duration); } else if (boost::iequals(match[2], "weeks")) { - AMENDMENT_MAJORITY_TIME = weeks(duration); + amendmentMajorityTime = weeks(duration); } - if (AMENDMENT_MAJORITY_TIME < minutes(15)) + if (amendmentMajorityTime < minutes(15)) { Throw("Invalid " SECTION_AMENDMENT_MAJORITY_TIME ", the minimum amount of time an amendment must hold a " @@ -941,10 +939,10 @@ Config::loadFromString(std::string const& fileContents) } if (getSingleSection(secConfig, SECTION_BETA_RPC_API, strTemp, j_)) - BETA_RPC_API = beast::lexicalCastThrow(strTemp); + betaRpcApi = beast::lexicalCastThrow(strTemp); // Do not load trusted validator configuration for standalone mode - if (!RUN_STANDALONE_) + if (!runStandalone_) { // If a file was explicitly specified, then throw if the // path is malformed or if the file does not exist or is @@ -966,8 +964,8 @@ Config::loadFromString(std::string const& fileContents) "]"); } - if (!validatorsFile.is_absolute() && !CONFIG_DIR.empty()) - validatorsFile = CONFIG_DIR / validatorsFile; + if (!validatorsFile.is_absolute() && !configDir.empty()) + validatorsFile = configDir / validatorsFile; if (!boost::filesystem::exists(validatorsFile)) { @@ -986,9 +984,9 @@ Config::loadFromString(std::string const& fileContents) validatorsFile.string()); } } - else if (!CONFIG_DIR.empty()) + else if (!configDir.empty()) { - validatorsFile = CONFIG_DIR / kValidatorsFileName; + validatorsFile = configDir / kValidatorsFileName; if (!validatorsFile.empty()) { @@ -1061,7 +1059,7 @@ Config::loadFromString(std::string const& fileContents) } } - VALIDATOR_LIST_THRESHOLD = [&]() -> std::optional { + validatorListThreshold = [&]() -> std::optional { auto const& listThreshold = section(SECTION_VALIDATOR_LIST_THRESHOLD); if (listThreshold.lines().empty()) { @@ -1119,14 +1117,14 @@ Config::loadFromString(std::string const& fileContents) // This doesn't properly belong here, but check to make sure that the // value specified for network_quorum is achievable: { - auto pm = PEERS_MAX; + auto pm = peersMax; // FIXME this apparently magic value is actually defined as a constant // elsewhere (see defaultMaxPeers) but we handle this check here. if (pm == 0) pm = 21; - if (NETWORK_QUORUM > pm) + if (networkQuorum > pm) { Throw( "The minimum number of required peers (network_quorum) exceeds " @@ -1138,13 +1136,13 @@ Config::loadFromString(std::string const& fileContents) boost::filesystem::path Config::getDebugLogFile() const { - auto logFile = DEBUG_LOGFILE_; + auto logFile = debugLogfile_; if (!logFile.empty() && !logFile.is_absolute()) { // Unless an absolute path for the log file is specified, the // path is relative to the config file directory. - logFile = boost::filesystem::absolute(logFile, CONFIG_DIR); + logFile = boost::filesystem::absolute(logFile, configDir); } if (!logFile.empty()) @@ -1175,7 +1173,7 @@ Config::getValueFor(SizedItem item, std::optional node) const auto const index = static_cast>(item); XRPL_ASSERT(index < kSizedItems.size(), "xrpl::Config::getValueFor : valid index input"); XRPL_ASSERT(!node || *node <= 4, "xrpl::Config::getValueFor : unset or valid node"); - return kSizedItems.at(index).second.at(node.value_or(NODE_SIZE)); + return kSizedItems.at(index).second.at(node.value_or(nodeSize)); } FeeSetup @@ -1186,14 +1184,14 @@ setupFeeVote(Section const& section) std::uint64_t temp = 0; if (set(temp, "reference_fee", section) && temp <= std::numeric_limits::max()) - setup.reference_fee = temp; + setup.referenceFee = temp; } { std::uint32_t temp = 0; if (set(temp, "account_reserve", section)) - setup.account_reserve = temp; + setup.accountReserve = temp; if (set(temp, "owner_reserve", section)) - setup.owner_reserve = temp; + setup.ownerReserve = temp; } return setup; } @@ -1203,7 +1201,7 @@ setupDatabaseCon(Config const& c, std::optional j) { DatabaseCon::Setup setup; - setup.startUp = c.START_UP; + setup.startUp = c.startUp; setup.standAlone = c.standalone(); setup.dataDir = c.legacy("database_path"); if (!setup.standAlone && setup.dataDir.empty()) @@ -1307,7 +1305,7 @@ setupDatabaseCon(Config const& c, std::optional j) } } - if (showRiskWarning && j && c.LEDGER_HISTORY > kSqliteTuningCutoff) + if (showRiskWarning && j && c.ledgerHistory > kSqliteTuningCutoff) { JLOG(j->warn()) << "reducing the data integrity guarantees from the " "default [sqlite] behavior is not recommended for " diff --git a/src/xrpld/overlay/Message.h b/src/xrpld/overlay/Message.h index 30d4b01cda..cd21ca40c6 100644 --- a/src/xrpld/overlay/Message.h +++ b/src/xrpld/overlay/Message.h @@ -80,7 +80,7 @@ private: std::vector buffer_; std::vector bufferCompressed_; std::size_t category_; - std::once_flag once_flag_; + std::once_flag onceFlag_; std::optional validatorKey_; /** Set the payload header diff --git a/src/xrpld/overlay/Slot.h b/src/xrpld/overlay/Slot.h index 12fecbbf42..0600265500 100644 --- a/src/xrpld/overlay/Slot.h +++ b/src/xrpld/overlay/Slot.h @@ -544,8 +544,8 @@ public: : handler_(handler) , logs_(registry.getLogs()) , journal_(registry.getJournal("Slots")) - , baseSquelchEnabled_(config.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE) - , maxSelectedPeers_(config.VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS) + , baseSquelchEnabled_(config.vpReduceRelayBaseSquelchEnable) + , maxSelectedPeers_(config.vpReduceRelaySquelchMaxSelectedPeers) { } ~Slots() = default; diff --git a/src/xrpld/overlay/detail/ConnectAttempt.cpp b/src/xrpld/overlay/detail/ConnectAttempt.cpp index ad58cc0d2c..1167e19ca3 100644 --- a/src/xrpld/overlay/detail/ConnectAttempt.cpp +++ b/src/xrpld/overlay/detail/ConnectAttempt.cpp @@ -432,10 +432,10 @@ ConnectAttempt::onHandshake(error_code ec) req_ = makeRequest( !overlay_.peerFinder().config().peerPrivate, - app_.config().COMPRESSION, - app_.config().LEDGER_REPLAY, - app_.config().TX_REDUCE_RELAY_ENABLE, - app_.config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE); + app_.config().compression, + app_.config().ledgerReplay, + app_.config().txReduceRelayEnable, + app_.config().vpReduceRelayBaseSquelchEnable); buildHandshake( req_, diff --git a/src/xrpld/overlay/detail/Handshake.cpp b/src/xrpld/overlay/detail/Handshake.cpp index 3465dbb816..39fd93f1d4 100644 --- a/src/xrpld/overlay/detail/Handshake.cpp +++ b/src/xrpld/overlay/detail/Handshake.cpp @@ -209,8 +209,8 @@ buildHandshake( h.insert("Instance-Cookie", std::to_string(app.instanceID())); - if (!app.config().SERVER_DOMAIN.empty()) - h.insert("Server-Domain", app.config().SERVER_DOMAIN); + if (!app.config().serverDomain.empty()) + h.insert("Server-Domain", app.config().serverDomain); if (beast::IP::isPublic(remoteIp)) h.insert("Remote-IP", remoteIp.to_string()); @@ -408,10 +408,10 @@ makeResponse( "X-Protocol-Ctl", makeFeaturesResponseHeader( req, - app.config().COMPRESSION, - app.config().LEDGER_REPLAY, - app.config().TX_REDUCE_RELAY_ENABLE, - app.config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE)); + app.config().compression, + app.config().ledgerReplay, + app.config().txReduceRelayEnable, + app.config().vpReduceRelayBaseSquelchEnable)); buildHandshake(resp, sharedValue, networkID, publicIp, remoteIp, app); diff --git a/src/xrpld/overlay/detail/Message.cpp b/src/xrpld/overlay/detail/Message.cpp index 68629ce9a4..120b34c78c 100644 --- a/src/xrpld/overlay/detail/Message.cpp +++ b/src/xrpld/overlay/detail/Message.cpp @@ -203,7 +203,7 @@ Message::getBuffer(Compressed tryCompressed) if (tryCompressed == Compressed::Off) return buffer_; - std::call_once(once_flag_, &Message::compress, this); + std::call_once(onceFlag_, &Message::compress, this); if (!bufferCompressed_.empty()) { diff --git a/src/xrpld/overlay/detail/OverlayImpl.cpp b/src/xrpld/overlay/detail/OverlayImpl.cpp index a39002bd51..b31f54058a 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.cpp +++ b/src/xrpld/overlay/detail/OverlayImpl.cpp @@ -112,7 +112,7 @@ OverlayImpl::Child::~Child() //------------------------------------------------------------------------------ -OverlayImpl::Timer::Timer(OverlayImpl& overlay) : Child(overlay), timer(overlay_.io_context_) +OverlayImpl::Timer::Timer(OverlayImpl& overlay) : Child(overlay), timer(overlay_.ioContext_) { } @@ -150,10 +150,10 @@ OverlayImpl::Timer::onTimer(error_code ec) overlay_.peerFinder_->oncePerSecond(); overlay_.sendEndpoints(); overlay_.autoConnect(); - if (overlay_.app_.config().TX_REDUCE_RELAY_ENABLE) + if (overlay_.app_.config().txReduceRelayEnable) overlay_.sendTxQueue(); - if ((++overlay_.timer_count_ % Tuning::kCheckIdlePeers) == 0) + if ((++overlay_.timerCount_ % Tuning::kCheckIdlePeers) == 0) overlay_.deleteIdlePeers(); asyncWait(); @@ -171,9 +171,9 @@ OverlayImpl::OverlayImpl( BasicConfig const& config, beast::insight::Collector::ptr const& collector) : app_(app) - , io_context_(ioContext) - , work_(std::in_place, boost::asio::make_work_guard(io_context_)) - , strand_(boost::asio::make_strand(io_context_)) + , ioContext_(ioContext) + , work_(std::in_place, boost::asio::make_work_guard(ioContext_)) + , strand_(boost::asio::make_strand(ioContext_)) , setup_(std::move(setup)) , journal_(app_.getJournal("Overlay")) , serverHandler_(serverHandler) @@ -186,7 +186,7 @@ OverlayImpl::OverlayImpl( config, collector)) , resolver_(resolver) - , next_id_(1) + , nextId_(1) , slots_(app, *this, app.config()) , stats_( std::bind(&OverlayImpl::collectMetrics, this), @@ -209,7 +209,7 @@ OverlayImpl::onHandoff( http_request_type&& request, endpoint_type remoteEndpoint) { - auto const id = next_id_++; + auto const id = nextId_++; auto peerJournal = app_.getJournal("Peer"); beast::WrappedSink sink(peerJournal.sink(), makePrefix(id)); beast::Journal const journal(sink); @@ -259,7 +259,7 @@ OverlayImpl::onHandoff( { handoff.moved = false; handoff.response = makeRedirectResponse(slot, request, remoteEndpoint.address()); - handoff.keep_alive = beast::rfc2616::isKeepAlive(request); + handoff.keepAlive = beast::rfc2616::isKeepAlive(request); return handoff; } } @@ -271,7 +271,7 @@ OverlayImpl::onHandoff( handoff.moved = false; handoff.response = makeErrorResponse( slot, request, remoteEndpoint.address(), "Unable to agree on a protocol version"); - handoff.keep_alive = false; + handoff.keepAlive = false; return handoff; } @@ -282,7 +282,7 @@ OverlayImpl::onHandoff( handoff.moved = false; handoff.response = makeErrorResponse(slot, request, remoteEndpoint.address(), "Incorrect security cookie"); - handoff.keep_alive = false; + handoff.keepAlive = false; return handoff; } @@ -311,7 +311,7 @@ OverlayImpl::onHandoff( << "Peer " << remoteEndpoint << " redirected, " << to_string(result); handoff.moved = false; handoff.response = makeRedirectResponse(slot, request, remoteEndpoint.address()); - handoff.keep_alive = false; + handoff.keepAlive = false; return handoff; } } @@ -351,7 +351,7 @@ OverlayImpl::onHandoff( peerFinder_->onClosed(slot); handoff.moved = false; handoff.response = makeErrorResponse(slot, request, remoteEndpoint.address(), e.what()); - handoff.keep_alive = false; + handoff.keepAlive = false; return handoff; } } @@ -444,11 +444,11 @@ OverlayImpl::connect(beast::IP::Endpoint const& remoteEndpoint) auto const p = std::make_shared( app_, - io_context_, + ioContext_, beast::IPAddressConversion::toAsioEndpoint(remoteEndpoint), usage, setup_.context, - next_id_++, + nextId_++, slot, app_.getJournal("Peer"), *this); @@ -516,7 +516,7 @@ OverlayImpl::start() // Populate our boot cache: if there are no entries in [ips] then we use // the entries in [ips_fixed]. - auto bootstrapIps = app_.config().IPS.empty() ? app_.config().IPS_FIXED : app_.config().IPS; + auto bootstrapIps = app_.config().ips.empty() ? app_.config().ipsFixed : app_.config().ips; // If nothing is specified, default to several well-known high-capacity // servers to serve as bootstrap: @@ -558,10 +558,10 @@ OverlayImpl::start() }); // Add the ips_fixed from the xrpld.cfg file - if (!app_.config().standalone() && !app_.config().IPS_FIXED.empty()) + if (!app_.config().standalone() && !app_.config().ipsFixed.empty()) { resolver_.resolve( - app_.config().IPS_FIXED, + app_.config().ipsFixed, [this](std::string const& name, std::vector const& addresses) { std::vector ips; ips.reserve(addresses.size()); @@ -1257,7 +1257,7 @@ OverlayImpl::relay( if (!relay) { - if (!app_.config().TX_REDUCE_RELAY_ENABLE) + if (!app_.config().txReduceRelayEnable) return; peers = getActivePeers(toSkip, total, disabled, enabledInSkip); @@ -1270,13 +1270,13 @@ OverlayImpl::relay( auto& txn = tx->get(); auto const sm = std::make_shared(txn, protocol::mtTRANSACTION); peers = getActivePeers(toSkip, total, disabled, enabledInSkip); - auto const minRelay = app_.config().TX_REDUCE_RELAY_MIN_PEERS + disabled; + auto const minRelay = app_.config().txReduceRelayMinPeers + disabled; - if (!app_.config().TX_REDUCE_RELAY_ENABLE || total <= minRelay) + if (!app_.config().txReduceRelayEnable || total <= minRelay) { for (auto const& p : peers) p->send(sm); - if (app_.config().TX_REDUCE_RELAY_ENABLE || app_.config().TX_REDUCE_RELAY_METRICS) + if (app_.config().txReduceRelayEnable || app_.config().txReduceRelayMetrics) txMetrics_.addMetrics(total, toSkip.size(), 0); return; } @@ -1284,8 +1284,8 @@ OverlayImpl::relay( // We have more peers than the minimum (disabled + minimum enabled), // relay to all disabled and some randomly selected enabled that // do not have the transaction. - auto const enabledTarget = app_.config().TX_REDUCE_RELAY_MIN_PEERS + - ((total - minRelay) * app_.config().TX_RELAY_PERCENTAGE / 100); + auto const enabledTarget = app_.config().txReduceRelayMinPeers + + ((total - minRelay) * app_.config().txRelayPercentage / 100); txMetrics_.addMetrics(enabledTarget, toSkip.size(), disabled); diff --git a/src/xrpld/overlay/detail/OverlayImpl.h b/src/xrpld/overlay/detail/OverlayImpl.h index 65c93a5845..6fcc2df854 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.h +++ b/src/xrpld/overlay/detail/OverlayImpl.h @@ -80,7 +80,7 @@ private: }; Application& app_; - boost::asio::io_context& io_context_; + boost::asio::io_context& ioContext_; std::optional> work_; boost::asio::strand strand_; mutable std::recursive_mutex mutex_; // VFALCO use std::mutex @@ -96,8 +96,8 @@ private: hash_map, std::weak_ptr> peers_; hash_map> ids_; Resolver& resolver_; - std::atomic next_id_; - int timer_count_{0}; + std::atomic nextId_; + int timerCount_{0}; std::atomic jqTransOverflow_{0}; std::atomic peerDisconnects_{0}; std::atomic peerDisconnectsCharges_{0}; diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 070f91c0bf..23e1785f6b 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -158,22 +158,20 @@ PeerImp::PeerImp( , request_(std::move(request)) , headers_(request_) , compressionEnabled_( - peerFeatureEnabled(headers_, kFeatureCompr, "lz4", app_.config().COMPRESSION) + peerFeatureEnabled(headers_, kFeatureCompr, "lz4", app_.config().compression) ? Compressed::On : Compressed::Off) , txReduceRelayEnabled_( - peerFeatureEnabled(headers_, kFeatureTxrr, app_.config().TX_REDUCE_RELAY_ENABLE)) + peerFeatureEnabled(headers_, kFeatureTxrr, app_.config().txReduceRelayEnable)) , ledgerReplayEnabled_( - peerFeatureEnabled(headers_, kFeatureLedgerReplay, app_.config().LEDGER_REPLAY)) + peerFeatureEnabled(headers_, kFeatureLedgerReplay, app_.config().ledgerReplay)) , ledgerReplayMsgHandler_(app, app.getLedgerReplayer()) { - JLOG(journal_.info()) << "compression enabled " << (compressionEnabled_ == Compressed::On) - << " vp reduce-relay base squelch enabled " - << peerFeatureEnabled( - headers_, - kFeatureVprr, - app_.config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE) - << " tx reduce-relay enabled " << txReduceRelayEnabled_; + JLOG(journal_.info()) + << "compression enabled " << (compressionEnabled_ == Compressed::On) + << " vp reduce-relay base squelch enabled " + << peerFeatureEnabled(headers_, kFeatureVprr, app_.config().vpReduceRelayBaseSquelchEnable) + << " tx reduce-relay enabled " << txReduceRelayEnabled_; } PeerImp::~PeerImp() @@ -817,8 +815,8 @@ PeerImp::onTimer(error_code const& ec) duration = clock_type::now() - trackingTime_; } - if ((t == Tracking::Diverged && (duration > app_.config().MAX_DIVERGED_TIME)) || - (t == Tracking::Unknown && (duration > app_.config().MAX_UNKNOWN_TIME))) + if ((t == Tracking::Diverged && (duration > app_.config().maxDivergedTime)) || + (t == Tracking::Unknown && (duration > app_.config().maxUnknownTime))) { overlay_.peerFinder().onFailure(slot_); fail("Not useful"); @@ -1208,7 +1206,7 @@ PeerImp::onMessageBegin( // LEDGER_DATA category == TrafficCount::Category::GlTscShare || category == TrafficCount::Category::GlTscGet) && - (txReduceRelayEnabled() || app_.config().TX_REDUCE_RELAY_METRICS)) + (txReduceRelayEnabled() || app_.config().txReduceRelayMetrics)) { overlay_.addTxMetrics(static_cast(type), static_cast(size)); } @@ -1518,7 +1516,7 @@ PeerImp::handleTransaction( { JLOG(pJournal_.trace()) << "No new transactions until synchronized"; } - else if (app_.getJobQueue().getJobCount(JtTransaction) > app_.config().MAX_TRANSACTIONS) + else if (app_.getJobQueue().getJobCount(JtTransaction) > app_.config().maxTransactions) { overlay_.incJqTransOverflow(); JLOG(pJournal_.info()) << "Transaction queue is full"; @@ -1889,7 +1887,7 @@ PeerImp::onMessage(std::shared_ptr const& m) overlay_.reportInboundTraffic( TrafficCount::Category::ProposalUntrusted, Message::messageSize(*m)); - if (app_.config().RELAY_UNTRUSTED_PROPOSALS == -1) + if (app_.config().relayUntrustedProposals == -1) return; } @@ -2496,7 +2494,7 @@ PeerImp::onMessage(std::shared_ptr const& m) overlay_.reportInboundTraffic( TrafficCount::Category::ValidationUntrusted, Message::messageSize(*m)); - if (app_.config().RELAY_UNTRUSTED_VALIDATIONS == -1) + if (app_.config().relayUntrustedValidations == -1) return; } @@ -3093,7 +3091,7 @@ PeerImp::checkPropose( } else { - relay = app_.config().RELAY_UNTRUSTED_PROPOSALS == 1 || cluster(); + relay = app_.config().relayUntrustedProposals == 1 || cluster(); } if (relay) diff --git a/src/xrpld/overlay/detail/PeerImp.h b/src/xrpld/overlay/detail/PeerImp.h index 9c66347810..dca70d88bd 100644 --- a/src/xrpld/overlay/detail/PeerImp.h +++ b/src/xrpld/overlay/detail/PeerImp.h @@ -839,25 +839,23 @@ PeerImp::PeerImp( , response_(std::move(response)) , headers_(response_) , compressionEnabled_( - peerFeatureEnabled(headers_, kFeatureCompr, "lz4", app_.config().COMPRESSION) + peerFeatureEnabled(headers_, kFeatureCompr, "lz4", app_.config().compression) ? Compressed::On : Compressed::Off) , txReduceRelayEnabled_( - peerFeatureEnabled(headers_, kFeatureTxrr, app_.config().TX_REDUCE_RELAY_ENABLE)) + peerFeatureEnabled(headers_, kFeatureTxrr, app_.config().txReduceRelayEnable)) , ledgerReplayEnabled_( - peerFeatureEnabled(headers_, kFeatureLedgerReplay, app_.config().LEDGER_REPLAY)) + peerFeatureEnabled(headers_, kFeatureLedgerReplay, app_.config().ledgerReplay)) , ledgerReplayMsgHandler_(app, app.getLedgerReplayer()) { readBuffer_.commit( boost::asio::buffer_copy(readBuffer_.prepare(boost::asio::buffer_size(buffers)), buffers)); - JLOG(journal_.info()) << "compression enabled " << (compressionEnabled_ == Compressed::On) - << " vp reduce-relay base squelch enabled " - << peerFeatureEnabled( - headers_, - kFeatureVprr, - app_.config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE) - << " tx reduce-relay enabled " << txReduceRelayEnabled_ << " on " - << remoteAddress_ << " " << id_; + JLOG(journal_.info()) + << "compression enabled " << (compressionEnabled_ == Compressed::On) + << " vp reduce-relay base squelch enabled " + << peerFeatureEnabled(headers_, kFeatureVprr, app_.config().vpReduceRelayBaseSquelchEnable) + << " tx reduce-relay enabled " << txReduceRelayEnabled_ << " on " << remoteAddress_ << " " + << id_; } template diff --git a/src/xrpld/overlay/detail/ProtocolMessage.h b/src/xrpld/overlay/detail/ProtocolMessage.h index ab41cbe337..b1a30bad10 100644 --- a/src/xrpld/overlay/detail/ProtocolMessage.h +++ b/src/xrpld/overlay/detail/ProtocolMessage.h @@ -98,19 +98,19 @@ struct MessageHeader @note This is the sum of sizes of the header and the payload. */ - std::uint32_t total_wire_size = 0; + std::uint32_t totalWireSize = 0; /** The size of the header associated with this message. */ - std::uint32_t header_size = 0; + std::uint32_t headerSize = 0; /** The size of the payload on the wire. */ - std::uint32_t payload_wire_size = 0; + std::uint32_t payloadWireSize = 0; /** Uncompressed message size if the message is compressed. */ - std::uint32_t uncompressed_size = 0; + std::uint32_t uncompressedSize = 0; /** The type of the message. */ - std::uint16_t message_type = 0; + std::uint16_t messageType = 0; /** Indicates which compression algorithm the payload is compressed with. * Currently only lz4 is supported. If None then the message is not @@ -159,10 +159,10 @@ parseMessageHeader(boost::system::error_code& ec, BufferSequence const& bufs, st // - 32 bits are the uncompressed data size if (*iter & 0x80) { - hdr.header_size = kHeaderBytesCompressed; + hdr.headerSize = kHeaderBytesCompressed; // not enough bytes to parse the header - if (size < hdr.header_size) + if (size < hdr.headerSize) { ec = make_error_code(boost::system::errc::success); return std::nullopt; @@ -183,18 +183,18 @@ parseMessageHeader(boost::system::error_code& ec, BufferSequence const& bufs, st } for (int i = 0; i != 4; ++i) - hdr.payload_wire_size = (hdr.payload_wire_size << 8) + *iter++; + hdr.payloadWireSize = (hdr.payloadWireSize << 8) + *iter++; // clear the top four bits (the compression bits). - hdr.payload_wire_size &= 0x0FFFFFFF; + hdr.payloadWireSize &= 0x0FFFFFFF; - hdr.total_wire_size = hdr.header_size + hdr.payload_wire_size; + hdr.totalWireSize = hdr.headerSize + hdr.payloadWireSize; for (int i = 0; i != 2; ++i) - hdr.message_type = (hdr.message_type << 8) + *iter++; + hdr.messageType = (hdr.messageType << 8) + *iter++; for (int i = 0; i != 4; ++i) - hdr.uncompressed_size = (hdr.uncompressed_size << 8) + *iter++; + hdr.uncompressedSize = (hdr.uncompressedSize << 8) + *iter++; return hdr; } @@ -204,9 +204,9 @@ parseMessageHeader(boost::system::error_code& ec, BufferSequence const& bufs, st // - 26 bits are the payload size if ((*iter & 0xFC) == 0) { - hdr.header_size = kHeaderBytes; + hdr.headerSize = kHeaderBytes; - if (size < hdr.header_size) + if (size < hdr.headerSize) { ec = make_error_code(boost::system::errc::success); return std::nullopt; @@ -215,13 +215,13 @@ parseMessageHeader(boost::system::error_code& ec, BufferSequence const& bufs, st hdr.algorithm = Algorithm::None; for (int i = 0; i != 4; ++i) - hdr.payload_wire_size = (hdr.payload_wire_size << 8) + *iter++; + hdr.payloadWireSize = (hdr.payloadWireSize << 8) + *iter++; - hdr.uncompressed_size = hdr.payload_wire_size; - hdr.total_wire_size = hdr.header_size + hdr.payload_wire_size; + hdr.uncompressedSize = hdr.payloadWireSize; + hdr.totalWireSize = hdr.headerSize + hdr.payloadWireSize; for (int i = 0; i != 2; ++i) - hdr.message_type = (hdr.message_type << 8) + *iter++; + hdr.messageType = (hdr.messageType << 8) + *iter++; return hdr; } @@ -240,18 +240,18 @@ parseMessageContent(MessageHeader const& header, Buffers const& buffers) auto m = std::make_shared(); ZeroCopyInputStream stream(buffers); - stream.Skip(header.header_size); + stream.Skip(header.headerSize); if (header.algorithm != compression::Algorithm::None) { std::vector payload; - payload.resize(header.uncompressed_size); + payload.resize(header.uncompressedSize); auto const payloadSize = xrpl::compression::decompress( stream, - header.payload_wire_size, + header.payloadWireSize, payload.data(), - header.uncompressed_size, + header.uncompressedSize, header.algorithm); if (payloadSize == 0 || !m->ParseFromArray(payload.data(), payloadSize)) @@ -279,13 +279,13 @@ invoke(MessageHeader const& header, Buffers const& buffers, Handler& handler) using namespace xrpl::compression; handler.onMessageBegin( - header.message_type, + header.messageType, m, - header.payload_wire_size, - header.uncompressed_size, + header.payloadWireSize, + header.uncompressedSize, header.algorithm != Algorithm::None); handler.onMessage(m); - handler.onMessageEnd(header.message_type, m); + handler.onMessageEnd(header.messageType, m); return true; } @@ -329,8 +329,8 @@ invokeProtocolMessage(Buffers const& buffers, Handler& handler, std::size_t& hin // whose size exceeds this may result in the connection being dropped. A // larger message size may be supported in the future or negotiated as // part of a protocol upgrade. - if (header->payload_wire_size > kMaximumMessageSize || - header->uncompressed_size > kMaximumMessageSize) + if (header->payloadWireSize > kMaximumMessageSize || + header->uncompressedSize > kMaximumMessageSize) { result.second = make_error_code(boost::system::errc::message_size); return result; @@ -345,15 +345,15 @@ invokeProtocolMessage(Buffers const& buffers, Handler& handler, std::size_t& hin // We don't have the whole message yet. This isn't an error but we have // nothing to do. - if (header->total_wire_size > size) + if (header->totalWireSize > size) { - hint = header->total_wire_size - size; + hint = header->totalWireSize - size; return result; } bool success = false; - switch (header->message_type) + switch (header->messageType) { case protocol::mtMANIFESTS: success = detail::invoke(*header, buffers, handler); @@ -420,12 +420,12 @@ invokeProtocolMessage(Buffers const& buffers, Handler& handler, std::size_t& hin success = detail::invoke(*header, buffers, handler); break; default: - handler.onMessageUnknown(header->message_type); + handler.onMessageUnknown(header->messageType); success = true; break; } - result.first = header->total_wire_size; + result.first = header->totalWireSize; if (!success) result.second = make_error_code(boost::system::errc::bad_message); diff --git a/src/xrpld/overlay/detail/TxMetrics.cpp b/src/xrpld/overlay/detail/TxMetrics.cpp index 2df072ef0c..d2597cb19f 100644 --- a/src/xrpld/overlay/detail/TxMetrics.cpp +++ b/src/xrpld/overlay/detail/TxMetrics.cpp @@ -77,13 +77,13 @@ SingleMetrics::addMetrics(std::uint32_t val) { using namespace std::chrono_literals; accum += val; - N++; + n++; auto const timeElapsed = clock_type::now() - intervalStart; auto const timeElapsedInSecs = std::chrono::duration_cast(timeElapsed); if (timeElapsedInSecs >= 1s) { - auto const avg = accum / (perTimeUnit ? timeElapsedInSecs.count() : N); + auto const avg = accum / (perTimeUnit ? timeElapsedInSecs.count() : n); rollingAvgAggregate.push_back(avg); auto const total = @@ -92,7 +92,7 @@ SingleMetrics::addMetrics(std::uint32_t val) intervalStart = clock_type::now(); accum = 0; - N = 0; + n = 0; } } diff --git a/src/xrpld/overlay/detail/TxMetrics.h b/src/xrpld/overlay/detail/TxMetrics.h index 7b8b4bae1b..50df7a65cc 100644 --- a/src/xrpld/overlay/detail/TxMetrics.h +++ b/src/xrpld/overlay/detail/TxMetrics.h @@ -29,7 +29,7 @@ struct SingleMetrics clock_type::time_point intervalStart{clock_type::now()}; std::uint64_t accum{0}; std::uint64_t rollingAvg{0}; - std::uint32_t N{0}; + std::uint32_t n{0}; bool perTimeUnit{true}; boost::circular_buffer rollingAvgAggregate{30, 0ull}; /** Add metrics value diff --git a/src/xrpld/peerfinder/detail/Counts.h b/src/xrpld/peerfinder/detail/Counts.h index ff88421e09..67b8370996 100644 --- a/src/xrpld/peerfinder/detail/Counts.h +++ b/src/xrpld/peerfinder/detail/Counts.h @@ -42,9 +42,9 @@ public: return true; if (s.inbound()) - return in_active_ < in_max_; + return inActive_ < inMax_; - return out_active_ < out_max_; + return outActive_ < outMax_; } /** Returns the number of attempts needed to bring us to the max. */ @@ -67,7 +67,7 @@ public: [[nodiscard]] int outMax() const { - return out_max_; + return outMax_; } /** Returns the number of outbound peers assigned an open slot. @@ -76,7 +76,7 @@ public: [[nodiscard]] int outActive() const { - return out_active_; + return outActive_; } /** Returns the number of fixed connections. */ @@ -90,7 +90,7 @@ public: [[nodiscard]] std::size_t fixedActive() const { - return fixed_active_; + return fixedActive_; } //-------------------------------------------------------------------------- @@ -99,9 +99,9 @@ public: void onConfig(Config const& config) { - out_max_ = config.outPeers; + outMax_ = config.outPeers; if (config.wantIncoming) - in_max_ = config.inPeers; + inMax_ = config.inPeers; } /** Returns the number of accepted connections that haven't handshaked. */ @@ -129,21 +129,21 @@ public: [[nodiscard]] int inMax() const { - return in_max_; + return inMax_; } /** Returns the number of inbound peers assigned an open slot. */ [[nodiscard]] int inboundActive() const { - return in_active_; + return inActive_; } /** Returns the total number of active peers excluding fixed peers. */ [[nodiscard]] int totalActive() const { - return in_active_ + out_active_; + return inActive_ + outActive_; } /** Returns the number of unused inbound slots. @@ -152,8 +152,8 @@ public: [[nodiscard]] int inboundSlotsFree() const { - if (in_active_ < in_max_) - return in_max_ - in_active_; + if (inActive_ < inMax_) + return inMax_ - inActive_; return 0; } @@ -163,8 +163,8 @@ public: [[nodiscard]] int outboundSlotsFree() const { - if (out_active_ < out_max_) - return out_max_ - out_active_; + if (outActive_ < outMax_) + return outMax_ - outActive_; return 0; } @@ -181,7 +181,7 @@ public: // // Fixed peers do not count towards the active outgoing total. - return out_max_ <= 0; + return outMax_ <= 0; } /** Output statistics. */ @@ -191,9 +191,9 @@ public: map["accept"] = acceptCount(); map["connect"] = connectCount(); map["close"] = closingCount(); - map["in"] << in_active_ << "/" << in_max_; - map["out"] << out_active_ << "/" << out_max_; - map["fixed"] = fixed_active_; + map["in"] << inActive_ << "/" << inMax_; + map["out"] << outActive_ << "/" << outMax_; + map["fixed"] = fixedActive_; map["reserved"] = reserved_; map["total"] = active_; } @@ -203,7 +203,7 @@ public: stateString() const { std::stringstream ss; - ss << out_active_ << "/" << out_max_ << " out, " << in_active_ << "/" << in_max_ << " in, " + ss << outActive_ << "/" << outMax_ << " out, " << inActive_ << "/" << inMax_ << " in, " << connectCount() << " connecting, " << closingCount() << " closing"; return ss.str(); } @@ -262,16 +262,16 @@ private: case Slot::State::Active: if (s.fixed()) - adjustCounter(fixed_active_, dir); + adjustCounter(fixedActive_, dir); if (!s.fixed() && !s.reserved()) { if (s.inbound()) { - adjustCounter(in_active_, dir); + adjustCounter(inActive_, dir); } else { - adjustCounter(out_active_, dir); + adjustCounter(outActive_, dir); } } adjustCounter(active_, dir); @@ -297,22 +297,22 @@ private: std::size_t active_{0}; /** Total number of inbound slots. */ - std::size_t in_max_{0}; + std::size_t inMax_{0}; /** Number of inbound slots assigned to active peers. */ - std::size_t in_active_{0}; + std::size_t inActive_{0}; /** Maximum desired outbound slots. */ - std::size_t out_max_{0}; + std::size_t outMax_{0}; /** Active outbound slots. */ - std::size_t out_active_{0}; + std::size_t outActive_{0}; /** Fixed connections. */ std::size_t fixed_{0}; /** Active fixed connections. */ - std::size_t fixed_active_{0}; + std::size_t fixedActive_{0}; /** Reserved connections. */ std::size_t reserved_{0}; diff --git a/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp b/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp index bbaeeff8e6..fcf30fa4f4 100644 --- a/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp +++ b/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp @@ -63,15 +63,15 @@ Config::makeConfig( { PeerFinder::Config config; - config.peerPrivate = cfg.PEER_PRIVATE; + config.peerPrivate = cfg.peerPrivate; // Servers with peer privacy don't want to allow incoming connections config.wantIncoming = (!config.peerPrivate) && (port != 0); - if ((cfg.PEERS_OUT_MAX == 0u) && (cfg.PEERS_IN_MAX == 0u)) + if ((cfg.peersOutMax == 0u) && (cfg.peersInMax == 0u)) { - if (cfg.PEERS_MAX != 0) - config.maxPeers = cfg.PEERS_MAX; + if (cfg.peersMax != 0) + config.maxPeers = cfg.peersMax; config.maxPeers = std::max(config.maxPeers, Tuning::kMinOutCount); config.outPeers = config.calcOutPeers(); @@ -94,8 +94,8 @@ Config::makeConfig( } else { - config.outPeers = cfg.PEERS_OUT_MAX; - config.inPeers = cfg.PEERS_IN_MAX; + config.outPeers = cfg.peersOutMax; + config.inPeers = cfg.peersInMax; config.maxPeers = 0; } @@ -108,7 +108,7 @@ Config::makeConfig( // if it's a private peer or we are running as standalone // automatic connections would defeat the purpose. - config.autoConnect = !cfg.standalone() && !cfg.PEER_PRIVATE; + config.autoConnect = !cfg.standalone() && !cfg.peerPrivate; config.listeningPort = port; config.features = ""; config.ipLimit = ipLimit; diff --git a/src/xrpld/peerfinder/detail/SlotImp.cpp b/src/xrpld/peerfinder/detail/SlotImp.cpp index f6ff24e6a6..a54ddb56e7 100644 --- a/src/xrpld/peerfinder/detail/SlotImp.cpp +++ b/src/xrpld/peerfinder/detail/SlotImp.cpp @@ -23,9 +23,9 @@ SlotImp::SlotImp( , fixed_(fixed) , reserved_(false) , state_(State::Accept) - , remote_endpoint_(std::move(remoteEndpoint)) - , local_endpoint_(localEndpoint) - , listening_port_(kUnknownPort) + , remoteEndpoint_(std::move(remoteEndpoint)) + , localEndpoint_(localEndpoint) + , listeningPort_(kUnknownPort) , checked(false) , canAccept(false) , connectivityCheckInProgress(false) @@ -38,8 +38,8 @@ SlotImp::SlotImp(beast::IP::Endpoint remoteEndpoint, bool fixed, clock_type& clo , fixed_(fixed) , reserved_(false) , state_(State::Connect) - , remote_endpoint_(std::move(remoteEndpoint)) - , listening_port_(kUnknownPort) + , remoteEndpoint_(std::move(remoteEndpoint)) + , listeningPort_(kUnknownPort) , checked(true) , canAccept(true) , connectivityCheckInProgress(false) diff --git a/src/xrpld/peerfinder/detail/SlotImp.h b/src/xrpld/peerfinder/detail/SlotImp.h index 0d09a37539..0cf4d7a3c8 100644 --- a/src/xrpld/peerfinder/detail/SlotImp.h +++ b/src/xrpld/peerfinder/detail/SlotImp.h @@ -52,19 +52,19 @@ public: beast::IP::Endpoint const& remoteEndpoint() const override { - return remote_endpoint_; + return remoteEndpoint_; } std::optional const& localEndpoint() const override { - return local_endpoint_; + return localEndpoint_; } std::optional const& publicKey() const override { - return public_key_; + return publicKey_; } std::string @@ -76,7 +76,7 @@ public: std::optional listeningPort() const override { - std::uint32_t const value = listening_port_; + std::uint32_t const value = listeningPort_; if (value == kUnknownPort) return std::nullopt; return value; @@ -85,25 +85,25 @@ public: void setListeningPort(std::uint16_t port) { - listening_port_ = port; + listeningPort_ = port; } void localEndpoint(beast::IP::Endpoint const& endpoint) { - local_endpoint_ = endpoint; + localEndpoint_ = endpoint; } void remoteEndpoint(beast::IP::Endpoint const& endpoint) { - remote_endpoint_ = endpoint; + remoteEndpoint_ = endpoint; } void publicKey(PublicKey const& key) { - public_key_ = key; + publicKey_ = key; } void @@ -160,12 +160,12 @@ private: bool const fixed_; bool reserved_; State state_; - beast::IP::Endpoint remote_endpoint_; - std::optional local_endpoint_; - std::optional public_key_; + beast::IP::Endpoint remoteEndpoint_; + std::optional localEndpoint_; + std::optional publicKey_; static constexpr std::int32_t kUnknownPort = -1; - std::atomic listening_port_; + std::atomic listeningPort_; public: // DEPRECATED public data members diff --git a/src/xrpld/rpc/ServerHandler.h b/src/xrpld/rpc/ServerHandler.h index 6b4cc34cc5..0aac05ea44 100644 --- a/src/xrpld/rpc/ServerHandler.h +++ b/src/xrpld/rpc/ServerHandler.h @@ -46,8 +46,8 @@ public: std::uint16_t port = 0; std::string user; std::string password; - std::string admin_user; - std::string admin_password; + std::string adminUser; + std::string adminPassword; }; // Configuration when acting in client role @@ -72,9 +72,9 @@ private: Setup setup_; Endpoints endpoints_; JobQueue& jobQueue_; - beast::insight::Counter rpc_requests_; - beast::insight::Event rpc_size_; - beast::insight::Event rpc_time_; + beast::insight::Counter rpcRequests_; + beast::insight::Event rpcSize_; + beast::insight::Event rpcTime_; std::mutex mutex_; std::condition_variable condition_; bool stopped_{false}; diff --git a/src/xrpld/rpc/detail/AssetCache.h b/src/xrpld/rpc/detail/AssetCache.h index 9112d78715..dd53620cdf 100644 --- a/src/xrpld/rpc/detail/AssetCache.h +++ b/src/xrpld/rpc/detail/AssetCache.h @@ -56,10 +56,10 @@ private: { AccountID account; LineDirection direction; - std::size_t hash_value; + std::size_t hashValue; AccountKey(AccountID const& account, LineDirection direction, std::size_t hash) - : account(account), direction(direction), hash_value(hash) + : account(account), direction(direction), hashValue(hash) { } @@ -71,14 +71,14 @@ private: bool operator==(AccountKey const& lhs) const { - return hash_value == lhs.hash_value && account == lhs.account && + return hashValue == lhs.hashValue && account == lhs.account && direction == lhs.direction; } [[nodiscard]] std::size_t getHash() const { - return hash_value; + return hashValue; } struct Hash diff --git a/src/xrpld/rpc/detail/PathRequest.cpp b/src/xrpld/rpc/detail/PathRequest.cpp index 6207b3393f..06507319f7 100644 --- a/src/xrpld/rpc/detail/PathRequest.cpp +++ b/src/xrpld/rpc/detail/PathRequest.cpp @@ -101,16 +101,16 @@ PathRequest::~PathRequest() return; std::string fast, full; - if (quick_reply_ != steady_clock::time_point{}) + if (quickReply_ != steady_clock::time_point{}) { fast = " fast:"; - fast += std::to_string(duration_cast(quick_reply_ - created_).count()); + fast += std::to_string(duration_cast(quickReply_ - created_).count()); fast += "ms"; } - if (full_reply_ != steady_clock::time_point{}) + if (fullReply_ != steady_clock::time_point{}) { full = " full:"; - full += std::to_string(duration_cast(full_reply_ - created_).count()); + full += std::to_string(duration_cast(fullReply_ - created_).count()); full += "ms"; } stream << iIdentifier_ << " complete:" << fast << full @@ -180,7 +180,7 @@ PathRequest::isValid(std::shared_ptr const& crCache) if (!raSrcAccount_ || !raDstAccount_) return false; - if (!convert_all_ && (saSendMax_ || saDstAmount_ <= beast::kZero)) + if (!convertAll_ && (saSendMax_ || saDstAmount_ <= beast::kZero)) { // If send max specified, dst amt must be -1. jvStatus_ = rpcError(RpcDstAmtMalformed); @@ -210,7 +210,7 @@ PathRequest::isValid(std::shared_ptr const& crCache) return false; } - if (!convert_all_ && saDstAmount_ < STAmount(lrLedger->fees().reserve)) + if (!convertAll_ && saDstAmount_ < STAmount(lrLedger->fees().reserve)) { // Payment must meet reserve. jvStatus_ = rpcError(RpcDstAmtMalformed); @@ -312,9 +312,9 @@ PathRequest::parseJson(json::Value const& jvParams) return PFR_PJ_INVALID; } - convert_all_ = saDstAmount_ == STAmount(saDstAmount_.asset(), 1u, 0, true); + convertAll_ = saDstAmount_ == STAmount(saDstAmount_.asset(), 1u, 0, true); - if (!validAsset(saDstAmount_.asset()) || (!convert_all_ && saDstAmount_ <= beast::kZero)) + if (!validAsset(saDstAmount_.asset()) || (!convertAll_ && saDstAmount_ <= beast::kZero)) { jvStatus_ = rpcError(RpcDstAmtMalformed); return PFR_PJ_INVALID; @@ -323,7 +323,7 @@ PathRequest::parseJson(json::Value const& jvParams) if (jvParams.isMember(jss::send_max)) { // Send_max requires destination amount to be -1. - if (!convert_all_) + if (!convertAll_) { jvStatus_ = rpcError(RpcDstAmtMalformed); return PFR_PJ_INVALID; @@ -577,7 +577,7 @@ PathRequest::findPaths( } } - auto const dstAmount = convertAmount(saDstAmount_, convert_all_); + auto const dstAmount = convertAmount(saDstAmount_, convertAll_); hash_map> currencyMap; for (auto const& asset : sourceAssets) { @@ -622,7 +622,7 @@ PathRequest::findPaths( JLOG(journal_.debug()) << iIdentifier_ << " Paths found, calling rippleCalc"; path::RippleCalc::Input rcInput; - if (convert_all_) + if (convertAll_) rcInput.partialPaymentAllowed = true; auto sandbox = std::make_unique(&*cache->getLedger(), TapNone); auto rc = path::RippleCalc::rippleCalculate( @@ -639,7 +639,7 @@ PathRequest::findPaths( app_, &rcInput); - if (!convert_all_ && !fullLiquidityPath.empty() && + if (!convertAll_ && !fullLiquidityPath.empty() && (rc.result() == terNO_LINE || rc.result() == tecPATH_PARTIAL)) { JLOG(journal_.debug()) << iIdentifier_ << " Trying with an extra path element"; @@ -679,7 +679,7 @@ PathRequest::findPaths( jvEntry[jss::source_amount] = rc.actualAmountIn.getJson(JsonOptions::Values::None); jvEntry[jss::paths_computed] = ps.getJson(JsonOptions::Values::None); - if (convert_all_) + if (convertAll_) { jvEntry[jss::destination_amount] = rc.actualAmountOut.getJson(JsonOptions::Values::None); @@ -754,33 +754,33 @@ PathRequest::doUpdate( // first pass if (loaded || fast) { - iLevel_ = app_.config().PATH_SEARCH_FAST; + iLevel_ = app_.config().pathSearchFast; } else { - iLevel_ = app_.config().PATH_SEARCH; + iLevel_ = app_.config().pathSearch; } } - else if ((iLevel_ == app_.config().PATH_SEARCH_FAST) && !fast) + else if ((iLevel_ == app_.config().pathSearchFast) && !fast) { // leaving fast pathfinding - iLevel_ = app_.config().PATH_SEARCH; - if (loaded && (iLevel_ > app_.config().PATH_SEARCH_FAST)) + iLevel_ = app_.config().pathSearch; + if (loaded && (iLevel_ > app_.config().pathSearchFast)) --iLevel_; } else if (bLastSuccess_) { // decrement, if possible - if (iLevel_ > app_.config().PATH_SEARCH || - (loaded && (iLevel_ > app_.config().PATH_SEARCH_FAST))) + if (iLevel_ > app_.config().pathSearch || + (loaded && (iLevel_ > app_.config().pathSearchFast))) --iLevel_; } else { // adjust as needed - if (!loaded && (iLevel_ < app_.config().PATH_SEARCH_MAX)) + if (!loaded && (iLevel_ < app_.config().pathSearchMax)) ++iLevel_; - if (loaded && (iLevel_ > app_.config().PATH_SEARCH_FAST)) + if (loaded && (iLevel_ > app_.config().pathSearchFast)) --iLevel_; } @@ -798,15 +798,15 @@ PathRequest::doUpdate( newStatus = rpcError(RpcInternal); } - if (fast && quick_reply_ == steady_clock::time_point{}) + if (fast && quickReply_ == steady_clock::time_point{}) { - quick_reply_ = steady_clock::now(); - owner_.reportFast(duration_cast(quick_reply_ - created_)); + quickReply_ = steady_clock::now(); + owner_.reportFast(duration_cast(quickReply_ - created_)); } - else if (!fast && full_reply_ == steady_clock::time_point{}) + else if (!fast && fullReply_ == steady_clock::time_point{}) { - full_reply_ = steady_clock::now(); - owner_.reportFull(duration_cast(full_reply_ - created_)); + fullReply_ = steady_clock::now(); + owner_.reportFull(duration_cast(fullReply_ - created_)); } { diff --git a/src/xrpld/rpc/detail/PathRequest.h b/src/xrpld/rpc/detail/PathRequest.h index 17381c5ea5..de8c10de0e 100644 --- a/src/xrpld/rpc/detail/PathRequest.h +++ b/src/xrpld/rpc/detail/PathRequest.h @@ -140,7 +140,7 @@ private: std::optional domain_; - bool convert_all_{}; + bool convertAll_{}; std::recursive_mutex indexLock_; LedgerIndex lastIndex_; @@ -152,8 +152,8 @@ private: int const iIdentifier_; std::chrono::steady_clock::time_point const created_; - std::chrono::steady_clock::time_point quick_reply_; - std::chrono::steady_clock::time_point full_reply_; + std::chrono::steady_clock::time_point quickReply_; + std::chrono::steady_clock::time_point fullReply_; static unsigned int const kMaxPaths = 4; }; diff --git a/src/xrpld/rpc/detail/Pathfinder.cpp b/src/xrpld/rpc/detail/Pathfinder.cpp index e949c9b6ff..daa50cfb07 100644 --- a/src/xrpld/rpc/detail/Pathfinder.cpp +++ b/src/xrpld/rpc/detail/Pathfinder.cpp @@ -226,7 +226,7 @@ Pathfinder::Pathfinder( , srcPathAsset_(uSrcPathAsset) , srcIssuer_(uSrcIssuer) , srcAmount_(amountFromPathAsset(uSrcPathAsset, uSrcIssuer, uSrcAccount)) - , convert_all_(convertAllCheck(dstAmount_)) + , convertAll_(convertAllCheck(dstAmount_)) , domain_(domain) , ledger_(cache->getLedger()) , rLCache_(cache) @@ -398,7 +398,7 @@ Pathfinder::getPathLiquidity( try { // Compute a path that provides at least the minimum liquidity. - if (convert_all_) + if (convertAll_) rcInput.partialPaymentAllowed = true; auto rc = path::RippleCalc::rippleCalculate( @@ -418,7 +418,7 @@ Pathfinder::getPathLiquidity( qualityOut = getRate(rc.actualAmountOut, rc.actualAmountIn); amountOut = rc.actualAmountOut; - if (!convert_all_) + if (!convertAll_) { // Now try to compute the remaining liquidity. rcInput.partialPaymentAllowed = true; @@ -451,7 +451,7 @@ Pathfinder::getPathLiquidity( void Pathfinder::computePathRanks(int maxPaths, std::function const& continueCallback) { - remainingAmount_ = convertAmount(dstAmount_, convert_all_); + remainingAmount_ = convertAmount(dstAmount_, convertAll_); // Must subtract liquidity in default path from remaining amount. try @@ -536,7 +536,7 @@ Pathfinder::rankPaths( rankedPaths.reserve(paths.size()); auto const saMinDstAmount = [&]() -> STAmount { - if (!convert_all_) + if (!convertAll_) { // Ignore paths that move only very small amounts. return smallestUsefulAmount(dstAmount_, maxPaths); @@ -581,7 +581,7 @@ Pathfinder::rankPaths( std::ranges::sort( rankedPaths, [&](Pathfinder::PathRank const& a, Pathfinder::PathRank const& b) { // 1) Higher quality (lower cost) is better - if (!convert_all_ && a.quality != b.quality) + if (!convertAll_ && a.quality != b.quality) return a.quality < b.quality; // 2) More liquidity (higher volume) is better diff --git a/src/xrpld/rpc/detail/Pathfinder.h b/src/xrpld/rpc/detail/Pathfinder.h index de2c2d83e6..36caab308e 100644 --- a/src/xrpld/rpc/detail/Pathfinder.h +++ b/src/xrpld/rpc/detail/Pathfinder.h @@ -178,7 +178,7 @@ private: /** The amount remaining from srcAccount_ after the default liquidity has been removed. */ STAmount remainingAmount_; - bool convert_all_; + bool convertAll_; std::optional domain_; std::shared_ptr ledger_; diff --git a/src/xrpld/rpc/detail/RPCCall.cpp b/src/xrpld/rpc/detail/RPCCall.cpp index 24fcc652df..f405ffe4de 100644 --- a/src/xrpld/rpc/detail/RPCCall.cpp +++ b/src/xrpld/rpc/detail/RPCCall.cpp @@ -1702,19 +1702,19 @@ rpcClient( // line client works without a config file } - if (config.rpc_ip) + if (config.rpcIp) { - setup.client.ip = config.rpc_ip->address().to_string(); - setup.client.port = config.rpc_ip->port(); + setup.client.ip = config.rpcIp->address().to_string(); + setup.client.port = config.rpcIp->port(); } json::Value jvParams(json::ValueType::Array); - if (!setup.client.admin_user.empty()) - jvRequest["admin_user"] = setup.client.admin_user; + if (!setup.client.adminUser.empty()) + jvRequest["admin_user"] = setup.client.adminUser; - if (!setup.client.admin_password.empty()) - jvRequest["admin_password"] = setup.client.admin_password; + if (!setup.client.adminPassword.empty()) + jvRequest["admin_password"] = setup.client.adminPassword; if (jvRequest.isObject()) { diff --git a/src/xrpld/rpc/detail/RPCHandler.cpp b/src/xrpld/rpc/detail/RPCHandler.cpp index 6b032317d3..7e30b81fa6 100644 --- a/src/xrpld/rpc/detail/RPCHandler.cpp +++ b/src/xrpld/rpc/detail/RPCHandler.cpp @@ -135,7 +135,7 @@ fillHandler(JsonContext& context, Handler const*& result) JLOG(context.j.trace()) << "COMMAND:" << strCommand; JLOG(context.j.trace()) << "REQUEST:" << context.params; - auto handler = getHandler(context.apiVersion, context.app.config().BETA_RPC_API, strCommand); + auto handler = getHandler(context.apiVersion, context.app.config().betaRpcApi, strCommand); if (handler == nullptr) return RpcUnknownCommand; diff --git a/src/xrpld/rpc/detail/RPCSub.cpp b/src/xrpld/rpc/detail/RPCSub.cpp index 56291ab34b..92e9849939 100644 --- a/src/xrpld/rpc/detail/RPCSub.cpp +++ b/src/xrpld/rpc/detail/RPCSub.cpp @@ -39,7 +39,7 @@ public: std::string strPassword, ServiceRegistry& registry) : RPCSub(source) - , io_context_(ioContext) + , ioContext_(ioContext) , jobQueue_(jobQueue) , url_(strUrl) , username_(std::move(strUsername)) @@ -159,7 +159,7 @@ private: JLOG(j_.info()) << "RPCCall::fromNetwork: " << ip_; RPCCall::fromNetwork( - io_context_, + ioContext_, ip_, port_, username_, @@ -180,7 +180,7 @@ private: } private: - boost::asio::io_context& io_context_; + boost::asio::io_context& ioContext_; JobQueue& jobQueue_; std::string url_; diff --git a/src/xrpld/rpc/detail/Role.cpp b/src/xrpld/rpc/detail/Role.cpp index dcc6965d58..68c5fcc484 100644 --- a/src/xrpld/rpc/detail/Role.cpp +++ b/src/xrpld/rpc/detail/Role.cpp @@ -28,14 +28,14 @@ bool passwordUnrequiredOrSentCorrect(Port const& port, json::Value const& params) { XRPL_ASSERT( - !(port.admin_nets_v4.empty() && port.admin_nets_v6.empty()), + !(port.adminNetsV4.empty() && port.adminNetsV6.empty()), "xrpl::passwordUnrequiredOrSentCorrect : non-empty admin nets"); - bool const passwordRequired = (!port.admin_user.empty() || !port.admin_password.empty()); + bool const passwordRequired = (!port.adminUser.empty() || !port.adminPassword.empty()); return !passwordRequired || ((params["admin_password"].isString() && - params["admin_password"].asString() == port.admin_password) && - (params["admin_user"].isString() && params["admin_user"].asString() == port.admin_user)); + params["admin_password"].asString() == port.adminPassword) && + (params["admin_user"].isString() && params["admin_user"].asString() == port.adminUser)); } bool @@ -80,7 +80,7 @@ ipAllowed( bool isAdmin(Port const& port, json::Value const& params, beast::IP::Address const& remoteIp) { - return ipAllowed(remoteIp, port.admin_nets_v4, port.admin_nets_v6) && + return ipAllowed(remoteIp, port.adminNetsV4, port.adminNetsV6) && passwordUnrequiredOrSentCorrect(port, params); } @@ -98,7 +98,7 @@ requestRole( if (required == Role::ADMIN) return Role::FORBID; - if (ipAllowed(remoteIp.address(), port.secure_gateway_nets_v4, port.secure_gateway_nets_v6)) + if (ipAllowed(remoteIp.address(), port.secureGatewayNetsV4, port.secureGatewayNetsV6)) { if (!user.empty()) return Role::IDENTIFIED; diff --git a/src/xrpld/rpc/detail/ServerHandler.cpp b/src/xrpld/rpc/detail/ServerHandler.cpp index 2ed6630af2..0bdece3ec3 100644 --- a/src/xrpld/rpc/detail/ServerHandler.cpp +++ b/src/xrpld/rpc/detail/ServerHandler.cpp @@ -139,9 +139,9 @@ ServerHandler::ServerHandler( , jobQueue_(jobQueue) { auto const& group(cm.group("rpc")); - rpc_requests_ = group->makeCounter("requests"); - rpc_size_ = group->makeEvent("size"); - rpc_time_ = group->makeEvent("time"); + rpcRequests_ = group->makeCounter("requests"); + rpcSize_ = group->makeEvent("size"); + rpcTime_ = group->makeEvent("time"); } ServerHandler::~ServerHandler() @@ -429,7 +429,7 @@ ServerHandler::processSession( Resource::Charge loadType = Resource::kFeeReferenceRpc; try { - auto apiVersion = RPC::getAPIVersionNumber(jv, app_.config().BETA_RPC_API); + auto apiVersion = RPC::getAPIVersionNumber(jv, app_.config().betaRpcApi); if (apiVersion == RPC::kApiInvalidVersion || (!jv.isMember(jss::command) && !jv.isMember(jss::method)) || (jv.isMember(jss::command) && !jv[jss::command].isString()) || @@ -457,7 +457,7 @@ ServerHandler::processSession( auto required = RPC::roleRequired( apiVersion, - app_.config().BETA_RPC_API, + app_.config().betaRpcApi, jv.isMember(jss::command) ? jv[jss::command].asString() : jv[jss::method].asString()); auto role = requestRole( required, @@ -657,13 +657,13 @@ ServerHandler::processRequest( jsonRPC[jss::params].size() > 0 && jsonRPC[jss::params][0u].isObject()) { apiVersion = RPC::getAPIVersionNumber( - jsonRPC[jss::params][json::UInt(0)], app_.config().BETA_RPC_API); + jsonRPC[jss::params][json::UInt(0)], app_.config().betaRpcApi); } if (apiVersion == RPC::kApiVersionIfUnspecified && batch) { // for batch request, api_version may be at a different level - apiVersion = RPC::getAPIVersionNumber(jsonRPC, app_.config().BETA_RPC_API); + apiVersion = RPC::getAPIVersionNumber(jsonRPC, app_.config().betaRpcApi); } if (apiVersion == RPC::kApiInvalidVersion) @@ -686,7 +686,7 @@ ServerHandler::processRequest( if (jsonRPC.isMember(jss::method) && jsonRPC[jss::method].isString()) { required = RPC::roleRequired( - apiVersion, app_.config().BETA_RPC_API, jsonRPC[jss::method].asString()); + apiVersion, app_.config().betaRpcApi, jsonRPC[jss::method].asString()); } if (jsonRPC.isMember(jss::params) && jsonRPC[jss::params].isArray() && @@ -993,11 +993,11 @@ ServerHandler::processRequest( auto response = to_string(reply); - rpc_time_.notify( + rpcTime_.notify( std::chrono::duration_cast( std::chrono::high_resolution_clock::now() - start)); - ++rpc_requests_; - rpc_size_.notify(beast::insight::Event::value_type{response.size()}); + ++rpcRequests_; + rpcSize_.notify(beast::insight::Event::value_type{response.size()}); response += '\n'; @@ -1060,13 +1060,13 @@ ServerHandler::Setup::makeContexts() { if (p.secure()) { - if (p.ssl_key.empty() && p.ssl_cert.empty() && p.ssl_chain.empty()) + if (p.sslKey.empty() && p.sslCert.empty() && p.sslChain.empty()) { - p.context = makeSslContext(p.ssl_ciphers); + p.context = makeSslContext(p.sslCiphers); } else { - p.context = makeSslContextAuthed(p.ssl_key, p.ssl_cert, p.ssl_chain, p.ssl_ciphers); + p.context = makeSslContextAuthed(p.sslKey, p.sslCert, p.sslChain, p.sslCiphers); } } else @@ -1106,19 +1106,19 @@ toPort(ParsedPort const& parsed, std::ostream& log) p.user = parsed.user; p.password = parsed.password; - p.admin_user = parsed.admin_user; - p.admin_password = parsed.admin_password; - p.ssl_key = parsed.ssl_key; - p.ssl_cert = parsed.ssl_cert; - p.ssl_chain = parsed.ssl_chain; - p.ssl_ciphers = parsed.ssl_ciphers; - p.pmd_options = parsed.pmd_options; - p.ws_queue_limit = parsed.ws_queue_limit; + p.adminUser = parsed.adminUser; + p.adminPassword = parsed.adminPassword; + p.sslKey = parsed.sslKey; + p.sslCert = parsed.sslCert; + p.sslChain = parsed.sslChain; + p.sslCiphers = parsed.sslCiphers; + p.pmdOptions = parsed.pmdOptions; + p.wsQueueLimit = parsed.wsQueueLimit; p.limit = parsed.limit; - p.admin_nets_v4 = parsed.admin_nets_v4; - p.admin_nets_v6 = parsed.admin_nets_v6; - p.secure_gateway_nets_v4 = parsed.secure_gateway_nets_v4; - p.secure_gateway_nets_v6 = parsed.secure_gateway_nets_v6; + p.adminNetsV4 = parsed.adminNetsV4; + p.adminNetsV6 = parsed.adminNetsV6; + p.secureGatewayNetsV4 = parsed.secureGatewayNetsV4; + p.secureGatewayNetsV6 = parsed.secureGatewayNetsV6; return p; } @@ -1221,8 +1221,8 @@ setupClient(ServerHandler::Setup& setup) setup.client.port = iter->port; setup.client.user = iter->user; setup.client.password = iter->password; - setup.client.admin_user = iter->admin_user; - setup.client.admin_password = iter->admin_password; + setup.client.adminUser = iter->adminUser; + setup.client.adminPassword = iter->adminPassword; } // Fill out the overlay portion of the Setup diff --git a/src/xrpld/rpc/detail/TransactionSign.cpp b/src/xrpld/rpc/detail/TransactionSign.cpp index 9faa82dfe8..dd0e78c178 100644 --- a/src/xrpld/rpc/detail/TransactionSign.cpp +++ b/src/xrpld/rpc/detail/TransactionSign.cpp @@ -312,7 +312,7 @@ checkPayment( std::nullopt, domain, app); - if (pf.findPaths(app.config().PATH_SEARCH_OLD)) + if (pf.findPaths(app.config().pathSearchOld)) { // 4 is the maximum paths pf.computePathRanks(4); @@ -508,7 +508,7 @@ transactionPreProcessImpl( validatedLedgerAge, app.config(), app.getFeeTrack(), - getAPIVersionNumber(params, app.config().BETA_RPC_API)); + getAPIVersionNumber(params, app.config().betaRpcApi)); if (RPC::containsError(txJsonResult)) return std::move(txJsonResult); @@ -846,16 +846,16 @@ getTxFee(Application const& app, Config const& config, json::Value tx) if (tx.isMember(jss::Signers)) { if (!tx[jss::Signers].isArray()) - return config.FEES.reference_fee; + return config.fees.referenceFee; if (tx[jss::Signers].size() > STTx::kMaxMultiSigners) - return config.FEES.reference_fee; + return config.fees.referenceFee; // check multi-signed signers for (auto& signer : tx[jss::Signers]) { if (!signer.isMember(jss::Signer) || !signer[jss::Signer].isObject()) - return config.FEES.reference_fee; + return config.fees.referenceFee; if (!signer[jss::Signer].isMember(jss::SigningPubKey)) { // autofill SigningPubKey @@ -872,7 +872,7 @@ getTxFee(Application const& app, Config const& config, json::Value tx) STParsedJSONObject parsed(std::string(jss::tx_json), tx); if (!parsed.object.has_value()) { - return config.FEES.reference_fee; + return config.fees.referenceFee; } try @@ -880,13 +880,13 @@ getTxFee(Application const& app, Config const& config, json::Value tx) STTx const& stTx = STTx(std::move(parsed.object.value())); std::string reason; if (!passesLocalChecks(stTx, reason)) - return config.FEES.reference_fee; + return config.fees.referenceFee; return calculateBaseFee(*app.getOpenLedger().current(), stTx); } catch (std::exception& e) { - return config.FEES.reference_fee; + return config.fees.referenceFee; } } @@ -1305,7 +1305,7 @@ transactionSubmitMultiSigned( validatedLedgerAge, app.config(), app.getFeeTrack(), - getAPIVersionNumber(jvRequest, app.config().BETA_RPC_API)); + getAPIVersionNumber(jvRequest, app.config().betaRpcApi)); if (RPC::containsError(txJsonResult)) return std::move(txJsonResult); diff --git a/src/xrpld/rpc/detail/WSInfoSub.h b/src/xrpld/rpc/detail/WSInfoSub.h index 336f35957f..c224b93e0e 100644 --- a/src/xrpld/rpc/detail/WSInfoSub.h +++ b/src/xrpld/rpc/detail/WSInfoSub.h @@ -24,8 +24,8 @@ public: auto const& h = ws->request(); if (ipAllowed( beast::IPAddressConversion::fromAsio(ws->remoteEndpoint()).address(), - ws->port().secure_gateway_nets_v4, - ws->port().secure_gateway_nets_v6)) + ws->port().secureGatewayNetsV4, + ws->port().secureGatewayNetsV6)) { auto it = h.find("X-User"); if (it != h.end()) diff --git a/src/xrpld/rpc/handlers/orderbook/PathFind.cpp b/src/xrpld/rpc/handlers/orderbook/PathFind.cpp index 7955a93eb4..3a6b52ee98 100644 --- a/src/xrpld/rpc/handlers/orderbook/PathFind.cpp +++ b/src/xrpld/rpc/handlers/orderbook/PathFind.cpp @@ -15,7 +15,7 @@ namespace xrpl { json::Value doPathFind(RPC::JsonContext& context) { - if (context.app.config().PATH_SEARCH_MAX == 0) + if (context.app.config().pathSearchMax == 0) return rpcError(RpcNotSupported); auto lpLedger = context.ledgerMaster.getClosedLedger(); diff --git a/src/xrpld/rpc/handlers/orderbook/RipplePathFind.cpp b/src/xrpld/rpc/handlers/orderbook/RipplePathFind.cpp index 956d50add7..b7edfb6dbe 100644 --- a/src/xrpld/rpc/handlers/orderbook/RipplePathFind.cpp +++ b/src/xrpld/rpc/handlers/orderbook/RipplePathFind.cpp @@ -23,7 +23,7 @@ namespace xrpl { json::Value doRipplePathFind(RPC::JsonContext& context) { - if (context.app.config().PATH_SEARCH_MAX == 0) + if (context.app.config().pathSearchMax == 0) return rpcError(RpcNotSupported); context.loadType = Resource::kFeeHeavyBurdenRpc; diff --git a/src/xrpld/rpc/handlers/server_info/Version.h b/src/xrpld/rpc/handlers/server_info/Version.h index 64c150162e..1868df5d40 100644 --- a/src/xrpld/rpc/handlers/server_info/Version.h +++ b/src/xrpld/rpc/handlers/server_info/Version.h @@ -8,7 +8,7 @@ class VersionHandler { public: explicit VersionHandler(JsonContext& c) - : apiVersion_(c.apiVersion), betaEnabled_(c.app.config().BETA_RPC_API) + : apiVersion_(c.apiVersion), betaEnabled_(c.app.config().betaRpcApi) { } diff --git a/src/xrpld/rpc/json_body.h b/src/xrpld/rpc/json_body.h index 9f881cacbc..4520a8bf39 100644 --- a/src/xrpld/rpc/json_body.h +++ b/src/xrpld/rpc/json_body.h @@ -56,7 +56,7 @@ struct JsonBody class writer // NOLINT(readability-identifier-naming) -- Boost.Beast body concept name { - std::string body_string_; + std::string bodyString_; public: using const_buffers_type = boost::asio::const_buffer; @@ -65,7 +65,7 @@ struct JsonBody explicit writer( boost::beast::http::header const& fields, value_type const& value) - : body_string_(to_string(value)) + : bodyString_(to_string(value)) { } @@ -81,7 +81,7 @@ struct JsonBody get(boost::beast::error_code& ec) { ec.assign(0, ec.category()); - return {{const_buffers_type{body_string_.data(), body_string_.size()}, false}}; + return {{const_buffers_type{bodyString_.data(), bodyString_.size()}, false}}; } }; }; From 28cc20c81679fd8bb9aa3ac85e450d1daf387816 Mon Sep 17 00:00:00 2001 From: Shawn Xie <35279399+shawnxie999@users.noreply.github.com> Date: Thu, 21 May 2026 02:19:04 -0400 Subject: [PATCH 16/17] fix: Fix wrong hybrid offer orderbook placement and update `LedgerStateFix` to amend `ExchangeRate` meta (#7087) Co-authored-by: Peter Chen --- .../xrpl/protocol/detail/transactions.macro | 1 + .../transactions/LedgerStateFix.h | 37 +++ .../xrpl/tx/invariants/DirectoryInvariant.h | 27 ++ include/xrpl/tx/invariants/InvariantCheck.h | 2 + include/xrpl/tx/transactors/dex/OfferCreate.h | 1 + .../tx/transactors/system/LedgerStateFix.h | 1 + .../tx/invariants/DirectoryInvariant.cpp | 96 +++++++ .../tx/transactors/dex/OfferCreate.cpp | 13 +- .../tx/transactors/system/LedgerStateFix.cpp | 86 +++++- src/test/app/FixNFTokenPageLinks_test.cpp | 7 + src/test/app/Invariants_test.cpp | 103 +++++++ src/test/app/PermissionedDEX_test.cpp | 262 ++++++++++++++++++ src/test/jtx/impl/ledgerStateFixes.cpp | 13 + src/test/jtx/ledgerStateFix.h | 4 + .../transactions/LedgerStateFixTests.cpp | 21 ++ 15 files changed, 669 insertions(+), 5 deletions(-) create mode 100644 include/xrpl/tx/invariants/DirectoryInvariant.h create mode 100644 src/libxrpl/tx/invariants/DirectoryInvariant.cpp diff --git a/include/xrpl/protocol/detail/transactions.macro b/include/xrpl/protocol/detail/transactions.macro index 9bac9ef7db..450e2558cc 100644 --- a/include/xrpl/protocol/detail/transactions.macro +++ b/include/xrpl/protocol/detail/transactions.macro @@ -688,6 +688,7 @@ TRANSACTION(ttLEDGER_STATE_FIX, 53, LedgerStateFix, ({ {sfLedgerFixType, SoeRequired}, {sfOwner, SoeOptional}, + {sfBookDirectory, SoeOptional}, })) /** This transaction type creates a MPTokensIssuance instance */ diff --git a/include/xrpl/protocol_autogen/transactions/LedgerStateFix.h b/include/xrpl/protocol_autogen/transactions/LedgerStateFix.h index 3c58815a02..52723ad5eb 100644 --- a/include/xrpl/protocol_autogen/transactions/LedgerStateFix.h +++ b/include/xrpl/protocol_autogen/transactions/LedgerStateFix.h @@ -83,6 +83,32 @@ public: { return this->tx_->isFieldPresent(sfOwner); } + + /** + * @brief Get sfBookDirectory (SoeOptional) + * @return The field value, or std::nullopt if not present. + */ + [[nodiscard]] + protocol_autogen::Optional + getBookDirectory() const + { + if (hasBookDirectory()) + { + return this->tx_->at(sfBookDirectory); + } + return std::nullopt; + } + + /** + * @brief Check if sfBookDirectory is present. + * @return True if the field is present, false otherwise. + */ + [[nodiscard]] + bool + hasBookDirectory() const + { + return this->tx_->isFieldPresent(sfBookDirectory); + } }; /** @@ -149,6 +175,17 @@ public: return *this; } + /** + * @brief Set sfBookDirectory (SoeOptional) + * @return Reference to this builder for method chaining. + */ + LedgerStateFixBuilder& + setBookDirectory(std::decay_t const& value) + { + object_[sfBookDirectory] = value; + return *this; + } + /** * @brief Build and return the LedgerStateFix wrapper. * @param publicKey The public key for signing. diff --git a/include/xrpl/tx/invariants/DirectoryInvariant.h b/include/xrpl/tx/invariants/DirectoryInvariant.h new file mode 100644 index 0000000000..96643ea465 --- /dev/null +++ b/include/xrpl/tx/invariants/DirectoryInvariant.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +namespace xrpl { + +class ValidBookDirectory +{ + bool badBookDirectory_ = false; + hash_set rootIndexes_; + +public: + void + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); + + bool + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); +}; + +} // namespace xrpl diff --git a/include/xrpl/tx/invariants/InvariantCheck.h b/include/xrpl/tx/invariants/InvariantCheck.h index bc9608fd56..a58ac0df50 100644 --- a/include/xrpl/tx/invariants/InvariantCheck.h +++ b/include/xrpl/tx/invariants/InvariantCheck.h @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -393,6 +394,7 @@ using InvariantChecks = std::tuple< ValidMPTIssuance, ValidPermissionedDomain, ValidPermissionedDEX, + ValidBookDirectory, ValidAMM, NoModifiedUnmodifiableFields, ValidPseudoAccounts, diff --git a/include/xrpl/tx/transactors/dex/OfferCreate.h b/include/xrpl/tx/transactors/dex/OfferCreate.h index d1ac8b5626..efae5312e2 100644 --- a/include/xrpl/tx/transactors/dex/OfferCreate.h +++ b/include/xrpl/tx/transactors/dex/OfferCreate.h @@ -85,6 +85,7 @@ private: Keylet const& offerIndex, STAmount const& saTakerPays, STAmount const& saTakerGets, + std::uint64_t openRate, std::function)> const& setDir); }; diff --git a/include/xrpl/tx/transactors/system/LedgerStateFix.h b/include/xrpl/tx/transactors/system/LedgerStateFix.h index 8d704467eb..6fbae6fc6a 100644 --- a/include/xrpl/tx/transactors/system/LedgerStateFix.h +++ b/include/xrpl/tx/transactors/system/LedgerStateFix.h @@ -9,6 +9,7 @@ class LedgerStateFix : public Transactor public: enum class FixType : std::uint16_t { NfTokenPageLink = 1, + BookExchangeRate = 2, }; static constexpr auto kConsequencesFactory = ConsequencesFactoryType::Normal; diff --git a/src/libxrpl/tx/invariants/DirectoryInvariant.cpp b/src/libxrpl/tx/invariants/DirectoryInvariant.cpp new file mode 100644 index 0000000000..2a4fac07d0 --- /dev/null +++ b/src/libxrpl/tx/invariants/DirectoryInvariant.cpp @@ -0,0 +1,96 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace xrpl { + +namespace { + +[[nodiscard]] bool +isRootBookDirectory(SLE const& dir) +{ + // Child page keys do not encode book quality. + return dir.isFieldPresent(sfExchangeRate) || dir.isFieldPresent(sfTakerPaysCurrency) || + dir.isFieldPresent(sfTakerPaysIssuer) || dir.isFieldPresent(sfTakerPaysMPT) || + dir.isFieldPresent(sfTakerGetsCurrency) || dir.isFieldPresent(sfTakerGetsIssuer) || + dir.isFieldPresent(sfTakerGetsMPT) || dir.isFieldPresent(sfDomainID); +} + +[[nodiscard]] bool +badExchangeRate(SLE const& dir) +{ + return isRootBookDirectory(dir) && + (!dir.isFieldPresent(sfExchangeRate) || + dir.getFieldU64(sfExchangeRate) != getQuality(dir.key())); +} + +} // namespace + +void +ValidBookDirectory::visitEntry( + bool, + std::shared_ptr const& before, + std::shared_ptr const& after) +{ + // New root directories must have matching exchange-rate metadata. New + // child directories must point to an existing root. + + // Only validate newly-created directories; LedgerStateFix handles legacy + // bad exchange-rate metadata. + if (badBookDirectory_ || before || !after || after->getType() != ltDIR_NODE) + return; + + auto const rootIndex = after->getFieldH256(sfRootIndex); + if (after->key() == rootIndex && !badBookDirectory_) + { + badBookDirectory_ = badBookDirectory_ || badExchangeRate(*after); + return; + } + + rootIndexes_.insert(rootIndex); +} + +bool +ValidBookDirectory::finalize( + STTx const&, + TER const, + XRPAmount const, + ReadView const& view, + beast::Journal const& j) +{ + if (!view.rules().enabled(fixCleanup3_2_0)) + return true; + + if (badBookDirectory_) + { + JLOG(j.fatal()) << "Invariant failed: book directory exchange rate " + "does not match directory quality"; + return false; + } + + for (auto const& rootIndex : rootIndexes_) + { + auto const root = view.read(Keylet(ltDIR_NODE, rootIndex)); + if (!root) + { + JLOG(j.fatal()) << "Invariant failed: book directory root missing"; + return false; + } + } + + return true; +} + +} // namespace xrpl diff --git a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp index 69c101644c..ed9eb1255d 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp @@ -547,6 +547,7 @@ OfferCreate::applyHybrid( Keylet const& offerKey, STAmount const& saTakerPays, STAmount const& saTakerGets, + std::uint64_t openRate, std::function)> const& setDir) { if (!sleOffer->isFieldPresent(sfDomainID)) @@ -558,7 +559,7 @@ OfferCreate::applyHybrid( // if offer is hybrid, need to also place into open offer dir Book const book{saTakerPays.asset(), saTakerGets.asset(), std::nullopt}; - auto dir = keylet::quality(keylet::kBook(book), getRate(saTakerGets, saTakerPays)); + auto dir = keylet::quality(keylet::kBook(book), openRate); bool const bookExists = sb.exists(dir); auto const bookNode = sb.dirAppend(dir, offerKey, [&](SLE::ref sle) { @@ -924,8 +925,16 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) // if it's a hybrid offer, set hybrid flag, and create an open dir if (bHybrid) { + // Pre-fixCleanup3_2_0: the open-book directory quality was computed + // from post-crossing amounts, which may differ from the original rate + // due to rounding in rate preservation. Post-fixCleanup3_2_0: use the + // original placement rate so the open-book directory quality matches + // the domain-book directory. + auto const openRate = ctx_.view().rules().enabled(fixCleanup3_2_0) + ? uRate + : getRate(saTakerGets, saTakerPays); auto const res = - applyHybrid(sb, sleOffer, offerIndex, saTakerPays, saTakerGets, setBookDir); + applyHybrid(sb, sleOffer, offerIndex, saTakerPays, saTakerGets, openRate, setBookDir); if (!isTesSuccess(res)) return {res, true}; // LCOV_EXCL_LINE } diff --git a/src/libxrpl/tx/transactors/system/LedgerStateFix.cpp b/src/libxrpl/tx/transactors/system/LedgerStateFix.cpp index 2f30311e6f..222e5dce7a 100644 --- a/src/libxrpl/tx/transactors/system/LedgerStateFix.cpp +++ b/src/libxrpl/tx/transactors/system/LedgerStateFix.cpp @@ -4,7 +4,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -12,24 +14,72 @@ #include #include +#include +#include #include +#include namespace xrpl { +namespace { + +using FixType = LedgerStateFix::FixType; + +std::array, 2> const kLedgerFixFields = {{ + {FixType::NfTokenPageLink, &sfOwner}, + {FixType::BookExchangeRate, &sfBookDirectory}, +}}; + +[[nodiscard]] SField const* +fixField(FixType const fixType) +{ + auto const iter = std::ranges::find_if( + kLedgerFixFields, [fixType](auto const& entry) { return entry.first == fixType; }); + + if (iter == kLedgerFixFields.end()) + return nullptr; // LCOV_EXCL_LINE + + return iter->second; +} + +[[nodiscard]] bool +hasUnexpectedFixField(STTx const& tx, SField const& expected) +{ + return std::ranges::any_of(kLedgerFixFields, [&tx, &expected](auto const& entry) { + auto const field = entry.second; + return field != &expected && tx.isFieldPresent(*field); + }); +} + +} // namespace + NotTEC LedgerStateFix::preflight(PreflightContext const& ctx) { - switch (static_cast(ctx.tx[sfLedgerFixType])) + auto const fixType = static_cast(ctx.tx[sfLedgerFixType]); + + switch (fixType) { case FixType::NfTokenPageLink: - if (!ctx.tx.isFieldPresent(sfOwner)) - return temINVALID; + break; + + case FixType::BookExchangeRate: + if (!ctx.rules.enabled(fixCleanup3_2_0)) + return temDISABLED; break; default: return tefINVALID_LEDGER_FIX_TYPE; } + auto const expectedField = fixField(fixType); + if (expectedField == nullptr) + return tefINVALID_LEDGER_FIX_TYPE; // LCOV_EXCL_LINE + + // Each fix type allows exactly one fix-specific field. + if (!ctx.tx.isFieldPresent(*expectedField) || hasUnexpectedFixField(ctx.tx, *expectedField)) + return temINVALID; + return tesSUCCESS; } @@ -53,6 +103,24 @@ LedgerStateFix::preclaim(PreclaimContext const& ctx) return tesSUCCESS; } + if (static_cast(ctx.tx[sfLedgerFixType]) == FixType::BookExchangeRate) + { + auto const dirKey = ctx.tx.getFieldH256(sfBookDirectory); + auto const sle = ctx.view.read(Keylet(ltDIR_NODE, dirKey)); + if (!sle) + return tecOBJECT_NOT_FOUND; + + // Must be the first page of a book directory (has sfExchangeRate). + if (!sle->isFieldPresent(sfExchangeRate)) + return tecNO_PERMISSION; + + // ExchangeRate is already correct, nothing to fix. + if (getQuality(sle->key()) == sle->getFieldU64(sfExchangeRate)) + return tecNO_PERMISSION; + + return tesSUCCESS; + } + // preflight is supposed to verify that only valid FixTypes get to preclaim. return tecINTERNAL; // LCOV_EXCL_LINE } @@ -68,6 +136,18 @@ LedgerStateFix::doApply() return tesSUCCESS; } + if (static_cast(ctx_.tx[sfLedgerFixType]) == FixType::BookExchangeRate) + { + auto const dirKey = ctx_.tx.getFieldH256(sfBookDirectory); + auto sle = view().peek(Keylet(ltDIR_NODE, dirKey)); + if (!sle) + return tecINTERNAL; // LCOV_EXCL_LINE + + sle->setFieldU64(sfExchangeRate, getQuality(sle->key())); + view().update(sle); + return tesSUCCESS; + } + // preflight is supposed to verify that only valid FixTypes get to doApply. return tecINTERNAL; // LCOV_EXCL_LINE } diff --git a/src/test/app/FixNFTokenPageLinks_test.cpp b/src/test/app/FixNFTokenPageLinks_test.cpp index f77d924c94..cfe2fd1808 100644 --- a/src/test/app/FixNFTokenPageLinks_test.cpp +++ b/src/test/app/FixNFTokenPageLinks_test.cpp @@ -173,6 +173,13 @@ class FixNFTokenPageLinks_test : public beast::unit_test::Suite tx.removeMember(sfOwner.jsonName); env(tx, Fee(linkFixFee), Ter(temINVALID)); } + { + // NFTokenPageLink fixes require sfOwner and reject fields that + // belong to other LedgerStateFix types. + json::Value tx = ledgerStateFix::nftPageLinks(alice, alice); + tx[sfBookDirectory.jsonName] = to_string(uint256{1}); + env(tx, Fee(linkFixFee), Ter(temINVALID)); + } { // Invalid LedgerFixType codes. json::Value tx = ledgerStateFix::nftPageLinks(alice, alice); diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index 21094e0142..5cb872f291 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -50,6 +51,7 @@ #include #include #include +#include #include #include @@ -2037,6 +2039,106 @@ class Invariants_test : public beast::unit_test::Suite } } + void + testBookDirectoryExchangeRate() + { + using namespace test::jtx; + testcase << "book directory exchange rate"; + + auto const getBookRootKey = [](Account const& account, std::uint64_t quality) { + Book const book{xrpIssue(), account["USD"], std::nullopt}; + return keylet::quality(keylet::kBook(book), quality); + }; + + // Root book-directory pages carry exchange-rate metadata that must + // match the quality encoded in the directory key. + auto const makeRootPage = [](Keylet const& dir, std::uint64_t exchangeRate) { + auto sleDir = std::make_shared(dir); + sleDir->setFieldH256(sfRootIndex, dir.key); + STVector256 indexes; + indexes.pushBack(uint256{1}); + sleDir->setFieldV256(sfIndexes, indexes); + sleDir->setFieldU64(sfExchangeRate, exchangeRate); + return sleDir; + }; + + // Child pages do not carry quality metadata; they only point back to + // the root directory. + auto const makeChildPage = [](Keylet const& rootDir) { + auto sleDir = std::make_shared(keylet::page(rootDir, 1)); + sleDir->setFieldH256(sfRootIndex, rootDir.key); + STVector256 indexes; + indexes.pushBack(uint256{2}); + sleDir->setFieldV256(sfIndexes, indexes); + return sleDir; + }; + + auto const makeOfferCreateTx = [] { + return STTx{ttOFFER_CREATE, [](STObject& tx) { + Account const account{"A1"}; + tx.setFieldAmount(sfTakerPays, XRP(1)); + tx.setFieldAmount(sfTakerGets, account["USD"](1)); + }}; + }; + std::initializer_list const failTers = {tecINVARIANT_FAILED, tefINVARIANT_FAILED}; + + // Creating a root book directory with mismatched exchange-rate + // metadata violates the invariant. + doInvariantCheck( + {{"book directory exchange rate does not match directory quality"}}, + [&](Account const& a1, Account const&, ApplyContext& ac) { + auto const directoryQuality = STAmount::kURateOne; + auto const dir = getBookRootKey(a1, directoryQuality); + ac.view().insert(makeRootPage(dir, directoryQuality + 1)); + return true; + }, + XRPAmount{}, + makeOfferCreateTx(), + failTers); + + // A new child page must point to an existing root page. + doInvariantCheck( + {{"book directory root missing"}}, + [&](Account const& a1, Account const&, ApplyContext& ac) { + auto const directoryQuality = STAmount::kURateOne; + auto const rootDir = getBookRootKey(a1, directoryQuality); + // Insert only the child page. It points at rootDir, but the + // corresponding root page is intentionally missing. + ac.view().insert(makeChildPage(rootDir)); + return true; + }, + XRPAmount{}, + makeOfferCreateTx(), + failTers); + + // Legacy bad-root tolerance: + // - The view contains a pre-existing root page with bad sfExchangeRate + // metadata. + // - The simulated transaction only creates a child page pointing to + // that root. + // - The invariant must pass because this transaction did not create + // the bad root, only adding a child page. + { + Env env{*this, defaultAmendments()}; + Account const a1{"A1"}; + env.fund(XRP(1000), a1); + env.close(); + + OpenView view{*env.current()}; + auto const directoryQuality = STAmount::kURateOne; + auto const rootDir = getBookRootKey(a1, directoryQuality); + view.rawInsert(makeRootPage(rootDir, directoryQuality + 1)); + + ValidBookDirectory invariant; + invariant.visitEntry(false, nullptr, makeChildPage(rootDir)); + + test::StreamSink sink{beast::Severity::Warning}; + beast::Journal const jlog{sink}; + BEAST_EXPECT( + invariant.finalize(makeOfferCreateTx(), tesSUCCESS, XRPAmount{}, view, jlog)); + } + } + Keylet createLoanBroker(jtx::Account const& a, jtx::Env& env, jtx::PrettyAsset const& asset) { @@ -4489,6 +4591,7 @@ public: testPermissionedDomainInvariants(defaultAmendments() - fixCleanup3_1_3); testPermissionedDEX(defaultAmendments() | fixCleanup3_1_3); testPermissionedDEX(defaultAmendments() - fixCleanup3_1_3); + testBookDirectoryExchangeRate(); testNoModifiedUnmodifiableFields(); testValidPseudoAccounts(); testValidLoanBroker(); diff --git a/src/test/app/PermissionedDEX_test.cpp b/src/test/app/PermissionedDEX_test.cpp index 3a95fb2f92..c6e94d7994 100644 --- a/src/test/app/PermissionedDEX_test.cpp +++ b/src/test/app/PermissionedDEX_test.cpp @@ -7,7 +7,9 @@ #include #include #include +#include #include +#include #include #include // IWYU pragma: keep #include @@ -1457,6 +1459,263 @@ class PermissionedDEX_test : public beast::unit_test::Suite } } + void + testHybridOfferCrossingQuality(FeatureBitset features) + { + bool const fixEnabled = features[fixCleanup3_2_0]; + testcase << "Hybrid offer crossing quality" + << (fixEnabled ? " (fixCleanup3_2_0)" : " (pre-fix)"); + + // Partially-crossed hybrid offer should have consistent quality + // across both book directories. + // + // Steps: + // - Bob places a hybrid offer. + // - Alice places an opposing hybrid offer that partially crosses. + // + // Verify: + // - Domain-book key quality == its sfExchangeRate. + // - Post-fix: open-book key quality == domain-book key quality. + // - Pre-fix: open-book key quality != domain-book key quality + // (key used post-crossing rate, sfExchangeRate used pre-crossing). + + Env env(*this, features); + auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + PermissionedDEX(env); + + // Bob places a hybrid offer: TakerPays = XRP(100), TakerGets = USD(40) + auto const bobOfferSeq{env.seq(bob_)}; + env(offer(bob_, XRP(100), USD(40)), Txflags(tfHybrid), Domain(domainID)); + env.close(); + BEAST_EXPECT(offerExists(env, bob_, bobOfferSeq)); + + // Alice places a hybrid offer in the opposite direction that + // partially crosses Bob's offer. + // Alice: TakerPays = USD(100), TakerGets = XRP(300) (rate = 3 XRP/USD) + // Bob's offer is at a better rate (2.5 XRP/USD) so crossing occurs. + auto const aliceOfferSeq{env.seq(alice_)}; + env(offer(alice_, USD(100), XRP(300)), Txflags(tfHybrid), Domain(domainID)); + env.close(); + + // After crossing, Alice's remaining offer should be placed. + auto const sle = env.le(keylet::offer(alice_.id(), aliceOfferSeq)); + BEAST_EXPECT(sle); + BEAST_EXPECT(sle->isFieldPresent(sfAdditionalBooks)); + BEAST_EXPECT(sle->getFieldArray(sfAdditionalBooks).size() == 1); + + auto const domainDirKey = sle->getFieldH256(sfBookDirectory); + auto const openDirKey = + sle->getFieldArray(sfAdditionalBooks)[0].getFieldH256(sfBookDirectory); + + auto const domainQuality = getQuality(domainDirKey); + auto const openQuality = getQuality(openDirKey); + + // Read the directory SLEs and check sfExchangeRate vs key quality. + auto const domainDirSle = env.le(Keylet(ltDIR_NODE, domainDirKey)); + auto const openDirSle = env.le(Keylet(ltDIR_NODE, openDirKey)); + BEAST_EXPECT(domainDirSle); + BEAST_EXPECT(openDirSle); + + auto const domainExRate = domainDirSle->getFieldU64(sfExchangeRate); + auto const openExRate = openDirSle->getFieldU64(sfExchangeRate); + auto const preCrossingQuality = std::uint64_t{5623825668291712342ULL}; + auto const postCrossingQuality = std::uint64_t{5623825668291712341ULL}; + + // Domain directory: sfExchangeRate should always match key quality + // (both use the pre-crossing rate). Correct behavior. + BEAST_EXPECT(domainQuality == preCrossingQuality); + BEAST_EXPECT(domainExRate == preCrossingQuality); + BEAST_EXPECT(domainExRate == domainQuality); + + if (fixEnabled) + { + // Correct behavior: both directory keys use the pre-crossing rate. + BEAST_EXPECT(openQuality == preCrossingQuality); + BEAST_EXPECT(domainQuality == openQuality); + + // sfExchangeRate matches key quality on both directories. + BEAST_EXPECT(openExRate == preCrossingQuality); + BEAST_EXPECT(openExRate == openQuality); + } + else + { + // Wrong legacy behavior: the open-book directory key uses the + // post-crossing rate instead of the domain-book rate. + BEAST_EXPECT(openQuality == postCrossingQuality); + BEAST_EXPECT(domainQuality != openQuality); + + // The open-book sfExchangeRate still uses the pre-crossing rate, + // so it no longer matches the actual quality encoded in the + // open-book directory key. + BEAST_EXPECT(openExRate == preCrossingQuality); + BEAST_EXPECT(openExRate != openQuality); + BEAST_EXPECT(openExRate == domainQuality); + } + } + + void + testBookExchangeRateFix(FeatureBitset features) + { + testcase("LedgerStateFix BookExchangeRate"); + + // Use the pre-fix path to create a hybrid offer with a mismatched + // sfExchangeRate, then apply LedgerStateFix to correct it. + // + // Steps: + // - Create a partially-crossed hybrid offer (pre-fixCleanup3_2_0) + // so the open-book directory has wrong sfExchangeRate. + // - Re-enable fixCleanup3_2_0 and submit a LedgerStateFix to + // repair the open-book directory's sfExchangeRate. + // + // Verify: + // - Before fix: sfExchangeRate != getQuality(key). + // - After fix: sfExchangeRate == getQuality(key). + + { + // Amendment gate: BookExchangeRate fixes require fixCleanup3_2_0. + Env env(*this, features - fixCleanup3_2_0); + Account const carol{"carol"}; + + env.fund(XRP(1000), carol); + env.close(); + + env(ledgerStateFix::bookExchangeRate(carol, uint256{1}), Ter(temDISABLED)); + } + + { + // Preflight check: BookExchangeRate fixes only accept their + // required fix-specific field. + Env env(*this, features); + Account const carol{"carol"}; + + env.fund(XRP(1000), carol); + env.close(); + + // BookExchangeRate fixes require sfBookDirectory. + auto missingBookDirectory = ledgerStateFix::bookExchangeRate(carol, uint256{1}); + missingBookDirectory.removeMember(sfBookDirectory.jsonName); + env(missingBookDirectory, Ter(temINVALID)); + + // BookExchangeRate fixes reject fields that belong to other + // LedgerStateFix types. + auto extraOwner = ledgerStateFix::bookExchangeRate(carol, uint256{1}); + extraOwner[sfOwner.jsonName] = carol.human(); + env(extraOwner, Ter(temINVALID)); + } + + { + Env env(*this, features); + auto const setup = PermissionedDEX(env); + auto const fixFee = drops(env.current()->fees().increment); + + { + // Preclaim check: the target directory must exist. + env(ledgerStateFix::bookExchangeRate(setup.carol, uint256{1}), + Fee(fixFee), + Ter(tecOBJECT_NOT_FOUND)); + } + + { + // Preclaim check: the target directory must be a book root + // page. Owner directories are ltDIR_NODE entries, but they do + // not carry sfExchangeRate. + auto const ownerDir = keylet::ownerDir(setup.bob.id()); + auto const ownerDirSle = env.le(ownerDir); + BEAST_EXPECT(ownerDirSle); + BEAST_EXPECT(!ownerDirSle->isFieldPresent(sfExchangeRate)); + + env(ledgerStateFix::bookExchangeRate(setup.carol, ownerDir.key), + Fee(fixFee), + Ter(tecNO_PERMISSION)); + } + + { + // Preclaim check: a correct sfExchangeRate leaves nothing to + // repair. + auto const bobOfferSeq{env.seq(setup.bob)}; + env(offer(setup.bob, XRP(100), setup.usd(40))); + env.close(); + + auto const sle = env.le(keylet::offer(setup.bob.id(), bobOfferSeq)); + BEAST_EXPECT(sle); + + auto const dirKey = sle->getFieldH256(sfBookDirectory); + { + auto const dirSle = env.le(Keylet(ltDIR_NODE, dirKey)); + BEAST_EXPECT(dirSle); + auto const exchangeRate = dirSle->getFieldU64(sfExchangeRate); + auto const quality = getQuality(dirKey); + BEAST_EXPECT(exchangeRate == quality); + } + + env(ledgerStateFix::bookExchangeRate(setup.carol, dirKey), + Fee(fixFee), + Ter(tecNO_PERMISSION)); + } + } + + { + // Repair path: start without fixCleanup3_2_0 to produce the + // mismatch, then enable the amendment and fix it. + Env env(*this, features - fixCleanup3_2_0); + auto const& [gw_, domainOwner, alice_, bob_, carol_, USD, domainID, credType] = + PermissionedDEX(env); + + // Bob places a hybrid offer. + env(offer(bob_, XRP(100), USD(40)), Txflags(tfHybrid), Domain(domainID)); + env.close(); + + // Alice partially crosses Bob. + auto const aliceOfferSeq{env.seq(alice_)}; + env(offer(alice_, USD(100), XRP(300)), Txflags(tfHybrid), Domain(domainID)); + env.close(); + + auto const sle = env.le(keylet::offer(alice_.id(), aliceOfferSeq)); + BEAST_EXPECT(sle); + + auto const openDirKey = + sle->getFieldArray(sfAdditionalBooks)[0].getFieldH256(sfBookDirectory); + + auto const preCrossingQuality = std::uint64_t{5623825668291712342ULL}; + auto const postCrossingQuality = std::uint64_t{5623825668291712341ULL}; + + // Confirm mismatch exists. + { + auto const dirSle = env.le(Keylet(ltDIR_NODE, openDirKey)); + BEAST_EXPECT(dirSle); + auto const exchangeRate = dirSle->getFieldU64(sfExchangeRate); + auto const quality = getQuality(openDirKey); + BEAST_EXPECT(exchangeRate == preCrossingQuality); + BEAST_EXPECT(quality == postCrossingQuality); + BEAST_EXPECT(exchangeRate != quality); + } + + // Enable fixCleanup3_2_0 and apply the LedgerStateFix. + env.enableFeature(fixCleanup3_2_0); + env.close(); + + auto const fixFee = drops(env.current()->fees().increment); + env(ledgerStateFix::bookExchangeRate(carol_, openDirKey), Fee(fixFee)); + env.close(); + + // Confirm sfExchangeRate now matches the key quality. + { + auto const dirSle = env.le(Keylet(ltDIR_NODE, openDirKey)); + BEAST_EXPECT(dirSle); + auto const exchangeRate = dirSle->getFieldU64(sfExchangeRate); + auto const quality = getQuality(openDirKey); + BEAST_EXPECT(exchangeRate == postCrossingQuality); + BEAST_EXPECT(quality == postCrossingQuality); + BEAST_EXPECT(exchangeRate == quality); + } + + // Submitting again should fail — nothing to fix. + env(ledgerStateFix::bookExchangeRate(carol_, openDirKey), + Fee(fixFee), + Ter(tecNO_PERMISSION)); + } + } + void testCancelRegularOfferWithDomainCreate(FeatureBitset features) { @@ -1528,6 +1787,9 @@ public: testHybridOfferDirectories(all); testHybridMalformedOffer(all); testHybridMalformedOffer(all - fixCleanup3_1_3); + testHybridOfferCrossingQuality(all); + testHybridOfferCrossingQuality(all - fixCleanup3_2_0); + testBookExchangeRateFix(all); // Cancelling a regular offer in a domain OfferCreate is allowed // only after fixCleanup3_2_0. diff --git a/src/test/jtx/impl/ledgerStateFixes.cpp b/src/test/jtx/impl/ledgerStateFixes.cpp index a4b6d9b986..30c6659124 100644 --- a/src/test/jtx/impl/ledgerStateFixes.cpp +++ b/src/test/jtx/impl/ledgerStateFixes.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -22,4 +23,16 @@ nftPageLinks(jtx::Account const& acct, jtx::Account const& owner) return jv; } +// Fix sfExchangeRate on a book directory. acct pays fee. +json::Value +bookExchangeRate(jtx::Account const& acct, uint256 const& bookDir) +{ + json::Value jv; + jv[sfAccount.jsonName] = acct.human(); + jv[sfLedgerFixType.jsonName] = static_cast(LedgerStateFix::FixType::BookExchangeRate); + jv[sfBookDirectory.jsonName] = to_string(bookDir); + jv[sfTransactionType.jsonName] = jss::LedgerStateFix; + return jv; +} + } // namespace xrpl::test::jtx::ledgerStateFix diff --git a/src/test/jtx/ledgerStateFix.h b/src/test/jtx/ledgerStateFix.h index 769a28fb08..71f3f76101 100644 --- a/src/test/jtx/ledgerStateFix.h +++ b/src/test/jtx/ledgerStateFix.h @@ -10,4 +10,8 @@ namespace xrpl::test::jtx::ledgerStateFix { json::Value nftPageLinks(jtx::Account const& acct, jtx::Account const& owner); +/** Repair sfExchangeRate on a book directory's first page. */ +json::Value +bookExchangeRate(jtx::Account const& acct, uint256 const& bookDir); + } // namespace xrpl::test::jtx::ledgerStateFix diff --git a/src/tests/libxrpl/protocol_autogen/transactions/LedgerStateFixTests.cpp b/src/tests/libxrpl/protocol_autogen/transactions/LedgerStateFixTests.cpp index 60034255c7..5b78f0cfdd 100644 --- a/src/tests/libxrpl/protocol_autogen/transactions/LedgerStateFixTests.cpp +++ b/src/tests/libxrpl/protocol_autogen/transactions/LedgerStateFixTests.cpp @@ -31,6 +31,7 @@ TEST(TransactionsLedgerStateFixTests, BuilderSettersRoundTrip) // Transaction-specific field values auto const ledgerFixTypeValue = canonical_UINT16(); auto const ownerValue = canonical_ACCOUNT(); + auto const bookDirectoryValue = canonical_UINT256(); LedgerStateFixBuilder builder{ accountValue, @@ -41,6 +42,7 @@ TEST(TransactionsLedgerStateFixTests, BuilderSettersRoundTrip) // Set optional fields builder.setOwner(ownerValue); + builder.setBookDirectory(bookDirectoryValue); auto tx = builder.build(publicKey, secretKey); @@ -72,6 +74,14 @@ TEST(TransactionsLedgerStateFixTests, BuilderSettersRoundTrip) EXPECT_TRUE(tx.hasOwner()); } + { + auto const& expected = bookDirectoryValue; + auto const actualOpt = tx.getBookDirectory(); + ASSERT_TRUE(actualOpt.has_value()) << "Optional field sfBookDirectory should be present"; + expectEqualField(expected, *actualOpt, "sfBookDirectory"); + EXPECT_TRUE(tx.hasBookDirectory()); + } + } // 2 & 4) Start from an STTx, construct a builder from it, build a new wrapper, @@ -90,6 +100,7 @@ TEST(TransactionsLedgerStateFixTests, BuilderFromStTxRoundTrip) // Transaction-specific field values auto const ledgerFixTypeValue = canonical_UINT16(); auto const ownerValue = canonical_ACCOUNT(); + auto const bookDirectoryValue = canonical_UINT256(); // Build an initial transaction LedgerStateFixBuilder initialBuilder{ @@ -100,6 +111,7 @@ TEST(TransactionsLedgerStateFixTests, BuilderFromStTxRoundTrip) }; initialBuilder.setOwner(ownerValue); + initialBuilder.setBookDirectory(bookDirectoryValue); auto initialTx = initialBuilder.build(publicKey, secretKey); @@ -131,6 +143,13 @@ TEST(TransactionsLedgerStateFixTests, BuilderFromStTxRoundTrip) expectEqualField(expected, *actualOpt, "sfOwner"); } + { + auto const& expected = bookDirectoryValue; + auto const actualOpt = rebuiltTx.getBookDirectory(); + ASSERT_TRUE(actualOpt.has_value()) << "Optional field sfBookDirectory should be present"; + expectEqualField(expected, *actualOpt, "sfBookDirectory"); + } + } // 3) Verify wrapper throws when constructed from wrong transaction type. @@ -190,6 +209,8 @@ TEST(TransactionsLedgerStateFixTests, OptionalFieldsReturnNullopt) // Verify optional fields are not present EXPECT_FALSE(tx.hasOwner()); EXPECT_FALSE(tx.getOwner().has_value()); + EXPECT_FALSE(tx.hasBookDirectory()); + EXPECT_FALSE(tx.getBookDirectory().has_value()); } } From afcf6fbcdcdaaccb3dfa66b7c0a0c3d570bed24a Mon Sep 17 00:00:00 2001 From: Rithvik Reddygari <67663680+ricky122-5@users.noreply.github.com> Date: Thu, 21 May 2026 02:33:19 -0400 Subject: [PATCH 17/17] docs: Add --parallel flag to cmake build commands in BUILD.md (#7302) --- BUILD.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/BUILD.md b/BUILD.md index 632832c002..a1163dbfcc 100644 --- a/BUILD.md +++ b/BUILD.md @@ -427,16 +427,19 @@ install ccache --version 4.11.3 --allow-downgrade`. Single-config generators: ``` - cmake --build . + cmake --build . --parallel N ``` Multi-config generators: ``` - cmake --build . --config Release - cmake --build . --config Debug + cmake --build . --config Release --parallel N + cmake --build . --config Debug --parallel N ``` + Replace the `--parallel` parameter N with the desired number of parallel jobs. A common starting point is half of the number of available CPU + cores. + 5. Test xrpld. Single-config generators: