diff --git a/.clang-format b/.clang-format index 46e7bbce94..ca8edf678f 100644 --- a/.clang-format +++ b/.clang-format @@ -37,7 +37,7 @@ BinPackParameters: false BreakBeforeBinaryOperators: false BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: true -ColumnLimit: 120 +ColumnLimit: 100 CommentPragmas: "^ IWYU pragma:" ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerIndentWidth: 4 diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000000..f7009c4666 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,191 @@ +--- +Checks: "-*, + bugprone-argument-comment + " +# bugprone-assert-side-effect, +# bugprone-bad-signal-to-kill-thread, +# bugprone-bool-pointer-implicit-conversion, +# bugprone-casting-through-void, +# bugprone-chained-comparison, +# bugprone-compare-pointer-to-member-virtual-function, +# bugprone-copy-constructor-init, +# bugprone-crtp-constructor-accessibility, +# bugprone-dangling-handle, +# bugprone-dynamic-static-initializers, +# bugprone-empty-catch, +# bugprone-fold-init-type, +# bugprone-forward-declaration-namespace, +# bugprone-inaccurate-erase, +# bugprone-inc-dec-in-conditions, +# bugprone-incorrect-enable-if, +# bugprone-incorrect-roundings, +# bugprone-infinite-loop, +# bugprone-integer-division, +# bugprone-lambda-function-name, +# bugprone-macro-parentheses, +# bugprone-macro-repeated-side-effects, +# bugprone-misplaced-operator-in-strlen-in-alloc, +# bugprone-misplaced-pointer-arithmetic-in-alloc, +# bugprone-misplaced-widening-cast, +# bugprone-move-forwarding-reference, +# bugprone-multi-level-implicit-pointer-conversion, +# bugprone-multiple-new-in-one-expression, +# bugprone-multiple-statement-macro, +# bugprone-no-escape, +# bugprone-non-zero-enum-to-bool-conversion, +# bugprone-optional-value-conversion, +# bugprone-parent-virtual-call, +# bugprone-pointer-arithmetic-on-polymorphic-object, +# bugprone-posix-return, +# bugprone-redundant-branch-condition, +# bugprone-reserved-identifier, +# bugprone-return-const-ref-from-parameter, +# bugprone-shared-ptr-array-mismatch, +# bugprone-signal-handler, +# bugprone-signed-char-misuse, +# bugprone-sizeof-container, +# bugprone-sizeof-expression, +# bugprone-spuriously-wake-up-functions, +# bugprone-standalone-empty, +# bugprone-string-constructor, +# bugprone-string-integer-assignment, +# bugprone-string-literal-with-embedded-nul, +# bugprone-stringview-nullptr, +# bugprone-suspicious-enum-usage, +# bugprone-suspicious-include, +# bugprone-suspicious-memory-comparison, +# bugprone-suspicious-memset-usage, +# bugprone-suspicious-missing-comma, +# bugprone-suspicious-realloc-usage, +# bugprone-suspicious-semicolon, +# bugprone-suspicious-string-compare, +# bugprone-suspicious-stringview-data-usage, +# bugprone-swapped-arguments, +# bugprone-switch-missing-default-case, +# bugprone-terminating-continue, +# bugprone-throw-keyword-missing, +# bugprone-too-small-loop-variable, +# bugprone-undefined-memory-manipulation, +# bugprone-undelegated-constructor, +# bugprone-unhandled-exception-at-new, +# bugprone-unhandled-self-assignment, +# bugprone-unique-ptr-array-mismatch, +# bugprone-unsafe-functions, +# bugprone-unused-local-non-trivial-variable, +# bugprone-unused-raii, +# bugprone-unused-return-value, +# bugprone-use-after-move, +# bugprone-virtual-near-miss, +# cppcoreguidelines-init-variables, +# cppcoreguidelines-misleading-capture-default-by-value, +# cppcoreguidelines-no-suspend-with-lock, +# cppcoreguidelines-pro-type-member-init, +# cppcoreguidelines-pro-type-static-cast-downcast, +# cppcoreguidelines-rvalue-reference-param-not-moved, +# cppcoreguidelines-use-default-member-init, +# cppcoreguidelines-virtual-class-destructor, +# hicpp-ignored-remove-result, +# llvm-namespace-comment, +# misc-const-correctness, +# misc-definitions-in-headers, +# misc-header-include-cycle, +# misc-include-cleaner, +# misc-misplaced-const, +# misc-redundant-expression, +# misc-static-assert, +# misc-throw-by-value-catch-by-reference, +# misc-unused-alias-decls, +# misc-unused-using-decls, +# modernize-concat-nested-namespaces, +# modernize-deprecated-headers, +# modernize-make-shared, +# modernize-make-unique, +# modernize-pass-by-value, +# modernize-type-traits, +# modernize-use-designated-initializers, +# modernize-use-emplace, +# modernize-use-equals-default, +# modernize-use-equals-delete, +# modernize-use-override, +# modernize-use-ranges, +# modernize-use-starts-ends-with, +# modernize-use-std-numbers, +# modernize-use-using, +# performance-faster-string-find, +# performance-for-range-copy, +# performance-implicit-conversion-in-loop, +# performance-inefficient-vector-operation, +# performance-move-const-arg, +# performance-move-constructor-init, +# performance-no-automatic-move, +# performance-trivially-destructible, +# readability-avoid-nested-conditional-operator, +# readability-avoid-return-with-void-value, +# readability-braces-around-statements, +# readability-const-return-type, +# readability-container-contains, +# readability-container-size-empty, +# readability-convert-member-functions-to-static, +# readability-duplicate-include, +# readability-else-after-return, +# readability-enum-initial-value, +# readability-implicit-bool-conversion, +# readability-inconsistent-declaration-parameter-name, +# readability-identifier-naming, +# readability-make-member-function-const, +# readability-math-missing-parentheses, +# readability-misleading-indentation, +# readability-non-const-parameter, +# readability-redundant-casting, +# readability-redundant-declaration, +# readability-redundant-inline-specifier, +# readability-redundant-member-init, +# readability-redundant-string-init, +# readability-reference-to-constructed-temporary, +# readability-simplify-boolean-expr, +# readability-static-accessed-through-instance, +# readability-static-definition-in-anonymous-namespace, +# readability-suspicious-call-argument, +# readability-use-std-min-max +# +# CheckOptions: +# readability-braces-around-statements.ShortStatementLines: 2 +# readability-identifier-naming.MacroDefinitionCase: UPPER_CASE +# readability-identifier-naming.ClassCase: CamelCase +# readability-identifier-naming.StructCase: CamelCase +# readability-identifier-naming.UnionCase: CamelCase +# readability-identifier-naming.EnumCase: CamelCase +# readability-identifier-naming.EnumConstantCase: CamelCase +# readability-identifier-naming.ScopedEnumConstantCase: CamelCase +# readability-identifier-naming.GlobalConstantCase: UPPER_CASE +# readability-identifier-naming.GlobalConstantPrefix: "k" +# readability-identifier-naming.GlobalVariableCase: CamelCase +# readability-identifier-naming.GlobalVariablePrefix: "g" +# readability-identifier-naming.ConstexprFunctionCase: camelBack +# readability-identifier-naming.ConstexprMethodCase: camelBack +# readability-identifier-naming.ClassMethodCase: camelBack +# readability-identifier-naming.ClassMemberCase: camelBack +# readability-identifier-naming.ClassConstantCase: UPPER_CASE +# readability-identifier-naming.ClassConstantPrefix: "k" +# readability-identifier-naming.StaticConstantCase: UPPER_CASE +# readability-identifier-naming.StaticConstantPrefix: "k" +# readability-identifier-naming.StaticVariableCase: UPPER_CASE +# readability-identifier-naming.StaticVariablePrefix: "k" +# readability-identifier-naming.ConstexprVariableCase: UPPER_CASE +# readability-identifier-naming.ConstexprVariablePrefix: "k" +# readability-identifier-naming.LocalConstantCase: camelBack +# readability-identifier-naming.LocalVariableCase: camelBack +# readability-identifier-naming.TemplateParameterCase: CamelCase +# readability-identifier-naming.ParameterCase: camelBack +# readability-identifier-naming.FunctionCase: camelBack +# readability-identifier-naming.MemberCase: camelBack +# readability-identifier-naming.PrivateMemberSuffix: _ +# readability-identifier-naming.ProtectedMemberSuffix: _ +# readability-identifier-naming.PublicMemberSuffix: "" +# readability-identifier-naming.FunctionIgnoredRegexp: ".*tag_invoke.*" +# bugprone-unsafe-functions.ReportMoreUnsafeFunctions: true +# bugprone-unused-return-value.CheckedReturnTypes: ::std::error_code;::std::error_condition;::std::errc +# misc-include-cleaner.IgnoreHeaders: '.*/(detail|impl)/.*;.*(expected|unexpected).*;.*ranges_lower_bound\.h;time.h;stdlib.h;__chrono/.*;fmt/chrono.h;boost/uuid/uuid_hash.hpp' +# +# HeaderFilterRegex: '^.*/(src|tests)/.*\.(h|hpp)$' +WarningsAsErrors: "*" diff --git a/.cmake-format.yaml b/.cmake-format.yaml index 1a3337fe8c..40c1101208 100644 --- a/.cmake-format.yaml +++ b/.cmake-format.yaml @@ -29,7 +29,7 @@ format: disable: false _help_line_width: - How wide to allow formatted cmake files - line_width: 120 + line_width: 100 _help_tab_size: - How many spaces to tab for indent tab_size: 4 diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..66e319e0e7 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,56 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + day: monday + time: "04:00" + timezone: Etc/GMT + commit-message: + prefix: "ci: [DEPENDABOT] " + target-branch: develop + + - package-ecosystem: github-actions + directory: .github/actions/build-deps/ + schedule: + interval: weekly + day: monday + time: "04:00" + timezone: Etc/GMT + commit-message: + prefix: "ci: [DEPENDABOT] " + target-branch: develop + + - package-ecosystem: github-actions + directory: .github/actions/generate-version/ + schedule: + interval: weekly + day: monday + time: "04:00" + timezone: Etc/GMT + commit-message: + prefix: "ci: [DEPENDABOT] " + target-branch: develop + + - package-ecosystem: github-actions + directory: .github/actions/print-env/ + schedule: + interval: weekly + day: monday + time: "04:00" + timezone: Etc/GMT + commit-message: + prefix: "ci: [DEPENDABOT] " + target-branch: develop + + - package-ecosystem: github-actions + directory: .github/actions/setup-conan/ + schedule: + interval: weekly + day: monday + time: "04:00" + timezone: Etc/GMT + commit-message: + prefix: "ci: [DEPENDABOT] " + target-branch: develop diff --git a/.github/scripts/levelization/results/loops.txt b/.github/scripts/levelization/results/loops.txt index 34842d7f48..7914704f9d 100644 --- a/.github/scripts/levelization/results/loops.txt +++ b/.github/scripts/levelization/results/loops.txt @@ -5,7 +5,7 @@ Loop: test.jtx test.unit_test test.unit_test == test.jtx Loop: xrpld.app xrpld.overlay - xrpld.overlay > xrpld.app + xrpld.overlay ~= xrpld.app Loop: xrpld.app xrpld.peerfinder xrpld.peerfinder == xrpld.app diff --git a/.github/scripts/levelization/results/ordering.txt b/.github/scripts/levelization/results/ordering.txt index 85f2457ea3..d4d07eee94 100644 --- a/.github/scripts/levelization/results/ordering.txt +++ b/.github/scripts/levelization/results/ordering.txt @@ -1,4 +1,6 @@ libxrpl.basics > xrpl.basics +libxrpl.conditions > xrpl.basics +libxrpl.conditions > xrpl.conditions libxrpl.core > xrpl.basics libxrpl.core > xrpl.core libxrpl.crypto > xrpl.basics @@ -30,6 +32,14 @@ libxrpl.server > xrpl.server libxrpl.shamap > xrpl.basics libxrpl.shamap > xrpl.protocol libxrpl.shamap > xrpl.shamap +libxrpl.tx > xrpl.basics +libxrpl.tx > xrpl.conditions +libxrpl.tx > xrpl.core +libxrpl.tx > xrpl.json +libxrpl.tx > xrpl.ledger +libxrpl.tx > xrpl.protocol +libxrpl.tx > xrpl.server +libxrpl.tx > xrpl.tx test.app > test.jtx test.app > test.rpc test.app > test.toplevel @@ -47,6 +57,7 @@ test.app > xrpl.protocol test.app > xrpl.rdb test.app > xrpl.resource test.app > xrpl.server +test.app > xrpl.tx test.basics > test.jtx test.basics > test.unit_test test.basics > xrpl.basics @@ -56,7 +67,7 @@ test.basics > xrpl.json test.basics > xrpl.protocol test.beast > xrpl.basics test.conditions > xrpl.basics -test.conditions > xrpld.conditions +test.conditions > xrpl.conditions test.consensus > test.csf test.consensus > test.toplevel test.consensus > test.unit_test @@ -65,6 +76,7 @@ test.consensus > xrpld.app test.consensus > xrpld.consensus test.consensus > xrpl.json test.consensus > xrpl.ledger +test.consensus > xrpl.tx test.core > test.jtx test.core > test.toplevel test.core > test.unit_test @@ -81,6 +93,7 @@ test.csf > xrpl.protocol test.json > test.jtx test.json > xrpl.json test.jtx > xrpl.basics +test.jtx > xrpl.core test.jtx > xrpld.app test.jtx > xrpld.core test.jtx > xrpld.rpc @@ -90,6 +103,7 @@ test.jtx > xrpl.net test.jtx > xrpl.protocol test.jtx > xrpl.resource test.jtx > xrpl.server +test.jtx > xrpl.tx test.ledger > test.jtx test.ledger > test.toplevel test.ledger > xrpl.basics @@ -135,8 +149,11 @@ test.rpc > xrpld.core test.rpc > xrpld.overlay test.rpc > xrpld.rpc test.rpc > xrpl.json +test.rpc > xrpl.ledger test.rpc > xrpl.protocol test.rpc > xrpl.resource +test.rpc > xrpl.server +test.rpc > xrpl.tx test.server > test.jtx test.server > test.toplevel test.server > test.unit_test @@ -157,6 +174,8 @@ test.unit_test > xrpl.basics tests.libxrpl > xrpl.basics tests.libxrpl > xrpl.json tests.libxrpl > xrpl.net +xrpl.conditions > xrpl.basics +xrpl.conditions > xrpl.protocol xrpl.core > xrpl.basics xrpl.core > xrpl.json xrpl.core > xrpl.ledger @@ -164,6 +183,8 @@ xrpl.core > xrpl.protocol xrpl.json > xrpl.basics xrpl.ledger > xrpl.basics xrpl.ledger > xrpl.protocol +xrpl.ledger > xrpl.server +xrpl.ledger > xrpl.shamap xrpl.net > xrpl.basics xrpl.nodestore > xrpl.basics xrpl.nodestore > xrpl.protocol @@ -180,13 +201,18 @@ xrpl.server > xrpl.core xrpl.server > xrpl.json xrpl.server > xrpl.protocol xrpl.server > xrpl.rdb +xrpl.server > xrpl.resource +xrpl.server > xrpl.shamap xrpl.shamap > xrpl.basics xrpl.shamap > xrpl.nodestore xrpl.shamap > xrpl.protocol +xrpl.tx > xrpl.basics +xrpl.tx > xrpl.core +xrpl.tx > xrpl.ledger +xrpl.tx > xrpl.protocol xrpld.app > test.unit_test xrpld.app > xrpl.basics xrpld.app > xrpl.core -xrpld.app > xrpld.conditions xrpld.app > xrpld.consensus xrpld.app > xrpld.core xrpld.app > xrpl.json @@ -198,8 +224,7 @@ xrpld.app > xrpl.rdb xrpld.app > xrpl.resource xrpld.app > xrpl.server xrpld.app > xrpl.shamap -xrpld.conditions > xrpl.basics -xrpld.conditions > xrpl.protocol +xrpld.app > xrpl.tx xrpld.consensus > xrpl.basics xrpld.consensus > xrpl.json xrpld.consensus > xrpl.protocol @@ -218,6 +243,7 @@ xrpld.overlay > xrpl.protocol xrpld.overlay > xrpl.rdb xrpld.overlay > xrpl.resource xrpld.overlay > xrpl.server +xrpld.overlay > xrpl.tx xrpld.peerfinder > xrpl.basics xrpld.peerfinder > xrpld.core xrpld.peerfinder > xrpl.protocol @@ -237,4 +263,5 @@ xrpld.rpc > xrpl.protocol xrpld.rpc > xrpl.rdb xrpld.rpc > xrpl.resource xrpld.rpc > xrpl.server +xrpld.rpc > xrpl.tx xrpld.shamap > xrpl.shamap diff --git a/.github/workflows/on-pr.yml b/.github/workflows/on-pr.yml index 46f6b7500a..be6a92eea2 100644 --- a/.github/workflows/on-pr.yml +++ b/.github/workflows/on-pr.yml @@ -33,7 +33,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Determine changed files # This step checks whether any files have changed that should # cause the next jobs to run. We do it this way rather than @@ -46,7 +46,7 @@ jobs: # that Github considers any skipped jobs to have passed, and in # turn the required checks as well. id: changes - uses: tj-actions/changed-files@ed68ef82c095e0d48ec87eccea555d944a631a4c # v46.0.5 + uses: tj-actions/changed-files@7dee1b0c1557f278e5c7dc244927139d78c0e22a # v47.0.4 with: files: | # These paths are unique to `on-pr.yml`. @@ -65,9 +65,12 @@ jobs: .github/workflows/reusable-build.yml .github/workflows/reusable-build-test-config.yml .github/workflows/reusable-build-test.yml + .github/workflows/reusable-clang-tidy.yml + .github/workflows/reusable-clang-tidy-files.yml .github/workflows/reusable-strategy-matrix.yml .github/workflows/reusable-test.yml .github/workflows/reusable-upload-recipe.yml + .clang-tidy .codecov.yml cmake/** conan/** @@ -107,6 +110,17 @@ jobs: if: ${{ needs.should-run.outputs.go == 'true' }} uses: ./.github/workflows/reusable-check-rename.yml + clang-tidy: + needs: should-run + if: ${{ needs.should-run.outputs.go == 'true' }} + uses: ./.github/workflows/reusable-clang-tidy.yml + permissions: + issues: write + contents: read + with: + check_only_changed: true + create_issue_on_failure: false + build-test: needs: should-run if: ${{ needs.should-run.outputs.go == 'true' }} @@ -156,6 +170,7 @@ jobs: needs: - check-levelization - check-rename + - clang-tidy - build-test - upload-recipe - notify-clio diff --git a/.github/workflows/on-trigger.yml b/.github/workflows/on-trigger.yml index 210670f5a1..c7e0e8c3aa 100644 --- a/.github/workflows/on-trigger.yml +++ b/.github/workflows/on-trigger.yml @@ -22,9 +22,12 @@ on: - ".github/workflows/reusable-build.yml" - ".github/workflows/reusable-build-test-config.yml" - ".github/workflows/reusable-build-test.yml" + - ".github/workflows/reusable-clang-tidy.yml" + - ".github/workflows/reusable-clang-tidy-files.yml" - ".github/workflows/reusable-strategy-matrix.yml" - ".github/workflows/reusable-test.yml" - ".github/workflows/reusable-upload-recipe.yml" + - ".clang-tidy" - ".codecov.yml" - "cmake/**" - "conan/**" @@ -60,6 +63,15 @@ defaults: shell: bash jobs: + clang-tidy: + uses: ./.github/workflows/reusable-clang-tidy.yml + permissions: + issues: write + contents: read + with: + check_only_changed: false + create_issue_on_failure: ${{ github.event_name == 'schedule' }} + build-test: uses: ./.github/workflows/reusable-build-test.yml strategy: diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index f61559d6d3..acde57fd91 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -4,6 +4,18 @@ name: Build and publish documentation on: push: + branches: + - "develop" + - "release*" + paths: + - ".github/workflows/publish-docs.yml" + - "*.md" + - "**/*.md" + - "docs/**" + - "include/**" + - "src/libxrpl/**" + - "src/xrpld/**" + pull_request: paths: - ".github/workflows/publish-docs.yml" - "*.md" @@ -23,7 +35,9 @@ defaults: env: BUILD_DIR: build - NPROC_SUBTRACT: 2 + # ubuntu-latest has only 2 CPUs for private repositories + # https://docs.github.com/en/actions/reference/runners/github-hosted-runners#standard-github-hosted-runners-for--private-repositories + NPROC_SUBTRACT: ${{ github.event.repository.private && '1' || '2' }} jobs: publish: @@ -33,7 +47,7 @@ jobs: contents: write steps: - name: Checkout repository - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Get number of processors uses: XRPLF/actions/get-nproc@cf0433aa74563aead044a1e395610c96d65a37cf @@ -65,7 +79,7 @@ jobs: cmake --build . --target docs --parallel ${BUILD_NPROC} - name: Publish documentation - if: ${{ github.ref_type == 'branch' && github.ref_name == github.event.repository.default_branch }} + if: ${{ github.event_name == 'push' }} uses: peaceiris/actions-gh-pages@4f9cc6602d3f66b9c108549d475ec49e8ef4d45e # v4.0.0 with: github_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index 85b973ea0c..4f52b68b84 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -104,7 +104,7 @@ jobs: uses: XRPLF/actions/cleanup-workspace@cf0433aa74563aead044a1e395610c96d65a37cf - name: Checkout repository - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Prepare runner uses: XRPLF/actions/prepare-runner@2cbf481018d930656e9276fcc20dc0e3a0be5b6d @@ -177,7 +177,7 @@ jobs: - name: Upload the binary (Linux) if: ${{ github.repository_owner == 'XRPLF' && runner.os == 'Linux' }} - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: name: xrpld-${{ inputs.config_name }} path: ${{ env.BUILD_DIR }}/xrpld @@ -254,7 +254,7 @@ jobs: - name: Upload coverage report if: ${{ github.repository_owner == 'XRPLF' && !inputs.build_only && env.COVERAGE_ENABLED == 'true' }} - uses: codecov/codecov-action@18283e04ce6e62d37312384ff67231eb8fd56d24 # v5.4.3 + uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de # v5.5.2 with: disable_search: true disable_telem: true diff --git a/.github/workflows/reusable-check-levelization.yml b/.github/workflows/reusable-check-levelization.yml index 29a1dc1480..ae3eed0f16 100644 --- a/.github/workflows/reusable-check-levelization.yml +++ b/.github/workflows/reusable-check-levelization.yml @@ -18,7 +18,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Check levelization run: .github/scripts/levelization/generate.sh - name: Check for differences diff --git a/.github/workflows/reusable-check-rename.yml b/.github/workflows/reusable-check-rename.yml index a73ac49b7d..0e335ab9ca 100644 --- a/.github/workflows/reusable-check-rename.yml +++ b/.github/workflows/reusable-check-rename.yml @@ -18,7 +18,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Check definitions run: .github/scripts/rename/definitions.sh . - name: Check copyright notices diff --git a/.github/workflows/reusable-clang-tidy-files.yml b/.github/workflows/reusable-clang-tidy-files.yml new file mode 100644 index 0000000000..432da1d15c --- /dev/null +++ b/.github/workflows/reusable-clang-tidy-files.yml @@ -0,0 +1,162 @@ +name: Run clang-tidy on files + +on: + workflow_call: + inputs: + files: + description: "List of files to check (empty means check all files)" + type: string + default: "" + create_issue_on_failure: + description: "Whether to create an issue if the check failed" + type: boolean + default: false + +defaults: + run: + shell: bash + +env: + # Conan installs the generators in the build/generators directory, see the + # layout() method in conanfile.py. We then run CMake from the build directory. + BUILD_DIR: build + BUILD_TYPE: Release + +jobs: + run-clang-tidy: + name: Run clang tidy + runs-on: ["self-hosted", "Linux", "X64", "heavy"] + container: "ghcr.io/xrplf/ci/debian-trixie:clang-21-sha-53033a2" + permissions: + issues: write + contents: read + steps: + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Prepare runner + uses: XRPLF/actions/prepare-runner@2cbf481018d930656e9276fcc20dc0e3a0be5b6d + with: + enable_ccache: false + + - name: Print build environment + uses: ./.github/actions/print-env + + - name: Get number of processors + uses: XRPLF/actions/get-nproc@cf0433aa74563aead044a1e395610c96d65a37cf + id: nproc + + - name: Setup Conan + uses: ./.github/actions/setup-conan + + - name: Build dependencies + uses: ./.github/actions/build-deps + with: + build_nproc: ${{ steps.nproc.outputs.nproc }} + build_type: ${{ env.BUILD_TYPE }} + log_verbosity: verbose + + - name: Configure CMake + working-directory: ${{ env.BUILD_DIR }} + run: | + cmake \ + -G 'Ninja' \ + -DCMAKE_TOOLCHAIN_FILE:FILEPATH=build/generators/conan_toolchain.cmake \ + -DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \ + -Dtests=ON \ + -Dwerr=ON \ + -Dxrpld=ON \ + .. + + # clang-tidy needs headers generated from proto files + - name: Build libxrpl.libpb + working-directory: ${{ env.BUILD_DIR }} + run: | + ninja -j ${{ steps.nproc.outputs.nproc }} xrpl.libpb + + - name: Run clang tidy + id: run_clang_tidy + continue-on-error: true + env: + FILES: ${{ inputs.files }} + run: | + run-clang-tidy -j ${{ steps.nproc.outputs.nproc }} -p "$BUILD_DIR" $FILES 2>&1 | tee clang-tidy-output.txt + + - name: Upload clang-tidy output + if: steps.run_clang_tidy.outcome != 'success' + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 + with: + name: clang-tidy-results + path: clang-tidy-output.txt + retention-days: 30 + + - name: Create an issue + if: steps.run_clang_tidy.outcome != 'success' && inputs.create_issue_on_failure + id: create_issue + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + # Prepare issue body with clang-tidy output + cat > issue.md < filtered-output.txt || true + + # If filtered output is empty, use original (might be a different error format) + if [ ! -s filtered-output.txt ]; then + cp clang-tidy-output.txt filtered-output.txt + fi + + # Truncate if too large + head -c 60000 filtered-output.txt >> issue.md + if [ "$(wc -c < filtered-output.txt)" -gt 60000 ]; then + echo "" >> issue.md + echo "... (output truncated, see artifacts for full output)" >> issue.md + fi + + rm filtered-output.txt + else + echo "No output file found" >> issue.md + fi + + cat >> issue.md < create_issue.log + + created_issue="$(sed 's|.*/||' create_issue.log)" + echo "created_issue=$created_issue" >> $GITHUB_OUTPUT + echo "Created issue #$created_issue" + + rm -f create_issue.log issue.md clang-tidy-output.txt + + - name: Fail the workflow if clang-tidy failed + if: steps.run_clang_tidy.outcome != 'success' + run: | + echo "Clang-tidy check failed!" + exit 1 diff --git a/.github/workflows/reusable-clang-tidy.yml b/.github/workflows/reusable-clang-tidy.yml new file mode 100644 index 0000000000..7c300ee26e --- /dev/null +++ b/.github/workflows/reusable-clang-tidy.yml @@ -0,0 +1,47 @@ +name: Clang-tidy check + +on: + workflow_call: + inputs: + check_only_changed: + description: "Check only changed files in PR. If false, checks all files in the repository." + type: boolean + default: false + create_issue_on_failure: + description: "Whether to create an issue if the check failed" + type: boolean + default: false + +defaults: + run: + shell: bash + +jobs: + determine-files: + name: Determine files to check + if: ${{ inputs.check_only_changed }} + runs-on: ubuntu-latest + outputs: + any_changed: ${{ steps.changed_files.outputs.any_changed }} + all_changed_files: ${{ steps.changed_files.outputs.all_changed_files }} + steps: + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Get changed C++ files + id: changed_files + uses: tj-actions/changed-files@7dee1b0c1557f278e5c7dc244927139d78c0e22a # v47.0.4 + with: + files: | + **/*.cpp + **/*.h + **/*.ipp + separator: " " + + run-clang-tidy: + needs: [determine-files] + if: ${{ always() && !cancelled() && (!inputs.check_only_changed || needs.determine-files.outputs.any_changed == 'true') }} + uses: ./.github/workflows/reusable-clang-tidy-files.yml + with: + files: ${{ inputs.check_only_changed && needs.determine-files.outputs.all_changed_files || '' }} + create_issue_on_failure: ${{ inputs.create_issue_on_failure }} diff --git a/.github/workflows/reusable-strategy-matrix.yml b/.github/workflows/reusable-strategy-matrix.yml index c975347307..b1232a138f 100644 --- a/.github/workflows/reusable-strategy-matrix.yml +++ b/.github/workflows/reusable-strategy-matrix.yml @@ -29,10 +29,10 @@ jobs: matrix: ${{ steps.generate.outputs.matrix }} steps: - name: Checkout repository - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Set up Python - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 with: python-version: 3.13 diff --git a/.github/workflows/reusable-upload-recipe.yml b/.github/workflows/reusable-upload-recipe.yml index 79af516fb3..6245fd06e1 100644 --- a/.github/workflows/reusable-upload-recipe.yml +++ b/.github/workflows/reusable-upload-recipe.yml @@ -43,7 +43,7 @@ jobs: container: ghcr.io/xrplf/ci/ubuntu-noble:gcc-13-sha-5dd7158 steps: - name: Checkout repository - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Generate build version number id: version diff --git a/.github/workflows/upload-conan-deps.yml b/.github/workflows/upload-conan-deps.yml index 60696a9769..b260c4c4f3 100644 --- a/.github/workflows/upload-conan-deps.yml +++ b/.github/workflows/upload-conan-deps.yml @@ -67,7 +67,7 @@ jobs: uses: XRPLF/actions/cleanup-workspace@cf0433aa74563aead044a1e395610c96d65a37cf - name: Checkout repository - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Prepare runner uses: XRPLF/actions/prepare-runner@2cbf481018d930656e9276fcc20dc0e3a0be5b6d diff --git a/.gitignore b/.gitignore index 2692d707e7..a1c2f034d1 100644 --- a/.gitignore +++ b/.gitignore @@ -71,3 +71,6 @@ DerivedData /.augment /.claude /CLAUDE.md + +# clangd cache +/.cache diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 79a3e4e7ec..9117fe0d3e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -20,7 +20,7 @@ repos: args: [--assume-in-merge] - repo: https://github.com/pre-commit/mirrors-clang-format - rev: 7d85583be209cb547946c82fbe51f4bc5dd1d017 # frozen: v18.1.8 + rev: 75ca4ad908dc4a99f57921f29b7e6c1521e10b26 # frozen: v21.1.8 hooks: - id: clang-format args: [--style=file] diff --git a/CMakeLists.txt b/CMakeLists.txt index 3c434506f7..764e917498 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,6 +17,7 @@ project(xrpl) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) include(CompilationEnv) @@ -38,16 +39,16 @@ include(Ccache) # make GIT_COMMIT_HASH define available to all sources find_package(Git) if (Git_FOUND) - execute_process(COMMAND ${GIT_EXECUTABLE} --git-dir=${CMAKE_CURRENT_SOURCE_DIR}/.git rev-parse HEAD - OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE gch) + execute_process(COMMAND ${GIT_EXECUTABLE} --git-dir=${CMAKE_CURRENT_SOURCE_DIR}/.git rev-parse + HEAD OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE gch) if (gch) set(GIT_COMMIT_HASH "${gch}") message(STATUS gch: ${GIT_COMMIT_HASH}) add_definitions(-DGIT_COMMIT_HASH="${GIT_COMMIT_HASH}") endif () - execute_process(COMMAND ${GIT_EXECUTABLE} --git-dir=${CMAKE_CURRENT_SOURCE_DIR}/.git rev-parse --abbrev-ref HEAD - OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE gb) + execute_process(COMMAND ${GIT_EXECUTABLE} --git-dir=${CMAKE_CURRENT_SOURCE_DIR}/.git rev-parse + --abbrev-ref HEAD OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE gb) if (gb) set(GIT_BRANCH "${gb}") message(STATUS gb: ${GIT_BRANCH}) @@ -67,7 +68,8 @@ include(FetchContent) include(ExternalProject) include(CMakeFuncs) # must come *after* ExternalProject b/c it overrides one function in EP if (target) - message(FATAL_ERROR "The target option has been removed - use native cmake options to control build") + message(FATAL_ERROR "The target option has been removed - use native cmake options to control build" + ) endif () include(XrplSanity) @@ -76,7 +78,8 @@ include(XrplSettings) # this check has to remain in the top-level cmake because of the early return statement if (packages_only) if (NOT TARGET rpm) - message(FATAL_ERROR "packages_only requested, but targets were not created - is docker installed?") + message(FATAL_ERROR "packages_only requested, but targets were not created - is docker installed?" + ) endif () return() endif () @@ -118,7 +121,8 @@ target_link_libraries( option(rocksdb "Enable RocksDB" ON) if (rocksdb) find_package(RocksDB REQUIRED) - set_target_properties(RocksDB::rocksdb PROPERTIES INTERFACE_COMPILE_DEFINITIONS XRPL_ROCKSDB_AVAILABLE=1) + set_target_properties(RocksDB::rocksdb PROPERTIES INTERFACE_COMPILE_DEFINITIONS + XRPL_ROCKSDB_AVAILABLE=1) target_link_libraries(xrpl_libs INTERFACE RocksDB::rocksdb) endif () diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 808d553e17..a928065ef2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -219,7 +219,7 @@ coherent rather than a set of _thou shalt not_ commandments. ## Formatting -All code must conform to `clang-format` version 18, +All code must conform to `clang-format` version 21, according to the settings in [`.clang-format`](./.clang-format), unless the result would be unreasonably difficult to read or maintain. To demarcate lines that should be left as-is, surround them with comments like diff --git a/cmake/Ccache.cmake b/cmake/Ccache.cmake index 000883cf6a..e34627ad8a 100644 --- a/cmake/Ccache.cmake +++ b/cmake/Ccache.cmake @@ -43,7 +43,8 @@ set(CMAKE_VS_GLOBALS "CLToolExe=cl.exe" "CLToolPath=${CMAKE_BINARY_DIR}" "TrackF # By default Visual Studio generators will use /Zi to capture debug information, which is not compatible with ccache, so # tell it to use /Z7 instead. if (MSVC) - foreach (var_ CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE) + foreach (var_ CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE CMAKE_CXX_FLAGS_DEBUG + CMAKE_CXX_FLAGS_RELEASE) string(REPLACE "/Zi" "/Z7" ${var_} "${${var_}}") endforeach () endif () diff --git a/cmake/CodeCoverage.cmake b/cmake/CodeCoverage.cmake index fcc4d44133..74796718c1 100644 --- a/cmake/CodeCoverage.cmake +++ b/cmake/CodeCoverage.cmake @@ -180,7 +180,8 @@ elseif (DEFINED ENV{CODE_COVERAGE_GCOV_TOOL}) set(GCOV_TOOL "$ENV{CODE_COVERAGE_GCOV_TOOL}") elseif ("${CMAKE_CXX_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang") if (APPLE) - execute_process(COMMAND xcrun -f llvm-cov OUTPUT_VARIABLE LLVMCOV_PATH OUTPUT_STRIP_TRAILING_WHITESPACE) + execute_process(COMMAND xcrun -f llvm-cov OUTPUT_VARIABLE LLVMCOV_PATH + OUTPUT_STRIP_TRAILING_WHITESPACE) else () find_program(LLVMCOV_PATH llvm-cov) endif () @@ -199,8 +200,8 @@ foreach (LANG ${LANGUAGES}) if ("${CMAKE_${LANG}_COMPILER_VERSION}" VERSION_LESS 3) message(FATAL_ERROR "Clang version must be 3.0.0 or greater! Aborting...") endif () - elseif (NOT "${CMAKE_${LANG}_COMPILER_ID}" MATCHES "GNU" AND NOT "${CMAKE_${LANG}_COMPILER_ID}" MATCHES - "(LLVM)?[Ff]lang") + elseif (NOT "${CMAKE_${LANG}_COMPILER_ID}" MATCHES "GNU" AND NOT "${CMAKE_${LANG}_COMPILER_ID}" + MATCHES "(LLVM)?[Ff]lang") message(FATAL_ERROR "Compiler is not GNU or Flang! Aborting...") endif () endforeach () @@ -321,14 +322,16 @@ function (setup_target_for_coverage_gcovr) endif () if ("--output" IN_LIST GCOVR_ADDITIONAL_ARGS) - message(FATAL_ERROR "Unsupported --output option detected in GCOVR_ADDITIONAL_ARGS! Aborting...") + message(FATAL_ERROR "Unsupported --output option detected in GCOVR_ADDITIONAL_ARGS! Aborting..." + ) else () if ((Coverage_FORMAT STREQUAL "html-details") OR (Coverage_FORMAT STREQUAL "html-nested")) set(GCOVR_OUTPUT_FILE ${PROJECT_BINARY_DIR}/${Coverage_NAME}/index.html) set(GCOVR_CREATE_FOLDER ${PROJECT_BINARY_DIR}/${Coverage_NAME}) elseif (Coverage_FORMAT STREQUAL "html-single") set(GCOVR_OUTPUT_FILE ${Coverage_NAME}.html) - elseif ((Coverage_FORMAT STREQUAL "json-summary") OR (Coverage_FORMAT STREQUAL "json-details") + elseif ((Coverage_FORMAT STREQUAL "json-summary") OR (Coverage_FORMAT STREQUAL + "json-details") OR (Coverage_FORMAT STREQUAL "coveralls")) set(GCOVR_OUTPUT_FILE ${Coverage_NAME}.json) elseif (Coverage_FORMAT STREQUAL "txt") @@ -452,8 +455,10 @@ function (setup_target_for_coverage_gcovr) COMMENT "Running gcovr to produce code coverage report.") # Show info where to find the report - add_custom_command(TARGET ${Coverage_NAME} POST_BUILD COMMAND echo - COMMENT "Code coverage report saved in ${GCOVR_OUTPUT_FILE} formatted as ${Coverage_FORMAT}") + add_custom_command( + TARGET ${Coverage_NAME} POST_BUILD COMMAND echo + COMMENT "Code coverage report saved in ${GCOVR_OUTPUT_FILE} formatted as ${Coverage_FORMAT}" + ) endfunction () # setup_target_for_coverage_gcovr function (add_code_coverage_to_target name scope) @@ -463,8 +468,9 @@ function (add_code_coverage_to_target name scope) separate_arguments(COVERAGE_C_LINKER_FLAGS NATIVE_COMMAND "${COVERAGE_C_LINKER_FLAGS}") # Add compiler options to the target - target_compile_options(${name} ${scope} $<$:${COVERAGE_CXX_COMPILER_FLAGS}> - $<$:${COVERAGE_C_COMPILER_FLAGS}>) + target_compile_options( + ${name} ${scope} $<$:${COVERAGE_CXX_COMPILER_FLAGS}> + $<$:${COVERAGE_C_COMPILER_FLAGS}>) target_link_libraries(${name} ${scope} $<$:${COVERAGE_CXX_LINKER_FLAGS}> $<$:${COVERAGE_C_LINKER_FLAGS}>) diff --git a/cmake/XrplCompiler.cmake b/cmake/XrplCompiler.cmake index f7ac8c2b71..8093004b2e 100644 --- a/cmake/XrplCompiler.cmake +++ b/cmake/XrplCompiler.cmake @@ -17,7 +17,8 @@ link_libraries(Xrpl::common) if (NOT DEFINED CMAKE_POSITION_INDEPENDENT_CODE) set(CMAKE_POSITION_INDEPENDENT_CODE ON) endif () -set_target_properties(common PROPERTIES INTERFACE_POSITION_INDEPENDENT_CODE ${CMAKE_POSITION_INDEPENDENT_CODE}) +set_target_properties(common PROPERTIES INTERFACE_POSITION_INDEPENDENT_CODE + ${CMAKE_POSITION_INDEPENDENT_CODE}) set(CMAKE_CXX_EXTENSIONS OFF) target_compile_definitions( common @@ -37,7 +38,8 @@ if (MSVC) # remove existing exception flag since we set it to -EHa string(REGEX REPLACE "[-/]EH[a-z]+" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") - foreach (var_ CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE) + foreach (var_ CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE CMAKE_CXX_FLAGS_DEBUG + CMAKE_CXX_FLAGS_RELEASE) # also remove dynamic runtime string(REGEX REPLACE "[-/]MD[d]*" " " ${var_} "${${var_}}") @@ -143,20 +145,23 @@ if (voidstar) elseif (NOT is_linux) message(FATAL_ERROR "Antithesis instrumentation requires Linux, aborting...") elseif (NOT (is_clang AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.0)) - message(FATAL_ERROR "Antithesis instrumentation requires Clang version 16 or later, aborting...") + message(FATAL_ERROR "Antithesis instrumentation requires Clang version 16 or later, aborting..." + ) endif () endif () if (use_mold) # use mold linker if available - execute_process(COMMAND ${CMAKE_CXX_COMPILER} -fuse-ld=mold -Wl,--version ERROR_QUIET OUTPUT_VARIABLE LD_VERSION) + execute_process(COMMAND ${CMAKE_CXX_COMPILER} -fuse-ld=mold -Wl,--version ERROR_QUIET + OUTPUT_VARIABLE LD_VERSION) if ("${LD_VERSION}" MATCHES "mold") target_link_libraries(common INTERFACE -fuse-ld=mold) endif () unset(LD_VERSION) elseif (use_gold AND is_gcc) # use gold linker if available - execute_process(COMMAND ${CMAKE_CXX_COMPILER} -fuse-ld=gold -Wl,--version ERROR_QUIET OUTPUT_VARIABLE LD_VERSION) + execute_process(COMMAND ${CMAKE_CXX_COMPILER} -fuse-ld=gold -Wl,--version ERROR_QUIET + OUTPUT_VARIABLE LD_VERSION) #[=========================================================[ NOTE: THE gold linker inserts -rpath as DT_RUNPATH by default instead of DT_RPATH, so you might have slightly @@ -186,7 +191,8 @@ elseif (use_gold AND is_gcc) unset(LD_VERSION) elseif (use_lld) # use lld linker if available - execute_process(COMMAND ${CMAKE_CXX_COMPILER} -fuse-ld=lld -Wl,--version ERROR_QUIET OUTPUT_VARIABLE LD_VERSION) + execute_process(COMMAND ${CMAKE_CXX_COMPILER} -fuse-ld=lld -Wl,--version ERROR_QUIET + OUTPUT_VARIABLE LD_VERSION) if ("${LD_VERSION}" MATCHES "LLD") target_link_libraries(common INTERFACE -fuse-ld=lld) endif () diff --git a/cmake/XrplCore.cmake b/cmake/XrplCore.cmake index cea19db9bc..e54dd09953 100644 --- a/cmake/XrplCore.cmake +++ b/cmake/XrplCore.cmake @@ -14,7 +14,8 @@ target_protobuf_sources(xrpl.libpb xrpl/proto LANGUAGE cpp IMPORT_DIRS include/x PROTOS include/xrpl/proto/xrpl.proto) file(GLOB_RECURSE protos "include/xrpl/proto/org/*.proto") -target_protobuf_sources(xrpl.libpb xrpl/proto LANGUAGE cpp IMPORT_DIRS include/xrpl/proto PROTOS "${protos}") +target_protobuf_sources(xrpl.libpb xrpl/proto LANGUAGE cpp IMPORT_DIRS include/xrpl/proto + PROTOS "${protos}") target_protobuf_sources( xrpl.libpb xrpl/proto LANGUAGE grpc @@ -24,8 +25,9 @@ target_protobuf_sources( GENERATE_EXTENSIONS .grpc.pb.h .grpc.pb.cc) target_compile_options( - xrpl.libpb PUBLIC $<$:-wd4996> $<$: --system-header-prefix="google/protobuf" - -Wno-deprecated-dynamic-exception-spec > + xrpl.libpb + PUBLIC $<$:-wd4996> $<$: + --system-header-prefix="google/protobuf" -Wno-deprecated-dynamic-exception-spec > PRIVATE $<$:-wd4065> $<$>:-Wno-deprecated-declarations>) target_link_libraries(xrpl.libpb PUBLIC protobuf::libprotobuf gRPC::grpc++) @@ -73,7 +75,8 @@ target_link_libraries(xrpl.libxrpl.protocol PUBLIC xrpl.libxrpl.crypto xrpl.libx # Level 05 add_module(xrpl core) -target_link_libraries(xrpl.libxrpl.core PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.json xrpl.libxrpl.protocol) +target_link_libraries(xrpl.libxrpl.core PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.json + xrpl.libxrpl.protocol) # Level 06 add_module(xrpl resource) @@ -81,25 +84,40 @@ target_link_libraries(xrpl.libxrpl.resource PUBLIC xrpl.libxrpl.protocol) # Level 07 add_module(xrpl net) -target_link_libraries(xrpl.libxrpl.net PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.json xrpl.libxrpl.protocol - xrpl.libxrpl.resource) +target_link_libraries(xrpl.libxrpl.net PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.json + xrpl.libxrpl.protocol xrpl.libxrpl.resource) add_module(xrpl nodestore) -target_link_libraries(xrpl.libxrpl.nodestore PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.json xrpl.libxrpl.protocol) +target_link_libraries(xrpl.libxrpl.nodestore PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.json + xrpl.libxrpl.protocol) add_module(xrpl shamap) -target_link_libraries(xrpl.libxrpl.shamap PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.crypto xrpl.libxrpl.protocol - xrpl.libxrpl.nodestore) +target_link_libraries(xrpl.libxrpl.shamap PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.crypto + xrpl.libxrpl.protocol xrpl.libxrpl.nodestore) add_module(xrpl rdb) target_link_libraries(xrpl.libxrpl.rdb PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.core) add_module(xrpl server) -target_link_libraries(xrpl.libxrpl.server PUBLIC xrpl.libxrpl.protocol xrpl.libxrpl.core xrpl.libxrpl.rdb) +target_link_libraries(xrpl.libxrpl.server PUBLIC xrpl.libxrpl.protocol xrpl.libxrpl.core + xrpl.libxrpl.rdb xrpl.libxrpl.resource) + +add_module(xrpl conditions) +target_link_libraries(xrpl.libxrpl.conditions PUBLIC xrpl.libxrpl.server) add_module(xrpl ledger) -target_link_libraries(xrpl.libxrpl.ledger PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.json xrpl.libxrpl.protocol - xrpl.libxrpl.rdb) +target_link_libraries( + xrpl.libxrpl.ledger + PUBLIC xrpl.libxrpl.basics + xrpl.libxrpl.json + xrpl.libxrpl.protocol + xrpl.libxrpl.rdb + xrpl.libxrpl.server + xrpl.libxrpl.shamap + xrpl.libxrpl.conditions) + +add_module(xrpl tx) +target_link_libraries(xrpl.libxrpl.tx PUBLIC xrpl.libxrpl.ledger) add_library(xrpl.libxrpl) set_target_properties(xrpl.libxrpl PROPERTIES OUTPUT_NAME xrpl) @@ -114,6 +132,7 @@ target_link_modules( PUBLIC basics beast + conditions core crypto json @@ -124,7 +143,8 @@ target_link_modules( rdb resource server - shamap) + shamap + tx) # All headers in libxrpl are in modules. # Uncomment this stanza if you have not yet moved new headers into a module. diff --git a/cmake/XrplDocs.cmake b/cmake/XrplDocs.cmake index 69581a99c7..4892e390ce 100644 --- a/cmake/XrplDocs.cmake +++ b/cmake/XrplDocs.cmake @@ -65,8 +65,8 @@ add_custom_command( OUTPUT "${doxygen_index_file}" COMMAND "${CMAKE_COMMAND}" -E env "DOXYGEN_OUTPUT_DIRECTORY=${doxygen_output_directory}" "DOXYGEN_INCLUDE_PATH=${doxygen_include_path}" "DOXYGEN_TAGFILES=${doxygen_tagfiles}" - "DOXYGEN_PLANTUML_JAR_PATH=${doxygen_plantuml_jar_path}" "DOXYGEN_DOT_PATH=${doxygen_dot_path}" - "${DOXYGEN_EXECUTABLE}" "${doxyfile}" + "DOXYGEN_PLANTUML_JAR_PATH=${doxygen_plantuml_jar_path}" + "DOXYGEN_DOT_PATH=${doxygen_dot_path}" "${DOXYGEN_EXECUTABLE}" "${doxyfile}" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" DEPENDS "${dependencies}" "${tagfile}") add_custom_target(docs DEPENDS "${doxygen_index_file}" SOURCES "${dependencies}") diff --git a/cmake/XrplInstall.cmake b/cmake/XrplInstall.cmake index 340dca553b..4cbf381f87 100644 --- a/cmake/XrplInstall.cmake +++ b/cmake/XrplInstall.cmake @@ -20,6 +20,7 @@ install(TARGETS common xrpl.libxrpl xrpl.libxrpl.basics xrpl.libxrpl.beast + xrpl.libxrpl.conditions xrpl.libxrpl.core xrpl.libxrpl.crypto xrpl.libxrpl.json @@ -31,6 +32,7 @@ install(TARGETS common xrpl.libxrpl.resource xrpl.libxrpl.server xrpl.libxrpl.shamap + xrpl.libxrpl.tx antithesis-sdk-cpp EXPORT XrplExports LIBRARY DESTINATION lib @@ -39,11 +41,13 @@ install(TARGETS common INCLUDES DESTINATION include) -install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/xrpl" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") +install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/xrpl" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") install(EXPORT XrplExports FILE XrplTargets.cmake NAMESPACE Xrpl:: DESTINATION lib/cmake/xrpl) include(CMakePackageConfigHelpers) -write_basic_package_version_file(XrplConfigVersion.cmake VERSION ${xrpld_version} COMPATIBILITY SameMajorVersion) +write_basic_package_version_file(XrplConfigVersion.cmake VERSION ${xrpld_version} + COMPATIBILITY SameMajorVersion) if (is_root_project AND TARGET xrpld) install(TARGETS xrpld RUNTIME DESTINATION bin) @@ -70,5 +74,5 @@ if (is_root_project AND TARGET xrpld) ") endif () -install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/cmake/XrplConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/XrplConfigVersion.cmake - DESTINATION lib/cmake/xrpl) +install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/cmake/XrplConfig.cmake + ${CMAKE_CURRENT_BINARY_DIR}/XrplConfigVersion.cmake DESTINATION lib/cmake/xrpl) diff --git a/cmake/XrplInterface.cmake b/cmake/XrplInterface.cmake index f471b37dd7..dbf907c7b4 100644 --- a/cmake/XrplInterface.cmake +++ b/cmake/XrplInterface.cmake @@ -33,10 +33,13 @@ target_compile_definitions( target_compile_options( opts INTERFACE $<$,$>:-Wsuggest-override> - $<$:-Wno-maybe-uninitialized> $<$:-fno-omit-frame-pointer> - $<$:-pg> $<$,$>:-p>) + $<$:-Wno-maybe-uninitialized> + $<$:-fno-omit-frame-pointer> + $<$:-pg> + $<$,$>:-p>) -target_link_libraries(opts INTERFACE $<$:-pg> $<$,$>:-p>) +target_link_libraries(opts INTERFACE $<$:-pg> + $<$,$>:-p>) if (jemalloc) find_package(jemalloc REQUIRED) diff --git a/cmake/XrplSanity.cmake b/cmake/XrplSanity.cmake index 5055414abd..489ad026e1 100644 --- a/cmake/XrplSanity.cmake +++ b/cmake/XrplSanity.cmake @@ -19,7 +19,8 @@ if (NOT is_multiconfig) endif () if (is_clang) # both Clang and AppleClang - if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16.0) + if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS + 16.0) message(FATAL_ERROR "This project requires clang 16 or later") endif () elseif (is_gcc) @@ -32,7 +33,8 @@ endif () if ("${CMAKE_CURRENT_SOURCE_DIR}" STREQUAL "${CMAKE_BINARY_DIR}") message(FATAL_ERROR "Builds (in-source) are not allowed in " "${CMAKE_CURRENT_SOURCE_DIR}. Please remove CMakeCache.txt and the CMakeFiles " - "directory from ${CMAKE_CURRENT_SOURCE_DIR} and try building in a separate directory.") + "directory from ${CMAKE_CURRENT_SOURCE_DIR} and try building in a separate directory." + ) endif () if (MSVC AND CMAKE_GENERATOR_PLATFORM STREQUAL "Win32") diff --git a/cmake/XrplSettings.cmake b/cmake/XrplSettings.cmake index 6d332be19d..5c753fdcda 100644 --- a/cmake/XrplSettings.cmake +++ b/cmake/XrplSettings.cmake @@ -70,7 +70,8 @@ if (is_linux AND NOT SANITIZER) else () set(TRUNCATED_LOGS_DEFAULT OFF) endif () - option(TRUNCATED_THREAD_NAME_LOGS "Show warnings about truncated thread names on Linux." ${TRUNCATED_LOGS_DEFAULT}) + option(TRUNCATED_THREAD_NAME_LOGS "Show warnings about truncated thread names on Linux." + ${TRUNCATED_LOGS_DEFAULT}) if (TRUNCATED_THREAD_NAME_LOGS) add_compile_definitions(TRUNCATED_THREAD_NAME_LOGS) endif () @@ -92,11 +93,13 @@ endif () option(jemalloc "Enables jemalloc for heap profiling" OFF) option(werr "treat warnings as errors" OFF) -option(local_protobuf "Force a local build of protobuf instead of looking for an installed version." OFF) +option(local_protobuf + "Force a local build of protobuf instead of looking for an installed version." OFF) option(local_grpc "Force a local build of gRPC instead of looking for an installed version." OFF) # the remaining options are obscure and rarely used -option(beast_no_unit_test_inline "Prevents unit test definitions from being inserted into global table" OFF) +option(beast_no_unit_test_inline + "Prevents unit test definitions from being inserted into global table" OFF) option(single_io_service_thread "Restricts the number of threads calling io_context::run to one. \ This can be useful when debugging." OFF) option(boost_show_deprecated "Allow boost to fail on deprecated usage. Only useful if you're trying\ diff --git a/cmake/XrplValidatorKeys.cmake b/cmake/XrplValidatorKeys.cmake index 5fa7e14886..58672aada5 100644 --- a/cmake/XrplValidatorKeys.cmake +++ b/cmake/XrplValidatorKeys.cmake @@ -1,4 +1,6 @@ -option(validator_keys "Enables building of validator-keys tool as a separate target (imported via FetchContent)" OFF) +option(validator_keys + "Enables building of validator-keys tool as a separate target (imported via FetchContent)" + OFF) if (validator_keys) git_branch(current_branch) @@ -8,8 +10,9 @@ if (validator_keys) endif () message(STATUS "Tracking ValidatorKeys branch: ${current_branch}") - FetchContent_Declare(validator_keys GIT_REPOSITORY https://github.com/ripple/validator-keys-tool.git - GIT_TAG "${current_branch}") + FetchContent_Declare( + validator_keys GIT_REPOSITORY https://github.com/ripple/validator-keys-tool.git + GIT_TAG "${current_branch}") FetchContent_MakeAvailable(validator_keys) set_target_properties(validator-keys PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") install(TARGETS validator-keys RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) diff --git a/cmake/add_module.cmake b/cmake/add_module.cmake index a3cb247fd2..73618e8be3 100644 --- a/cmake/add_module.cmake +++ b/cmake/add_module.cmake @@ -15,11 +15,12 @@ include(isolate_headers) function (add_module parent name) set(target ${PROJECT_NAME}.lib${parent}.${name}) add_library(${target} OBJECT) - file(GLOB_RECURSE sources CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/lib${parent}/${name}/*.cpp") + file(GLOB_RECURSE sources CONFIGURE_DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/src/lib${parent}/${name}/*.cpp") target_sources(${target} PRIVATE ${sources}) target_include_directories(${target} PUBLIC "$") isolate_headers(${target} "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/include/${parent}/${name}" PUBLIC) - isolate_headers(${target} "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_SOURCE_DIR}/src/lib${parent}/${name}" - PRIVATE) + isolate_headers(${target} "${CMAKE_CURRENT_SOURCE_DIR}/src" + "${CMAKE_CURRENT_SOURCE_DIR}/src/lib${parent}/${name}" PRIVATE) endfunction () diff --git a/cmake/deps/Boost.cmake b/cmake/deps/Boost.cmake index fe62fcb79c..a7b145364d 100644 --- a/cmake/deps/Boost.cmake +++ b/cmake/deps/Boost.cmake @@ -39,6 +39,7 @@ if (SANITIZERS_ENABLED AND is_clang) endif () message(STATUS "Adding [${Boost_INCLUDE_DIRS}] to sanitizer blacklist") file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/san_bl.txt "src:${Boost_INCLUDE_DIRS}/*") - target_compile_options(opts INTERFACE # ignore boost headers for sanitizing - -fsanitize-blacklist=${CMAKE_CURRENT_BINARY_DIR}/san_bl.txt) + target_compile_options( + opts INTERFACE # ignore boost headers for sanitizing + -fsanitize-blacklist=${CMAKE_CURRENT_BINARY_DIR}/san_bl.txt) endif () diff --git a/cspell.config.yaml b/cspell.config.yaml index c90a51dd76..d9e835daea 100644 --- a/cspell.config.yaml +++ b/cspell.config.yaml @@ -6,6 +6,7 @@ ignorePaths: - docs/**/*.puml - cmake/** - LICENSE.md + - .clang-tidy language: en allowCompoundWords: true # TODO (#6334) ignoreRandomStrings: true diff --git a/docs/CodingStyle.md b/docs/CodingStyle.md index 3c26709047..2788f7b210 100644 --- a/docs/CodingStyle.md +++ b/docs/CodingStyle.md @@ -17,8 +17,8 @@ guideline is to maintain the standards that are used in those libraries. ## Guidelines If you want to do something contrary to these guidelines, understand -why you're doing it. Think, use common sense, and consider that this -your changes will probably need to be maintained long after you've +why you're doing it. Think, use common sense, and consider that these +changes will probably need to be maintained long after you've moved on to other projects. - Use white space and blank lines to guide the eye and keep your intent clear. diff --git a/include/xrpl/basics/BasicConfig.h b/include/xrpl/basics/BasicConfig.h index d18019fa9f..f02bf07a83 100644 --- a/include/xrpl/basics/BasicConfig.h +++ b/include/xrpl/basics/BasicConfig.h @@ -84,7 +84,8 @@ public: if (lines_.empty()) return ""; if (lines_.size() > 1) - Throw("A legacy value must have exactly one line. Section: " + name_); + Throw( + "A legacy value must have exactly one line. Section: " + name_); return lines_[0]; } @@ -268,7 +269,8 @@ public: bool had_trailing_comments() const { - return std::any_of(map_.cbegin(), map_.cend(), [](auto s) { return s.second.had_trailing_comments(); }); + return std::any_of( + map_.cbegin(), map_.cend(), [](auto s) { return s.second.had_trailing_comments(); }); } protected: diff --git a/include/xrpl/basics/CompressionAlgorithms.h b/include/xrpl/basics/CompressionAlgorithms.h index b8fe4c8018..c549a58b93 100644 --- a/include/xrpl/basics/CompressionAlgorithms.h +++ b/include/xrpl/basics/CompressionAlgorithms.h @@ -35,7 +35,10 @@ lz4Compress(void const* in, std::size_t inSize, BufferFactory&& bf) auto compressed = bf(outCapacity); auto compressedSize = LZ4_compress_default( - reinterpret_cast(in), reinterpret_cast(compressed), inSize, outCapacity); + reinterpret_cast(in), + reinterpret_cast(compressed), + inSize, + outCapacity); if (compressedSize == 0) Throw("lz4 compress: failed"); @@ -66,8 +69,10 @@ lz4Decompress( Throw("lz4Decompress: integer overflow (output)"); if (LZ4_decompress_safe( - reinterpret_cast(in), reinterpret_cast(decompressed), inSize, decompressedSize) != - decompressedSize) + reinterpret_cast(in), + reinterpret_cast(decompressed), + inSize, + decompressedSize) != decompressedSize) Throw("lz4Decompress: failed"); return decompressedSize; @@ -83,7 +88,11 @@ lz4Decompress( */ template std::size_t -lz4Decompress(InputStream& in, std::size_t inSize, std::uint8_t* decompressed, std::size_t decompressedSize) +lz4Decompress( + InputStream& in, + std::size_t inSize, + std::uint8_t* decompressed, + std::size_t decompressedSize) { std::vector compressed; std::uint8_t const* chunk = nullptr; diff --git a/include/xrpl/basics/DecayingSample.h b/include/xrpl/basics/DecayingSample.h index e4c9ad5d7a..a8d6a2360e 100644 --- a/include/xrpl/basics/DecayingSample.h +++ b/include/xrpl/basics/DecayingSample.h @@ -55,7 +55,8 @@ private: if (m_value != value_type()) { - std::size_t elapsed = std::chrono::duration_cast(now - m_when).count(); + std::size_t elapsed = + std::chrono::duration_cast(now - m_when).count(); // A span larger than four times the window decays the // value to an insignificant amount so just reset it. diff --git a/include/xrpl/basics/Expected.h b/include/xrpl/basics/Expected.h index 7c98e72107..083a9233cf 100644 --- a/include/xrpl/basics/Expected.h +++ b/include/xrpl/basics/Expected.h @@ -120,7 +120,8 @@ public: template requires std::convertible_to && (!std::is_reference_v) - constexpr Expected(Unexpected e) : Base(boost::outcome_v2::in_place_type_t{}, std::move(e.value())) + constexpr Expected(Unexpected e) + : Base(boost::outcome_v2::in_place_type_t{}, std::move(e.value())) { } @@ -191,7 +192,8 @@ public: // Specialization of Expected. Allows returning either success // (without a value) or the reason for the failure. template -class [[nodiscard]] Expected : private boost::outcome_v2::result +class [[nodiscard]] +Expected : private boost::outcome_v2::result { using Base = boost::outcome_v2::result; diff --git a/include/xrpl/basics/FileUtilities.h b/include/xrpl/basics/FileUtilities.h index 299269703a..8cf7e4893f 100644 --- a/include/xrpl/basics/FileUtilities.h +++ b/include/xrpl/basics/FileUtilities.h @@ -14,6 +14,9 @@ getFileContents( std::optional maxSize = std::nullopt); void -writeFileContents(boost::system::error_code& ec, boost::filesystem::path const& destPath, std::string const& contents); +writeFileContents( + boost::system::error_code& ec, + boost::filesystem::path const& destPath, + std::string const& contents); } // namespace xrpl diff --git a/include/xrpl/basics/IntrusivePointer.h b/include/xrpl/basics/IntrusivePointer.h index 4464c37dc5..e6261be340 100644 --- a/include/xrpl/basics/IntrusivePointer.h +++ b/include/xrpl/basics/IntrusivePointer.h @@ -44,8 +44,8 @@ struct SharedIntrusiveAdoptNoIncrementTag // template -concept CAdoptTag = - std::is_same_v || std::is_same_v; +concept CAdoptTag = std::is_same_v || + std::is_same_v; //------------------------------------------------------------------------------ @@ -443,7 +443,8 @@ make_SharedIntrusive(Args&&... args) auto p = new TT(std::forward(args)...); static_assert( - noexcept(SharedIntrusive(std::declval(), std::declval())), + noexcept(SharedIntrusive( + std::declval(), std::declval())), "SharedIntrusive constructor should not throw or this can leak " "memory"); diff --git a/include/xrpl/basics/IntrusivePointer.ipp b/include/xrpl/basics/IntrusivePointer.ipp index d52aa6299f..de57e61ba6 100644 --- a/include/xrpl/basics/IntrusivePointer.ipp +++ b/include/xrpl/basics/IntrusivePointer.ipp @@ -208,7 +208,8 @@ SharedIntrusive::operator->() const noexcept } template -SharedIntrusive::operator bool() const noexcept +SharedIntrusive:: +operator bool() const noexcept { return bool(unsafeGetRawPtr()); } @@ -503,7 +504,8 @@ SharedWeakUnion::getStrong() const } template -SharedWeakUnion::operator bool() const noexcept +SharedWeakUnion:: +operator bool() const noexcept { return bool(get()); } diff --git a/include/xrpl/basics/IntrusiveRefCounts.h b/include/xrpl/basics/IntrusiveRefCounts.h index 0273ed4647..3b2be5c625 100644 --- a/include/xrpl/basics/IntrusiveRefCounts.h +++ b/include/xrpl/basics/IntrusiveRefCounts.h @@ -184,7 +184,8 @@ private: /** Mask that will zero out everything except the weak count. */ - static constexpr FieldType weakMask = (((one << WeakCountNumBits) - 1) << StrongCountNumBits) & valueMask; + static constexpr FieldType weakMask = + (((one << WeakCountNumBits) - 1) << StrongCountNumBits) & valueMask; /** Unpack the count and tag fields from the packed atomic integer form. */ struct RefCountPair @@ -209,8 +210,10 @@ private: FieldType combinedValue() const noexcept; - static constexpr CountType maxStrongValue = static_cast((one << StrongCountNumBits) - 1); - static constexpr CountType maxWeakValue = static_cast((one << WeakCountNumBits) - 1); + static constexpr CountType maxStrongValue = + static_cast((one << StrongCountNumBits) - 1); + static constexpr CountType maxWeakValue = + static_cast((one << WeakCountNumBits) - 1); /** Put an extra margin to detect when running up against limits. This is only used in debug code, and is useful if we reduce the number of bits in the strong and weak counts (to 16 and 14 bits). @@ -395,7 +398,8 @@ inline IntrusiveRefCounts::~IntrusiveRefCounts() noexcept { #ifndef NDEBUG auto v = refCounts.load(std::memory_order_acquire); - XRPL_ASSERT((!(v & valueMask)), "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : count must be zero"); + XRPL_ASSERT( + (!(v & valueMask)), "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : count must be zero"); auto t = v & tagMask; XRPL_ASSERT((!t || t == tagMask), "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : valid tag"); #endif @@ -433,8 +437,10 @@ IntrusiveRefCounts::RefCountPair::combinedValue() const noexcept (strong < checkStrongMaxValue && weak < checkWeakMaxValue), "xrpl::IntrusiveRefCounts::RefCountPair::combinedValue : inputs " "inside range"); - return (static_cast(weak) << IntrusiveRefCounts::StrongCountNumBits) | - static_cast(strong) | partialDestroyStartedBit | partialDestroyFinishedBit; + return (static_cast(weak) + << IntrusiveRefCounts::StrongCountNumBits) | + static_cast(strong) | partialDestroyStartedBit | + partialDestroyFinishedBit; } template @@ -442,7 +448,8 @@ inline void partialDestructorFinished(T** o) { T& self = **o; - IntrusiveRefCounts::RefCountPair p = self.refCounts.fetch_or(IntrusiveRefCounts::partialDestroyFinishedMask); + IntrusiveRefCounts::RefCountPair p = + self.refCounts.fetch_or(IntrusiveRefCounts::partialDestroyFinishedMask); XRPL_ASSERT( (!p.partialDestroyFinishedBit && p.partialDestroyStartedBit && !p.strong), "xrpl::partialDestructorFinished : not a weak ref"); diff --git a/include/xrpl/basics/LocalValue.h b/include/xrpl/basics/LocalValue.h index 94af41a41d..4ac76b130d 100644 --- a/include/xrpl/basics/LocalValue.h +++ b/include/xrpl/basics/LocalValue.h @@ -103,6 +103,7 @@ LocalValue::operator*() } return *reinterpret_cast( - lvs->values.emplace(this, std::make_unique>(t_)).first->second->get()); + lvs->values.emplace(this, std::make_unique>(t_)) + .first->second->get()); } } // namespace xrpl diff --git a/include/xrpl/basics/Log.h b/include/xrpl/basics/Log.h index 786fbc5da2..08da3e57b5 100644 --- a/include/xrpl/basics/Log.h +++ b/include/xrpl/basics/Log.h @@ -170,7 +170,11 @@ public: partition_severities() const; void - write(beast::severities::Severity level, std::string const& partition, std::string const& text, bool console); + write( + beast::severities::Severity level, + std::string const& partition, + std::string const& text, + bool console); std::string rotate(); diff --git a/include/xrpl/basics/Number.h b/include/xrpl/basics/Number.h index c269d27781..e3da029c03 100644 --- a/include/xrpl/basics/Number.h +++ b/include/xrpl/basics/Number.h @@ -240,7 +240,11 @@ public: Number(rep mantissa); explicit Number(rep mantissa, int exponent); - explicit constexpr Number(bool negative, internalrep mantissa, int exponent, unchecked) noexcept; + explicit constexpr Number( + bool negative, + internalrep mantissa, + int exponent, + unchecked) noexcept; // Assume unsigned values are... unsigned. i.e. positive explicit constexpr Number(internalrep mantissa, int exponent, unchecked) noexcept; // Only unit tests are expected to use this ctor @@ -294,7 +298,8 @@ public: friend constexpr bool operator==(Number const& x, Number const& y) noexcept { - return x.negative_ == y.negative_ && x.mantissa_ == y.mantissa_ && x.exponent_ == y.exponent_; + return x.negative_ == y.negative_ && x.mantissa_ == y.mantissa_ && + x.exponent_ == y.exponent_; } friend constexpr bool @@ -502,7 +507,11 @@ private: class Guard; }; -inline constexpr Number::Number(bool negative, internalrep mantissa, int exponent, unchecked) noexcept +inline constexpr Number::Number( + bool negative, + internalrep mantissa, + int exponent, + unchecked) noexcept : negative_(negative), mantissa_{mantissa}, exponent_{exponent} { } @@ -520,7 +529,8 @@ inline Number::Number(bool negative, internalrep mantissa, int exponent, normali normalize(); } -inline Number::Number(internalrep mantissa, int exponent, normalized) : Number(false, mantissa, exponent, normalized{}) +inline Number::Number(internalrep mantissa, int exponent, normalized) + : Number(false, mantissa, exponent, normalized{}) { } @@ -682,8 +692,8 @@ Number::isnormal() const noexcept MantissaRange const& range = range_; auto const abs_m = mantissa_; return *this == Number{} || - (range.min <= abs_m && abs_m <= range.max && (abs_m <= maxRep || abs_m % 10 == 0) && minExponent <= exponent_ && - exponent_ <= maxExponent); + (range.min <= abs_m && abs_m <= range.max && (abs_m <= maxRep || abs_m % 10 == 0) && + minExponent <= exponent_ && exponent_ <= maxExponent); } template @@ -695,7 +705,10 @@ Number::normalizeToRange(T minMantissa, T maxMantissa) const int exponent = exponent_; if constexpr (std::is_unsigned_v) - XRPL_ASSERT_PARTS(!negative, "xrpl::Number::normalizeToRange", "Number is non-negative for unsigned range."); + XRPL_ASSERT_PARTS( + !negative, + "xrpl::Number::normalizeToRange", + "Number is non-negative for unsigned range."); Number::normalize(negative, mantissa, exponent, minMantissa, maxMantissa); auto const sign = negative ? -1 : 1; @@ -781,7 +794,8 @@ class NumberRoundModeGuard saveNumberRoundMode saved_; public: - explicit NumberRoundModeGuard(Number::rounding_mode mode) noexcept : saved_{Number::setround(mode)} + explicit NumberRoundModeGuard(Number::rounding_mode mode) noexcept + : saved_{Number::setround(mode)} { } @@ -801,7 +815,8 @@ class NumberMantissaScaleGuard MantissaRange::mantissa_scale const saved_; public: - explicit NumberMantissaScaleGuard(MantissaRange::mantissa_scale scale) noexcept : saved_{Number::getMantissaScale()} + explicit NumberMantissaScaleGuard(MantissaRange::mantissa_scale scale) noexcept + : saved_{Number::getMantissaScale()} { Number::setMantissaScale(scale); } diff --git a/include/xrpl/basics/SharedWeakCachePointer.ipp b/include/xrpl/basics/SharedWeakCachePointer.ipp index 6e7514ffae..bb1e201ca8 100644 --- a/include/xrpl/basics/SharedWeakCachePointer.ipp +++ b/include/xrpl/basics/SharedWeakCachePointer.ipp @@ -19,7 +19,8 @@ SharedWeakCachePointer::SharedWeakCachePointer(SharedWeakCachePointer&& rhs) template template requires std::convertible_to -SharedWeakCachePointer::SharedWeakCachePointer(std::shared_ptr&& rhs) : combo_{std::move(rhs)} +SharedWeakCachePointer::SharedWeakCachePointer(std::shared_ptr&& rhs) + : combo_{std::move(rhs)} { } @@ -63,7 +64,8 @@ SharedWeakCachePointer::getStrong() const } template -SharedWeakCachePointer::operator bool() const noexcept +SharedWeakCachePointer:: +operator bool() const noexcept { return !!std::get_if>(&combo_); } diff --git a/include/xrpl/basics/SlabAllocator.h b/include/xrpl/basics/SlabAllocator.h index 2578afdc5a..d7ca3a87f1 100644 --- a/include/xrpl/basics/SlabAllocator.h +++ b/include/xrpl/basics/SlabAllocator.h @@ -155,13 +155,17 @@ public: contexts (e.g. when minimal memory usage is needed) and allows for graceful failure. */ - constexpr explicit SlabAllocator(std::size_t extra, std::size_t alloc = 0, std::size_t align = 0) + constexpr explicit SlabAllocator( + std::size_t extra, + std::size_t alloc = 0, + std::size_t align = 0) : itemAlignment_(align ? align : alignof(Type)) , itemSize_(boost::alignment::align_up(sizeof(Type) + extra, itemAlignment_)) , slabSize_(alloc) { XRPL_ASSERT( - (itemAlignment_ & (itemAlignment_ - 1)) == 0, "xrpl::SlabAllocator::SlabAllocator : valid alignment"); + (itemAlignment_ & (itemAlignment_ - 1)) == 0, + "xrpl::SlabAllocator::SlabAllocator : valid alignment"); } SlabAllocator(SlabAllocator const& other) = delete; @@ -215,7 +219,7 @@ public: // clang-format off if (!buf) [[unlikely]] return nullptr; - // clang-format on + // clang-format on #if BOOST_OS_LINUX // When allocating large blocks, attempt to leverage Linux's @@ -228,7 +232,8 @@ public: // We need to carve out a bit of memory for the slab header // and then align the rest appropriately: - auto slabData = reinterpret_cast(reinterpret_cast(buf) + sizeof(SlabBlock)); + auto slabData = + reinterpret_cast(reinterpret_cast(buf) + sizeof(SlabBlock)); auto slabSize = size - sizeof(SlabBlock); // This operation is essentially guaranteed not to fail but @@ -239,10 +244,12 @@ public: return nullptr; } - slab = new (buf) SlabBlock(slabs_.load(), reinterpret_cast(slabData), slabSize, itemSize_); + slab = new (buf) SlabBlock( + slabs_.load(), reinterpret_cast(slabData), slabSize, itemSize_); // Link the new slab - while (!slabs_.compare_exchange_weak(slab->next_, slab, std::memory_order_release, std::memory_order_relaxed)) + while (!slabs_.compare_exchange_weak( + slab->next_, slab, std::memory_order_release, std::memory_order_relaxed)) { ; // Nothing to do } @@ -299,7 +306,10 @@ public: std::size_t align; public: - constexpr SlabConfig(std::size_t extra_, std::size_t alloc_ = 0, std::size_t align_ = alignof(Type)) + constexpr SlabConfig( + std::size_t extra_, + std::size_t alloc_ = 0, + std::size_t align_ = alignof(Type)) : extra(extra_), alloc(alloc_), align(align_) { } @@ -309,15 +319,18 @@ public: { // Ensure that the specified allocators are sorted from smallest to // largest by size: - std::sort( - std::begin(cfg), std::end(cfg), [](SlabConfig const& a, SlabConfig const& b) { return a.extra < b.extra; }); + std::sort(std::begin(cfg), std::end(cfg), [](SlabConfig const& a, SlabConfig const& b) { + return a.extra < b.extra; + }); // We should never have two slabs of the same size - if (std::adjacent_find(std::begin(cfg), std::end(cfg), [](SlabConfig const& a, SlabConfig const& b) { - return a.extra == b.extra; - }) != cfg.end()) + if (std::adjacent_find( + std::begin(cfg), std::end(cfg), [](SlabConfig const& a, SlabConfig const& b) { + return a.extra == b.extra; + }) != cfg.end()) { - throw std::runtime_error("SlabAllocatorSet<" + beast::type_name() + ">: duplicate slab size"); + throw std::runtime_error( + "SlabAllocatorSet<" + beast::type_name() + ">: duplicate slab size"); } for (auto const& c : cfg) diff --git a/include/xrpl/basics/Slice.h b/include/xrpl/basics/Slice.h index 2f6081760f..6aa5446236 100644 --- a/include/xrpl/basics/Slice.h +++ b/include/xrpl/basics/Slice.h @@ -40,7 +40,8 @@ public: operator=(Slice const&) noexcept = default; /** Create a slice pointing to existing memory. */ - Slice(void const* data, std::size_t size) noexcept : data_(reinterpret_cast(data)), size_(size) + Slice(void const* data, std::size_t size) noexcept + : data_(reinterpret_cast(data)), size_(size) { } @@ -197,7 +198,8 @@ operator!=(Slice const& lhs, Slice const& rhs) noexcept inline bool operator<(Slice const& lhs, Slice const& rhs) noexcept { - return std::lexicographical_compare(lhs.data(), lhs.data() + lhs.size(), rhs.data(), rhs.data() + rhs.size()); + return std::lexicographical_compare( + lhs.data(), lhs.data() + lhs.size(), rhs.data(), rhs.data() + rhs.size()); } template diff --git a/include/xrpl/basics/StringUtilities.h b/include/xrpl/basics/StringUtilities.h index 9b1cf4892d..9cf6cd315d 100644 --- a/include/xrpl/basics/StringUtilities.h +++ b/include/xrpl/basics/StringUtilities.h @@ -108,7 +108,8 @@ struct parsedURL bool operator==(parsedURL const& other) const { - return scheme == other.scheme && domain == other.domain && port == other.port && path == other.path; + return scheme == other.scheme && domain == other.domain && port == other.port && + path == other.path; } }; diff --git a/include/xrpl/basics/TaggedCache.h b/include/xrpl/basics/TaggedCache.h index 78c4ea7aeb..6cbe8680c9 100644 --- a/include/xrpl/basics/TaggedCache.h +++ b/include/xrpl/basics/TaggedCache.h @@ -175,7 +175,10 @@ private: struct Stats { template - Stats(std::string const& prefix, Handler const& handler, beast::insight::Collector::ptr const& collector) + Stats( + std::string const& prefix, + Handler const& handler, + beast::insight::Collector::ptr const& collector) : hook(collector->make_hook(handler)) , size(collector->make_gauge(prefix, "size")) , hit_rate(collector->make_gauge(prefix, "hit_rate")) @@ -197,7 +200,8 @@ private: public: clock_type::time_point last_access; - explicit KeyOnlyEntry(clock_type::time_point const& last_access_) : last_access(last_access_) + explicit KeyOnlyEntry(clock_type::time_point const& last_access_) + : last_access(last_access_) { } diff --git a/include/xrpl/basics/TaggedCache.ipp b/include/xrpl/basics/TaggedCache.ipp index 3d0c0342cc..8c0fde5e7d 100644 --- a/include/xrpl/basics/TaggedCache.ipp +++ b/include/xrpl/basics/TaggedCache.ipp @@ -14,13 +14,22 @@ template < class Hash, class KeyEqual, class Mutex> -inline TaggedCache::TaggedCache( - std::string const& name, - int size, - clock_type::duration expiration, - clock_type& clock, - beast::Journal journal, - beast::insight::Collector::ptr const& collector) +inline TaggedCache< + Key, + T, + IsKeyCache, + SharedWeakUnionPointer, + SharedPointerType, + Hash, + KeyEqual, + Mutex>:: + TaggedCache( + std::string const& name, + int size, + clock_type::duration expiration, + clock_type& clock, + beast::Journal journal, + beast::insight::Collector::ptr const& collector) : m_journal(journal) , m_clock(clock) , m_stats(name, std::bind(&TaggedCache::collect_metrics, this), collector) @@ -43,8 +52,8 @@ template < class KeyEqual, class Mutex> inline auto -TaggedCache::clock() - -> clock_type& +TaggedCache:: + clock() -> clock_type& { return m_clock; } @@ -59,7 +68,8 @@ template < class KeyEqual, class Mutex> inline std::size_t -TaggedCache::size() const +TaggedCache:: + size() const { std::lock_guard lock(m_mutex); return m_cache.size(); @@ -75,7 +85,8 @@ template < class KeyEqual, class Mutex> inline int -TaggedCache::getCacheSize() const +TaggedCache:: + getCacheSize() const { std::lock_guard lock(m_mutex); return m_cache_count; @@ -91,7 +102,8 @@ template < class KeyEqual, class Mutex> inline int -TaggedCache::getTrackSize() const +TaggedCache:: + getTrackSize() const { std::lock_guard lock(m_mutex); return m_cache.size(); @@ -107,7 +119,8 @@ template < class KeyEqual, class Mutex> inline float -TaggedCache::getHitRate() +TaggedCache:: + getHitRate() { std::lock_guard lock(m_mutex); auto const total = static_cast(m_hits + m_misses); @@ -124,7 +137,8 @@ template < class KeyEqual, class Mutex> inline void -TaggedCache::clear() +TaggedCache:: + clear() { std::lock_guard lock(m_mutex); m_cache.clear(); @@ -141,7 +155,8 @@ template < class KeyEqual, class Mutex> inline void -TaggedCache::reset() +TaggedCache:: + reset() { std::lock_guard lock(m_mutex); m_cache.clear(); @@ -161,8 +176,8 @@ template < class Mutex> template inline bool -TaggedCache::touch_if_exists( - KeyComparable const& key) +TaggedCache:: + touch_if_exists(KeyComparable const& key) { std::lock_guard lock(m_mutex); auto const iter(m_cache.find(key)); @@ -186,7 +201,8 @@ template < class KeyEqual, class Mutex> inline void -TaggedCache::sweep() +TaggedCache:: + sweep() { // Keep references to all the stuff we sweep // For performance, each worker thread should exit before the swept data @@ -212,8 +228,9 @@ TaggedCache (now - minimumAge)) when_expire = now - minimumAge; - JLOG(m_journal.trace()) << m_name << " is growing fast " << m_cache.size() << " of " << m_target_size - << " aging at " << (now - when_expire).count() << " of " << m_target_age.count(); + JLOG(m_journal.trace()) + << m_name << " is growing fast " << m_cache.size() << " of " << m_target_size + << " aging at " << (now - when_expire).count() << " of " << m_target_age.count(); } std::vector workers; @@ -222,7 +239,8 @@ TaggedCache(std::chrono::steady_clock::now() - start).count() - << "ms"; + JLOG(m_journal.debug()) << m_name << " TaggedCache sweep lock duration " + << std::chrono::duration_cast( + std::chrono::steady_clock::now() - start) + .count() + << "ms"; } template < @@ -247,9 +266,8 @@ template < class KeyEqual, class Mutex> inline bool -TaggedCache::del( - key_type const& key, - bool valid) +TaggedCache:: + del(key_type const& key, bool valid) { // Remove from cache, if !valid, remove from map too. Returns true if // removed from cache @@ -288,10 +306,8 @@ template < class Mutex> template inline bool -TaggedCache::canonicalize( - key_type const& key, - SharedPointerType& data, - R&& replaceCallback) +TaggedCache:: + canonicalize(key_type const& key, SharedPointerType& data, R&& replaceCallback) { // Return canonical value, store if needed, refresh in cache // Return values: true=we had the data already @@ -302,7 +318,9 @@ TaggedCache inline SharedPointerType -TaggedCache::fetch( - key_type const& key) +TaggedCache:: + fetch(key_type const& key) { std::lock_guard l(m_mutex); auto ret = initialFetch(key, l); @@ -425,9 +443,8 @@ template < class Mutex> template inline auto -TaggedCache::insert( - key_type const& key, - T const& value) -> std::enable_if_t +TaggedCache:: + insert(key_type const& key, T const& value) -> std::enable_if_t { static_assert( std::is_same_v, SharedPointerType> || @@ -456,13 +473,13 @@ template < class Mutex> template inline auto -TaggedCache::insert( - key_type const& key) -> std::enable_if_t +TaggedCache:: + insert(key_type const& key) -> std::enable_if_t { std::lock_guard lock(m_mutex); clock_type::time_point const now(m_clock.now()); - auto [it, inserted] = - m_cache.emplace(std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(now)); + auto [it, inserted] = m_cache.emplace( + std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(now)); if (!inserted) it->second.last_access = now; return inserted; @@ -478,9 +495,8 @@ template < class KeyEqual, class Mutex> inline bool -TaggedCache::retrieve( - key_type const& key, - T& data) +TaggedCache:: + retrieve(key_type const& key, T& data) { // retrieve the value of the stored data auto entry = fetch(key); @@ -502,8 +518,8 @@ template < class KeyEqual, class Mutex> inline auto -TaggedCache::peekMutex() - -> mutex_type& +TaggedCache:: + peekMutex() -> mutex_type& { return m_mutex; } @@ -518,8 +534,8 @@ template < class KeyEqual, class Mutex> inline auto -TaggedCache::getKeys() const - -> std::vector +TaggedCache:: + getKeys() const -> std::vector { std::vector v; @@ -543,7 +559,8 @@ template < class KeyEqual, class Mutex> inline double -TaggedCache::rate() const +TaggedCache:: + rate() const { std::lock_guard lock(m_mutex); auto const tot = m_hits + m_misses; @@ -563,9 +580,8 @@ template < class Mutex> template inline SharedPointerType -TaggedCache::fetch( - key_type const& digest, - Handler const& h) +TaggedCache:: + fetch(key_type const& digest, Handler const& h) { { std::lock_guard l(m_mutex); @@ -596,9 +612,8 @@ template < class KeyEqual, class Mutex> inline SharedPointerType -TaggedCache::initialFetch( - key_type const& key, - std::lock_guard const& l) +TaggedCache:: + initialFetch(key_type const& key, std::lock_guard const& l) { auto cit = m_cache.find(key); if (cit == m_cache.end()) @@ -634,7 +649,8 @@ template < class KeyEqual, class Mutex> inline void -TaggedCache::collect_metrics() +TaggedCache:: + collect_metrics() { m_stats.size.set(getCacheSize()); @@ -660,13 +676,14 @@ template < class KeyEqual, class Mutex> inline std::thread -TaggedCache::sweepHelper( - clock_type::time_point const& when_expire, - [[maybe_unused]] clock_type::time_point const& now, - typename KeyValueCacheType::map_type& partition, - SweptPointersVector& stuffToSweep, - std::atomic& allRemovals, - std::lock_guard const&) +TaggedCache:: + sweepHelper( + clock_type::time_point const& when_expire, + [[maybe_unused]] clock_type::time_point const& now, + typename KeyValueCacheType::map_type& partition, + SweptPointersVector& stuffToSweep, + std::atomic& allRemovals, + std::lock_guard const&) { return std::thread([&, this]() { int cacheRemovals = 0; @@ -720,8 +737,9 @@ TaggedCache::value, + "Exception must derive from std::exception."); E e(std::forward(args)...); LogThrow(std::string("Throwing exception of type " + beast::type_name() + ": ") + e.what()); diff --git a/include/xrpl/basics/join.h b/include/xrpl/basics/join.h index 16fae4ff87..0fb00aaf82 100644 --- a/include/xrpl/basics/join.h +++ b/include/xrpl/basics/join.h @@ -23,7 +23,8 @@ public: Collection const& collection; std::string const delimiter; - explicit CollectionAndDelimiter(Collection const& c, std::string delim) : collection(c), delimiter(std::move(delim)) + explicit CollectionAndDelimiter(Collection const& c, std::string delim) + : collection(c), delimiter(std::move(delim)) { } @@ -63,7 +64,8 @@ public: char const* collection; std::string const delimiter; - explicit CollectionAndDelimiter(char const c[N], std::string delim) : collection(c), delimiter(std::move(delim)) + explicit CollectionAndDelimiter(char const c[N], std::string delim) + : collection(c), delimiter(std::move(delim)) { } diff --git a/include/xrpl/basics/partitioned_unordered_map.h b/include/xrpl/basics/partitioned_unordered_map.h index 181597ca69..f9e55d71a6 100644 --- a/include/xrpl/basics/partitioned_unordered_map.h +++ b/include/xrpl/basics/partitioned_unordered_map.h @@ -330,8 +330,8 @@ public: auto const& key = std::get<0>(keyTuple); iterator it(&map_); it.ait_ = it.map_->begin() + partitioner(key); - auto [eit, inserted] = - it.ait_->emplace(std::piecewise_construct, std::forward(keyTuple), std::forward(valueTuple)); + auto [eit, inserted] = it.ait_->emplace( + std::piecewise_construct, std::forward(keyTuple), std::forward(valueTuple)); it.mit_ = eit; return {it, inserted}; } diff --git a/include/xrpl/basics/random.h b/include/xrpl/basics/random.h index 34e460fd8a..399439c023 100644 --- a/include/xrpl/basics/random.h +++ b/include/xrpl/basics/random.h @@ -19,7 +19,8 @@ static_assert( "The Ripple default PRNG engine must return an unsigned integral type."); static_assert( - std::numeric_limits::max() >= std::numeric_limits::max(), + std::numeric_limits::max() >= + std::numeric_limits::max(), "The Ripple default PRNG engine return must be at least 64 bits wide."); #endif @@ -144,12 +145,14 @@ std::enable_if_t< Byte> rand_byte(Engine& engine) { - return static_cast( - rand_int(engine, std::numeric_limits::min(), std::numeric_limits::max())); + return static_cast(rand_int( + engine, std::numeric_limits::min(), std::numeric_limits::max())); } template -std::enable_if_t<(std::is_same::value || std::is_same::value), Byte> +std::enable_if_t< + (std::is_same::value || std::is_same::value), + Byte> rand_byte() { return rand_byte(default_prng()); diff --git a/include/xrpl/basics/safe_cast.h b/include/xrpl/basics/safe_cast.h index 285d76782a..8f5826f2a8 100644 --- a/include/xrpl/basics/safe_cast.h +++ b/include/xrpl/basics/safe_cast.h @@ -18,9 +18,12 @@ template inline constexpr std::enable_if_t && std::is_integral_v, Dest> safe_cast(Src s) noexcept { - static_assert(std::is_signed_v || std::is_unsigned_v, "Cannot cast signed to unsigned"); + static_assert( + std::is_signed_v || std::is_unsigned_v, "Cannot cast signed to unsigned"); constexpr unsigned not_same = std::is_signed_v != std::is_signed_v; - static_assert(sizeof(Dest) >= sizeof(Src) + not_same, "Destination is too small to hold all values of source"); + static_assert( + sizeof(Dest) >= sizeof(Src) + not_same, + "Destination is too small to hold all values of source"); return static_cast(s); } diff --git a/include/xrpl/basics/scope.h b/include/xrpl/basics/scope.h index 797a7d3fdc..1d5524ba35 100644 --- a/include/xrpl/basics/scope.h +++ b/include/xrpl/basics/scope.h @@ -36,7 +36,8 @@ public: scope_exit(scope_exit&& 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_} + : exit_function_{std::forward(rhs.exit_function_)} + , execute_on_destruction_{rhs.execute_on_destruction_} { rhs.release(); } @@ -47,8 +48,9 @@ public: template explicit scope_exit( EFP&& f, - std::enable_if_t, scope_exit> && std::is_constructible_v>* = - 0) noexcept + std::enable_if_t< + !std::is_same_v, scope_exit> && + std::is_constructible_v>* = 0) noexcept : exit_function_{std::forward(f)} { static_assert(std::is_nothrow_constructible_v(f))>); @@ -93,8 +95,9 @@ public: template explicit scope_fail( EFP&& f, - std::enable_if_t, scope_fail> && std::is_constructible_v>* = - 0) noexcept + std::enable_if_t< + !std::is_same_v, scope_fail> && + std::is_constructible_v>* = 0) noexcept : exit_function_{std::forward(f)} { static_assert(std::is_nothrow_constructible_v(f))>); @@ -139,7 +142,9 @@ public: template explicit scope_success( EFP&& f, - std::enable_if_t, scope_success> && std::is_constructible_v>* = + std::enable_if_t< + !std::is_same_v, scope_success> && + std::is_constructible_v>* = 0) noexcept(std::is_nothrow_constructible_v || std::is_nothrow_constructible_v) : exit_function_{std::forward(f)} { diff --git a/include/xrpl/basics/spinlock.h b/include/xrpl/basics/spinlock.h index 7b05b7c339..eb60e85962 100644 --- a/include/xrpl/basics/spinlock.h +++ b/include/xrpl/basics/spinlock.h @@ -99,9 +99,12 @@ public: @note For performance reasons, you should strive to have `lock` be on a cacheline by itself. */ - packed_spinlock(std::atomic& lock, int index) : bits_(lock), mask_(static_cast(1) << index) + packed_spinlock(std::atomic& lock, int index) + : bits_(lock), mask_(static_cast(1) << index) { - XRPL_ASSERT(index >= 0 && (mask_ != 0), "xrpl::packed_spinlock::packed_spinlock : valid index and mask"); + XRPL_ASSERT( + index >= 0 && (mask_ != 0), + "xrpl::packed_spinlock::packed_spinlock : valid index and mask"); } [[nodiscard]] bool @@ -174,7 +177,10 @@ public: T expected = 0; return lock_.compare_exchange_weak( - expected, std::numeric_limits::max(), std::memory_order_acquire, std::memory_order_relaxed); + expected, + std::numeric_limits::max(), + std::memory_order_acquire, + std::memory_order_relaxed); } void diff --git a/include/xrpl/basics/strHex.h b/include/xrpl/basics/strHex.h index 76a3d86ff3..cc07bf5b9d 100644 --- a/include/xrpl/basics/strHex.h +++ b/include/xrpl/basics/strHex.h @@ -10,7 +10,9 @@ std::string strHex(FwdIt begin, FwdIt end) { static_assert( - std::is_convertible::iterator_category, std::forward_iterator_tag>::value, + std::is_convertible< + typename std::iterator_traits::iterator_category, + std::forward_iterator_tag>::value, "FwdIt must be a forward iterator"); std::string result; result.reserve(2 * std::distance(begin, end)); diff --git a/include/xrpl/basics/tagged_integer.h b/include/xrpl/basics/tagged_integer.h index 439cc537e2..18d6a707a0 100644 --- a/include/xrpl/basics/tagged_integer.h +++ b/include/xrpl/basics/tagged_integer.h @@ -23,14 +23,15 @@ namespace xrpl { allowed arithmetic operations. */ template -class tagged_integer - : boost::totally_ordered< - tagged_integer, - boost::integer_arithmetic< - tagged_integer, - boost::bitwise< - tagged_integer, - boost::unit_steppable, boost::shiftable>>>>> +class tagged_integer : boost::totally_ordered< + tagged_integer, + boost::integer_arithmetic< + tagged_integer, + boost::bitwise< + tagged_integer, + boost::unit_steppable< + tagged_integer, + boost::shiftable>>>>> { private: Int m_value; @@ -43,7 +44,8 @@ public: template < class OtherInt, - class = typename std::enable_if::value && sizeof(OtherInt) <= sizeof(Int)>::type> + class = typename std::enable_if< + std::is_integral::value && sizeof(OtherInt) <= sizeof(Int)>::type> explicit constexpr tagged_integer(OtherInt value) noexcept : m_value(value) { static_assert(sizeof(tagged_integer) == sizeof(Int), "tagged_integer is adding padding"); diff --git a/include/xrpl/beast/asio/io_latency_probe.h b/include/xrpl/beast/asio/io_latency_probe.h index 347203acb3..81c8bc0dfa 100644 --- a/include/xrpl/beast/asio/io_latency_probe.h +++ b/include/xrpl/beast/asio/io_latency_probe.h @@ -86,7 +86,8 @@ public: std::lock_guard lock(m_mutex); if (m_cancel) throw std::logic_error("io_latency_probe is canceled"); - boost::asio::post(m_ios, sample_op(std::forward(handler), Clock::now(), false, this)); + boost::asio::post( + m_ios, sample_op(std::forward(handler), Clock::now(), false, this)); } /** Initiate continuous i/o latency sampling. @@ -100,7 +101,8 @@ public: std::lock_guard lock(m_mutex); if (m_cancel) throw std::logic_error("io_latency_probe is canceled"); - boost::asio::post(m_ios, sample_op(std::forward(handler), Clock::now(), true, this)); + boost::asio::post( + m_ios, sample_op(std::forward(handler), Clock::now(), true, this)); } private: @@ -140,7 +142,11 @@ private: bool m_repeat; io_latency_probe* m_probe; - sample_op(Handler const& handler, time_point const& start, bool repeat, io_latency_probe* probe) + sample_op( + Handler const& handler, + time_point const& start, + bool repeat, + io_latency_probe* probe) : m_handler(handler), m_start(start), m_repeat(repeat), m_probe(probe) { XRPL_ASSERT( @@ -203,12 +209,14 @@ private: // The latency is too high to maintain the desired // period so don't bother with a timer. // - boost::asio::post(m_probe->m_ios, sample_op(m_handler, now, m_repeat, m_probe)); + boost::asio::post( + m_probe->m_ios, sample_op(m_handler, now, m_repeat, m_probe)); } else { m_probe->m_timer.expires_after(when - now); - m_probe->m_timer.async_wait(sample_op(m_handler, now, m_repeat, m_probe)); + m_probe->m_timer.async_wait( + sample_op(m_handler, now, m_repeat, m_probe)); } } } @@ -219,7 +227,8 @@ private: if (!m_probe) return; typename Clock::time_point const now(Clock::now()); - boost::asio::post(m_probe->m_ios, sample_op(m_handler, now, m_repeat, m_probe)); + boost::asio::post( + m_probe->m_ios, sample_op(m_handler, now, m_repeat, m_probe)); } }; }; diff --git a/include/xrpl/beast/clock/manual_clock.h b/include/xrpl/beast/clock/manual_clock.h index a301b4e1fe..b959a95b90 100644 --- a/include/xrpl/beast/clock/manual_clock.h +++ b/include/xrpl/beast/clock/manual_clock.h @@ -42,7 +42,9 @@ public: void set(time_point const& when) { - XRPL_ASSERT(!Clock::is_steady || when >= now_, "beast::manual_clock::set(time_point) : forward input"); + XRPL_ASSERT( + !Clock::is_steady || when >= now_, + "beast::manual_clock::set(time_point) : forward input"); now_ = when; } @@ -60,7 +62,8 @@ public: advance(std::chrono::duration const& elapsed) { XRPL_ASSERT( - !Clock::is_steady || (now_ + elapsed) >= now_, "beast::manual_clock::advance(duration) : forward input"); + !Clock::is_steady || (now_ + elapsed) >= now_, + "beast::manual_clock::advance(duration) : forward input"); now_ += elapsed; } diff --git a/include/xrpl/beast/container/aged_container_utility.h b/include/xrpl/beast/container/aged_container_utility.h index fd5d481aa5..cf6bae9990 100644 --- a/include/xrpl/beast/container/aged_container_utility.h +++ b/include/xrpl/beast/container/aged_container_utility.h @@ -14,7 +14,8 @@ expire(AgedContainer& c, std::chrono::duration const& age) { std::size_t n(0); auto const expired(c.clock().now() - age); - for (auto iter(c.chronological.cbegin()); iter != c.chronological.cend() && iter.when() <= expired;) + for (auto iter(c.chronological.cbegin()); + iter != c.chronological.cend() && iter.when() <= expired;) { iter = c.erase(iter); ++n; diff --git a/include/xrpl/beast/container/aged_multiset.h b/include/xrpl/beast/container/aged_multiset.h index 2ad09344e5..8d906c694f 100644 --- a/include/xrpl/beast/container/aged_multiset.h +++ b/include/xrpl/beast/container/aged_multiset.h @@ -13,6 +13,6 @@ template < class Clock = std::chrono::steady_clock, class Compare = std::less, class Allocator = std::allocator> -using aged_multiset = detail::aged_ordered_container; - +using aged_multiset = + detail::aged_ordered_container; } diff --git a/include/xrpl/beast/container/aged_unordered_map.h b/include/xrpl/beast/container/aged_unordered_map.h index 116d5669a1..520ffe5848 100644 --- a/include/xrpl/beast/container/aged_unordered_map.h +++ b/include/xrpl/beast/container/aged_unordered_map.h @@ -15,6 +15,6 @@ template < class Hash = std::hash, class KeyEqual = std::equal_to, class Allocator = std::allocator>> -using aged_unordered_map = detail::aged_unordered_container; - +using aged_unordered_map = + detail::aged_unordered_container; } diff --git a/include/xrpl/beast/container/aged_unordered_multimap.h b/include/xrpl/beast/container/aged_unordered_multimap.h index 4c3333a099..dc6338949b 100644 --- a/include/xrpl/beast/container/aged_unordered_multimap.h +++ b/include/xrpl/beast/container/aged_unordered_multimap.h @@ -15,6 +15,6 @@ template < class Hash = std::hash, class KeyEqual = std::equal_to, class Allocator = std::allocator>> -using aged_unordered_multimap = detail::aged_unordered_container; - +using aged_unordered_multimap = + detail::aged_unordered_container; } diff --git a/include/xrpl/beast/container/aged_unordered_set.h b/include/xrpl/beast/container/aged_unordered_set.h index a8ee61f1f5..a1c032e159 100644 --- a/include/xrpl/beast/container/aged_unordered_set.h +++ b/include/xrpl/beast/container/aged_unordered_set.h @@ -14,6 +14,6 @@ template < class Hash = std::hash, class KeyEqual = std::equal_to, class Allocator = std::allocator> -using aged_unordered_set = detail::aged_unordered_container; - +using aged_unordered_set = + detail::aged_unordered_container; } diff --git a/include/xrpl/beast/container/detail/aged_container_iterator.h b/include/xrpl/beast/container/detail/aged_container_iterator.h index 12cd15f677..99aab2a9a9 100644 --- a/include/xrpl/beast/container/detail/aged_container_iterator.h +++ b/include/xrpl/beast/container/detail/aged_container_iterator.h @@ -35,22 +35,26 @@ public: class = typename std::enable_if< (other_is_const == false || is_const == true) && std::is_same::value == false>::type> - explicit aged_container_iterator(aged_container_iterator const& other) + explicit aged_container_iterator( + aged_container_iterator const& other) : m_iter(other.m_iter) { } // Disable constructing a const_iterator from a non-const_iterator. - template ::type> - aged_container_iterator(aged_container_iterator const& other) : m_iter(other.m_iter) + template < + bool other_is_const, + class = typename std::enable_if::type> + aged_container_iterator(aged_container_iterator const& other) + : m_iter(other.m_iter) { } // Disable assigning a const_iterator to a non-const iterator template auto - operator=(aged_container_iterator const& other) -> - typename std::enable_if::type + operator=(aged_container_iterator const& other) -> typename std:: + enable_if::type { m_iter = other.m_iter; return *this; diff --git a/include/xrpl/beast/container/detail/aged_ordered_container.h b/include/xrpl/beast/container/detail/aged_ordered_container.h index 2f3d8973e9..b482cd33c1 100644 --- a/include/xrpl/beast/container/detail/aged_ordered_container.h +++ b/include/xrpl/beast/container/detail/aged_ordered_container.h @@ -57,7 +57,8 @@ template < class T, class Clock = std::chrono::steady_clock, class Compare = std::less, - class Allocator = std::allocator, Key>::type>> + class Allocator = + std::allocator, Key>::type>> class aged_ordered_container { public: @@ -83,8 +84,10 @@ private: } // VFALCO TODO hoist to remove template argument dependencies - struct element : boost::intrusive::set_base_hook>, - boost::intrusive::list_base_hook> + struct element : boost::intrusive::set_base_hook< + boost::intrusive::link_mode>, + boost::intrusive::list_base_hook< + boost::intrusive::link_mode> { // Stash types here so the iterator doesn't // need to see the container declaration. @@ -100,14 +103,17 @@ private: { } - element(time_point const& when_, value_type&& value_) : value(std::move(value_)), when(when_) + element(time_point const& when_, value_type&& value_) + : value(std::move(value_)), when(when_) { } template < class... Args, - class = typename std::enable_if::value>::type> - element(time_point const& when_, Args&&... args) : value(std::forward(args)...), when(when_) + class = + typename std::enable_if::value>::type> + element(time_point const& when_, Args&&... args) + : value(std::forward(args)...), when(when_) { } @@ -191,7 +197,8 @@ private: } }; - using list_type = typename boost::intrusive::make_list>::type; + using list_type = typename boost::intrusive:: + make_list>::type; using cont_type = typename std::conditional< IsMulti, @@ -199,15 +206,18 @@ private: element, boost::intrusive::constant_time_size, boost::intrusive::compare>::type, - typename boost::intrusive:: - make_set, boost::intrusive::compare>:: - type>::type; + typename boost::intrusive::make_set< + element, + boost::intrusive::constant_time_size, + boost::intrusive::compare>::type>::type; - using ElementAllocator = typename std::allocator_traits::template rebind_alloc; + using ElementAllocator = + typename std::allocator_traits::template rebind_alloc; using ElementAllocatorTraits = std::allocator_traits; - class config_t : private KeyValueCompare, public beast::detail::empty_base_optimization + class config_t : private KeyValueCompare, + public beast::detail::empty_base_optimization { public: explicit config_t(clock_type& clock_) : clock(clock_) @@ -224,7 +234,9 @@ private: } config_t(clock_type& clock_, Compare const& comp, Allocator const& alloc_) - : KeyValueCompare(comp), beast::detail::empty_base_optimization(alloc_), clock(clock_) + : KeyValueCompare(comp) + , beast::detail::empty_base_optimization(alloc_) + , clock(clock_) { } @@ -337,7 +349,8 @@ private: std::unique_ptr p( ElementAllocatorTraits::allocate(m_config.alloc(), 1), Deleter(m_config.alloc())); - ElementAllocatorTraits::construct(m_config.alloc(), p.get(), clock().now(), std::forward(args)...); + ElementAllocatorTraits::construct( + m_config.alloc(), p.get(), clock().now(), std::forward(args)...); return p.release(); } @@ -368,9 +381,12 @@ public: // A set iterator (IsMap==false) is always const // because the elements of a set are immutable. using iterator = beast::detail::aged_container_iterator; - using const_iterator = beast::detail::aged_container_iterator; - using reverse_iterator = beast::detail::aged_container_iterator; - using const_reverse_iterator = beast::detail::aged_container_iterator; + using const_iterator = + beast::detail::aged_container_iterator; + using reverse_iterator = + beast::detail::aged_container_iterator; + using const_reverse_iterator = + beast::detail::aged_container_iterator; //-------------------------------------------------------------------------- // @@ -386,9 +402,12 @@ public: public: // A set iterator (IsMap==false) is always const // because the elements of a set are immutable. - using iterator = beast::detail::aged_container_iterator; - using const_iterator = beast::detail::aged_container_iterator; - using reverse_iterator = beast::detail::aged_container_iterator; + using iterator = + beast::detail::aged_container_iterator; + using const_iterator = + beast::detail::aged_container_iterator; + using reverse_iterator = + beast::detail::aged_container_iterator; using const_reverse_iterator = beast::detail::aged_container_iterator; @@ -469,7 +488,8 @@ public: { static_assert(std::is_standard_layout::value, "must be standard layout"); return list.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - + ((std::size_t)std::addressof(((element*)0)->member)))); } const_iterator @@ -477,7 +497,8 @@ public: { static_assert(std::is_standard_layout::value, "must be standard layout"); return list.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - + ((std::size_t)std::addressof(((element*)0)->member)))); } private: @@ -518,7 +539,12 @@ public: aged_ordered_container(InputIt first, InputIt last, clock_type& clock, Allocator const& alloc); template - aged_ordered_container(InputIt first, InputIt last, clock_type& clock, Compare const& comp, Allocator const& alloc); + aged_ordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Compare const& comp, + Allocator const& alloc); aged_ordered_container(aged_ordered_container const& other); @@ -530,9 +556,15 @@ public: aged_ordered_container(std::initializer_list init, clock_type& clock); - aged_ordered_container(std::initializer_list init, clock_type& clock, Compare const& comp); + aged_ordered_container( + std::initializer_list init, + clock_type& clock, + Compare const& comp); - aged_ordered_container(std::initializer_list init, clock_type& clock, Allocator const& alloc); + aged_ordered_container( + std::initializer_list init, + clock_type& clock, + Allocator const& alloc); aged_ordered_container( std::initializer_list init, @@ -688,7 +720,8 @@ public: { static_assert(std::is_standard_layout::value, "must be standard layout"); return m_cont.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - + ((std::size_t)std::addressof(((element*)0)->member)))); } const_iterator @@ -696,7 +729,8 @@ public: { static_assert(std::is_standard_layout::value, "must be standard layout"); return m_cont.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - + ((std::size_t)std::addressof(((element*)0)->member)))); } //-------------------------------------------------------------------------- @@ -735,7 +769,8 @@ public: // map, set template auto - insert(value_type const& value) -> typename std::enable_if>::type; + insert(value_type const& value) -> + typename std::enable_if>::type; // multimap, multiset template @@ -745,19 +780,22 @@ public: // set template auto - insert(value_type&& value) -> typename std::enable_if>::type; + insert(value_type&& value) -> + typename std::enable_if>::type; // multiset template auto - insert(value_type&& value) -> typename std::enable_if::type; + insert(value_type&& value) -> + typename std::enable_if::type; //--- // map, set template auto - insert(const_iterator hint, value_type const& value) -> typename std::enable_if::type; + insert(const_iterator hint, value_type const& value) -> + typename std::enable_if::type; // multimap, multiset template @@ -771,7 +809,8 @@ public: // map, set template auto - insert(const_iterator hint, value_type&& value) -> typename std::enable_if::type; + insert(const_iterator hint, value_type&& value) -> + typename std::enable_if::type; // multimap, multiset template @@ -819,7 +858,8 @@ public: // map, set template auto - emplace(Args&&... args) -> typename std::enable_if>::type; + emplace(Args&&... args) -> + typename std::enable_if>::type; // multiset, multimap template @@ -842,13 +882,19 @@ public: } // enable_if prevents erase (reverse_iterator pos) from compiling - template ::value>> + template < + bool is_const, + class Iterator, + class = std::enable_if_t::value>> beast::detail::aged_container_iterator erase(beast::detail::aged_container_iterator pos); // enable_if prevents erase (reverse_iterator first, reverse_iterator last) // from compiling - template ::value>> + template < + bool is_const, + class Iterator, + class = std::enable_if_t::value>> beast::detail::aged_container_iterator erase( beast::detail::aged_container_iterator first, @@ -864,7 +910,10 @@ public: //-------------------------------------------------------------------------- // enable_if prevents touch (reverse_iterator pos) from compiling - template ::value>> + template < + bool is_const, + class Iterator, + class = std::enable_if_t::value>> void touch(beast::detail::aged_container_iterator pos) { @@ -984,69 +1033,136 @@ public: // is only done on the key portion of the value type, ignoring // the mapped type. // - template + template < + bool OtherIsMulti, + bool OtherIsMap, + class OtherT, + class OtherDuration, + class OtherAllocator> bool - operator==( - aged_ordered_container const& - other) const; + operator==(aged_ordered_container< + OtherIsMulti, + OtherIsMap, + Key, + OtherT, + OtherDuration, + Compare, + OtherAllocator> const& other) const; - template + template < + bool OtherIsMulti, + bool OtherIsMap, + class OtherT, + class OtherDuration, + class OtherAllocator> bool - operator!=( - aged_ordered_container const& - other) const + operator!=(aged_ordered_container< + OtherIsMulti, + OtherIsMap, + Key, + OtherT, + OtherDuration, + Compare, + OtherAllocator> const& other) const { return !(this->operator==(other)); } - template + template < + bool OtherIsMulti, + bool OtherIsMap, + class OtherT, + class OtherDuration, + class OtherAllocator> bool - operator<( - aged_ordered_container const& - other) const + operator<(aged_ordered_container< + OtherIsMulti, + OtherIsMap, + Key, + OtherT, + OtherDuration, + Compare, + OtherAllocator> const& other) const { value_compare const comp(value_comp()); return std::lexicographical_compare(cbegin(), cend(), other.cbegin(), other.cend(), comp); } - template + template < + bool OtherIsMulti, + bool OtherIsMap, + class OtherT, + class OtherDuration, + class OtherAllocator> bool - operator<=( - aged_ordered_container const& - other) const + operator<=(aged_ordered_container< + OtherIsMulti, + OtherIsMap, + Key, + OtherT, + OtherDuration, + Compare, + OtherAllocator> const& other) const { return !(other < *this); } - template + template < + bool OtherIsMulti, + bool OtherIsMap, + class OtherT, + class OtherDuration, + class OtherAllocator> bool - operator>( - aged_ordered_container const& - other) const + operator>(aged_ordered_container< + OtherIsMulti, + OtherIsMap, + Key, + OtherT, + OtherDuration, + Compare, + OtherAllocator> const& other) const { return other < *this; } - template + template < + bool OtherIsMulti, + bool OtherIsMap, + class OtherT, + class OtherDuration, + class OtherAllocator> bool - operator>=( - aged_ordered_container const& - other) const + operator>=(aged_ordered_container< + OtherIsMulti, + OtherIsMap, + Key, + OtherT, + OtherDuration, + Compare, + OtherAllocator> const& other) const { return !(*this < other); } private: // enable_if prevents erase (reverse_iterator pos, now) from compiling - template ::value>> + template < + bool is_const, + class Iterator, + class = std::enable_if_t::value>> void - touch(beast::detail::aged_container_iterator pos, typename clock_type::time_point const& now); + touch( + beast::detail::aged_container_iterator pos, + typename clock_type::time_point const& now); - template ::propagate_on_container_swap::value> + template < + bool maybe_propagate = std::allocator_traits::propagate_on_container_swap::value> typename std::enable_if::type swap_data(aged_ordered_container& other) noexcept; - template ::propagate_on_container_swap::value> + template < + bool maybe_propagate = std::allocator_traits::propagate_on_container_swap::value> typename std::enable_if::type swap_data(aged_ordered_container& other) noexcept; @@ -1058,7 +1174,8 @@ private: //------------------------------------------------------------------------------ template -aged_ordered_container::aged_ordered_container(clock_type& clock) +aged_ordered_container::aged_ordered_container( + clock_type& clock) : m_config(clock) { } @@ -1249,8 +1366,8 @@ aged_ordered_container::opera template auto -aged_ordered_container::operator=(aged_ordered_container&& other) - -> aged_ordered_container& +aged_ordered_container::operator=( + aged_ordered_container&& other) -> aged_ordered_container& { clear(); this->m_config = std::move(other.m_config); @@ -1296,13 +1413,15 @@ aged_ordered_container::at(K template template typename std::conditional::type& -aged_ordered_container::operator[](Key const& key) +aged_ordered_container::operator[]( + Key const& key) { typename cont_type::insert_commit_data d; auto const result(m_cont.insert_check(key, std::cref(m_config.key_compare()), d)); if (result.second) { - element* const p(new_element(std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple())); + element* const p(new_element( + std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple())); m_cont.insert_commit(*p, d); chronological.list.push_back(*p); return p->value.second; @@ -1319,8 +1438,10 @@ aged_ordered_container::opera auto const result(m_cont.insert_check(key, std::cref(m_config.key_compare()), d)); if (result.second) { - element* const p( - new_element(std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::forward_as_tuple())); + element* const p(new_element( + std::piecewise_construct, + std::forward_as_tuple(std::move(key)), + std::forward_as_tuple())); m_cont.insert_commit(*p, d); chronological.list.push_back(*p); return p->value.second; @@ -1344,7 +1465,8 @@ aged_ordered_container::clear template template auto -aged_ordered_container::insert(value_type const& value) -> +aged_ordered_container::insert( + value_type const& value) -> typename std::enable_if>::type { typename cont_type::insert_commit_data d; @@ -1363,8 +1485,8 @@ aged_ordered_container::inser template template auto -aged_ordered_container::insert(value_type const& value) -> - typename std::enable_if::type +aged_ordered_container::insert( + value_type const& value) -> typename std::enable_if::type { auto const before(m_cont.upper_bound(extract(value), std::cref(m_config.key_compare()))); element* const p(new_element(value)); @@ -1377,7 +1499,8 @@ aged_ordered_container::inser template template auto -aged_ordered_container::insert(value_type&& value) -> +aged_ordered_container::insert( + value_type&& value) -> typename std::enable_if>::type { typename cont_type::insert_commit_data d; @@ -1396,8 +1519,8 @@ aged_ordered_container::inser template template auto -aged_ordered_container::insert(value_type&& value) -> - typename std::enable_if::type +aged_ordered_container::insert( + value_type&& value) -> typename std::enable_if::type { auto const before(m_cont.upper_bound(extract(value), std::cref(m_config.key_compare()))); element* const p(new_element(std::move(value))); @@ -1417,7 +1540,8 @@ aged_ordered_container::inser value_type const& value) -> typename std::enable_if::type { typename cont_type::insert_commit_data d; - auto const result(m_cont.insert_check(hint.iterator(), extract(value), std::cref(m_config.key_compare()), d)); + auto const result( + m_cont.insert_check(hint.iterator(), extract(value), std::cref(m_config.key_compare()), d)); if (result.second) { element* const p(new_element(value)); @@ -1437,7 +1561,8 @@ aged_ordered_container::inser value_type&& value) -> typename std::enable_if::type { typename cont_type::insert_commit_data d; - auto const result(m_cont.insert_check(hint.iterator(), extract(value), std::cref(m_config.key_compare()), d)); + auto const result( + m_cont.insert_check(hint.iterator(), extract(value), std::cref(m_config.key_compare()), d)); if (result.second) { element* const p(new_element(std::move(value))); @@ -1452,8 +1577,8 @@ aged_ordered_container::inser template template auto -aged_ordered_container::emplace(Args&&... args) -> - typename std::enable_if>::type +aged_ordered_container::emplace(Args&&... args) + -> typename std::enable_if>::type { // VFALCO NOTE Its unfortunate that we need to // construct element here @@ -1474,8 +1599,8 @@ aged_ordered_container::empla template template auto -aged_ordered_container::emplace(Args&&... args) -> - typename std::enable_if::type +aged_ordered_container::emplace(Args&&... args) + -> typename std::enable_if::type { element* const p(new_element(std::forward(args)...)); auto const before(m_cont.upper_bound(extract(p->value), std::cref(m_config.key_compare()))); @@ -1496,7 +1621,8 @@ aged_ordered_container::empla // construct element here element* const p(new_element(std::forward(args)...)); typename cont_type::insert_commit_data d; - auto const result(m_cont.insert_check(hint.iterator(), extract(p->value), std::cref(m_config.key_compare()), d)); + auto const result(m_cont.insert_check( + hint.iterator(), extract(p->value), std::cref(m_config.key_compare()), d)); if (result.second) { auto const iter(m_cont.insert_commit(*p, d)); @@ -1533,7 +1659,8 @@ aged_ordered_container::erase template template auto -aged_ordered_container::erase(K const& k) -> size_type +aged_ordered_container::erase(K const& k) + -> size_type { auto iter(m_cont.find(k, std::cref(m_config.key_compare()))); if (iter == m_cont.end()) @@ -1553,7 +1680,8 @@ aged_ordered_container::erase template void -aged_ordered_container::swap(aged_ordered_container& other) noexcept +aged_ordered_container::swap( + aged_ordered_container& other) noexcept { swap_data(other); std::swap(chronological, other.chronological); @@ -1565,7 +1693,8 @@ aged_ordered_container::swap( template template auto -aged_ordered_container::touch(K const& k) -> size_type +aged_ordered_container::touch(K const& k) + -> size_type { auto const now(clock().now()); size_type n(0); @@ -1581,13 +1710,31 @@ aged_ordered_container::touch //------------------------------------------------------------------------------ template -template +template < + bool OtherIsMulti, + bool OtherIsMap, + class OtherT, + class OtherDuration, + class OtherAllocator> bool aged_ordered_container::operator==( - aged_ordered_container const& other) - const + aged_ordered_container< + OtherIsMulti, + OtherIsMap, + Key, + OtherT, + OtherDuration, + Compare, + OtherAllocator> const& other) const { - using Other = aged_ordered_container; + using Other = aged_ordered_container< + OtherIsMulti, + OtherIsMap, + Key, + OtherT, + OtherDuration, + Compare, + OtherAllocator>; if (size() != other.size()) return false; std::equal_to eq; @@ -1642,7 +1789,8 @@ aged_ordered_container::swap_ //------------------------------------------------------------------------------ template -struct is_aged_container> +struct is_aged_container< + beast::detail::aged_ordered_container> : std::true_type { explicit is_aged_container() = default; @@ -1654,7 +1802,8 @@ template & lhs, - beast::detail::aged_ordered_container& rhs) noexcept + beast::detail::aged_ordered_container& + rhs) noexcept { lhs.swap(rhs); } @@ -1677,7 +1826,8 @@ expire( { std::size_t n(0); auto const expired(c.clock().now() - age); - for (auto iter(c.chronological.cbegin()); iter != c.chronological.cend() && iter.when() <= expired;) + for (auto iter(c.chronological.cbegin()); + iter != c.chronological.cend() && iter.when() <= expired;) { iter = c.erase(iter); ++n; diff --git a/include/xrpl/beast/container/detail/aged_unordered_container.h b/include/xrpl/beast/container/detail/aged_unordered_container.h index a73ec107a7..d912f06ce1 100644 --- a/include/xrpl/beast/container/detail/aged_unordered_container.h +++ b/include/xrpl/beast/container/detail/aged_unordered_container.h @@ -62,7 +62,8 @@ template < class Clock = std::chrono::steady_clock, class Hash = std::hash, class KeyEqual = std::equal_to, - class Allocator = std::allocator, Key>::type>> + class Allocator = + std::allocator, Key>::type>> class aged_unordered_container { public: @@ -88,9 +89,10 @@ private: } // VFALCO TODO hoist to remove template argument dependencies - struct element - : boost::intrusive::unordered_set_base_hook>, - boost::intrusive::list_base_hook> + struct element : boost::intrusive::unordered_set_base_hook< + boost::intrusive::link_mode>, + boost::intrusive::list_base_hook< + boost::intrusive::link_mode> { // Stash types here so the iterator doesn't // need to see the container declaration. @@ -106,14 +108,17 @@ private: { } - element(time_point const& when_, value_type&& value_) : value(std::move(value_)), when(when_) + element(time_point const& when_, value_type&& value_) + : value(std::move(value_)), when(when_) { } template < class... Args, - class = typename std::enable_if::value>::type> - element(time_point const& when_, Args&&... args) : value(std::forward(args)...), when(when_) + class = + typename std::enable_if::value>::type> + element(time_point const& when_, Args&&... args) + : value(std::forward(args)...), when(when_) { } @@ -203,7 +208,8 @@ private: } }; - using list_type = typename boost::intrusive::make_list>::type; + using list_type = typename boost::intrusive:: + make_list>::type; using cont_type = typename std::conditional< IsMulti, @@ -223,11 +229,13 @@ private: using bucket_type = typename cont_type::bucket_type; using bucket_traits = typename cont_type::bucket_traits; - using ElementAllocator = typename std::allocator_traits::template rebind_alloc; + using ElementAllocator = + typename std::allocator_traits::template rebind_alloc; using ElementAllocatorTraits = std::allocator_traits; - using BucketAllocator = typename std::allocator_traits::template rebind_alloc; + using BucketAllocator = + typename std::allocator_traits::template rebind_alloc; using BucketAllocatorTraits = std::allocator_traits; @@ -244,7 +252,8 @@ private: { } - config_t(clock_type& clock_, KeyEqual const& keyEqual) : KeyValueEqual(keyEqual), clock(clock_) + config_t(clock_type& clock_, KeyEqual const& keyEqual) + : KeyValueEqual(keyEqual), clock(clock_) { } @@ -259,16 +268,24 @@ private: } config_t(clock_type& clock_, Hash const& hash, Allocator const& alloc_) - : ValueHash(hash), beast::detail::empty_base_optimization(alloc_), clock(clock_) + : ValueHash(hash) + , beast::detail::empty_base_optimization(alloc_) + , clock(clock_) { } config_t(clock_type& clock_, KeyEqual const& keyEqual, Allocator const& alloc_) - : KeyValueEqual(keyEqual), beast::detail::empty_base_optimization(alloc_), clock(clock_) + : KeyValueEqual(keyEqual) + , beast::detail::empty_base_optimization(alloc_) + , clock(clock_) { } - config_t(clock_type& clock_, Hash const& hash, KeyEqual const& keyEqual, Allocator const& alloc_) + config_t( + clock_type& clock_, + Hash const& hash, + KeyEqual const& keyEqual, + Allocator const& alloc_) : ValueHash(hash) , KeyValueEqual(keyEqual) , beast::detail::empty_base_optimization(alloc_) @@ -395,8 +412,9 @@ private: class Buckets { public: - using vec_type = - std::vector::template rebind_alloc>; + using vec_type = std::vector< + bucket_type, + typename std::allocator_traits::template rebind_alloc>; Buckets() : m_max_load_factor(1.f), m_vec() { @@ -504,7 +522,8 @@ private: std::unique_ptr p( ElementAllocatorTraits::allocate(m_config.alloc(), 1), Deleter(m_config.alloc())); - ElementAllocatorTraits::construct(m_config.alloc(), p.get(), clock().now(), std::forward(args)...); + ElementAllocatorTraits::construct( + m_config.alloc(), p.get(), clock().now(), std::forward(args)...); return p.release(); } @@ -535,10 +554,13 @@ public: // A set iterator (IsMap==false) is always const // because the elements of a set are immutable. using iterator = beast::detail::aged_container_iterator; - using const_iterator = beast::detail::aged_container_iterator; + using const_iterator = + beast::detail::aged_container_iterator; - using local_iterator = beast::detail::aged_container_iterator; - using const_local_iterator = beast::detail::aged_container_iterator; + using local_iterator = + beast::detail::aged_container_iterator; + using const_local_iterator = + beast::detail::aged_container_iterator; //-------------------------------------------------------------------------- // @@ -554,9 +576,12 @@ public: public: // A set iterator (IsMap==false) is always const // because the elements of a set are immutable. - using iterator = beast::detail::aged_container_iterator; - using const_iterator = beast::detail::aged_container_iterator; - using reverse_iterator = beast::detail::aged_container_iterator; + using iterator = + beast::detail::aged_container_iterator; + using const_iterator = + beast::detail::aged_container_iterator; + using reverse_iterator = + beast::detail::aged_container_iterator; using const_reverse_iterator = beast::detail::aged_container_iterator; @@ -637,7 +662,8 @@ public: { static_assert(std::is_standard_layout::value, "must be standard layout"); return list.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - + ((std::size_t)std::addressof(((element*)0)->member)))); } const_iterator @@ -645,7 +671,8 @@ public: { static_assert(std::is_standard_layout::value, "must be standard layout"); return list.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - + ((std::size_t)std::addressof(((element*)0)->member)))); } private: @@ -682,7 +709,11 @@ public: aged_unordered_container(clock_type& clock, KeyEqual const& key_eq, Allocator const& alloc); - aged_unordered_container(clock_type& clock, Hash const& hash, KeyEqual const& key_eq, Allocator const& alloc); + aged_unordered_container( + clock_type& clock, + Hash const& hash, + KeyEqual const& key_eq, + Allocator const& alloc); template aged_unordered_container(InputIt first, InputIt last, clock_type& clock); @@ -691,16 +722,34 @@ public: aged_unordered_container(InputIt first, InputIt last, clock_type& clock, Hash const& hash); template - aged_unordered_container(InputIt first, InputIt last, clock_type& clock, KeyEqual const& key_eq); + aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + KeyEqual const& key_eq); template - aged_unordered_container(InputIt first, InputIt last, clock_type& clock, Allocator const& alloc); + aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Allocator const& alloc); template - aged_unordered_container(InputIt first, InputIt last, clock_type& clock, Hash const& hash, KeyEqual const& key_eq); + aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Hash const& hash, + KeyEqual const& key_eq); template - aged_unordered_container(InputIt first, InputIt last, clock_type& clock, Hash const& hash, Allocator const& alloc); + aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Hash const& hash, + Allocator const& alloc); template aged_unordered_container( @@ -729,11 +778,20 @@ public: aged_unordered_container(std::initializer_list init, clock_type& clock); - aged_unordered_container(std::initializer_list init, clock_type& clock, Hash const& hash); + aged_unordered_container( + std::initializer_list init, + clock_type& clock, + Hash const& hash); - aged_unordered_container(std::initializer_list init, clock_type& clock, KeyEqual const& key_eq); + aged_unordered_container( + std::initializer_list init, + clock_type& clock, + KeyEqual const& key_eq); - aged_unordered_container(std::initializer_list init, clock_type& clock, Allocator const& alloc); + aged_unordered_container( + std::initializer_list init, + clock_type& clock, + Allocator const& alloc); aged_unordered_container( std::initializer_list init, @@ -872,7 +930,8 @@ public: { static_assert(std::is_standard_layout::value, "must be standard layout"); return m_cont.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - + ((std::size_t)std::addressof(((element*)0)->member)))); } const_iterator @@ -880,7 +939,8 @@ public: { static_assert(std::is_standard_layout::value, "must be standard layout"); return m_cont.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - + ((std::size_t)std::addressof(((element*)0)->member)))); } //-------------------------------------------------------------------------- @@ -919,7 +979,8 @@ public: // map, set template auto - insert(value_type const& value) -> typename std::enable_if>::type; + insert(value_type const& value) -> + typename std::enable_if>::type; // multimap, multiset template @@ -929,12 +990,14 @@ public: // map, set template auto - insert(value_type&& value) -> typename std::enable_if>::type; + insert(value_type&& value) -> + typename std::enable_if>::type; // multimap, multiset template auto - insert(value_type&& value) -> typename std::enable_if::type; + insert(value_type&& value) -> + typename std::enable_if::type; // map, set template @@ -1012,7 +1075,8 @@ public: // set, map template auto - emplace(Args&&... args) -> typename std::enable_if>::type; + emplace(Args&&... args) -> + typename std::enable_if>::type; // multiset, multimap template @@ -1074,7 +1138,8 @@ public: size_type count(K const& k) const { - return m_cont.count(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal())); + return m_cont.count( + k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal())); } // VFALCO TODO Respect is_transparent (c++14) @@ -1082,7 +1147,8 @@ public: iterator find(K const& k) { - return iterator(m_cont.find(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); + return iterator(m_cont.find( + k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); } // VFALCO TODO Respect is_transparent (c++14) @@ -1090,8 +1156,8 @@ public: const_iterator find(K const& k) const { - return const_iterator( - m_cont.find(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); + return const_iterator(m_cont.find( + k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); } // VFALCO TODO Respect is_transparent (c++14) @@ -1099,7 +1165,8 @@ public: std::pair equal_range(K const& k) { - auto const r(m_cont.equal_range(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); + auto const r(m_cont.equal_range( + k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); return std::make_pair(iterator(r.first), iterator(r.second)); } @@ -1108,7 +1175,8 @@ public: std::pair equal_range(K const& k) const { - auto const r(m_cont.equal_range(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); + auto const r(m_cont.equal_range( + k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); return std::make_pair(const_iterator(r.first), const_iterator(r.second)); } @@ -1328,12 +1396,14 @@ private: // map, set template auto - insert_unchecked(value_type const& value) -> typename std::enable_if>::type; + insert_unchecked(value_type const& value) -> + typename std::enable_if>::type; // multimap, multiset template auto - insert_unchecked(value_type const& value) -> typename std::enable_if::type; + insert_unchecked(value_type const& value) -> + typename std::enable_if::type; template void @@ -1362,7 +1432,9 @@ private: template void - touch(beast::detail::aged_container_iterator pos, typename clock_type::time_point const& now) + touch( + beast::detail::aged_container_iterator pos, + typename clock_type::time_point const& now) { auto& e(*pos.iterator()); e.when = now; @@ -1370,7 +1442,8 @@ private: chronological.list.push_back(e); } - template ::propagate_on_container_swap::value> + template < + bool maybe_propagate = std::allocator_traits::propagate_on_container_swap::value> typename std::enable_if::type swap_data(aged_unordered_container& other) noexcept { @@ -1379,7 +1452,8 @@ private: std::swap(m_config.clock, other.m_config.clock); } - template ::propagate_on_container_swap::value> + template < + bool maybe_propagate = std::allocator_traits::propagate_on_container_swap::value> typename std::enable_if::type swap_data(aged_unordered_container& other) noexcept { @@ -1395,125 +1469,208 @@ private: //------------------------------------------------------------------------------ -template -aged_unordered_container::aged_unordered_container( - clock_type& clock) - : m_config(clock), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container(clock_type& clock) + : m_config(clock) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template -aged_unordered_container::aged_unordered_container( - clock_type& clock, - Hash const& hash) - : m_config(clock, hash), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container(clock_type& clock, Hash const& hash) + : m_config(clock, hash) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template -aged_unordered_container::aged_unordered_container( - clock_type& clock, - KeyEqual const& key_eq) - : m_config(clock, key_eq), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container(clock_type& clock, KeyEqual const& key_eq) + : m_config(clock, key_eq) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template -aged_unordered_container::aged_unordered_container( - clock_type& clock, - Allocator const& alloc) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container(clock_type& clock, Allocator const& alloc) : m_config(clock, alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template -aged_unordered_container::aged_unordered_container( - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container(clock_type& clock, Hash const& hash, KeyEqual const& key_eq) : m_config(clock, hash, key_eq) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template -aged_unordered_container::aged_unordered_container( - clock_type& clock, - Hash const& hash, - Allocator const& alloc) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container(clock_type& clock, Hash const& hash, Allocator const& alloc) : m_config(clock, hash, alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template -aged_unordered_container::aged_unordered_container( - clock_type& clock, - KeyEqual const& key_eq, - Allocator const& alloc) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container(clock_type& clock, KeyEqual const& key_eq, Allocator const& alloc) : m_config(clock, key_eq, alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template -aged_unordered_container::aged_unordered_container( - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq, - Allocator const& alloc) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container( + clock_type& clock, + Hash const& hash, + KeyEqual const& key_eq, + Allocator const& alloc) : m_config(clock, hash, key_eq, alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template -aged_unordered_container::aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock) - : m_config(clock), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) +aged_unordered_container:: + aged_unordered_container(InputIt first, InputIt last, clock_type& clock) + : m_config(clock) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(first, last); } -template +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template -aged_unordered_container::aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Hash const& hash) - : m_config(clock, hash), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) +aged_unordered_container:: + aged_unordered_container(InputIt first, InputIt last, clock_type& clock, Hash const& hash) + : m_config(clock, hash) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(first, last); } -template +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template -aged_unordered_container::aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - KeyEqual const& key_eq) - : m_config(clock, key_eq), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) +aged_unordered_container:: + aged_unordered_container(InputIt first, InputIt last, clock_type& clock, KeyEqual const& key_eq) + : m_config(clock, key_eq) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(first, last); } -template +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template -aged_unordered_container::aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Allocator const& alloc) +aged_unordered_container:: + aged_unordered_container(InputIt first, InputIt last, clock_type& clock, Allocator const& alloc) : m_config(clock, alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) @@ -1521,28 +1678,46 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template -aged_unordered_container::aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq) +aged_unordered_container:: + aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Hash const& hash, + KeyEqual const& key_eq) : m_config(clock, hash, key_eq) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(first, last); } -template +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template -aged_unordered_container::aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Hash const& hash, - Allocator const& alloc) +aged_unordered_container:: + aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Hash const& hash, + Allocator const& alloc) : m_config(clock, hash, alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) @@ -1550,14 +1725,23 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template -aged_unordered_container::aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - KeyEqual const& key_eq, - Allocator const& alloc) +aged_unordered_container:: + aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + KeyEqual const& key_eq, + Allocator const& alloc) : m_config(clock, key_eq, alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) @@ -1565,15 +1749,24 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template -aged_unordered_container::aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq, - Allocator const& alloc) +aged_unordered_container:: + aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Hash const& hash, + KeyEqual const& key_eq, + Allocator const& alloc) : m_config(clock, hash, key_eq, alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) @@ -1581,9 +1774,17 @@ aged_unordered_container -aged_unordered_container::aged_unordered_container( - aged_unordered_container const& other) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container(aged_unordered_container const& other) : m_config(other.m_config) , m_buck(m_config.alloc()) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) @@ -1591,10 +1792,17 @@ aged_unordered_container -aged_unordered_container::aged_unordered_container( - aged_unordered_container const& other, - Allocator const& alloc) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container(aged_unordered_container const& other, Allocator const& alloc) : m_config(other.m_config, alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) @@ -1602,18 +1810,35 @@ aged_unordered_container -aged_unordered_container::aged_unordered_container( - aged_unordered_container&& other) - : m_config(std::move(other.m_config)), m_buck(std::move(other.m_buck)), m_cont(std::move(other.m_cont)) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container(aged_unordered_container&& other) + : m_config(std::move(other.m_config)) + , m_buck(std::move(other.m_buck)) + , m_cont(std::move(other.m_cont)) { chronological.list = std::move(other.chronological.list); } -template -aged_unordered_container::aged_unordered_container( - aged_unordered_container&& other, - Allocator const& alloc) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container(aged_unordered_container&& other, Allocator const& alloc) : m_config(std::move(other.m_config), alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) @@ -1622,40 +1847,77 @@ aged_unordered_container -aged_unordered_container::aged_unordered_container( - std::initializer_list init, - clock_type& clock) - : m_config(clock), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container(std::initializer_list init, clock_type& clock) + : m_config(clock) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(init.begin(), init.end()); } -template -aged_unordered_container::aged_unordered_container( - std::initializer_list init, - clock_type& clock, - Hash const& hash) - : m_config(clock, hash), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container( + std::initializer_list init, + clock_type& clock, + Hash const& hash) + : m_config(clock, hash) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(init.begin(), init.end()); } -template -aged_unordered_container::aged_unordered_container( - std::initializer_list init, - clock_type& clock, - KeyEqual const& key_eq) - : m_config(clock, key_eq), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container( + std::initializer_list init, + clock_type& clock, + KeyEqual const& key_eq) + : m_config(clock, key_eq) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(init.begin(), init.end()); } -template -aged_unordered_container::aged_unordered_container( - std::initializer_list init, - clock_type& clock, - Allocator const& alloc) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container( + std::initializer_list init, + clock_type& clock, + Allocator const& alloc) : m_config(clock, alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) @@ -1663,24 +1925,42 @@ aged_unordered_container -aged_unordered_container::aged_unordered_container( - std::initializer_list init, - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container( + std::initializer_list init, + clock_type& clock, + Hash const& hash, + KeyEqual const& key_eq) : m_config(clock, hash, key_eq) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(init.begin(), init.end()); } -template -aged_unordered_container::aged_unordered_container( - std::initializer_list init, - clock_type& clock, - Hash const& hash, - Allocator const& alloc) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container( + std::initializer_list init, + clock_type& clock, + Hash const& hash, + Allocator const& alloc) : m_config(clock, hash, alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) @@ -1688,12 +1968,21 @@ aged_unordered_container -aged_unordered_container::aged_unordered_container( - std::initializer_list init, - clock_type& clock, - KeyEqual const& key_eq, - Allocator const& alloc) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container( + std::initializer_list init, + clock_type& clock, + KeyEqual const& key_eq, + Allocator const& alloc) : m_config(clock, key_eq, alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) @@ -1701,13 +1990,22 @@ aged_unordered_container -aged_unordered_container::aged_unordered_container( - std::initializer_list init, - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq, - Allocator const& alloc) +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + aged_unordered_container( + std::initializer_list init, + clock_type& clock, + Hash const& hash, + KeyEqual const& key_eq, + Allocator const& alloc) : m_config(clock, hash, key_eq, alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) @@ -1715,13 +2013,30 @@ aged_unordered_container -aged_unordered_container::~aged_unordered_container() +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> +aged_unordered_container:: + ~aged_unordered_container() { clear(); } -template +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> auto aged_unordered_container::operator=( aged_unordered_container const& other) -> aged_unordered_container& @@ -1738,7 +2053,15 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> auto aged_unordered_container::operator=( aged_unordered_container&& other) -> aged_unordered_container& @@ -1753,7 +2076,15 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> auto aged_unordered_container::operator=( std::initializer_list init) -> aged_unordered_container& @@ -1765,40 +2096,69 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template typename std::conditional::type& aged_unordered_container::at(K const& k) { - auto const iter(m_cont.find(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); + auto const iter( + m_cont.find(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); if (iter == m_cont.end()) throw std::out_of_range("key not found"); return iter->value.second; } -template +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template typename std::conditional::type const& -aged_unordered_container::at(K const& k) const +aged_unordered_container::at( + K const& k) const { - auto const iter(m_cont.find(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); + auto const iter( + m_cont.find(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); if (iter == m_cont.end()) throw std::out_of_range("key not found"); return iter->value.second; } -template +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template typename std::conditional::type& -aged_unordered_container::operator[](Key const& key) +aged_unordered_container::operator[]( + Key const& key) { maybe_rehash(1); typename cont_type::insert_commit_data d; - auto const result( - m_cont.insert_check(key, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); + auto const result(m_cont.insert_check( + key, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); if (result.second) { - element* const p(new_element(std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple())); + element* const p(new_element( + std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple())); m_cont.insert_commit(*p, d); chronological.list.push_back(*p); return p->value.second; @@ -1806,19 +2166,30 @@ aged_unordered_containervalue.second; } -template +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template typename std::conditional::type& -aged_unordered_container::operator[](Key&& key) +aged_unordered_container::operator[]( + Key&& key) { maybe_rehash(1); typename cont_type::insert_commit_data d; - auto const result( - m_cont.insert_check(key, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); + auto const result(m_cont.insert_check( + key, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); if (result.second) { - element* const p( - new_element(std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::forward_as_tuple())); + element* const p(new_element( + std::piecewise_construct, + std::forward_as_tuple(std::move(key)), + std::forward_as_tuple())); m_cont.insert_commit(*p, d); chronological.list.push_back(*p); return p->value.second; @@ -1828,7 +2199,15 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> void aged_unordered_container::clear() { @@ -1840,16 +2219,28 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template auto -aged_unordered_container::insert(value_type const& value) -> +aged_unordered_container::insert( + value_type const& value) -> typename std::enable_if>::type { maybe_rehash(1); typename cont_type::insert_commit_data d; auto const result(m_cont.insert_check( - extract(value), std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); + extract(value), + std::cref(m_config.hash_function()), + std::cref(m_config.key_value_equal()), + d)); if (result.second) { element* const p(new_element(value)); @@ -1861,11 +2252,19 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template auto -aged_unordered_container::insert(value_type const& value) -> - typename std::enable_if::type +aged_unordered_container::insert( + value_type const& value) -> typename std::enable_if::type { maybe_rehash(1); element* const p(new_element(value)); @@ -1875,16 +2274,28 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template auto -aged_unordered_container::insert(value_type&& value) -> +aged_unordered_container::insert( + value_type&& value) -> typename std::enable_if>::type { maybe_rehash(1); typename cont_type::insert_commit_data d; auto const result(m_cont.insert_check( - extract(value), std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); + extract(value), + std::cref(m_config.hash_function()), + std::cref(m_config.key_value_equal()), + d)); if (result.second) { element* const p(new_element(std::move(value))); @@ -1896,11 +2307,19 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template auto -aged_unordered_container::insert(value_type&& value) -> - typename std::enable_if::type +aged_unordered_container::insert( + value_type&& value) -> typename std::enable_if::type { maybe_rehash(1); element* const p(new_element(std::move(value))); @@ -1911,11 +2330,19 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template auto -aged_unordered_container::emplace(Args&&... args) -> - typename std::enable_if>::type +aged_unordered_container::emplace( + Args&&... args) -> typename std::enable_if>::type { maybe_rehash(1); // VFALCO NOTE Its unfortunate that we need to @@ -1932,11 +2359,19 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template auto -aged_unordered_container::emplace(Args&&... args) -> - typename std::enable_if>::type +aged_unordered_container::emplace( + Args&&... args) -> typename std::enable_if>::type { maybe_rehash(1); // VFALCO NOTE Its unfortunate that we need to @@ -1944,7 +2379,10 @@ aged_unordered_container(args)...)); typename cont_type::insert_commit_data d; auto const result(m_cont.insert_check( - extract(p->value), std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); + extract(p->value), + std::cref(m_config.hash_function()), + std::cref(m_config.key_value_equal()), + d)); if (result.second) { auto const iter(m_cont.insert_commit(*p, d)); @@ -1957,11 +2395,19 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template auto -aged_unordered_container::emplace(Args&&... args) -> - typename std::enable_if::type +aged_unordered_container::emplace( + Args&&... args) -> typename std::enable_if::type { maybe_rehash(1); element* const p(new_element(std::forward(args)...)); @@ -1971,7 +2417,15 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template auto aged_unordered_container::emplace_hint( @@ -1984,7 +2438,10 @@ aged_unordered_container(args)...)); typename cont_type::insert_commit_data d; auto const result(m_cont.insert_check( - extract(p->value), std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); + extract(p->value), + std::cref(m_config.hash_function()), + std::cref(m_config.key_value_equal()), + d)); if (result.second) { auto const iter(m_cont.insert_commit(*p, d)); @@ -1995,7 +2452,15 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template beast::detail::aged_container_iterator aged_unordered_container::erase( @@ -2005,7 +2470,15 @@ aged_unordered_container(pos.iterator()); } -template +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template beast::detail::aged_container_iterator aged_unordered_container::erase( @@ -2018,12 +2491,22 @@ aged_unordered_container(first.iterator()); } -template +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template auto -aged_unordered_container::erase(K const& k) -> size_type +aged_unordered_container::erase( + K const& k) -> size_type { - auto iter(m_cont.find(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); + auto iter( + m_cont.find(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); if (iter == m_cont.end()) return 0; size_type n(0); @@ -2039,7 +2522,15 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> void aged_unordered_container::swap( aged_unordered_container& other) noexcept @@ -2049,10 +2540,19 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template auto -aged_unordered_container::touch(K const& k) -> size_type +aged_unordered_container::touch( + K const& k) -> size_type { auto const now(clock().now()); size_type n(0); @@ -2065,7 +2565,15 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template < bool OtherIsMap, class OtherKey, @@ -2097,7 +2605,15 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template < bool OtherIsMap, class OtherKey, @@ -2141,15 +2657,27 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template auto -aged_unordered_container::insert_unchecked( - value_type const& value) -> typename std::enable_if>::type +aged_unordered_container:: + insert_unchecked(value_type const& value) -> + typename std::enable_if>::type { typename cont_type::insert_commit_data d; auto const result(m_cont.insert_check( - extract(value), std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); + extract(value), + std::cref(m_config.hash_function()), + std::cref(m_config.key_value_equal()), + d)); if (result.second) { element* const p(new_element(value)); @@ -2161,11 +2689,20 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> template auto -aged_unordered_container::insert_unchecked( - value_type const& value) -> typename std::enable_if::type +aged_unordered_container:: + insert_unchecked(value_type const& value) -> + typename std::enable_if::type { element* const p(new_element(value)); chronological.list.push_back(*p); @@ -2179,20 +2716,41 @@ aged_unordered_container +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> struct is_aged_container< - beast::detail::aged_unordered_container> : std::true_type + beast::detail:: + aged_unordered_container> + : std::true_type { explicit is_aged_container() = default; }; // Free functions -template +template < + bool IsMulti, + bool IsMap, + class Key, + class T, + class Clock, + class Hash, + class KeyEqual, + class Allocator> void swap( - beast::detail::aged_unordered_container& lhs, - beast::detail::aged_unordered_container& rhs) noexcept + beast::detail:: + aged_unordered_container& lhs, + beast::detail:: + aged_unordered_container& + rhs) noexcept { lhs.swap(rhs); } @@ -2211,12 +2769,14 @@ template < class Period> std::size_t expire( - beast::detail::aged_unordered_container& c, + beast::detail:: + aged_unordered_container& c, std::chrono::duration const& age) noexcept { std::size_t n(0); auto const expired(c.clock().now() - age); - for (auto iter(c.chronological.cbegin()); iter != c.chronological.cend() && iter.when() <= expired;) + for (auto iter(c.chronological.cbegin()); + iter != c.chronological.cend() && iter.when() <= expired;) { iter = c.erase(iter); ++n; diff --git a/include/xrpl/beast/core/LexicalCast.h b/include/xrpl/beast/core/LexicalCast.h index a7c135f23f..18e63c9c10 100644 --- a/include/xrpl/beast/core/LexicalCast.h +++ b/include/xrpl/beast/core/LexicalCast.h @@ -50,7 +50,9 @@ struct LexicalCast { explicit LexicalCast() = default; - static_assert(std::is_integral_v, "beast::LexicalCast can only be used with integral types"); + static_assert( + std::is_integral_v, + "beast::LexicalCast can only be used with integral types"); template std::enable_if_t && !std::is_same_v, bool> diff --git a/include/xrpl/beast/core/LockFreeStack.h b/include/xrpl/beast/core/LockFreeStack.h index bb32698dd8..fe3baa0564 100644 --- a/include/xrpl/beast/core/LockFreeStack.h +++ b/include/xrpl/beast/core/LockFreeStack.h @@ -19,10 +19,12 @@ public: using iterator_category = std::forward_iterator_tag; using value_type = typename Container::value_type; using difference_type = typename Container::difference_type; - using pointer = - typename std::conditional::type; - using reference = - typename std::conditional::type; + using pointer = typename std:: + conditional::type; + using reference = typename std::conditional< + IsConst, + typename Container::const_reference, + typename Container::reference>::type; LockFreeStackIterator() : m_node() { @@ -33,7 +35,8 @@ public: } template - explicit LockFreeStackIterator(LockFreeStackIterator const& other) : m_node(other.m_node) + explicit LockFreeStackIterator(LockFreeStackIterator const& other) + : m_node(other.m_node) { } @@ -190,7 +193,8 @@ public: { first = (old_head == &m_end); node->m_next = old_head; - } while (!m_head.compare_exchange_strong(old_head, node, std::memory_order_release, std::memory_order_relaxed)); + } while (!m_head.compare_exchange_strong( + old_head, node, std::memory_order_release, std::memory_order_relaxed)); return first; } @@ -213,7 +217,8 @@ public: if (node == &m_end) return nullptr; new_head = node->m_next.load(); - } while (!m_head.compare_exchange_strong(node, new_head, std::memory_order_release, std::memory_order_relaxed)); + } while (!m_head.compare_exchange_strong( + node, new_head, std::memory_order_release, std::memory_order_relaxed)); return static_cast(node); } diff --git a/include/xrpl/beast/hash/hash_append.h b/include/xrpl/beast/hash/hash_append.h index e4d646e532..d456bb3a73 100644 --- a/include/xrpl/beast/hash/hash_append.h +++ b/include/xrpl/beast/hash/hash_append.h @@ -26,7 +26,8 @@ template inline void reverse_bytes(T& t) { - unsigned char* bytes = static_cast(std::memmove(std::addressof(t), std::addressof(t), sizeof(T))); + unsigned char* bytes = + static_cast(std::memmove(std::addressof(t), std::addressof(t), sizeof(T))); for (unsigned i = 0; i < sizeof(T) / 2; ++i) std::swap(bytes[i], bytes[sizeof(T) - 1 - i]); } @@ -51,7 +52,8 @@ template inline void maybe_reverse_bytes(T& t, Hasher&) { - maybe_reverse_bytes(t, std::integral_constant{}); + maybe_reverse_bytes( + t, std::integral_constant{}); } } // namespace detail @@ -65,8 +67,9 @@ maybe_reverse_bytes(T& t, Hasher&) template struct is_uniquely_represented - : public std:: - integral_constant::value || std::is_enum::value || std::is_pointer::value> + : public std::integral_constant< + bool, + std::is_integral::value || std::is_enum::value || std::is_pointer::value> { explicit is_uniquely_represented() = default; }; @@ -107,7 +110,8 @@ template struct is_uniquely_represented> : public std::integral_constant< bool, - std::conjunction_v...> && sizeof(std::tuple) == (sizeof(T) + ...)> + std::conjunction_v...> && + sizeof(std::tuple) == (sizeof(T) + ...)> { explicit is_uniquely_represented() = default; }; @@ -124,8 +128,9 @@ struct is_uniquely_represented : public is_uniquely_represented template struct is_uniquely_represented> - : public std:: - integral_constant::value && sizeof(T) * N == sizeof(std::array)> + : public std::integral_constant< + bool, + is_uniquely_represented::value && sizeof(T) * N == sizeof(std::array)> { explicit is_uniquely_represented() = default; }; @@ -145,10 +150,11 @@ struct is_uniquely_represented> */ /** @{ */ template -struct is_contiguously_hashable : public std::integral_constant< - bool, - is_uniquely_represented::value && - (sizeof(T) == 1 || HashAlgorithm::endian == boost::endian::order::native)> +struct is_contiguously_hashable + : public std::integral_constant< + bool, + is_uniquely_represented::value && + (sizeof(T) == 1 || HashAlgorithm::endian == boost::endian::order::native)> { explicit is_contiguously_hashable() = default; }; diff --git a/include/xrpl/beast/rfc2616.h b/include/xrpl/beast/rfc2616.h index 2ff770c011..b19c2c511a 100644 --- a/include/xrpl/beast/rfc2616.h +++ b/include/xrpl/beast/rfc2616.h @@ -25,7 +25,8 @@ struct ci_equal_pred operator()(char c1, char c2) { // VFALCO TODO Use a table lookup here - return std::tolower(static_cast(c1)) == std::tolower(static_cast(c2)); + return std::tolower(static_cast(c1)) == + std::tolower(static_cast(c2)); } }; @@ -169,7 +170,9 @@ split(FwdIt first, FwdIt last, Char delim) return result; } -template ::value_type>>> +template < + class FwdIt, + class Result = std::vector::value_type>>> Result split_commas(FwdIt first, FwdIt last) { @@ -356,8 +359,10 @@ bool is_keep_alive(boost::beast::http::message const& m) { if (m.version() <= 10) - return boost::beast::http::token_list{m[boost::beast::http::field::connection]}.exists("keep-alive"); - return !boost::beast::http::token_list{m[boost::beast::http::field::connection]}.exists("close"); + return boost::beast::http::token_list{m[boost::beast::http::field::connection]}.exists( + "keep-alive"); + return !boost::beast::http::token_list{m[boost::beast::http::field::connection]}.exists( + "close"); } } // namespace rfc2616 diff --git a/include/xrpl/beast/test/yield_to.h b/include/xrpl/beast/test/yield_to.h index b10530c0d3..6c49c4a89c 100644 --- a/include/xrpl/beast/test/yield_to.h +++ b/include/xrpl/beast/test/yield_to.h @@ -40,7 +40,8 @@ public: /// The type of yield context passed to functions. using yield_context = boost::asio::yield_context; - explicit enable_yield_to(std::size_t concurrency = 1) : work_(boost::asio::make_work_guard(ios_)) + explicit enable_yield_to(std::size_t concurrency = 1) + : work_(boost::asio::make_work_guard(ios_)) { threads_.reserve(concurrency); while (concurrency--) diff --git a/include/xrpl/beast/unit_test/global_suites.h b/include/xrpl/beast/unit_test/global_suites.h index 68b4e2ced8..db5fee35dd 100644 --- a/include/xrpl/beast/unit_test/global_suites.h +++ b/include/xrpl/beast/unit_test/global_suites.h @@ -22,7 +22,12 @@ global_suites() template struct insert_suite { - insert_suite(char const* name, char const* module, char const* library, bool manual, int priority) + insert_suite( + char const* name, + char const* module, + char const* library, + bool manual, + int priority) { global_suites().insert(name, module, library, manual, priority); } diff --git a/include/xrpl/beast/unit_test/reporter.h b/include/xrpl/beast/unit_test/reporter.h index ee7168d039..63ad90ff7c 100644 --- a/include/xrpl/beast/unit_test/reporter.h +++ b/include/xrpl/beast/unit_test/reporter.h @@ -139,7 +139,10 @@ reporter<_>::results::add(suite_results const& r) if (elapsed >= std::chrono::seconds{1}) { auto const iter = std::lower_bound( - top.begin(), top.end(), elapsed, [](run_time const& t1, typename clock_type::duration const& t2) { + top.begin(), + top.end(), + elapsed, + [](run_time const& t1, typename clock_type::duration const& t2) { return t1.second > t2; }); if (iter != top.end()) @@ -172,8 +175,9 @@ reporter<_>::~reporter() os_ << std::setw(8) << fmtdur(i.second) << " " << i.first << '\n'; } auto const elapsed = clock_type::now() - results_.start; - os_ << fmtdur(elapsed) << ", " << amount{results_.suites, "suite"} << ", " << amount{results_.cases, "case"} << ", " - << amount{results_.total, "test"} << " total, " << amount{results_.failed, "failure"} << std::endl; + os_ << fmtdur(elapsed) << ", " << amount{results_.suites, "suite"} << ", " + << amount{results_.cases, "case"} << ", " << amount{results_.total, "test"} << " total, " + << amount{results_.failed, "failure"} << std::endl; } template @@ -208,7 +212,8 @@ void reporter<_>::on_case_begin(std::string const& name) { case_results_ = case_results(name); - os_ << suite_results_.name << (case_results_.name.empty() ? "" : (" " + case_results_.name)) << std::endl; + os_ << suite_results_.name << (case_results_.name.empty() ? "" : (" " + case_results_.name)) + << std::endl; } template @@ -231,7 +236,8 @@ reporter<_>::on_fail(std::string const& reason) { ++case_results_.failed; ++case_results_.total; - os_ << "#" << case_results_.total << " failed" << (reason.empty() ? "" : ": ") << reason << std::endl; + os_ << "#" << case_results_.total << " failed" << (reason.empty() ? "" : ": ") << reason + << std::endl; } template diff --git a/include/xrpl/beast/unit_test/suite.h b/include/xrpl/beast/unit_test/suite.h index 0e6b592a87..9031f9833e 100644 --- a/include/xrpl/beast/unit_test/suite.h +++ b/include/xrpl/beast/unit_test/suite.h @@ -91,7 +91,10 @@ private: } }; - template , class Allocator = std::allocator> + template < + class CharT, + class Traits = std::char_traits, + class Allocator = std::allocator> class log_os : public std::basic_ostream { log_buf buf_; @@ -562,7 +565,8 @@ suite::run(runner& r) If the condition is false, the file and line number are reported. */ -#define BEAST_EXPECTS(cond, reason) ((cond) ? (pass(), true) : (fail((reason), __FILE__, __LINE__), false)) +#define BEAST_EXPECTS(cond, reason) \ + ((cond) ? (pass(), true) : (fail((reason), __FILE__, __LINE__), false)) #endif } // namespace unit_test @@ -572,9 +576,9 @@ suite::run(runner& r) // detail: // This inserts the suite with the given manual flag -#define BEAST_DEFINE_TESTSUITE_INSERT(Class, Module, Library, manual, priority) \ - static beast::unit_test::detail::insert_suite Library##Module##Class##_test_instance( \ - #Class, #Module, #Library, manual, priority) +#define BEAST_DEFINE_TESTSUITE_INSERT(Class, Module, Library, manual, priority) \ + static beast::unit_test::detail::insert_suite \ + Library##Module##Class##_test_instance(#Class, #Module, #Library, manual, priority) //------------------------------------------------------------------------------ @@ -629,7 +633,8 @@ suite::run(runner& r) #else #include -#define BEAST_DEFINE_TESTSUITE(Class, Module, Library) BEAST_DEFINE_TESTSUITE_INSERT(Class, Module, Library, false, 0) +#define BEAST_DEFINE_TESTSUITE(Class, Module, Library) \ + BEAST_DEFINE_TESTSUITE_INSERT(Class, Module, Library, false, 0) #define BEAST_DEFINE_TESTSUITE_MANUAL(Class, Module, Library) \ BEAST_DEFINE_TESTSUITE_INSERT(Class, Module, Library, true, 0) #define BEAST_DEFINE_TESTSUITE_PRIO(Class, Module, Library, Priority) \ diff --git a/include/xrpl/beast/unit_test/suite_info.h b/include/xrpl/beast/unit_test/suite_info.h index 019251b0c4..0ffb330422 100644 --- a/include/xrpl/beast/unit_test/suite_info.h +++ b/include/xrpl/beast/unit_test/suite_info.h @@ -27,7 +27,13 @@ class suite_info run_type run_; public: - suite_info(std::string name, std::string module, std::string library, bool manual, int priority, run_type run) + suite_info( + std::string name, + std::string module, + std::string library, + bool manual, + int priority, + run_type run) : name_(std::move(name)) , module_(std::move(module)) , library_(std::move(library)) @@ -91,10 +97,17 @@ public: /// Convenience for producing suite_info for a given test type. template suite_info -make_suite_info(std::string name, std::string module, std::string library, bool manual, int priority) +make_suite_info( + std::string name, + std::string module, + std::string library, + bool manual, + int priority) { return suite_info( - std::move(name), std::move(module), std::move(library), manual, priority, [](runner& r) { Suite{}(r); }); + std::move(name), std::move(module), std::move(library), manual, priority, [](runner& r) { + Suite{}(r); + }); } } // namespace unit_test diff --git a/include/xrpl/beast/unit_test/suite_list.h b/include/xrpl/beast/unit_test/suite_list.h index 4412883e31..bbd2914c45 100644 --- a/include/xrpl/beast/unit_test/suite_list.h +++ b/include/xrpl/beast/unit_test/suite_list.h @@ -39,7 +39,12 @@ public: template void -suite_list::insert(char const* name, char const* module, char const* library, bool manual, int priority) +suite_list::insert( + char const* name, + char const* module, + char const* library, + bool manual, + int priority) { #ifndef NDEBUG { diff --git a/include/xrpl/beast/utility/Journal.h b/include/xrpl/beast/utility/Journal.h index dff88826ce..2ac5050b2d 100644 --- a/include/xrpl/beast/utility/Journal.h +++ b/include/xrpl/beast/utility/Journal.h @@ -190,7 +190,8 @@ public: */ Stream(Sink& sink, Severity level) : m_sink(sink), m_level(level) { - XRPL_ASSERT(m_level < severities::kDisabled, "beast::Journal::Stream::Stream : maximum level"); + XRPL_ASSERT( + m_level < severities::kDisabled, "beast::Journal::Stream::Stream : maximum level"); } /** Construct or copy another Stream. */ @@ -421,7 +422,8 @@ class basic_logstream : public std::basic_ostream detail::logstream_buf buf_; public: - explicit basic_logstream(beast::Journal::Stream const& strm) : std::basic_ostream(&buf_), buf_(strm) + explicit basic_logstream(beast::Journal::Stream const& strm) + : std::basic_ostream(&buf_), buf_(strm) { } }; diff --git a/include/xrpl/beast/utility/instrumentation.h b/include/xrpl/beast/utility/instrumentation.h index 0d0b2ce415..106856514b 100644 --- a/include/xrpl/beast/utility/instrumentation.h +++ b/include/xrpl/beast/utility/instrumentation.h @@ -19,7 +19,8 @@ #endif #define XRPL_ASSERT ALWAYS_OR_UNREACHABLE -#define XRPL_ASSERT_PARTS(cond, function, description, ...) XRPL_ASSERT(cond, function " : " description) +#define XRPL_ASSERT_PARTS(cond, function, description, ...) \ + XRPL_ASSERT(cond, function " : " description) // How to use the instrumentation macros: // diff --git a/include/xrpl/beast/utility/maybe_const.h b/include/xrpl/beast/utility/maybe_const.h index 4aac7f018e..3f6e1f95bd 100644 --- a/include/xrpl/beast/utility/maybe_const.h +++ b/include/xrpl/beast/utility/maybe_const.h @@ -9,8 +9,10 @@ template struct maybe_const { explicit maybe_const() = default; - using type = typename std:: - conditional::type const, typename std::remove_const::type>::type; + using type = typename std::conditional< + IsConst, + typename std::remove_const::type const, + typename std::remove_const::type>::type; }; /** Alias for omitting `typename`. */ diff --git a/include/xrpl/beast/utility/rngfill.h b/include/xrpl/beast/utility/rngfill.h index 7c694aac4f..f6ac46476d 100644 --- a/include/xrpl/beast/utility/rngfill.h +++ b/include/xrpl/beast/utility/rngfill.h @@ -35,7 +35,10 @@ rngfill(void* const buffer, std::size_t const bytes, Generator& g) } } -template > +template < + class Generator, + std::size_t N, + class = std::enable_if_t> void rngfill(std::array& a, Generator& g) { diff --git a/src/xrpld/conditions/Condition.h b/include/xrpl/conditions/Condition.h similarity index 98% rename from src/xrpld/conditions/Condition.h rename to include/xrpl/conditions/Condition.h index 50872e75ef..6b306a3982 100644 --- a/src/xrpld/conditions/Condition.h +++ b/include/xrpl/conditions/Condition.h @@ -1,9 +1,8 @@ #pragma once -#include - #include #include +#include #include #include diff --git a/src/xrpld/conditions/Fulfillment.h b/include/xrpl/conditions/Fulfillment.h similarity index 97% rename from src/xrpld/conditions/Fulfillment.h rename to include/xrpl/conditions/Fulfillment.h index 840e9f9993..ab47804e45 100644 --- a/src/xrpld/conditions/Fulfillment.h +++ b/include/xrpl/conditions/Fulfillment.h @@ -1,9 +1,8 @@ #pragma once -#include - #include #include +#include namespace xrpl { namespace cryptoconditions { @@ -77,7 +76,8 @@ inline bool operator==(Fulfillment const& lhs, Fulfillment const& rhs) { // FIXME: for compound conditions, need to also check subtypes - return lhs.type() == rhs.type() && lhs.cost() == rhs.cost() && lhs.fingerprint() == rhs.fingerprint(); + return lhs.type() == rhs.type() && lhs.cost() == rhs.cost() && + lhs.fingerprint() == rhs.fingerprint(); } inline bool diff --git a/src/xrpld/conditions/detail/PreimageSha256.h b/include/xrpl/conditions/detail/PreimageSha256.h similarity index 95% rename from src/xrpld/conditions/detail/PreimageSha256.h rename to include/xrpl/conditions/detail/PreimageSha256.h index f3ce1a03e0..8726473c2d 100644 --- a/src/xrpld/conditions/detail/PreimageSha256.h +++ b/include/xrpl/conditions/detail/PreimageSha256.h @@ -1,11 +1,10 @@ #pragma once -#include -#include -#include - #include #include +#include +#include +#include #include #include diff --git a/src/xrpld/conditions/detail/error.h b/include/xrpl/conditions/detail/error.h similarity index 100% rename from src/xrpld/conditions/detail/error.h rename to include/xrpl/conditions/detail/error.h diff --git a/src/xrpld/conditions/detail/utils.h b/include/xrpl/conditions/detail/utils.h similarity index 98% rename from src/xrpld/conditions/detail/utils.h rename to include/xrpl/conditions/detail/utils.h index 2a4187718b..17d93d43b5 100644 --- a/src/xrpld/conditions/detail/utils.h +++ b/include/xrpl/conditions/detail/utils.h @@ -1,9 +1,8 @@ #pragma once -#include - #include #include +#include #include diff --git a/include/xrpl/core/Coro.ipp b/include/xrpl/core/Coro.ipp index 2853adf0de..26d35d3c69 100644 --- a/include/xrpl/core/Coro.ipp +++ b/include/xrpl/core/Coro.ipp @@ -11,7 +11,8 @@ JobQueue::Coro::Coro(Coro_create_t, JobQueue& jq, JobType type, std::string cons , name_(name) , running_(false) , coro_( - [this, fn = std::forward(f)](boost::coroutines::asymmetric_coroutine::push_type& do_yield) { + [this, fn = std::forward(f)]( + boost::coroutines::asymmetric_coroutine::push_type& do_yield) { yield_ = &do_yield; yield(); fn(shared_from_this()); diff --git a/src/xrpld/app/misc/HashRouter.h b/include/xrpl/core/HashRouter.h similarity index 96% rename from src/xrpld/app/misc/HashRouter.h rename to include/xrpl/core/HashRouter.h index ad6da520bd..b4f07f6dc0 100644 --- a/src/xrpld/app/misc/HashRouter.h +++ b/include/xrpl/core/HashRouter.h @@ -210,7 +210,11 @@ public: // Add a peer suppression and return whether the entry should be processed bool - shouldProcess(uint256 const& key, PeerShortID peer, HashRouterFlags& flags, std::chrono::seconds tx_interval); + shouldProcess( + uint256 const& key, + PeerShortID peer, + HashRouterFlags& flags, + std::chrono::seconds tx_interval); /** Set the flags on a hash. @@ -248,10 +252,8 @@ private: Setup const setup_; // Stores all suppressed hashes and their expiration time - beast::aged_unordered_map> suppressionMap_; + beast::aged_unordered_map> + suppressionMap_; }; -HashRouter::Setup -setup_HashRouter(Config const&); - } // namespace xrpl diff --git a/include/xrpl/core/Job.h b/include/xrpl/core/Job.h index 61651fd673..b01b4cd68b 100644 --- a/include/xrpl/core/Job.h +++ b/include/xrpl/core/Job.h @@ -92,7 +92,11 @@ public: Job(JobType type, std::uint64_t index); // VFALCO TODO try to remove the dependency on LoadMonitor. - Job(JobType type, std::string const& name, std::uint64_t index, LoadMonitor& lm, std::function const& job); + Job(JobType type, + std::string const& name, + std::uint64_t index, + LoadMonitor& lm, + std::function const& job); JobType getType() const; diff --git a/include/xrpl/core/JobQueue.h b/include/xrpl/core/JobQueue.h index b410e200e1..5fafaea142 100644 --- a/include/xrpl/core/JobQueue.h +++ b/include/xrpl/core/JobQueue.h @@ -140,7 +140,8 @@ public: */ template < typename JobHandler, - typename = std::enable_if_t()()), void>::value>> + typename = + std::enable_if_t()()), void>::value>> bool addJob(JobType type, std::string const& name, JobHandler&& jobHandler) { diff --git a/include/xrpl/core/JobTypeData.h b/include/xrpl/core/JobTypeData.h index cdcb19c316..32df3e88cf 100644 --- a/include/xrpl/core/JobTypeData.h +++ b/include/xrpl/core/JobTypeData.h @@ -31,8 +31,16 @@ public: beast::insight::Event dequeue; beast::insight::Event execute; - JobTypeData(JobTypeInfo const& info_, beast::insight::Collector::ptr const& collector, Logs& logs) noexcept - : m_load(logs.journal("LoadMonitor")), m_collector(collector), info(info_), waiting(0), running(0), deferred(0) + JobTypeData( + JobTypeInfo const& info_, + beast::insight::Collector::ptr const& collector, + Logs& logs) noexcept + : m_load(logs.journal("LoadMonitor")) + , m_collector(collector) + , info(info_) + , waiting(0) + , running(0) + , deferred(0) { m_load.setTargetLatency(info.getAverageLatency(), info.getPeakLatency()); diff --git a/include/xrpl/core/JobTypeInfo.h b/include/xrpl/core/JobTypeInfo.h index d4daa1ec68..537656fa1d 100644 --- a/include/xrpl/core/JobTypeInfo.h +++ b/include/xrpl/core/JobTypeInfo.h @@ -32,7 +32,11 @@ public: int limit, std::chrono::milliseconds avgLatency, std::chrono::milliseconds peakLatency) - : m_type(type), m_name(std::move(name)), m_limit(limit), m_avgLatency(avgLatency), m_peakLatency(peakLatency) + : m_type(type) + , m_name(std::move(name)) + , m_limit(limit) + , m_avgLatency(avgLatency) + , m_peakLatency(peakLatency) { } diff --git a/include/xrpl/core/JobTypes.h b/include/xrpl/core/JobTypes.h index 88f98aad66..4dc2fd96cd 100644 --- a/include/xrpl/core/JobTypes.h +++ b/include/xrpl/core/JobTypes.h @@ -15,7 +15,13 @@ public: using const_iterator = Map::const_iterator; private: - JobTypes() : m_unknown(jtINVALID, "invalid", 0, std::chrono::milliseconds{0}, std::chrono::milliseconds{0}) + JobTypes() + : m_unknown( + jtINVALID, + "invalid", + 0, + std::chrono::milliseconds{0}, + std::chrono::milliseconds{0}) { using namespace std::chrono_literals; int maxLimit = std::numeric_limits::max(); @@ -26,7 +32,9 @@ private: int limit, std::chrono::milliseconds avgLatency, std::chrono::milliseconds peakLatency) { - XRPL_ASSERT(m_map.find(jt) == m_map.end(), "xrpl::JobTypes::JobTypes::add : unique job type input"); + XRPL_ASSERT( + m_map.find(jt) == m_map.end(), + "xrpl::JobTypes::JobTypes::add : unique job type input"); [[maybe_unused]] auto const inserted = m_map diff --git a/include/xrpl/core/NetworkIDService.h b/include/xrpl/core/NetworkIDService.h new file mode 100644 index 0000000000..d12fa42055 --- /dev/null +++ b/include/xrpl/core/NetworkIDService.h @@ -0,0 +1,33 @@ +#pragma once + +#include + +namespace xrpl { + +/** Service that provides access to the network ID. + + This service provides read-only access to the network ID configured + for this server. The network ID identifies which network (mainnet, + testnet, devnet, or custom network) this server is configured to + connect to. + + Well-known network IDs: + - 0: Mainnet + - 1: Testnet + - 2: Devnet + - 1025+: Custom networks (require NetworkID field in transactions) +*/ +class NetworkIDService +{ +public: + virtual ~NetworkIDService() = default; + + /** Get the configured network ID + * + * @return The network ID this server is configured for + */ + virtual std::uint32_t + getNetworkID() const noexcept = 0; +}; + +} // namespace xrpl diff --git a/include/xrpl/core/PeerReservationTable.h b/include/xrpl/core/PeerReservationTable.h index 8f187bf324..ffaef2fa08 100644 --- a/include/xrpl/core/PeerReservationTable.h +++ b/include/xrpl/core/PeerReservationTable.h @@ -55,7 +55,8 @@ struct KeyEqual final class PeerReservationTable final { public: - explicit PeerReservationTable(beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) + explicit PeerReservationTable( + beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) : journal_(journal) { } diff --git a/include/xrpl/core/PerfLog.h b/include/xrpl/core/PerfLog.h index eebd41ae09..64bdb3b625 100644 --- a/include/xrpl/core/PerfLog.h +++ b/include/xrpl/core/PerfLog.h @@ -151,7 +151,11 @@ PerfLog::Setup setup_PerfLog(Section const& section, boost::filesystem::path const& configDir); std::unique_ptr -make_PerfLog(PerfLog::Setup const& setup, Application& app, beast::Journal journal, std::function&& signalStop); +make_PerfLog( + PerfLog::Setup const& setup, + Application& app, + beast::Journal journal, + std::function&& signalStop); template auto diff --git a/include/xrpl/core/ServiceRegistry.h b/include/xrpl/core/ServiceRegistry.h index 86591a815f..1a2e33d5ee 100644 --- a/include/xrpl/core/ServiceRegistry.h +++ b/include/xrpl/core/ServiceRegistry.h @@ -41,6 +41,7 @@ class LoadFeeTrack; class LoadManager; class ManifestCache; class NetworkOPs; +class NetworkIDService; class OpenLedger; class OrderBookDB; class Overlay; @@ -99,6 +100,9 @@ public: virtual CachedSLEs& cachedSLEs() = 0; + virtual NetworkIDService& + getNetworkIDService() = 0; + // Protocol and validation services virtual AmendmentTable& getAmendmentTable() = 0; @@ -214,6 +218,13 @@ public: virtual Logs& logs() = 0; + virtual std::optional const& + trapTxID() const = 0; + + /** Retrieve the "wallet database" */ + virtual DatabaseCon& + getWalletDB() = 0; + // Temporary: Get the underlying Application for functions that haven't // been migrated yet. This should be removed once all code is migrated. virtual Application& diff --git a/include/xrpl/core/detail/Workers.h b/include/xrpl/core/detail/Workers.h index c5df622fa1..8d898e35c0 100644 --- a/include/xrpl/core/detail/Workers.h +++ b/include/xrpl/core/detail/Workers.h @@ -160,7 +160,8 @@ private: Idle: Active, but blocked on waiting for a task. Paused: Blocked waiting to exit or become active. */ - class Worker : public beast::LockFreeStack::Node, public beast::LockFreeStack::Node + class Worker : public beast::LockFreeStack::Node, + public beast::LockFreeStack::Node { public: Worker(Workers& workers, std::string const& threadName, int const instance); diff --git a/include/xrpl/json/json_reader.h b/include/xrpl/json/json_reader.h index 3a1bc38929..09dac80a2f 100644 --- a/include/xrpl/json/json_reader.h +++ b/include/xrpl/json/json_reader.h @@ -145,7 +145,11 @@ private: bool decodeUnicodeCodePoint(Token& token, Location& current, Location end, unsigned int& unicode); bool - decodeUnicodeEscapeSequence(Token& token, Location& current, Location end, unsigned int& unicode); + decodeUnicodeEscapeSequence( + Token& token, + Location& current, + Location end, + unsigned int& unicode); bool addError(std::string const& message, Token& token, Location extra = 0); bool diff --git a/include/xrpl/json/json_writer.h b/include/xrpl/json/json_writer.h index 9455d4abd9..e468a5940d 100644 --- a/include/xrpl/json/json_writer.h +++ b/include/xrpl/json/json_writer.h @@ -315,7 +315,8 @@ public: operator<<(std::ostream& o, Compact const& cJv) { detail::write_value( - [&o](void const* data, std::size_t n) { o.write(static_cast(data), n); }, cJv.jv_); + [&o](void const* data, std::size_t n) { o.write(static_cast(data), n); }, + cJv.jv_); return o; } }; diff --git a/src/xrpld/app/ledger/AcceptedLedgerTx.h b/include/xrpl/ledger/AcceptedLedgerTx.h similarity index 92% rename from src/xrpld/app/ledger/AcceptedLedgerTx.h rename to include/xrpl/ledger/AcceptedLedgerTx.h index 6c936bbcf2..d07016b860 100644 --- a/src/xrpld/app/ledger/AcceptedLedgerTx.h +++ b/include/xrpl/ledger/AcceptedLedgerTx.h @@ -1,15 +1,15 @@ #pragma once -#include - +#include +#include #include +#include +#include #include namespace xrpl { -class Logs; - /** A transaction that is in a closed ledger. diff --git a/src/xrpld/app/misc/AmendmentTable.h b/include/xrpl/ledger/AmendmentTable.h similarity index 91% rename from src/xrpld/app/misc/AmendmentTable.h rename to include/xrpl/ledger/AmendmentTable.h index 94ac9608a7..fb90d6e859 100644 --- a/src/xrpld/app/misc/AmendmentTable.h +++ b/include/xrpl/ledger/AmendmentTable.h @@ -1,16 +1,18 @@ #pragma once -#include -#include - +#include +#include #include #include #include +#include #include namespace xrpl { +class ServiceRegistry; + /** The amendment table stores the list of enabled and potential amendments. Individuals amendments are voted on by validators during the consensus process. @@ -21,7 +23,8 @@ public: struct FeatureInfo { FeatureInfo() = delete; - FeatureInfo(std::string const& n, uint256 const& f, VoteBehavior v) : name(n), feature(f), vote(v) + FeatureInfo(std::string const& n, uint256 const& f, VoteBehavior v) + : name(n), feature(f), vote(v) { } @@ -152,18 +155,20 @@ public: Serializer s; amendTx.add(s); - JLOG(j.debug()) << "Amendments: Adding pseudo-transaction: " << amendTx.getTransactionID() << ": " - << strHex(s.slice()) << ": " << amendTx; + JLOG(j.debug()) << "Amendments: Adding pseudo-transaction: " + << amendTx.getTransactionID() << ": " << strHex(s.slice()) << ": " + << amendTx; initialPosition->addGiveItem( - SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(amendTx.getTransactionID(), s.slice())); + SHAMapNodeType::tnTRANSACTION_NM, + make_shamapitem(amendTx.getTransactionID(), s.slice())); } } }; std::unique_ptr make_AmendmentTable( - Application& app, + ServiceRegistry& registry, std::chrono::seconds majorityTime, std::vector const& supported, Section const& enabled, diff --git a/include/xrpl/ledger/ApplyView.h b/include/xrpl/ledger/ApplyView.h index 2de5f79452..d5be5c9a1e 100644 --- a/include/xrpl/ledger/ApplyView.h +++ b/include/xrpl/ledger/ApplyView.h @@ -33,7 +33,8 @@ constexpr ApplyFlags operator|(ApplyFlags const& lhs, ApplyFlags const& rhs) { return safe_cast( - safe_cast>(lhs) | safe_cast>(rhs)); + safe_cast>(lhs) | + safe_cast>(rhs)); } static_assert((tapFAIL_HARD | tapRETRY) == safe_cast(0x30u), "ApplyFlags operator |"); @@ -43,7 +44,8 @@ constexpr ApplyFlags operator&(ApplyFlags const& lhs, ApplyFlags const& rhs) { return safe_cast( - safe_cast>(lhs) & safe_cast>(rhs)); + safe_cast>(lhs) & + safe_cast>(rhs)); } static_assert((tapFAIL_HARD & tapRETRY) == tapNONE, "ApplyFlags operator &"); @@ -211,7 +213,11 @@ public: // Called when a credit is made to an account // This is required to support PaymentSandbox virtual void - creditHook(AccountID const& from, AccountID const& to, STAmount const& amount, STAmount const& preCreditBalance) + creditHook( + AccountID const& from, + AccountID const& to, + STAmount const& amount, + STAmount const& preCreditBalance) { } diff --git a/include/xrpl/ledger/ApplyViewImpl.h b/include/xrpl/ledger/ApplyViewImpl.h index f6c83462f2..7f790f2be5 100644 --- a/include/xrpl/ledger/ApplyViewImpl.h +++ b/include/xrpl/ledger/ApplyViewImpl.h @@ -33,7 +33,13 @@ public: destructor. */ std::optional - apply(OpenView& to, STTx const& tx, TER ter, std::optional parentBatchId, bool isDryRun, beast::Journal j); + apply( + OpenView& to, + STTx const& tx, + TER ter, + std::optional parentBatchId, + bool isDryRun, + beast::Journal j); /** Set the amount of currency delivered. diff --git a/src/xrpld/app/ledger/BookListeners.h b/include/xrpl/ledger/BookListeners.h similarity index 97% rename from src/xrpld/app/ledger/BookListeners.h rename to include/xrpl/ledger/BookListeners.h index 036e988749..3ed267448b 100644 --- a/src/xrpld/app/ledger/BookListeners.h +++ b/include/xrpl/ledger/BookListeners.h @@ -1,8 +1,7 @@ #pragma once -#include - #include +#include #include #include diff --git a/include/xrpl/ledger/Credit.h b/include/xrpl/ledger/Credit.h index 58ec23a86a..770b82a650 100644 --- a/include/xrpl/ledger/Credit.h +++ b/include/xrpl/ledger/Credit.h @@ -15,7 +15,11 @@ namespace xrpl { */ /** @{ */ STAmount -creditLimit(ReadView const& view, AccountID const& account, AccountID const& issuer, Currency const& currency); +creditLimit( + ReadView const& view, + AccountID const& account, + AccountID const& issuer, + Currency const& currency); IOUAmount creditLimit2(ReadView const& v, AccountID const& acc, AccountID const& iss, Currency const& cur); @@ -29,7 +33,11 @@ creditLimit2(ReadView const& v, AccountID const& acc, AccountID const& iss, Curr */ /** @{ */ STAmount -creditBalance(ReadView const& view, AccountID const& account, AccountID const& issuer, Currency const& currency); +creditBalance( + ReadView const& view, + AccountID const& account, + AccountID const& issuer, + Currency const& currency); /** @} */ } // namespace xrpl diff --git a/include/xrpl/ledger/OpenView.h b/include/xrpl/ledger/OpenView.h index 42f62d5bca..5c942ce5e3 100644 --- a/include/xrpl/ledger/OpenView.h +++ b/include/xrpl/ledger/OpenView.h @@ -57,7 +57,9 @@ private: std::shared_ptr meta; // Constructor needed for emplacement in std::map - txData(std::shared_ptr const& txn_, std::shared_ptr const& meta_) + txData( + std::shared_ptr const& txn_, + std::shared_ptr const& meta_) : txn(txn_), meta(meta_) { } @@ -130,7 +132,11 @@ public: The tx list starts empty and will contain all newly inserted tx. */ - OpenView(open_ledger_t, ReadView const* base, Rules const& rules, std::shared_ptr hold = nullptr); + OpenView( + open_ledger_t, + ReadView const* base, + Rules const& rules, + std::shared_ptr hold = nullptr); OpenView(open_ledger_t, Rules const& rules, std::shared_ptr const& base) : OpenView(open_ledger, &*base, rules, base) diff --git a/include/xrpl/ledger/OrderBookDB.h b/include/xrpl/ledger/OrderBookDB.h new file mode 100644 index 0000000000..3d689607bf --- /dev/null +++ b/include/xrpl/ledger/OrderBookDB.h @@ -0,0 +1,93 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace xrpl { + +/** Tracks order books in the ledger. + + This interface provides access to order book information, including: + - Which order books exist in the ledger + - Querying order books by issue + - Managing order book subscriptions + + The order book database is updated as ledgers are accepted and provides + efficient lookup of order book information for pathfinding and client + subscriptions. +*/ +class OrderBookDB +{ +public: + virtual ~OrderBookDB() = default; + + /** Initialize or update the order book database with a new ledger. + + This method should be called when a new ledger is accepted to update + the order book database with the current state of all order books. + + @param ledger The ledger to scan for order books + */ + virtual void + setup(std::shared_ptr const& ledger) = 0; + + /** Add an order book to track. + + @param book The order book to add + */ + virtual void + addOrderBook(Book const& book) = 0; + + /** Get all order books that want a specific issue. + + Returns a list of all order books where the taker pays the specified + issue. This is useful for pathfinding to find all possible next hops + from a given currency. + + @param issue The issue to search for + @param domain Optional domain restriction for the order book + @return Vector of books that want this issue + */ + virtual std::vector + getBooksByTakerPays(Issue const& issue, std::optional const& domain = std::nullopt) = 0; + + /** Get the count of order books that want a specific issue. + + @param issue The issue to search for + @param domain Optional domain restriction for the order book + @return Number of books that want this issue + */ + virtual int + getBookSize(Issue const& issue, std::optional const& domain = std::nullopt) = 0; + + /** Check if an order book to XRP exists for the given issue. + + @param issue The issue to check + @param domain Optional domain restriction for the order book + @return true if a book from this issue to XRP exists + */ + virtual bool + isBookToXRP(Issue const& issue, std::optional domain = std::nullopt) = 0; + + virtual void + processTxn( + std::shared_ptr const& ledger, + AcceptedLedgerTx const& alTx, + MultiApiJson const& jvObj) = 0; + + virtual BookListeners::pointer + getBookListeners(Book const&) = 0; + virtual BookListeners::pointer + makeBookListeners(Book const&) = 0; +}; + +} // namespace xrpl diff --git a/include/xrpl/ledger/PaymentSandbox.h b/include/xrpl/ledger/PaymentSandbox.h index fe62d753ec..891e3ef27b 100644 --- a/include/xrpl/ledger/PaymentSandbox.h +++ b/include/xrpl/ledger/PaymentSandbox.h @@ -18,7 +18,8 @@ class DeferredCredits public: struct Adjustment { - Adjustment(STAmount const& d, STAmount const& c, STAmount const& b) : debits(d), credits(c), origBalance(b) + Adjustment(STAmount const& d, STAmount const& c, STAmount const& b) + : debits(d), credits(c), origBalance(b) { } STAmount debits; @@ -119,7 +120,8 @@ public: // or a PaymentSandbox-derived class, we MUST go through // one of these constructors or invariants will be broken. /** @{ */ - explicit PaymentSandbox(PaymentSandbox const* base) : ApplyViewBase(base, base->flags()), ps_(base) + explicit PaymentSandbox(PaymentSandbox const* base) + : ApplyViewBase(base, base->flags()), ps_(base) { } @@ -129,11 +131,15 @@ public: /** @} */ STAmount - balanceHook(AccountID const& account, AccountID const& issuer, STAmount const& amount) const override; + balanceHook(AccountID const& account, AccountID const& issuer, STAmount const& amount) + const override; void - creditHook(AccountID const& from, AccountID const& to, STAmount const& amount, STAmount const& preCreditBalance) - override; + creditHook( + AccountID const& from, + AccountID const& to, + STAmount const& amount, + STAmount const& preCreditBalance) override; void adjustOwnerCountHook(AccountID const& account, std::uint32_t cur, std::uint32_t next) override; diff --git a/include/xrpl/ledger/ReadView.h b/include/xrpl/ledger/ReadView.h index faec10993a..e3a5163418 100644 --- a/include/xrpl/ledger/ReadView.h +++ b/include/xrpl/ledger/ReadView.h @@ -247,7 +247,9 @@ Rules makeRulesGivenLedger(DigestAwareReadView const& ledger, Rules const& current); Rules -makeRulesGivenLedger(DigestAwareReadView const& ledger, std::unordered_set> const& presets); +makeRulesGivenLedger( + DigestAwareReadView const& ledger, + std::unordered_set> const& presets); } // namespace xrpl diff --git a/include/xrpl/ledger/View.h b/include/xrpl/ledger/View.h index fa16e16006..cd23cf4978 100644 --- a/include/xrpl/ledger/View.h +++ b/include/xrpl/ledger/View.h @@ -74,10 +74,18 @@ isGlobalFrozen(ReadView const& view, Asset const& asset); // Note, depth parameter is used to limit the recursion depth [[nodiscard]] bool -isVaultPseudoAccountFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptShare, int depth); +isVaultPseudoAccountFrozen( + ReadView const& view, + AccountID const& account, + MPTIssue const& mptShare, + int depth); [[nodiscard]] bool -isIndividualFrozen(ReadView const& view, AccountID const& account, Currency const& currency, AccountID const& issuer); +isIndividualFrozen( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer); [[nodiscard]] inline bool isIndividualFrozen(ReadView const& view, AccountID const& account, Issue const& issue) @@ -91,11 +99,16 @@ isIndividualFrozen(ReadView const& view, AccountID const& account, MPTIssue cons [[nodiscard]] inline bool isIndividualFrozen(ReadView const& view, AccountID const& account, Asset const& asset) { - return std::visit([&](auto const& issue) { return isIndividualFrozen(view, account, issue); }, asset.value()); + return std::visit( + [&](auto const& issue) { return isIndividualFrozen(view, account, issue); }, asset.value()); } [[nodiscard]] bool -isFrozen(ReadView const& view, AccountID const& account, Currency const& currency, AccountID const& issuer); +isFrozen( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer); [[nodiscard]] inline bool isFrozen(ReadView const& view, AccountID const& account, Issue const& issue, int = 0 /*ignored*/) @@ -114,7 +127,8 @@ isFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssu [[nodiscard]] inline bool isFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth = 0) { - return std::visit([&](auto const& issue) { return isFrozen(view, account, issue, depth); }, asset.value()); + return std::visit( + [&](auto const& issue) { return isFrozen(view, account, issue, depth); }, asset.value()); } [[nodiscard]] inline TER @@ -132,7 +146,8 @@ checkFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptI [[nodiscard]] inline TER checkFrozen(ReadView const& view, AccountID const& account, Asset const& asset) { - return std::visit([&](auto const& issue) { return checkFrozen(view, account, issue); }, asset.value()); + return std::visit( + [&](auto const& issue) { return checkFrozen(view, account, issue); }, asset.value()); } [[nodiscard]] bool @@ -143,7 +158,10 @@ isAnyFrozen( int depth = 0); [[nodiscard]] inline bool -isAnyFrozen(ReadView const& view, std::initializer_list const& accounts, Issue const& issue) +isAnyFrozen( + ReadView const& view, + std::initializer_list const& accounts, + Issue const& issue) { for (auto const& account : accounts) { @@ -154,7 +172,11 @@ isAnyFrozen(ReadView const& view, std::initializer_list const& accoun } [[nodiscard]] inline bool -isAnyFrozen(ReadView const& view, std::initializer_list const& accounts, Asset const& asset, int depth = 0) +isAnyFrozen( + ReadView const& view, + std::initializer_list const& accounts, + Asset const& asset, + int depth = 0) { return std::visit( [&](TIss const& issue) { @@ -167,16 +189,28 @@ isAnyFrozen(ReadView const& view, std::initializer_list const& accoun } [[nodiscard]] bool -isDeepFrozen(ReadView const& view, AccountID const& account, Currency const& currency, AccountID const& issuer); +isDeepFrozen( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer); [[nodiscard]] inline bool -isDeepFrozen(ReadView const& view, AccountID const& account, Issue const& issue, int = 0 /*ignored*/) +isDeepFrozen( + ReadView const& view, + AccountID const& account, + Issue const& issue, + int = 0 /*ignored*/) { return isDeepFrozen(view, account, issue.currency, issue.account); } [[nodiscard]] inline bool -isDeepFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth = 0) +isDeepFrozen( + ReadView const& view, + AccountID const& account, + MPTIssue const& mptIssue, + int depth = 0) { // Unlike IOUs, frozen / locked MPTs are not allowed to send or receive // funds, so checking "deep frozen" is the same as checking "frozen". @@ -191,7 +225,9 @@ isDeepFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mpt [[nodiscard]] inline bool isDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth = 0) { - return std::visit([&](auto const& issue) { return isDeepFrozen(view, account, issue, depth); }, asset.value()); + return std::visit( + [&](auto const& issue) { return isDeepFrozen(view, account, issue, depth); }, + asset.value()); } [[nodiscard]] inline TER @@ -209,11 +245,16 @@ checkDeepFrozen(ReadView const& view, AccountID const& account, MPTIssue const& [[nodiscard]] inline TER checkDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset) { - return std::visit([&](auto const& issue) { return checkDeepFrozen(view, account, issue); }, asset.value()); + return std::visit( + [&](auto const& issue) { return checkDeepFrozen(view, account, issue); }, asset.value()); } [[nodiscard]] bool -isLPTokenFrozen(ReadView const& view, AccountID const& account, Issue const& asset, Issue const& asset2); +isLPTokenFrozen( + ReadView const& view, + AccountID const& account, + Issue const& asset, + Issue const& asset2); // Returns the amount an account can spend. // @@ -291,7 +332,10 @@ xrpLiquid(ReadView const& view, AccountID const& id, std::int32_t ownerCountAdj, /** Iterate all items in the given directory. */ void -forEachItem(ReadView const& view, Keylet const& root, std::function const&)> const& f); +forEachItem( + ReadView const& view, + Keylet const& root, + std::function const&)> const& f); /** Iterate all items after an item in the given directory. @param after The key of the item to start after @@ -310,7 +354,10 @@ forEachItemAfter( /** Iterate all items in an account's owner directory. */ inline void -forEachItem(ReadView const& view, AccountID const& id, std::function const&)> const& f) +forEachItem( + ReadView const& view, + AccountID const& id, + std::function const&)> const& f) { return forEachItem(view, keylet::ownerDir(id), f); } @@ -407,7 +454,11 @@ getCandidateLedger(LedgerIndex requested) use the second form if you have not acquired the valid ledger yet */ [[nodiscard]] bool -areCompatible(ReadView const& validLedger, ReadView const& testLedger, beast::Journal::Stream& s, char const* reason); +areCompatible( + ReadView const& validLedger, + ReadView const& testLedger, + beast::Journal::Stream& s, + char const* reason); [[nodiscard]] bool areCompatible( @@ -425,7 +476,11 @@ areCompatible( /** Adjust the owner count up or down. */ void -adjustOwnerCount(ApplyView& view, std::shared_ptr const& sle, std::int32_t amount, beast::Journal j); +adjustOwnerCount( + ApplyView& view, + std::shared_ptr const& sle, + std::int32_t amount, + beast::Journal j); /** @{ */ /** Returns the first entry in the directory, advancing the index @@ -451,7 +506,12 @@ cdirFirst( uint256& entry); bool -dirFirst(ApplyView& view, uint256 const& root, std::shared_ptr& page, unsigned int& index, uint256& entry); +dirFirst( + ApplyView& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry); /** @} */ /** @{ */ @@ -478,14 +538,23 @@ cdirNext( uint256& entry); bool -dirNext(ApplyView& view, uint256 const& root, std::shared_ptr& page, unsigned int& index, uint256& entry); +dirNext( + ApplyView& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry); /** @} */ [[nodiscard]] std::function describeOwnerDir(AccountID const& account); [[nodiscard]] TER -dirLink(ApplyView& view, AccountID const& owner, std::shared_ptr& object, SF_UINT64 const& node = sfOwnerNode); +dirLink( + ApplyView& view, + AccountID const& owner, + std::shared_ptr& object, + SF_UINT64 const& node = sfOwnerNode); AccountID pseudoAccountAddress(ReadView const& view, uint256 const& pseudoOwnerKey); @@ -509,7 +578,9 @@ createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const // * NOT a ltACCOUNT_ROOT OR // * null pointer [[nodiscard]] bool -isPseudoAccount(std::shared_ptr sleAcct, std::set const& pseudoFieldFilter = {}); +isPseudoAccount( + std::shared_ptr sleAcct, + std::set const& pseudoFieldFilter = {}); // Returns the list of fields that define an ACCOUNT_ROOT as a pseudo-account if // set @@ -523,7 +594,10 @@ isPseudoAccount(std::shared_ptr sleAcct, std::set cons getPseudoAccountFields(); [[nodiscard]] inline bool -isPseudoAccount(ReadView const& view, AccountID const& accountId, std::set const& pseudoFieldFilter = {}) +isPseudoAccount( + ReadView const& view, + AccountID const& accountId, + std::set const& pseudoFieldFilter = {}) { return isPseudoAccount(view.read(keylet::account(accountId)), pseudoFieldFilter); } @@ -683,13 +757,25 @@ trustCreate( beast::Journal j); [[nodiscard]] TER -removeEmptyHolding(ApplyView& view, AccountID const& accountID, Issue const& issue, beast::Journal journal); +removeEmptyHolding( + ApplyView& view, + AccountID const& accountID, + Issue const& issue, + beast::Journal journal); [[nodiscard]] TER -removeEmptyHolding(ApplyView& view, AccountID const& accountID, MPTIssue const& mptIssue, beast::Journal journal); +removeEmptyHolding( + ApplyView& view, + AccountID const& accountID, + MPTIssue const& mptIssue, + beast::Journal journal); [[nodiscard]] inline TER -removeEmptyHolding(ApplyView& view, AccountID const& accountID, Asset const& asset, beast::Journal journal) +removeEmptyHolding( + ApplyView& view, + AccountID const& accountID, + Asset const& asset, + beast::Journal journal) { return std::visit( [&](TIss const& issue) -> TER { @@ -741,7 +827,11 @@ rippleCredit( beast::Journal j); TER -rippleLockEscrowMPT(ApplyView& view, AccountID const& uGrantorID, STAmount const& saAmount, beast::Journal j); +rippleLockEscrowMPT( + ApplyView& view, + AccountID const& uGrantorID, + STAmount const& saAmount, + beast::Journal j); TER rippleUnlockEscrowMPT( @@ -781,13 +871,28 @@ accountSendMulti( WaiveTransferFee waiveFee = WaiveTransferFee::No); [[nodiscard]] TER -issueIOU(ApplyView& view, AccountID const& account, STAmount const& amount, Issue const& issue, beast::Journal j); +issueIOU( + ApplyView& view, + AccountID const& account, + STAmount const& amount, + Issue const& issue, + beast::Journal j); [[nodiscard]] TER -redeemIOU(ApplyView& view, AccountID const& account, STAmount const& amount, Issue const& issue, beast::Journal j); +redeemIOU( + ApplyView& view, + AccountID const& account, + STAmount const& amount, + Issue const& issue, + beast::Journal j); [[nodiscard]] TER -transferXRP(ApplyView& view, AccountID const& from, AccountID const& to, STAmount const& amount, beast::Journal j); +transferXRP( + ApplyView& view, + AccountID const& from, + AccountID const& to, + STAmount const& amount, + beast::Journal j); /* Check if MPToken (for MPT) or trust line (for IOU) exists: * - StrongAuth - before checking if authorization is required @@ -818,7 +923,11 @@ enum class AuthType { StrongAuth, WeakAuth, Legacy }; * The default "Legacy" auth type is equivalent to WeakAuth. */ [[nodiscard]] TER -requireAuth(ReadView const& view, Issue const& issue, AccountID const& account, AuthType authType = AuthType::Legacy); +requireAuth( + ReadView const& view, + Issue const& issue, + AccountID const& account, + AuthType authType = AuthType::Legacy); /** Check if the account lacks required authorization. * @@ -858,7 +967,9 @@ requireAuth( AuthType authType = AuthType::Legacy) { return std::visit( - [&](TIss const& issue_) { return requireAuth(view, issue_, account, authType); }, + [&](TIss const& issue_) { + return requireAuth(view, issue_, account, authType); + }, asset.value()); } @@ -898,7 +1009,11 @@ enforceMPTokenAuthorization( * and tesSUCCESS otherwise. */ [[nodiscard]] TER -canTransfer(ReadView const& view, MPTIssue const& mptIssue, AccountID const& from, AccountID const& to); +canTransfer( + ReadView const& view, + MPTIssue const& mptIssue, + AccountID const& from, + AccountID const& to); [[nodiscard]] TER canTransfer(ReadView const& view, Issue const& issue, AccountID const& from, AccountID const& to); @@ -910,7 +1025,9 @@ canTransfer(ReadView const& view, Issue const& issue, AccountID const& from, Acc AccountID const& to) { return std::visit( - [&](TIss const& issue) -> TER { return canTransfer(view, issue, from, to); }, + [&](TIss const& issue) -> TER { + return canTransfer(view, issue, from, to); + }, asset.value()); } @@ -918,7 +1035,8 @@ canTransfer(ReadView const& view, Issue const& issue, AccountID const& from, Acc * (if should not be skipped) and if the entry should be skipped. The status * is always tesSUCCESS if the entry should be skipped. */ -using EntryDeleter = std::function(LedgerEntryType, uint256 const&, std::shared_ptr&)>; +using EntryDeleter = std::function< + std::pair(LedgerEntryType, uint256 const&, std::shared_ptr&)>; /** Cleanup owner directory entries on account delete. * Used for a regular and AMM accounts deletion. The caller * has to provide the deleter function, which handles details of diff --git a/include/xrpl/ledger/detail/RawStateTable.h b/include/xrpl/ledger/detail/RawStateTable.h index e09f2f0e44..7a3e2077ff 100644 --- a/include/xrpl/ledger/detail/RawStateTable.h +++ b/include/xrpl/ledger/detail/RawStateTable.h @@ -23,11 +23,13 @@ public: static constexpr size_t initialBufferSize = kilobytes(256); RawStateTable() - : monotonic_resource_{std::make_unique(initialBufferSize)} + : monotonic_resource_{std::make_unique( + initialBufferSize)} , items_{monotonic_resource_.get()} {}; RawStateTable(RawStateTable const& rhs) - : monotonic_resource_{std::make_unique(initialBufferSize)} + : monotonic_resource_{std::make_unique( + initialBufferSize)} , items_{rhs.items_, monotonic_resource_.get()} , dropsDestroyed_{rhs.dropsDestroyed_} {}; diff --git a/include/xrpl/ledger/detail/ReadViewFwdRange.ipp b/include/xrpl/ledger/detail/ReadViewFwdRange.ipp index 212be52432..ce6754b39c 100644 --- a/include/xrpl/ledger/detail/ReadViewFwdRange.ipp +++ b/include/xrpl/ledger/detail/ReadViewFwdRange.ipp @@ -16,7 +16,9 @@ ReadViewFwdRange::iterator::iterator(iterator&& other) noexcept } template -ReadViewFwdRange::iterator::iterator(ReadView const* view, std::unique_ptr impl) +ReadViewFwdRange::iterator::iterator( + ReadView const* view, + std::unique_ptr impl) : view_(view), impl_(std::move(impl)) { } diff --git a/include/xrpl/net/AutoSocket.h b/include/xrpl/net/AutoSocket.h index 85a3adb456..29cec23998 100644 --- a/include/xrpl/net/AutoSocket.h +++ b/include/xrpl/net/AutoSocket.h @@ -26,13 +26,20 @@ public: using callback = std::function; public: - AutoSocket(boost::asio::io_context& s, boost::asio::ssl::context& c, bool secureOnly, bool plainOnly) - : mSecure(secureOnly), mBuffer((plainOnly || secureOnly) ? 0 : 4), j_{beast::Journal::getNullSink()} + AutoSocket( + boost::asio::io_context& s, + boost::asio::ssl::context& c, + bool secureOnly, + bool plainOnly) + : mSecure(secureOnly) + , mBuffer((plainOnly || secureOnly) ? 0 : 4) + , j_{beast::Journal::getNullSink()} { mSocket = std::make_unique(s, c); } - AutoSocket(boost::asio::io_context& s, boost::asio::ssl::context& c) : AutoSocket(s, c, false, false) + AutoSocket(boost::asio::io_context& s, boost::asio::ssl::context& c) + : AutoSocket(s, c, false, false) { } @@ -105,7 +112,12 @@ public: mSocket->next_layer().async_receive( boost::asio::buffer(mBuffer), boost::asio::socket_base::message_peek, - std::bind(&AutoSocket::handle_autodetect, this, cbFunc, std::placeholders::_1, std::placeholders::_2)); + std::bind( + &AutoSocket::handle_autodetect, + this, + cbFunc, + std::placeholders::_1, + std::placeholders::_2)); } } @@ -152,7 +164,10 @@ public: template void - async_read_until(boost::asio::basic_streambuf& buffers, std::string const& delim, Handler handler) + async_read_until( + boost::asio::basic_streambuf& buffers, + std::string const& delim, + Handler handler) { if (isSecure()) boost::asio::async_read_until(*mSocket, buffers, delim, handler); @@ -162,7 +177,10 @@ public: template void - async_read_until(boost::asio::basic_streambuf& buffers, MatchCondition cond, Handler handler) + async_read_until( + boost::asio::basic_streambuf& buffers, + MatchCondition cond, + Handler handler) { if (isSecure()) boost::asio::async_read_until(*mSocket, buffers, cond, handler); diff --git a/include/xrpl/net/HTTPClient.h b/include/xrpl/net/HTTPClient.h index 289ce8f6e3..9ea5f98a37 100644 --- a/include/xrpl/net/HTTPClient.h +++ b/include/xrpl/net/HTTPClient.h @@ -37,8 +37,10 @@ public: std::string const& strPath, std::size_t responseMax, // if no Content-Length header std::chrono::seconds timeout, - std::function - complete, + std::function complete, beast::Journal& j); static void @@ -49,8 +51,10 @@ public: std::string const& strPath, std::size_t responseMax, // if no Content-Length header std::chrono::seconds timeout, - std::function - complete, + std::function complete, beast::Journal& j); static void @@ -62,8 +66,10 @@ public: std::function build, std::size_t responseMax, // if no Content-Length header std::chrono::seconds timeout, - std::function - complete, + std::function complete, beast::Journal& j); }; diff --git a/include/xrpl/net/HTTPClientSSLContext.h b/include/xrpl/net/HTTPClientSSLContext.h index 1033b9a22b..80e5835f5e 100644 --- a/include/xrpl/net/HTTPClientSSLContext.h +++ b/include/xrpl/net/HTTPClientSSLContext.h @@ -30,8 +30,8 @@ public: registerSSLCerts(ssl_context_, ec, j_); if (ec && sslVerifyDir.empty()) - Throw( - boost::str(boost::format("Failed to set_default_verify_paths: %s") % ec.message())); + Throw(boost::str( + boost::format("Failed to set_default_verify_paths: %s") % ec.message())); } else { @@ -43,7 +43,8 @@ public: ssl_context_.add_verify_path(sslVerifyDir, ec); if (ec) - Throw(boost::str(boost::format("Failed to add verify path: %s") % ec.message())); + Throw( + boost::str(boost::format("Failed to add verify path: %s") % ec.message())); } } @@ -114,7 +115,9 @@ public: if (!ec) { strm.set_verify_callback( - std::bind(&rfc6125_verify, host, std::placeholders::_1, std::placeholders::_2, j_), ec); + std::bind( + &rfc6125_verify, host, std::placeholders::_1, std::placeholders::_2, j_), + ec); } } @@ -131,12 +134,17 @@ public: * @param j journal for logging */ static bool - rfc6125_verify(std::string const& domain, bool preverified, boost::asio::ssl::verify_context& ctx, beast::Journal j) + rfc6125_verify( + std::string const& domain, + bool preverified, + boost::asio::ssl::verify_context& ctx, + beast::Journal j) { if (boost::asio::ssl::host_name_verification(domain)(preverified, ctx)) return true; - JLOG(j.warn()) << "Outbound SSL connection to " << domain << " fails certificate verification"; + JLOG(j.warn()) << "Outbound SSL connection to " << domain + << " fails certificate verification"; return false; } diff --git a/include/xrpl/nodestore/Backend.h b/include/xrpl/nodestore/Backend.h index 6af292d5b3..7c3ea57bb8 100644 --- a/include/xrpl/nodestore/Backend.h +++ b/include/xrpl/nodestore/Backend.h @@ -63,7 +63,8 @@ public: virtual void open(bool createIfMissing, uint64_t appType, uint64_t uid, uint64_t salt) { - Throw("Deterministic appType/uid/salt not supported by backend " + getName()); + Throw( + "Deterministic appType/uid/salt not supported by backend " + getName()); } /** Close the backend. diff --git a/include/xrpl/nodestore/Database.h b/include/xrpl/nodestore/Database.h index d1f5b1bda2..e33b8a3a5c 100644 --- a/include/xrpl/nodestore/Database.h +++ b/include/xrpl/nodestore/Database.h @@ -243,7 +243,10 @@ private: std::condition_variable readCondVar_; // reads to do - std::map const&)>>>> + std::map< + uint256, + std::vector< + std::pair const&)>>>> read_; std::atomic readStopping_ = false; @@ -251,7 +254,11 @@ private: std::atomic runningThreads_ = 0; virtual std::shared_ptr - fetchNodeObject(uint256 const& hash, std::uint32_t ledgerSeq, FetchReport& fetchReport, bool duplicate) = 0; + fetchNodeObject( + uint256 const& hash, + std::uint32_t ledgerSeq, + FetchReport& fetchReport, + bool duplicate) = 0; /** Visit every object in the database This is usually called during import. diff --git a/include/xrpl/nodestore/DatabaseRotating.h b/include/xrpl/nodestore/DatabaseRotating.h index e20b49805c..23a749f972 100644 --- a/include/xrpl/nodestore/DatabaseRotating.h +++ b/include/xrpl/nodestore/DatabaseRotating.h @@ -13,7 +13,11 @@ namespace NodeStore { class DatabaseRotating : public Database { public: - DatabaseRotating(Scheduler& scheduler, int readThreads, Section const& config, beast::Journal journal) + DatabaseRotating( + Scheduler& scheduler, + int readThreads, + Section const& config, + beast::Journal journal) : Database(scheduler, readThreads, config, journal) { } @@ -28,7 +32,8 @@ public: virtual void rotate( std::unique_ptr&& newBackend, - std::function const& f) = 0; + std::function const& + f) = 0; }; } // namespace NodeStore diff --git a/include/xrpl/nodestore/Manager.h b/include/xrpl/nodestore/Manager.h index 9553407881..ff00ee3ee1 100644 --- a/include/xrpl/nodestore/Manager.h +++ b/include/xrpl/nodestore/Manager.h @@ -38,7 +38,11 @@ public: /** Create a backend. */ virtual std::unique_ptr - make_Backend(Section const& parameters, std::size_t burstSize, Scheduler& scheduler, beast::Journal journal) = 0; + make_Backend( + Section const& parameters, + std::size_t burstSize, + Scheduler& scheduler, + beast::Journal journal) = 0; /** Construct a NodeStore database. diff --git a/include/xrpl/nodestore/detail/DatabaseNodeImp.h b/include/xrpl/nodestore/detail/DatabaseNodeImp.h index 94859c4d22..21f06fef8d 100644 --- a/include/xrpl/nodestore/detail/DatabaseNodeImp.h +++ b/include/xrpl/nodestore/detail/DatabaseNodeImp.h @@ -82,7 +82,8 @@ private: std::shared_ptr backend_; std::shared_ptr - fetchNodeObject(uint256 const& hash, std::uint32_t, FetchReport& fetchReport, bool duplicate) override; + fetchNodeObject(uint256 const& hash, std::uint32_t, FetchReport& fetchReport, bool duplicate) + override; void for_each(std::function)> f) override diff --git a/include/xrpl/nodestore/detail/DatabaseRotatingImp.h b/include/xrpl/nodestore/detail/DatabaseRotatingImp.h index 1a378c54c7..8d4cd9ddbc 100644 --- a/include/xrpl/nodestore/detail/DatabaseRotatingImp.h +++ b/include/xrpl/nodestore/detail/DatabaseRotatingImp.h @@ -31,7 +31,8 @@ public: void rotate( std::unique_ptr&& newBackend, - std::function const& f) override; + std::function const& + f) override; std::string getName() const override; @@ -61,7 +62,8 @@ private: mutable std::mutex mutex_; std::shared_ptr - fetchNodeObject(uint256 const& hash, std::uint32_t, FetchReport& fetchReport, bool duplicate) override; + fetchNodeObject(uint256 const& hash, std::uint32_t, FetchReport& fetchReport, bool duplicate) + override; void for_each(std::function)> f) override; diff --git a/include/xrpl/nodestore/detail/ManagerImp.h b/include/xrpl/nodestore/detail/ManagerImp.h index f46a7d56d0..cb10a740c1 100644 --- a/include/xrpl/nodestore/detail/ManagerImp.h +++ b/include/xrpl/nodestore/detail/ManagerImp.h @@ -33,8 +33,11 @@ public: erase(Factory& factory) override; std::unique_ptr - make_Backend(Section const& parameters, std::size_t burstSize, Scheduler& scheduler, beast::Journal journal) - override; + make_Backend( + Section const& parameters, + std::size_t burstSize, + Scheduler& scheduler, + beast::Journal journal) override; std::unique_ptr make_Database( diff --git a/include/xrpl/nodestore/detail/codec.h b/include/xrpl/nodestore/detail/codec.h index 1d08beff59..8a337ca4c3 100644 --- a/include/xrpl/nodestore/detail/codec.h +++ b/include/xrpl/nodestore/detail/codec.h @@ -62,8 +62,8 @@ lz4_compress(void const* in, std::size_t in_size, BufferFactory&& bf) std::uint8_t* out = reinterpret_cast(bf(n + out_max)); result.first = out; std::memcpy(out, vi.data(), n); - auto const out_size = - LZ4_compress_default(reinterpret_cast(in), reinterpret_cast(out + n), in_size, out_max); + auto const out_size = LZ4_compress_default( + reinterpret_cast(in), reinterpret_cast(out + n), in_size, out_max); if (out_size == 0) Throw("lz4 compress"); result.second = n + out_size; @@ -137,8 +137,9 @@ nodeobject_decompress(void const* in, std::size_t in_size, BufferFactory&& bf) { if (in_size < 32) Throw( - "nodeobject codec v1: short inner node subsize: " + std::string("in_size = ") + - std::to_string(in_size) + " i = " + std::to_string(i)); + "nodeobject codec v1: short inner node subsize: " + + std::string("in_size = ") + std::to_string(in_size) + + " i = " + std::to_string(i)); std::memcpy(os.data(32), is(32), 32); in_size -= 32; } @@ -148,14 +149,16 @@ nodeobject_decompress(void const* in, std::size_t in_size, BufferFactory&& bf) } } if (in_size > 0) - Throw("nodeobject codec v1: long inner node, in_size = " + std::to_string(in_size)); + Throw( + "nodeobject codec v1: long inner node, in_size = " + std::to_string(in_size)); break; } case 3: // full v1 inner node { if (in_size != 16 * 32) // hashes Throw( - "nodeobject codec v1: short full inner node, in_size = " + std::to_string(in_size)); + "nodeobject codec v1: short full inner node, in_size = " + + std::to_string(in_size)); istream is(p, in_size); result.second = 525; void* const out = bf(result.second); diff --git a/include/xrpl/protocol/AMMCore.h b/include/xrpl/protocol/AMMCore.h index a2c531f361..1a0252d67a 100644 --- a/include/xrpl/protocol/AMMCore.h +++ b/include/xrpl/protocol/AMMCore.h @@ -17,7 +17,8 @@ std::uint16_t constexpr AUCTION_SLOT_MAX_AUTH_ACCOUNTS = 4; std::uint32_t constexpr AUCTION_SLOT_FEE_SCALE_FACTOR = 100000; std::uint32_t constexpr AUCTION_SLOT_DISCOUNTED_FEE_FRACTION = 10; std::uint32_t constexpr AUCTION_SLOT_MIN_FEE_FRACTION = 25; -std::uint32_t constexpr AUCTION_SLOT_INTERVAL_DURATION = TOTAL_TIME_SLOT_SECS / AUCTION_SLOT_TIME_INTERVALS; +std::uint32_t constexpr AUCTION_SLOT_INTERVAL_DURATION = + TOTAL_TIME_SLOT_SECS / AUCTION_SLOT_TIME_INTERVALS; // Votes std::uint16_t constexpr VOTE_MAX_SLOTS = 8; @@ -49,7 +50,9 @@ invalidAMMAmount( bool validZero = false); NotTEC -invalidAMMAsset(Issue const& issue, std::optional> const& pair = std::nullopt); +invalidAMMAsset( + Issue const& issue, + std::optional> const& pair = std::nullopt); NotTEC invalidAMMAssetPair( diff --git a/include/xrpl/protocol/AmountConversions.h b/include/xrpl/protocol/AmountConversions.h index 0807e96c49..e1a224dac9 100644 --- a/include/xrpl/protocol/AmountConversions.h +++ b/include/xrpl/protocol/AmountConversions.h @@ -53,7 +53,8 @@ inline IOUAmount toAmount(STAmount const& amt) { XRPL_ASSERT( - amt.mantissa() < std::numeric_limits::max(), "xrpl::toAmount : maximum mantissa"); + amt.mantissa() < std::numeric_limits::max(), + "xrpl::toAmount : maximum mantissa"); bool const isNeg = amt.negative(); std::int64_t const sMant = isNeg ? -std::int64_t(amt.mantissa()) : amt.mantissa(); @@ -66,7 +67,8 @@ inline XRPAmount toAmount(STAmount const& amt) { XRPL_ASSERT( - amt.mantissa() < std::numeric_limits::max(), "xrpl::toAmount : maximum mantissa"); + amt.mantissa() < std::numeric_limits::max(), + "xrpl::toAmount : maximum mantissa"); bool const isNeg = amt.negative(); std::int64_t const sMant = isNeg ? -std::int64_t(amt.mantissa()) : amt.mantissa(); diff --git a/include/xrpl/protocol/ApiVersion.h b/include/xrpl/protocol/ApiVersion.h index 756a41d25e..8772b5a49d 100644 --- a/include/xrpl/protocol/ApiVersion.h +++ b/include/xrpl/protocol/ApiVersion.h @@ -47,9 +47,11 @@ constexpr static auto apiMaximumValidVersion = apiBetaVersion; static_assert(apiInvalidVersion < apiMinimumSupportedVersion); static_assert( - apiVersionIfUnspecified >= apiMinimumSupportedVersion && apiVersionIfUnspecified <= apiMaximumSupportedVersion); + apiVersionIfUnspecified >= apiMinimumSupportedVersion && + apiVersionIfUnspecified <= apiMaximumSupportedVersion); static_assert( - apiCommandLineVersion >= apiMinimumSupportedVersion && apiCommandLineVersion <= apiMaximumSupportedVersion); + apiCommandLineVersion >= apiMinimumSupportedVersion && + apiCommandLineVersion <= apiMaximumSupportedVersion); static_assert(apiMaximumSupportedVersion >= apiMinimumSupportedVersion); static_assert(apiBetaVersion >= apiMaximumSupportedVersion); static_assert(apiMaximumValidVersion >= apiMaximumSupportedVersion); @@ -97,7 +99,8 @@ inline unsigned int getAPIVersionNumber(Json::Value const& jv, bool betaEnabled) { static Json::Value const minVersion(RPC::apiMinimumSupportedVersion); - Json::Value const maxVersion(betaEnabled ? RPC::apiBetaVersion : RPC::apiMaximumSupportedVersion); + Json::Value const maxVersion( + betaEnabled ? RPC::apiBetaVersion : RPC::apiMaximumSupportedVersion); if (jv.isObject()) { @@ -135,7 +138,9 @@ forApiVersions(Fn const& fn, Args&&... args) { constexpr auto size = maxVer + 1 - minVer; [&](std::index_sequence) { - (((void)fn(std::integral_constant{}, std::forward(args)...)), ...); + (((void)fn( + std::integral_constant{}, std::forward(args)...)), + ...); }(std::make_index_sequence{}); } @@ -143,10 +148,12 @@ template void forAllApiVersions(Fn const& fn, Args&&... args) requires requires { - forApiVersions(fn, std::forward(args)...); + forApiVersions( + fn, std::forward(args)...); } { - forApiVersions(fn, std::forward(args)...); + forApiVersions( + fn, std::forward(args)...); } } // namespace xrpl diff --git a/include/xrpl/protocol/ErrorCodes.h b/include/xrpl/protocol/ErrorCodes.h index 08c034e38f..c138d5d39a 100644 --- a/include/xrpl/protocol/ErrorCodes.h +++ b/include/xrpl/protocol/ErrorCodes.h @@ -167,7 +167,8 @@ namespace RPC { 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) + constexpr ErrorInfo() + : code(rpcUNKNOWN), token("unknown"), message("An unknown error code."), http_status(200) { } @@ -176,7 +177,11 @@ struct ErrorInfo { } - constexpr ErrorInfo(error_code_i code_, char const* token_, char const* message_, int http_status_) + constexpr ErrorInfo( + error_code_i code_, + char const* token_, + char const* message_, + int http_status_) : code(code_), token(token_), message(message_), http_status(http_status_) { } diff --git a/include/xrpl/protocol/Feature.h b/include/xrpl/protocol/Feature.h index 6d674fbef2..34d78fc50b 100644 --- a/include/xrpl/protocol/Feature.h +++ b/include/xrpl/protocol/Feature.h @@ -296,7 +296,7 @@ public: friend FeatureBitset operator^(FeatureBitset const& lhs, uint256 const& rhs) { - return lhs ^ FeatureBitset { rhs }; + return lhs ^ FeatureBitset{rhs}; } friend FeatureBitset diff --git a/include/xrpl/protocol/IOUAmount.h b/include/xrpl/protocol/IOUAmount.h index 52c2272da0..2ee453f575 100644 --- a/include/xrpl/protocol/IOUAmount.h +++ b/include/xrpl/protocol/IOUAmount.h @@ -95,7 +95,8 @@ inline IOUAmount::IOUAmount(beast::Zero) *this = beast::zero; } -inline IOUAmount::IOUAmount(mantissa_type mantissa, exponent_type exponent) : mantissa_(mantissa), exponent_(exponent) +inline IOUAmount::IOUAmount(mantissa_type mantissa, exponent_type exponent) + : mantissa_(mantissa), exponent_(exponent) { normalize(); } @@ -110,7 +111,8 @@ IOUAmount::operator=(beast::Zero) return *this; } -inline IOUAmount::operator Number() const +inline IOUAmount:: +operator Number() const { return Number{mantissa_, exponent_}; } @@ -140,7 +142,8 @@ IOUAmount::operator<(IOUAmount const& other) const return Number{*this} < Number{other}; } -inline IOUAmount::operator bool() const noexcept +inline IOUAmount:: +operator bool() const noexcept { return mantissa_ != 0; } diff --git a/include/xrpl/protocol/Indexes.h b/include/xrpl/protocol/Indexes.h index f1e0b1655a..7884905d9e 100644 --- a/include/xrpl/protocol/Indexes.h +++ b/include/xrpl/protocol/Indexes.h @@ -169,7 +169,9 @@ Keylet depositPreauth(AccountID const& owner, AccountID const& preauthorized) noexcept; Keylet -depositPreauth(AccountID const& owner, std::set> const& authCreds) noexcept; +depositPreauth( + AccountID const& owner, + std::set> const& authCreds) noexcept; inline Keylet depositPreauth(uint256 const& key) noexcept diff --git a/include/xrpl/protocol/KnownFormats.h b/include/xrpl/protocol/KnownFormats.h index 67701c91ca..ce14a210ab 100644 --- a/include/xrpl/protocol/KnownFormats.h +++ b/include/xrpl/protocol/KnownFormats.h @@ -98,7 +98,8 @@ public: if (auto const result = findByName(name)) return result->getType(); Throw( - name_ + ": Unknown format name '" + name.substr(0, std::min(name.size(), std::size_t(32))) + "'"); + name_ + ": Unknown format name '" + + name.substr(0, std::min(name.size(), std::size_t(32))) + "'"); } /** Retrieve a format based on its type. @@ -154,7 +155,9 @@ protected: { if (auto const item = findByType(type)) { - LogicError(std::string("Duplicate key for item '") + name + "': already maps to " + item->getName()); + LogicError( + std::string("Duplicate key for item '") + name + "': already maps to " + + item->getName()); } formats_.emplace_front(name, type, uniqueFields, commonFields); diff --git a/include/xrpl/protocol/MPTAmount.h b/include/xrpl/protocol/MPTAmount.h index 66027185b3..5c1642ae5c 100644 --- a/include/xrpl/protocol/MPTAmount.h +++ b/include/xrpl/protocol/MPTAmount.h @@ -93,7 +93,8 @@ MPTAmount::operator=(beast::Zero) } /** Returns true if the amount is not zero */ -constexpr MPTAmount::operator bool() const noexcept +constexpr MPTAmount:: +operator bool() const noexcept { return value_ != 0; } diff --git a/include/xrpl/protocol/MultiApiJson.h b/include/xrpl/protocol/MultiApiJson.h index ad7a6b8f0d..1ebe72f15e 100644 --- a/include/xrpl/protocol/MultiApiJson.h +++ b/include/xrpl/protocol/MultiApiJson.h @@ -86,8 +86,16 @@ struct MultiApiJson template requires std::same_as, MultiApiJson> auto - operator()(Json& json, std::integral_constant const version, Fn fn, Args&&... args) const - -> std::invoke_result_t, Args&&...> + operator()( + Json& json, + std::integral_constant const version, + Fn fn, + Args&&... args) const + -> std::invoke_result_t< + Fn, + decltype(json.val[0]), + std::integral_constant, + Args&&...> { static_assert(valid(Version) && index(Version) >= 0 && index(Version) < size); return std::invoke(fn, json.val[index(Version)], version, std::forward(args)...); @@ -107,7 +115,7 @@ struct MultiApiJson // unsigned int version, extra arguments template requires(!some_integral_constant) && std::convertible_to && - std::same_as, MultiApiJson> + std::same_as, MultiApiJson> auto operator()(Json& json, Version version, Fn fn, Args&&... args) const -> std::invoke_result_t @@ -122,9 +130,10 @@ struct MultiApiJson // unsigned int version, Json only template requires(!some_integral_constant) && std::convertible_to && - std::same_as, MultiApiJson> + std::same_as, MultiApiJson> auto - operator()(Json& json, Version version, Fn fn) const -> std::invoke_result_t + operator()(Json& json, Version version, Fn fn) const + -> std::invoke_result_t { XRPL_ASSERT( valid(version) && index(version) >= 0 && index(version) < size, @@ -137,7 +146,9 @@ struct MultiApiJson visit() { return [self = this](auto... args) - requires requires { visitor(std::declval(), std::declval()...); } + requires requires { + visitor(std::declval(), std::declval()...); + } { return visitor(*self, std::forward(args)...); }; } @@ -145,14 +156,17 @@ struct MultiApiJson visit() const { return [self = this](auto... args) - requires requires { visitor(std::declval(), std::declval()...); } + requires requires { + visitor(std::declval(), std::declval()...); + } { return visitor(*self, std::forward(args)...); }; } template auto visit(Args... args) -> std::invoke_result_t - requires(sizeof...(args) > 0) && requires { visitor(*this, std::forward(args)...); } + requires(sizeof...(args) > 0) && + requires { visitor(*this, std::forward(args)...); } { return visitor(*this, std::forward(args)...); } @@ -160,7 +174,8 @@ struct MultiApiJson template auto visit(Args... args) const -> std::invoke_result_t - requires(sizeof...(args) > 0) && requires { visitor(*this, std::forward(args)...); } + requires(sizeof...(args) > 0) && + requires { visitor(*this, std::forward(args)...); } { return visitor(*this, std::forward(args)...); } @@ -169,6 +184,7 @@ struct MultiApiJson } // namespace detail // Wrapper for Json for all supported API versions. -using MultiApiJson = detail::MultiApiJson; +using MultiApiJson = + detail::MultiApiJson; } // namespace xrpl diff --git a/include/xrpl/protocol/NFTokenID.h b/include/xrpl/protocol/NFTokenID.h index f3635d6fac..4bdacc1095 100644 --- a/include/xrpl/protocol/NFTokenID.h +++ b/include/xrpl/protocol/NFTokenID.h @@ -29,7 +29,10 @@ std::vector getNFTokenIDFromDeletedOffer(TxMeta const& transactionMeta); void -insertNFTokenID(Json::Value& response, std::shared_ptr const& transaction, TxMeta const& transactionMeta); +insertNFTokenID( + Json::Value& response, + std::shared_ptr const& transaction, + TxMeta const& transactionMeta); /** @} */ } // namespace xrpl diff --git a/include/xrpl/protocol/NFTokenOfferID.h b/include/xrpl/protocol/NFTokenOfferID.h index c3117db197..01b0ced638 100644 --- a/include/xrpl/protocol/NFTokenOfferID.h +++ b/include/xrpl/protocol/NFTokenOfferID.h @@ -18,7 +18,9 @@ namespace xrpl { @{ */ bool -canHaveNFTokenOfferID(std::shared_ptr const& serializedTx, TxMeta const& transactionMeta); +canHaveNFTokenOfferID( + std::shared_ptr const& serializedTx, + TxMeta const& transactionMeta); std::optional getOfferIDFromCreatedOffer(TxMeta const& transactionMeta); diff --git a/include/xrpl/protocol/Protocol.h b/include/xrpl/protocol/Protocol.h index dfb2b9dfe8..7ddf43d175 100644 --- a/include/xrpl/protocol/Protocol.h +++ b/include/xrpl/protocol/Protocol.h @@ -114,7 +114,8 @@ namespace Lending { Valid values are between 0 and 10% inclusive. */ -TenthBips16 constexpr maxManagementFeeRate(unsafe_cast(percentageToTenthBips(10).value())); +TenthBips16 constexpr maxManagementFeeRate( + unsafe_cast(percentageToTenthBips(10).value())); static_assert(maxManagementFeeRate == TenthBips16(std::uint16_t(10'000u))); /** The maximum coverage rate required of a loan broker in 1/10 bips. @@ -253,6 +254,16 @@ std::uint8_t constexpr maxAssetCheckDepth = 5; /** A ledger index. */ using LedgerIndex = std::uint32_t; +std::uint32_t constexpr FLAG_LEDGER_INTERVAL = 256; + +/** Returns true if the given ledgerIndex is a voting ledgerIndex */ +bool +isVotingLedger(LedgerIndex seq); + +/** Returns true if the given ledgerIndex is a flag ledgerIndex */ +bool +isFlagLedger(LedgerIndex seq); + /** A transaction identifier. The value is computed as the hash of the canonicalized, serialized transaction object. diff --git a/include/xrpl/protocol/PublicKey.h b/include/xrpl/protocol/PublicKey.h index eff2af6839..e806f6ffeb 100644 --- a/include/xrpl/protocol/PublicKey.h +++ b/include/xrpl/protocol/PublicKey.h @@ -125,7 +125,8 @@ operator==(PublicKey const& lhs, PublicKey const& rhs) inline bool operator<(PublicKey const& lhs, PublicKey const& rhs) { - return std::lexicographical_compare(lhs.data(), lhs.data() + lhs.size(), rhs.data(), rhs.data() + rhs.size()); + return std::lexicographical_compare( + lhs.data(), lhs.data() + lhs.size(), rhs.data(), rhs.data() + rhs.size()); } template diff --git a/include/xrpl/protocol/Quality.h b/include/xrpl/protocol/Quality.h index 4d3fcbfcc0..09b0f4e7cb 100644 --- a/include/xrpl/protocol/Quality.h +++ b/include/xrpl/protocol/Quality.h @@ -114,7 +114,8 @@ public: /** Create a quality from the ratio of two amounts. */ template - explicit Quality(TAmounts const& amount) : Quality(Amounts(toSTAmount(amount.in), toSTAmount(amount.out))) + explicit Quality(TAmounts const& amount) + : Quality(Amounts(toSTAmount(amount.in), toSTAmount(amount.out))) { } @@ -263,7 +264,8 @@ public: friend double relativeDistance(Quality const& q1, Quality const& q2) { - XRPL_ASSERT(q1.m_value > 0 && q2.m_value > 0, "xrpl::Quality::relativeDistance : minimum inputs"); + XRPL_ASSERT( + q1.m_value > 0 && q2.m_value > 0, "xrpl::Quality::relativeDistance : minimum inputs"); if (q1.m_value == q2.m_value) // make expected common case fast return 0; @@ -278,7 +280,8 @@ public: auto const expDiff = exponent(maxV) - exponent(minV); double const minVD = static_cast(minVMantissa); - double const maxVD = expDiff ? maxVMantissa * pow(10, expDiff) : static_cast(maxVMantissa); + double const maxVD = + expDiff ? maxVMantissa * pow(10, expDiff) : static_cast(maxVMantissa); // maxVD and minVD are scaled so they have the same exponents. Dividing // cancels out the exponents, so we only need to deal with the (scaled) @@ -312,7 +315,8 @@ TAmounts Quality::ceil_in(TAmounts const& amount, In const& limit) const { // Construct a function pointer to the function we want to call. - static constexpr Amounts (Quality::*ceil_in_fn_ptr)(Amounts const&, STAmount const&) const = &Quality::ceil_in; + static constexpr Amounts (Quality::*ceil_in_fn_ptr)(Amounts const&, STAmount const&) const = + &Quality::ceil_in; return ceil_TAmounts_helper(amount, limit, amount.in, ceil_in_fn_ptr); } @@ -322,8 +326,8 @@ TAmounts Quality::ceil_in_strict(TAmounts const& amount, In const& limit, bool roundUp) const { // Construct a function pointer to the function we want to call. - static constexpr Amounts (Quality::*ceil_in_fn_ptr)(Amounts const&, STAmount const&, bool) const = - &Quality::ceil_in_strict; + static constexpr Amounts (Quality::*ceil_in_fn_ptr)(Amounts const&, STAmount const&, bool) + const = &Quality::ceil_in_strict; return ceil_TAmounts_helper(amount, limit, amount.in, ceil_in_fn_ptr, roundUp); } @@ -333,7 +337,8 @@ TAmounts Quality::ceil_out(TAmounts const& amount, Out const& limit) const { // Construct a function pointer to the function we want to call. - static constexpr Amounts (Quality::*ceil_out_fn_ptr)(Amounts const&, STAmount const&) const = &Quality::ceil_out; + static constexpr Amounts (Quality::*ceil_out_fn_ptr)(Amounts const&, STAmount const&) const = + &Quality::ceil_out; return ceil_TAmounts_helper(amount, limit, amount.out, ceil_out_fn_ptr); } @@ -343,8 +348,8 @@ TAmounts Quality::ceil_out_strict(TAmounts const& amount, Out const& limit, bool roundUp) const { // Construct a function pointer to the function we want to call. - static constexpr Amounts (Quality::*ceil_out_fn_ptr)(Amounts const&, STAmount const&, bool) const = - &Quality::ceil_out_strict; + static constexpr Amounts (Quality::*ceil_out_fn_ptr)(Amounts const&, STAmount const&, bool) + const = &Quality::ceil_out_strict; return ceil_TAmounts_helper(amount, limit, amount.out, ceil_out_fn_ptr, roundUp); } diff --git a/include/xrpl/protocol/QualityFunction.h b/include/xrpl/protocol/QualityFunction.h index 4f76f4df0a..15865a6e07 100644 --- a/include/xrpl/protocol/QualityFunction.h +++ b/include/xrpl/protocol/QualityFunction.h @@ -67,7 +67,10 @@ public: }; template -QualityFunction::QualityFunction(TAmounts const& amounts, std::uint32_t tfee, QualityFunction::AMMTag) +QualityFunction::QualityFunction( + TAmounts const& amounts, + std::uint32_t tfee, + QualityFunction::AMMTag) { if (amounts.in <= beast::zero || amounts.out <= beast::zero) Throw("QualityFunction amounts are 0."); diff --git a/include/xrpl/protocol/Rules.h b/include/xrpl/protocol/Rules.h index 7d4a458fce..11ca8eb72a 100644 --- a/include/xrpl/protocol/Rules.h +++ b/include/xrpl/protocol/Rules.h @@ -49,7 +49,9 @@ private: makeRulesGivenLedger(DigestAwareReadView const& ledger, Rules const& current); friend Rules - makeRulesGivenLedger(DigestAwareReadView const& ledger, std::unordered_set> const& presets); + makeRulesGivenLedger( + DigestAwareReadView const& ledger, + std::unordered_set> const& presets); Rules( std::unordered_set> const& presets, diff --git a/include/xrpl/protocol/SOTemplate.h b/include/xrpl/protocol/SOTemplate.h index 794fc86c11..576bd8c34a 100644 --- a/include/xrpl/protocol/SOTemplate.h +++ b/include/xrpl/protocol/SOTemplate.h @@ -53,7 +53,10 @@ public: template requires(std::is_same_v || std::is_same_v) - SOElement(TypedField const& fieldName, SOEStyle style, SOETxMPTIssue supportMpt = soeMPTNotSupported) + SOElement( + TypedField const& fieldName, + SOEStyle style, + SOETxMPTIssue supportMpt = soeMPTNotSupported) : sField_(fieldName), style_(style), supportMpt_(supportMpt) { init(fieldName); @@ -97,7 +100,9 @@ public: After creating the template fields cannot be added, modified, or removed. */ - SOTemplate(std::initializer_list uniqueFields, std::initializer_list commonFields = {}); + SOTemplate( + std::initializer_list uniqueFields, + std::initializer_list commonFields = {}); /* Provide for the enumeration of fields */ std::vector::const_iterator diff --git a/include/xrpl/protocol/STAmount.h b/include/xrpl/protocol/STAmount.h index df2b1c19a0..dadeec096f 100644 --- a/include/xrpl/protocol/STAmount.h +++ b/include/xrpl/protocol/STAmount.h @@ -80,7 +80,12 @@ public: unchecked); template - STAmount(A const& asset, mantissa_type mantissa, exponent_type exponent, bool negative, unchecked); + STAmount( + A const& asset, + mantissa_type mantissa, + exponent_type exponent, + bool negative, + unchecked); // Call canonicalize template @@ -300,13 +305,23 @@ STAmount::STAmount( } template -STAmount::STAmount(A const& asset, mantissa_type mantissa, exponent_type exponent, bool negative, unchecked) +STAmount::STAmount( + A const& asset, + mantissa_type mantissa, + exponent_type exponent, + bool negative, + unchecked) : mAsset(asset), mValue(mantissa), mOffset(exponent), mIsNegative(negative) { } template -STAmount::STAmount(SField const& name, A const& asset, std::uint64_t mantissa, int exponent, bool negative) +STAmount::STAmount( + SField const& name, + A const& asset, + std::uint64_t mantissa, + int exponent, + bool negative) : STBase(name), mAsset(asset), mValue(mantissa), mOffset(exponent), mIsNegative(negative) { // mValue is uint64, but needs to fit in the range of int64 @@ -326,7 +341,8 @@ STAmount::STAmount(SField const& name, A const& asset, std::uint64_t mantissa, i } template -STAmount::STAmount(A const& asset, std::int64_t mantissa, int exponent) : mAsset(asset), mOffset(exponent) +STAmount::STAmount(A const& asset, std::int64_t mantissa, int exponent) + : mAsset(asset), mOffset(exponent) { set(mantissa); canonicalize(); @@ -480,12 +496,14 @@ STAmount::zeroed() const return STAmount(mAsset); } -inline STAmount::operator bool() const noexcept +inline STAmount:: +operator bool() const noexcept { return *this != beast::zero; } -inline STAmount::operator Number() const +inline STAmount:: +operator Number() const { if (native()) return xrp(); @@ -658,7 +676,10 @@ getRate(STAmount const& offerOut, STAmount const& offerIn); * */ [[nodiscard]] STAmount -roundToScale(STAmount const& value, std::int32_t scale, Number::rounding_mode rounding = Number::getround()); +roundToScale( + STAmount const& value, + std::int32_t scale, + Number::rounding_mode rounding = Number::getround()); /** Round an arbitrary precision Number IN PLACE to the precision of a given * Asset. diff --git a/include/xrpl/protocol/STArray.h b/include/xrpl/protocol/STArray.h index d9c5306d14..045b682f88 100644 --- a/include/xrpl/protocol/STArray.h +++ b/include/xrpl/protocol/STArray.h @@ -23,12 +23,14 @@ public: template < class Iter, - class = std::enable_if_t::reference, STObject>>> + class = std::enable_if_t< + std::is_convertible_v::reference, STObject>>> explicit STArray(Iter first, Iter last); template < class Iter, - class = std::enable_if_t::reference, STObject>>> + class = std::enable_if_t< + std::is_convertible_v::reference, STObject>>> STArray(SField const& f, Iter first, Iter last); STArray& diff --git a/include/xrpl/protocol/STBitString.h b/include/xrpl/protocol/STBitString.h index e8b6e7282b..7bd270a98c 100644 --- a/include/xrpl/protocol/STBitString.h +++ b/include/xrpl/protocol/STBitString.h @@ -83,7 +83,8 @@ inline STBitString::STBitString(SField const& n, value_type const& v) : ST } template -inline STBitString::STBitString(SerialIter& sit, SField const& name) : STBitString(name, sit.getBitString()) +inline STBitString::STBitString(SerialIter& sit, SField const& name) + : STBitString(name, sit.getBitString()) { } @@ -169,7 +170,8 @@ STBitString::value() const } template -STBitString::operator value_type() const +STBitString:: +operator value_type() const { return value_; } diff --git a/include/xrpl/protocol/STBlob.h b/include/xrpl/protocol/STBlob.h index 15a9bd5f78..71d1a04478 100644 --- a/include/xrpl/protocol/STBlob.h +++ b/include/xrpl/protocol/STBlob.h @@ -68,11 +68,13 @@ private: friend class detail::STVar; }; -inline STBlob::STBlob(STBlob const& rhs) : STBase(rhs), CountedObject(rhs), value_(rhs.data(), rhs.size()) +inline STBlob::STBlob(STBlob const& rhs) + : STBase(rhs), CountedObject(rhs), value_(rhs.data(), rhs.size()) { } -inline STBlob::STBlob(SField const& f, void const* data, std::size_t size) : STBase(f), value_(data, size) +inline STBlob::STBlob(SField const& f, void const* data, std::size_t size) + : STBase(f), value_(data, size) { } diff --git a/include/xrpl/protocol/STInteger.h b/include/xrpl/protocol/STInteger.h index b5c4dbf6cf..f4bbd6e73d 100644 --- a/include/xrpl/protocol/STInteger.h +++ b/include/xrpl/protocol/STInteger.h @@ -134,7 +134,8 @@ STInteger::setValue(Integer v) } template -inline STInteger::operator Integer() const +inline STInteger:: +operator Integer() const { return value_; } diff --git a/include/xrpl/protocol/STLedgerEntry.h b/include/xrpl/protocol/STLedgerEntry.h index 6ba3b36c6b..dde7d49ebd 100644 --- a/include/xrpl/protocol/STLedgerEntry.h +++ b/include/xrpl/protocol/STLedgerEntry.h @@ -55,7 +55,11 @@ public: isThreadedType(Rules const& rules) const; bool - thread(uint256 const& txID, std::uint32_t ledgerSeq, uint256& prevTxID, std::uint32_t& prevLedgerID); + thread( + uint256 const& txID, + std::uint32_t ledgerSeq, + uint256& prevTxID, + std::uint32_t& prevLedgerID); private: /* Make STObject comply with the template for this SLE type @@ -77,11 +81,13 @@ private: using SLE = STLedgerEntry; -inline STLedgerEntry::STLedgerEntry(LedgerEntryType type, uint256 const& key) : STLedgerEntry(Keylet(type, key)) +inline STLedgerEntry::STLedgerEntry(LedgerEntryType type, uint256 const& key) + : STLedgerEntry(Keylet(type, key)) { } -inline STLedgerEntry::STLedgerEntry(SerialIter&& sit, uint256 const& index) : STLedgerEntry(sit, index) +inline STLedgerEntry::STLedgerEntry(SerialIter&& sit, uint256 const& index) + : STLedgerEntry(sit, index) { } diff --git a/include/xrpl/protocol/STObject.h b/include/xrpl/protocol/STObject.h index 5d5d829c99..09eff8c3d2 100644 --- a/include/xrpl/protocol/STObject.h +++ b/include/xrpl/protocol/STObject.h @@ -147,9 +147,12 @@ public: int getCount() const; - bool setFlag(std::uint32_t); - bool clearFlag(std::uint32_t); - bool isFlag(std::uint32_t) const; + bool + setFlag(std::uint32_t); + bool + clearFlag(std::uint32_t); + bool + isFlag(std::uint32_t) const; std::uint32_t getFlags() const; @@ -431,8 +434,8 @@ private: // by value. template < typename T, - typename V = - typename std::remove_cv().value())>::type>::type> + typename V = typename std::remove_cv< + typename std::remove_reference().value())>::type>::type> V getFieldByValue(SField const& field) const; @@ -507,10 +510,14 @@ protected: // Constraint += and -= ValueProxy operators // to value types that support arithmetic operations template -concept IsArithmeticNumber = std::is_arithmetic_v || std::is_same_v || std::is_same_v; -template -concept IsArithmeticValueUnit = - std::is_same_v> && IsArithmeticNumber && std::is_class_v; +concept IsArithmeticNumber = + std::is_arithmetic_v || std::is_same_v || std::is_same_v; +template < + typename U, + typename Value = typename U::value_type, + typename Unit = typename U::unit_type> +concept IsArithmeticValueUnit = std::is_same_v> && + IsArithmeticNumber && std::is_class_v; template concept IsArithmeticST = !IsArithmeticValueUnit && IsArithmeticNumber; template @@ -519,7 +526,8 @@ concept IsArithmetic = IsArithmeticNumber || IsArithmeticST || IsArithmeti template concept Addable = requires(T t, U u) { t = t + u; }; template -concept IsArithmeticCompatible = IsArithmetic && Addable; +concept IsArithmeticCompatible = + IsArithmetic && Addable; template class STObject::ValueProxy : public Proxy @@ -799,7 +807,8 @@ STObject::ValueProxy::operator-=(U const& u) } template -STObject::ValueProxy::operator value_type() const +STObject::ValueProxy:: +operator value_type() const { return this->value(); } @@ -812,13 +821,15 @@ STObject::ValueProxy::ValueProxy(STObject* st, TypedField const* f) : Prox //------------------------------------------------------------------------------ template -STObject::OptionalProxy::operator bool() const noexcept +STObject::OptionalProxy:: +operator bool() const noexcept { return engaged(); } template -STObject::OptionalProxy::operator typename STObject::OptionalProxy::optional_type() const +STObject::OptionalProxy:: +operator typename STObject::OptionalProxy::optional_type() const { return optional_value(); } @@ -1050,12 +1061,15 @@ STObject::at(TypedField const& f) const return u->value(); XRPL_ASSERT(mType, "xrpl::STObject::at(TypedField auto) : field template non-null"); - XRPL_ASSERT(b->getSType() == STI_NOTPRESENT, "xrpl::STObject::at(TypedField auto) : type not present"); + XRPL_ASSERT( + b->getSType() == STI_NOTPRESENT, "xrpl::STObject::at(TypedField auto) : type not present"); if (mType->style(f) == soeOPTIONAL) Throw("Missing optional field: " + f.getName()); - XRPL_ASSERT(mType->style(f) == soeDEFAULT, "xrpl::STObject::at(TypedField auto) : template style is default"); + XRPL_ASSERT( + mType->style(f) == soeDEFAULT, + "xrpl::STObject::at(TypedField auto) : template style is default"); // Used to help handle the case where value_type is a const reference, // otherwise we would return the address of a temporary. @@ -1077,7 +1091,9 @@ STObject::at(OptionaledField const& of) const mType, "xrpl::STObject::at(OptionaledField auto) : field template " "non-null"); - XRPL_ASSERT(b->getSType() == STI_NOTPRESENT, "xrpl::STObject::at(OptionaledField auto) : type not present"); + XRPL_ASSERT( + b->getSType() == STI_NOTPRESENT, + "xrpl::STObject::at(OptionaledField auto) : type not present"); if (mType->style(*of.f) == soeOPTIONAL) return std::nullopt; XRPL_ASSERT( diff --git a/include/xrpl/protocol/STPathSet.h b/include/xrpl/protocol/STPathSet.h index 1bab654d3f..2ccbc3d657 100644 --- a/include/xrpl/protocol/STPathSet.h +++ b/include/xrpl/protocol/STPathSet.h @@ -49,7 +49,11 @@ public: AccountID const& issuer, bool forceCurrency = false); - STPathElement(unsigned int uType, AccountID const& account, Currency const& currency, AccountID const& issuer); + STPathElement( + unsigned int uType, + AccountID const& account, + Currency const& currency, + AccountID const& issuer); auto getNodeType() const; @@ -230,7 +234,8 @@ inline STPathElement::STPathElement( is_offer_ = false; mAccountID = *account; mType |= typeAccount; - XRPL_ASSERT(mAccountID != noAccount(), "xrpl::STPathElement::STPathElement : account is set"); + XRPL_ASSERT( + mAccountID != noAccount(), "xrpl::STPathElement::STPathElement : account is set"); } if (currency) @@ -254,7 +259,11 @@ inline STPathElement::STPathElement( Currency const& currency, AccountID const& issuer, bool forceCurrency) - : mType(typeNone), mAccountID(account), mCurrencyID(currency), mIssuerID(issuer), is_offer_(isXRP(mAccountID)) + : mType(typeNone) + , mAccountID(account) + , mCurrencyID(currency) + , mIssuerID(issuer) + , is_offer_(isXRP(mAccountID)) { if (!is_offer_) mType |= typeAccount; @@ -273,7 +282,11 @@ inline STPathElement::STPathElement( AccountID const& account, Currency const& currency, AccountID const& issuer) - : mType(uType), mAccountID(account), mCurrencyID(currency), mIssuerID(issuer), is_offer_(isXRP(mAccountID)) + : mType(uType) + , mAccountID(account) + , mCurrencyID(currency) + , mIssuerID(issuer) + , is_offer_(isXRP(mAccountID)) { hash_value_ = get_hash(*this); } diff --git a/include/xrpl/protocol/STTx.h b/include/xrpl/protocol/STTx.h index a12c658dc2..72bd38d5d6 100644 --- a/include/xrpl/protocol/STTx.h +++ b/include/xrpl/protocol/STTx.h @@ -119,7 +119,11 @@ public: getMetaSQL(std::uint32_t inLedger, std::string const& escapedMetaData) const; std::string - getMetaSQL(Serializer rawTxn, std::uint32_t inLedger, char status, std::string const& escapedMetaData) const; + getMetaSQL( + Serializer rawTxn, + std::uint32_t inLedger, + char status, + std::string const& escapedMetaData) const; std::vector const& getBatchTransactionIDs() const; diff --git a/include/xrpl/protocol/STValidation.h b/include/xrpl/protocol/STValidation.h index aa48161f68..861e2152f8 100644 --- a/include/xrpl/protocol/STValidation.h +++ b/include/xrpl/protocol/STValidation.h @@ -64,7 +64,12 @@ public: @param f callback function to "fill" the validation with necessary data */ template - STValidation(NetClock::time_point signTime, PublicKey const& pk, SecretKey const& sk, NodeID const& nodeID, F&& f); + STValidation( + NetClock::time_point signTime, + PublicKey const& pk, + SecretKey const& sk, + NodeID const& nodeID, + F&& f); // Hash of the validated ledger uint256 @@ -117,10 +122,13 @@ public: render() const { std::stringstream ss; - ss << "validation: " << " ledger_hash: " << getLedgerHash() << " consensus_hash: " << getConsensusHash() - << " sign_time: " << to_string(getSignTime()) << " seen_time: " << to_string(getSeenTime()) - << " signer_public_key: " << getSignerPublic() << " node_id: " << getNodeID() << " is_valid: " << isValid() - << " is_full: " << isFull() << " is_trusted: " << isTrusted() << " signing_hash: " << getSigningHash() + ss << "validation: " << " ledger_hash: " << getLedgerHash() + << " consensus_hash: " << getConsensusHash() + << " sign_time: " << to_string(getSignTime()) + << " seen_time: " << to_string(getSeenTime()) + << " signer_public_key: " << getSignerPublic() << " node_id: " << getNodeID() + << " is_valid: " << isValid() << " is_full: " << isFull() + << " is_trusted: " << isTrusted() << " signing_hash: " << getSigningHash() << " base58: " << toBase58(TokenType::NodePublic, getSignerPublic()); return ss.str(); } @@ -152,7 +160,8 @@ STValidation::STValidation(SerialIter& sit, LookupNodeID&& lookupNodeID, bool ch { if (checkSignature && !isValid()) { - JLOG(debugLog().error()) << "Invalid signature in validation: " << getJson(JsonOptions::none); + JLOG(debugLog().error()) << "Invalid signature in validation: " + << getJson(JsonOptions::none); Throw("Invalid signature in validation"); } @@ -174,7 +183,10 @@ STValidation::STValidation( SecretKey const& sk, NodeID const& nodeID, F&& f) - : STObject(validationFormat(), sfValidation), signingPubKey_(pk), nodeID_(nodeID), seenTime_(signTime) + : STObject(validationFormat(), sfValidation) + , signingPubKey_(pk) + , nodeID_(nodeID) + , seenTime_(signTime) { XRPL_ASSERT( nodeID_.isNonZero(), diff --git a/include/xrpl/protocol/STVector256.h b/include/xrpl/protocol/STVector256.h index c83d981bfc..dd77067b7c 100644 --- a/include/xrpl/protocol/STVector256.h +++ b/include/xrpl/protocol/STVector256.h @@ -110,7 +110,8 @@ inline STVector256::STVector256(std::vector const& vector) : mValue(vec { } -inline STVector256::STVector256(SField const& n, std::vector const& vector) : STBase(n), mValue(vector) +inline STVector256::STVector256(SField const& n, std::vector const& vector) + : STBase(n), mValue(vector) { } @@ -135,7 +136,8 @@ STVector256::setValue(STVector256 const& v) } /** Retrieve a copy of the vector we contain */ -inline STVector256::operator std::vector() const +inline STVector256:: +operator std::vector() const { return mValue; } diff --git a/include/xrpl/protocol/STXChainBridge.h b/include/xrpl/protocol/STXChainBridge.h index 709d3886b7..f74cc02041 100644 --- a/include/xrpl/protocol/STXChainBridge.h +++ b/include/xrpl/protocol/STXChainBridge.h @@ -114,15 +114,31 @@ private: inline bool operator==(STXChainBridge const& lhs, STXChainBridge const& rhs) { - return std::tie(lhs.lockingChainDoor_, lhs.lockingChainIssue_, lhs.issuingChainDoor_, lhs.issuingChainIssue_) == - std::tie(rhs.lockingChainDoor_, rhs.lockingChainIssue_, rhs.issuingChainDoor_, rhs.issuingChainIssue_); + return std::tie( + lhs.lockingChainDoor_, + lhs.lockingChainIssue_, + lhs.issuingChainDoor_, + lhs.issuingChainIssue_) == + std::tie( + rhs.lockingChainDoor_, + rhs.lockingChainIssue_, + rhs.issuingChainDoor_, + rhs.issuingChainIssue_); } inline bool operator<(STXChainBridge const& lhs, STXChainBridge const& rhs) { - return std::tie(lhs.lockingChainDoor_, lhs.lockingChainIssue_, lhs.issuingChainDoor_, lhs.issuingChainIssue_) < - std::tie(rhs.lockingChainDoor_, rhs.lockingChainIssue_, rhs.issuingChainDoor_, rhs.issuingChainIssue_); + return std::tie( + lhs.lockingChainDoor_, + lhs.lockingChainIssue_, + lhs.issuingChainDoor_, + lhs.issuingChainIssue_) < + std::tie( + rhs.lockingChainDoor_, + rhs.lockingChainIssue_, + rhs.issuingChainDoor_, + rhs.issuingChainIssue_); } inline AccountID const& diff --git a/include/xrpl/protocol/Sign.h b/include/xrpl/protocol/Sign.h index 9f0bf2f1ca..0b5b5d7239 100644 --- a/include/xrpl/protocol/Sign.h +++ b/include/xrpl/protocol/Sign.h @@ -19,7 +19,12 @@ namespace xrpl { @note If a signature already exists, it is overwritten. */ void -sign(STObject& st, HashPrefix const& prefix, KeyType type, SecretKey const& sk, SF_VL const& sigField = sfSignature); +sign( + STObject& st, + HashPrefix const& prefix, + KeyType type, + SecretKey const& sk, + SF_VL const& sigField = sfSignature); /** Returns `true` if STObject contains valid signature @@ -30,7 +35,11 @@ sign(STObject& st, HashPrefix const& prefix, KeyType type, SecretKey const& sk, If not specified the value defaults to `sfSignature`. */ bool -verify(STObject const& st, HashPrefix const& prefix, PublicKey const& pk, SF_VL const& sigField = sfSignature); +verify( + STObject const& st, + HashPrefix const& prefix, + PublicKey const& pk, + SF_VL const& sigField = sfSignature); /** Return a Serializer suitable for computing a multisigning TxnSignature. */ Serializer diff --git a/include/xrpl/protocol/TER.h b/include/xrpl/protocol/TER.h index 52001ce72b..64201881b0 100644 --- a/include/xrpl/protocol/TER.h +++ b/include/xrpl/protocol/TER.h @@ -416,7 +416,9 @@ public: } // Trait tells enable_if which types are allowed for construction. - template >>::value>> + template < + typename T, + typename = std::enable_if_t>>::value>> constexpr TERSubset(T rhs) : code_(TERtoInt(rhs)) { } @@ -484,60 +486,60 @@ public: // Only enabled if both arguments return int if TERtiInt is called with them. template constexpr auto -operator==(L const& lhs, R const& rhs) - -> std::enable_if_t< - std::is_same::value && std::is_same::value, - bool> +operator==(L const& lhs, R const& rhs) -> std::enable_if_t< + std::is_same::value && + std::is_same::value, + bool> { return TERtoInt(lhs) == TERtoInt(rhs); } template constexpr auto -operator!=(L const& lhs, R const& rhs) - -> std::enable_if_t< - std::is_same::value && std::is_same::value, - bool> +operator!=(L const& lhs, R const& rhs) -> std::enable_if_t< + std::is_same::value && + std::is_same::value, + bool> { return TERtoInt(lhs) != TERtoInt(rhs); } template constexpr auto -operator<(L const& lhs, R const& rhs) - -> std::enable_if_t< - std::is_same::value && std::is_same::value, - bool> +operator<(L const& lhs, R const& rhs) -> std::enable_if_t< + std::is_same::value && + std::is_same::value, + bool> { return TERtoInt(lhs) < TERtoInt(rhs); } template constexpr auto -operator<=(L const& lhs, R const& rhs) - -> std::enable_if_t< - std::is_same::value && std::is_same::value, - bool> +operator<=(L const& lhs, R const& rhs) -> std::enable_if_t< + std::is_same::value && + std::is_same::value, + bool> { return TERtoInt(lhs) <= TERtoInt(rhs); } template constexpr auto -operator>(L const& lhs, R const& rhs) - -> std::enable_if_t< - std::is_same::value && std::is_same::value, - bool> +operator>(L const& lhs, R const& rhs) -> std::enable_if_t< + std::is_same::value && + std::is_same::value, + bool> { return TERtoInt(lhs) > TERtoInt(rhs); } template constexpr auto -operator>=(L const& lhs, R const& rhs) - -> std::enable_if_t< - std::is_same::value && std::is_same::value, - bool> +operator>=(L const& lhs, R const& rhs) -> std::enable_if_t< + std::is_same::value && + std::is_same::value, + bool> { return TERtoInt(lhs) >= TERtoInt(rhs); } diff --git a/include/xrpl/protocol/Units.h b/include/xrpl/protocol/Units.h index ecf0bf7798..b377c80e26 100644 --- a/include/xrpl/protocol/Units.h +++ b/include/xrpl/protocol/Units.h @@ -35,8 +35,8 @@ class TenthBipsTag; // namespace. template -concept Valid = - std::is_class_v && std::is_object_v && std::is_object_v; +concept Valid = std::is_class_v && std::is_object_v && + std::is_object_v; /** `Usable` is checked to ensure that only values with known valid type tags can be used (sometimes transparently) in @@ -47,12 +47,15 @@ concept Valid = */ template concept Usable = Valid && - (std::is_same_v || std::is_same_v || - std::is_same_v || std::is_same_v || + (std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v || std::is_same_v); template -concept Compatible = Valid && std::is_arithmetic_v && std::is_arithmetic_v && +concept Compatible = + Valid && std::is_arithmetic_v && std::is_arithmetic_v && std::is_convertible_v; template @@ -62,8 +65,8 @@ template concept IntegralValue = Integral; template -concept CastableValue = - IntegralValue && IntegralValue && std::is_same_v; +concept CastableValue = IntegralValue && IntegralValue && + std::is_same_v; template class ValueUnit : private boost::totally_ordered>, @@ -292,7 +295,8 @@ public: { if constexpr (std::is_integral_v) { - using jsontype = std::conditional_t, Json::Int, Json::UInt>; + using jsontype = + std::conditional_t, Json::Int, Json::UInt>; constexpr auto min = std::numeric_limits::min(); constexpr auto max = std::numeric_limits::max(); @@ -343,7 +347,8 @@ to_string(ValueUnit const& amount) } template -concept muldivSource = Valid && std::is_convertible_v; +concept muldivSource = + Valid && std::is_convertible_v; template concept muldivDest = muldivSource && // Dest is also a source @@ -359,8 +364,8 @@ concept muldivable = muldivSources && muldivDest; // Source and Dest can be the same by default template -concept muldivCommutable = - muldivable && !std::is_same_v; +concept muldivCommutable = muldivable && + !std::is_same_v; template ValueUnit @@ -400,7 +405,10 @@ mulDivU(Source1 value, Dest mul, Source2 div) using namespace boost::multiprecision; uint128_t product; - product = multiply(product, static_cast(value.value()), static_cast(mul.value())); + product = multiply( + product, + static_cast(value.value()), + static_cast(mul.value())); auto quotient = product / div.value(); diff --git a/include/xrpl/protocol/XChainAttestations.h b/include/xrpl/protocol/XChainAttestations.h index fc3c464b92..06eff0fcf2 100644 --- a/include/xrpl/protocol/XChainAttestations.h +++ b/include/xrpl/protocol/XChainAttestations.h @@ -339,7 +339,9 @@ struct XChainCreateAccountAttestation match(MatchFields const& rhs) const; friend bool - operator==(XChainCreateAccountAttestation const& lhs, XChainCreateAccountAttestation const& rhs); + operator==( + XChainCreateAccountAttestation const& lhs, + XChainCreateAccountAttestation const& rhs); }; // Attestations from witness servers for a particular claim ID and bridge. @@ -408,7 +410,9 @@ public: template [[nodiscard]] inline bool -operator==(XChainAttestationsBase const& lhs, XChainAttestationsBase const& rhs) +operator==( + XChainAttestationsBase const& lhs, + XChainAttestationsBase const& rhs) { return lhs.attestations() == rhs.attestations(); } @@ -456,7 +460,8 @@ class XChainClaimAttestations final : public XChainAttestationsBase +class XChainCreateAccountAttestations final + : public XChainAttestationsBase { using TBase = XChainAttestationsBase; using TBase::TBase; diff --git a/include/xrpl/protocol/XRPAmount.h b/include/xrpl/protocol/XRPAmount.h index c1af338e4b..6e4133361b 100644 --- a/include/xrpl/protocol/XRPAmount.h +++ b/include/xrpl/protocol/XRPAmount.h @@ -166,7 +166,8 @@ public: std::optional dropsAs() const { - if ((drops_ > std::numeric_limits::max()) || (!std::numeric_limits::is_signed && drops_ < 0) || + if ((drops_ > std::numeric_limits::max()) || + (!std::numeric_limits::is_signed && drops_ < 0) || (std::numeric_limits::is_signed && drops_ < std::numeric_limits::lowest())) { return std::nullopt; diff --git a/include/xrpl/protocol/detail/b58_utils.h b/include/xrpl/protocol/detail/b58_utils.h index a34104555e..adb889ee53 100644 --- a/include/xrpl/protocol/detail/b58_utils.h +++ b/include/xrpl/protocol/detail/b58_utils.h @@ -122,7 +122,8 @@ inplace_bigint_div_rem(std::span numerator, std::uint64_t divisor) unsigned __int128 const low128 = low; return ((high128 << 64) | low128); }; - auto div_rem_64 = [](unsigned __int128 num, std::uint64_t denom) -> std::tuple { + auto div_rem_64 = [](unsigned __int128 num, + std::uint64_t denom) -> std::tuple { unsigned __int128 const denom128 = denom; unsigned __int128 const d = num / denom128; unsigned __int128 const r = num - (denom128 * d); diff --git a/include/xrpl/protocol/detail/transactions.macro b/include/xrpl/protocol/detail/transactions.macro index bc7eefedb5..b696a1d1c2 100644 --- a/include/xrpl/protocol/detail/transactions.macro +++ b/include/xrpl/protocol/detail/transactions.macro @@ -8,11 +8,11 @@ * To ease maintenance, you may replace any unneeded values with "..." * e.g. #define TRANSACTION(tag, value, name, ...) * - * You must define a transactor class in the `ripple` namespace named `name`, + * You must define a transactor class in the `xrpl` namespace named `name`, * and include its header alongside the TRANSACTOR definition using this * format: * #if TRANSACTION_INCLUDE - * # include + * # include * #endif * * The `privileges` parameter of the TRANSACTION macro is a bitfield @@ -22,7 +22,7 @@ /** This transaction type executes a payment. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttPAYMENT, 0, Payment, Delegation::delegable, @@ -42,7 +42,7 @@ TRANSACTION(ttPAYMENT, 0, Payment, /** This transaction type creates an escrow object. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttESCROW_CREATE, 1, EscrowCreate, Delegation::delegable, @@ -73,7 +73,7 @@ TRANSACTION(ttESCROW_FINISH, 2, EscrowFinish, /** This transaction type adjusts various account settings. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttACCOUNT_SET, 3, AccountSet, Delegation::notDelegable, @@ -94,7 +94,7 @@ TRANSACTION(ttACCOUNT_SET, 3, AccountSet, /** This transaction type cancels an existing escrow. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttESCROW_CANCEL, 4, EscrowCancel, Delegation::delegable, @@ -107,7 +107,7 @@ TRANSACTION(ttESCROW_CANCEL, 4, EscrowCancel, /** This transaction type sets or clears an account's "regular key". */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttREGULAR_KEY_SET, 5, SetRegularKey, Delegation::notDelegable, @@ -121,7 +121,7 @@ TRANSACTION(ttREGULAR_KEY_SET, 5, SetRegularKey, /** This transaction type creates an offer to trade one asset for another. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttOFFER_CREATE, 7, OfferCreate, Delegation::delegable, @@ -137,7 +137,7 @@ TRANSACTION(ttOFFER_CREATE, 7, OfferCreate, /** This transaction type cancels existing offers to trade one asset for another. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttOFFER_CANCEL, 8, OfferCancel, Delegation::delegable, @@ -151,7 +151,7 @@ TRANSACTION(ttOFFER_CANCEL, 8, OfferCancel, /** This transaction type creates a new set of tickets. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttTICKET_CREATE, 10, TicketCreate, Delegation::delegable, @@ -167,7 +167,7 @@ TRANSACTION(ttTICKET_CREATE, 10, TicketCreate, // The SignerEntries are optional because a SignerList is deleted by // setting the SignerQuorum to zero and omitting SignerEntries. #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttSIGNER_LIST_SET, 12, SignerListSet, Delegation::notDelegable, @@ -180,7 +180,7 @@ TRANSACTION(ttSIGNER_LIST_SET, 12, SignerListSet, /** This transaction type creates a new unidirectional XRP payment channel. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttPAYCHAN_CREATE, 13, PaymentChannelCreate, Delegation::delegable, @@ -222,7 +222,7 @@ TRANSACTION(ttPAYCHAN_CLAIM, 15, PaymentChannelClaim, /** This transaction type creates a new check. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttCHECK_CREATE, 16, CheckCreate, Delegation::delegable, @@ -238,7 +238,7 @@ TRANSACTION(ttCHECK_CREATE, 16, CheckCreate, /** This transaction type cashes an existing check. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttCHECK_CASH, 17, CheckCash, Delegation::delegable, @@ -252,7 +252,7 @@ TRANSACTION(ttCHECK_CASH, 17, CheckCash, /** This transaction type cancels an existing check. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttCHECK_CANCEL, 18, CheckCancel, Delegation::delegable, @@ -264,7 +264,7 @@ TRANSACTION(ttCHECK_CANCEL, 18, CheckCancel, /** This transaction type grants or revokes authorization to transfer funds. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttDEPOSIT_PREAUTH, 19, DepositPreauth, Delegation::delegable, @@ -279,7 +279,7 @@ TRANSACTION(ttDEPOSIT_PREAUTH, 19, DepositPreauth, /** This transaction type modifies a trustline between two accounts. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttTRUST_SET, 20, TrustSet, Delegation::delegable, @@ -293,7 +293,7 @@ TRANSACTION(ttTRUST_SET, 20, TrustSet, /** This transaction type deletes an existing account. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttACCOUNT_DELETE, 21, AccountDelete, Delegation::notDelegable, @@ -309,7 +309,7 @@ TRANSACTION(ttACCOUNT_DELETE, 21, AccountDelete, /** This transaction mints a new NFT. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttNFTOKEN_MINT, 25, NFTokenMint, Delegation::delegable, @@ -327,7 +327,7 @@ TRANSACTION(ttNFTOKEN_MINT, 25, NFTokenMint, /** This transaction burns (i.e. destroys) an existing NFT. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttNFTOKEN_BURN, 26, NFTokenBurn, Delegation::delegable, @@ -340,7 +340,7 @@ TRANSACTION(ttNFTOKEN_BURN, 26, NFTokenBurn, /** This transaction creates a new offer to buy or sell an NFT. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttNFTOKEN_CREATE_OFFER, 27, NFTokenCreateOffer, Delegation::delegable, @@ -356,7 +356,7 @@ TRANSACTION(ttNFTOKEN_CREATE_OFFER, 27, NFTokenCreateOffer, /** This transaction cancels an existing offer to buy or sell an existing NFT. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttNFTOKEN_CANCEL_OFFER, 28, NFTokenCancelOffer, Delegation::delegable, @@ -368,7 +368,7 @@ TRANSACTION(ttNFTOKEN_CANCEL_OFFER, 28, NFTokenCancelOffer, /** This transaction accepts an existing offer to buy or sell an existing NFT. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttNFTOKEN_ACCEPT_OFFER, 29, NFTokenAcceptOffer, Delegation::delegable, @@ -382,7 +382,7 @@ TRANSACTION(ttNFTOKEN_ACCEPT_OFFER, 29, NFTokenAcceptOffer, /** This transaction claws back issued tokens. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttCLAWBACK, 30, Clawback, Delegation::delegable, @@ -395,7 +395,7 @@ TRANSACTION(ttCLAWBACK, 30, Clawback, /** This transaction claws back tokens from an AMM pool. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttAMM_CLAWBACK, 31, AMMClawback, Delegation::delegable, @@ -410,7 +410,7 @@ TRANSACTION(ttAMM_CLAWBACK, 31, AMMClawback, /** This transaction type creates an AMM instance */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttAMM_CREATE, 35, AMMCreate, Delegation::delegable, @@ -424,7 +424,7 @@ TRANSACTION(ttAMM_CREATE, 35, AMMCreate, /** This transaction type deposits into an AMM instance */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttAMM_DEPOSIT, 36, AMMDeposit, Delegation::delegable, @@ -442,7 +442,7 @@ TRANSACTION(ttAMM_DEPOSIT, 36, AMMDeposit, /** This transaction type withdraws from an AMM instance */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttAMM_WITHDRAW, 37, AMMWithdraw, Delegation::delegable, @@ -459,7 +459,7 @@ TRANSACTION(ttAMM_WITHDRAW, 37, AMMWithdraw, /** This transaction type votes for the trading fee */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttAMM_VOTE, 38, AMMVote, Delegation::delegable, @@ -473,7 +473,7 @@ TRANSACTION(ttAMM_VOTE, 38, AMMVote, /** This transaction type bids for the auction slot */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttAMM_BID, 39, AMMBid, Delegation::delegable, @@ -489,7 +489,7 @@ TRANSACTION(ttAMM_BID, 39, AMMBid, /** This transaction type deletes AMM in the empty state */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttAMM_DELETE, 40, AMMDelete, Delegation::delegable, @@ -502,7 +502,7 @@ TRANSACTION(ttAMM_DELETE, 40, AMMDelete, /** This transactions creates a crosschain sequence number */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttXCHAIN_CREATE_CLAIM_ID, 41, XChainCreateClaimID, Delegation::delegable, @@ -617,7 +617,7 @@ TRANSACTION(ttXCHAIN_CREATE_BRIDGE, 48, XChainCreateBridge, /** This transaction type creates or updates a DID */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttDID_SET, 49, DIDSet, Delegation::delegable, @@ -638,7 +638,7 @@ TRANSACTION(ttDID_DELETE, 50, DIDDelete, /** This transaction type creates an Oracle instance */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttORACLE_SET, 51, OracleSet, Delegation::delegable, @@ -655,7 +655,7 @@ TRANSACTION(ttORACLE_SET, 51, OracleSet, /** This transaction type deletes an Oracle instance */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttORACLE_DELETE, 52, OracleDelete, Delegation::delegable, @@ -667,7 +667,7 @@ TRANSACTION(ttORACLE_DELETE, 52, OracleDelete, /** This transaction type fixes a problem in the ledger state */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttLEDGER_STATE_FIX, 53, LedgerStateFix, Delegation::delegable, @@ -680,7 +680,7 @@ TRANSACTION(ttLEDGER_STATE_FIX, 53, LedgerStateFix, /** This transaction type creates a MPTokensIssuance instance */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttMPTOKEN_ISSUANCE_CREATE, 54, MPTokenIssuanceCreate, Delegation::delegable, @@ -697,7 +697,7 @@ TRANSACTION(ttMPTOKEN_ISSUANCE_CREATE, 54, MPTokenIssuanceCreate, /** This transaction type destroys a MPTokensIssuance instance */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttMPTOKEN_ISSUANCE_DESTROY, 55, MPTokenIssuanceDestroy, Delegation::delegable, @@ -709,7 +709,7 @@ TRANSACTION(ttMPTOKEN_ISSUANCE_DESTROY, 55, MPTokenIssuanceDestroy, /** This transaction type sets flags on a MPTokensIssuance or MPToken instance */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttMPTOKEN_ISSUANCE_SET, 56, MPTokenIssuanceSet, Delegation::delegable, @@ -726,7 +726,7 @@ TRANSACTION(ttMPTOKEN_ISSUANCE_SET, 56, MPTokenIssuanceSet, /** This transaction type authorizes a MPToken instance */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttMPTOKEN_AUTHORIZE, 57, MPTokenAuthorize, Delegation::delegable, @@ -739,7 +739,7 @@ TRANSACTION(ttMPTOKEN_AUTHORIZE, 57, MPTokenAuthorize, /** This transaction type create an Credential instance */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttCREDENTIAL_CREATE, 58, CredentialCreate, Delegation::delegable, @@ -775,7 +775,7 @@ TRANSACTION(ttCREDENTIAL_DELETE, 60, CredentialDelete, /** This transaction type modify a NFToken */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttNFTOKEN_MODIFY, 61, NFTokenModify, Delegation::delegable, @@ -789,7 +789,7 @@ TRANSACTION(ttNFTOKEN_MODIFY, 61, NFTokenModify, /** This transaction type creates or modifies a Permissioned Domain */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttPERMISSIONED_DOMAIN_SET, 62, PermissionedDomainSet, Delegation::delegable, @@ -802,7 +802,7 @@ TRANSACTION(ttPERMISSIONED_DOMAIN_SET, 62, PermissionedDomainSet, /** This transaction type deletes a Permissioned Domain */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttPERMISSIONED_DOMAIN_DELETE, 63, PermissionedDomainDelete, Delegation::delegable, @@ -814,7 +814,7 @@ TRANSACTION(ttPERMISSIONED_DOMAIN_DELETE, 63, PermissionedDomainDelete, /** This transaction type delegates authorized account specified permissions */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttDELEGATE_SET, 64, DelegateSet, Delegation::notDelegable, @@ -827,7 +827,7 @@ TRANSACTION(ttDELEGATE_SET, 64, DelegateSet, /** This transaction creates a single asset vault. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttVAULT_CREATE, 65, VaultCreate, Delegation::delegable, @@ -845,7 +845,7 @@ TRANSACTION(ttVAULT_CREATE, 65, VaultCreate, /** This transaction updates a single asset vault. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttVAULT_SET, 66, VaultSet, Delegation::delegable, @@ -860,7 +860,7 @@ TRANSACTION(ttVAULT_SET, 66, VaultSet, /** This transaction deletes a single asset vault. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttVAULT_DELETE, 67, VaultDelete, Delegation::delegable, @@ -872,7 +872,7 @@ TRANSACTION(ttVAULT_DELETE, 67, VaultDelete, /** This transaction trades assets for shares with a vault. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttVAULT_DEPOSIT, 68, VaultDeposit, Delegation::delegable, @@ -885,7 +885,7 @@ TRANSACTION(ttVAULT_DEPOSIT, 68, VaultDeposit, /** This transaction trades shares for assets with a vault. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttVAULT_WITHDRAW, 69, VaultWithdraw, Delegation::delegable, @@ -900,7 +900,7 @@ TRANSACTION(ttVAULT_WITHDRAW, 69, VaultWithdraw, /** This transaction claws back tokens from a vault. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttVAULT_CLAWBACK, 70, VaultClawback, Delegation::delegable, @@ -914,7 +914,7 @@ TRANSACTION(ttVAULT_CLAWBACK, 70, VaultClawback, /** This transaction type batches together transactions. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttBATCH, 71, Batch, Delegation::notDelegable, @@ -929,7 +929,7 @@ TRANSACTION(ttBATCH, 71, Batch, /** This transaction creates and updates a Loan Broker */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttLOAN_BROKER_SET, 74, LoanBrokerSet, Delegation::delegable, @@ -946,7 +946,7 @@ TRANSACTION(ttLOAN_BROKER_SET, 74, LoanBrokerSet, /** This transaction deletes a Loan Broker */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttLOAN_BROKER_DELETE, 75, LoanBrokerDelete, Delegation::delegable, @@ -957,7 +957,7 @@ TRANSACTION(ttLOAN_BROKER_DELETE, 75, LoanBrokerDelete, /** This transaction deposits First Loss Capital into a Loan Broker */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttLOAN_BROKER_COVER_DEPOSIT, 76, LoanBrokerCoverDeposit, Delegation::delegable, @@ -969,7 +969,7 @@ TRANSACTION(ttLOAN_BROKER_COVER_DEPOSIT, 76, LoanBrokerCoverDeposit, /** This transaction withdraws First Loss Capital from a Loan Broker */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttLOAN_BROKER_COVER_WITHDRAW, 77, LoanBrokerCoverWithdraw, Delegation::delegable, @@ -984,7 +984,7 @@ TRANSACTION(ttLOAN_BROKER_COVER_WITHDRAW, 77, LoanBrokerCoverWithdraw, /** This transaction claws back First Loss Capital from a Loan Broker to the issuer of the capital */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttLOAN_BROKER_COVER_CLAWBACK, 78, LoanBrokerCoverClawback, Delegation::delegable, @@ -996,7 +996,7 @@ TRANSACTION(ttLOAN_BROKER_COVER_CLAWBACK, 78, LoanBrokerCoverClawback, /** This transaction creates a Loan */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttLOAN_SET, 80, LoanSet, Delegation::delegable, @@ -1023,7 +1023,7 @@ TRANSACTION(ttLOAN_SET, 80, LoanSet, /** This transaction deletes an existing Loan */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttLOAN_DELETE, 81, LoanDelete, Delegation::delegable, @@ -1034,7 +1034,7 @@ TRANSACTION(ttLOAN_DELETE, 81, LoanDelete, /** This transaction is used to change the delinquency status of an existing Loan */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttLOAN_MANAGE, 82, LoanManage, Delegation::delegable, @@ -1048,7 +1048,7 @@ TRANSACTION(ttLOAN_MANAGE, 82, LoanManage, /** The Borrower uses this transaction to make a Payment on the Loan. */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttLOAN_PAY, 84, LoanPay, Delegation::delegable, @@ -1063,7 +1063,7 @@ TRANSACTION(ttLOAN_PAY, 84, LoanPay, For details, see: https://xrpl.org/amendments.html */ #if TRANSACTION_INCLUDE -# include +# include #endif TRANSACTION(ttAMENDMENT, 100, EnableAmendment, Delegation::notDelegable, diff --git a/include/xrpl/protocol/json_get_or_throw.h b/include/xrpl/protocol/json_get_or_throw.h index 7cdf481ad3..336d875450 100644 --- a/include/xrpl/protocol/json_get_or_throw.h +++ b/include/xrpl/protocol/json_get_or_throw.h @@ -34,7 +34,8 @@ struct JsonTypeMismatchError : std::exception char const* const key; std::string const expectedType; mutable std::string msg; - JsonTypeMismatchError(Json::StaticString const& k, std::string et) : key{k.c_str()}, expectedType{std::move(et)} + JsonTypeMismatchError(Json::StaticString const& k, std::string et) + : key{k.c_str()}, expectedType{std::move(et)} { } char const* @@ -42,7 +43,8 @@ struct JsonTypeMismatchError : std::exception { if (msg.empty()) { - msg = std::string("Type mismatch on json key: ") + key + "; expected type: " + expectedType; + msg = std::string("Type mismatch on json key: ") + key + + "; expected type: " + expectedType; } return msg.c_str(); } diff --git a/include/xrpl/protocol/nftPageMask.h b/include/xrpl/protocol/nftPageMask.h index 05a42ce294..2f7337c328 100644 --- a/include/xrpl/protocol/nftPageMask.h +++ b/include/xrpl/protocol/nftPageMask.h @@ -9,7 +9,8 @@ namespace nft { // NFT directory pages order their contents based only on the low 96 bits of // the NFToken value. This mask provides easy access to the necessary mask. -uint256 constexpr pageMask(std::string_view("0000000000000000000000000000000000000000ffffffffffffffffffffffff")); +uint256 constexpr pageMask( + std::string_view("0000000000000000000000000000000000000000ffffffffffffffffffffffff")); } // namespace nft } // namespace xrpl diff --git a/include/xrpl/protocol/tokens.h b/include/xrpl/protocol/tokens.h index 8cda8efc86..043db02825 100644 --- a/include/xrpl/protocol/tokens.h +++ b/include/xrpl/protocol/tokens.h @@ -74,7 +74,10 @@ namespace b58_fast { // Use the fast version (10-15x faster) is using gcc extensions (int128 in // particular) [[nodiscard]] B58Result> -encodeBase58Token(TokenType token_type, std::span input, std::span out); +encodeBase58Token( + TokenType token_type, + std::span input, + std::span out); [[nodiscard]] B58Result> decodeBase58Token(TokenType type, std::string_view s, std::span outBuf); diff --git a/include/xrpl/rdb/DatabaseCon.h b/include/xrpl/rdb/DatabaseCon.h index 37a53044e4..d1fb7114e3 100644 --- a/include/xrpl/rdb/DatabaseCon.h +++ b/include/xrpl/rdb/DatabaseCon.h @@ -27,10 +27,12 @@ private: std::unique_lock lock_; public: - LockedSociSession(std::shared_ptr it, mutex& m) : session_(std::move(it)), lock_(m) + LockedSociSession(std::shared_ptr it, mutex& m) + : session_(std::move(it)), lock_(m) { } - LockedSociSession(LockedSociSession&& rhs) noexcept : session_(std::move(rhs.session_)), lock_(std::move(rhs.lock_)) + LockedSociSession(LockedSociSession&& rhs) noexcept + : session_(std::move(rhs.session_)), lock_(std::move(rhs.lock_)) { } LockedSociSession() = delete; @@ -104,7 +106,8 @@ public: beast::Journal journal) // Use temporary files or regular DB files? : DatabaseCon( - setup.standAlone && setup.startUp != StartUpType::LOAD && setup.startUp != StartUpType::LOAD_FILE && + setup.standAlone && setup.startUp != StartUpType::LOAD && + setup.startUp != StartUpType::LOAD_FILE && setup.startUp != StartUpType::REPLAY ? "" : (setup.dataDir / dbName), @@ -166,8 +169,8 @@ public: checkoutDb() { using namespace std::chrono_literals; - LockedSociSession session = - perf::measureDurationAndLog([&]() { return LockedSociSession(session_, lock_); }, "checkoutDb", 10ms, j_); + LockedSociSession session = perf::measureDurationAndLog( + [&]() { return LockedSociSession(session_, lock_); }, "checkoutDb", 10ms, j_); return session; } diff --git a/include/xrpl/rdb/RelationalDatabase.h b/include/xrpl/rdb/RelationalDatabase.h index b80c6c8331..e728e518aa 100644 --- a/include/xrpl/rdb/RelationalDatabase.h +++ b/include/xrpl/rdb/RelationalDatabase.h @@ -414,7 +414,10 @@ public: * default error code is not changed. */ virtual std::variant - getTransaction(uint256 const& id, std::optional> const& range, error_code_i& ec) = 0; + getTransaction( + uint256 const& id, + std::optional> const& range, + error_code_i& ec) = 0; /** * @brief getKBUsedAll Returns the amount of space used by all databases. @@ -464,7 +467,8 @@ rangeCheckedCast(C c) // LCOV_EXCL_START UNREACHABLE("xrpl::rangeCheckedCast : domain error"); JLOG(debugLog().error()) << "rangeCheckedCast domain error:" - << " value = " << c << " min = " << std::numeric_limits::lowest() + << " value = " << c + << " min = " << std::numeric_limits::lowest() << " max: " << std::numeric_limits::max(); // LCOV_EXCL_STOP } diff --git a/include/xrpl/resource/ResourceManager.h b/include/xrpl/resource/ResourceManager.h index c04e7bb79b..4aab017691 100644 --- a/include/xrpl/resource/ResourceManager.h +++ b/include/xrpl/resource/ResourceManager.h @@ -27,7 +27,10 @@ public: virtual Consumer newInboundEndpoint(beast::IP::Endpoint const& address) = 0; virtual Consumer - newInboundEndpoint(beast::IP::Endpoint const& address, bool const proxy, std::string_view forwardedFor) = 0; + newInboundEndpoint( + beast::IP::Endpoint const& address, + bool const proxy, + std::string_view forwardedFor) = 0; /** Create a new endpoint keyed by outbound IP address and port. */ virtual Consumer diff --git a/include/xrpl/resource/detail/Logic.h b/include/xrpl/resource/detail/Logic.h index 066e416550..9a7959f481 100644 --- a/include/xrpl/resource/detail/Logic.h +++ b/include/xrpl/resource/detail/Logic.h @@ -68,7 +68,10 @@ private: //-------------------------------------------------------------------------- public: - Logic(beast::insight::Collector::ptr const& collector, clock_type& clock, beast::Journal journal) + Logic( + beast::insight::Collector::ptr const& collector, + clock_type& clock, + beast::Journal journal) : m_stats(collector), m_clock(clock), m_journal(journal) { } @@ -340,7 +343,8 @@ public: Import& import(iter->second); if (iter->second.whenExpires <= elapsed) { - for (auto item_iter(import.items.begin()); item_iter != import.items.end(); ++item_iter) + for (auto item_iter(import.items.begin()); item_iter != import.items.end(); + ++item_iter) { item_iter->consumer.entry().remote_balance -= item_iter->balance; } @@ -422,7 +426,8 @@ public: static constexpr Charge::value_type feeLogAsWarn = 3000; static constexpr Charge::value_type feeLogAsInfo = 1000; static constexpr Charge::value_type feeLogAsDebug = 100; - static_assert(feeLogAsWarn > feeLogAsInfo && feeLogAsInfo > feeLogAsDebug && feeLogAsDebug > 10); + static_assert( + feeLogAsWarn > feeLogAsInfo && feeLogAsInfo > feeLogAsDebug && feeLogAsDebug > 10); static auto getStream = [](Resource::Charge::value_type cost, beast::Journal& journal) { if (cost >= feeLogAsWarn) @@ -479,8 +484,8 @@ public: int const balance(entry.balance(now)); if (balance >= dropThreshold) { - JLOG(m_journal.warn()) << "Consumer entry " << entry << " dropped with balance " << balance - << " at or above drop threshold " << dropThreshold; + JLOG(m_journal.warn()) << "Consumer entry " << entry << " dropped with balance " + << balance << " at or above drop threshold " << dropThreshold; // Adding feeDrop at this point keeps the dropped connection // from re-connecting for at least a little while after it is @@ -502,7 +507,10 @@ public: //-------------------------------------------------------------------------- void - writeList(clock_type::time_point const now, beast::PropertyStream::Set& items, EntryIntrusiveList& list) + writeList( + clock_type::time_point const now, + beast::PropertyStream::Set& items, + EntryIntrusiveList& list) { for (auto& entry : list) { diff --git a/src/xrpld/rpc/InfoSub.h b/include/xrpl/server/InfoSub.h similarity index 95% rename from src/xrpld/rpc/InfoSub.h rename to include/xrpl/server/InfoSub.h index d49e401bd3..97cdf1aa35 100644 --- a/src/xrpld/rpc/InfoSub.h +++ b/include/xrpl/server/InfoSub.h @@ -62,7 +62,10 @@ public: // for use during InfoSub destruction // Removes only from the server virtual void - unsubAccountInternal(std::uint64_t uListener, hash_set const& vnaAccountIDs, bool realTime) = 0; + unsubAccountInternal( + std::uint64_t uListener, + hash_set const& vnaAccountIDs, + bool realTime) = 0; /** * subscribe an account's new transactions and retrieve the account's @@ -84,7 +87,10 @@ public: unsubAccountHistory(ref ispListener, AccountID const& account, bool historyOnly) = 0; virtual void - unsubAccountHistoryInternal(std::uint64_t uListener, AccountID const& account, bool historyOnly) = 0; + unsubAccountHistoryInternal( + std::uint64_t uListener, + AccountID const& account, + bool historyOnly) = 0; // VFALCO TODO Document the bool return value virtual bool @@ -131,6 +137,7 @@ public: virtual bool subPeerStatus(ref ispListener) = 0; + virtual bool unsubPeerStatus(std::uint64_t uListener) = 0; virtual void diff --git a/src/xrpld/app/misc/LoadFeeTrack.h b/include/xrpl/server/LoadFeeTrack.h similarity index 94% rename from src/xrpld/app/misc/LoadFeeTrack.h rename to include/xrpl/server/LoadFeeTrack.h index 8eb53187ce..fc031a1833 100644 --- a/src/xrpld/app/misc/LoadFeeTrack.h +++ b/include/xrpl/server/LoadFeeTrack.h @@ -83,7 +83,8 @@ public: std::lock_guard sl(lock_); return std::make_pair( - std::max(localTxnLoadFee_, remoteTxnLoadFee_), std::max(remoteTxnLoadFee_, clusterTxnLoadFee_)); + std::max(localTxnLoadFee_, remoteTxnLoadFee_), + std::max(remoteTxnLoadFee_, clusterTxnLoadFee_)); } void @@ -110,7 +111,8 @@ public: isLoadedCluster() const { std::lock_guard sl(lock_); - return (raiseCount_ != 0) || (localTxnLoadFee_ != lftNormalFee) || (clusterTxnLoadFee_ != lftNormalFee); + return (raiseCount_ != 0) || (localTxnLoadFee_ != lftNormalFee) || + (clusterTxnLoadFee_ != lftNormalFee); } private: diff --git a/include/xrpl/server/Manifest.h b/include/xrpl/server/Manifest.h index 79426a1a46..7f1bba921e 100644 --- a/include/xrpl/server/Manifest.h +++ b/include/xrpl/server/Manifest.h @@ -85,7 +85,11 @@ struct Manifest std::optional const& signingKey_, std::uint32_t seq, std::string const& domain_) - : serialized(serialized_), masterKey(masterKey_), signingKey(signingKey_), sequence(seq), domain(domain_) + : serialized(serialized_) + , masterKey(masterKey_) + , signingKey(signingKey_) + , sequence(seq) + , domain(domain_) { } @@ -141,14 +145,20 @@ std::optional deserializeManifest(Slice s, beast::Journal journal); inline std::optional -deserializeManifest(std::string const& s, beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) +deserializeManifest( + std::string const& s, + beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) { return deserializeManifest(makeSlice(s), journal); } -template ::value || std::is_same::value>> +template < + class T, + class = std::enable_if_t::value || std::is_same::value>> std::optional -deserializeManifest(std::vector const& v, beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) +deserializeManifest( + std::vector const& v, + beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) { return deserializeManifest(makeSlice(v), journal); } @@ -159,8 +169,9 @@ operator==(Manifest const& lhs, Manifest const& rhs) { // In theory, comparing the two serialized strings should be // sufficient. - return lhs.sequence == rhs.sequence && lhs.masterKey == rhs.masterKey && lhs.signingKey == rhs.signingKey && - lhs.domain == rhs.domain && lhs.serialized == rhs.serialized; + return lhs.sequence == rhs.sequence && lhs.masterKey == rhs.masterKey && + lhs.signingKey == rhs.signingKey && lhs.domain == rhs.domain && + lhs.serialized == rhs.serialized; } inline bool @@ -368,7 +379,10 @@ public: May be called concurrently */ void - save(DatabaseCon& dbCon, std::string const& dbTable, std::function const& isTrusted); + save( + DatabaseCon& dbCon, + std::string const& dbTable, + std::function const& isTrusted); /** Invokes the callback once for every populated manifest. diff --git a/src/xrpld/app/misc/NetworkOPs.h b/include/xrpl/server/NetworkOPs.h similarity index 90% rename from src/xrpld/app/misc/NetworkOPs.h rename to include/xrpl/server/NetworkOPs.h index 66c915008a..75f1e0e1b2 100644 --- a/src/xrpld/app/misc/NetworkOPs.h +++ b/include/xrpl/server/NetworkOPs.h @@ -1,13 +1,12 @@ #pragma once -#include -#include -#include - #include -#include +#include #include +#include #include +#include +#include #include @@ -19,10 +18,13 @@ namespace xrpl { // Master operational handler, server sequencer, network tracker class Peer; +class STTx; +class ReadView; class LedgerMaster; class Transaction; class ValidatorKeys; class CanonicalTXSet; +class RCLCxPeerPos; // This is the primary interface into the "client" portion of the program. // Code that wants to do normal operations on the network such as @@ -114,7 +116,11 @@ public: * @param failType fail_hard setting from transaction submission. */ virtual void - processTransaction(std::shared_ptr& transaction, bool bUnlimited, bool bLocal, FailHard failType) = 0; + processTransaction( + std::shared_ptr& transaction, + bool bUnlimited, + bool bLocal, + FailHard failType) = 0; /** * Process a set of transactions synchronously, and ensuring that they are @@ -245,20 +251,4 @@ public: stateAccounting(Json::Value& obj) = 0; }; -//------------------------------------------------------------------------------ - -std::unique_ptr -make_NetworkOPs( - Application& app, - NetworkOPs::clock_type& clock, - bool standalone, - std::size_t minPeerCount, - bool start_valid, - JobQueue& job_queue, - LedgerMaster& ledgerMaster, - ValidatorKeys const& validatorKeys, - boost::asio::io_context& io_svc, - beast::Journal journal, - beast::insight::Collector::ptr const& collector); - } // namespace xrpl diff --git a/include/xrpl/server/Session.h b/include/xrpl/server/Session.h index 37cbf59775..f7146c3b00 100644 --- a/include/xrpl/server/Session.h +++ b/include/xrpl/server/Session.h @@ -63,7 +63,8 @@ public: void write(BufferSequence const& buffers) { - for (typename BufferSequence::const_iterator iter(buffers.begin()); iter != buffers.end(); ++iter) + for (typename BufferSequence::const_iterator iter(buffers.begin()); iter != buffers.end(); + ++iter) { typename BufferSequence::value_type const& buffer(*iter); write(buffer.data(), boost::asio::buffer_size(buffer)); diff --git a/include/xrpl/server/Wallet.h b/include/xrpl/server/Wallet.h index dcfbada8eb..29b28c41a1 100644 --- a/include/xrpl/server/Wallet.h +++ b/include/xrpl/server/Wallet.h @@ -35,7 +35,11 @@ makeTestWalletDB(DatabaseCon::Setup const& setup, std::string const& dbname, bea * @param j Journal. */ void -getManifests(soci::session& session, std::string const& dbTable, ManifestCache& mCache, beast::Journal j); +getManifests( + soci::session& session, + std::string const& dbTable, + ManifestCache& mCache, + beast::Journal j); /** * @brief saveManifests Saves all given manifests to the database. @@ -95,7 +99,10 @@ getPeerReservationTable(soci::session& session, beast::Journal j); * @param description Description of the node. */ void -insertPeerReservation(soci::session& session, PublicKey const& nodeId, std::string const& description); +insertPeerReservation( + soci::session& session, + PublicKey const& nodeId, + std::string const& description); /** * @brief deletePeerReservation Deletes an entry from the peer reservation @@ -140,6 +147,10 @@ readAmendments( * @param vote Whether to vote in favor of this amendment. */ void -voteAmendment(soci::session& session, uint256 const& amendment, std::string const& name, AmendmentVote vote); +voteAmendment( + soci::session& session, + uint256 const& amendment, + std::string const& name, + AmendmentVote vote); } // namespace xrpl diff --git a/include/xrpl/server/detail/BaseHTTPPeer.h b/include/xrpl/server/detail/BaseHTTPPeer.h index ab85cb7c89..f900261b84 100644 --- a/include/xrpl/server/detail/BaseHTTPPeer.h +++ b/include/xrpl/server/detail/BaseHTTPPeer.h @@ -198,7 +198,8 @@ BaseHTTPPeer::BaseHTTPPeer( , remote_address_(remote_address) , journal_(journal) { - read_buf_.commit(boost::asio::buffer_copy(read_buf_.prepare(boost::asio::buffer_size(buffers)), buffers)); + read_buf_.commit( + boost::asio::buffer_copy(read_buf_.prepare(boost::asio::buffer_size(buffers)), buffers)); static std::atomic sid; nid_ = ++sid; id_ = std::string("#") + std::to_string(nid_) + " "; @@ -218,7 +219,10 @@ void BaseHTTPPeer::close() { if (!strand_.running_in_this_thread()) - return post(strand_, std::bind((void(BaseHTTPPeer::*)(void)) & BaseHTTPPeer::close, impl().shared_from_this())); + return post( + strand_, + std::bind( + (void (BaseHTTPPeer::*)(void))&BaseHTTPPeer::close, impl().shared_from_this())); boost::beast::get_lowest_layer(impl().stream_).close(); } @@ -242,7 +246,8 @@ BaseHTTPPeer::start_timer() { boost::beast::get_lowest_layer(impl().stream_) .expires_after( - std::chrono::seconds(remote_address_.address().is_loopback() ? timeoutSecondsLocal : timeoutSeconds)); + std::chrono::seconds( + remote_address_.address().is_loopback() ? timeoutSecondsLocal : timeoutSeconds)); } // Convenience for discarding the error code @@ -313,19 +318,29 @@ BaseHTTPPeer::on_write(error_code const& ec, std::size_t bytes_tr bind_executor( strand_, std::bind( - &BaseHTTPPeer::on_write, impl().shared_from_this(), std::placeholders::_1, std::placeholders::_2))); + &BaseHTTPPeer::on_write, + impl().shared_from_this(), + std::placeholders::_1, + std::placeholders::_2))); } if (!complete_) return; if (graceful_) return do_close(); util::spawn( - strand_, std::bind(&BaseHTTPPeer::do_read, impl().shared_from_this(), std::placeholders::_1)); + strand_, + std::bind( + &BaseHTTPPeer::do_read, + impl().shared_from_this(), + std::placeholders::_1)); } template void -BaseHTTPPeer::do_writer(std::shared_ptr const& writer, bool keep_alive, yield_context do_yield) +BaseHTTPPeer::do_writer( + std::shared_ptr const& writer, + bool keep_alive, + yield_context do_yield) { std::function resume; { @@ -333,7 +348,12 @@ BaseHTTPPeer::do_writer(std::shared_ptr const& writer, bo resume = std::function([this, p, writer, keep_alive]() { util::spawn( strand_, - std::bind(&BaseHTTPPeer::do_writer, p, writer, keep_alive, std::placeholders::_1)); + std::bind( + &BaseHTTPPeer::do_writer, + p, + writer, + keep_alive, + std::placeholders::_1)); }); } @@ -342,8 +362,8 @@ BaseHTTPPeer::do_writer(std::shared_ptr const& writer, bo if (!writer->prepare(bufferSize, resume)) return; error_code ec; - auto const bytes_transferred = - boost::asio::async_write(impl().stream_, writer->data(), boost::asio::transfer_at_least(1), do_yield[ec]); + auto const bytes_transferred = boost::asio::async_write( + impl().stream_, writer->data(), boost::asio::transfer_at_least(1), do_yield[ec]); if (ec) return fail(ec, "writer"); writer->consume(bytes_transferred); @@ -355,7 +375,11 @@ BaseHTTPPeer::do_writer(std::shared_ptr const& writer, bo return do_close(); util::spawn( - strand_, std::bind(&BaseHTTPPeer::do_read, impl().shared_from_this(), std::placeholders::_1)); + strand_, + std::bind( + &BaseHTTPPeer::do_read, + impl().shared_from_this(), + std::placeholders::_1)); } //------------------------------------------------------------------------------ @@ -374,7 +398,9 @@ BaseHTTPPeer::write(void const* buf, std::size_t bytes) }()) { if (!strand_.running_in_this_thread()) - return post(strand_, std::bind(&BaseHTTPPeer::on_write, impl().shared_from_this(), error_code{}, 0)); + return post( + strand_, + std::bind(&BaseHTTPPeer::on_write, impl().shared_from_this(), error_code{}, 0)); else return on_write(error_code{}, 0); } @@ -410,7 +436,8 @@ void BaseHTTPPeer::complete() { if (!strand_.running_in_this_thread()) - return post(strand_, std::bind(&BaseHTTPPeer::complete, impl().shared_from_this())); + return post( + strand_, std::bind(&BaseHTTPPeer::complete, impl().shared_from_this())); message_ = {}; complete_ = true; @@ -423,7 +450,11 @@ BaseHTTPPeer::complete() // keep-alive util::spawn( - strand_, std::bind(&BaseHTTPPeer::do_read, impl().shared_from_this(), std::placeholders::_1)); + strand_, + std::bind( + &BaseHTTPPeer::do_read, + impl().shared_from_this(), + std::placeholders::_1)); } // DEPRECATED @@ -436,7 +467,7 @@ BaseHTTPPeer::close(bool graceful) return post( strand_, std::bind( - (void(BaseHTTPPeer::*)(bool)) & BaseHTTPPeer::close, + (void (BaseHTTPPeer::*)(bool))&BaseHTTPPeer::close, impl().shared_from_this(), graceful)); diff --git a/include/xrpl/server/detail/BaseWSPeer.h b/include/xrpl/server/detail/BaseWSPeer.h index ab985dfac5..f415520e59 100644 --- a/include/xrpl/server/detail/BaseWSPeer.h +++ b/include/xrpl/server/detail/BaseWSPeer.h @@ -48,7 +48,8 @@ private: bool ping_active_ = false; boost::beast::websocket::ping_data payload_; error_code ec_; - std::function control_callback_; + std::function + control_callback_; public: template @@ -174,16 +175,20 @@ BaseWSPeer::run() impl().ws_.set_option(port().pmd_options); // Must manage the control callback memory outside of the `control_callback` // function - control_callback_ = std::bind(&BaseWSPeer::on_ping_pong, this, std::placeholders::_1, std::placeholders::_2); + control_callback_ = + std::bind(&BaseWSPeer::on_ping_pong, this, std::placeholders::_1, std::placeholders::_2); impl().ws_.control_callback(control_callback_); start_timer(); close_on_timer_ = true; - impl().ws_.set_option(boost::beast::websocket::stream_base::decorator( - [](auto& res) { res.set(boost::beast::http::field::server, BuildInfo::getFullVersionString()); })); + impl().ws_.set_option(boost::beast::websocket::stream_base::decorator([](auto& res) { + res.set(boost::beast::http::field::server, BuildInfo::getFullVersionString()); + })); impl().ws_.async_accept( request_, bind_executor( - strand_, std::bind(&BaseWSPeer::on_ws_handshake, impl().shared_from_this(), std::placeholders::_1))); + strand_, + std::bind( + &BaseWSPeer::on_ws_handshake, impl().shared_from_this(), std::placeholders::_1))); } template @@ -227,9 +232,11 @@ BaseWSPeer::close(boost::beast::websocket::close_reason const& re if (wq_.empty()) { impl().ws_.async_close( - reason, bind_executor(strand_, [self = impl().shared_from_this()](boost::beast::error_code const& ec) { - self->on_close(ec); - })); + reason, + bind_executor( + strand_, [self = impl().shared_from_this()](boost::beast::error_code const& ec) { + self->on_close(ec); + })); } else { @@ -272,7 +279,8 @@ BaseWSPeer::on_write(error_code const& ec) if (ec) return fail(ec, "write"); auto& w = *wq_.front(); - auto const result = w.prepare(65536, std::bind(&BaseWSPeer::do_write, impl().shared_from_this())); + auto const result = + w.prepare(65536, std::bind(&BaseWSPeer::do_write, impl().shared_from_this())); if (boost::indeterminate(result.first)) return; start_timer(); @@ -280,13 +288,18 @@ BaseWSPeer::on_write(error_code const& ec) impl().ws_.async_write_some( static_cast(result.first), result.second, - bind_executor(strand_, std::bind(&BaseWSPeer::on_write, impl().shared_from_this(), std::placeholders::_1))); + bind_executor( + strand_, + std::bind( + &BaseWSPeer::on_write, impl().shared_from_this(), std::placeholders::_1))); else impl().ws_.async_write_some( static_cast(result.first), result.second, bind_executor( - strand_, std::bind(&BaseWSPeer::on_write_fin, impl().shared_from_this(), std::placeholders::_1))); + strand_, + std::bind( + &BaseWSPeer::on_write_fin, impl().shared_from_this(), std::placeholders::_1))); } template @@ -300,7 +313,10 @@ BaseWSPeer::on_write_fin(error_code const& ec) { impl().ws_.async_close( cr_, - bind_executor(strand_, std::bind(&BaseWSPeer::on_close, impl().shared_from_this(), std::placeholders::_1))); + bind_executor( + strand_, + std::bind( + &BaseWSPeer::on_close, impl().shared_from_this(), std::placeholders::_1))); } else if (!wq_.empty()) on_write({}); @@ -313,7 +329,10 @@ BaseWSPeer::do_read() if (!strand_.running_in_this_thread()) return post(strand_, std::bind(&BaseWSPeer::do_read, impl().shared_from_this())); impl().ws_.async_read( - rb_, bind_executor(strand_, std::bind(&BaseWSPeer::on_read, impl().shared_from_this(), std::placeholders::_1))); + rb_, + bind_executor( + strand_, + std::bind(&BaseWSPeer::on_read, impl().shared_from_this(), std::placeholders::_1))); } template @@ -357,7 +376,11 @@ BaseWSPeer::start_timer() } timer_.async_wait(bind_executor( - strand_, std::bind(&BaseWSPeer::on_timer, impl().shared_from_this(), std::placeholders::_1))); + strand_, + std::bind( + &BaseWSPeer::on_timer, + impl().shared_from_this(), + std::placeholders::_1))); } // Convenience for discarding the error code @@ -389,7 +412,9 @@ BaseWSPeer::on_ping(error_code const& ec) template void -BaseWSPeer::on_ping_pong(boost::beast::websocket::frame_type kind, boost::beast::string_view payload) +BaseWSPeer::on_ping_pong( + boost::beast::websocket::frame_type kind, + boost::beast::string_view payload) { if (kind == boost::beast::websocket::frame_type::pong) { @@ -424,7 +449,9 @@ BaseWSPeer::on_timer(error_code ec) impl().ws_.async_ping( payload_, bind_executor( - strand_, std::bind(&BaseWSPeer::on_ping, impl().shared_from_this(), std::placeholders::_1))); + strand_, + std::bind( + &BaseWSPeer::on_ping, impl().shared_from_this(), std::placeholders::_1))); JLOG(this->j_.trace()) << "sent ping"; return; } diff --git a/include/xrpl/server/detail/Door.h b/include/xrpl/server/detail/Door.h index e41049f203..f977dc6002 100644 --- a/include/xrpl/server/detail/Door.h +++ b/include/xrpl/server/detail/Door.h @@ -136,7 +136,11 @@ public: private: template void - create(bool ssl, ConstBufferSequence const& buffers, stream_type&& stream, endpoint_type remote_address); + create( + bool ssl, + ConstBufferSequence const& buffers, + stream_type&& stream, + endpoint_type remote_address); void do_accept(yield_context yield); @@ -165,7 +169,8 @@ template void Door::Detector::run() { - util::spawn(strand_, std::bind(&Detector::do_detect, this->shared_from_this(), std::placeholders::_1)); + util::spawn( + strand_, std::bind(&Detector::do_detect, this->shared_from_this(), std::placeholders::_1)); } template @@ -258,7 +263,11 @@ Door::reOpen() } template -Door::Door(Handler& handler, boost::asio::io_context& io_context, Port const& port, beast::Journal j) +Door::Door( + Handler& handler, + boost::asio::io_context& io_context, + Port const& port, + beast::Journal j) : j_(j) , port_(port) , handler_(handler) @@ -266,9 +275,11 @@ Door::Door(Handler& handler, boost::asio::io_context& io_context, Port , acceptor_(io_context) , strand_(boost::asio::make_strand(io_context)) , ssl_( - port_.protocol.count("https") > 0 || port_.protocol.count("wss") > 0 || port_.protocol.count("wss2") > 0 || - port_.protocol.count("peer") > 0) - , plain_(port_.protocol.count("http") > 0 || port_.protocol.count("ws") > 0 || port_.protocol.count("ws2")) + port_.protocol.count("https") > 0 || port_.protocol.count("wss") > 0 || + port_.protocol.count("wss2") > 0 || port_.protocol.count("peer") > 0) + , plain_( + port_.protocol.count("http") > 0 || port_.protocol.count("ws") > 0 || + port_.protocol.count("ws2")) , backoff_timer_(io_context) { reOpen(); @@ -278,7 +289,9 @@ template void Door::run() { - util::spawn(strand_, std::bind(&Door::do_accept, this->shared_from_this(), std::placeholders::_1)); + util::spawn( + strand_, + std::bind(&Door::do_accept, this->shared_from_this(), std::placeholders::_1)); } template @@ -286,7 +299,8 @@ void Door::close() { if (!strand_.running_in_this_thread()) - return boost::asio::post(strand_, std::bind(&Door::close, this->shared_from_this())); + return boost::asio::post( + strand_, std::bind(&Door::close, this->shared_from_this())); backoff_timer_.cancel(); error_code ec; acceptor_.close(ec); @@ -297,7 +311,11 @@ Door::close() template template void -Door::create(bool ssl, ConstBufferSequence const& buffers, stream_type&& stream, endpoint_type remote_address) +Door::create( + bool ssl, + ConstBufferSequence const& buffers, + stream_type&& stream, + endpoint_type remote_address) { if (ssl) { @@ -337,9 +355,11 @@ Door::do_accept(boost::asio::yield_context do_yield) if (ec == boost::asio::error::operation_aborted) break; - if (ec == boost::asio::error::no_descriptors || ec == boost::asio::error::no_buffer_space) + if (ec == boost::asio::error::no_descriptors || + ec == boost::asio::error::no_buffer_space) { - JLOG(j_.warn()) << "accept: Too many open files. Pausing for " << accept_delay_.count() << "ms."; + JLOG(j_.warn()) << "accept: Too many open files. Pausing for " + << accept_delay_.count() << "ms."; backoff_timer_.expires_after(accept_delay_); boost::system::error_code tec; @@ -358,8 +378,8 @@ Door::do_accept(boost::asio::yield_context do_yield) if (ssl_ && plain_) { - if (auto sp = - ios().template emplace(port_, handler_, ioc_, std::move(stream), remote_address, j_)) + if (auto sp = ios().template emplace( + port_, handler_, ioc_, std::move(stream), remote_address, j_)) sp->run(); } else if (ssl_ || plain_) diff --git a/include/xrpl/server/detail/PlainHTTPPeer.h b/include/xrpl/server/detail/PlainHTTPPeer.h index 94c84336f9..ef6128560a 100644 --- a/include/xrpl/server/detail/PlainHTTPPeer.h +++ b/include/xrpl/server/detail/PlainHTTPPeer.h @@ -60,7 +60,13 @@ PlainHTTPPeer::PlainHTTPPeer( endpoint_type remote_endpoint, ConstBufferSequence const& buffers, stream_type&& stream) - : BaseHTTPPeer(port, handler, ioc.get_executor(), journal, remote_endpoint, buffers) + : BaseHTTPPeer( + port, + handler, + ioc.get_executor(), + journal, + remote_endpoint, + buffers) , stream_(std::move(stream)) , socket_(stream_.socket()) { @@ -85,7 +91,9 @@ PlainHTTPPeer::run() if (!socket_.is_open()) return; - util::spawn(this->strand_, std::bind(&PlainHTTPPeer::do_read, this->shared_from_this(), std::placeholders::_1)); + util::spawn( + this->strand_, + std::bind(&PlainHTTPPeer::do_read, this->shared_from_this(), std::placeholders::_1)); } template @@ -107,7 +115,8 @@ void PlainHTTPPeer::do_request() { ++this->request_count_; - auto const what = this->handler_.onHandoff(this->session(), std::move(this->message_), this->remote_address_); + auto const what = + this->handler_.onHandoff(this->session(), std::move(this->message_), this->remote_address_); if (what.moved) return; boost::system::error_code ec; diff --git a/include/xrpl/server/detail/SSLHTTPPeer.h b/include/xrpl/server/detail/SSLHTTPPeer.h index 138145544e..240261fce6 100644 --- a/include/xrpl/server/detail/SSLHTTPPeer.h +++ b/include/xrpl/server/detail/SSLHTTPPeer.h @@ -73,7 +73,13 @@ SSLHTTPPeer::SSLHTTPPeer( endpoint_type remote_address, ConstBufferSequence const& buffers, middle_type&& stream) - : BaseHTTPPeer(port, handler, ioc.get_executor(), journal, remote_address, buffers) + : BaseHTTPPeer( + port, + handler, + ioc.get_executor(), + journal, + remote_address, + buffers) , stream_ptr_(std::make_unique(middle_type(std::move(stream)), *port.context)) , stream_(*stream_ptr_) , socket_(stream_.next_layer().socket()) @@ -92,7 +98,9 @@ SSLHTTPPeer::run() } if (!socket_.is_open()) return; - util::spawn(this->strand_, std::bind(&SSLHTTPPeer::do_handshake, this->shared_from_this(), std::placeholders::_1)); + util::spawn( + this->strand_, + std::bind(&SSLHTTPPeer::do_handshake, this->shared_from_this(), std::placeholders::_1)); } template @@ -116,17 +124,21 @@ SSLHTTPPeer::do_handshake(yield_context do_yield) boost::system::error_code ec; stream_.set_verify_mode(boost::asio::ssl::verify_none); this->start_timer(); - this->read_buf_.consume(stream_.async_handshake(stream_type::server, this->read_buf_.data(), do_yield[ec])); + this->read_buf_.consume( + stream_.async_handshake(stream_type::server, this->read_buf_.data(), do_yield[ec])); this->cancel_timer(); if (ec == boost::beast::error::timeout) return this->on_timer(); if (ec) return this->fail(ec, "handshake"); - bool const http = this->port().protocol.count("peer") > 0 || this->port().protocol.count("wss") > 0 || - this->port().protocol.count("wss2") > 0 || this->port().protocol.count("https") > 0; + bool const http = this->port().protocol.count("peer") > 0 || + this->port().protocol.count("wss") > 0 || this->port().protocol.count("wss2") > 0 || + this->port().protocol.count("https") > 0; if (http) { - util::spawn(this->strand_, std::bind(&SSLHTTPPeer::do_read, this->shared_from_this(), std::placeholders::_1)); + util::spawn( + this->strand_, + std::bind(&SSLHTTPPeer::do_read, this->shared_from_this(), std::placeholders::_1)); return; } // `this` will be destroyed @@ -153,7 +165,8 @@ SSLHTTPPeer::do_close() { this->start_timer(); stream_.async_shutdown(bind_executor( - this->strand_, std::bind(&SSLHTTPPeer::on_shutdown, this->shared_from_this(), std::placeholders::_1))); + this->strand_, + std::bind(&SSLHTTPPeer::on_shutdown, this->shared_from_this(), std::placeholders::_1))); } template diff --git a/include/xrpl/server/detail/ServerImpl.h b/include/xrpl/server/detail/ServerImpl.h index e836b964d2..1f91413521 100644 --- a/include/xrpl/server/detail/ServerImpl.h +++ b/include/xrpl/server/detail/ServerImpl.h @@ -116,7 +116,10 @@ private: }; template -ServerImpl::ServerImpl(Handler& handler, boost::asio::io_context& io_context, beast::Journal journal) +ServerImpl::ServerImpl( + Handler& handler, + boost::asio::io_context& io_context, + beast::Journal journal) : handler_(handler) , j_(journal) , io_context_(io_context) diff --git a/include/xrpl/server/detail/Spawn.h b/include/xrpl/server/detail/Spawn.h index d94fb4fa05..50760be761 100644 --- a/include/xrpl/server/detail/Spawn.h +++ b/include/xrpl/server/detail/Spawn.h @@ -12,7 +12,8 @@ namespace xrpl::util { namespace impl { template -concept IsStrand = std::same_as, boost::asio::strand::inner_executor_type>>; +concept IsStrand = std:: + same_as, boost::asio::strand::inner_executor_type>>; /** * @brief A completion handler that restores `boost::asio::spawn`'s behaviour @@ -66,7 +67,8 @@ spawn(Ctx&& ctx, F&& func) { if constexpr (impl::IsStrand) { - boost::asio::spawn(std::forward(ctx), std::forward(func), impl::kPROPAGATE_EXCEPTIONS); + boost::asio::spawn( + std::forward(ctx), std::forward(func), impl::kPROPAGATE_EXCEPTIONS); } else { diff --git a/include/xrpl/shamap/SHAMap.h b/include/xrpl/shamap/SHAMap.h index cd084ab48b..2c0910a830 100644 --- a/include/xrpl/shamap/SHAMap.h +++ b/include/xrpl/shamap/SHAMap.h @@ -99,7 +99,8 @@ public: /** The depth of the hash map: data is only present in the leaves */ static inline constexpr unsigned int leafDepth = 64; - using DeltaItem = std::pair, boost::intrusive_ptr>; + using DeltaItem = + std::pair, boost::intrusive_ptr>; using Delta = std::map; SHAMap() = delete; @@ -325,8 +326,10 @@ public: invariants() const; private: - using SharedPtrNodeStack = std::stack, SHAMapNodeID>>; - using DeltaRef = std::pair, boost::intrusive_ptr>; + using SharedPtrNodeStack = + std::stack, SHAMapNodeID>>; + using DeltaRef = + std::pair, boost::intrusive_ptr>; // tree node cache operations intr_ptr::SharedPtr @@ -349,7 +352,10 @@ private: /** Update hashes up to the root */ void - dirtyUp(SharedPtrNodeStack& stack, uint256 const& target, intr_ptr::SharedPtr terminal); + dirtyUp( + SharedPtrNodeStack& stack, + uint256 const& target, + intr_ptr::SharedPtr terminal); /** Walk towards the specified id, returning the node. Caller must check if the return is nullptr, and if not, if the node->peekItem()->key() == @@ -376,11 +382,15 @@ private: // returns the first item at or below this node SHAMapLeafNode* - firstBelow(intr_ptr::SharedPtr, SharedPtrNodeStack& stack, int branch = 0) const; + firstBelow(intr_ptr::SharedPtr, SharedPtrNodeStack& stack, int branch = 0) + const; // returns the last item at or below this node SHAMapLeafNode* - lastBelow(intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, int branch = branchFactor) const; + lastBelow( + intr_ptr::SharedPtr node, + SharedPtrNodeStack& stack, + int branch = branchFactor) const; // helper function for firstBelow and lastBelow SHAMapLeafNode* @@ -388,7 +398,8 @@ private: intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, int branch, - std::tuple, std::function> const& loopParams) const; + std::tuple, std::function> const& loopParams) + const; // Simple descent // Get a child of the specified node @@ -403,12 +414,22 @@ private: // Descend with filter // If pending, callback is called as if it called fetchNodeNT - using descendCallback = std::function, SHAMapHash const&)>; + using descendCallback = + std::function, SHAMapHash const&)>; SHAMapTreeNode* - descendAsync(SHAMapInnerNode* parent, int branch, SHAMapSyncFilter* filter, bool& pending, descendCallback&&) const; + descendAsync( + SHAMapInnerNode* parent, + int branch, + SHAMapSyncFilter* filter, + bool& pending, + descendCallback&&) const; std::pair - descend(SHAMapInnerNode* parent, SHAMapNodeID const& parentID, int branch, SHAMapSyncFilter* filter) const; + descend( + SHAMapInnerNode* parent, + SHAMapNodeID const& parentID, + int branch, + SHAMapSyncFilter* filter) const; // Non-storing // Does not hook the returned node to its parent @@ -613,7 +634,10 @@ inline SHAMap::const_iterator::const_iterator(SHAMap const* map, std::nullptr_t) { } -inline SHAMap::const_iterator::const_iterator(SHAMap const* map, pointer item, SharedPtrNodeStack&& stack) +inline SHAMap::const_iterator::const_iterator( + SHAMap const* map, + pointer item, + SharedPtrNodeStack&& stack) : stack_(std::move(stack)), map_(map), item_(item) { } diff --git a/include/xrpl/shamap/SHAMapAccountStateLeafNode.h b/include/xrpl/shamap/SHAMapAccountStateLeafNode.h index 552d2b4692..98ac9776c3 100644 --- a/include/xrpl/shamap/SHAMapAccountStateLeafNode.h +++ b/include/xrpl/shamap/SHAMapAccountStateLeafNode.h @@ -9,7 +9,8 @@ namespace xrpl { /** A leaf node for a state object. */ -class SHAMapAccountStateLeafNode final : public SHAMapLeafNode, public CountedObject +class SHAMapAccountStateLeafNode final : public SHAMapLeafNode, + public CountedObject { public: SHAMapAccountStateLeafNode(boost::intrusive_ptr item, std::uint32_t cowid) @@ -18,7 +19,10 @@ public: updateHash(); } - SHAMapAccountStateLeafNode(boost::intrusive_ptr item, std::uint32_t cowid, SHAMapHash const& hash) + SHAMapAccountStateLeafNode( + boost::intrusive_ptr item, + std::uint32_t cowid, + SHAMapHash const& hash) : SHAMapLeafNode(std::move(item), cowid, hash) { } diff --git a/include/xrpl/shamap/SHAMapAddNode.h b/include/xrpl/shamap/SHAMapAddNode.h index 7d0aaf3be4..e38884e050 100644 --- a/include/xrpl/shamap/SHAMapAddNode.h +++ b/include/xrpl/shamap/SHAMapAddNode.h @@ -51,7 +51,8 @@ inline SHAMapAddNode::SHAMapAddNode() : mGood(0), mBad(0), mDuplicate(0) { } -inline SHAMapAddNode::SHAMapAddNode(int good, int bad, int duplicate) : mGood(good), mBad(bad), mDuplicate(duplicate) +inline SHAMapAddNode::SHAMapAddNode(int good, int bad, int duplicate) + : mGood(good), mBad(bad), mDuplicate(duplicate) { } diff --git a/include/xrpl/shamap/SHAMapItem.h b/include/xrpl/shamap/SHAMapItem.h index ab9cf74dc8..dd098d88aa 100644 --- a/include/xrpl/shamap/SHAMapItem.h +++ b/include/xrpl/shamap/SHAMapItem.h @@ -42,9 +42,11 @@ private: // the only way to properly create one is to first allocate enough memory // so we limit this constructor to codepaths that do this right and limit // arbitrary construction. - SHAMapItem(uint256 const& tag, Slice data) : tag_(tag), size_(static_cast(data.size())) + SHAMapItem(uint256 const& tag, Slice data) + : tag_(tag), size_(static_cast(data.size())) { - std::memcpy(reinterpret_cast(this) + sizeof(*this), data.data(), data.size()); + std::memcpy( + reinterpret_cast(this) + sizeof(*this), data.data(), data.size()); } public: @@ -136,7 +138,8 @@ intrusive_ptr_release(SHAMapItem const* x) inline boost::intrusive_ptr make_shamapitem(uint256 const& tag, Slice data) { - XRPL_ASSERT(data.size() <= megabytes(16), "xrpl::make_shamapitem : maximum input size"); + XRPL_ASSERT( + data.size() <= megabytes(16), "xrpl::make_shamapitem : maximum input size"); std::uint8_t* raw = detail::slabber.allocate(data.size()); diff --git a/include/xrpl/shamap/SHAMapLeafNode.h b/include/xrpl/shamap/SHAMapLeafNode.h index aedcb3b79c..08f83b463a 100644 --- a/include/xrpl/shamap/SHAMapLeafNode.h +++ b/include/xrpl/shamap/SHAMapLeafNode.h @@ -14,7 +14,10 @@ protected: SHAMapLeafNode(boost::intrusive_ptr item, std::uint32_t cowid); - SHAMapLeafNode(boost::intrusive_ptr item, std::uint32_t cowid, SHAMapHash const& hash); + SHAMapLeafNode( + boost::intrusive_ptr item, + std::uint32_t cowid, + SHAMapHash const& hash); public: SHAMapLeafNode(SHAMapLeafNode const&) = delete; diff --git a/include/xrpl/shamap/SHAMapSyncFilter.h b/include/xrpl/shamap/SHAMapSyncFilter.h index 219f9ac558..b34d160c25 100644 --- a/include/xrpl/shamap/SHAMapSyncFilter.h +++ b/include/xrpl/shamap/SHAMapSyncFilter.h @@ -18,8 +18,12 @@ public: // Note that the nodeData is overwritten by this call virtual void - gotNode(bool fromFilter, SHAMapHash const& nodeHash, std::uint32_t ledgerSeq, Blob&& nodeData, SHAMapNodeType type) - const = 0; + gotNode( + bool fromFilter, + SHAMapHash const& nodeHash, + std::uint32_t ledgerSeq, + Blob&& nodeData, + SHAMapNodeType type) const = 0; virtual std::optional getNode(SHAMapHash const& nodeHash) const = 0; diff --git a/include/xrpl/shamap/SHAMapTreeNode.h b/include/xrpl/shamap/SHAMapTreeNode.h index 668f658754..f837a8643b 100644 --- a/include/xrpl/shamap/SHAMapTreeNode.h +++ b/include/xrpl/shamap/SHAMapTreeNode.h @@ -55,7 +55,8 @@ protected: { } - explicit SHAMapTreeNode(std::uint32_t cowid, SHAMapHash const& hash) noexcept : hash_(hash), cowid_(cowid) + explicit SHAMapTreeNode(std::uint32_t cowid, SHAMapHash const& hash) noexcept + : hash_(hash), cowid_(cowid) { } /** @} */ diff --git a/include/xrpl/shamap/SHAMapTxLeafNode.h b/include/xrpl/shamap/SHAMapTxLeafNode.h index 0a44380b9b..dcedb26881 100644 --- a/include/xrpl/shamap/SHAMapTxLeafNode.h +++ b/include/xrpl/shamap/SHAMapTxLeafNode.h @@ -18,7 +18,10 @@ public: updateHash(); } - SHAMapTxLeafNode(boost::intrusive_ptr item, std::uint32_t cowid, SHAMapHash const& hash) + SHAMapTxLeafNode( + boost::intrusive_ptr item, + std::uint32_t cowid, + SHAMapHash const& hash) : SHAMapLeafNode(std::move(item), cowid, hash) { } diff --git a/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h b/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h index d11cc87ff7..60e645fccc 100644 --- a/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h +++ b/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h @@ -9,7 +9,8 @@ namespace xrpl { /** A leaf node for a transaction and its associated metadata. */ -class SHAMapTxPlusMetaLeafNode final : public SHAMapLeafNode, public CountedObject +class SHAMapTxPlusMetaLeafNode final : public SHAMapLeafNode, + public CountedObject { public: SHAMapTxPlusMetaLeafNode(boost::intrusive_ptr item, std::uint32_t cowid) @@ -18,7 +19,10 @@ public: updateHash(); } - SHAMapTxPlusMetaLeafNode(boost::intrusive_ptr item, std::uint32_t cowid, SHAMapHash const& hash) + SHAMapTxPlusMetaLeafNode( + boost::intrusive_ptr item, + std::uint32_t cowid, + SHAMapHash const& hash) : SHAMapLeafNode(std::move(item), cowid, hash) { } diff --git a/include/xrpl/shamap/detail/TaggedPointer.h b/include/xrpl/shamap/detail/TaggedPointer.h index 217cd93d0a..d7adde4b05 100644 --- a/include/xrpl/shamap/detail/TaggedPointer.h +++ b/include/xrpl/shamap/detail/TaggedPointer.h @@ -39,7 +39,9 @@ namespace xrpl { class TaggedPointer { private: - static_assert(alignof(SHAMapHash) >= 4, "Bad alignment: Tag pointer requires low two bits to be zero."); + static_assert( + alignof(SHAMapHash) >= 4, + "Bad alignment: Tag pointer requires low two bits to be zero."); /** Upper bits are the pointer, lowest two bits are the tag A moved-from object will have a tp_ of zero. */ diff --git a/include/xrpl/shamap/detail/TaggedPointer.ipp b/include/xrpl/shamap/detail/TaggedPointer.ipp index bedb33a733..903108ac66 100644 --- a/include/xrpl/shamap/detail/TaggedPointer.ipp +++ b/include/xrpl/shamap/detail/TaggedPointer.ipp @@ -25,7 +25,8 @@ static_assert( // Terminology: A chunk is the memory being allocated from a block. A block // contains multiple chunks. This is the terminology the boost documentation // uses. Pools use "Simple Segregated Storage" as their storage format. -constexpr size_t elementSizeBytes = (sizeof(SHAMapHash) + sizeof(intr_ptr::SharedPtr)); +constexpr size_t elementSizeBytes = + (sizeof(SHAMapHash) + sizeof(intr_ptr::SharedPtr)); constexpr size_t blockSizeBytes = kilobytes(512); @@ -37,7 +38,8 @@ initArrayChunkSizeBytes(std::index_sequence) boundaries[I] * elementSizeBytes..., }; } -constexpr auto arrayChunkSizeBytes = initArrayChunkSizeBytes(std::make_index_sequence{}); +constexpr auto arrayChunkSizeBytes = + initArrayChunkSizeBytes(std::make_index_sequence{}); template constexpr std::array @@ -47,7 +49,8 @@ initArrayChunksPerBlock(std::index_sequence) blockSizeBytes / arrayChunkSizeBytes[I]..., }; } -constexpr auto chunksPerBlock = initArrayChunksPerBlock(std::make_index_sequence{}); +constexpr auto chunksPerBlock = + initArrayChunksPerBlock(std::make_index_sequence{}); [[nodiscard]] inline std::uint8_t numAllocatedChildren(std::uint8_t n) @@ -59,8 +62,10 @@ numAllocatedChildren(std::uint8_t n) [[nodiscard]] inline std::size_t boundariesIndex(std::uint8_t numChildren) { - XRPL_ASSERT(numChildren <= SHAMapInnerNode::branchFactor, "xrpl::boundariesIndex : valid input"); - return std::distance(boundaries.begin(), std::lower_bound(boundaries.begin(), boundaries.end(), numChildren)); + XRPL_ASSERT( + numChildren <= SHAMapInnerNode::branchFactor, "xrpl::boundariesIndex : valid input"); + return std::distance( + boundaries.begin(), std::lower_bound(boundaries.begin(), boundaries.end(), numChildren)); } template @@ -358,7 +363,8 @@ inline TaggedPointer::TaggedPointer( // keep new (&dstHashes[dstIndex]) SHAMapHash{srcHashes[srcIndex]}; - new (&dstChildren[dstIndex]) intr_ptr::SharedPtr{std::move(srcChildren[srcIndex])}; + new (&dstChildren[dstIndex]) + intr_ptr::SharedPtr{std::move(srcChildren[srcIndex])}; ++dstIndex; ++srcIndex; } @@ -413,7 +419,10 @@ inline TaggedPointer::TaggedPointer( } } -inline TaggedPointer::TaggedPointer(TaggedPointer&& other, std::uint16_t isBranch, std::uint8_t toAllocate) +inline TaggedPointer::TaggedPointer( + TaggedPointer&& other, + std::uint16_t isBranch, + std::uint8_t toAllocate) : TaggedPointer(std::move(other)) { auto const oldNumAllocated = capacity(); @@ -435,7 +444,8 @@ inline TaggedPointer::TaggedPointer(TaggedPointer&& other, std::uint16_t isBranc // new arrays are dense, old arrays are sparse iterNonEmptyChildIndexes(isBranch, [&](auto branchNum, auto indexNum) { new (&newHashes[branchNum]) SHAMapHash{oldHashes[indexNum]}; - new (&newChildren[branchNum]) intr_ptr::SharedPtr{std::move(oldChildren[indexNum])}; + new (&newChildren[branchNum]) + intr_ptr::SharedPtr{std::move(oldChildren[indexNum])}; }); // Run the constructors for the remaining elements for (int i = 0; i < SHAMapInnerNode::branchFactor; ++i) @@ -518,7 +528,8 @@ TaggedPointer::getHashesAndChildren() const auto const [tag, ptr] = decode(); auto const hashes = reinterpret_cast(ptr); std::uint8_t numAllocated = boundaries[tag]; - auto const children = reinterpret_cast*>(hashes + numAllocated); + auto const children = + reinterpret_cast*>(hashes + numAllocated); return {numAllocated, hashes, children}; }; diff --git a/src/xrpld/app/tx/detail/ApplyContext.h b/include/xrpl/tx/ApplyContext.h similarity index 85% rename from src/xrpld/app/tx/detail/ApplyContext.h rename to include/xrpl/tx/ApplyContext.h index 45345df265..9e382556c2 100644 --- a/src/xrpld/app/tx/detail/ApplyContext.h +++ b/include/xrpl/tx/ApplyContext.h @@ -1,9 +1,7 @@ #pragma once -#include -#include - #include +#include #include #include #include @@ -17,7 +15,7 @@ class ApplyContext { public: explicit ApplyContext( - Application& app, + ServiceRegistry& registry, OpenView& base, std::optional const& parentBatchId, STTx const& tx, @@ -27,19 +25,19 @@ public: beast::Journal journal = beast::Journal{beast::Journal::getNullSink()}); explicit ApplyContext( - Application& app, + ServiceRegistry& registry, OpenView& base, STTx const& tx, TER preclaimResult, XRPAmount baseFee, ApplyFlags flags, beast::Journal journal = beast::Journal{beast::Journal::getNullSink()}) - : ApplyContext(app, base, std::nullopt, tx, preclaimResult, baseFee, flags, journal) + : ApplyContext(registry, base, std::nullopt, tx, preclaimResult, baseFee, flags, journal) { XRPL_ASSERT((flags & tapBATCH) == 0, "Batch apply flag should not be set"); } - Application& app; + ServiceRegistry& registry; STTx const& tx; TER const preclaimResult; XRPAmount const baseFee; @@ -90,11 +88,12 @@ public: /** Visit unapplied changes. */ void - visit(std::function const& before, - std::shared_ptr const& after)> const& func); + visit( + std::function const& before, + std::shared_ptr const& after)> const& func); void destroyXRP(XRPAmount const& fee) diff --git a/src/xrpld/app/tx/detail/InvariantCheck.h b/include/xrpl/tx/InvariantCheck.h similarity index 98% rename from src/xrpld/app/tx/detail/InvariantCheck.h rename to include/xrpl/tx/InvariantCheck.h index 7e9a62d9e2..dc42f9d38c 100644 --- a/src/xrpld/app/tx/detail/InvariantCheck.h +++ b/include/xrpl/tx/InvariantCheck.h @@ -38,7 +38,10 @@ public: * @param after ledger entry after modification by the transaction */ void - visitEntry(bool isDelete, std::shared_ptr const& before, std::shared_ptr const& after); + visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after); /** * @brief called after all ledger entries have been visited to determine @@ -53,7 +56,12 @@ public: * @return true if check passes, false if it fails */ bool - finalize(STTx const& tx, TER const tec, XRPAmount const fee, ReadView const& view, beast::Journal const& j); + finalize( + STTx const& tx, + TER const tec, + XRPAmount const fee, + ReadView const& view, + beast::Journal const& j); }; #endif @@ -533,7 +541,8 @@ private: bool finalizeDEX(bool enforce, beast::Journal const&) const; bool - generalInvariant(STTx const&, ReadView const&, ZeroAllowed zeroAllowed, beast::Journal const&) const; + generalInvariant(STTx const&, ReadView const&, ZeroAllowed zeroAllowed, beast::Journal const&) + const; }; /** diff --git a/src/xrpld/app/tx/detail/SignerEntries.h b/include/xrpl/tx/SignerEntries.h similarity index 90% rename from src/xrpld/app/tx/detail/SignerEntries.h rename to include/xrpl/tx/SignerEntries.h index fe01d6b1ee..0b997b3e4d 100644 --- a/src/xrpld/app/tx/detail/SignerEntries.h +++ b/include/xrpl/tx/SignerEntries.h @@ -1,11 +1,10 @@ #pragma once -#include // NotTEC - #include // #include // beast::Journal #include // temMALFORMED #include // AccountID +#include // NotTEC #include #include @@ -34,7 +33,10 @@ public: std::uint16_t weight; std::optional tag; - SignerEntry(AccountID const& inAccount, std::uint16_t inWeight, std::optional inTag) + SignerEntry( + AccountID const& inAccount, + std::uint16_t inWeight, + std::optional inTag) : account(inAccount), weight(inWeight), tag(inTag) { } diff --git a/src/xrpld/app/tx/detail/Transactor.h b/include/xrpl/tx/Transactor.h similarity index 90% rename from src/xrpld/app/tx/detail/Transactor.h rename to include/xrpl/tx/Transactor.h index e06086a55d..0e88cf92e1 100644 --- a/src/xrpld/app/tx/detail/Transactor.h +++ b/include/xrpl/tx/Transactor.h @@ -1,12 +1,11 @@ #pragma once -#include -#include - #include #include #include #include +#include +#include namespace xrpl { @@ -14,7 +13,7 @@ namespace xrpl { struct PreflightContext { public: - Application& app; + ServiceRegistry& registry; STTx const& tx; Rules const rules; ApplyFlags flags; @@ -22,24 +21,29 @@ public: beast::Journal const j; PreflightContext( - Application& app_, + ServiceRegistry& registry_, STTx const& tx_, uint256 parentBatchId_, Rules const& rules_, ApplyFlags flags_, beast::Journal j_ = beast::Journal{beast::Journal::getNullSink()}) - : app(app_), tx(tx_), rules(rules_), flags(flags_), parentBatchId(parentBatchId_), j(j_) + : registry(registry_) + , tx(tx_) + , rules(rules_) + , flags(flags_) + , parentBatchId(parentBatchId_) + , j(j_) { XRPL_ASSERT((flags_ & tapBATCH) == tapBATCH, "Batch apply flag should be set"); } PreflightContext( - Application& app_, + ServiceRegistry& registry_, STTx const& tx_, Rules const& rules_, ApplyFlags flags_, beast::Journal j_ = beast::Journal{beast::Journal::getNullSink()}) - : app(app_), tx(tx_), rules(rules_), flags(flags_), j(j_) + : registry(registry_), tx(tx_), rules(rules_), flags(flags_), j(j_) { XRPL_ASSERT((flags_ & tapBATCH) == 0, "Batch apply flag should not be set"); } @@ -52,7 +56,7 @@ public: struct PreclaimContext { public: - Application& app; + ServiceRegistry& registry; ReadView const& view; TER preflightResult; ApplyFlags flags; @@ -61,14 +65,14 @@ public: beast::Journal const j; PreclaimContext( - Application& app_, + ServiceRegistry& registry_, ReadView const& view_, TER preflightResult_, STTx const& tx_, ApplyFlags flags_, std::optional parentBatchId_, beast::Journal j_ = beast::Journal{beast::Journal::getNullSink()}) - : app(app_) + : registry(registry_) , view(view_) , preflightResult(preflightResult_) , flags(flags_) @@ -82,13 +86,13 @@ public: } PreclaimContext( - Application& app_, + ServiceRegistry& registry_, ReadView const& view_, TER preflightResult_, STTx const& tx_, ApplyFlags flags_, beast::Journal j_ = beast::Journal{beast::Journal::getNullSink()}) - : PreclaimContext(app_, view_, preflightResult_, tx_, flags_, std::nullopt, j_) + : PreclaimContext(registry_, view_, preflightResult_, tx_, flags_, std::nullopt, j_) { XRPL_ASSERT((flags_ & tapBATCH) == 0, "Batch apply flag should not be set"); } @@ -208,7 +212,11 @@ public: // Interface used by DeleteAccount static TER - ticketDelete(ApplyView& view, AccountID const& account, uint256 const& ticketIndex, beast::Journal j); + ticketDelete( + ApplyView& view, + AccountID const& account, + uint256 const& ticketIndex, + beast::Journal j); protected: TER @@ -225,14 +233,14 @@ protected: /** Compute the minimum fee required to process a transaction with a given baseFee based on the current server load. - @param app The application hosting the server + @param registry The service registry. @param baseFee The base fee of a candidate transaction @see xrpl::calculateBaseFee @param fees Fee settings from the current ledger @param flags Transaction processing fees */ static XRPAmount - minimumFee(Application& app, XRPAmount baseFee, Fees const& fees, ApplyFlags flags); + minimumFee(ServiceRegistry& registry, XRPAmount baseFee, Fees const& fees, ApplyFlags flags); // Returns the fee in fee units, not scaled for load. static XRPAmount @@ -281,7 +289,9 @@ protected: /// Minimum will usually be zero. template static bool - validNumericMinimum(std::optional value, unit::ValueUnit min = unit::ValueUnit{}); + validNumericMinimum( + std::optional value, + unit::ValueUnit min = unit::ValueUnit{}); private: std::pair @@ -396,7 +406,10 @@ Transactor::validNumericRange(std::optional value, T max, T min) template bool -Transactor::validNumericRange(std::optional value, unit::ValueUnit max, unit::ValueUnit min) +Transactor::validNumericRange( + std::optional value, + unit::ValueUnit max, + unit::ValueUnit min) { return validNumericRange(value, max.value(), min.value()); } diff --git a/src/xrpld/app/tx/apply.h b/include/xrpl/tx/apply.h similarity index 93% rename from src/xrpld/app/tx/apply.h rename to include/xrpl/tx/apply.h index c3ff4f905e..49b30fea02 100644 --- a/src/xrpld/app/tx/apply.h +++ b/include/xrpl/tx/apply.h @@ -1,18 +1,16 @@ #pragma once -#include -#include - #include #include #include +#include #include namespace xrpl { -class Application; class HashRouter; +class ServiceRegistry; /** Describes the pre-processing validity of a transaction. @@ -41,7 +39,7 @@ enum class Validity { @see Validity */ std::pair -checkValidity(HashRouter& router, STTx const& tx, Rules const& rules, Config const& config); +checkValidity(HashRouter& router, STTx const& tx, Rules const& rules); /** Sets the validity of a given transaction in the cache. @@ -97,7 +95,12 @@ forceValidity(HashRouter& router, uint256 const& txid, Validity validity); whether or not the transaction was applied. */ ApplyResult -apply(Application& app, OpenView& view, STTx const& tx, ApplyFlags flags, beast::Journal journal); +apply( + ServiceRegistry& registry, + OpenView& view, + STTx const& tx, + ApplyFlags flags, + beast::Journal journal); /** Enum class for return value from `applyTransaction` @@ -121,7 +124,7 @@ enum class ApplyTransactionResult { */ ApplyTransactionResult applyTransaction( - Application& app, + ServiceRegistry& registry, OpenView& view, STTx const& tx, bool retryAssured, diff --git a/src/xrpld/app/tx/applySteps.h b/include/xrpl/tx/applySteps.h similarity index 94% rename from src/xrpld/app/tx/applySteps.h rename to include/xrpl/tx/applySteps.h index ef87d352f3..2e76e20f5d 100644 --- a/src/xrpld/app/tx/applySteps.h +++ b/include/xrpl/tx/applySteps.h @@ -5,7 +5,7 @@ namespace xrpl { -class Application; +class ServiceRegistry; class STTx; class TxQ; @@ -15,7 +15,8 @@ struct ApplyResult bool applied; std::optional metadata; - ApplyResult(TER t, bool a, std::optional m = std::nullopt) : ter(t), applied(a), metadata(std::move(m)) + ApplyResult(TER t, bool a, std::optional m = std::nullopt) + : ter(t), applied(a), metadata(std::move(m)) { } }; @@ -240,11 +241,16 @@ public: */ /** @{ */ PreflightResult -preflight(Application& app, Rules const& rules, STTx const& tx, ApplyFlags flags, beast::Journal j); +preflight( + ServiceRegistry& registry, + Rules const& rules, + STTx const& tx, + ApplyFlags flags, + beast::Journal j); PreflightResult preflight( - Application& app, + ServiceRegistry& registry, Rules const& rules, uint256 const& parentBatchId, STTx const& tx, @@ -281,7 +287,7 @@ preflight( this transaction. */ PreclaimResult -preclaim(PreflightResult const& preflightResult, Application& app, OpenView const& view); +preclaim(PreflightResult const& preflightResult, ServiceRegistry& registry, OpenView const& view); /** Compute only the expected base fee for a transaction. @@ -323,7 +329,7 @@ calculateDefaultBaseFee(ReadView const& view, STTx const& tx); @param preclaimResult The result of a previous call to `preclaim` for the transaction. - @param app The current running `Application`. + @param registry The service registry. @param view The open ledger that the transaction will attempt to be applied to. @@ -333,6 +339,6 @@ calculateDefaultBaseFee(ReadView const& view, STTx const& tx); whether or not the transaction was applied. */ ApplyResult -doApply(PreclaimResult const& preclaimResult, Application& app, OpenView& view); +doApply(PreclaimResult const& preclaimResult, ServiceRegistry& registry, OpenView& view); } // namespace xrpl diff --git a/src/xrpld/app/tx/detail/BookTip.h b/include/xrpl/tx/paths/BookTip.h similarity index 100% rename from src/xrpld/app/tx/detail/BookTip.h rename to include/xrpl/tx/paths/BookTip.h diff --git a/src/xrpld/app/paths/Flow.h b/include/xrpl/tx/paths/Flow.h similarity index 95% rename from src/xrpld/app/paths/Flow.h rename to include/xrpl/tx/paths/Flow.h index 1a46ce221a..32e8c3611b 100644 --- a/src/xrpld/app/paths/Flow.h +++ b/include/xrpl/tx/paths/Flow.h @@ -1,9 +1,8 @@ #pragma once -#include -#include - #include +#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/Offer.h b/include/xrpl/tx/paths/Offer.h similarity index 95% rename from src/xrpld/app/tx/detail/Offer.h rename to include/xrpl/tx/paths/Offer.h index 7c783233f1..4b161c5f2d 100644 --- a/src/xrpld/app/tx/detail/Offer.h +++ b/include/xrpl/tx/paths/Offer.h @@ -154,8 +154,9 @@ public: if (consumed.in > m_amounts.in || consumed.out > m_amounts.out) { // LCOV_EXCL_START - JLOG(j.error()) << "AMMOffer::checkInvariant failed: consumed " << to_string(consumed.in) << " " - << to_string(consumed.out) << " amounts " << to_string(m_amounts.in) << " " + JLOG(j.error()) << "AMMOffer::checkInvariant failed: consumed " + << to_string(consumed.in) << " " << to_string(consumed.out) + << " amounts " << to_string(m_amounts.in) << " " << to_string(m_amounts.out); return false; @@ -204,7 +205,8 @@ TOffer::setFieldAmounts() template TAmounts -TOffer::limitOut(TAmounts const& offerAmount, TOut const& limit, bool roundUp) const +TOffer::limitOut(TAmounts const& offerAmount, TOut const& limit, bool roundUp) + const { // It turns out that the ceil_out implementation has some slop in // it, which ceil_out_strict removes. @@ -213,9 +215,11 @@ TOffer::limitOut(TAmounts const& offerAmount, TOut const& template TAmounts -TOffer::limitIn(TAmounts const& offerAmount, TIn const& limit, bool roundUp) const +TOffer::limitIn(TAmounts const& offerAmount, TIn const& limit, bool roundUp) + const { - if (auto const& rules = getCurrentTransactionRules(); rules && rules->enabled(fixReducedOffersV2)) + if (auto const& rules = getCurrentTransactionRules(); + rules && rules->enabled(fixReducedOffersV2)) // It turns out that the ceil_in implementation has some slop in // it. ceil_in_strict removes that slop. But removing that slop // affects transaction outcomes, so the change must be made using diff --git a/src/xrpld/app/tx/detail/OfferStream.h b/include/xrpl/tx/paths/OfferStream.h similarity index 98% rename from src/xrpld/app/tx/detail/OfferStream.h rename to include/xrpl/tx/paths/OfferStream.h index 2f6bda3fab..df96a1b6da 100644 --- a/src/xrpld/app/tx/detail/OfferStream.h +++ b/include/xrpl/tx/paths/OfferStream.h @@ -1,12 +1,11 @@ #pragma once -#include -#include - #include #include #include #include +#include +#include #include diff --git a/src/xrpld/app/paths/RippleCalc.h b/include/xrpl/tx/paths/RippleCalc.h similarity index 100% rename from src/xrpld/app/paths/RippleCalc.h rename to include/xrpl/tx/paths/RippleCalc.h diff --git a/src/xrpld/app/paths/detail/AmountSpec.h b/include/xrpl/tx/paths/detail/AmountSpec.h similarity index 100% rename from src/xrpld/app/paths/detail/AmountSpec.h rename to include/xrpl/tx/paths/detail/AmountSpec.h diff --git a/src/xrpld/app/paths/detail/FlatSets.h b/include/xrpl/tx/paths/detail/FlatSets.h similarity index 100% rename from src/xrpld/app/paths/detail/FlatSets.h rename to include/xrpl/tx/paths/detail/FlatSets.h diff --git a/src/xrpld/app/paths/detail/FlowDebugInfo.h b/include/xrpl/tx/paths/detail/FlowDebugInfo.h similarity index 81% rename from src/xrpld/app/paths/detail/FlowDebugInfo.h rename to include/xrpl/tx/paths/detail/FlowDebugInfo.h index d7b97a49d4..d2d9dc8466 100644 --- a/src/xrpld/app/paths/detail/FlowDebugInfo.h +++ b/include/xrpl/tx/paths/detail/FlowDebugInfo.h @@ -1,10 +1,9 @@ #pragma once -#include - #include #include #include +#include #include @@ -206,44 +205,52 @@ struct FlowDebugInfo } ostr << ']'; }; - auto writeXrpAmtList = [&write_list](std::vector const& amts, char delim = ';') { - auto get_val = [](EitherAmount const& a) -> std::string { return xrpl::to_string(a.xrp); }; + auto writeXrpAmtList = [&write_list]( + std::vector const& amts, char delim = ';') { + auto get_val = [](EitherAmount const& a) -> std::string { + return xrpl::to_string(a.xrp); + }; write_list(amts, get_val, delim); }; - auto writeIouAmtList = [&write_list](std::vector const& amts, char delim = ';') { - auto get_val = [](EitherAmount const& a) -> std::string { return xrpl::to_string(a.iou); }; + auto writeIouAmtList = [&write_list]( + std::vector const& amts, char delim = ';') { + auto get_val = [](EitherAmount const& a) -> std::string { + return xrpl::to_string(a.iou); + }; write_list(amts, get_val, delim); }; auto writeIntList = [&write_list](std::vector const& vals, char delim = ';') { auto get_val = [](size_t const& v) -> size_t const& { return v; }; write_list(vals, get_val); }; - auto writeNestedIouAmtList = [&ostr, &writeIouAmtList](std::vector> const& amts) { - ostr << '['; - if (!amts.empty()) - { - writeIouAmtList(amts[0], '|'); - for (size_t i = 1, e = amts.size(); i < e; ++i) + auto writeNestedIouAmtList = + [&ostr, &writeIouAmtList](std::vector> const& amts) { + ostr << '['; + if (!amts.empty()) { - ostr << ';'; - writeIouAmtList(amts[i], '|'); + writeIouAmtList(amts[0], '|'); + for (size_t i = 1, e = amts.size(); i < e; ++i) + { + ostr << ';'; + writeIouAmtList(amts[i], '|'); + } } - } - ostr << ']'; - }; - auto writeNestedXrpAmtList = [&ostr, &writeXrpAmtList](std::vector> const& amts) { - ostr << '['; - if (!amts.empty()) - { - writeXrpAmtList(amts[0], '|'); - for (size_t i = 1, e = amts.size(); i < e; ++i) + ostr << ']'; + }; + auto writeNestedXrpAmtList = + [&ostr, &writeXrpAmtList](std::vector> const& amts) { + ostr << '['; + if (!amts.empty()) { - ostr << ';'; - writeXrpAmtList(amts[i], '|'); + writeXrpAmtList(amts[0], '|'); + for (size_t i = 1, e = amts.size(); i < e; ++i) + { + ostr << ';'; + writeXrpAmtList(amts[i], '|'); + } } - } - ostr << ']'; - }; + ostr << ']'; + }; ostr << ", in_pass: "; if (passInfo.nativeIn) @@ -277,7 +284,9 @@ struct FlowDebugInfo }; inline void -writeDiffElement(std::ostringstream& ostr, std::pair, STAmount> const& elem) +writeDiffElement( + std::ostringstream& ostr, + std::pair, STAmount> const& elem) { using namespace std; auto const k = elem.first; @@ -303,7 +312,8 @@ writeDiffs(std::ostringstream& ostr, Iter begin, Iter end) ostr << ']'; }; -using BalanceDiffs = std::pair, STAmount>, XRPAmount>; +using BalanceDiffs = + std::pair, STAmount>, XRPAmount>; inline BalanceDiffs balanceDiffs(PaymentSandbox const& sb, ReadView const& rv) diff --git a/src/xrpld/app/paths/detail/Steps.h b/include/xrpl/tx/paths/detail/Steps.h similarity index 97% rename from src/xrpld/app/paths/detail/Steps.h rename to include/xrpl/tx/paths/detail/Steps.h index 580b8c487e..53c9294155 100644 --- a/src/xrpld/app/paths/detail/Steps.h +++ b/include/xrpl/tx/paths/detail/Steps.h @@ -1,13 +1,12 @@ #pragma once -#include - #include #include #include #include #include #include +#include #include @@ -549,8 +548,9 @@ struct StrandContext bool ownerPaysTransferFee_, OfferCrossing offerCrossing_, bool isDefaultPath_, - std::array, 2>& seenDirectIssues_, ///< For detecting currency loops - boost::container::flat_set& seenBookOuts_, ///< For detecting book loops + std::array, 2>& + seenDirectIssues_, ///< For detecting currency loops + boost::container::flat_set& seenBookOuts_, ///< For detecting book loops AMMContext& ammContext_, std::optional const& domainID, beast::Journal j_); ///< Journal for logging @@ -560,7 +560,11 @@ struct StrandContext namespace test { // Needed for testing bool -directStepEqual(Step const& step, AccountID const& src, AccountID const& dst, Currency const& currency); +directStepEqual( + Step const& step, + AccountID const& src, + AccountID const& dst, + Currency const& currency); bool xrpEndpointStepEqual(Step const& step, AccountID const& acc); @@ -570,7 +574,11 @@ bookStepEqual(Step const& step, xrpl::Book const& book); } // namespace test std::pair> -make_DirectStepI(StrandContext const& ctx, AccountID const& src, AccountID const& dst, Currency const& c); +make_DirectStepI( + StrandContext const& ctx, + AccountID const& src, + AccountID const& dst, + Currency const& c); std::pair> make_BookStepII(StrandContext const& ctx, Issue const& in, Issue const& out); diff --git a/src/xrpld/app/paths/detail/StrandFlow.h b/include/xrpl/tx/paths/detail/StrandFlow.h similarity index 91% rename from src/xrpld/app/paths/detail/StrandFlow.h rename to include/xrpl/tx/paths/detail/StrandFlow.h index aa3d00a822..929aca0663 100644 --- a/src/xrpld/app/paths/detail/StrandFlow.h +++ b/include/xrpl/tx/paths/detail/StrandFlow.h @@ -1,18 +1,17 @@ #pragma once -#include -#include -#include -#include -#include -#include -#include - #include #include #include #include #include +#include +#include +#include +#include +#include +#include +#include #include @@ -143,8 +142,9 @@ flow( // throwing out the sandbox can only increase liquidity // yet the limiting is still limiting // LCOV_EXCL_START - JLOG(j.fatal()) << "Re-executed limiting step failed. r.first: " - << to_string(get(r.first)) << " maxIn: " << to_string(*maxIn); + JLOG(j.fatal()) + << "Re-executed limiting step failed. r.first: " + << to_string(get(r.first)) << " maxIn: " << to_string(*maxIn); UNREACHABLE( "xrpl::flow : first step re-executing the " "limiting step failed"); @@ -179,8 +179,9 @@ flow( // yet the limiting is still limiting // LCOV_EXCL_START #ifndef NDEBUG - JLOG(j.fatal()) << "Re-executed limiting step failed. r.second: " << r.second - << " stepOut: " << stepOut; + JLOG(j.fatal()) + << "Re-executed limiting step failed. r.second: " << r.second + << " stepOut: " << stepOut; #else JLOG(j.fatal()) << "Re-executed limiting step failed"; #endif @@ -216,7 +217,8 @@ flow( // new limit // LCOV_EXCL_START #ifndef NDEBUG - JLOG(j.fatal()) << "Re-executed forward pass failed. r.first: " << r.first << " stepIn: " << stepIn; + JLOG(j.fatal()) << "Re-executed forward pass failed. r.first: " << r.first + << " stepIn: " << stepIn; #else JLOG(j.fatal()) << "Re-executed forward pass failed"; #endif @@ -253,11 +255,18 @@ flow( } #endif - bool const inactive = std::any_of( - strand.begin(), strand.end(), [](std::unique_ptr const& step) { return step->inactive(); }); + bool const inactive = + std::any_of(strand.begin(), strand.end(), [](std::unique_ptr const& step) { + return step->inactive(); + }); return Result( - strand, get(strandIn), get(strandOut), std::move(*sb), std::move(ofrsToRm), inactive); + strand, + get(strandIn), + get(strandOut), + std::move(*sb), + std::move(ofrsToRm), + inactive); } catch (FlowException const&) { @@ -282,15 +291,24 @@ struct FlowResult TOutAmt const& out_, PaymentSandbox&& sandbox_, boost::container::flat_set ofrsToRm) - : in(in_), out(out_), sandbox(std::move(sandbox_)), removableOffers(std::move(ofrsToRm)), ter(tesSUCCESS) + : in(in_) + , out(out_) + , sandbox(std::move(sandbox_)) + , removableOffers(std::move(ofrsToRm)) + , ter(tesSUCCESS) { } - FlowResult(TER ter_, boost::container::flat_set ofrsToRm) : removableOffers(std::move(ofrsToRm)), ter(ter_) + FlowResult(TER ter_, boost::container::flat_set ofrsToRm) + : removableOffers(std::move(ofrsToRm)), ter(ter_) { } - FlowResult(TER ter_, TInAmt const& in_, TOutAmt const& out_, boost::container::flat_set ofrsToRm) + FlowResult( + TER ter_, + TInAmt const& in_, + TOutAmt const& out_, + boost::container::flat_set ofrsToRm) : in(in_), out(out_), removableOffers(std::move(ofrsToRm)), ter(ter_) { } @@ -326,7 +344,11 @@ qualityUpperBound(ReadView const& v, Strand const& strand) */ template inline TOutAmt -limitOut(ReadView const& v, Strand const& strand, TOutAmt const& remainingOut, Quality const& limitQuality) +limitOut( + ReadView const& v, + Strand const& strand, + TOutAmt const& remainingOut, + Quality const& limitQuality) { std::optional stepQualityFunc; std::optional qf; @@ -428,10 +450,13 @@ public: } // must stable sort for deterministic order across different c++ // standard library implementations - std::stable_sort(strandQualities.begin(), strandQualities.end(), [](auto const& lhs, auto const& rhs) { - // higher qualities first - return std::get(lhs) > std::get(rhs); - }); + std::stable_sort( + strandQualities.begin(), + strandQualities.end(), + [](auto const& lhs, auto const& rhs) { + // higher qualities first + return std::get(lhs) > std::get(rhs); + }); next_.clear(); next_.reserve(strandQualities.size()); for (auto const& sq : strandQualities) @@ -650,8 +675,8 @@ flow( Quality const q(f.out, f.in); - JLOG(j.trace()) << "New flow iter (iter, in, out): " << curTry - 1 << " " << to_string(f.in) << " " - << to_string(f.out); + JLOG(j.trace()) << "New flow iter (iter, in, out): " << curTry - 1 << " " + << to_string(f.in) << " " << to_string(f.out); // limitOut() finds output to generate exact requested // limitQuality. But the actual limit quality might be slightly @@ -688,9 +713,11 @@ flow( remainingIn = *sendMax - sum(savedIns); if (flowDebugInfo) - flowDebugInfo->pushPass(EitherAmount(best->in), EitherAmount(best->out), activeStrands.size()); + flowDebugInfo->pushPass( + EitherAmount(best->in), EitherAmount(best->out), activeStrands.size()); - JLOG(j.trace()) << "Best path: in: " << to_string(best->in) << " out: " << to_string(best->out) + JLOG(j.trace()) << "Best path: in: " << to_string(best->in) + << " out: " << to_string(best->out) << " remainingOut: " << to_string(remainingOut); best->sb.apply(sb); @@ -720,7 +747,8 @@ flow( auto const actualOut = sum(savedOuts); auto const actualIn = sum(savedIns); - JLOG(j.trace()) << "Total flow: in: " << to_string(actualIn) << " out: " << to_string(actualOut); + JLOG(j.trace()) << "Total flow: in: " << to_string(actualIn) + << " out: " << to_string(actualOut); /* flowCross doesn't handle offer crossing with tfFillOrKill flag correctly. * 1. If tfFillOrKill is set then the owner must receive the full @@ -765,7 +793,8 @@ flow( return {tecPATH_DRY, std::move(ofrsToRmOnFail)}; } } - if (offerCrossing && (!partialPayment && (!fillOrKillEnabled || offerCrossing == OfferCrossing::sell))) + if (offerCrossing && + (!partialPayment && (!fillOrKillEnabled || offerCrossing == OfferCrossing::sell))) { // If we're offer crossing and partialPayment is *not* true, then // we're handling a FillOrKill offer. In this case remainingIn must diff --git a/src/xrpld/app/tx/detail/AMMBid.h b/include/xrpl/tx/transactors/AMM/AMMBid.h similarity index 98% rename from src/xrpld/app/tx/detail/AMMBid.h rename to include/xrpl/tx/transactors/AMM/AMMBid.h index 83ea6e0729..b80bfe3bef 100644 --- a/src/xrpld/app/tx/detail/AMMBid.h +++ b/include/xrpl/tx/transactors/AMM/AMMBid.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/AMMClawback.h b/include/xrpl/tx/transactors/AMM/AMMClawback.h similarity index 97% rename from src/xrpld/app/tx/detail/AMMClawback.h rename to include/xrpl/tx/transactors/AMM/AMMClawback.h index 3da3c44605..2bfccfa202 100644 --- a/src/xrpld/app/tx/detail/AMMClawback.h +++ b/include/xrpl/tx/transactors/AMM/AMMClawback.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { class Sandbox; diff --git a/src/xrpld/app/paths/AMMContext.h b/include/xrpl/tx/transactors/AMM/AMMContext.h similarity index 100% rename from src/xrpld/app/paths/AMMContext.h rename to include/xrpl/tx/transactors/AMM/AMMContext.h diff --git a/src/xrpld/app/tx/detail/AMMCreate.h b/include/xrpl/tx/transactors/AMM/AMMCreate.h similarity index 98% rename from src/xrpld/app/tx/detail/AMMCreate.h rename to include/xrpl/tx/transactors/AMM/AMMCreate.h index 6f9fd77a2f..5deaa129ed 100644 --- a/src/xrpld/app/tx/detail/AMMCreate.h +++ b/include/xrpl/tx/transactors/AMM/AMMCreate.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/AMMDelete.h b/include/xrpl/tx/transactors/AMM/AMMDelete.h similarity index 94% rename from src/xrpld/app/tx/detail/AMMDelete.h rename to include/xrpl/tx/transactors/AMM/AMMDelete.h index 20c8f87262..1c0996f8a2 100644 --- a/src/xrpld/app/tx/detail/AMMDelete.h +++ b/include/xrpl/tx/transactors/AMM/AMMDelete.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/AMMDeposit.h b/include/xrpl/tx/transactors/AMM/AMMDeposit.h similarity index 99% rename from src/xrpld/app/tx/detail/AMMDeposit.h rename to include/xrpl/tx/transactors/AMM/AMMDeposit.h index 45c7995438..287d46ff07 100644 --- a/src/xrpld/app/tx/detail/AMMDeposit.h +++ b/include/xrpl/tx/transactors/AMM/AMMDeposit.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/misc/AMMHelpers.h b/include/xrpl/tx/transactors/AMM/AMMHelpers.h similarity index 91% rename from src/xrpld/app/misc/AMMHelpers.h rename to include/xrpl/tx/transactors/AMM/AMMHelpers.h index cde485f5dc..1db9176538 100644 --- a/src/xrpld/app/misc/AMMHelpers.h +++ b/include/xrpl/tx/transactors/AMM/AMMHelpers.h @@ -60,7 +60,11 @@ lpTokensOut( * @return */ STAmount -ammAssetIn(STAmount const& asset1Balance, STAmount const& lptAMMBalance, STAmount const& lpTokens, std::uint16_t tfee); +ammAssetIn( + STAmount const& asset1Balance, + STAmount const& lptAMMBalance, + STAmount const& lpTokens, + std::uint16_t tfee); /** Calculate LP Tokens given asset's withdraw amount. Return 0 * if can't calculate. @@ -85,7 +89,11 @@ lpTokensIn( * @return calculated asset amount */ STAmount -ammAssetOut(STAmount const& assetBalance, STAmount const& lptAMMBalance, STAmount const& lpTokens, std::uint16_t tfee); +ammAssetOut( + STAmount const& assetBalance, + STAmount const& lptAMMBalance, + STAmount const& lpTokens, + std::uint16_t tfee); /** Check if the relative distance between the qualities * is within the requested distance. @@ -159,7 +167,10 @@ solveQuadraticEqSmallest(Number const& a, Number const& b, Number const& c); */ template std::optional> -getAMMOfferStartWithTakerGets(TAmounts const& pool, Quality const& targetQuality, std::uint16_t const& tfee) +getAMMOfferStartWithTakerGets( + TAmounts const& pool, + Quality const& targetQuality, + std::uint16_t const& tfee) { if (targetQuality.rate() == beast::zero) return std::nullopt; @@ -185,7 +196,8 @@ getAMMOfferStartWithTakerGets(TAmounts const& pool, Quality const& ta auto getAmounts = [&pool, &tfee](Number const& nTakerGetsProposed) { // Round downward to minimize the offer and to maximize the quality. // This has the most impact when takerGets is XRP. - auto const takerGets = toAmount(getIssue(pool.out), nTakerGetsProposed, Number::downward); + auto const takerGets = + toAmount(getIssue(pool.out), nTakerGetsProposed, Number::downward); return TAmounts{swapAssetOut(pool, takerGets, tfee), takerGets}; }; @@ -222,7 +234,10 @@ getAMMOfferStartWithTakerGets(TAmounts const& pool, Quality const& ta */ template std::optional> -getAMMOfferStartWithTakerPays(TAmounts const& pool, Quality const& targetQuality, std::uint16_t tfee) +getAMMOfferStartWithTakerPays( + TAmounts const& pool, + Quality const& targetQuality, + std::uint16_t tfee) { if (targetQuality.rate() == beast::zero) return std::nullopt; @@ -248,7 +263,8 @@ getAMMOfferStartWithTakerPays(TAmounts const& pool, Quality const& ta auto getAmounts = [&pool, &tfee](Number const& nTakerPaysProposed) { // Round downward to minimize the offer and to maximize the quality. // This has the most impact when takerPays is XRP. - auto const takerPays = toAmount(getIssue(pool.in), nTakerPaysProposed, Number::downward); + auto const takerPays = + toAmount(getIssue(pool.in), nTakerPaysProposed, Number::downward); return TAmounts{takerPays, swapAssetIn(pool, takerPays, tfee)}; }; @@ -313,32 +329,34 @@ changeSpotPriceQuality( }(); if (nTakerPays <= 0) { - JLOG(j.trace()) << "changeSpotPriceQuality calc failed: " << to_string(pool.in) << " " - << to_string(pool.out) << " " << quality << " " << tfee; + JLOG(j.trace()) << "changeSpotPriceQuality calc failed: " << to_string(pool.in) + << " " << to_string(pool.out) << " " << quality << " " << tfee; return std::nullopt; } auto const takerPays = toAmount(getIssue(pool.in), nTakerPays, Number::upward); // should not fail - if (auto const amounts = TAmounts{takerPays, swapAssetIn(pool, takerPays, tfee)}; - Quality{amounts} < quality && !withinRelativeDistance(Quality{amounts}, quality, Number(1, -7))) + if (auto const amounts = + TAmounts{takerPays, swapAssetIn(pool, takerPays, tfee)}; + Quality{amounts} < quality && + !withinRelativeDistance(Quality{amounts}, quality, Number(1, -7))) { - JLOG(j.error()) << "changeSpotPriceQuality failed: " << to_string(pool.in) << " " << to_string(pool.out) - << " " - << " " << quality << " " << tfee << " " << to_string(amounts.in) << " " - << to_string(amounts.out); + JLOG(j.error()) << "changeSpotPriceQuality failed: " << to_string(pool.in) << " " + << to_string(pool.out) << " " + << " " << quality << " " << tfee << " " << to_string(amounts.in) + << " " << to_string(amounts.out); Throw("changeSpotPriceQuality failed"); } else { JLOG(j.trace()) << "changeSpotPriceQuality succeeded: " << to_string(pool.in) << " " << to_string(pool.out) << " " - << " " << quality << " " << tfee << " " << to_string(amounts.in) << " " - << to_string(amounts.out); + << " " << quality << " " << tfee << " " << to_string(amounts.in) + << " " << to_string(amounts.out); return amounts; } } - JLOG(j.trace()) << "changeSpotPriceQuality calc failed: " << to_string(pool.in) << " " << to_string(pool.out) - << " " << quality << " " << tfee; + JLOG(j.trace()) << "changeSpotPriceQuality calc failed: " << to_string(pool.in) << " " + << to_string(pool.out) << " " << quality << " " << tfee; return std::nullopt; } @@ -351,20 +369,23 @@ changeSpotPriceQuality( }(); if (!amounts) { - JLOG(j.trace()) << "changeSpotPrice calc failed: " << to_string(pool.in) << " " << to_string(pool.out) << " " - << quality << " " << tfee << std::endl; + JLOG(j.trace()) << "changeSpotPrice calc failed: " << to_string(pool.in) << " " + << to_string(pool.out) << " " << quality << " " << tfee << std::endl; return std::nullopt; } if (Quality{*amounts} < quality) { - JLOG(j.error()) << "changeSpotPriceQuality failed: " << to_string(pool.in) << " " << to_string(pool.out) << " " - << quality << " " << tfee << " " << to_string(amounts->in) << " " << to_string(amounts->out); + JLOG(j.error()) << "changeSpotPriceQuality failed: " << to_string(pool.in) << " " + << to_string(pool.out) << " " << quality << " " << tfee << " " + << to_string(amounts->in) << " " << to_string(amounts->out); return std::nullopt; } - JLOG(j.trace()) << "changeSpotPriceQuality succeeded: " << to_string(pool.in) << " " << to_string(pool.out) << " " - << " " << quality << " " << tfee << " " << to_string(amounts->in) << " " << to_string(amounts->out); + JLOG(j.trace()) << "changeSpotPriceQuality succeeded: " << to_string(pool.in) << " " + << to_string(pool.out) << " " + << " " << quality << " " << tfee << " " << to_string(amounts->in) << " " + << to_string(amounts->out); return amounts; } @@ -631,7 +652,11 @@ getRoundedAsset( * digits) when adding the lptokens to the balance. */ STAmount -getRoundedLPTokens(Rules const& rules, STAmount const& balance, Number const& frac, IsDeposit isDeposit); +getRoundedLPTokens( + Rules const& rules, + STAmount const& balance, + Number const& frac, + IsDeposit isDeposit); /** Round AMM single deposit/withdrawal LPToken amount. * The lambda's are used to delay evaluation until the function is executed @@ -684,6 +709,10 @@ adjustAssetOutByTokens( * is used to adjust equal deposit/withdraw amount. */ Number -adjustFracByTokens(Rules const& rules, STAmount const& lptAMMBalance, STAmount const& tokens, Number const& frac); +adjustFracByTokens( + Rules const& rules, + STAmount const& lptAMMBalance, + STAmount const& tokens, + Number const& frac); } // namespace xrpl diff --git a/src/xrpld/app/misc/AMMUtils.h b/include/xrpl/tx/transactors/AMM/AMMUtils.h similarity index 95% rename from src/xrpld/app/misc/AMMUtils.h rename to include/xrpl/tx/transactors/AMM/AMMUtils.h index c97397a141..18db7e6555 100644 --- a/src/xrpld/app/misc/AMMUtils.h +++ b/include/xrpl/tx/transactors/AMM/AMMUtils.h @@ -50,7 +50,11 @@ ammLPHolds( beast::Journal const j); STAmount -ammLPHolds(ReadView const& view, SLE const& ammSle, AccountID const& lpAccount, beast::Journal const j); +ammLPHolds( + ReadView const& view, + SLE const& ammSle, + AccountID const& lpAccount, + beast::Journal const j); /** Get AMM trading fee for the given account. The fee is discounted * if the account is the auction slot owner or one of the slot's authorized diff --git a/src/xrpld/app/tx/detail/AMMVote.h b/include/xrpl/tx/transactors/AMM/AMMVote.h similarity index 97% rename from src/xrpld/app/tx/detail/AMMVote.h rename to include/xrpl/tx/transactors/AMM/AMMVote.h index 2bc3da2301..ab04b30993 100644 --- a/src/xrpld/app/tx/detail/AMMVote.h +++ b/include/xrpl/tx/transactors/AMM/AMMVote.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/AMMWithdraw.h b/include/xrpl/tx/transactors/AMM/AMMWithdraw.h similarity index 99% rename from src/xrpld/app/tx/detail/AMMWithdraw.h rename to include/xrpl/tx/transactors/AMM/AMMWithdraw.h index 246c66100c..c15bb68644 100644 --- a/src/xrpld/app/tx/detail/AMMWithdraw.h +++ b/include/xrpl/tx/transactors/AMM/AMMWithdraw.h @@ -1,8 +1,7 @@ #pragma once -#include - #include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/Batch.h b/include/xrpl/tx/transactors/Batch.h similarity index 93% rename from src/xrpld/app/tx/detail/Batch.h rename to include/xrpl/tx/transactors/Batch.h index 8af8b2e020..0861deb094 100644 --- a/src/xrpld/app/tx/detail/Batch.h +++ b/include/xrpl/tx/transactors/Batch.h @@ -1,10 +1,8 @@ #pragma once -#include -#include - #include #include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/Change.h b/include/xrpl/tx/transactors/Change.h similarity index 93% rename from src/xrpld/app/tx/detail/Change.h rename to include/xrpl/tx/transactors/Change.h index 683b054ccb..1bf63ff0db 100644 --- a/src/xrpld/app/tx/detail/Change.h +++ b/include/xrpl/tx/transactors/Change.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/CancelCheck.h b/include/xrpl/tx/transactors/Check/CancelCheck.h similarity index 90% rename from src/xrpld/app/tx/detail/CancelCheck.h rename to include/xrpl/tx/transactors/Check/CancelCheck.h index f125b9af5b..8a0e42c7ca 100644 --- a/src/xrpld/app/tx/detail/CancelCheck.h +++ b/include/xrpl/tx/transactors/Check/CancelCheck.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/CashCheck.h b/include/xrpl/tx/transactors/Check/CashCheck.h similarity index 90% rename from src/xrpld/app/tx/detail/CashCheck.h rename to include/xrpl/tx/transactors/Check/CashCheck.h index 50a4f8a63a..138790cf34 100644 --- a/src/xrpld/app/tx/detail/CashCheck.h +++ b/include/xrpl/tx/transactors/Check/CashCheck.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/CreateCheck.h b/include/xrpl/tx/transactors/Check/CreateCheck.h similarity index 90% rename from src/xrpld/app/tx/detail/CreateCheck.h rename to include/xrpl/tx/transactors/Check/CreateCheck.h index b80536fe02..98950b68f2 100644 --- a/src/xrpld/app/tx/detail/CreateCheck.h +++ b/include/xrpl/tx/transactors/Check/CreateCheck.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/Clawback.h b/include/xrpl/tx/transactors/Clawback.h similarity index 91% rename from src/xrpld/app/tx/detail/Clawback.h rename to include/xrpl/tx/transactors/Clawback.h index 427edb25b4..7451266461 100644 --- a/src/xrpld/app/tx/detail/Clawback.h +++ b/include/xrpl/tx/transactors/Clawback.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/CreateTicket.h b/include/xrpl/tx/transactors/CreateTicket.h similarity index 96% rename from src/xrpld/app/tx/detail/CreateTicket.h rename to include/xrpl/tx/transactors/CreateTicket.h index 2a6e1bb8cc..867ad99c12 100644 --- a/src/xrpld/app/tx/detail/CreateTicket.h +++ b/include/xrpl/tx/transactors/CreateTicket.h @@ -1,7 +1,6 @@ #pragma once -#include -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/Credentials.h b/include/xrpl/tx/transactors/Credentials.h similarity index 97% rename from src/xrpld/app/tx/detail/Credentials.h rename to include/xrpl/tx/transactors/Credentials.h index 02bccde198..8c96f40526 100644 --- a/src/xrpld/app/tx/detail/Credentials.h +++ b/include/xrpl/tx/transactors/Credentials.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/DID.h b/include/xrpl/tx/transactors/DID.h similarity index 95% rename from src/xrpld/app/tx/detail/DID.h rename to include/xrpl/tx/transactors/DID.h index a00039a999..8ab80bc694 100644 --- a/src/xrpld/app/tx/detail/DID.h +++ b/include/xrpl/tx/transactors/DID.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/DelegateSet.h b/include/xrpl/tx/transactors/Delegate/DelegateSet.h similarity index 72% rename from src/xrpld/app/tx/detail/DelegateSet.h rename to include/xrpl/tx/transactors/Delegate/DelegateSet.h index 2120674557..452a6d8305 100644 --- a/src/xrpld/app/tx/detail/DelegateSet.h +++ b/include/xrpl/tx/transactors/Delegate/DelegateSet.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { @@ -24,7 +24,11 @@ public: // Interface used by DeleteAccount static TER - deleteDelegate(ApplyView& view, std::shared_ptr const& sle, AccountID const& account, beast::Journal j); + deleteDelegate( + ApplyView& view, + std::shared_ptr const& sle, + AccountID const& account, + beast::Journal j); }; } // namespace xrpl diff --git a/src/xrpld/app/misc/DelegateUtils.h b/include/xrpl/tx/transactors/Delegate/DelegateUtils.h similarity index 100% rename from src/xrpld/app/misc/DelegateUtils.h rename to include/xrpl/tx/transactors/Delegate/DelegateUtils.h diff --git a/src/xrpld/app/tx/detail/DeleteAccount.h b/include/xrpl/tx/transactors/DeleteAccount.h similarity index 93% rename from src/xrpld/app/tx/detail/DeleteAccount.h rename to include/xrpl/tx/transactors/DeleteAccount.h index 742d1f4257..f55888ee00 100644 --- a/src/xrpld/app/tx/detail/DeleteAccount.h +++ b/include/xrpl/tx/transactors/DeleteAccount.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/DeleteOracle.h b/include/xrpl/tx/transactors/DeleteOracle.h similarity index 82% rename from src/xrpld/app/tx/detail/DeleteOracle.h rename to include/xrpl/tx/transactors/DeleteOracle.h index 7d7cc340cb..bff33205aa 100644 --- a/src/xrpld/app/tx/detail/DeleteOracle.h +++ b/include/xrpl/tx/transactors/DeleteOracle.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { @@ -32,7 +32,11 @@ public: doApply() override; static TER - deleteOracle(ApplyView& view, std::shared_ptr const& sle, AccountID const& account, beast::Journal j); + deleteOracle( + ApplyView& view, + std::shared_ptr const& sle, + AccountID const& account, + beast::Journal j); }; using OracleDelete = DeleteOracle; diff --git a/src/xrpld/app/tx/detail/DepositPreauth.h b/include/xrpl/tx/transactors/DepositPreauth.h similarity index 93% rename from src/xrpld/app/tx/detail/DepositPreauth.h rename to include/xrpl/tx/transactors/DepositPreauth.h index f1afac3b18..24050da600 100644 --- a/src/xrpld/app/tx/detail/DepositPreauth.h +++ b/include/xrpl/tx/transactors/DepositPreauth.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/Escrow.h b/include/xrpl/tx/transactors/Escrow.h similarity index 97% rename from src/xrpld/app/tx/detail/Escrow.h rename to include/xrpl/tx/transactors/Escrow.h index cb99dcae06..0fd627e5a9 100644 --- a/src/xrpld/app/tx/detail/Escrow.h +++ b/include/xrpl/tx/transactors/Escrow.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/LedgerStateFix.h b/include/xrpl/tx/transactors/LedgerStateFix.h similarity index 92% rename from src/xrpld/app/tx/detail/LedgerStateFix.h rename to include/xrpl/tx/transactors/LedgerStateFix.h index 66fe124cff..728f8c651d 100644 --- a/src/xrpld/app/tx/detail/LedgerStateFix.h +++ b/include/xrpl/tx/transactors/LedgerStateFix.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/misc/LendingHelpers.h b/include/xrpl/tx/transactors/Lending/LendingHelpers.h similarity index 97% rename from src/xrpld/app/misc/LendingHelpers.h rename to include/xrpl/tx/transactors/Lending/LendingHelpers.h index f8297dfdf7..4057c9c173 100644 --- a/src/xrpld/app/misc/LendingHelpers.h +++ b/include/xrpl/tx/transactors/Lending/LendingHelpers.h @@ -154,7 +154,11 @@ struct LoanProperties // accumulated rounding errors and leftover dust amounts. template void -adjustImpreciseNumber(NumberProxy value, Number const& adjustment, Asset const& asset, int vaultScale) +adjustImpreciseNumber( + NumberProxy value, + Number const& adjustment, + Asset const& asset, + int vaultScale) { value = roundToAsset(asset, value + adjustment, vaultScale); @@ -199,7 +203,11 @@ LoanState constructRoundedLoanState(SLE::const_ref loan); Number -computeManagementFee(Asset const& asset, Number const& interest, TenthBips32 managementFeeRate, std::int32_t scale); +computeManagementFee( + Asset const& asset, + Number const& interest, + TenthBips32 managementFeeRate, + std::int32_t scale); Number computeFullPaymentInterest( @@ -370,7 +378,10 @@ computeInterestAndFeeParts( std::int32_t loanScale); Number -loanPeriodicPayment(Number const& principalOutstanding, Number const& periodicRate, std::uint32_t paymentsRemaining); +loanPeriodicPayment( + Number const& principalOutstanding, + Number const& periodicRate, + std::uint32_t paymentsRemaining); Number loanPrincipalFromPeriodicPayment( diff --git a/src/xrpld/app/tx/detail/LoanBrokerCoverClawback.h b/include/xrpl/tx/transactors/Lending/LoanBrokerCoverClawback.h similarity index 93% rename from src/xrpld/app/tx/detail/LoanBrokerCoverClawback.h rename to include/xrpl/tx/transactors/Lending/LoanBrokerCoverClawback.h index 139d50696a..b1e539392f 100644 --- a/src/xrpld/app/tx/detail/LoanBrokerCoverClawback.h +++ b/include/xrpl/tx/transactors/Lending/LoanBrokerCoverClawback.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/LoanBrokerCoverDeposit.h b/include/xrpl/tx/transactors/Lending/LoanBrokerCoverDeposit.h similarity index 92% rename from src/xrpld/app/tx/detail/LoanBrokerCoverDeposit.h rename to include/xrpl/tx/transactors/Lending/LoanBrokerCoverDeposit.h index 3f683c6a62..8dda417443 100644 --- a/src/xrpld/app/tx/detail/LoanBrokerCoverDeposit.h +++ b/include/xrpl/tx/transactors/Lending/LoanBrokerCoverDeposit.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/LoanBrokerCoverWithdraw.h b/include/xrpl/tx/transactors/Lending/LoanBrokerCoverWithdraw.h similarity index 93% rename from src/xrpld/app/tx/detail/LoanBrokerCoverWithdraw.h rename to include/xrpl/tx/transactors/Lending/LoanBrokerCoverWithdraw.h index 50d0b98fa5..52b14bfb67 100644 --- a/src/xrpld/app/tx/detail/LoanBrokerCoverWithdraw.h +++ b/include/xrpl/tx/transactors/Lending/LoanBrokerCoverWithdraw.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/LoanBrokerDelete.h b/include/xrpl/tx/transactors/Lending/LoanBrokerDelete.h similarity index 92% rename from src/xrpld/app/tx/detail/LoanBrokerDelete.h rename to include/xrpl/tx/transactors/Lending/LoanBrokerDelete.h index cb44277f55..b9c9851c41 100644 --- a/src/xrpld/app/tx/detail/LoanBrokerDelete.h +++ b/include/xrpl/tx/transactors/Lending/LoanBrokerDelete.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/LoanBrokerSet.h b/include/xrpl/tx/transactors/Lending/LoanBrokerSet.h similarity index 93% rename from src/xrpld/app/tx/detail/LoanBrokerSet.h rename to include/xrpl/tx/transactors/Lending/LoanBrokerSet.h index cda452bebe..ce1e069791 100644 --- a/src/xrpld/app/tx/detail/LoanBrokerSet.h +++ b/include/xrpl/tx/transactors/Lending/LoanBrokerSet.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/LoanDelete.h b/include/xrpl/tx/transactors/Lending/LoanDelete.h similarity index 92% rename from src/xrpld/app/tx/detail/LoanDelete.h rename to include/xrpl/tx/transactors/Lending/LoanDelete.h index 37889d31fb..ff78d7db60 100644 --- a/src/xrpld/app/tx/detail/LoanDelete.h +++ b/include/xrpl/tx/transactors/Lending/LoanDelete.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/LoanManage.h b/include/xrpl/tx/transactors/Lending/LoanManage.h similarity index 76% rename from src/xrpld/app/tx/detail/LoanManage.h rename to include/xrpl/tx/transactors/Lending/LoanManage.h index 44b2b62b3d..810e9bbf65 100644 --- a/src/xrpld/app/tx/detail/LoanManage.h +++ b/include/xrpl/tx/transactors/Lending/LoanManage.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { @@ -39,12 +39,22 @@ public: /** Helper function that might be needed by other transactors */ static TER - impairLoan(ApplyView& view, SLE::ref loanSle, SLE::ref vaultSle, Asset const& vaultAsset, beast::Journal j); + impairLoan( + ApplyView& view, + SLE::ref loanSle, + SLE::ref vaultSle, + Asset const& vaultAsset, + beast::Journal j); /** Helper function that might be needed by other transactors */ [[nodiscard]] static TER - unimpairLoan(ApplyView& view, SLE::ref loanSle, SLE::ref vaultSle, Asset const& vaultAsset, beast::Journal j); + unimpairLoan( + ApplyView& view, + SLE::ref loanSle, + SLE::ref vaultSle, + Asset const& vaultAsset, + beast::Journal j); TER doApply() override; diff --git a/src/xrpld/app/tx/detail/LoanPay.h b/include/xrpl/tx/transactors/Lending/LoanPay.h similarity index 94% rename from src/xrpld/app/tx/detail/LoanPay.h rename to include/xrpl/tx/transactors/Lending/LoanPay.h index c947b1b6f8..2e3cce75ed 100644 --- a/src/xrpld/app/tx/detail/LoanPay.h +++ b/include/xrpl/tx/transactors/Lending/LoanPay.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/LoanSet.h b/include/xrpl/tx/transactors/Lending/LoanSet.h similarity index 93% rename from src/xrpld/app/tx/detail/LoanSet.h rename to include/xrpl/tx/transactors/Lending/LoanSet.h index e4bb79a36d..e9916b9d6b 100644 --- a/src/xrpld/app/tx/detail/LoanSet.h +++ b/include/xrpl/tx/transactors/Lending/LoanSet.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/MPTokenAuthorize.h b/include/xrpl/tx/transactors/MPT/MPTokenAuthorize.h similarity index 79% rename from src/xrpld/app/tx/detail/MPTokenAuthorize.h rename to include/xrpl/tx/transactors/MPT/MPTokenAuthorize.h index c887b70fa8..b6a34d4f14 100644 --- a/src/xrpld/app/tx/detail/MPTokenAuthorize.h +++ b/include/xrpl/tx/transactors/MPT/MPTokenAuthorize.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { @@ -32,7 +32,11 @@ public: preclaim(PreclaimContext const& ctx); static TER - createMPToken(ApplyView& view, MPTID const& mptIssuanceID, AccountID const& account, std::uint32_t const flags); + createMPToken( + ApplyView& view, + MPTID const& mptIssuanceID, + AccountID const& account, + std::uint32_t const flags); TER doApply() override; diff --git a/src/xrpld/app/tx/detail/MPTokenIssuanceCreate.h b/include/xrpl/tx/transactors/MPT/MPTokenIssuanceCreate.h similarity index 96% rename from src/xrpld/app/tx/detail/MPTokenIssuanceCreate.h rename to include/xrpl/tx/transactors/MPT/MPTokenIssuanceCreate.h index 56c20ed551..0ebde22a37 100644 --- a/src/xrpld/app/tx/detail/MPTokenIssuanceCreate.h +++ b/include/xrpl/tx/transactors/MPT/MPTokenIssuanceCreate.h @@ -1,9 +1,8 @@ #pragma once -#include - #include #include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/MPTokenIssuanceDestroy.h b/include/xrpl/tx/transactors/MPT/MPTokenIssuanceDestroy.h similarity index 91% rename from src/xrpld/app/tx/detail/MPTokenIssuanceDestroy.h rename to include/xrpl/tx/transactors/MPT/MPTokenIssuanceDestroy.h index 89243944d0..c4a448032a 100644 --- a/src/xrpld/app/tx/detail/MPTokenIssuanceDestroy.h +++ b/include/xrpl/tx/transactors/MPT/MPTokenIssuanceDestroy.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/MPTokenIssuanceSet.h b/include/xrpl/tx/transactors/MPT/MPTokenIssuanceSet.h similarity index 93% rename from src/xrpld/app/tx/detail/MPTokenIssuanceSet.h rename to include/xrpl/tx/transactors/MPT/MPTokenIssuanceSet.h index 68794ca48c..dccd4e4cee 100644 --- a/src/xrpld/app/tx/detail/MPTokenIssuanceSet.h +++ b/include/xrpl/tx/transactors/MPT/MPTokenIssuanceSet.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/NFTokenAcceptOffer.h b/include/xrpl/tx/transactors/NFT/NFTokenAcceptOffer.h similarity index 95% rename from src/xrpld/app/tx/detail/NFTokenAcceptOffer.h rename to include/xrpl/tx/transactors/NFT/NFTokenAcceptOffer.h index 549c38d33b..d876a70362 100644 --- a/src/xrpld/app/tx/detail/NFTokenAcceptOffer.h +++ b/include/xrpl/tx/transactors/NFT/NFTokenAcceptOffer.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/NFTokenBurn.h b/include/xrpl/tx/transactors/NFT/NFTokenBurn.h similarity index 90% rename from src/xrpld/app/tx/detail/NFTokenBurn.h rename to include/xrpl/tx/transactors/NFT/NFTokenBurn.h index c2bc300ab8..8737997f03 100644 --- a/src/xrpld/app/tx/detail/NFTokenBurn.h +++ b/include/xrpl/tx/transactors/NFT/NFTokenBurn.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/NFTokenCancelOffer.h b/include/xrpl/tx/transactors/NFT/NFTokenCancelOffer.h similarity index 91% rename from src/xrpld/app/tx/detail/NFTokenCancelOffer.h rename to include/xrpl/tx/transactors/NFT/NFTokenCancelOffer.h index b1801ede25..bb8cd4c216 100644 --- a/src/xrpld/app/tx/detail/NFTokenCancelOffer.h +++ b/include/xrpl/tx/transactors/NFT/NFTokenCancelOffer.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/NFTokenCreateOffer.h b/include/xrpl/tx/transactors/NFT/NFTokenCreateOffer.h similarity index 91% rename from src/xrpld/app/tx/detail/NFTokenCreateOffer.h rename to include/xrpl/tx/transactors/NFT/NFTokenCreateOffer.h index ed54338f49..a48e53589d 100644 --- a/src/xrpld/app/tx/detail/NFTokenCreateOffer.h +++ b/include/xrpl/tx/transactors/NFT/NFTokenCreateOffer.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/NFTokenMint.h b/include/xrpl/tx/transactors/NFT/NFTokenMint.h similarity index 89% rename from src/xrpld/app/tx/detail/NFTokenMint.h rename to include/xrpl/tx/transactors/NFT/NFTokenMint.h index 52981ef467..c3a7db4581 100644 --- a/src/xrpld/app/tx/detail/NFTokenMint.h +++ b/include/xrpl/tx/transactors/NFT/NFTokenMint.h @@ -1,9 +1,8 @@ #pragma once -#include -#include - #include +#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/NFTokenModify.h b/include/xrpl/tx/transactors/NFT/NFTokenModify.h similarity index 90% rename from src/xrpld/app/tx/detail/NFTokenModify.h rename to include/xrpl/tx/transactors/NFT/NFTokenModify.h index f755746f1f..a64df65783 100644 --- a/src/xrpld/app/tx/detail/NFTokenModify.h +++ b/include/xrpl/tx/transactors/NFT/NFTokenModify.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/NFTokenUtils.h b/include/xrpl/tx/transactors/NFT/NFTokenUtils.h similarity index 85% rename from src/xrpld/app/tx/detail/NFTokenUtils.h rename to include/xrpl/tx/transactors/NFT/NFTokenUtils.h index 44d3cfb956..a5e2b30354 100644 --- a/src/xrpld/app/tx/detail/NFTokenUtils.h +++ b/include/xrpl/tx/transactors/NFT/NFTokenUtils.h @@ -1,12 +1,11 @@ #pragma once -#include - #include #include #include #include #include +#include namespace xrpl { @@ -15,7 +14,10 @@ namespace nft { /** Delete up to a specified number of offers from the specified token offer * directory. */ std::size_t -removeTokenOffersWithLimit(ApplyView& view, Keylet const& directory, std::size_t maxDeletableOffers); +removeTokenOffersWithLimit( + ApplyView& view, + Keylet const& directory, + std::size_t maxDeletableOffers); /** Returns tesSUCCESS if NFToken has few enough offers that it can be burned */ TER @@ -31,7 +33,8 @@ struct TokenAndPage STObject token; std::shared_ptr page; - TokenAndPage(STObject const& token_, std::shared_ptr page_) : token(token_), page(std::move(page_)) + TokenAndPage(STObject const& token_, std::shared_ptr page_) + : token(token_), page(std::move(page_)) { } }; @@ -47,7 +50,11 @@ TER removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID); TER -removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID, std::shared_ptr&& page); +removeToken( + ApplyView& view, + AccountID const& owner, + uint256 const& nftokenID, + std::shared_ptr&& page); /** Deletes the given token offer. @@ -119,10 +126,18 @@ tokenOfferCreateApply( std::uint32_t txFlags = lsfSellNFToken); TER -checkTrustlineAuthorized(ReadView const& view, AccountID const id, beast::Journal const j, Issue const& issue); +checkTrustlineAuthorized( + ReadView const& view, + AccountID const id, + beast::Journal const j, + Issue const& issue); TER -checkTrustlineDeepFrozen(ReadView const& view, AccountID const id, beast::Journal const j, Issue const& issue); +checkTrustlineDeepFrozen( + ReadView const& view, + AccountID const id, + beast::Journal const j, + Issue const& issue); } // namespace nft diff --git a/src/xrpld/app/tx/detail/CancelOffer.h b/include/xrpl/tx/transactors/Offer/CancelOffer.h similarity index 91% rename from src/xrpld/app/tx/detail/CancelOffer.h rename to include/xrpl/tx/transactors/Offer/CancelOffer.h index 30a7129fb4..6107c3211f 100644 --- a/src/xrpld/app/tx/detail/CancelOffer.h +++ b/include/xrpl/tx/transactors/Offer/CancelOffer.h @@ -1,8 +1,7 @@ #pragma once -#include - #include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/CreateOffer.h b/include/xrpl/tx/transactors/Offer/CreateOffer.h similarity index 97% rename from src/xrpld/app/tx/detail/CreateOffer.h rename to include/xrpl/tx/transactors/Offer/CreateOffer.h index 14f82c501e..cb15d08ace 100644 --- a/src/xrpld/app/tx/detail/CreateOffer.h +++ b/include/xrpl/tx/transactors/Offer/CreateOffer.h @@ -1,8 +1,7 @@ #pragma once -#include - #include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/PayChan.h b/include/xrpl/tx/transactors/PayChan.h similarity index 97% rename from src/xrpld/app/tx/detail/PayChan.h rename to include/xrpl/tx/transactors/PayChan.h index 8748ec9383..cc23f029f2 100644 --- a/src/xrpld/app/tx/detail/PayChan.h +++ b/include/xrpl/tx/transactors/PayChan.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/Payment.h b/include/xrpl/tx/transactors/Payment.h similarity index 95% rename from src/xrpld/app/tx/detail/Payment.h rename to include/xrpl/tx/transactors/Payment.h index 192f2b0edb..bc5bc4fee3 100644 --- a/src/xrpld/app/tx/detail/Payment.h +++ b/include/xrpl/tx/transactors/Payment.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/misc/PermissionedDEXHelpers.h b/include/xrpl/tx/transactors/PermissionedDEXHelpers.h similarity index 75% rename from src/xrpld/app/misc/PermissionedDEXHelpers.h rename to include/xrpl/tx/transactors/PermissionedDEXHelpers.h index 832129db2f..3992f8885e 100644 --- a/src/xrpld/app/misc/PermissionedDEXHelpers.h +++ b/include/xrpl/tx/transactors/PermissionedDEXHelpers.h @@ -10,7 +10,11 @@ accountInDomain(ReadView const& view, AccountID const& account, Domain const& do // Check if an offer is in the permissioned domain [[nodiscard]] bool -offerInDomain(ReadView const& view, uint256 const& offerID, Domain const& domainID, beast::Journal j); +offerInDomain( + ReadView const& view, + uint256 const& offerID, + Domain const& domainID, + beast::Journal j); } // namespace permissioned_dex diff --git a/src/xrpld/app/tx/detail/PermissionedDomainDelete.h b/include/xrpl/tx/transactors/PermissionedDomain/PermissionedDomainDelete.h similarity index 91% rename from src/xrpld/app/tx/detail/PermissionedDomainDelete.h rename to include/xrpl/tx/transactors/PermissionedDomain/PermissionedDomainDelete.h index 294fb794ae..b5c72413a2 100644 --- a/src/xrpld/app/tx/detail/PermissionedDomainDelete.h +++ b/include/xrpl/tx/transactors/PermissionedDomain/PermissionedDomainDelete.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/PermissionedDomainSet.h b/include/xrpl/tx/transactors/PermissionedDomain/PermissionedDomainSet.h similarity index 92% rename from src/xrpld/app/tx/detail/PermissionedDomainSet.h rename to include/xrpl/tx/transactors/PermissionedDomain/PermissionedDomainSet.h index 824104e50d..acf9194ee2 100644 --- a/src/xrpld/app/tx/detail/PermissionedDomainSet.h +++ b/include/xrpl/tx/transactors/PermissionedDomain/PermissionedDomainSet.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/SetAccount.h b/include/xrpl/tx/transactors/SetAccount.h similarity index 94% rename from src/xrpld/app/tx/detail/SetAccount.h rename to include/xrpl/tx/transactors/SetAccount.h index db59826347..3abfcb43bb 100644 --- a/src/xrpld/app/tx/detail/SetAccount.h +++ b/include/xrpl/tx/transactors/SetAccount.h @@ -1,8 +1,7 @@ #pragma once -#include - #include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/SetOracle.h b/include/xrpl/tx/transactors/SetOracle.h similarity index 94% rename from src/xrpld/app/tx/detail/SetOracle.h rename to include/xrpl/tx/transactors/SetOracle.h index 6b47a5397e..be1a7b8821 100644 --- a/src/xrpld/app/tx/detail/SetOracle.h +++ b/include/xrpl/tx/transactors/SetOracle.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/SetRegularKey.h b/include/xrpl/tx/transactors/SetRegularKey.h similarity index 90% rename from src/xrpld/app/tx/detail/SetRegularKey.h rename to include/xrpl/tx/transactors/SetRegularKey.h index bc712b319a..bb1dd48a68 100644 --- a/src/xrpld/app/tx/detail/SetRegularKey.h +++ b/include/xrpl/tx/transactors/SetRegularKey.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/SetSignerList.h b/include/xrpl/tx/transactors/SetSignerList.h similarity index 88% rename from src/xrpld/app/tx/detail/SetSignerList.h rename to include/xrpl/tx/transactors/SetSignerList.h index efd8e508f9..4c2489922d 100644 --- a/src/xrpld/app/tx/detail/SetSignerList.h +++ b/include/xrpl/tx/transactors/SetSignerList.h @@ -1,10 +1,9 @@ #pragma once -#include -#include - #include #include +#include +#include #include #include @@ -44,7 +43,11 @@ public: // Interface used by DeleteAccount static TER - removeFromLedger(Application& app, ApplyView& view, AccountID const& account, beast::Journal j); + removeFromLedger( + ServiceRegistry& registry, + ApplyView& view, + AccountID const& account, + beast::Journal j); private: static std::tuple, Operation> diff --git a/src/xrpld/app/tx/detail/SetTrust.h b/include/xrpl/tx/transactors/SetTrust.h similarity index 93% rename from src/xrpld/app/tx/detail/SetTrust.h rename to include/xrpl/tx/transactors/SetTrust.h index 1081567a66..47ec26b6ad 100644 --- a/src/xrpld/app/tx/detail/SetTrust.h +++ b/include/xrpl/tx/transactors/SetTrust.h @@ -1,8 +1,7 @@ #pragma once -#include - #include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/VaultClawback.h b/include/xrpl/tx/transactors/Vault/VaultClawback.h similarity index 93% rename from src/xrpld/app/tx/detail/VaultClawback.h rename to include/xrpl/tx/transactors/Vault/VaultClawback.h index c93289e641..131a1d87e7 100644 --- a/src/xrpld/app/tx/detail/VaultClawback.h +++ b/include/xrpl/tx/transactors/Vault/VaultClawback.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/VaultCreate.h b/include/xrpl/tx/transactors/Vault/VaultCreate.h similarity index 92% rename from src/xrpld/app/tx/detail/VaultCreate.h rename to include/xrpl/tx/transactors/Vault/VaultCreate.h index 20b18f5cc2..cc35cd765b 100644 --- a/src/xrpld/app/tx/detail/VaultCreate.h +++ b/include/xrpl/tx/transactors/Vault/VaultCreate.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/VaultDelete.h b/include/xrpl/tx/transactors/Vault/VaultDelete.h similarity index 90% rename from src/xrpld/app/tx/detail/VaultDelete.h rename to include/xrpl/tx/transactors/Vault/VaultDelete.h index 8d1f214885..f881a692fd 100644 --- a/src/xrpld/app/tx/detail/VaultDelete.h +++ b/include/xrpl/tx/transactors/Vault/VaultDelete.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/VaultDeposit.h b/include/xrpl/tx/transactors/Vault/VaultDeposit.h similarity index 90% rename from src/xrpld/app/tx/detail/VaultDeposit.h rename to include/xrpl/tx/transactors/Vault/VaultDeposit.h index 6c63308407..0943596f20 100644 --- a/src/xrpld/app/tx/detail/VaultDeposit.h +++ b/include/xrpl/tx/transactors/Vault/VaultDeposit.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/VaultSet.h b/include/xrpl/tx/transactors/Vault/VaultSet.h similarity index 91% rename from src/xrpld/app/tx/detail/VaultSet.h rename to include/xrpl/tx/transactors/Vault/VaultSet.h index 1e8a15291e..fb69f132b1 100644 --- a/src/xrpld/app/tx/detail/VaultSet.h +++ b/include/xrpl/tx/transactors/Vault/VaultSet.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/VaultWithdraw.h b/include/xrpl/tx/transactors/Vault/VaultWithdraw.h similarity index 90% rename from src/xrpld/app/tx/detail/VaultWithdraw.h rename to include/xrpl/tx/transactors/Vault/VaultWithdraw.h index f832c206f8..ffe14a7141 100644 --- a/src/xrpld/app/tx/detail/VaultWithdraw.h +++ b/include/xrpl/tx/transactors/Vault/VaultWithdraw.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/XChainBridge.h b/include/xrpl/tx/transactors/XChainBridge.h similarity index 99% rename from src/xrpld/app/tx/detail/XChainBridge.h rename to include/xrpl/tx/transactors/XChainBridge.h index 3d0c250f24..0a2fccc18b 100644 --- a/src/xrpld/app/tx/detail/XChainBridge.h +++ b/include/xrpl/tx/transactors/XChainBridge.h @@ -1,8 +1,7 @@ #pragma once -#include - #include +#include namespace xrpl { diff --git a/src/libxrpl/basics/Archive.cpp b/src/libxrpl/basics/Archive.cpp index a4100e8196..06f19b27ee 100644 --- a/src/libxrpl/basics/Archive.cpp +++ b/src/libxrpl/basics/Archive.cpp @@ -41,8 +41,9 @@ extractTarLz4(boost::filesystem::path const& src, boost::filesystem::path const& Throw("Failed to allocate archive"); if (archive_write_disk_set_options( - aw.get(), ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_ACL | ARCHIVE_EXTRACT_FFLAGS) < - ARCHIVE_OK) + aw.get(), + ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_ACL | + ARCHIVE_EXTRACT_FFLAGS) < ARCHIVE_OK) { Throw(archive_error_string(aw.get())); } diff --git a/src/libxrpl/basics/BasicConfig.cpp b/src/libxrpl/basics/BasicConfig.cpp index 64e80c63ec..63d3a56c40 100644 --- a/src/libxrpl/basics/BasicConfig.cpp +++ b/src/libxrpl/basics/BasicConfig.cpp @@ -132,7 +132,8 @@ BasicConfig::section(std::string const& name) const void BasicConfig::overwrite(std::string const& section, std::string const& key, std::string const& value) { - auto const result = map_.emplace(std::piecewise_construct, std::make_tuple(section), std::make_tuple(section)); + auto const result = + map_.emplace(std::piecewise_construct, std::make_tuple(section), std::make_tuple(section)); result.first->second.set(key, value); } @@ -161,8 +162,8 @@ BasicConfig::build(IniFileSections const& ifs) { for (auto const& entry : ifs) { - auto const result = - map_.emplace(std::piecewise_construct, std::make_tuple(entry.first), std::make_tuple(entry.first)); + auto const result = map_.emplace( + std::piecewise_construct, std::make_tuple(entry.first), std::make_tuple(entry.first)); result.first->second.append(entry.second); } } diff --git a/src/libxrpl/basics/FileUtilities.cpp b/src/libxrpl/basics/FileUtilities.cpp index 35cc4350ef..0f636276da 100644 --- a/src/libxrpl/basics/FileUtilities.cpp +++ b/src/libxrpl/basics/FileUtilities.cpp @@ -45,7 +45,8 @@ getFileContents( return {}; } - std::string const result{std::istreambuf_iterator{fileStream}, std::istreambuf_iterator{}}; + std::string const result{ + std::istreambuf_iterator{fileStream}, std::istreambuf_iterator{}}; if (fileStream.bad()) { @@ -57,7 +58,10 @@ getFileContents( } void -writeFileContents(boost::system::error_code& ec, boost::filesystem::path const& destPath, std::string const& contents) +writeFileContents( + boost::system::error_code& ec, + boost::filesystem::path const& destPath, + std::string const& contents) { using namespace boost::filesystem; using namespace boost::system::errc; diff --git a/src/libxrpl/basics/Log.cpp b/src/libxrpl/basics/Log.cpp index fc5100a152..3e36b7d458 100644 --- a/src/libxrpl/basics/Log.cpp +++ b/src/libxrpl/basics/Log.cpp @@ -163,7 +163,11 @@ Logs::partition_severities() const } void -Logs::write(beast::severities::Severity level, std::string const& partition, std::string const& text, bool console) +Logs::write( + beast::severities::Severity level, + std::string const& partition, + std::string const& text, + bool console) { std::string s; format(s, text, level, partition); diff --git a/src/libxrpl/basics/Number.cpp b/src/libxrpl/basics/Number.cpp index 1651e8aba2..59a41157db 100644 --- a/src/libxrpl/basics/Number.cpp +++ b/src/libxrpl/basics/Number.cpp @@ -211,7 +211,11 @@ Number::Guard::round() noexcept template void -Number::Guard::bringIntoRange(bool& negative, T& mantissa, int& exponent, internalrep const& minMantissa) +Number::Guard::bringIntoRange( + bool& negative, + T& mantissa, + int& exponent, + internalrep const& minMantissa) { // Bring mantissa back into the minMantissa / maxMantissa range AFTER // rounding @@ -259,7 +263,11 @@ Number::Guard::doRoundUp( template void -Number::Guard::doRoundDown(bool& negative, T& mantissa, int& exponent, internalrep const& minMantissa) +Number::Guard::doRoundDown( + bool& negative, + T& mantissa, + int& exponent, + internalrep const& minMantissa) { auto r = round(); if (r == 1 || (r == 0 && (mantissa & 1) == 1)) @@ -428,7 +436,9 @@ doNormalize( g.doRoundUp(negative, mantissa_, exponent_, minMantissa, maxMantissa, "Number::normalize 2"); XRPL_ASSERT_PARTS( - mantissa_ >= minMantissa && mantissa_ <= maxMantissa, "xrpl::doNormalize", "final mantissa fits in range"); + mantissa_ >= minMantissa && mantissa_ <= maxMantissa, + "xrpl::doNormalize", + "final mantissa fits in range"); } template <> @@ -669,7 +679,12 @@ Number::operator*=(Number const& y) xm = static_cast(zm); xe = ze; g.doRoundUp( - zn, xm, xe, minMantissa, maxMantissa, "Number::multiplication overflow : exponent is " + std::to_string(xe)); + zn, + xm, + xe, + minMantissa, + maxMantissa, + "Number::multiplication overflow : exponent is " + std::to_string(xe)); negative_ = zn; mantissa_ = xm; exponent_ = xe; @@ -773,7 +788,8 @@ Number::operator/=(Number const& y) return *this; } -Number::operator rep() const +Number:: +operator rep() const { rep drops = mantissa(); int offset = exponent(); @@ -884,9 +900,11 @@ to_string(Number const& amount) XRPL_ASSERT(post_to >= post_from, "xrpl::to_string(Number) : second distance check"); - post_to = std::find_if(std::make_reverse_iterator(post_to), std::make_reverse_iterator(post_from), [](char c) { - return c != '0'; - }).base(); + post_to = std::find_if( + std::make_reverse_iterator(post_to), + std::make_reverse_iterator(post_from), + [](char c) { return c != '0'; }) + .base(); std::string ret; diff --git a/src/libxrpl/basics/ResolverAsio.cpp b/src/libxrpl/basics/ResolverAsio.cpp index 78346870a7..7c0a93a930 100644 --- a/src/libxrpl/basics/ResolverAsio.cpp +++ b/src/libxrpl/basics/ResolverAsio.cpp @@ -187,7 +187,8 @@ public: boost::asio::dispatch( m_io_context, boost::asio::bind_executor( - m_strand, std::bind(&ResolverAsioImpl::do_stop, this, CompletionCounter(this)))); + m_strand, + std::bind(&ResolverAsioImpl::do_stop, this, CompletionCounter(this)))); JLOG(m_journal.debug()) << "Queued a stop request"; } @@ -216,7 +217,9 @@ public: boost::asio::dispatch( m_io_context, boost::asio::bind_executor( - m_strand, std::bind(&ResolverAsioImpl::do_resolve, this, names, handler, CompletionCounter(this)))); + m_strand, + std::bind( + &ResolverAsioImpl::do_resolve, this, names, handler, CompletionCounter(this)))); } //------------------------------------------------------------------------- @@ -264,7 +267,8 @@ public: boost::asio::post( m_io_context, - boost::asio::bind_executor(m_strand, std::bind(&ResolverAsioImpl::do_work, this, CompletionCounter(this)))); + boost::asio::bind_executor( + m_strand, std::bind(&ResolverAsioImpl::do_work, this, CompletionCounter(this)))); } HostAndPort @@ -339,7 +343,8 @@ public: boost::asio::post( m_io_context, boost::asio::bind_executor( - m_strand, std::bind(&ResolverAsioImpl::do_work, this, CompletionCounter(this)))); + m_strand, + std::bind(&ResolverAsioImpl::do_work, this, CompletionCounter(this)))); return; } @@ -366,15 +371,16 @@ public: { m_work.emplace_back(names, handler); - JLOG(m_journal.debug()) << "Queued new job with " << names.size() << " tasks. " << m_work.size() - << " jobs outstanding."; + JLOG(m_journal.debug()) << "Queued new job with " << names.size() << " tasks. " + << m_work.size() << " jobs outstanding."; if (m_work.size() > 0) { boost::asio::post( m_io_context, boost::asio::bind_executor( - m_strand, std::bind(&ResolverAsioImpl::do_work, this, CompletionCounter(this)))); + m_strand, + std::bind(&ResolverAsioImpl::do_work, this, CompletionCounter(this)))); } } } diff --git a/src/libxrpl/basics/base64.cpp b/src/libxrpl/basics/base64.cpp index 3b692bc743..fa06ac2cdc 100644 --- a/src/libxrpl/basics/base64.cpp +++ b/src/libxrpl/basics/base64.cpp @@ -47,7 +47,8 @@ namespace base64 { inline char const* get_alphabet() { - static char constexpr tab[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}; + static char constexpr tab[] = { + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}; return &tab[0]; } diff --git a/src/libxrpl/basics/make_SSLContext.cpp b/src/libxrpl/basics/make_SSLContext.cpp index 57cbf7a24a..885275be9e 100644 --- a/src/libxrpl/basics/make_SSLContext.cpp +++ b/src/libxrpl/basics/make_SSLContext.cpp @@ -174,19 +174,22 @@ initAnonymous(boost::asio::ssl::context& context) X509V3_set_ctx_nodb(&ctx); X509V3_set_ctx(&ctx, x509, x509, nullptr, nullptr, 0); - if (auto ext = X509V3_EXT_conf_nid(nullptr, &ctx, NID_basic_constraints, "critical,CA:FALSE")) + if (auto ext = + X509V3_EXT_conf_nid(nullptr, &ctx, NID_basic_constraints, "critical,CA:FALSE")) { X509_add_ext(x509, ext, -1); X509_EXTENSION_free(ext); } - if (auto ext = X509V3_EXT_conf_nid(nullptr, &ctx, NID_ext_key_usage, "critical,serverAuth,clientAuth")) + if (auto ext = X509V3_EXT_conf_nid( + nullptr, &ctx, NID_ext_key_usage, "critical,serverAuth,clientAuth")) { X509_add_ext(x509, ext, -1); X509_EXTENSION_free(ext); } - if (auto ext = X509V3_EXT_conf_nid(nullptr, &ctx, NID_key_usage, "critical,digitalSignature")) + if (auto ext = + X509V3_EXT_conf_nid(nullptr, &ctx, NID_key_usage, "critical,digitalSignature")) { X509_add_ext(x509, ext, -1); X509_EXTENSION_free(ext); @@ -286,7 +289,8 @@ initAuthenticated( catch (std::exception const& ex) { fclose(f); - LogicError(std::string("Reading the SSL chain file generated an exception: ") + ex.what()); + LogicError( + std::string("Reading the SSL chain file generated an exception: ") + ex.what()); } } diff --git a/src/libxrpl/beast/clock/basic_seconds_clock.cpp b/src/libxrpl/beast/clock/basic_seconds_clock.cpp index 27fb7b78c9..5248657479 100644 --- a/src/libxrpl/beast/clock/basic_seconds_clock.cpp +++ b/src/libxrpl/beast/clock/basic_seconds_clock.cpp @@ -38,7 +38,8 @@ static_assert(std::atomic::is_always_lock_free); seconds_clock_thread::~seconds_clock_thread() { - XRPL_ASSERT(thread_.joinable(), "beast::seconds_clock_thread::~seconds_clock_thread : thread joinable"); + XRPL_ASSERT( + thread_.joinable(), "beast::seconds_clock_thread::~seconds_clock_thread : thread joinable"); { std::lock_guard lock(mut_); stop_ = true; @@ -47,7 +48,8 @@ seconds_clock_thread::~seconds_clock_thread() thread_.join(); } -seconds_clock_thread::seconds_clock_thread() : stop_{false}, tp_{Clock::now().time_since_epoch().count()} +seconds_clock_thread::seconds_clock_thread() + : stop_{false}, tp_{Clock::now().time_since_epoch().count()} { thread_ = std::thread(&seconds_clock_thread::run, this); } diff --git a/src/libxrpl/beast/core/CurrentThreadName.cpp b/src/libxrpl/beast/core/CurrentThreadName.cpp index 9d8d4e4bf2..b63911e9f4 100644 --- a/src/libxrpl/beast/core/CurrentThreadName.cpp +++ b/src/libxrpl/beast/core/CurrentThreadName.cpp @@ -80,15 +80,20 @@ setCurrentThreadNameImpl(std::string_view name) { // truncate and set the thread name. char boundedName[maxThreadNameLength + 1]; - std::snprintf(boundedName, sizeof(boundedName), "%.*s", static_cast(maxThreadNameLength), name.data()); + std::snprintf( + boundedName, + sizeof(boundedName), + "%.*s", + static_cast(maxThreadNameLength), + name.data()); pthread_setname_np(pthread_self(), boundedName); #ifdef TRUNCATED_THREAD_NAME_LOGS if (name.size() > maxThreadNameLength) { - std::cerr << "WARNING: Thread name \"" << name << "\" (length " << name.size() << ") exceeds maximum of " - << maxThreadNameLength << " characters on Linux.\n"; + std::cerr << "WARNING: Thread name \"" << name << "\" (length " << name.size() + << ") exceeds maximum of " << maxThreadNameLength << " characters on Linux.\n"; XRPL_ASSERT( false, diff --git a/src/libxrpl/beast/core/SemanticVersion.cpp b/src/libxrpl/beast/core/SemanticVersion.cpp index d22211cc7d..b18043d5f0 100644 --- a/src/libxrpl/beast/core/SemanticVersion.cpp +++ b/src/libxrpl/beast/core/SemanticVersion.cpp @@ -58,8 +58,9 @@ chopUInt(int& value, int limit, std::string& input) if (input.empty()) return false; - auto left_iter = std::find_if_not( - input.begin(), input.end(), [](std::string::value_type c) { return std::isdigit(c, std::locale::classic()); }); + auto left_iter = std::find_if_not(input.begin(), input.end(), [](std::string::value_type c) { + return std::isdigit(c, std::locale::classic()); + }); std::string item(input.begin(), left_iter); @@ -98,7 +99,8 @@ extract_identifier(std::string& value, bool allowLeadingZeroes, std::string& inp if (!allowLeadingZeroes && input[0] == '0') return false; - auto last = input.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"); + auto last = + input.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"); // Must not be empty if (last == 0) @@ -110,7 +112,10 @@ extract_identifier(std::string& value, bool allowLeadingZeroes, std::string& inp } bool -extract_identifiers(SemanticVersion::identifier_list& identifiers, bool allowLeadingZeroes, std::string& input) +extract_identifiers( + SemanticVersion::identifier_list& identifiers, + bool allowLeadingZeroes, + std::string& input) { if (input.empty()) return false; @@ -143,8 +148,9 @@ bool SemanticVersion::parse(std::string const& input) { // May not have leading or trailing whitespace - auto left_iter = std::find_if_not( - input.begin(), input.end(), [](std::string::value_type c) { return std::isspace(c, std::locale::classic()); }); + auto left_iter = std::find_if_not(input.begin(), input.end(), [](std::string::value_type c) { + return std::isspace(c, std::locale::classic()); + }); auto right_iter = std::find_if_not(input.rbegin(), input.rend(), [](std::string::value_type c) { return std::isspace(c, std::locale::classic()); @@ -206,7 +212,8 @@ SemanticVersion::print() const { std::string s; - s = std::to_string(majorVersion) + "." + std::to_string(minorVersion) + "." + std::to_string(patchVersion); + s = std::to_string(majorVersion) + "." + std::to_string(minorVersion) + "." + + std::to_string(patchVersion); if (!preReleaseIdentifiers.empty()) { @@ -250,7 +257,9 @@ compare(SemanticVersion const& lhs, SemanticVersion const& rhs) return -1; // Compare pre-release identifiers - for (int i = 0; i < std::max(lhs.preReleaseIdentifiers.size(), rhs.preReleaseIdentifiers.size()); ++i) + for (int i = 0; + i < std::max(lhs.preReleaseIdentifiers.size(), rhs.preReleaseIdentifiers.size()); + ++i) { // A larger list of identifiers has a higher precedence if (i >= rhs.preReleaseIdentifiers.size()) diff --git a/src/libxrpl/beast/insight/Groups.cpp b/src/libxrpl/beast/insight/Groups.cpp index 1ff8dbc4c1..2b4178a9ca 100644 --- a/src/libxrpl/beast/insight/Groups.cpp +++ b/src/libxrpl/beast/insight/Groups.cpp @@ -25,7 +25,8 @@ public: std::string const m_name; Collector::ptr m_collector; - GroupImp(std::string const& name_, Collector::ptr const& collector) : m_name(name_), m_collector(collector) + GroupImp(std::string const& name_, Collector::ptr const& collector) + : m_name(name_), m_collector(collector) { } diff --git a/src/libxrpl/beast/insight/StatsDCollector.cpp b/src/libxrpl/beast/insight/StatsDCollector.cpp index e005a0b177..8462a00b3d 100644 --- a/src/libxrpl/beast/insight/StatsDCollector.cpp +++ b/src/libxrpl/beast/insight/StatsDCollector.cpp @@ -172,7 +172,9 @@ private: class StatsDMeterImpl : public MeterImpl, public StatsDMetricBase { public: - explicit StatsDMeterImpl(std::string const& name, std::shared_ptr const& impl); + explicit StatsDMeterImpl( + std::string const& name, + std::shared_ptr const& impl); ~StatsDMeterImpl() override; @@ -198,7 +200,8 @@ private: //------------------------------------------------------------------------------ -class StatsDCollectorImp : public StatsDCollector, public std::enable_shared_from_this +class StatsDCollectorImp : public StatsDCollector, + public std::enable_shared_from_this { private: enum { @@ -333,7 +336,10 @@ public: // The keepAlive parameter makes sure the buffers sent to // boost::asio::async_send do not go away until the call is finished void - on_send(std::shared_ptr> /*keepAlive*/, boost::system::error_code ec, std::size_t) + on_send( + std::shared_ptr> /*keepAlive*/, + boost::system::error_code ec, + std::size_t) { if (ec == boost::asio::error::operation_aborted) return; @@ -390,7 +396,11 @@ public: m_socket.async_send( buffers, std::bind( - &StatsDCollectorImp::on_send, this, keepAlive, std::placeholders::_1, std::placeholders::_2)); + &StatsDCollectorImp::on_send, + this, + keepAlive, + std::placeholders::_1, + std::placeholders::_2)); buffers.clear(); size = 0; } @@ -404,7 +414,12 @@ public: log(buffers); m_socket.async_send( buffers, - std::bind(&StatsDCollectorImp::on_send, this, keepAlive, std::placeholders::_1, std::placeholders::_2)); + std::bind( + &StatsDCollectorImp::on_send, + this, + keepAlive, + std::placeholders::_1, + std::placeholders::_2)); } } @@ -465,7 +480,9 @@ public: //------------------------------------------------------------------------------ -StatsDHookImpl::StatsDHookImpl(HandlerType const& handler, std::shared_ptr const& impl) +StatsDHookImpl::StatsDHookImpl( + HandlerType const& handler, + std::shared_ptr const& impl) : m_impl(impl), m_handler(handler) { m_impl->add(*this); @@ -484,7 +501,9 @@ StatsDHookImpl::do_process() //------------------------------------------------------------------------------ -StatsDCounterImpl::StatsDCounterImpl(std::string const& name, std::shared_ptr const& impl) +StatsDCounterImpl::StatsDCounterImpl( + std::string const& name, + std::shared_ptr const& impl) : m_impl(impl), m_name(name), m_value(0), m_dirty(false) { m_impl->add(*this); @@ -501,7 +520,9 @@ StatsDCounterImpl::increment(CounterImpl::value_type amount) boost::asio::dispatch( m_impl->get_io_context(), std::bind( - &StatsDCounterImpl::do_increment, std::static_pointer_cast(shared_from_this()), amount)); + &StatsDCounterImpl::do_increment, + std::static_pointer_cast(shared_from_this()), + amount)); } void @@ -533,7 +554,9 @@ StatsDCounterImpl::do_process() //------------------------------------------------------------------------------ -StatsDEventImpl::StatsDEventImpl(std::string const& name, std::shared_ptr const& impl) +StatsDEventImpl::StatsDEventImpl( + std::string const& name, + std::shared_ptr const& impl) : m_impl(impl), m_name(name) { } @@ -543,7 +566,10 @@ StatsDEventImpl::notify(EventImpl::value_type const& value) { boost::asio::dispatch( m_impl->get_io_context(), - std::bind(&StatsDEventImpl::do_notify, std::static_pointer_cast(shared_from_this()), value)); + std::bind( + &StatsDEventImpl::do_notify, + std::static_pointer_cast(shared_from_this()), + value)); } void @@ -557,7 +583,9 @@ StatsDEventImpl::do_notify(EventImpl::value_type const& value) //------------------------------------------------------------------------------ -StatsDGaugeImpl::StatsDGaugeImpl(std::string const& name, std::shared_ptr const& impl) +StatsDGaugeImpl::StatsDGaugeImpl( + std::string const& name, + std::shared_ptr const& impl) : m_impl(impl), m_name(name), m_last_value(0), m_value(0), m_dirty(false) { m_impl->add(*this); @@ -573,7 +601,10 @@ StatsDGaugeImpl::set(GaugeImpl::value_type value) { boost::asio::dispatch( m_impl->get_io_context(), - std::bind(&StatsDGaugeImpl::do_set, std::static_pointer_cast(shared_from_this()), value)); + std::bind( + &StatsDGaugeImpl::do_set, + std::static_pointer_cast(shared_from_this()), + value)); } void @@ -582,7 +613,9 @@ StatsDGaugeImpl::increment(GaugeImpl::difference_type amount) boost::asio::dispatch( m_impl->get_io_context(), std::bind( - &StatsDGaugeImpl::do_increment, std::static_pointer_cast(shared_from_this()), amount)); + &StatsDGaugeImpl::do_increment, + std::static_pointer_cast(shared_from_this()), + amount)); } void @@ -639,7 +672,9 @@ StatsDGaugeImpl::do_process() //------------------------------------------------------------------------------ -StatsDMeterImpl::StatsDMeterImpl(std::string const& name, std::shared_ptr const& impl) +StatsDMeterImpl::StatsDMeterImpl( + std::string const& name, + std::shared_ptr const& impl) : m_impl(impl), m_name(name), m_value(0), m_dirty(false) { m_impl->add(*this); @@ -656,7 +691,9 @@ StatsDMeterImpl::increment(MeterImpl::value_type amount) boost::asio::dispatch( m_impl->get_io_context(), std::bind( - &StatsDMeterImpl::do_increment, std::static_pointer_cast(shared_from_this()), amount)); + &StatsDMeterImpl::do_increment, + std::static_pointer_cast(shared_from_this()), + amount)); } void diff --git a/src/libxrpl/beast/net/IPAddressV4.cpp b/src/libxrpl/beast/net/IPAddressV4.cpp index 021b7588d9..c65e6fcf89 100644 --- a/src/libxrpl/beast/net/IPAddressV4.cpp +++ b/src/libxrpl/beast/net/IPAddressV4.cpp @@ -7,8 +7,8 @@ bool is_private(AddressV4 const& addr) { return ((addr.to_uint() & 0xff000000) == 0x0a000000) || // Prefix /8, 10. #.#.# - ((addr.to_uint() & 0xfff00000) == 0xac100000) || // Prefix /12 172. 16.#.# - 172.31.#.# - ((addr.to_uint() & 0xffff0000) == 0xc0a80000) || // Prefix /16 192.168.#.# + ((addr.to_uint() & 0xfff00000) == 0xac100000) || // Prefix /12 172. 16.#.# - 172.31.#.# + ((addr.to_uint() & 0xffff0000) == 0xc0a80000) || // Prefix /16 192.168.#.# addr.is_loopback(); } diff --git a/src/libxrpl/beast/net/IPAddressV6.cpp b/src/libxrpl/beast/net/IPAddressV6.cpp index b1db5ae09c..a261002ed3 100644 --- a/src/libxrpl/beast/net/IPAddressV6.cpp +++ b/src/libxrpl/beast/net/IPAddressV6.cpp @@ -11,7 +11,8 @@ is_private(AddressV6 const& addr) { return ( (addr.to_bytes()[0] & 0xfd) || // TODO fc00::/8 too ? - (addr.is_v4_mapped() && is_private(boost::asio::ip::make_address_v4(boost::asio::ip::v4_mapped, addr)))); + (addr.is_v4_mapped() && + is_private(boost::asio::ip::make_address_v4(boost::asio::ip::v4_mapped, addr)))); } bool diff --git a/src/libxrpl/beast/net/IPEndpoint.cpp b/src/libxrpl/beast/net/IPEndpoint.cpp index a79b0d750c..701181ef88 100644 --- a/src/libxrpl/beast/net/IPEndpoint.cpp +++ b/src/libxrpl/beast/net/IPEndpoint.cpp @@ -50,7 +50,9 @@ std::string Endpoint::to_string() const { std::string s; - s.reserve((address().is_v6() ? INET6_ADDRSTRLEN - 1 : 15) + (port() == 0 ? 0 : 6 + (address().is_v6() ? 2 : 0))); + s.reserve( + (address().is_v6() ? INET6_ADDRSTRLEN - 1 : 15) + + (port() == 0 ? 0 : 6 + (address().is_v6() ? 2 : 0))); if (port() != 0 && address().is_v6()) s += '['; @@ -108,12 +110,14 @@ operator>>(std::istream& is, Endpoint& endpoint) if (isspace(static_cast(i)) || (readTo && i == readTo)) break; - if ((i == '.') || (i >= '0' && i <= ':') || (i >= 'a' && i <= 'f') || (i >= 'A' && i <= 'F')) + if ((i == '.') || (i >= '0' && i <= ':') || (i >= 'a' && i <= 'f') || + (i >= 'A' && i <= 'F')) { addrStr += i; // don't exceed a reasonable length... - if (addrStr.size() == INET6_ADDRSTRLEN || (readTo && readTo == ':' && addrStr.size() > 15)) + if (addrStr.size() == INET6_ADDRSTRLEN || + (readTo && readTo == ':' && addrStr.size() > 15)) { is.setstate(std::ios_base::failbit); return is; diff --git a/src/libxrpl/beast/utility/beast_PropertyStream.cpp b/src/libxrpl/beast/utility/beast_PropertyStream.cpp index daf6bc4526..f714ad8871 100644 --- a/src/libxrpl/beast/utility/beast_PropertyStream.cpp +++ b/src/libxrpl/beast/utility/beast_PropertyStream.cpp @@ -151,7 +151,8 @@ PropertyStream::Set::stream() const // //------------------------------------------------------------------------------ -PropertyStream::Source::Source(std::string const& name) : m_name(name), item_(this), parent_(nullptr) +PropertyStream::Source::Source(std::string const& name) + : m_name(name), item_(this), parent_(nullptr) { } @@ -176,7 +177,8 @@ PropertyStream::Source::add(Source& source) std::lock_guard lk1(lock_, std::adopt_lock); std::lock_guard lk2(source.lock_, std::adopt_lock); - XRPL_ASSERT(source.parent_ == nullptr, "beast::PropertyStream::Source::add : null source parent"); + XRPL_ASSERT( + source.parent_ == nullptr, "beast::PropertyStream::Source::add : null source parent"); children_.push_back(source.item_); source.parent_ = this; } @@ -188,7 +190,8 @@ PropertyStream::Source::remove(Source& child) std::lock_guard lk1(lock_, std::adopt_lock); std::lock_guard lk2(child.lock_, std::adopt_lock); - XRPL_ASSERT(child.parent_ == this, "beast::PropertyStream::Source::remove : child parent match"); + XRPL_ASSERT( + child.parent_ == this, "beast::PropertyStream::Source::remove : child parent match"); children_.erase(children_.iterator_to(child.item_)); child.parent_ = nullptr; } diff --git a/src/xrpld/conditions/detail/Condition.cpp b/src/libxrpl/conditions/Condition.cpp similarity index 97% rename from src/xrpld/conditions/detail/Condition.cpp rename to src/libxrpl/conditions/Condition.cpp index 9cac75121d..30beba3402 100644 --- a/src/xrpld/conditions/detail/Condition.cpp +++ b/src/libxrpl/conditions/Condition.cpp @@ -1,6 +1,6 @@ -#include -#include -#include +#include +#include +#include namespace xrpl { namespace cryptoconditions { diff --git a/src/xrpld/conditions/detail/Fulfillment.cpp b/src/libxrpl/conditions/Fulfillment.cpp similarity index 94% rename from src/xrpld/conditions/detail/Fulfillment.cpp rename to src/libxrpl/conditions/Fulfillment.cpp index 9ecaa44ab8..11581a8705 100644 --- a/src/xrpld/conditions/detail/Fulfillment.cpp +++ b/src/libxrpl/conditions/Fulfillment.cpp @@ -1,9 +1,8 @@ -#include -#include -#include -#include - #include +#include +#include +#include +#include namespace xrpl { namespace cryptoconditions { diff --git a/src/xrpld/conditions/detail/error.cpp b/src/libxrpl/conditions/error.cpp similarity index 95% rename from src/xrpld/conditions/detail/error.cpp rename to src/libxrpl/conditions/error.cpp index 04c8d03fbb..9c9d4658e4 100644 --- a/src/xrpld/conditions/detail/error.cpp +++ b/src/libxrpl/conditions/error.cpp @@ -1,6 +1,5 @@ -#include - #include +#include #include @@ -110,7 +109,8 @@ std::error_code make_error_code(error ev) { return std::error_code{ - safe_cast::type>(ev), detail::get_cryptoconditions_error_category()}; + safe_cast::type>(ev), + detail::get_cryptoconditions_error_category()}; } } // namespace cryptoconditions diff --git a/src/xrpld/app/misc/HashRouter.cpp b/src/libxrpl/core/HashRouter.cpp similarity index 69% rename from src/xrpld/app/misc/HashRouter.cpp rename to src/libxrpl/core/HashRouter.cpp index eca46c9872..dff1394f77 100644 --- a/src/xrpld/app/misc/HashRouter.cpp +++ b/src/libxrpl/core/HashRouter.cpp @@ -1,5 +1,4 @@ -#include -#include +#include namespace xrpl { @@ -108,38 +107,4 @@ HashRouter::shouldRelay(uint256 const& key) -> std::optional( - "HashRouter hold time must be at least 12 seconds (the " - "approximate validation time for three ledgers)."); - setup.holdTime = seconds(tmp); - } - if (set(tmp, "relay_time", section)) - { - if (tmp < 8) - Throw( - "HashRouter relay time must be at least 8 seconds (the " - "approximate validation time for two ledgers)."); - setup.relayTime = seconds(tmp); - } - if (setup.relayTime > setup.holdTime) - { - Throw("HashRouter relay time must be less than or equal to hold time"); - } - - return setup; -} - } // namespace xrpl diff --git a/src/libxrpl/core/detail/Job.cpp b/src/libxrpl/core/detail/Job.cpp index 4e957b9619..7e5ca274b3 100644 --- a/src/libxrpl/core/detail/Job.cpp +++ b/src/libxrpl/core/detail/Job.cpp @@ -11,7 +11,12 @@ Job::Job(JobType type, std::uint64_t index) : mType(type), mJobIndex(index) { } -Job::Job(JobType type, std::string const& name, std::uint64_t index, LoadMonitor& lm, std::function const& job) +Job::Job( + JobType type, + std::string const& name, + std::uint64_t index, + LoadMonitor& lm, + std::function const& job) : mType(type), mJobIndex(index), mJob(job), mName(name), m_queue_time(clock_type::now()) { m_loadEvent = std::make_shared(std::ref(lm), name, false); diff --git a/src/libxrpl/core/detail/JobQueue.cpp b/src/libxrpl/core/detail/JobQueue.cpp index 37e5402946..80fb8d2536 100644 --- a/src/libxrpl/core/detail/JobQueue.cpp +++ b/src/libxrpl/core/detail/JobQueue.cpp @@ -62,7 +62,8 @@ JobQueue::addRefCountedJob(JobType type, std::string const& name, JobFunction co XRPL_ASSERT(type != jtINVALID, "xrpl::JobQueue::addRefCountedJob : valid input job type"); auto iter(m_jobData.find(type)); - XRPL_ASSERT(iter != m_jobData.end(), "xrpl::JobQueue::addRefCountedJob : job type found in jobs"); + XRPL_ASSERT( + iter != m_jobData.end(), "xrpl::JobQueue::addRefCountedJob : job type found in jobs"); if (iter == m_jobData.end()) return false; @@ -83,7 +84,8 @@ JobQueue::addRefCountedJob(JobType type, std::string const& name, JobFunction co JobType const type(job.getType()); XRPL_ASSERT(type != jtINVALID, "xrpl::JobQueue::addRefCountedJob : has valid job type"); - XRPL_ASSERT(m_jobSet.find(job) != m_jobSet.end(), "xrpl::JobQueue::addRefCountedJob : job found"); + XRPL_ASSERT( + m_jobSet.find(job) != m_jobSet.end(), "xrpl::JobQueue::addRefCountedJob : job found"); perfLog_.jobQueue(type); JobTypeData& data(getJobTypeData(type)); @@ -165,7 +167,9 @@ JobQueue::addLoadEvents(JobType t, int count, std::chrono::milliseconds elapsed) bool JobQueue::isOverloaded() { - return std::any_of(m_jobData.begin(), m_jobData.end(), [](auto& entry) { return entry.second.load().isOver(); }); + return std::any_of(m_jobData.begin(), m_jobData.end(), [](auto& entry) { + return entry.second.load().isOver(); + }); } Json::Value @@ -285,7 +289,8 @@ JobQueue::getNextJob(Job& job) XRPL_ASSERT(type != jtINVALID, "xrpl::JobQueue::getNextJob : valid job type"); JobTypeData& data(getJobTypeData(type)); - XRPL_ASSERT(data.running <= getJobLimit(type), "xrpl::JobQueue::getNextJob : maximum jobs running"); + XRPL_ASSERT( + data.running <= getJobLimit(type), "xrpl::JobQueue::getNextJob : maximum jobs running"); // Run this job if we're running below the limit. if (data.running < getJobLimit(data.type())) @@ -312,7 +317,9 @@ JobQueue::finishJob(JobType type) // Queue a deferred task if possible if (data.deferred > 0) { - XRPL_ASSERT(data.running + data.waiting >= getJobLimit(type), "xrpl::JobQueue::finishJob : job limit"); + XRPL_ASSERT( + data.running + data.waiting >= getJobLimit(type), + "xrpl::JobQueue::finishJob : job limit"); --data.deferred; m_workers.addTask(); diff --git a/src/libxrpl/core/detail/LoadMonitor.cpp b/src/libxrpl/core/detail/LoadMonitor.cpp index 376b25c178..89a364ca30 100644 --- a/src/libxrpl/core/detail/LoadMonitor.cpp +++ b/src/libxrpl/core/detail/LoadMonitor.cpp @@ -89,7 +89,8 @@ LoadMonitor::addLoadSample(LoadEvent const& s) if (latency > 500ms) { auto mj = (latency > 1s) ? j_.warn() : j_.info(); - JLOG(mj) << "Job: " << s.name() << " run: " << round(s.runTime()).count() << "ms" + JLOG(mj) << "Job: " << s.name() << " run: " << round(s.runTime()).count() + << "ms" << " wait: " << round(s.waitTime()).count() << "ms"; } @@ -142,7 +143,8 @@ LoadMonitor::isOver() if (mLatencyEvents == 0) return 0; - return isOverTarget(mLatencyMSAvg / (mLatencyEvents * 4), mLatencyMSPeak / (mLatencyEvents * 4)); + return isOverTarget( + mLatencyMSAvg / (mLatencyEvents * 4), mLatencyMSPeak / (mLatencyEvents * 4)); } LoadMonitor::Stats diff --git a/src/libxrpl/core/detail/Workers.cpp b/src/libxrpl/core/detail/Workers.cpp index 27103d765d..a5e331bd44 100644 --- a/src/libxrpl/core/detail/Workers.cpp +++ b/src/libxrpl/core/detail/Workers.cpp @@ -5,7 +5,11 @@ namespace xrpl { -Workers::Workers(Callback& callback, perf::PerfLog* perfLog, std::string const& threadNames, int numberOfThreads) +Workers::Workers( + Callback& callback, + perf::PerfLog* perfLog, + std::string const& threadNames, + int numberOfThreads) : m_callback(callback) , perfLog_(perfLog) , m_threadNames(threadNames) @@ -133,7 +137,11 @@ Workers::deleteWorkers(beast::LockFreeStack& stack) //------------------------------------------------------------------------------ Workers::Worker::Worker(Workers& workers, std::string const& threadName, int const instance) - : m_workers{workers}, threadName_{threadName}, instance_{instance}, wakeCount_{0}, shouldExit_{false} + : m_workers{workers} + , threadName_{threadName} + , instance_{instance} + , wakeCount_{0} + , shouldExit_{false} { thread_ = std::thread{&Workers::Worker::run, this}; } diff --git a/src/libxrpl/crypto/RFC1751.cpp b/src/libxrpl/crypto/RFC1751.cpp index dc841fca83..54d3e6f9d0 100644 --- a/src/libxrpl/crypto/RFC1751.cpp +++ b/src/libxrpl/crypto/RFC1751.cpp @@ -21,153 +21,177 @@ namespace xrpl { // char const* RFC1751::s_dictionary[2048] = { - "A", "ABE", "ACE", "ACT", "AD", "ADA", "ADD", "AGO", "AID", "AIM", "AIR", "ALL", "ALP", "AM", - "AMY", "AN", "ANA", "AND", "ANN", "ANT", "ANY", "APE", "APS", "APT", "ARC", "ARE", "ARK", "ARM", - "ART", "AS", "ASH", "ASK", "AT", "ATE", "AUG", "AUK", "AVE", "AWE", "AWK", "AWL", "AWN", "AX", - "AYE", "BAD", "BAG", "BAH", "BAM", "BAN", "BAR", "BAT", "BAY", "BE", "BED", "BEE", "BEG", "BEN", - "BET", "BEY", "BIB", "BID", "BIG", "BIN", "BIT", "BOB", "BOG", "BON", "BOO", "BOP", "BOW", "BOY", - "BUB", "BUD", "BUG", "BUM", "BUN", "BUS", "BUT", "BUY", "BY", "BYE", "CAB", "CAL", "CAM", "CAN", - "CAP", "CAR", "CAT", "CAW", "COD", "COG", "COL", "CON", "COO", "COP", "COT", "COW", "COY", "CRY", - "CUB", "CUE", "CUP", "CUR", "CUT", "DAB", "DAD", "DAM", "DAN", "DAR", "DAY", "DEE", "DEL", "DEN", - "DES", "DEW", "DID", "DIE", "DIG", "DIN", "DIP", "DO", "DOE", "DOG", "DON", "DOT", "DOW", "DRY", - "DUB", "DUD", "DUE", "DUG", "DUN", "EAR", "EAT", "ED", "EEL", "EGG", "EGO", "ELI", "ELK", "ELM", - "ELY", "EM", "END", "EST", "ETC", "EVA", "EVE", "EWE", "EYE", "FAD", "FAN", "FAR", "FAT", "FAY", - "FED", "FEE", "FEW", "FIB", "FIG", "FIN", "FIR", "FIT", "FLO", "FLY", "FOE", "FOG", "FOR", "FRY", - "FUM", "FUN", "FUR", "GAB", "GAD", "GAG", "GAL", "GAM", "GAP", "GAS", "GAY", "GEE", "GEL", "GEM", - "GET", "GIG", "GIL", "GIN", "GO", "GOT", "GUM", "GUN", "GUS", "GUT", "GUY", "GYM", "GYP", "HA", - "HAD", "HAL", "HAM", "HAN", "HAP", "HAS", "HAT", "HAW", "HAY", "HE", "HEM", "HEN", "HER", "HEW", - "HEY", "HI", "HID", "HIM", "HIP", "HIS", "HIT", "HO", "HOB", "HOC", "HOE", "HOG", "HOP", "HOT", - "HOW", "HUB", "HUE", "HUG", "HUH", "HUM", "HUT", "I", "ICY", "IDA", "IF", "IKE", "ILL", "INK", - "INN", "IO", "ION", "IQ", "IRA", "IRE", "IRK", "IS", "IT", "ITS", "IVY", "JAB", "JAG", "JAM", - "JAN", "JAR", "JAW", "JAY", "JET", "JIG", "JIM", "JO", "JOB", "JOE", "JOG", "JOT", "JOY", "JUG", - "JUT", "KAY", "KEG", "KEN", "KEY", "KID", "KIM", "KIN", "KIT", "LA", "LAB", "LAC", "LAD", "LAG", - "LAM", "LAP", "LAW", "LAY", "LEA", "LED", "LEE", "LEG", "LEN", "LEO", "LET", "LEW", "LID", "LIE", - "LIN", "LIP", "LIT", "LO", "LOB", "LOG", "LOP", "LOS", "LOT", "LOU", "LOW", "LOY", "LUG", "LYE", - "MA", "MAC", "MAD", "MAE", "MAN", "MAO", "MAP", "MAT", "MAW", "MAY", "ME", "MEG", "MEL", "MEN", - "MET", "MEW", "MID", "MIN", "MIT", "MOB", "MOD", "MOE", "MOO", "MOP", "MOS", "MOT", "MOW", "MUD", - "MUG", "MUM", "MY", "NAB", "NAG", "NAN", "NAP", "NAT", "NAY", "NE", "NED", "NEE", "NET", "NEW", - "NIB", "NIL", "NIP", "NIT", "NO", "NOB", "NOD", "NON", "NOR", "NOT", "NOV", "NOW", "NU", "NUN", - "NUT", "O", "OAF", "OAK", "OAR", "OAT", "ODD", "ODE", "OF", "OFF", "OFT", "OH", "OIL", "OK", - "OLD", "ON", "ONE", "OR", "ORB", "ORE", "ORR", "OS", "OTT", "OUR", "OUT", "OVA", "OW", "OWE", - "OWL", "OWN", "OX", "PA", "PAD", "PAL", "PAM", "PAN", "PAP", "PAR", "PAT", "PAW", "PAY", "PEA", - "PEG", "PEN", "PEP", "PER", "PET", "PEW", "PHI", "PI", "PIE", "PIN", "PIT", "PLY", "PO", "POD", - "POE", "POP", "POT", "POW", "PRO", "PRY", "PUB", "PUG", "PUN", "PUP", "PUT", "QUO", "RAG", "RAM", - "RAN", "RAP", "RAT", "RAW", "RAY", "REB", "RED", "REP", "RET", "RIB", "RID", "RIG", "RIM", "RIO", - "RIP", "ROB", "ROD", "ROE", "RON", "ROT", "ROW", "ROY", "RUB", "RUE", "RUG", "RUM", "RUN", "RYE", - "SAC", "SAD", "SAG", "SAL", "SAM", "SAN", "SAP", "SAT", "SAW", "SAY", "SEA", "SEC", "SEE", "SEN", - "SET", "SEW", "SHE", "SHY", "SIN", "SIP", "SIR", "SIS", "SIT", "SKI", "SKY", "SLY", "SO", "SOB", - "SOD", "SON", "SOP", "SOW", "SOY", "SPA", "SPY", "SUB", "SUD", "SUE", "SUM", "SUN", "SUP", "TAB", - "TAD", "TAG", "TAN", "TAP", "TAR", "TEA", "TED", "TEE", "TEN", "THE", "THY", "TIC", "TIE", "TIM", - "TIN", "TIP", "TO", "TOE", "TOG", "TOM", "TON", "TOO", "TOP", "TOW", "TOY", "TRY", "TUB", "TUG", - "TUM", "TUN", "TWO", "UN", "UP", "US", "USE", "VAN", "VAT", "VET", "VIE", "WAD", "WAG", "WAR", - "WAS", "WAY", "WE", "WEB", "WED", "WEE", "WET", "WHO", "WHY", "WIN", "WIT", "WOK", "WON", "WOO", - "WOW", "WRY", "WU", "YAM", "YAP", "YAW", "YE", "YEA", "YES", "YET", "YOU", "ABED", "ABEL", "ABET", - "ABLE", "ABUT", "ACHE", "ACID", "ACME", "ACRE", "ACTA", "ACTS", "ADAM", "ADDS", "ADEN", "AFAR", "AFRO", "AGEE", - "AHEM", "AHOY", "AIDA", "AIDE", "AIDS", "AIRY", "AJAR", "AKIN", "ALAN", "ALEC", "ALGA", "ALIA", "ALLY", "ALMA", - "ALOE", "ALSO", "ALTO", "ALUM", "ALVA", "AMEN", "AMES", "AMID", "AMMO", "AMOK", "AMOS", "AMRA", "ANDY", "ANEW", - "ANNA", "ANNE", "ANTE", "ANTI", "AQUA", "ARAB", "ARCH", "AREA", "ARGO", "ARID", "ARMY", "ARTS", "ARTY", "ASIA", - "ASKS", "ATOM", "AUNT", "AURA", "AUTO", "AVER", "AVID", "AVIS", "AVON", "AVOW", "AWAY", "AWRY", "BABE", "BABY", - "BACH", "BACK", "BADE", "BAIL", "BAIT", "BAKE", "BALD", "BALE", "BALI", "BALK", "BALL", "BALM", "BAND", "BANE", - "BANG", "BANK", "BARB", "BARD", "BARE", "BARK", "BARN", "BARR", "BASE", "BASH", "BASK", "BASS", "BATE", "BATH", - "BAWD", "BAWL", "BEAD", "BEAK", "BEAM", "BEAN", "BEAR", "BEAT", "BEAU", "BECK", "BEEF", "BEEN", "BEER", "BEET", - "BELA", "BELL", "BELT", "BEND", "BENT", "BERG", "BERN", "BERT", "BESS", "BEST", "BETA", "BETH", "BHOY", "BIAS", - "BIDE", "BIEN", "BILE", "BILK", "BILL", "BIND", "BING", "BIRD", "BITE", "BITS", "BLAB", "BLAT", "BLED", "BLEW", - "BLOB", "BLOC", "BLOT", "BLOW", "BLUE", "BLUM", "BLUR", "BOAR", "BOAT", "BOCA", "BOCK", "BODE", "BODY", "BOGY", - "BOHR", "BOIL", "BOLD", "BOLO", "BOLT", "BOMB", "BONA", "BOND", "BONE", "BONG", "BONN", "BONY", "BOOK", "BOOM", - "BOON", "BOOT", "BORE", "BORG", "BORN", "BOSE", "BOSS", "BOTH", "BOUT", "BOWL", "BOYD", "BRAD", "BRAE", "BRAG", - "BRAN", "BRAY", "BRED", "BREW", "BRIG", "BRIM", "BROW", "BUCK", "BUDD", "BUFF", "BULB", "BULK", "BULL", "BUNK", - "BUNT", "BUOY", "BURG", "BURL", "BURN", "BURR", "BURT", "BURY", "BUSH", "BUSS", "BUST", "BUSY", "BYTE", "CADY", - "CAFE", "CAGE", "CAIN", "CAKE", "CALF", "CALL", "CALM", "CAME", "CANE", "CANT", "CARD", "CARE", "CARL", "CARR", - "CART", "CASE", "CASH", "CASK", "CAST", "CAVE", "CEIL", "CELL", "CENT", "CERN", "CHAD", "CHAR", "CHAT", "CHAW", - "CHEF", "CHEN", "CHEW", "CHIC", "CHIN", "CHOU", "CHOW", "CHUB", "CHUG", "CHUM", "CITE", "CITY", "CLAD", "CLAM", - "CLAN", "CLAW", "CLAY", "CLOD", "CLOG", "CLOT", "CLUB", "CLUE", "COAL", "COAT", "COCA", "COCK", "COCO", "CODA", - "CODE", "CODY", "COED", "COIL", "COIN", "COKE", "COLA", "COLD", "COLT", "COMA", "COMB", "COME", "COOK", "COOL", - "COON", "COOT", "CORD", "CORE", "CORK", "CORN", "COST", "COVE", "COWL", "CRAB", "CRAG", "CRAM", "CRAY", "CREW", - "CRIB", "CROW", "CRUD", "CUBA", "CUBE", "CUFF", "CULL", "CULT", "CUNY", "CURB", "CURD", "CURE", "CURL", "CURT", - "CUTS", "DADE", "DALE", "DAME", "DANA", "DANE", "DANG", "DANK", "DARE", "DARK", "DARN", "DART", "DASH", "DATA", - "DATE", "DAVE", "DAVY", "DAWN", "DAYS", "DEAD", "DEAF", "DEAL", "DEAN", "DEAR", "DEBT", "DECK", "DEED", "DEEM", - "DEER", "DEFT", "DEFY", "DELL", "DENT", "DENY", "DESK", "DIAL", "DICE", "DIED", "DIET", "DIME", "DINE", "DING", - "DINT", "DIRE", "DIRT", "DISC", "DISH", "DISK", "DIVE", "DOCK", "DOES", "DOLE", "DOLL", "DOLT", "DOME", "DONE", - "DOOM", "DOOR", "DORA", "DOSE", "DOTE", "DOUG", "DOUR", "DOVE", "DOWN", "DRAB", "DRAG", "DRAM", "DRAW", "DREW", - "DRUB", "DRUG", "DRUM", "DUAL", "DUCK", "DUCT", "DUEL", "DUET", "DUKE", "DULL", "DUMB", "DUNE", "DUNK", "DUSK", - "DUST", "DUTY", "EACH", "EARL", "EARN", "EASE", "EAST", "EASY", "EBEN", "ECHO", "EDDY", "EDEN", "EDGE", "EDGY", - "EDIT", "EDNA", "EGAN", "ELAN", "ELBA", "ELLA", "ELSE", "EMIL", "EMIT", "EMMA", "ENDS", "ERIC", "EROS", "EVEN", - "EVER", "EVIL", "EYED", "FACE", "FACT", "FADE", "FAIL", "FAIN", "FAIR", "FAKE", "FALL", "FAME", "FANG", "FARM", - "FAST", "FATE", "FAWN", "FEAR", "FEAT", "FEED", "FEEL", "FEET", "FELL", "FELT", "FEND", "FERN", "FEST", "FEUD", - "FIEF", "FIGS", "FILE", "FILL", "FILM", "FIND", "FINE", "FINK", "FIRE", "FIRM", "FISH", "FISK", "FIST", "FITS", - "FIVE", "FLAG", "FLAK", "FLAM", "FLAT", "FLAW", "FLEA", "FLED", "FLEW", "FLIT", "FLOC", "FLOG", "FLOW", "FLUB", - "FLUE", "FOAL", "FOAM", "FOGY", "FOIL", "FOLD", "FOLK", "FOND", "FONT", "FOOD", "FOOL", "FOOT", "FORD", "FORE", - "FORK", "FORM", "FORT", "FOSS", "FOUL", "FOUR", "FOWL", "FRAU", "FRAY", "FRED", "FREE", "FRET", "FREY", "FROG", - "FROM", "FUEL", "FULL", "FUME", "FUND", "FUNK", "FURY", "FUSE", "FUSS", "GAFF", "GAGE", "GAIL", "GAIN", "GAIT", - "GALA", "GALE", "GALL", "GALT", "GAME", "GANG", "GARB", "GARY", "GASH", "GATE", "GAUL", "GAUR", "GAVE", "GAWK", - "GEAR", "GELD", "GENE", "GENT", "GERM", "GETS", "GIBE", "GIFT", "GILD", "GILL", "GILT", "GINA", "GIRD", "GIRL", - "GIST", "GIVE", "GLAD", "GLEE", "GLEN", "GLIB", "GLOB", "GLOM", "GLOW", "GLUE", "GLUM", "GLUT", "GOAD", "GOAL", - "GOAT", "GOER", "GOES", "GOLD", "GOLF", "GONE", "GONG", "GOOD", "GOOF", "GORE", "GORY", "GOSH", "GOUT", "GOWN", - "GRAB", "GRAD", "GRAY", "GREG", "GREW", "GREY", "GRID", "GRIM", "GRIN", "GRIT", "GROW", "GRUB", "GULF", "GULL", - "GUNK", "GURU", "GUSH", "GUST", "GWEN", "GWYN", "HAAG", "HAAS", "HACK", "HAIL", "HAIR", "HALE", "HALF", "HALL", - "HALO", "HALT", "HAND", "HANG", "HANK", "HANS", "HARD", "HARK", "HARM", "HART", "HASH", "HAST", "HATE", "HATH", - "HAUL", "HAVE", "HAWK", "HAYS", "HEAD", "HEAL", "HEAR", "HEAT", "HEBE", "HECK", "HEED", "HEEL", "HEFT", "HELD", - "HELL", "HELM", "HERB", "HERD", "HERE", "HERO", "HERS", "HESS", "HEWN", "HICK", "HIDE", "HIGH", "HIKE", "HILL", - "HILT", "HIND", "HINT", "HIRE", "HISS", "HIVE", "HOBO", "HOCK", "HOFF", "HOLD", "HOLE", "HOLM", "HOLT", "HOME", - "HONE", "HONK", "HOOD", "HOOF", "HOOK", "HOOT", "HORN", "HOSE", "HOST", "HOUR", "HOVE", "HOWE", "HOWL", "HOYT", - "HUCK", "HUED", "HUFF", "HUGE", "HUGH", "HUGO", "HULK", "HULL", "HUNK", "HUNT", "HURD", "HURL", "HURT", "HUSH", - "HYDE", "HYMN", "IBIS", "ICON", "IDEA", "IDLE", "IFFY", "INCA", "INCH", "INTO", "IONS", "IOTA", "IOWA", "IRIS", - "IRMA", "IRON", "ISLE", "ITCH", "ITEM", "IVAN", "JACK", "JADE", "JAIL", "JAKE", "JANE", "JAVA", "JEAN", "JEFF", - "JERK", "JESS", "JEST", "JIBE", "JILL", "JILT", "JIVE", "JOAN", "JOBS", "JOCK", "JOEL", "JOEY", "JOHN", "JOIN", - "JOKE", "JOLT", "JOVE", "JUDD", "JUDE", "JUDO", "JUDY", "JUJU", "JUKE", "JULY", "JUNE", "JUNK", "JUNO", "JURY", - "JUST", "JUTE", "KAHN", "KALE", "KANE", "KANT", "KARL", "KATE", "KEEL", "KEEN", "KENO", "KENT", "KERN", "KERR", - "KEYS", "KICK", "KILL", "KIND", "KING", "KIRK", "KISS", "KITE", "KLAN", "KNEE", "KNEW", "KNIT", "KNOB", "KNOT", - "KNOW", "KOCH", "KONG", "KUDO", "KURD", "KURT", "KYLE", "LACE", "LACK", "LACY", "LADY", "LAID", "LAIN", "LAIR", - "LAKE", "LAMB", "LAME", "LAND", "LANE", "LANG", "LARD", "LARK", "LASS", "LAST", "LATE", "LAUD", "LAVA", "LAWN", - "LAWS", "LAYS", "LEAD", "LEAF", "LEAK", "LEAN", "LEAR", "LEEK", "LEER", "LEFT", "LEND", "LENS", "LENT", "LEON", - "LESK", "LESS", "LEST", "LETS", "LIAR", "LICE", "LICK", "LIED", "LIEN", "LIES", "LIEU", "LIFE", "LIFT", "LIKE", - "LILA", "LILT", "LILY", "LIMA", "LIMB", "LIME", "LIND", "LINE", "LINK", "LINT", "LION", "LISA", "LIST", "LIVE", - "LOAD", "LOAF", "LOAM", "LOAN", "LOCK", "LOFT", "LOGE", "LOIS", "LOLA", "LONE", "LONG", "LOOK", "LOON", "LOOT", - "LORD", "LORE", "LOSE", "LOSS", "LOST", "LOUD", "LOVE", "LOWE", "LUCK", "LUCY", "LUGE", "LUKE", "LULU", "LUND", - "LUNG", "LURA", "LURE", "LURK", "LUSH", "LUST", "LYLE", "LYNN", "LYON", "LYRA", "MACE", "MADE", "MAGI", "MAID", - "MAIL", "MAIN", "MAKE", "MALE", "MALI", "MALL", "MALT", "MANA", "MANN", "MANY", "MARC", "MARE", "MARK", "MARS", - "MART", "MARY", "MASH", "MASK", "MASS", "MAST", "MATE", "MATH", "MAUL", "MAYO", "MEAD", "MEAL", "MEAN", "MEAT", - "MEEK", "MEET", "MELD", "MELT", "MEMO", "MEND", "MENU", "MERT", "MESH", "MESS", "MICE", "MIKE", "MILD", "MILE", - "MILK", "MILL", "MILT", "MIMI", "MIND", "MINE", "MINI", "MINK", "MINT", "MIRE", "MISS", "MIST", "MITE", "MITT", - "MOAN", "MOAT", "MOCK", "MODE", "MOLD", "MOLE", "MOLL", "MOLT", "MONA", "MONK", "MONT", "MOOD", "MOON", "MOOR", - "MOOT", "MORE", "MORN", "MORT", "MOSS", "MOST", "MOTH", "MOVE", "MUCH", "MUCK", "MUDD", "MUFF", "MULE", "MULL", - "MURK", "MUSH", "MUST", "MUTE", "MUTT", "MYRA", "MYTH", "NAGY", "NAIL", "NAIR", "NAME", "NARY", "NASH", "NAVE", - "NAVY", "NEAL", "NEAR", "NEAT", "NECK", "NEED", "NEIL", "NELL", "NEON", "NERO", "NESS", "NEST", "NEWS", "NEWT", - "NIBS", "NICE", "NICK", "NILE", "NINA", "NINE", "NOAH", "NODE", "NOEL", "NOLL", "NONE", "NOOK", "NOON", "NORM", - "NOSE", "NOTE", "NOUN", "NOVA", "NUDE", "NULL", "NUMB", "OATH", "OBEY", "OBOE", "ODIN", "OHIO", "OILY", "OINT", - "OKAY", "OLAF", "OLDY", "OLGA", "OLIN", "OMAN", "OMEN", "OMIT", "ONCE", "ONES", "ONLY", "ONTO", "ONUS", "ORAL", - "ORGY", "OSLO", "OTIS", "OTTO", "OUCH", "OUST", "OUTS", "OVAL", "OVEN", "OVER", "OWLY", "OWNS", "QUAD", "QUIT", - "QUOD", "RACE", "RACK", "RACY", "RAFT", "RAGE", "RAID", "RAIL", "RAIN", "RAKE", "RANK", "RANT", "RARE", "RASH", - "RATE", "RAVE", "RAYS", "READ", "REAL", "REAM", "REAR", "RECK", "REED", "REEF", "REEK", "REEL", "REID", "REIN", - "RENA", "REND", "RENT", "REST", "RICE", "RICH", "RICK", "RIDE", "RIFT", "RILL", "RIME", "RING", "RINK", "RISE", - "RISK", "RITE", "ROAD", "ROAM", "ROAR", "ROBE", "ROCK", "RODE", "ROIL", "ROLL", "ROME", "ROOD", "ROOF", "ROOK", - "ROOM", "ROOT", "ROSA", "ROSE", "ROSS", "ROSY", "ROTH", "ROUT", "ROVE", "ROWE", "ROWS", "RUBE", "RUBY", "RUDE", - "RUDY", "RUIN", "RULE", "RUNG", "RUNS", "RUNT", "RUSE", "RUSH", "RUSK", "RUSS", "RUST", "RUTH", "SACK", "SAFE", - "SAGE", "SAID", "SAIL", "SALE", "SALK", "SALT", "SAME", "SAND", "SANE", "SANG", "SANK", "SARA", "SAUL", "SAVE", - "SAYS", "SCAN", "SCAR", "SCAT", "SCOT", "SEAL", "SEAM", "SEAR", "SEAT", "SEED", "SEEK", "SEEM", "SEEN", "SEES", - "SELF", "SELL", "SEND", "SENT", "SETS", "SEWN", "SHAG", "SHAM", "SHAW", "SHAY", "SHED", "SHIM", "SHIN", "SHOD", - "SHOE", "SHOT", "SHOW", "SHUN", "SHUT", "SICK", "SIDE", "SIFT", "SIGH", "SIGN", "SILK", "SILL", "SILO", "SILT", - "SINE", "SING", "SINK", "SIRE", "SITE", "SITS", "SITU", "SKAT", "SKEW", "SKID", "SKIM", "SKIN", "SKIT", "SLAB", - "SLAM", "SLAT", "SLAY", "SLED", "SLEW", "SLID", "SLIM", "SLIT", "SLOB", "SLOG", "SLOT", "SLOW", "SLUG", "SLUM", - "SLUR", "SMOG", "SMUG", "SNAG", "SNOB", "SNOW", "SNUB", "SNUG", "SOAK", "SOAR", "SOCK", "SODA", "SOFA", "SOFT", - "SOIL", "SOLD", "SOME", "SONG", "SOON", "SOOT", "SORE", "SORT", "SOUL", "SOUR", "SOWN", "STAB", "STAG", "STAN", - "STAR", "STAY", "STEM", "STEW", "STIR", "STOW", "STUB", "STUN", "SUCH", "SUDS", "SUIT", "SULK", "SUMS", "SUNG", - "SUNK", "SURE", "SURF", "SWAB", "SWAG", "SWAM", "SWAN", "SWAT", "SWAY", "SWIM", "SWUM", "TACK", "TACT", "TAIL", - "TAKE", "TALE", "TALK", "TALL", "TANK", "TASK", "TATE", "TAUT", "TEAL", "TEAM", "TEAR", "TECH", "TEEM", "TEEN", - "TEET", "TELL", "TEND", "TENT", "TERM", "TERN", "TESS", "TEST", "THAN", "THAT", "THEE", "THEM", "THEN", "THEY", - "THIN", "THIS", "THUD", "THUG", "TICK", "TIDE", "TIDY", "TIED", "TIER", "TILE", "TILL", "TILT", "TIME", "TINA", - "TINE", "TINT", "TINY", "TIRE", "TOAD", "TOGO", "TOIL", "TOLD", "TOLL", "TONE", "TONG", "TONY", "TOOK", "TOOL", - "TOOT", "TORE", "TORN", "TOTE", "TOUR", "TOUT", "TOWN", "TRAG", "TRAM", "TRAY", "TREE", "TREK", "TRIG", "TRIM", - "TRIO", "TROD", "TROT", "TROY", "TRUE", "TUBA", "TUBE", "TUCK", "TUFT", "TUNA", "TUNE", "TUNG", "TURF", "TURN", - "TUSK", "TWIG", "TWIN", "TWIT", "ULAN", "UNIT", "URGE", "USED", "USER", "USES", "UTAH", "VAIL", "VAIN", "VALE", - "VARY", "VASE", "VAST", "VEAL", "VEDA", "VEIL", "VEIN", "VEND", "VENT", "VERB", "VERY", "VETO", "VICE", "VIEW", - "VINE", "VISE", "VOID", "VOLT", "VOTE", "WACK", "WADE", "WAGE", "WAIL", "WAIT", "WAKE", "WALE", "WALK", "WALL", - "WALT", "WAND", "WANE", "WANG", "WANT", "WARD", "WARM", "WARN", "WART", "WASH", "WAST", "WATS", "WATT", "WAVE", - "WAVY", "WAYS", "WEAK", "WEAL", "WEAN", "WEAR", "WEED", "WEEK", "WEIR", "WELD", "WELL", "WELT", "WENT", "WERE", - "WERT", "WEST", "WHAM", "WHAT", "WHEE", "WHEN", "WHET", "WHOA", "WHOM", "WICK", "WIFE", "WILD", "WILL", "WIND", - "WINE", "WING", "WINK", "WINO", "WIRE", "WISE", "WISH", "WITH", "WOLF", "WONT", "WOOD", "WOOL", "WORD", "WORE", - "WORK", "WORM", "WORN", "WOVE", "WRIT", "WYNN", "YALE", "YANG", "YANK", "YARD", "YARN", "YAWL", "YAWN", "YEAH", - "YEAR", "YELL", "YOGA", "YOKE"}; + "A", "ABE", "ACE", "ACT", "AD", "ADA", "ADD", "AGO", "AID", "AIM", "AIR", "ALL", + "ALP", "AM", "AMY", "AN", "ANA", "AND", "ANN", "ANT", "ANY", "APE", "APS", "APT", + "ARC", "ARE", "ARK", "ARM", "ART", "AS", "ASH", "ASK", "AT", "ATE", "AUG", "AUK", + "AVE", "AWE", "AWK", "AWL", "AWN", "AX", "AYE", "BAD", "BAG", "BAH", "BAM", "BAN", + "BAR", "BAT", "BAY", "BE", "BED", "BEE", "BEG", "BEN", "BET", "BEY", "BIB", "BID", + "BIG", "BIN", "BIT", "BOB", "BOG", "BON", "BOO", "BOP", "BOW", "BOY", "BUB", "BUD", + "BUG", "BUM", "BUN", "BUS", "BUT", "BUY", "BY", "BYE", "CAB", "CAL", "CAM", "CAN", + "CAP", "CAR", "CAT", "CAW", "COD", "COG", "COL", "CON", "COO", "COP", "COT", "COW", + "COY", "CRY", "CUB", "CUE", "CUP", "CUR", "CUT", "DAB", "DAD", "DAM", "DAN", "DAR", + "DAY", "DEE", "DEL", "DEN", "DES", "DEW", "DID", "DIE", "DIG", "DIN", "DIP", "DO", + "DOE", "DOG", "DON", "DOT", "DOW", "DRY", "DUB", "DUD", "DUE", "DUG", "DUN", "EAR", + "EAT", "ED", "EEL", "EGG", "EGO", "ELI", "ELK", "ELM", "ELY", "EM", "END", "EST", + "ETC", "EVA", "EVE", "EWE", "EYE", "FAD", "FAN", "FAR", "FAT", "FAY", "FED", "FEE", + "FEW", "FIB", "FIG", "FIN", "FIR", "FIT", "FLO", "FLY", "FOE", "FOG", "FOR", "FRY", + "FUM", "FUN", "FUR", "GAB", "GAD", "GAG", "GAL", "GAM", "GAP", "GAS", "GAY", "GEE", + "GEL", "GEM", "GET", "GIG", "GIL", "GIN", "GO", "GOT", "GUM", "GUN", "GUS", "GUT", + "GUY", "GYM", "GYP", "HA", "HAD", "HAL", "HAM", "HAN", "HAP", "HAS", "HAT", "HAW", + "HAY", "HE", "HEM", "HEN", "HER", "HEW", "HEY", "HI", "HID", "HIM", "HIP", "HIS", + "HIT", "HO", "HOB", "HOC", "HOE", "HOG", "HOP", "HOT", "HOW", "HUB", "HUE", "HUG", + "HUH", "HUM", "HUT", "I", "ICY", "IDA", "IF", "IKE", "ILL", "INK", "INN", "IO", + "ION", "IQ", "IRA", "IRE", "IRK", "IS", "IT", "ITS", "IVY", "JAB", "JAG", "JAM", + "JAN", "JAR", "JAW", "JAY", "JET", "JIG", "JIM", "JO", "JOB", "JOE", "JOG", "JOT", + "JOY", "JUG", "JUT", "KAY", "KEG", "KEN", "KEY", "KID", "KIM", "KIN", "KIT", "LA", + "LAB", "LAC", "LAD", "LAG", "LAM", "LAP", "LAW", "LAY", "LEA", "LED", "LEE", "LEG", + "LEN", "LEO", "LET", "LEW", "LID", "LIE", "LIN", "LIP", "LIT", "LO", "LOB", "LOG", + "LOP", "LOS", "LOT", "LOU", "LOW", "LOY", "LUG", "LYE", "MA", "MAC", "MAD", "MAE", + "MAN", "MAO", "MAP", "MAT", "MAW", "MAY", "ME", "MEG", "MEL", "MEN", "MET", "MEW", + "MID", "MIN", "MIT", "MOB", "MOD", "MOE", "MOO", "MOP", "MOS", "MOT", "MOW", "MUD", + "MUG", "MUM", "MY", "NAB", "NAG", "NAN", "NAP", "NAT", "NAY", "NE", "NED", "NEE", + "NET", "NEW", "NIB", "NIL", "NIP", "NIT", "NO", "NOB", "NOD", "NON", "NOR", "NOT", + "NOV", "NOW", "NU", "NUN", "NUT", "O", "OAF", "OAK", "OAR", "OAT", "ODD", "ODE", + "OF", "OFF", "OFT", "OH", "OIL", "OK", "OLD", "ON", "ONE", "OR", "ORB", "ORE", + "ORR", "OS", "OTT", "OUR", "OUT", "OVA", "OW", "OWE", "OWL", "OWN", "OX", "PA", + "PAD", "PAL", "PAM", "PAN", "PAP", "PAR", "PAT", "PAW", "PAY", "PEA", "PEG", "PEN", + "PEP", "PER", "PET", "PEW", "PHI", "PI", "PIE", "PIN", "PIT", "PLY", "PO", "POD", + "POE", "POP", "POT", "POW", "PRO", "PRY", "PUB", "PUG", "PUN", "PUP", "PUT", "QUO", + "RAG", "RAM", "RAN", "RAP", "RAT", "RAW", "RAY", "REB", "RED", "REP", "RET", "RIB", + "RID", "RIG", "RIM", "RIO", "RIP", "ROB", "ROD", "ROE", "RON", "ROT", "ROW", "ROY", + "RUB", "RUE", "RUG", "RUM", "RUN", "RYE", "SAC", "SAD", "SAG", "SAL", "SAM", "SAN", + "SAP", "SAT", "SAW", "SAY", "SEA", "SEC", "SEE", "SEN", "SET", "SEW", "SHE", "SHY", + "SIN", "SIP", "SIR", "SIS", "SIT", "SKI", "SKY", "SLY", "SO", "SOB", "SOD", "SON", + "SOP", "SOW", "SOY", "SPA", "SPY", "SUB", "SUD", "SUE", "SUM", "SUN", "SUP", "TAB", + "TAD", "TAG", "TAN", "TAP", "TAR", "TEA", "TED", "TEE", "TEN", "THE", "THY", "TIC", + "TIE", "TIM", "TIN", "TIP", "TO", "TOE", "TOG", "TOM", "TON", "TOO", "TOP", "TOW", + "TOY", "TRY", "TUB", "TUG", "TUM", "TUN", "TWO", "UN", "UP", "US", "USE", "VAN", + "VAT", "VET", "VIE", "WAD", "WAG", "WAR", "WAS", "WAY", "WE", "WEB", "WED", "WEE", + "WET", "WHO", "WHY", "WIN", "WIT", "WOK", "WON", "WOO", "WOW", "WRY", "WU", "YAM", + "YAP", "YAW", "YE", "YEA", "YES", "YET", "YOU", "ABED", "ABEL", "ABET", "ABLE", "ABUT", + "ACHE", "ACID", "ACME", "ACRE", "ACTA", "ACTS", "ADAM", "ADDS", "ADEN", "AFAR", "AFRO", "AGEE", + "AHEM", "AHOY", "AIDA", "AIDE", "AIDS", "AIRY", "AJAR", "AKIN", "ALAN", "ALEC", "ALGA", "ALIA", + "ALLY", "ALMA", "ALOE", "ALSO", "ALTO", "ALUM", "ALVA", "AMEN", "AMES", "AMID", "AMMO", "AMOK", + "AMOS", "AMRA", "ANDY", "ANEW", "ANNA", "ANNE", "ANTE", "ANTI", "AQUA", "ARAB", "ARCH", "AREA", + "ARGO", "ARID", "ARMY", "ARTS", "ARTY", "ASIA", "ASKS", "ATOM", "AUNT", "AURA", "AUTO", "AVER", + "AVID", "AVIS", "AVON", "AVOW", "AWAY", "AWRY", "BABE", "BABY", "BACH", "BACK", "BADE", "BAIL", + "BAIT", "BAKE", "BALD", "BALE", "BALI", "BALK", "BALL", "BALM", "BAND", "BANE", "BANG", "BANK", + "BARB", "BARD", "BARE", "BARK", "BARN", "BARR", "BASE", "BASH", "BASK", "BASS", "BATE", "BATH", + "BAWD", "BAWL", "BEAD", "BEAK", "BEAM", "BEAN", "BEAR", "BEAT", "BEAU", "BECK", "BEEF", "BEEN", + "BEER", "BEET", "BELA", "BELL", "BELT", "BEND", "BENT", "BERG", "BERN", "BERT", "BESS", "BEST", + "BETA", "BETH", "BHOY", "BIAS", "BIDE", "BIEN", "BILE", "BILK", "BILL", "BIND", "BING", "BIRD", + "BITE", "BITS", "BLAB", "BLAT", "BLED", "BLEW", "BLOB", "BLOC", "BLOT", "BLOW", "BLUE", "BLUM", + "BLUR", "BOAR", "BOAT", "BOCA", "BOCK", "BODE", "BODY", "BOGY", "BOHR", "BOIL", "BOLD", "BOLO", + "BOLT", "BOMB", "BONA", "BOND", "BONE", "BONG", "BONN", "BONY", "BOOK", "BOOM", "BOON", "BOOT", + "BORE", "BORG", "BORN", "BOSE", "BOSS", "BOTH", "BOUT", "BOWL", "BOYD", "BRAD", "BRAE", "BRAG", + "BRAN", "BRAY", "BRED", "BREW", "BRIG", "BRIM", "BROW", "BUCK", "BUDD", "BUFF", "BULB", "BULK", + "BULL", "BUNK", "BUNT", "BUOY", "BURG", "BURL", "BURN", "BURR", "BURT", "BURY", "BUSH", "BUSS", + "BUST", "BUSY", "BYTE", "CADY", "CAFE", "CAGE", "CAIN", "CAKE", "CALF", "CALL", "CALM", "CAME", + "CANE", "CANT", "CARD", "CARE", "CARL", "CARR", "CART", "CASE", "CASH", "CASK", "CAST", "CAVE", + "CEIL", "CELL", "CENT", "CERN", "CHAD", "CHAR", "CHAT", "CHAW", "CHEF", "CHEN", "CHEW", "CHIC", + "CHIN", "CHOU", "CHOW", "CHUB", "CHUG", "CHUM", "CITE", "CITY", "CLAD", "CLAM", "CLAN", "CLAW", + "CLAY", "CLOD", "CLOG", "CLOT", "CLUB", "CLUE", "COAL", "COAT", "COCA", "COCK", "COCO", "CODA", + "CODE", "CODY", "COED", "COIL", "COIN", "COKE", "COLA", "COLD", "COLT", "COMA", "COMB", "COME", + "COOK", "COOL", "COON", "COOT", "CORD", "CORE", "CORK", "CORN", "COST", "COVE", "COWL", "CRAB", + "CRAG", "CRAM", "CRAY", "CREW", "CRIB", "CROW", "CRUD", "CUBA", "CUBE", "CUFF", "CULL", "CULT", + "CUNY", "CURB", "CURD", "CURE", "CURL", "CURT", "CUTS", "DADE", "DALE", "DAME", "DANA", "DANE", + "DANG", "DANK", "DARE", "DARK", "DARN", "DART", "DASH", "DATA", "DATE", "DAVE", "DAVY", "DAWN", + "DAYS", "DEAD", "DEAF", "DEAL", "DEAN", "DEAR", "DEBT", "DECK", "DEED", "DEEM", "DEER", "DEFT", + "DEFY", "DELL", "DENT", "DENY", "DESK", "DIAL", "DICE", "DIED", "DIET", "DIME", "DINE", "DING", + "DINT", "DIRE", "DIRT", "DISC", "DISH", "DISK", "DIVE", "DOCK", "DOES", "DOLE", "DOLL", "DOLT", + "DOME", "DONE", "DOOM", "DOOR", "DORA", "DOSE", "DOTE", "DOUG", "DOUR", "DOVE", "DOWN", "DRAB", + "DRAG", "DRAM", "DRAW", "DREW", "DRUB", "DRUG", "DRUM", "DUAL", "DUCK", "DUCT", "DUEL", "DUET", + "DUKE", "DULL", "DUMB", "DUNE", "DUNK", "DUSK", "DUST", "DUTY", "EACH", "EARL", "EARN", "EASE", + "EAST", "EASY", "EBEN", "ECHO", "EDDY", "EDEN", "EDGE", "EDGY", "EDIT", "EDNA", "EGAN", "ELAN", + "ELBA", "ELLA", "ELSE", "EMIL", "EMIT", "EMMA", "ENDS", "ERIC", "EROS", "EVEN", "EVER", "EVIL", + "EYED", "FACE", "FACT", "FADE", "FAIL", "FAIN", "FAIR", "FAKE", "FALL", "FAME", "FANG", "FARM", + "FAST", "FATE", "FAWN", "FEAR", "FEAT", "FEED", "FEEL", "FEET", "FELL", "FELT", "FEND", "FERN", + "FEST", "FEUD", "FIEF", "FIGS", "FILE", "FILL", "FILM", "FIND", "FINE", "FINK", "FIRE", "FIRM", + "FISH", "FISK", "FIST", "FITS", "FIVE", "FLAG", "FLAK", "FLAM", "FLAT", "FLAW", "FLEA", "FLED", + "FLEW", "FLIT", "FLOC", "FLOG", "FLOW", "FLUB", "FLUE", "FOAL", "FOAM", "FOGY", "FOIL", "FOLD", + "FOLK", "FOND", "FONT", "FOOD", "FOOL", "FOOT", "FORD", "FORE", "FORK", "FORM", "FORT", "FOSS", + "FOUL", "FOUR", "FOWL", "FRAU", "FRAY", "FRED", "FREE", "FRET", "FREY", "FROG", "FROM", "FUEL", + "FULL", "FUME", "FUND", "FUNK", "FURY", "FUSE", "FUSS", "GAFF", "GAGE", "GAIL", "GAIN", "GAIT", + "GALA", "GALE", "GALL", "GALT", "GAME", "GANG", "GARB", "GARY", "GASH", "GATE", "GAUL", "GAUR", + "GAVE", "GAWK", "GEAR", "GELD", "GENE", "GENT", "GERM", "GETS", "GIBE", "GIFT", "GILD", "GILL", + "GILT", "GINA", "GIRD", "GIRL", "GIST", "GIVE", "GLAD", "GLEE", "GLEN", "GLIB", "GLOB", "GLOM", + "GLOW", "GLUE", "GLUM", "GLUT", "GOAD", "GOAL", "GOAT", "GOER", "GOES", "GOLD", "GOLF", "GONE", + "GONG", "GOOD", "GOOF", "GORE", "GORY", "GOSH", "GOUT", "GOWN", "GRAB", "GRAD", "GRAY", "GREG", + "GREW", "GREY", "GRID", "GRIM", "GRIN", "GRIT", "GROW", "GRUB", "GULF", "GULL", "GUNK", "GURU", + "GUSH", "GUST", "GWEN", "GWYN", "HAAG", "HAAS", "HACK", "HAIL", "HAIR", "HALE", "HALF", "HALL", + "HALO", "HALT", "HAND", "HANG", "HANK", "HANS", "HARD", "HARK", "HARM", "HART", "HASH", "HAST", + "HATE", "HATH", "HAUL", "HAVE", "HAWK", "HAYS", "HEAD", "HEAL", "HEAR", "HEAT", "HEBE", "HECK", + "HEED", "HEEL", "HEFT", "HELD", "HELL", "HELM", "HERB", "HERD", "HERE", "HERO", "HERS", "HESS", + "HEWN", "HICK", "HIDE", "HIGH", "HIKE", "HILL", "HILT", "HIND", "HINT", "HIRE", "HISS", "HIVE", + "HOBO", "HOCK", "HOFF", "HOLD", "HOLE", "HOLM", "HOLT", "HOME", "HONE", "HONK", "HOOD", "HOOF", + "HOOK", "HOOT", "HORN", "HOSE", "HOST", "HOUR", "HOVE", "HOWE", "HOWL", "HOYT", "HUCK", "HUED", + "HUFF", "HUGE", "HUGH", "HUGO", "HULK", "HULL", "HUNK", "HUNT", "HURD", "HURL", "HURT", "HUSH", + "HYDE", "HYMN", "IBIS", "ICON", "IDEA", "IDLE", "IFFY", "INCA", "INCH", "INTO", "IONS", "IOTA", + "IOWA", "IRIS", "IRMA", "IRON", "ISLE", "ITCH", "ITEM", "IVAN", "JACK", "JADE", "JAIL", "JAKE", + "JANE", "JAVA", "JEAN", "JEFF", "JERK", "JESS", "JEST", "JIBE", "JILL", "JILT", "JIVE", "JOAN", + "JOBS", "JOCK", "JOEL", "JOEY", "JOHN", "JOIN", "JOKE", "JOLT", "JOVE", "JUDD", "JUDE", "JUDO", + "JUDY", "JUJU", "JUKE", "JULY", "JUNE", "JUNK", "JUNO", "JURY", "JUST", "JUTE", "KAHN", "KALE", + "KANE", "KANT", "KARL", "KATE", "KEEL", "KEEN", "KENO", "KENT", "KERN", "KERR", "KEYS", "KICK", + "KILL", "KIND", "KING", "KIRK", "KISS", "KITE", "KLAN", "KNEE", "KNEW", "KNIT", "KNOB", "KNOT", + "KNOW", "KOCH", "KONG", "KUDO", "KURD", "KURT", "KYLE", "LACE", "LACK", "LACY", "LADY", "LAID", + "LAIN", "LAIR", "LAKE", "LAMB", "LAME", "LAND", "LANE", "LANG", "LARD", "LARK", "LASS", "LAST", + "LATE", "LAUD", "LAVA", "LAWN", "LAWS", "LAYS", "LEAD", "LEAF", "LEAK", "LEAN", "LEAR", "LEEK", + "LEER", "LEFT", "LEND", "LENS", "LENT", "LEON", "LESK", "LESS", "LEST", "LETS", "LIAR", "LICE", + "LICK", "LIED", "LIEN", "LIES", "LIEU", "LIFE", "LIFT", "LIKE", "LILA", "LILT", "LILY", "LIMA", + "LIMB", "LIME", "LIND", "LINE", "LINK", "LINT", "LION", "LISA", "LIST", "LIVE", "LOAD", "LOAF", + "LOAM", "LOAN", "LOCK", "LOFT", "LOGE", "LOIS", "LOLA", "LONE", "LONG", "LOOK", "LOON", "LOOT", + "LORD", "LORE", "LOSE", "LOSS", "LOST", "LOUD", "LOVE", "LOWE", "LUCK", "LUCY", "LUGE", "LUKE", + "LULU", "LUND", "LUNG", "LURA", "LURE", "LURK", "LUSH", "LUST", "LYLE", "LYNN", "LYON", "LYRA", + "MACE", "MADE", "MAGI", "MAID", "MAIL", "MAIN", "MAKE", "MALE", "MALI", "MALL", "MALT", "MANA", + "MANN", "MANY", "MARC", "MARE", "MARK", "MARS", "MART", "MARY", "MASH", "MASK", "MASS", "MAST", + "MATE", "MATH", "MAUL", "MAYO", "MEAD", "MEAL", "MEAN", "MEAT", "MEEK", "MEET", "MELD", "MELT", + "MEMO", "MEND", "MENU", "MERT", "MESH", "MESS", "MICE", "MIKE", "MILD", "MILE", "MILK", "MILL", + "MILT", "MIMI", "MIND", "MINE", "MINI", "MINK", "MINT", "MIRE", "MISS", "MIST", "MITE", "MITT", + "MOAN", "MOAT", "MOCK", "MODE", "MOLD", "MOLE", "MOLL", "MOLT", "MONA", "MONK", "MONT", "MOOD", + "MOON", "MOOR", "MOOT", "MORE", "MORN", "MORT", "MOSS", "MOST", "MOTH", "MOVE", "MUCH", "MUCK", + "MUDD", "MUFF", "MULE", "MULL", "MURK", "MUSH", "MUST", "MUTE", "MUTT", "MYRA", "MYTH", "NAGY", + "NAIL", "NAIR", "NAME", "NARY", "NASH", "NAVE", "NAVY", "NEAL", "NEAR", "NEAT", "NECK", "NEED", + "NEIL", "NELL", "NEON", "NERO", "NESS", "NEST", "NEWS", "NEWT", "NIBS", "NICE", "NICK", "NILE", + "NINA", "NINE", "NOAH", "NODE", "NOEL", "NOLL", "NONE", "NOOK", "NOON", "NORM", "NOSE", "NOTE", + "NOUN", "NOVA", "NUDE", "NULL", "NUMB", "OATH", "OBEY", "OBOE", "ODIN", "OHIO", "OILY", "OINT", + "OKAY", "OLAF", "OLDY", "OLGA", "OLIN", "OMAN", "OMEN", "OMIT", "ONCE", "ONES", "ONLY", "ONTO", + "ONUS", "ORAL", "ORGY", "OSLO", "OTIS", "OTTO", "OUCH", "OUST", "OUTS", "OVAL", "OVEN", "OVER", + "OWLY", "OWNS", "QUAD", "QUIT", "QUOD", "RACE", "RACK", "RACY", "RAFT", "RAGE", "RAID", "RAIL", + "RAIN", "RAKE", "RANK", "RANT", "RARE", "RASH", "RATE", "RAVE", "RAYS", "READ", "REAL", "REAM", + "REAR", "RECK", "REED", "REEF", "REEK", "REEL", "REID", "REIN", "RENA", "REND", "RENT", "REST", + "RICE", "RICH", "RICK", "RIDE", "RIFT", "RILL", "RIME", "RING", "RINK", "RISE", "RISK", "RITE", + "ROAD", "ROAM", "ROAR", "ROBE", "ROCK", "RODE", "ROIL", "ROLL", "ROME", "ROOD", "ROOF", "ROOK", + "ROOM", "ROOT", "ROSA", "ROSE", "ROSS", "ROSY", "ROTH", "ROUT", "ROVE", "ROWE", "ROWS", "RUBE", + "RUBY", "RUDE", "RUDY", "RUIN", "RULE", "RUNG", "RUNS", "RUNT", "RUSE", "RUSH", "RUSK", "RUSS", + "RUST", "RUTH", "SACK", "SAFE", "SAGE", "SAID", "SAIL", "SALE", "SALK", "SALT", "SAME", "SAND", + "SANE", "SANG", "SANK", "SARA", "SAUL", "SAVE", "SAYS", "SCAN", "SCAR", "SCAT", "SCOT", "SEAL", + "SEAM", "SEAR", "SEAT", "SEED", "SEEK", "SEEM", "SEEN", "SEES", "SELF", "SELL", "SEND", "SENT", + "SETS", "SEWN", "SHAG", "SHAM", "SHAW", "SHAY", "SHED", "SHIM", "SHIN", "SHOD", "SHOE", "SHOT", + "SHOW", "SHUN", "SHUT", "SICK", "SIDE", "SIFT", "SIGH", "SIGN", "SILK", "SILL", "SILO", "SILT", + "SINE", "SING", "SINK", "SIRE", "SITE", "SITS", "SITU", "SKAT", "SKEW", "SKID", "SKIM", "SKIN", + "SKIT", "SLAB", "SLAM", "SLAT", "SLAY", "SLED", "SLEW", "SLID", "SLIM", "SLIT", "SLOB", "SLOG", + "SLOT", "SLOW", "SLUG", "SLUM", "SLUR", "SMOG", "SMUG", "SNAG", "SNOB", "SNOW", "SNUB", "SNUG", + "SOAK", "SOAR", "SOCK", "SODA", "SOFA", "SOFT", "SOIL", "SOLD", "SOME", "SONG", "SOON", "SOOT", + "SORE", "SORT", "SOUL", "SOUR", "SOWN", "STAB", "STAG", "STAN", "STAR", "STAY", "STEM", "STEW", + "STIR", "STOW", "STUB", "STUN", "SUCH", "SUDS", "SUIT", "SULK", "SUMS", "SUNG", "SUNK", "SURE", + "SURF", "SWAB", "SWAG", "SWAM", "SWAN", "SWAT", "SWAY", "SWIM", "SWUM", "TACK", "TACT", "TAIL", + "TAKE", "TALE", "TALK", "TALL", "TANK", "TASK", "TATE", "TAUT", "TEAL", "TEAM", "TEAR", "TECH", + "TEEM", "TEEN", "TEET", "TELL", "TEND", "TENT", "TERM", "TERN", "TESS", "TEST", "THAN", "THAT", + "THEE", "THEM", "THEN", "THEY", "THIN", "THIS", "THUD", "THUG", "TICK", "TIDE", "TIDY", "TIED", + "TIER", "TILE", "TILL", "TILT", "TIME", "TINA", "TINE", "TINT", "TINY", "TIRE", "TOAD", "TOGO", + "TOIL", "TOLD", "TOLL", "TONE", "TONG", "TONY", "TOOK", "TOOL", "TOOT", "TORE", "TORN", "TOTE", + "TOUR", "TOUT", "TOWN", "TRAG", "TRAM", "TRAY", "TREE", "TREK", "TRIG", "TRIM", "TRIO", "TROD", + "TROT", "TROY", "TRUE", "TUBA", "TUBE", "TUCK", "TUFT", "TUNA", "TUNE", "TUNG", "TURF", "TURN", + "TUSK", "TWIG", "TWIN", "TWIT", "ULAN", "UNIT", "URGE", "USED", "USER", "USES", "UTAH", "VAIL", + "VAIN", "VALE", "VARY", "VASE", "VAST", "VEAL", "VEDA", "VEIL", "VEIN", "VEND", "VENT", "VERB", + "VERY", "VETO", "VICE", "VIEW", "VINE", "VISE", "VOID", "VOLT", "VOTE", "WACK", "WADE", "WAGE", + "WAIL", "WAIT", "WAKE", "WALE", "WALK", "WALL", "WALT", "WAND", "WANE", "WANG", "WANT", "WARD", + "WARM", "WARN", "WART", "WASH", "WAST", "WATS", "WATT", "WAVE", "WAVY", "WAYS", "WEAK", "WEAL", + "WEAN", "WEAR", "WEED", "WEEK", "WEIR", "WELD", "WELL", "WELT", "WENT", "WERE", "WERT", "WEST", + "WHAM", "WHAT", "WHEE", "WHEN", "WHET", "WHOA", "WHOM", "WICK", "WIFE", "WILD", "WILL", "WIND", + "WINE", "WING", "WINK", "WINO", "WIRE", "WISE", "WISH", "WITH", "WOLF", "WONT", "WOOD", "WOOL", + "WORD", "WORE", "WORK", "WORM", "WORN", "WOVE", "WRIT", "WYNN", "YALE", "YANG", "YANK", "YARD", + "YARN", "YAWL", "YAWN", "YEAH", "YEAR", "YELL", "YOGA", "YOKE"}; /* Extract 'length' bits from the char array 's' starting with bit 'start' */ @@ -212,8 +236,9 @@ RFC1751::btoe(std::string& strHuman, std::string const& strData) caBuffer[8] = char(p) << 6; - strHuman = std::string() + s_dictionary[extract(caBuffer, 0, 11)] + " " + s_dictionary[extract(caBuffer, 11, 11)] + - " " + s_dictionary[extract(caBuffer, 22, 11)] + " " + s_dictionary[extract(caBuffer, 33, 11)] + " " + + strHuman = std::string() + s_dictionary[extract(caBuffer, 0, 11)] + " " + + s_dictionary[extract(caBuffer, 11, 11)] + " " + s_dictionary[extract(caBuffer, 22, 11)] + + " " + s_dictionary[extract(caBuffer, 33, 11)] + " " + s_dictionary[extract(caBuffer, 44, 11)] + " " + s_dictionary[extract(caBuffer, 55, 11)]; } @@ -363,7 +388,8 @@ RFC1751::getKeyFromEnglish(std::string& strKey, std::string const& strHuman) boost::algorithm::trim(strTrimmed); - boost::algorithm::split(vWords, strTrimmed, boost::algorithm::is_space(), boost::algorithm::token_compress_on); + boost::algorithm::split( + vWords, strTrimmed, boost::algorithm::is_space(), boost::algorithm::token_compress_on); rc = 12 == vWords.size() ? 1 : -1; diff --git a/src/libxrpl/json/json_reader.cpp b/src/libxrpl/json/json_reader.cpp index 22df530b7e..d28268454f 100644 --- a/src/libxrpl/json/json_reader.cpp +++ b/src/libxrpl/json/json_reader.cpp @@ -358,7 +358,8 @@ Reader::readNumber() { if (!std::isdigit(static_cast(*current_))) { - auto ret = std::find(std::begin(extended_tokens), std::end(extended_tokens), *current_); + auto ret = + std::find(std::begin(extended_tokens), std::end(extended_tokens), *current_); if (ret == std::end(extended_tokens)) break; @@ -423,7 +424,8 @@ Reader::readObject(Token& tokenStart, unsigned depth) if (!readToken(colon) || colon.type_ != tokenMemberSeparator) { - return addErrorAndRecover("Missing ':' after object member name", colon, tokenObjectEnd); + return addErrorAndRecover( + "Missing ':' after object member name", colon, tokenObjectEnd); } // Reject duplicate names @@ -441,9 +443,11 @@ Reader::readObject(Token& tokenStart, unsigned depth) Token comma; if (!readToken(comma) || - (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator && comma.type_ != tokenComment)) + (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator && + comma.type_ != tokenComment)) { - return addErrorAndRecover("Missing ',' or '}' in object declaration", comma, tokenObjectEnd); + return addErrorAndRecover( + "Missing ',' or '}' in object declaration", comma, tokenObjectEnd); } bool finalizeTokenOk = true; @@ -496,7 +500,8 @@ Reader::readArray(Token& tokenStart, unsigned depth) if (!ok || badTokenType) { - return addErrorAndRecover("Missing ',' or ']' in array declaration", token, tokenArrayEnd); + return addErrorAndRecover( + "Missing ',' or ']' in array declaration", token, tokenArrayEnd); } if (token.type_ == tokenArrayEnd) @@ -517,14 +522,17 @@ Reader::decodeNumber(Token& token) if (current == token.end_) { - return addError("'" + std::string(token.start_, token.end_) + "' is not a valid number.", token); + return addError( + "'" + std::string(token.start_, token.end_) + "' is not a valid number.", token); } // The existing Json integers are 32-bit so using a 64-bit value here avoids // overflows in the conversion code below. std::int64_t value = 0; - static_assert(sizeof(value) > sizeof(Value::maxUInt), "The JSON integer overflow logic will need to be reworked."); + static_assert( + sizeof(value) > sizeof(Value::maxUInt), + "The JSON integer overflow logic will need to be reworked."); while (current < token.end_ && (value <= Value::maxUInt)) { @@ -532,7 +540,8 @@ Reader::decodeNumber(Token& token) if (c < '0' || c > '9') { - return addError("'" + std::string(token.start_, token.end_) + "' is not a number.", token); + return addError( + "'" + std::string(token.start_, token.end_) + "' is not a number.", token); } value = (value * 10) + (c - '0'); @@ -541,7 +550,8 @@ Reader::decodeNumber(Token& token) // More tokens left -> input is larger than largest possible return value if (current != token.end_) { - return addError("'" + std::string(token.start_, token.end_) + "' exceeds the allowable range.", token); + return addError( + "'" + std::string(token.start_, token.end_) + "' exceeds the allowable range.", token); } if (isNegative) @@ -550,7 +560,9 @@ Reader::decodeNumber(Token& token) if (value < Value::minInt || value > Value::maxInt) { - return addError("'" + std::string(token.start_, token.end_) + "' exceeds the allowable range.", token); + return addError( + "'" + std::string(token.start_, token.end_) + "' exceeds the allowable range.", + token); } currentValue() = static_cast(value); @@ -559,7 +571,9 @@ Reader::decodeNumber(Token& token) { if (value > Value::maxUInt) { - return addError("'" + std::string(token.start_, token.end_) + "' exceeds the allowable range.", token); + return addError( + "'" + std::string(token.start_, token.end_) + "' exceeds the allowable range.", + token); } // If it's representable as a signed integer, construct it as one. @@ -736,10 +750,15 @@ Reader::decodeUnicodeCodePoint(Token& token, Location& current, Location end, un } bool -Reader::decodeUnicodeEscapeSequence(Token& token, Location& current, Location end, unsigned int& unicode) +Reader::decodeUnicodeEscapeSequence( + Token& token, + Location& current, + Location end, + unsigned int& unicode) { if (end - current < 4) - return addError("Bad unicode escape sequence in string: four digits expected.", token, current); + return addError( + "Bad unicode escape sequence in string: four digits expected.", token, current); unicode = 0; diff --git a/src/libxrpl/json/json_value.cpp b/src/libxrpl/json/json_value.cpp index edbbafc1eb..60197d75f0 100644 --- a/src/libxrpl/json/json_value.cpp +++ b/src/libxrpl/json/json_value.cpp @@ -95,9 +95,11 @@ Value::CZString::CZString(char const* cstr, DuplicationPolicy allocate) Value::CZString::CZString(CZString const& other) : cstr_( - other.index_ != noDuplication && other.cstr_ != 0 ? valueAllocator()->makeMemberName(other.cstr_) - : other.cstr_) - , index_(other.cstr_ ? (other.index_ == noDuplication ? noDuplication : duplicate) : other.index_) + other.index_ != noDuplication && other.cstr_ != 0 + ? valueAllocator()->makeMemberName(other.cstr_) + : other.cstr_) + , index_( + other.cstr_ ? (other.index_ == noDuplication ? noDuplication : duplicate) : other.index_) { } @@ -219,7 +221,8 @@ Value::Value(xrpl::Number const& value) : type_(stringValue), allocated_(true) Value::Value(std::string const& value) : type_(stringValue), allocated_(true) { - value_.string_ = valueAllocator()->duplicateStringValue(value.c_str(), (unsigned int)value.length()); + value_.string_ = + valueAllocator()->duplicateStringValue(value.c_str(), (unsigned int)value.length()); } Value::Value(StaticString const& value) : type_(stringValue), allocated_(false) @@ -305,7 +308,8 @@ Value::operator=(Value const& other) return *this; } -Value::Value(Value&& other) noexcept : value_(other.value_), type_(other.type_), allocated_(other.allocated_) +Value::Value(Value&& other) noexcept + : value_(other.value_), type_(other.type_), allocated_(other.allocated_) { other.type_ = nullValue; other.allocated_ = 0; @@ -381,7 +385,8 @@ operator<(Value const& x, Value const& y) case stringValue: return (x.value_.string_ == 0 && y.value_.string_) || - (y.value_.string_ && x.value_.string_ && strcmp(x.value_.string_, y.value_.string_) < 0); + (y.value_.string_ && x.value_.string_ && + strcmp(x.value_.string_, y.value_.string_) < 0); case arrayValue: case objectValue: { @@ -431,11 +436,13 @@ operator==(Value const& x, Value const& y) case stringValue: return x.value_.string_ == y.value_.string_ || - (y.value_.string_ && x.value_.string_ && !strcmp(x.value_.string_, y.value_.string_)); + (y.value_.string_ && x.value_.string_ && + !strcmp(x.value_.string_, y.value_.string_)); case arrayValue: case objectValue: - return x.value_.map_->size() == y.value_.map_->size() && *x.value_.map_ == *y.value_.map_; + return x.value_.map_->size() == y.value_.map_->size() && + *x.value_.map_ == *y.value_.map_; // LCOV_EXCL_START default: @@ -501,11 +508,14 @@ Value::asInt() const return value_.int_; case uintValue: - JSON_ASSERT_MESSAGE(value_.uint_ < (unsigned)maxInt, "integer out of signed integer range"); + JSON_ASSERT_MESSAGE( + value_.uint_ < (unsigned)maxInt, "integer out of signed integer range"); return value_.uint_; case realValue: - JSON_ASSERT_MESSAGE(value_.real_ >= minInt && value_.real_ <= maxInt, "Real out of signed integer range"); + JSON_ASSERT_MESSAGE( + value_.real_ >= minInt && value_.real_ <= maxInt, + "Real out of signed integer range"); return Int(value_.real_); case booleanValue: @@ -551,7 +561,8 @@ Value::asAbsUInt() const case realValue: { if (value_.real_ < 0) { - JSON_ASSERT_MESSAGE(-1 * value_.real_ <= maxUInt, "Real out of unsigned integer range"); + JSON_ASSERT_MESSAGE( + -1 * value_.real_ <= maxUInt, "Real out of unsigned integer range"); return UInt(-1 * value_.real_); } JSON_ASSERT_MESSAGE(value_.real_ <= maxUInt, "Real out of unsigned integer range"); @@ -595,14 +606,16 @@ Value::asUInt() const return 0; case intValue: - JSON_ASSERT_MESSAGE(value_.int_ >= 0, "Negative integer can not be converted to unsigned integer"); + JSON_ASSERT_MESSAGE( + value_.int_ >= 0, "Negative integer can not be converted to unsigned integer"); return value_.int_; case uintValue: return value_.uint_; case realValue: - JSON_ASSERT_MESSAGE(value_.real_ >= 0 && value_.real_ <= maxUInt, "Real out of unsigned integer range"); + JSON_ASSERT_MESSAGE( + value_.real_ >= 0 && value_.real_ <= maxUInt, "Real out of unsigned integer range"); return UInt(value_.real_); case booleanValue: @@ -704,27 +717,30 @@ Value::isConvertibleTo(ValueType other) const case intValue: return (other == nullValue && value_.int_ == 0) || other == intValue || - (other == uintValue && value_.int_ >= 0) || other == realValue || other == stringValue || - other == booleanValue; + (other == uintValue && value_.int_ >= 0) || other == realValue || + other == stringValue || other == booleanValue; case uintValue: return (other == nullValue && value_.uint_ == 0) || - (other == intValue && value_.uint_ <= (unsigned)maxInt) || other == uintValue || other == realValue || - other == stringValue || other == booleanValue; + (other == intValue && value_.uint_ <= (unsigned)maxInt) || other == uintValue || + other == realValue || other == stringValue || other == booleanValue; case realValue: return (other == nullValue && value_.real_ == 0.0) || (other == intValue && value_.real_ >= minInt && value_.real_ <= maxInt) || (other == uintValue && value_.real_ >= 0 && value_.real_ <= maxUInt && - std::fabs(round(value_.real_) - value_.real_) < std::numeric_limits::epsilon()) || + std::fabs(round(value_.real_) - value_.real_) < + std::numeric_limits::epsilon()) || other == realValue || other == stringValue || other == booleanValue; case booleanValue: - return (other == nullValue && value_.bool_ == false) || other == intValue || other == uintValue || - other == realValue || other == stringValue || other == booleanValue; + return (other == nullValue && value_.bool_ == false) || other == intValue || + other == uintValue || other == realValue || other == stringValue || + other == booleanValue; case stringValue: - return other == stringValue || (other == nullValue && (!value_.string_ || value_.string_[0] == 0)); + return other == stringValue || + (other == nullValue && (!value_.string_ || value_.string_[0] == 0)); case arrayValue: return other == arrayValue || (other == nullValue && value_.map_->size() == 0); @@ -777,7 +793,8 @@ Value::size() const return 0; // unreachable; } -Value::operator bool() const +Value:: +operator bool() const { if (isNull()) return false; @@ -794,7 +811,9 @@ Value::operator bool() const void Value::clear() { - XRPL_ASSERT(type_ == nullValue || type_ == arrayValue || type_ == objectValue, "Json::Value::clear : valid type"); + XRPL_ASSERT( + type_ == nullValue || type_ == arrayValue || type_ == objectValue, + "Json::Value::clear : valid type"); switch (type_) { @@ -811,7 +830,8 @@ Value::clear() Value& Value::operator[](UInt index) { - XRPL_ASSERT(type_ == nullValue || type_ == arrayValue, "Json::Value::operator[](UInt) : valid type"); + XRPL_ASSERT( + type_ == nullValue || type_ == arrayValue, "Json::Value::operator[](UInt) : valid type"); if (type_ == nullValue) *this = Value(arrayValue); @@ -830,7 +850,9 @@ Value::operator[](UInt index) Value const& Value::operator[](UInt index) const { - XRPL_ASSERT(type_ == nullValue || type_ == arrayValue, "Json::Value::operator[](UInt) const : valid type"); + XRPL_ASSERT( + type_ == nullValue || type_ == arrayValue, + "Json::Value::operator[](UInt) const : valid type"); if (type_ == nullValue) return null; @@ -853,7 +875,8 @@ Value::operator[](char const* key) Value& Value::resolveReference(char const* key, bool isStatic) { - XRPL_ASSERT(type_ == nullValue || type_ == objectValue, "Json::Value::resolveReference : valid type"); + XRPL_ASSERT( + type_ == nullValue || type_ == objectValue, "Json::Value::resolveReference : valid type"); if (type_ == nullValue) *this = Value(objectValue); @@ -886,7 +909,9 @@ Value::isValidIndex(UInt index) const Value const& Value::operator[](char const* key) const { - XRPL_ASSERT(type_ == nullValue || type_ == objectValue, "Json::Value::operator[](const char*) const : valid type"); + XRPL_ASSERT( + type_ == nullValue || type_ == objectValue, + "Json::Value::operator[](const char*) const : valid type"); if (type_ == nullValue) return null; @@ -952,7 +977,8 @@ Value::get(std::string const& key, Value const& defaultValue) const Value Value::removeMember(char const* key) { - XRPL_ASSERT(type_ == nullValue || type_ == objectValue, "Json::Value::removeMember : valid type"); + XRPL_ASSERT( + type_ == nullValue || type_ == objectValue, "Json::Value::removeMember : valid type"); if (type_ == nullValue) return null; @@ -999,7 +1025,8 @@ Value::isMember(StaticString const& key) const Value::Members Value::getMemberNames() const { - XRPL_ASSERT(type_ == nullValue || type_ == objectValue, "Json::Value::getMemberNames : valid type"); + XRPL_ASSERT( + type_ == nullValue || type_ == objectValue, "Json::Value::getMemberNames : valid type"); if (type_ == nullValue) return Value::Members(); diff --git a/src/libxrpl/json/json_valueiterator.cpp b/src/libxrpl/json/json_valueiterator.cpp index 90a1ebe44b..e40e674ee7 100644 --- a/src/libxrpl/json/json_valueiterator.cpp +++ b/src/libxrpl/json/json_valueiterator.cpp @@ -17,7 +17,8 @@ ValueIteratorBase::ValueIteratorBase() : current_(), isNull_(true) { } -ValueIteratorBase::ValueIteratorBase(Value::ObjectValues::iterator const& current) : current_(current), isNull_(false) +ValueIteratorBase::ValueIteratorBase(Value::ObjectValues::iterator const& current) + : current_(current), isNull_(false) { } @@ -125,7 +126,8 @@ ValueIteratorBase::memberName() const // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// -ValueConstIterator::ValueConstIterator(Value::ObjectValues::iterator const& current) : ValueIteratorBase(current) +ValueConstIterator::ValueConstIterator(Value::ObjectValues::iterator const& current) + : ValueIteratorBase(current) { } @@ -144,7 +146,8 @@ ValueConstIterator::operator=(ValueIteratorBase const& other) // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// -ValueIterator::ValueIterator(Value::ObjectValues::iterator const& current) : ValueIteratorBase(current) +ValueIterator::ValueIterator(Value::ObjectValues::iterator const& current) + : ValueIteratorBase(current) { } diff --git a/src/libxrpl/json/json_writer.cpp b/src/libxrpl/json/json_writer.cpp index e36cf72b1c..13baf95845 100644 --- a/src/libxrpl/json/json_writer.cpp +++ b/src/libxrpl/json/json_writer.cpp @@ -374,7 +374,9 @@ StyledWriter::writeArrayValue(Value const& value) } else // output on a single line { - XRPL_ASSERT(childValues_.size() == size, "Json::StyledWriter::writeArrayValue : child size match"); + XRPL_ASSERT( + childValues_.size() == size, + "Json::StyledWriter::writeArrayValue : child size match"); document_ += "[ "; for (unsigned index = 0; index < size; ++index) @@ -400,7 +402,8 @@ StyledWriter::isMultilineArray(Value const& value) for (int index = 0; index < size && !isMultiLine; ++index) { Value const& childValue = value[index]; - isMultiLine = isMultiLine || ((childValue.isArray() || childValue.isObject()) && childValue.size() > 0); + isMultiLine = isMultiLine || + ((childValue.isArray() || childValue.isObject()) && childValue.size() > 0); } if (!isMultiLine) // check if line length > max line length @@ -464,7 +467,9 @@ StyledWriter::indent() void StyledWriter::unindent() { - XRPL_ASSERT(int(indentString_.size()) >= indentSize_, "Json::StyledWriter::unindent : maximum indent size"); + XRPL_ASSERT( + int(indentString_.size()) >= indentSize_, + "Json::StyledWriter::unindent : maximum indent size"); indentString_.resize(indentString_.size() - indentSize_); } @@ -594,7 +599,9 @@ StyledStreamWriter::writeArrayValue(Value const& value) } else // output on a single line { - XRPL_ASSERT(childValues_.size() == size, "Json::StyledStreamWriter::writeArrayValue : child size match"); + XRPL_ASSERT( + childValues_.size() == size, + "Json::StyledStreamWriter::writeArrayValue : child size match"); *document_ << "[ "; for (unsigned index = 0; index < size; ++index) @@ -620,7 +627,8 @@ StyledStreamWriter::isMultilineArray(Value const& value) for (int index = 0; index < size && !isMultiLine; ++index) { Value const& childValue = value[index]; - isMultiLine = isMultiLine || ((childValue.isArray() || childValue.isObject()) && childValue.size() > 0); + isMultiLine = isMultiLine || + ((childValue.isArray() || childValue.isObject()) && childValue.size() > 0); } if (!isMultiLine) // check if line length > max line length @@ -686,7 +694,8 @@ void StyledStreamWriter::unindent() { XRPL_ASSERT( - indentString_.size() >= indentation_.size(), "Json::StyledStreamWriter::unindent : maximum indent size"); + indentString_.size() >= indentation_.size(), + "Json::StyledStreamWriter::unindent : maximum indent size"); indentString_.resize(indentString_.size() - indentation_.size()); } diff --git a/src/xrpld/app/ledger/AcceptedLedgerTx.cpp b/src/libxrpl/ledger/AcceptedLedgerTx.cpp similarity index 79% rename from src/xrpld/app/ledger/AcceptedLedgerTx.cpp rename to src/libxrpl/ledger/AcceptedLedgerTx.cpp index 2ef05e511d..f0d243f9b6 100644 --- a/src/xrpld/app/ledger/AcceptedLedgerTx.cpp +++ b/src/libxrpl/ledger/AcceptedLedgerTx.cpp @@ -1,7 +1,7 @@ -#include - #include #include +#include +#include #include #include @@ -11,7 +11,9 @@ AcceptedLedgerTx::AcceptedLedgerTx( std::shared_ptr const& ledger, std::shared_ptr const& txn, std::shared_ptr const& met) - : mTxn(txn), mMeta(txn->getTransactionID(), ledger->seq(), *met), mAffected(mMeta.getAffectedAccounts()) + : mTxn(txn) + , mMeta(txn->getTransactionID(), ledger->seq(), *met) + , mAffected(mMeta.getAffectedAccounts()) { XRPL_ASSERT(!ledger->open(), "xrpl::AcceptedLedgerTx::AcceptedLedgerTx : valid ledger state"); @@ -42,8 +44,12 @@ AcceptedLedgerTx::AcceptedLedgerTx( // If the offer create is not self funded then add the owner balance if (account != amount.issue().account) { - auto const ownerFunds = - accountFunds(*ledger, account, amount, fhIGNORE_FREEZE, beast::Journal{beast::Journal::getNullSink()}); + auto const ownerFunds = accountFunds( + *ledger, + account, + amount, + fhIGNORE_FREEZE, + beast::Journal{beast::Journal::getNullSink()}); mJson[jss::transaction][jss::owner_funds] = ownerFunds.getText(); } } diff --git a/src/libxrpl/ledger/ApplyStateTable.cpp b/src/libxrpl/ledger/ApplyStateTable.cpp index 9892951e15..e31b39b437 100644 --- a/src/libxrpl/ledger/ApplyStateTable.cpp +++ b/src/libxrpl/ledger/ApplyStateTable.cpp @@ -127,8 +127,8 @@ ApplyStateTable::apply( auto curNode = item.second.second; if ((type == &sfModifiedNode) && (*curNode == *origNode)) continue; - std::uint16_t nodeType = - curNode ? curNode->getFieldU16(sfLedgerEntryType) : origNode->getFieldU16(sfLedgerEntryType); + std::uint16_t nodeType = curNode ? curNode->getFieldU16(sfLedgerEntryType) + : origNode->getFieldU16(sfLedgerEntryType); meta.setAffectedNode(item.first, *type, nodeType); if (type == &sfDeletedNode) { @@ -143,7 +143,8 @@ ApplyStateTable::apply( { // go through the original node for // modified fields saved on modification - if (obj.getFName().shouldMeta(SField::sMD_ChangeOrig) && !curNode->hasMatchingEntry(obj)) + if (obj.getFName().shouldMeta(SField::sMD_ChangeOrig) && + !curNode->hasMatchingEntry(obj)) prevs.emplace_back(obj); } @@ -176,7 +177,8 @@ ApplyStateTable::apply( for (auto const& obj : *origNode) { // search the original node for values saved on modify - if (obj.getFName().shouldMeta(SField::sMD_ChangeOrig) && !curNode->hasMatchingEntry(obj)) + if (obj.getFName().shouldMeta(SField::sMD_ChangeOrig) && + !curNode->hasMatchingEntry(obj)) prevs.emplace_back(obj); } @@ -209,7 +211,8 @@ ApplyStateTable::apply( for (auto const& obj : *curNode) { // save non-default values - if (!obj.isDefault() && obj.getFName().shouldMeta(SField::sMD_Create | SField::sMD_Always)) + if (!obj.isDefault() && + obj.getFName().shouldMeta(SField::sMD_Create | SField::sMD_Always)) news.emplace_back(obj); } @@ -276,8 +279,10 @@ ApplyStateTable::exists(ReadView const& base, Keylet const& k) const } auto -ApplyStateTable::succ(ReadView const& base, key_type const& key, std::optional const& last) const - -> std::optional +ApplyStateTable::succ( + ReadView const& base, + key_type const& key, + std::optional const& last) const -> std::optional { std::optional next = key; items_t::const_iterator iter; @@ -392,8 +397,8 @@ void ApplyStateTable::rawErase(ReadView const& base, std::shared_ptr const& sle) { using namespace std; - auto const result = - items_.emplace(piecewise_construct, forward_as_tuple(sle->key()), forward_as_tuple(Action::erase, sle)); + auto const result = items_.emplace( + piecewise_construct, forward_as_tuple(sle->key()), forward_as_tuple(Action::erase, sle)); if (result.second) return; auto& item = result.first->second; @@ -421,7 +426,10 @@ ApplyStateTable::insert(ReadView const& base, std::shared_ptr const& sle) { using namespace std; items_.emplace_hint( - iter, piecewise_construct, forward_as_tuple(sle->key()), forward_as_tuple(Action::insert, sle)); + iter, + piecewise_construct, + forward_as_tuple(sle->key()), + forward_as_tuple(Action::insert, sle)); return; } auto& item = iter->second; @@ -448,7 +456,10 @@ ApplyStateTable::replace(ReadView const& base, std::shared_ptr const& sle) { using namespace std; items_.emplace_hint( - iter, piecewise_construct, forward_as_tuple(sle->key()), forward_as_tuple(Action::modify, sle)); + iter, + piecewise_construct, + forward_as_tuple(sle->key()), + forward_as_tuple(Action::modify, sle)); return; } auto& item = iter->second; @@ -577,7 +588,12 @@ ApplyStateTable::getForMod(ReadView const& base, key_type const& key, Mods& mods } void -ApplyStateTable::threadTx(ReadView const& base, TxMeta& meta, AccountID const& to, Mods& mods, beast::Journal j) +ApplyStateTable::threadTx( + ReadView const& base, + TxMeta& meta, + AccountID const& to, + Mods& mods, + beast::Journal j) { auto const sle = getForMod(base, keylet::account(to).key, mods, j); if (!sle) @@ -589,7 +605,8 @@ ApplyStateTable::threadTx(ReadView const& base, TxMeta& meta, AccountID const& t return; } // threadItem only applied to AccountRoot - XRPL_ASSERT(sle->isThreadedType(base.rules()), "xrpl::ApplyStateTable::threadTx : SLE is threaded"); + XRPL_ASSERT( + sle->isThreadedType(base.rules()), "xrpl::ApplyStateTable::threadTx : SLE is threaded"); threadItem(meta, sle); } diff --git a/src/libxrpl/ledger/ApplyView.cpp b/src/libxrpl/ledger/ApplyView.cpp index fc35ff5119..463b2ba538 100644 --- a/src/libxrpl/ledger/ApplyView.cpp +++ b/src/libxrpl/ledger/ApplyView.cpp @@ -363,7 +363,8 @@ ApplyView::dirRemove(Keylet const& directory, std::uint64_t page, uint256 const& // Check whether the next page is the last page and, if // so, whether it's empty. If it is, delete it. - if (nextPage != rootPage && next->getFieldU64(sfIndexNext) == rootPage && next->getFieldV256(sfIndexes).empty()) + if (nextPage != rootPage && next->getFieldU64(sfIndexNext) == rootPage && + next->getFieldV256(sfIndexes).empty()) { // Since next doesn't point to the root, it // can't be pointing to prev. diff --git a/src/libxrpl/ledger/ApplyViewBase.cpp b/src/libxrpl/ledger/ApplyViewBase.cpp index ecb5180557..a5bea68759 100644 --- a/src/libxrpl/ledger/ApplyViewBase.cpp +++ b/src/libxrpl/ledger/ApplyViewBase.cpp @@ -40,7 +40,8 @@ ApplyViewBase::exists(Keylet const& k) const } auto -ApplyViewBase::succ(key_type const& key, std::optional const& last) const -> std::optional +ApplyViewBase::succ(key_type const& key, std::optional const& last) const + -> std::optional { return items_.succ(*base_, key, last); } diff --git a/src/libxrpl/ledger/BookDirs.cpp b/src/libxrpl/ledger/BookDirs.cpp index 03dd0b0e13..4ba5945e8e 100644 --- a/src/libxrpl/ledger/BookDirs.cpp +++ b/src/libxrpl/ledger/BookDirs.cpp @@ -74,7 +74,8 @@ BookDirs::const_iterator::operator++() XRPL_ASSERT(index_ != zero, "xrpl::BookDirs::const_iterator::operator++ : nonzero index"); if (!cdirNext(*view_, cur_key_, sle_, entry_, index_)) { - if (index_ != 0 || (cur_key_ = view_->succ(++cur_key_, next_quality_).value_or(zero)) == zero) + if (index_ != 0 || + (cur_key_ = view_->succ(++cur_key_, next_quality_).value_or(zero)) == zero) { cur_key_ = key_; entry_ = 0; @@ -97,7 +98,8 @@ BookDirs::const_iterator::operator++() BookDirs::const_iterator BookDirs::const_iterator::operator++(int) { - XRPL_ASSERT(index_ != beast::zero, "xrpl::BookDirs::const_iterator::operator++(int) : nonzero index"); + XRPL_ASSERT( + index_ != beast::zero, "xrpl::BookDirs::const_iterator::operator++(int) : nonzero index"); const_iterator tmp(*this); ++(*this); return tmp; diff --git a/src/xrpld/app/ledger/BookListeners.cpp b/src/libxrpl/ledger/BookListeners.cpp similarity index 95% rename from src/xrpld/app/ledger/BookListeners.cpp rename to src/libxrpl/ledger/BookListeners.cpp index 4d72c6f3b3..9ba25b783a 100644 --- a/src/xrpld/app/ledger/BookListeners.cpp +++ b/src/libxrpl/ledger/BookListeners.cpp @@ -1,4 +1,4 @@ -#include +#include namespace xrpl { diff --git a/src/libxrpl/ledger/CredentialHelpers.cpp b/src/libxrpl/ledger/CredentialHelpers.cpp index c737d42f07..04438e09ad 100644 --- a/src/libxrpl/ledger/CredentialHelpers.cpp +++ b/src/libxrpl/ledger/CredentialHelpers.cpp @@ -11,7 +11,8 @@ namespace credentials { bool checkExpired(std::shared_ptr const& sleCredential, NetClock::time_point const& closed) { - std::uint32_t const exp = (*sleCredential)[~sfExpiration].value_or(std::numeric_limits::max()); + std::uint32_t const exp = + (*sleCredential)[~sfExpiration].value_or(std::numeric_limits::max()); std::uint32_t const now = closed.time_since_epoch().count(); return now > exp; } @@ -46,7 +47,8 @@ deleteSLE(ApplyView& view, std::shared_ptr const& sleCredential, beast::Jou if (!sleCredential) return tecNO_ENTRY; - auto delSLE = [&view, &sleCredential, j](AccountID const& account, SField const& node, bool isOwner) -> TER { + auto delSLE = [&view, &sleCredential, j]( + AccountID const& account, SField const& node, bool isOwner) -> TER { auto const sleAccount = view.peek(keylet::account(account)); if (!sleAccount) { @@ -102,7 +104,8 @@ checkFields(STTx const& tx, beast::Journal j) auto const& credentials = tx.getFieldV256(sfCredentialIDs); if (credentials.empty() || (credentials.size() > maxCredentialsArraySize)) { - JLOG(j.trace()) << "Malformed transaction: Credentials array size is invalid: " << credentials.size(); + JLOG(j.trace()) << "Malformed transaction: Credentials array size is invalid: " + << credentials.size(); return temMALFORMED; } @@ -334,9 +337,9 @@ verifyDepositPreauth( if (src != dst) { if (!view.exists(keylet::depositPreauth(dst, src))) - return !credentialsPresent - ? tecNO_PERMISSION - : credentials::authorizedDepositPreauth(view, tx.getFieldV256(sfCredentialIDs), dst); + return !credentialsPresent ? tecNO_PERMISSION + : credentials::authorizedDepositPreauth( + view, tx.getFieldV256(sfCredentialIDs), dst); } } diff --git a/src/libxrpl/ledger/Credit.cpp b/src/libxrpl/ledger/Credit.cpp index 064fcdaf3b..0a0283c3b8 100644 --- a/src/libxrpl/ledger/Credit.cpp +++ b/src/libxrpl/ledger/Credit.cpp @@ -6,7 +6,11 @@ namespace xrpl { STAmount -creditLimit(ReadView const& view, AccountID const& account, AccountID const& issuer, Currency const& currency) +creditLimit( + ReadView const& view, + AccountID const& account, + AccountID const& issuer, + Currency const& currency) { STAmount result(Issue{currency, account}); @@ -30,7 +34,11 @@ creditLimit2(ReadView const& v, AccountID const& acc, AccountID const& iss, Curr } STAmount -creditBalance(ReadView const& view, AccountID const& account, AccountID const& issuer, Currency const& currency) +creditBalance( + ReadView const& view, + AccountID const& account, + AccountID const& issuer, + Currency const& currency) { STAmount result(Issue{currency, account}); diff --git a/src/libxrpl/ledger/Dir.cpp b/src/libxrpl/ledger/Dir.cpp index cf0b01aa7f..a27171fe12 100644 --- a/src/libxrpl/ledger/Dir.cpp +++ b/src/libxrpl/ledger/Dir.cpp @@ -4,7 +4,8 @@ namespace xrpl { using const_iterator = Dir::const_iterator; -Dir::Dir(ReadView const& view, Keylet const& key) : view_(&view), root_(key), sle_(view_->read(root_)) +Dir::Dir(ReadView const& view, Keylet const& key) + : view_(&view), root_(key), sle_(view_->read(root_)) { if (sle_ != nullptr) indexes_ = &sle_->getFieldV256(sfIndexes); diff --git a/src/libxrpl/ledger/OpenView.cpp b/src/libxrpl/ledger/OpenView.cpp index 73bd3e16ea..d27d755c66 100644 --- a/src/libxrpl/ledger/OpenView.cpp +++ b/src/libxrpl/ledger/OpenView.cpp @@ -10,7 +10,8 @@ private: txs_map::const_iterator iter_; public: - explicit txs_iter_impl(bool metadata, txs_map::const_iterator iter) : metadata_(metadata), iter_(iter) + explicit txs_iter_impl(bool metadata, txs_map::const_iterator iter) + : metadata_(metadata), iter_(iter) { } @@ -56,7 +57,8 @@ public: OpenView::OpenView(OpenView const& rhs) : ReadView(rhs) , TxsRawView(rhs) - , monotonic_resource_{std::make_unique(initialBufferSize)} + , monotonic_resource_{std::make_unique( + initialBufferSize)} , txs_{rhs.txs_, monotonic_resource_.get()} , rules_{rhs.rules_} , header_{rhs.header_} @@ -65,8 +67,13 @@ OpenView::OpenView(OpenView const& rhs) , hold_{rhs.hold_} , open_{rhs.open_} {}; -OpenView::OpenView(open_ledger_t, ReadView const* base, Rules const& rules, std::shared_ptr hold) - : monotonic_resource_{std::make_unique(initialBufferSize)} +OpenView::OpenView( + open_ledger_t, + ReadView const* base, + Rules const& rules, + std::shared_ptr hold) + : monotonic_resource_{std::make_unique( + initialBufferSize)} , txs_{monotonic_resource_.get()} , rules_(rules) , header_(base->header()) @@ -81,7 +88,8 @@ OpenView::OpenView(open_ledger_t, ReadView const* base, Rules const& rules, std: } OpenView::OpenView(ReadView const* base, std::shared_ptr hold) - : monotonic_resource_{std::make_unique(initialBufferSize)} + : monotonic_resource_{std::make_unique( + initialBufferSize)} , txs_{monotonic_resource_.get()} , rules_(base->rules()) , header_(base->header()) @@ -132,7 +140,8 @@ OpenView::exists(Keylet const& k) const } auto -OpenView::succ(key_type const& key, std::optional const& last) const -> std::optional +OpenView::succ(key_type const& key, std::optional const& last) const + -> std::optional { return items_.succ(*base_, key, last); } @@ -231,8 +240,8 @@ OpenView::rawTxInsert( std::shared_ptr const& txn, std::shared_ptr const& metaData) { - auto const result = - txs_.emplace(std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(txn, metaData)); + auto const result = txs_.emplace( + std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(txn, metaData)); if (!result.second) LogicError("rawTxInsert: duplicate TX id: " + to_string(key)); } diff --git a/src/libxrpl/ledger/PaymentSandbox.cpp b/src/libxrpl/ledger/PaymentSandbox.cpp index 67492142da..e211917466 100644 --- a/src/libxrpl/ledger/PaymentSandbox.cpp +++ b/src/libxrpl/ledger/PaymentSandbox.cpp @@ -23,7 +23,8 @@ DeferredCredits::credit( STAmount const& amount, STAmount const& preCreditSenderBalance) { - XRPL_ASSERT(sender != receiver, "xrpl::detail::DeferredCredits::credit : sender is not receiver"); + XRPL_ASSERT( + sender != receiver, "xrpl::detail::DeferredCredits::credit : sender is not receiver"); XRPL_ASSERT(!amount.negative(), "xrpl::detail::DeferredCredits::credit : positive amount"); auto const k = makeKey(sender, receiver, amount.getCurrency()); @@ -81,8 +82,10 @@ DeferredCredits::ownerCount(AccountID const& id) const // Get the adjustments for the balance between main and other. auto -DeferredCredits::adjustments(AccountID const& main, AccountID const& other, Currency const& currency) const - -> std::optional +DeferredCredits::adjustments( + AccountID const& main, + AccountID const& other, + Currency const& currency) const -> std::optional { std::optional result; @@ -136,7 +139,10 @@ DeferredCredits::apply(DeferredCredits& to) } // namespace detail STAmount -PaymentSandbox::balanceHook(AccountID const& account, AccountID const& issuer, STAmount const& amount) const +PaymentSandbox::balanceHook( + AccountID const& account, + AccountID const& issuer, + STAmount const& amount) const { /* There are two algorithms here. The pre-switchover algorithm takes the @@ -205,7 +211,10 @@ PaymentSandbox::creditHook( } void -PaymentSandbox::adjustOwnerCountHook(AccountID const& account, std::uint32_t cur, std::uint32_t next) +PaymentSandbox::adjustOwnerCountHook( + AccountID const& account, + std::uint32_t cur, + std::uint32_t next) { tab_.ownerCount(account, cur, next); } diff --git a/src/libxrpl/ledger/RawStateTable.cpp b/src/libxrpl/ledger/RawStateTable.cpp index 4b5f6837b2..fcd8126c87 100644 --- a/src/libxrpl/ledger/RawStateTable.cpp +++ b/src/libxrpl/ledger/RawStateTable.cpp @@ -126,7 +126,8 @@ private: void skip() { - while (iter1_ != end1_ && iter1_->second.action == Action::erase && sle0_->key() == sle1_->key()) + while (iter1_ != end1_ && iter1_->second.action == Action::erase && + sle0_->key() == sle1_->key()) { inc1(); inc0(); @@ -182,8 +183,8 @@ RawStateTable::exists(ReadView const& base, Keylet const& k) const the lower of the two. */ auto -RawStateTable::succ(ReadView const& base, key_type const& key, std::optional const& last) const - -> std::optional +RawStateTable::succ(ReadView const& base, key_type const& key, std::optional const& last) + const -> std::optional { std::optional next = key; items_t::const_iterator iter; @@ -219,7 +220,9 @@ RawStateTable::erase(std::shared_ptr const& sle) { // The base invariant is checked during apply auto const result = items_.emplace( - std::piecewise_construct, std::forward_as_tuple(sle->key()), std::forward_as_tuple(Action::erase, sle)); + std::piecewise_construct, + std::forward_as_tuple(sle->key()), + std::forward_as_tuple(Action::erase, sle)); if (result.second) return; auto& item = result.first->second; @@ -242,7 +245,9 @@ void RawStateTable::insert(std::shared_ptr const& sle) { auto const result = items_.emplace( - std::piecewise_construct, std::forward_as_tuple(sle->key()), std::forward_as_tuple(Action::insert, sle)); + std::piecewise_construct, + std::forward_as_tuple(sle->key()), + std::forward_as_tuple(Action::insert, sle)); if (result.second) return; auto& item = result.first->second; @@ -265,7 +270,9 @@ void RawStateTable::replace(std::shared_ptr const& sle) { auto const result = items_.emplace( - std::piecewise_construct, std::forward_as_tuple(sle->key()), std::forward_as_tuple(Action::replace, sle)); + std::piecewise_construct, + std::forward_as_tuple(sle->key()), + std::forward_as_tuple(Action::replace, sle)); if (result.second) return; auto& item = result.first->second; @@ -306,13 +313,15 @@ RawStateTable::destroyXRP(XRPAmount const& fee) std::unique_ptr RawStateTable::slesBegin(ReadView const& base) const { - return std::make_unique(items_.begin(), items_.end(), base.sles.begin(), base.sles.end()); + return std::make_unique( + items_.begin(), items_.end(), base.sles.begin(), base.sles.end()); } std::unique_ptr RawStateTable::slesEnd(ReadView const& base) const { - return std::make_unique(items_.end(), items_.end(), base.sles.end(), base.sles.end()); + return std::make_unique( + items_.end(), items_.end(), base.sles.end(), base.sles.end()); } std::unique_ptr diff --git a/src/libxrpl/ledger/ReadView.cpp b/src/libxrpl/ledger/ReadView.cpp index d6674ba0da..e0764d6c81 100644 --- a/src/libxrpl/ledger/ReadView.cpp +++ b/src/libxrpl/ledger/ReadView.cpp @@ -53,7 +53,9 @@ makeRulesGivenLedger(DigestAwareReadView const& ledger, Rules const& current) } Rules -makeRulesGivenLedger(DigestAwareReadView const& ledger, std::unordered_set> const& presets) +makeRulesGivenLedger( + DigestAwareReadView const& ledger, + std::unordered_set> const& presets) { Keylet const k = keylet::amendments(); std::optional digest = ledger.digest(k.key); diff --git a/src/libxrpl/ledger/View.cpp b/src/libxrpl/ledger/View.cpp index 72df44ec4a..837d5dfee6 100644 --- a/src/libxrpl/ledger/View.cpp +++ b/src/libxrpl/ledger/View.cpp @@ -27,9 +27,15 @@ namespace detail { template < class V, class N, - class = std::enable_if_t, SLE> && std::is_base_of_v>> + class = std::enable_if_t< + std::is_same_v, SLE> && std::is_base_of_v>> bool -internalDirNext(V& view, uint256 const& root, std::shared_ptr& page, unsigned int& index, uint256& entry) +internalDirNext( + V& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry) { auto const& svIndexes = page->getFieldV256(sfIndexes); XRPL_ASSERT(index <= svIndexes.size(), "xrpl::detail::internalDirNext : index inside range"); @@ -66,9 +72,15 @@ internalDirNext(V& view, uint256 const& root, std::shared_ptr& page, unsigned template < class V, class N, - class = std::enable_if_t, SLE> && std::is_base_of_v>> + class = std::enable_if_t< + std::is_same_v, SLE> && std::is_base_of_v>> bool -internalDirFirst(V& view, uint256 const& root, std::shared_ptr& page, unsigned int& index, uint256& entry) +internalDirFirst( + V& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry) { if constexpr (std::is_const_v) page = view.read(keylet::page(root)); @@ -86,13 +98,23 @@ internalDirFirst(V& view, uint256 const& root, std::shared_ptr& page, unsigne } // namespace detail bool -dirFirst(ApplyView& view, uint256 const& root, std::shared_ptr& page, unsigned int& index, uint256& entry) +dirFirst( + ApplyView& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry) { return detail::internalDirFirst(view, root, page, index, entry); } bool -dirNext(ApplyView& view, uint256 const& root, std::shared_ptr& page, unsigned int& index, uint256& entry) +dirNext( + ApplyView& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry) { return detail::internalDirNext(view, root, page, index, entry); } @@ -166,7 +188,11 @@ isGlobalFrozen(ReadView const& view, Asset const& asset) } bool -isIndividualFrozen(ReadView const& view, AccountID const& account, Currency const& currency, AccountID const& issuer) +isIndividualFrozen( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer) { if (isXRP(currency)) return false; @@ -191,7 +217,11 @@ isIndividualFrozen(ReadView const& view, AccountID const& account, MPTIssue cons // Can the specified account spend the specified currency issued by // the specified issuer or does the freeze flag prohibit it? bool -isFrozen(ReadView const& view, AccountID const& account, Currency const& currency, AccountID const& issuer) +isFrozen( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer) { if (isXRP(currency)) return false; @@ -216,7 +246,11 @@ isFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssu } [[nodiscard]] bool -isAnyFrozen(ReadView const& view, std::initializer_list const& accounts, MPTIssue const& mptIssue, int depth) +isAnyFrozen( + ReadView const& view, + std::initializer_list const& accounts, + MPTIssue const& mptIssue, + int depth) { if (isGlobalFrozen(view, mptIssue)) return true; @@ -237,7 +271,11 @@ isAnyFrozen(ReadView const& view, std::initializer_list const& accoun } bool -isVaultPseudoAccountFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptShare, int depth) +isVaultPseudoAccountFrozen( + ReadView const& view, + AccountID const& account, + MPTIssue const& mptShare, + int depth) { if (!view.rules().enabled(featureSingleAssetVault)) return false; @@ -274,7 +312,11 @@ isVaultPseudoAccountFrozen(ReadView const& view, AccountID const& account, MPTIs } bool -isDeepFrozen(ReadView const& view, AccountID const& account, Currency const& currency, AccountID const& issuer) +isDeepFrozen( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer) { if (isXRP(currency)) { @@ -296,7 +338,11 @@ isDeepFrozen(ReadView const& view, AccountID const& account, Currency const& cur } bool -isLPTokenFrozen(ReadView const& view, AccountID const& account, Issue const& asset, Issue const& asset2) +isLPTokenFrozen( + ReadView const& view, + AccountID const& account, + Issue const& asset, + Issue const& asset2) { return isFrozen(view, account, asset.currency, asset.account) || isFrozen(view, account, asset2.currency, asset2.account); @@ -320,7 +366,8 @@ getLineIfUsable( if (zeroIfFrozen == fhZERO_IF_FROZEN) { - if (isFrozen(view, account, currency, issuer) || isDeepFrozen(view, account, currency, issuer)) + if (isFrozen(view, account, currency, issuer) || + isDeepFrozen(view, account, currency, issuer)) { return nullptr; } @@ -339,7 +386,11 @@ getLineIfUsable( auto const sleAmm = view.read(keylet::amm((*sleIssuer)[sfAMMID])); if (!sleAmm || - isLPTokenFrozen(view, account, (*sleAmm)[sfAsset].get(), (*sleAmm)[sfAsset2].get())) + isLPTokenFrozen( + view, + account, + (*sleAmm)[sfAsset].get(), + (*sleAmm)[sfAsset2].get())) { return nullptr; } @@ -411,7 +462,8 @@ accountHolds( return STAmount{Issue{currency, issuer}, STAmount::cMaxValue, STAmount::cMaxOffset}; // IOU: Return balance on trust line modulo freeze - SLE::const_pointer const sle = getLineIfUsable(view, account, currency, issuer, zeroIfFrozen, j); + SLE::const_pointer const sle = + getLineIfUsable(view, account, currency, issuer, zeroIfFrozen, j); return getTrustLineBalance(view, sle, account, currency, issuer, returnSpendable, j); } @@ -425,7 +477,8 @@ accountHolds( beast::Journal j, SpendableHandling includeFullBalance) { - return accountHolds(view, account, issue.currency, issue.account, zeroIfFrozen, j, includeFullBalance); + return accountHolds( + view, account, issue.currency, issue.account, zeroIfFrozen, j, includeFullBalance); } STAmount @@ -451,7 +504,9 @@ accountHolds( return STAmount{mptIssue}; } return STAmount{ - mptIssue, issuance->at(~sfMaximumAmount).value_or(maxMPTokenAmount) - issuance->at(sfOutstandingAmount)}; + mptIssue, + issuance->at(~sfMaximumAmount).value_or(maxMPTokenAmount) - + issuance->at(sfOutstandingAmount)}; } STAmount amount; @@ -468,9 +523,11 @@ accountHolds( // Only if auth check is needed, as it needs to do an additional read // operation. Note featureSingleAssetVault will affect error codes. - if (zeroIfUnauthorized == ahZERO_IF_UNAUTHORIZED && view.rules().enabled(featureSingleAssetVault)) + if (zeroIfUnauthorized == ahZERO_IF_UNAUTHORIZED && + view.rules().enabled(featureSingleAssetVault)) { - if (auto const err = requireAuth(view, mptIssue, account, AuthType::StrongAuth); !isTesSuccess(err)) + if (auto const err = requireAuth(view, mptIssue, account, AuthType::StrongAuth); + !isTesSuccess(err)) amount.clear(mptIssue); } else if (zeroIfUnauthorized == ahZERO_IF_UNAUTHORIZED) @@ -479,7 +536,8 @@ accountHolds( // if auth is enabled on the issuance and mpt is not authorized, // clear amount - if (sleIssuance && sleIssuance->isFlag(lsfMPTRequireAuth) && !sleMpt->isFlag(lsfMPTAuthorized)) + if (sleIssuance && sleIssuance->isFlag(lsfMPTRequireAuth) && + !sleMpt->isFlag(lsfMPTAuthorized)) amount.clear(mptIssue); } } @@ -505,7 +563,8 @@ accountHolds( } else if constexpr (std::is_same_v) { - return accountHolds(view, account, value, zeroIfFrozen, zeroIfUnauthorized, j, includeFullBalance); + return accountHolds( + view, account, value, zeroIfFrozen, zeroIfUnauthorized, j, includeFullBalance); } }, asset.value()); @@ -522,7 +581,8 @@ accountFunds( if (!saDefault.native() && saDefault.getIssuer() == id) return saDefault; - return accountHolds(view, id, saDefault.getCurrency(), saDefault.getIssuer(), freezeHandling, j); + return accountHolds( + view, id, saDefault.getCurrency(), saDefault.getIssuer(), freezeHandling, j); } // Prevent ownerCount from wrapping under error conditions. @@ -579,7 +639,8 @@ xrpLiquid(ReadView const& view, AccountID const& id, std::int32_t ownerCountAdj, confineOwnerCount(view.ownerCountHook(id, sle->getFieldU32(sfOwnerCount)), ownerCountAdj); // Pseudo-accounts have no reserve requirement - auto const reserve = isPseudoAccount(sle) ? XRPAmount{0} : view.fees().accountReserve(ownerCount); + auto const reserve = + isPseudoAccount(sle) ? XRPAmount{0} : view.fees().accountReserve(ownerCount); auto const fullBalance = sle->getFieldAmount(sfBalance); @@ -587,15 +648,20 @@ xrpLiquid(ReadView const& view, AccountID const& id, std::int32_t ownerCountAdj, STAmount const amount = (balance < reserve) ? STAmount{0} : balance - reserve; - JLOG(j.trace()) << "accountHolds:" << " account=" << to_string(id) << " amount=" << amount.getFullText() - << " fullBalance=" << fullBalance.getFullText() << " balance=" << balance.getFullText() - << " reserve=" << reserve << " ownerCount=" << ownerCount << " ownerCountAdj=" << ownerCountAdj; + JLOG(j.trace()) << "accountHolds:" << " account=" << to_string(id) + << " amount=" << amount.getFullText() + << " fullBalance=" << fullBalance.getFullText() + << " balance=" << balance.getFullText() << " reserve=" << reserve + << " ownerCount=" << ownerCount << " ownerCountAdj=" << ownerCountAdj; return amount.xrp(); } void -forEachItem(ReadView const& view, Keylet const& root, std::function const&)> const& f) +forEachItem( + ReadView const& view, + Keylet const& root, + std::function const&)> const& f) { XRPL_ASSERT(root.type == ltDIR_NODE, "xrpl::forEachItem : valid root type"); @@ -712,7 +778,8 @@ transferRate(ReadView const& view, MPTID const& issuanceID) // fee is 0-50,000 (0-50%), rate is 1,000,000,000-2,000,000,000 // For example, if transfer fee is 50% then 10,000 * 50,000 = 500,000 // which represents 50% of 1,000,000,000 - if (auto const sle = view.read(keylet::mptIssuance(issuanceID)); sle && sle->isFieldPresent(sfTransferFee)) + if (auto const sle = view.read(keylet::mptIssuance(issuanceID)); + sle && sle->isFieldPresent(sfTransferFee)) return Rate{1'000'000'000u + 10'000 * sle->getFieldU16(sfTransferFee)}; return parityRate; @@ -732,14 +799,19 @@ transferRate(ReadView const& view, STAmount const& amount) } bool -areCompatible(ReadView const& validLedger, ReadView const& testLedger, beast::Journal::Stream& s, char const* reason) +areCompatible( + ReadView const& validLedger, + ReadView const& testLedger, + beast::Journal::Stream& s, + char const* reason) { bool ret = true; if (validLedger.header().seq < testLedger.header().seq) { // valid -> ... -> test - auto hash = hashOfSeq(testLedger, validLedger.header().seq, beast::Journal{beast::Journal::getNullSink()}); + auto hash = hashOfSeq( + testLedger, validLedger.header().seq, beast::Journal{beast::Journal::getNullSink()}); if (hash && (*hash != validLedger.header().hash)) { JLOG(s) << reason << " incompatible with valid ledger"; @@ -752,7 +824,8 @@ areCompatible(ReadView const& validLedger, ReadView const& testLedger, beast::Jo else if (validLedger.header().seq > testLedger.header().seq) { // test -> ... -> valid - auto hash = hashOfSeq(validLedger, testLedger.header().seq, beast::Journal{beast::Journal::getNullSink()}); + auto hash = hashOfSeq( + validLedger, testLedger.header().seq, beast::Journal{beast::Journal::getNullSink()}); if (hash && (*hash != testLedger.header().hash)) { JLOG(s) << reason << " incompatible preceding ledger"; @@ -774,7 +847,8 @@ areCompatible(ReadView const& validLedger, ReadView const& testLedger, beast::Jo if (!ret) { - JLOG(s) << "Val: " << validLedger.header().seq << " " << to_string(validLedger.header().hash); + JLOG(s) << "Val: " << validLedger.header().seq << " " + << to_string(validLedger.header().hash); JLOG(s) << "New: " << testLedger.header().seq << " " << to_string(testLedger.header().hash); } @@ -795,7 +869,8 @@ areCompatible( if (testLedger.header().seq > validIndex) { // Ledger we are testing follows last valid ledger - auto hash = hashOfSeq(testLedger, validIndex, beast::Journal{beast::Journal::getNullSink()}); + auto hash = + hashOfSeq(testLedger, validIndex, beast::Journal{beast::Journal::getNullSink()}); if (hash && (*hash != validHash)) { JLOG(s) << reason << " incompatible following ledger"; @@ -900,12 +975,13 @@ hashOfSeq(ReadView const& ledger, LedgerIndex seq, beast::Journal journal) STVector256 vec = hashIndex->getFieldV256(sfHashes); if (vec.size() >= diff) return vec[vec.size() - diff]; - JLOG(journal.warn()) << "Ledger " << ledger.seq() << " missing hash for " << seq << " (" << vec.size() - << "," << diff << ")"; + JLOG(journal.warn()) << "Ledger " << ledger.seq() << " missing hash for " << seq << " (" + << vec.size() << "," << diff << ")"; } else { - JLOG(journal.warn()) << "Ledger " << ledger.seq() << ":" << ledger.header().hash << " missing normal list"; + JLOG(journal.warn()) << "Ledger " << ledger.seq() << ":" << ledger.header().hash + << " missing normal list"; } } @@ -938,7 +1014,11 @@ hashOfSeq(ReadView const& ledger, LedgerIndex seq, beast::Journal journal) //------------------------------------------------------------------------------ void -adjustOwnerCount(ApplyView& view, std::shared_ptr const& sle, std::int32_t amount, beast::Journal j) +adjustOwnerCount( + ApplyView& view, + std::shared_ptr const& sle, + std::int32_t amount, + beast::Journal j) { if (!sle) return; @@ -958,9 +1038,14 @@ describeOwnerDir(AccountID const& account) } TER -dirLink(ApplyView& view, AccountID const& owner, std::shared_ptr& object, SF_UINT64 const& node) +dirLink( + ApplyView& view, + AccountID const& owner, + std::shared_ptr& object, + SF_UINT64 const& node) { - auto const page = view.dirInsert(keylet::ownerDir(owner), object->key(), describeOwnerDir(owner)); + auto const page = + view.dirInsert(keylet::ownerDir(owner), object->key(), describeOwnerDir(owner)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE object->setFieldU64(node, *page); @@ -1017,16 +1102,20 @@ getPseudoAccountFields() } [[nodiscard]] bool -isPseudoAccount(std::shared_ptr sleAcct, std::set const& pseudoFieldFilter) +isPseudoAccount( + std::shared_ptr sleAcct, + std::set const& pseudoFieldFilter) { auto const& fields = getPseudoAccountFields(); // Intentionally use defensive coding here because it's cheap and makes the // semantics of true return value clean. return sleAcct && sleAcct->getType() == ltACCOUNT_ROOT && - std::count_if(fields.begin(), fields.end(), [&sleAcct, &pseudoFieldFilter](SField const* sf) -> bool { - return sleAcct->isFieldPresent(*sf) && (pseudoFieldFilter.empty() || pseudoFieldFilter.contains(sf)); - }) > 0; + std::count_if( + fields.begin(), fields.end(), [&sleAcct, &pseudoFieldFilter](SField const* sf) -> bool { + return sleAcct->isFieldPresent(*sf) && + (pseudoFieldFilter.empty() || pseudoFieldFilter.contains(sf)); + }) > 0; } Expected, TER> @@ -1036,7 +1125,9 @@ createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const auto const& fields = getPseudoAccountFields(); XRPL_ASSERT( std::count_if( - fields.begin(), fields.end(), [&ownerField](SField const* sf) -> bool { return *sf == ownerField; }) == 1, + fields.begin(), + fields.end(), + [&ownerField](SField const* sf) -> bool { return *sf == ownerField; }) == 1, "xrpl::createPseudoAccount : valid owner field"); auto const accountId = pseudoAccountAddress(view, pseudoOwnerKey); @@ -1101,7 +1192,8 @@ canAddHolding(ReadView const& view, MPTIssue const& mptIssue) canAddHolding(ReadView const& view, Asset const& asset) { return std::visit( - [&](TIss const& issue) -> TER { return canAddHolding(view, issue); }, asset.value()); + [&](TIss const& issue) -> TER { return canAddHolding(view, issue); }, + asset.value()); } [[nodiscard]] TER @@ -1135,7 +1227,11 @@ checkDestinationAndTag(SLE::const_ref toSle, bool hasDestinationTag) * even if `from` is the issuer. */ static TER -withdrawToDestExceedsLimit(ReadView const& view, AccountID const& from, AccountID const& to, STAmount const& amount) +withdrawToDestExceedsLimit( + ReadView const& view, + AccountID const& from, + AccountID const& to, + STAmount const& amount) { auto const& issuer = amount.getIssuer(); if (from == to || to == issuer || isXRP(issuer)) @@ -1232,7 +1328,12 @@ doWithdraw( // Sanity check if (accountHolds( - view, sourceAcct, amount.asset(), FreezeHandling::fhIGNORE_FREEZE, AuthHandling::ahIGNORE_AUTH, j) < amount) + view, + sourceAcct, + amount.asset(), + FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, + j) < amount) { // LCOV_EXCL_START JLOG(j.error()) << "LoanBrokerCoverWithdraw: negative balance of " @@ -1289,14 +1390,14 @@ addEmptyHolding( dstId, index.key, sleDst, - /*auth=*/false, - /*noRipple=*/true, - /*freeze=*/false, + /*bAuth=*/false, + /*bNoRipple=*/true, + /*bFreeze=*/false, /*deepFreeze*/ false, - /*balance=*/STAmount{Issue{currency, noAccount()}}, - /*limit=*/STAmount{Issue{currency, dstId}}, - /*qualityIn=*/0, - /*qualityOut=*/0, + /*saBalance=*/STAmount{Issue{currency, noAccount()}}, + /*saLimit=*/STAmount{Issue{currency, dstId}}, + /*uSrcQualityIn=*/0, + /*uSrcQualityOut=*/0, journal); } @@ -1351,7 +1452,8 @@ authorizeMPToken( if (!sleMpt || (*sleMpt)[sfMPTAmount] != 0) return tecINTERNAL; // LCOV_EXCL_LINE - if (!view.dirRemove(keylet::ownerDir(account), (*sleMpt)[sfOwnerNode], sleMpt->key(), false)) + if (!view.dirRemove( + keylet::ownerDir(account), (*sleMpt)[sfOwnerNode], sleMpt->key(), false)) return tecINTERNAL; // LCOV_EXCL_LINE adjustOwnerCount(view, sleAcct, -1, journal); @@ -1371,7 +1473,8 @@ authorizeMPToken( // items. This is similar to the reserve requirements of trust lines. std::uint32_t const uOwnerCount = sleAcct->getFieldU32(sfOwnerCount); XRPAmount const reserveCreate( - (uOwnerCount < 2) ? XRPAmount(beast::zero) : view.fees().accountReserve(uOwnerCount + 1)); + (uOwnerCount < 2) ? XRPAmount(beast::zero) + : view.fees().accountReserve(uOwnerCount + 1)); if (priorBalance < reserveCreate) return tecINSUFFICIENT_RESERVE; @@ -1456,8 +1559,8 @@ trustCreate( std::uint32_t uQualityOut, beast::Journal j) { - JLOG(j.trace()) << "trustCreate: " << to_string(uSrcAccountID) << ", " << to_string(uDstAccountID) << ", " - << saBalance.getFullText(); + JLOG(j.trace()) << "trustCreate: " << to_string(uSrcAccountID) << ", " + << to_string(uDstAccountID) << ", " << saBalance.getFullText(); auto const& uLowAccountID = !bSrcHigh ? uSrcAccountID : uDstAccountID; auto const& uHighAccountID = bSrcHigh ? uSrcAccountID : uDstAccountID; @@ -1473,14 +1576,14 @@ trustCreate( auto const sleRippleState = std::make_shared(ltRIPPLE_STATE, uIndex); view.insert(sleRippleState); - auto lowNode = - view.dirInsert(keylet::ownerDir(uLowAccountID), sleRippleState->key(), describeOwnerDir(uLowAccountID)); + auto lowNode = view.dirInsert( + keylet::ownerDir(uLowAccountID), sleRippleState->key(), describeOwnerDir(uLowAccountID)); if (!lowNode) return tecDIR_FULL; // LCOV_EXCL_LINE - auto highNode = - view.dirInsert(keylet::ownerDir(uHighAccountID), sleRippleState->key(), describeOwnerDir(uHighAccountID)); + auto highNode = view.dirInsert( + keylet::ownerDir(uHighAccountID), sleRippleState->key(), describeOwnerDir(uHighAccountID)); if (!highNode) return tecDIR_FULL; // LCOV_EXCL_LINE @@ -1551,7 +1654,11 @@ trustCreate( } [[nodiscard]] TER -removeEmptyHolding(ApplyView& view, AccountID const& accountID, Issue const& issue, beast::Journal journal) +removeEmptyHolding( + ApplyView& view, + AccountID const& accountID, + Issue const& issue, + beast::Journal journal) { if (issue.native()) { @@ -1605,11 +1712,16 @@ removeEmptyHolding(ApplyView& view, AccountID const& accountID, Issue const& iss line->clearFlag(lsfHighReserve); } - return trustDelete(view, line, line->at(sfLowLimit)->getIssuer(), line->at(sfHighLimit)->getIssuer(), journal); + return trustDelete( + view, line, line->at(sfLowLimit)->getIssuer(), line->at(sfHighLimit)->getIssuer(), journal); } [[nodiscard]] TER -removeEmptyHolding(ApplyView& view, AccountID const& accountID, MPTIssue const& mptIssue, beast::Journal journal) +removeEmptyHolding( + ApplyView& view, + AccountID const& accountID, + MPTIssue const& mptIssue, + beast::Journal journal) { // If the account is the issuer, then no token should exist. MPTs do not // have the legacy ability to create such a situation, but check anyway. If @@ -1744,8 +1856,11 @@ rippleCreditIOU( bool const bSenderHigh = uSenderID > uReceiverID; auto const index = keylet::line(uSenderID, uReceiverID, currency); - XRPL_ASSERT(!isXRP(uSenderID) && uSenderID != noAccount(), "xrpl::rippleCreditIOU : sender is not XRP"); - XRPL_ASSERT(!isXRP(uReceiverID) && uReceiverID != noAccount(), "xrpl::rippleCreditIOU : receiver is not XRP"); + XRPL_ASSERT( + !isXRP(uSenderID) && uSenderID != noAccount(), "xrpl::rippleCreditIOU : sender is not XRP"); + XRPL_ASSERT( + !isXRP(uReceiverID) && uReceiverID != noAccount(), + "xrpl::rippleCreditIOU : receiver is not XRP"); // If the line exists, modify it accordingly. if (auto const sleRippleState = view.peek(index)) @@ -1761,8 +1876,9 @@ rippleCreditIOU( saBalance -= saAmount; - JLOG(j.trace()) << "rippleCreditIOU: " << to_string(uSenderID) << " -> " << to_string(uReceiverID) - << " : before=" << saBefore.getFullText() << " amount=" << saAmount.getFullText() + JLOG(j.trace()) << "rippleCreditIOU: " << to_string(uSenderID) << " -> " + << to_string(uReceiverID) << " : before=" << saBefore.getFullText() + << " amount=" << saAmount.getFullText() << " after=" << saBalance.getFullText(); std::uint32_t const uFlags(sleRippleState->getFieldU32(sfFlags)); @@ -1777,7 +1893,8 @@ rippleCreditIOU( && (uFlags & (!bSenderHigh ? lsfLowReserve : lsfHighReserve)) // Sender reserve is set. && static_cast(uFlags & (!bSenderHigh ? lsfLowNoRipple : lsfHighNoRipple)) != - static_cast(view.read(keylet::account(uSenderID))->getFlags() & lsfDefaultRipple) && + static_cast( + view.read(keylet::account(uSenderID))->getFlags() & lsfDefaultRipple) && !(uFlags & (!bSenderHigh ? lsfLowFreeze : lsfHighFreeze)) && !sleRippleState->getFieldAmount(!bSenderHigh ? sfLowLimit : sfHighLimit) // Sender trust limit is 0. @@ -1790,7 +1907,8 @@ rippleCreditIOU( adjustOwnerCount(view, view.peek(keylet::account(uSenderID)), -1, j); // Clear reserve flag. - sleRippleState->setFieldU32(sfFlags, uFlags & (!bSenderHigh ? ~lsfLowReserve : ~lsfHighReserve)); + sleRippleState->setFieldU32( + sfFlags, uFlags & (!bSenderHigh ? ~lsfLowReserve : ~lsfHighReserve)); // Balance is zero, receiver reserve is clear. bDelete = !saBalance // Balance is zero. @@ -1808,7 +1926,11 @@ rippleCreditIOU( if (bDelete) { return trustDelete( - view, sleRippleState, bSenderHigh ? uReceiverID : uSenderID, !bSenderHigh ? uReceiverID : uSenderID, j); + view, + sleRippleState, + bSenderHigh ? uReceiverID : uSenderID, + !bSenderHigh ? uReceiverID : uSenderID, + j); } view.update(sleRippleState); @@ -1822,7 +1944,8 @@ rippleCreditIOU( JLOG(j.debug()) << "rippleCreditIOU: " "create line: " - << to_string(uSenderID) << " -> " << to_string(uReceiverID) << " : " << saAmount.getFullText(); + << to_string(uSenderID) << " -> " << to_string(uReceiverID) << " : " + << saAmount.getFullText(); auto const sleAccount = view.peek(keylet::account(uReceiverID)); if (!sleAccount) @@ -1863,7 +1986,9 @@ rippleSendIOU( { auto const& issuer = saAmount.getIssuer(); - XRPL_ASSERT(!isXRP(uSenderID) && !isXRP(uReceiverID), "xrpl::rippleSendIOU : neither sender nor receiver is XRP"); + XRPL_ASSERT( + !isXRP(uSenderID) && !isXRP(uReceiverID), + "xrpl::rippleSendIOU : neither sender nor receiver is XRP"); XRPL_ASSERT(uSenderID != uReceiverID, "xrpl::rippleSendIOU : sender is not receiver"); if (uSenderID == issuer || uReceiverID == issuer || issuer == noAccount()) @@ -1880,10 +2005,12 @@ rippleSendIOU( // Calculate the amount to transfer accounting // for any transfer fees if the fee is not waived: - saActual = (waiveFee == WaiveTransferFee::Yes) ? saAmount : multiply(saAmount, transferRate(view, issuer)); + saActual = (waiveFee == WaiveTransferFee::Yes) ? saAmount + : multiply(saAmount, transferRate(view, issuer)); - JLOG(j.debug()) << "rippleSendIOU> " << to_string(uSenderID) << " - > " << to_string(uReceiverID) - << " : deliver=" << saAmount.getFullText() << " cost=" << saActual.getFullText(); + JLOG(j.debug()) << "rippleSendIOU> " << to_string(uSenderID) << " - > " + << to_string(uReceiverID) << " : deliver=" << saAmount.getFullText() + << " cost=" << saActual.getFullText(); TER terResult = rippleCreditIOU(view, issuer, uReceiverID, saAmount, true, j); @@ -1944,13 +2071,15 @@ rippleSendMultiIOU( // Calculate the amount to transfer accounting // for any transfer fees if the fee is not waived: - STAmount actualSend = - (waiveFee == WaiveTransferFee::Yes) ? amount : multiply(amount, transferRate(view, issuer)); + STAmount actualSend = (waiveFee == WaiveTransferFee::Yes) + ? amount + : multiply(amount, transferRate(view, issuer)); actual += actualSend; takeFromSender += actualSend; - JLOG(j.debug()) << "rippleSendMultiIOU> " << to_string(senderID) << " - > " << to_string(receiverID) - << " : deliver=" << amount.getFullText() << " cost=" << actual.getFullText(); + JLOG(j.debug()) << "rippleSendMultiIOU> " << to_string(senderID) << " - > " + << to_string(receiverID) << " : deliver=" << amount.getFullText() + << " cost=" << actual.getFullText(); if (TER const terResult = rippleCreditIOU(view, issuer, receiverID, amount, true, j)) return terResult; @@ -2000,8 +2129,8 @@ accountSendIOU( { STAmount saActual; - JLOG(j.trace()) << "accountSendIOU: " << to_string(uSenderID) << " -> " << to_string(uReceiverID) << " : " - << saAmount.getFullText(); + JLOG(j.trace()) << "accountSendIOU: " << to_string(uSenderID) << " -> " + << to_string(uReceiverID) << " : " << saAmount.getFullText(); return rippleSendIOU(view, uSenderID, uReceiverID, saAmount, saActual, j, waiveFee); } @@ -2013,8 +2142,10 @@ accountSendIOU( */ TER terResult(tesSUCCESS); - SLE::pointer sender = uSenderID != beast::zero ? view.peek(keylet::account(uSenderID)) : SLE::pointer(); - SLE::pointer receiver = uReceiverID != beast::zero ? view.peek(keylet::account(uReceiverID)) : SLE::pointer(); + SLE::pointer sender = + uSenderID != beast::zero ? view.peek(keylet::account(uSenderID)) : SLE::pointer(); + SLE::pointer receiver = + uReceiverID != beast::zero ? view.peek(keylet::account(uReceiverID)) : SLE::pointer(); if (auto stream = j.trace()) { @@ -2027,8 +2158,9 @@ accountSendIOU( if (receiver) receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); - stream << "accountSendIOU> " << to_string(uSenderID) << " (" << sender_bal << ") -> " << to_string(uReceiverID) - << " (" << receiver_bal << ") : " << saAmount.getFullText(); + stream << "accountSendIOU> " << to_string(uSenderID) << " (" << sender_bal << ") -> " + << to_string(uReceiverID) << " (" << receiver_bal + << ") : " << saAmount.getFullText(); } if (sender) @@ -2073,8 +2205,9 @@ accountSendIOU( if (receiver) receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); - stream << "accountSendIOU< " << to_string(uSenderID) << " (" << sender_bal << ") -> " << to_string(uReceiverID) - << " (" << receiver_bal << ") : " << saAmount.getFullText(); + stream << "accountSendIOU< " << to_string(uSenderID) << " (" << sender_bal << ") -> " + << to_string(uReceiverID) << " (" << receiver_bal + << ") : " << saAmount.getFullText(); } return terResult; @@ -2089,12 +2222,14 @@ accountSendMultiIOU( beast::Journal j, WaiveTransferFee waiveFee) { - XRPL_ASSERT_PARTS(receivers.size() > 1, "xrpl::accountSendMultiIOU", "multiple recipients provided"); + XRPL_ASSERT_PARTS( + receivers.size() > 1, "xrpl::accountSendMultiIOU", "multiple recipients provided"); if (!issue.native()) { STAmount actual; - JLOG(j.trace()) << "accountSendMultiIOU: " << to_string(senderID) << " sending " << receivers.size() << " IOUs"; + JLOG(j.trace()) << "accountSendMultiIOU: " << to_string(senderID) << " sending " + << receivers.size() << " IOUs"; return rippleSendMultiIOU(view, senderID, issue, receivers, actual, j, waiveFee); } @@ -2105,7 +2240,8 @@ accountSendMultiIOU( * ensure that transfers are balanced. */ - SLE::pointer sender = senderID != beast::zero ? view.peek(keylet::account(senderID)) : SLE::pointer(); + SLE::pointer sender = + senderID != beast::zero ? view.peek(keylet::account(senderID)) : SLE::pointer(); if (auto stream = j.trace()) { @@ -2114,8 +2250,8 @@ accountSendMultiIOU( if (sender) sender_bal = sender->getFieldAmount(sfBalance).getFullText(); - stream << "accountSendMultiIOU> " << to_string(senderID) << " (" << sender_bal << ") -> " << receivers.size() - << " receivers."; + stream << "accountSendMultiIOU> " << to_string(senderID) << " (" << sender_bal << ") -> " + << receivers.size() << " receivers."; } // Failures return immediately. @@ -2136,7 +2272,8 @@ accountSendMultiIOU( if (!amount || (senderID == receiverID)) continue; - SLE::pointer receiver = receiverID != beast::zero ? view.peek(keylet::account(receiverID)) : SLE::pointer(); + SLE::pointer receiver = + receiverID != beast::zero ? view.peek(keylet::account(receiverID)) : SLE::pointer(); if (auto stream = j.trace()) { @@ -2145,8 +2282,9 @@ accountSendMultiIOU( if (receiver) receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); - stream << "accountSendMultiIOU> " << to_string(senderID) << " -> " << to_string(receiverID) << " (" - << receiver_bal << ") : " << amount.getFullText(); + stream << "accountSendMultiIOU> " << to_string(senderID) << " -> " + << to_string(receiverID) << " (" << receiver_bal + << ") : " << amount.getFullText(); } if (receiver) @@ -2169,8 +2307,9 @@ accountSendMultiIOU( if (receiver) receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); - stream << "accountSendMultiIOU< " << to_string(senderID) << " -> " << to_string(receiverID) << " (" - << receiver_bal << ") : " << amount.getFullText(); + stream << "accountSendMultiIOU< " << to_string(senderID) << " -> " + << to_string(receiverID) << " (" << receiver_bal + << ") : " << amount.getFullText(); } } @@ -2199,8 +2338,8 @@ accountSendMultiIOU( if (sender) sender_bal = sender->getFieldAmount(sfBalance).getFullText(); - stream << "accountSendMultiIOU< " << to_string(senderID) << " (" << sender_bal << ") -> " << receivers.size() - << " receivers."; + stream << "accountSendMultiIOU< " << to_string(senderID) << " (" << sender_bal << ") -> " + << receivers.size() << " receivers."; } return tesSUCCESS; } @@ -2294,7 +2433,8 @@ rippleSendMPT( { auto const sendAmount = saAmount.mpt().value(); auto const maximumAmount = sle->at(~sfMaximumAmount).value_or(maxMPTokenAmount); - if (sendAmount > maximumAmount || sle->getFieldU64(sfOutstandingAmount) > maximumAmount - sendAmount) + if (sendAmount > maximumAmount || + sle->getFieldU64(sfOutstandingAmount) > maximumAmount - sendAmount) return tecPATH_DRY; } @@ -2311,10 +2451,12 @@ rippleSendMPT( ? saAmount : multiply(saAmount, transferRate(view, saAmount.get().getMptID())); - JLOG(j.debug()) << "rippleSendMPT> " << to_string(uSenderID) << " - > " << to_string(uReceiverID) - << " : deliver=" << saAmount.getFullText() << " cost=" << saActual.getFullText(); + JLOG(j.debug()) << "rippleSendMPT> " << to_string(uSenderID) << " - > " + << to_string(uReceiverID) << " : deliver=" << saAmount.getFullText() + << " cost=" << saActual.getFullText(); - if (auto const terResult = rippleCreditMPT(view, issuer, uReceiverID, saAmount, j); terResult != tesSUCCESS) + if (auto const terResult = rippleCreditMPT(view, issuer, uReceiverID, saAmount, j); + terResult != tesSUCCESS) return terResult; return rippleCreditMPT(view, uSenderID, issuer, saActual, j); @@ -2370,7 +2512,8 @@ rippleSendMultiMPT( "sender == issuer, takeFromSender == zero"); auto const sendAmount = amount.mpt().value(); auto const maximumAmount = sle->at(~sfMaximumAmount).value_or(maxMPTokenAmount); - if (sendAmount > maximumAmount || sle->getFieldU64(sfOutstandingAmount) > maximumAmount - sendAmount) + if (sendAmount > maximumAmount || + sle->getFieldU64(sfOutstandingAmount) > maximumAmount - sendAmount) return tecPATH_DRY; } @@ -2391,8 +2534,9 @@ rippleSendMultiMPT( actual += actualSend; takeFromSender += actualSend; - JLOG(j.debug()) << "rippleSendMultiMPT> " << to_string(senderID) << " - > " << to_string(receiverID) - << " : deliver=" << amount.getFullText() << " cost=" << actualSend.getFullText(); + JLOG(j.debug()) << "rippleSendMultiMPT> " << to_string(senderID) << " - > " + << to_string(receiverID) << " : deliver=" << amount.getFullText() + << " cost=" << actualSend.getFullText(); if (auto const terResult = rippleCreditMPT(view, issuer, receiverID, amount, j)) return terResult; @@ -2415,7 +2559,9 @@ accountSendMPT( beast::Journal j, WaiveTransferFee waiveFee) { - XRPL_ASSERT(saAmount >= beast::zero && saAmount.holds(), "xrpl::accountSendMPT : minimum amount and MPT"); + XRPL_ASSERT( + saAmount >= beast::zero && saAmount.holds(), + "xrpl::accountSendMPT : minimum amount and MPT"); /* If we aren't sending anything or if the sender is the same as the * receiver then we don't need to do anything. @@ -2470,7 +2616,8 @@ accountSendMulti( beast::Journal j, WaiveTransferFee waiveFee) { - XRPL_ASSERT_PARTS(receivers.size() > 1, "xrpl::accountSendMulti", "multiple recipients provided"); + XRPL_ASSERT_PARTS( + receivers.size() > 1, "xrpl::accountSendMulti", "multiple recipients provided"); return std::visit( [&](TIss const& issue) { if constexpr (std::is_same_v) @@ -2532,9 +2679,16 @@ updateTrustLine( } TER -issueIOU(ApplyView& view, AccountID const& account, STAmount const& amount, Issue const& issue, beast::Journal j) +issueIOU( + ApplyView& view, + AccountID const& account, + STAmount const& amount, + Issue const& issue, + beast::Journal j) { - XRPL_ASSERT(!isXRP(account) && !isXRP(issue.account), "xrpl::issueIOU : neither account nor issuer is XRP"); + XRPL_ASSERT( + !isXRP(account) && !isXRP(issue.account), + "xrpl::issueIOU : neither account nor issuer is XRP"); // Consistency check XRPL_ASSERT(issue == amount.issue(), "xrpl::issueIOU : matching issue"); @@ -2559,8 +2713,8 @@ issueIOU(ApplyView& view, AccountID const& account, STAmount const& amount, Issu final_balance -= amount; - auto const must_delete = - updateTrustLine(view, state, bSenderHigh, issue.account, start_balance, final_balance, j); + auto const must_delete = updateTrustLine( + view, state, bSenderHigh, issue.account, start_balance, final_balance, j); view.creditHook(issue.account, account, amount, start_balance); @@ -2573,7 +2727,11 @@ issueIOU(ApplyView& view, AccountID const& account, STAmount const& amount, Issu state->setFieldAmount(sfBalance, final_balance); if (must_delete) return trustDelete( - view, state, bSenderHigh ? account : issue.account, bSenderHigh ? issue.account : account, j); + view, + state, + bSenderHigh ? account : issue.account, + bSenderHigh ? issue.account : account, + j); view.update(state); @@ -2613,9 +2771,16 @@ issueIOU(ApplyView& view, AccountID const& account, STAmount const& amount, Issu } TER -redeemIOU(ApplyView& view, AccountID const& account, STAmount const& amount, Issue const& issue, beast::Journal j) +redeemIOU( + ApplyView& view, + AccountID const& account, + STAmount const& amount, + Issue const& issue, + beast::Journal j) { - XRPL_ASSERT(!isXRP(account) && !isXRP(issue.account), "xrpl::redeemIOU : neither account nor issuer is XRP"); + XRPL_ASSERT( + !isXRP(account) && !isXRP(issue.account), + "xrpl::redeemIOU : neither account nor issuer is XRP"); // Consistency check XRPL_ASSERT(issue == amount.issue(), "xrpl::redeemIOU : matching issue"); @@ -2638,7 +2803,8 @@ redeemIOU(ApplyView& view, AccountID const& account, STAmount const& amount, Iss final_balance -= amount; - auto const must_delete = updateTrustLine(view, state, bSenderHigh, account, start_balance, final_balance, j); + auto const must_delete = + updateTrustLine(view, state, bSenderHigh, account, start_balance, final_balance, j); view.creditHook(account, issue.account, amount, start_balance); @@ -2653,7 +2819,11 @@ redeemIOU(ApplyView& view, AccountID const& account, STAmount const& amount, Iss if (must_delete) { return trustDelete( - view, state, bSenderHigh ? issue.account : account, bSenderHigh ? account : issue.account, j); + view, + state, + bSenderHigh ? issue.account : account, + bSenderHigh ? account : issue.account, + j); } view.update(state); @@ -2664,15 +2834,20 @@ redeemIOU(ApplyView& view, AccountID const& account, STAmount const& amount, Iss // balance. If it doesn't, then something is very wrong. Don't try // to continue. // LCOV_EXCL_START - JLOG(j.fatal()) << "redeemIOU: " << to_string(account) << " attempts to redeem " << amount.getFullText() - << " but no trust line exists!"; + JLOG(j.fatal()) << "redeemIOU: " << to_string(account) << " attempts to redeem " + << amount.getFullText() << " but no trust line exists!"; return tefINTERNAL; // LCOV_EXCL_STOP } TER -transferXRP(ApplyView& view, AccountID const& from, AccountID const& to, STAmount const& amount, beast::Journal j) +transferXRP( + ApplyView& view, + AccountID const& from, + AccountID const& to, + STAmount const& amount, + beast::Journal j) { XRPL_ASSERT(from != beast::zero, "xrpl::transferXRP : nonzero from account"); XRPL_ASSERT(to != beast::zero, "xrpl::transferXRP : nonzero to account"); @@ -2684,7 +2859,8 @@ transferXRP(ApplyView& view, AccountID const& from, AccountID const& to, STAmoun if (!sender || !receiver) return tefINTERNAL; // LCOV_EXCL_LINE - JLOG(j.trace()) << "transferXRP: " << to_string(from) << " -> " << to_string(to) << ") : " << amount.getFullText(); + JLOG(j.trace()) << "transferXRP: " << to_string(from) << " -> " << to_string(to) + << ") : " << amount.getFullText(); if (sender->getFieldAmount(sfBalance) < amount) { @@ -2723,8 +2899,9 @@ requireAuth(ReadView const& view, Issue const& issue, AccountID const& account, issuerAccount && (*issuerAccount)[sfFlags] & lsfRequireAuth) { if (trustLine) - return ((*trustLine)[sfFlags] & ((account > issue.account) ? lsfLowAuth : lsfHighAuth)) ? tesSUCCESS - : TER{tecNO_AUTH}; + return ((*trustLine)[sfFlags] & ((account > issue.account) ? lsfLowAuth : lsfHighAuth)) + ? tesSUCCESS + : TER{tecNO_AUTH}; return TER{tecNO_LINE}; } @@ -2732,7 +2909,12 @@ requireAuth(ReadView const& view, Issue const& issue, AccountID const& account, } TER -requireAuth(ReadView const& view, MPTIssue const& mptIssue, AccountID const& account, AuthType authType, int depth) +requireAuth( + ReadView const& view, + MPTIssue const& mptIssue, + AccountID const& account, + AuthType authType, + int depth) { auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); auto const sleIssuance = view.read(mptID); @@ -2793,7 +2975,8 @@ requireAuth(ReadView const& view, MPTIssue const& mptIssue, AccountID const& acc sleIssuance->getFieldU32(sfFlags) & lsfMPTRequireAuth, "xrpl::requireAuth : issuance requires authorization"); // ter = tefINTERNAL | tecOBJECT_NOT_FOUND | tecNO_AUTH | tecEXPIRED - if (auto const ter = credentials::validDomain(view, *maybeDomainID, account); isTesSuccess(ter)) + if (auto const ter = credentials::validDomain(view, *maybeDomainID, account); + isTesSuccess(ter)) return ter; // Note: sleToken might be null else if (!sleToken) return ter; @@ -2809,7 +2992,8 @@ requireAuth(ReadView const& view, MPTIssue const& mptIssue, AccountID const& acc } // mptoken must be authorized if issuance enabled requireAuth - if (sleIssuance->isFlag(lsfMPTRequireAuth) && (!sleToken || !sleToken->isFlag(lsfMPTAuthorized))) + if (sleIssuance->isFlag(lsfMPTRequireAuth) && + (!sleToken || !sleToken->isFlag(lsfMPTAuthorized))) return tecNO_AUTH; return tesSUCCESS; // Note: sleToken might be null @@ -2827,7 +3011,9 @@ enforceMPTokenAuthorization( if (!sleIssuance) return tefINTERNAL; // LCOV_EXCL_LINE - XRPL_ASSERT(sleIssuance->isFlag(lsfMPTRequireAuth), "xrpl::enforceMPTokenAuthorization : authorization required"); + XRPL_ASSERT( + sleIssuance->isFlag(lsfMPTRequireAuth), + "xrpl::enforceMPTokenAuthorization : authorization required"); if (account == sleIssuance->at(sfIssuer)) return tefINTERNAL; // LCOV_EXCL_LINE @@ -2872,7 +3058,8 @@ enforceMPTokenAuthorization( // We found an MPToken, but sfDomainID is not set, so this is a classic // MPToken which requires authorization by the token issuer. XRPL_ASSERT( - sleToken != nullptr && !maybeDomainID.has_value(), "xrpl::enforceMPTokenAuthorization : found MPToken"); + sleToken != nullptr && !maybeDomainID.has_value(), + "xrpl::enforceMPTokenAuthorization : found MPToken"); if (sleToken->isFlag(lsfMPTAuthorized)) return tesSUCCESS; @@ -2882,7 +3069,9 @@ enforceMPTokenAuthorization( { // Found an MPToken, authorized by the domain. Ignore authorization flag // lsfMPTAuthorized because it is meaningless. Return tesSUCCESS - XRPL_ASSERT(maybeDomainID.has_value(), "xrpl::enforceMPTokenAuthorization : found MPToken for domain"); + XRPL_ASSERT( + maybeDomainID.has_value(), + "xrpl::enforceMPTokenAuthorization : found MPToken for domain"); return tesSUCCESS; } else if (authorizedByDomain) @@ -2911,7 +3100,11 @@ enforceMPTokenAuthorization( } TER -canTransfer(ReadView const& view, MPTIssue const& mptIssue, AccountID const& from, AccountID const& to) +canTransfer( + ReadView const& view, + MPTIssue const& mptIssue, + AccountID const& from, + AccountID const& to) { auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); auto const sleIssuance = view.read(mptID); @@ -2972,7 +3165,8 @@ cleanupOnAccountDelete( uint256 dirEntry{beast::zero}; std::uint32_t deleted = 0; - if (view.exists(ownerDirKeylet) && dirFirst(view, ownerDirKeylet.key, sleDirNode, uDirEntry, dirEntry)) + if (view.exists(ownerDirKeylet) && + dirFirst(view, ownerDirKeylet.key, sleDirNode, uDirEntry, dirEntry)) { do { @@ -2991,7 +3185,8 @@ cleanupOnAccountDelete( // LCOV_EXCL_STOP } - LedgerEntryType const nodeType{safe_cast(sleItem->getFieldU16(sfLedgerEntryType))}; + LedgerEntryType const nodeType{ + safe_cast(sleItem->getFieldU16(sfLedgerEntryType))}; // Deleter handles the details of specific account-owned object // deletion @@ -3043,7 +3238,8 @@ deleteAMMTrustLine( return tecINTERNAL; // LCOV_EXCL_LINE auto const& [low, high] = std::minmax( - sleState->getFieldAmount(sfLowLimit).getIssuer(), sleState->getFieldAmount(sfHighLimit).getIssuer()); + sleState->getFieldAmount(sfLowLimit).getIssuer(), + sleState->getFieldAmount(sfHighLimit).getIssuer()); auto sleLow = view.peek(keylet::account(low)); auto sleHigh = view.peek(keylet::account(high)); if (!sleLow || !sleHigh) @@ -3110,14 +3306,18 @@ assetsToSharesDeposit( STAmount const& assets) { XRPL_ASSERT(!assets.negative(), "xrpl::assetsToSharesDeposit : non-negative assets"); - XRPL_ASSERT(assets.asset() == vault->at(sfAsset), "xrpl::assetsToSharesDeposit : assets and vault match"); + XRPL_ASSERT( + assets.asset() == vault->at(sfAsset), + "xrpl::assetsToSharesDeposit : assets and vault match"); if (assets.negative() || assets.asset() != vault->at(sfAsset)) return std::nullopt; // LCOV_EXCL_LINE Number const assetTotal = vault->at(sfAssetsTotal); STAmount shares{vault->at(sfShareMPTID)}; if (assetTotal == 0) - return STAmount{shares.asset(), Number(assets.mantissa(), assets.exponent() + vault->at(sfScale)).truncate()}; + return STAmount{ + shares.asset(), + Number(assets.mantissa(), assets.exponent() + vault->at(sfScale)).truncate()}; Number const shareTotal = issuance->at(sfOutstandingAmount); shares = ((shareTotal * assets) / assetTotal).truncate(); @@ -3131,14 +3331,17 @@ sharesToAssetsDeposit( STAmount const& shares) { XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsDeposit : non-negative shares"); - XRPL_ASSERT(shares.asset() == vault->at(sfShareMPTID), "xrpl::sharesToAssetsDeposit : shares and vault match"); + XRPL_ASSERT( + shares.asset() == vault->at(sfShareMPTID), + "xrpl::sharesToAssetsDeposit : shares and vault match"); if (shares.negative() || shares.asset() != vault->at(sfShareMPTID)) return std::nullopt; // LCOV_EXCL_LINE Number const assetTotal = vault->at(sfAssetsTotal); STAmount assets{vault->at(sfAsset)}; if (assetTotal == 0) - return STAmount{assets.asset(), shares.mantissa(), shares.exponent() - vault->at(sfScale), false}; + return STAmount{ + assets.asset(), shares.mantissa(), shares.exponent() - vault->at(sfScale), false}; Number const shareTotal = issuance->at(sfOutstandingAmount); assets = (assetTotal * shares) / shareTotal; @@ -3153,7 +3356,9 @@ assetsToSharesWithdraw( TruncateShares truncate) { XRPL_ASSERT(!assets.negative(), "xrpl::assetsToSharesDeposit : non-negative assets"); - XRPL_ASSERT(assets.asset() == vault->at(sfAsset), "xrpl::assetsToSharesWithdraw : assets and vault match"); + XRPL_ASSERT( + assets.asset() == vault->at(sfAsset), + "xrpl::assetsToSharesWithdraw : assets and vault match"); if (assets.negative() || assets.asset() != vault->at(sfAsset)) return std::nullopt; // LCOV_EXCL_LINE @@ -3177,7 +3382,9 @@ sharesToAssetsWithdraw( STAmount const& shares) { XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsDeposit : non-negative shares"); - XRPL_ASSERT(shares.asset() == vault->at(sfShareMPTID), "xrpl::sharesToAssetsWithdraw : shares and vault match"); + XRPL_ASSERT( + shares.asset() == vault->at(sfShareMPTID), + "xrpl::sharesToAssetsWithdraw : shares and vault match"); if (shares.negative() || shares.asset() != vault->at(sfShareMPTID)) return std::nullopt; // LCOV_EXCL_LINE @@ -3192,14 +3399,19 @@ sharesToAssetsWithdraw( } TER -rippleLockEscrowMPT(ApplyView& view, AccountID const& sender, STAmount const& amount, beast::Journal j) +rippleLockEscrowMPT( + ApplyView& view, + AccountID const& sender, + STAmount const& amount, + beast::Journal j) { auto const mptIssue = amount.get(); auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); auto sleIssuance = view.peek(mptID); if (!sleIssuance) { // LCOV_EXCL_START - JLOG(j.error()) << "rippleLockEscrowMPT: MPT issuance not found for " << mptIssue.getMptID(); + JLOG(j.error()) << "rippleLockEscrowMPT: MPT issuance not found for " + << mptIssue.getMptID(); return tecOBJECT_NOT_FOUND; } // LCOV_EXCL_STOP @@ -3226,8 +3438,8 @@ rippleLockEscrowMPT(ApplyView& view, AccountID const& sender, STAmount const& am // Underflow check for subtraction if (!canSubtract(STAmount(mptIssue, amt), STAmount(mptIssue, pay))) { // LCOV_EXCL_START - JLOG(j.error()) << "rippleLockEscrowMPT: insufficient MPTAmount for " << to_string(sender) << ": " << amt - << " < " << pay; + JLOG(j.error()) << "rippleLockEscrowMPT: insufficient MPTAmount for " + << to_string(sender) << ": " << amt << " < " << pay; return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3238,8 +3450,8 @@ rippleLockEscrowMPT(ApplyView& view, AccountID const& sender, STAmount const& am if (!canAdd(STAmount(mptIssue, locked), STAmount(mptIssue, pay))) { // LCOV_EXCL_START - JLOG(j.error()) << "rippleLockEscrowMPT: overflow on locked amount for " << to_string(sender) << ": " - << locked << " + " << pay; + JLOG(j.error()) << "rippleLockEscrowMPT: overflow on locked amount for " + << to_string(sender) << ": " << locked << " + " << pay; return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3286,7 +3498,8 @@ rippleUnlockEscrowMPT( beast::Journal j) { if (!view.rules().enabled(fixTokenEscrowV1)) - XRPL_ASSERT(netAmount == grossAmount, "xrpl::rippleUnlockEscrowMPT : netAmount == grossAmount"); + XRPL_ASSERT( + netAmount == grossAmount, "xrpl::rippleUnlockEscrowMPT : netAmount == grossAmount"); auto const& issuer = netAmount.getIssuer(); auto const& mptIssue = netAmount.get(); @@ -3294,7 +3507,8 @@ rippleUnlockEscrowMPT( auto sleIssuance = view.peek(mptID); if (!sleIssuance) { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: MPT issuance not found for " << mptIssue.getMptID(); + JLOG(j.error()) << "rippleUnlockEscrowMPT: MPT issuance not found for " + << mptIssue.getMptID(); return tecOBJECT_NOT_FOUND; } // LCOV_EXCL_STOP @@ -3302,7 +3516,8 @@ rippleUnlockEscrowMPT( { if (!sleIssuance->isFieldPresent(sfLockedAmount)) { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: no locked amount in issuance for " << mptIssue.getMptID(); + JLOG(j.error()) << "rippleUnlockEscrowMPT: no locked amount in issuance for " + << mptIssue.getMptID(); return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3312,8 +3527,8 @@ rippleUnlockEscrowMPT( // Underflow check for subtraction if (!canSubtract(STAmount(mptIssue, locked), STAmount(mptIssue, redeem))) { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient locked amount for " << mptIssue.getMptID() << ": " - << locked << " < " << redeem; + JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient locked amount for " + << mptIssue.getMptID() << ": " << locked << " < " << redeem; return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3342,8 +3557,8 @@ rippleUnlockEscrowMPT( // Overflow check for addition if (!canAdd(STAmount(mptIssue, current), STAmount(mptIssue, delta))) { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: overflow on MPTAmount for " << to_string(receiver) << ": " - << current << " + " << delta; + JLOG(j.error()) << "rippleUnlockEscrowMPT: overflow on MPTAmount for " + << to_string(receiver) << ": " << current << " + " << delta; return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3359,8 +3574,8 @@ rippleUnlockEscrowMPT( // Underflow check for subtraction if (!canSubtract(STAmount(mptIssue, outstanding), STAmount(mptIssue, redeem))) { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient outstanding amount for " << mptIssue.getMptID() - << ": " << outstanding << " < " << redeem; + JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient outstanding amount for " + << mptIssue.getMptID() << ": " << outstanding << " < " << redeem; return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3387,7 +3602,8 @@ rippleUnlockEscrowMPT( if (!sle->isFieldPresent(sfLockedAmount)) { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: no locked amount in MPToken for " << to_string(sender); + JLOG(j.error()) << "rippleUnlockEscrowMPT: no locked amount in MPToken for " + << to_string(sender); return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3397,8 +3613,8 @@ rippleUnlockEscrowMPT( // Underflow check for subtraction if (!canSubtract(STAmount(mptIssue, locked), STAmount(mptIssue, delta))) { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient locked amount for " << to_string(sender) << ": " - << locked << " < " << delta; + JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient locked amount for " + << to_string(sender) << ": " << locked << " < " << delta; return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3421,8 +3637,8 @@ rippleUnlockEscrowMPT( // Underflow check for subtraction if (!canSubtract(STAmount(mptIssue, outstanding), STAmount(mptIssue, diff))) { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient outstanding amount for " << mptIssue.getMptID() - << ": " << outstanding << " < " << diff; + JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient outstanding amount for " + << mptIssue.getMptID() << ": " << outstanding << " < " << diff; return tecINTERNAL; } // LCOV_EXCL_STOP diff --git a/src/libxrpl/net/HTTPClient.cpp b/src/libxrpl/net/HTTPClient.cpp index e5a1196cb0..91a64a1ca9 100644 --- a/src/libxrpl/net/HTTPClient.cpp +++ b/src/libxrpl/net/HTTPClient.cpp @@ -74,8 +74,10 @@ public: std::deque deqSites, std::function build, std::chrono::seconds timeout, - std::function - complete) + std::function complete) { mSSL = bSSL; mDeqSites = deqSites; @@ -93,8 +95,10 @@ public: std::deque deqSites, std::string const& strPath, std::chrono::seconds timeout, - std::function - complete) + std::function complete) { mComplete = complete; mTimeout = timeout; @@ -103,7 +107,11 @@ public: bSSL, deqSites, std::bind( - &HTTPClientImp::makeGet, shared_from_this(), strPath, std::placeholders::_1, std::placeholders::_2), + &HTTPClientImp::makeGet, + shared_from_this(), + strPath, + std::placeholders::_1, + std::placeholders::_2), timeout, complete); } @@ -116,7 +124,9 @@ public: JLOG(j_.trace()) << "Fetch: " << mDeqSites[0]; auto query = std::make_shared( - mDeqSites[0], std::to_string(mPort), boost::asio::ip::resolver_query_base::numeric_service); + mDeqSites[0], + std::to_string(mPort), + boost::asio::ip::resolver_query_base::numeric_service); mQuery = query; try @@ -128,7 +138,9 @@ public: mShutdown = e.code(); JLOG(j_.trace()) << "expires_after: " << mShutdown.message(); - mDeadline.async_wait(std::bind(&HTTPClientImp::handleDeadline, shared_from_this(), std::placeholders::_1)); + mDeadline.async_wait( + std::bind( + &HTTPClientImp::handleDeadline, shared_from_this(), std::placeholders::_1)); } if (!mShutdown) @@ -140,7 +152,10 @@ public: mQuery->port, mQuery->flags, std::bind( - &HTTPClientImp::handleResolve, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); + &HTTPClientImp::handleResolve, + shared_from_this(), + std::placeholders::_1, + std::placeholders::_2)); } if (mShutdown) @@ -170,14 +185,16 @@ public: // Mark us as shutting down. // XXX Use our own error code. - mShutdown = boost::system::error_code{boost::system::errc::bad_address, boost::system::system_category()}; + mShutdown = boost::system::error_code{ + boost::system::errc::bad_address, boost::system::system_category()}; // Cancel any resolving. mResolver.cancel(); // Stop the transaction. mSocket.async_shutdown( - std::bind(&HTTPClientImp::handleShutdown, shared_from_this(), std::placeholders::_1)); + std::bind( + &HTTPClientImp::handleShutdown, shared_from_this(), std::placeholders::_1)); } } @@ -191,11 +208,15 @@ public: } void - handleResolve(boost::system::error_code const& ecResult, boost::asio::ip::tcp::resolver::results_type result) + handleResolve( + boost::system::error_code const& ecResult, + boost::asio::ip::tcp::resolver::results_type result) { if (!mShutdown) { - mShutdown = ecResult ? ecResult : httpClientSSLContext->preConnectVerify(mSocket.SSLSocket(), mDeqSites[0]); + mShutdown = ecResult + ? ecResult + : httpClientSSLContext->preConnectVerify(mSocket.SSLSocket(), mDeqSites[0]); } if (mShutdown) @@ -211,7 +232,8 @@ public: boost::asio::async_connect( mSocket.lowest_layer(), result, - std::bind(&HTTPClientImp::handleConnect, shared_from_this(), std::placeholders::_1)); + std::bind( + &HTTPClientImp::handleConnect, shared_from_this(), std::placeholders::_1)); } } @@ -234,7 +256,8 @@ public: if (mShutdown) { - JLOG(j_.trace()) << "postConnectVerify: " << mDeqSites[0] << ": " << mShutdown.message(); + JLOG(j_.trace()) << "postConnectVerify: " << mDeqSites[0] << ": " + << mShutdown.message(); } } @@ -246,7 +269,8 @@ public: { mSocket.async_handshake( AutoSocket::ssl_socket::client, - std::bind(&HTTPClientImp::handleRequest, shared_from_this(), std::placeholders::_1)); + std::bind( + &HTTPClientImp::handleRequest, shared_from_this(), std::placeholders::_1)); } else { @@ -275,7 +299,10 @@ public: mSocket.async_write( mRequest, std::bind( - &HTTPClientImp::handleWrite, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); + &HTTPClientImp::handleWrite, + shared_from_this(), + std::placeholders::_1, + std::placeholders::_2)); } } @@ -299,18 +326,23 @@ public: mHeader, "\r\n\r\n", std::bind( - &HTTPClientImp::handleHeader, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); + &HTTPClientImp::handleHeader, + shared_from_this(), + std::placeholders::_1, + std::placeholders::_2)); } } void handleHeader(boost::system::error_code const& ecResult, std::size_t bytes_transferred) { - std::string strHeader{{std::istreambuf_iterator(&mHeader)}, std::istreambuf_iterator()}; + std::string strHeader{ + {std::istreambuf_iterator(&mHeader)}, std::istreambuf_iterator()}; JLOG(j_.trace()) << "Header: \"" << strHeader << "\""; static boost::regex reStatus{"\\`HTTP/1\\S+ (\\d{3}) .*\\'"}; // HTTP/1.1 200 OK - static boost::regex reSize{"\\`.*\\r\\nContent-Length:\\s+([0-9]+).*\\'", boost::regex::icase}; + static boost::regex reSize{ + "\\`.*\\r\\nContent-Length:\\s+([0-9]+).*\\'", boost::regex::icase}; static boost::regex reBody{"\\`.*\\r\\n\\r\\n(.*)\\'"}; boost::smatch smMatch; @@ -320,7 +352,8 @@ public: // XXX Use our own error code. JLOG(j_.trace()) << "No status code"; invokeComplete( - boost::system::error_code{boost::system::errc::bad_address, boost::system::system_category()}); + boost::system::error_code{ + boost::system::errc::bad_address, boost::system::system_category()}); return; } @@ -339,7 +372,8 @@ public: { JLOG(j_.trace()) << "Response field too large"; invokeComplete( - boost::system::error_code{boost::system::errc::value_too_large, boost::system::system_category()}); + boost::system::error_code{ + boost::system::errc::value_too_large, boost::system::system_category()}); return; } @@ -359,7 +393,10 @@ public: mResponse.prepare(responseSize - mBody.size()), boost::asio::transfer_all(), std::bind( - &HTTPClientImp::handleData, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); + &HTTPClientImp::handleData, + shared_from_this(), + std::placeholders::_1, + std::placeholders::_2)); } } @@ -384,7 +421,8 @@ public: else { mResponse.commit(bytes_transferred); - std::string strBody{{std::istreambuf_iterator(&mResponse)}, std::istreambuf_iterator()}; + std::string strBody{ + {std::istreambuf_iterator(&mResponse)}, std::istreambuf_iterator()}; invokeComplete(ecResult, mStatus, mBody + strBody); } } @@ -392,7 +430,10 @@ public: // Call cancel the deadline timer and invoke the completion routine. void - invokeComplete(boost::system::error_code const& ecResult, int iStatus = 0, std::string const& strData = "") + invokeComplete( + boost::system::error_code const& ecResult, + int iStatus = 0, + std::string const& strData = "") { boost::system::error_code ecCancel; try @@ -451,7 +492,9 @@ private: std::size_t const maxResponseSize_; int mStatus; std::function mBuild; - std::function mComplete; + std::function< + bool(boost::system::error_code const& ecResult, int iStatus, std::string const& strData)> + mComplete; boost::asio::basic_waitable_timer mDeadline; @@ -474,7 +517,9 @@ HTTPClient::get( std::string const& strPath, std::size_t responseMax, std::chrono::seconds timeout, - std::function complete, + std::function< + bool(boost::system::error_code const& ecResult, int iStatus, std::string const& strData)> + complete, beast::Journal& j) { auto client = std::make_shared(io_context, port, responseMax, j); @@ -490,7 +535,9 @@ HTTPClient::get( std::string const& strPath, std::size_t responseMax, std::chrono::seconds timeout, - std::function complete, + std::function< + bool(boost::system::error_code const& ecResult, int iStatus, std::string const& strData)> + complete, beast::Journal& j) { std::deque deqSites(1, strSite); @@ -508,7 +555,9 @@ HTTPClient::request( std::function setRequest, std::size_t responseMax, std::chrono::seconds timeout, - std::function complete, + std::function< + bool(boost::system::error_code const& ecResult, int iStatus, std::string const& strData)> + complete, beast::Journal& j) { std::deque deqSites(1, strSite); diff --git a/src/libxrpl/net/RegisterSSLCerts.cpp b/src/libxrpl/net/RegisterSSLCerts.cpp index a15472969e..87c2eb81b7 100644 --- a/src/libxrpl/net/RegisterSSLCerts.cpp +++ b/src/libxrpl/net/RegisterSSLCerts.cpp @@ -23,7 +23,8 @@ registerSSLCerts(boost::asio::ssl::context& ctx, boost::system::error_code& ec, if (h != nullptr) CertCloseStore(h, 0); }; - std::unique_ptr hStore{CertOpenSystemStore(0, "ROOT"), certStoreDelete}; + std::unique_ptr hStore{ + CertOpenSystemStore(0, "ROOT"), certStoreDelete}; if (!hStore) { @@ -33,11 +34,13 @@ registerSSLCerts(boost::asio::ssl::context& ctx, boost::system::error_code& ec, ERR_clear_error(); - std::unique_ptr store{X509_STORE_new(), X509_STORE_free}; + std::unique_ptr store{ + X509_STORE_new(), X509_STORE_free}; if (!store) { - ec = boost::system::error_code(static_cast(::ERR_get_error()), boost::asio::error::get_ssl_category()); + ec = boost::system::error_code( + static_cast(::ERR_get_error()), boost::asio::error::get_ssl_category()); return; } diff --git a/src/libxrpl/nodestore/BatchWriter.cpp b/src/libxrpl/nodestore/BatchWriter.cpp index 73213fe3ba..ed7753f68e 100644 --- a/src/libxrpl/nodestore/BatchWriter.cpp +++ b/src/libxrpl/nodestore/BatchWriter.cpp @@ -61,7 +61,8 @@ BatchWriter::writeBatch() std::lock_guard sl(mWriteMutex); mWriteSet.swap(set); - XRPL_ASSERT(mWriteSet.empty(), "xrpl::NodeStore::BatchWriter::writeBatch : writes not set"); + XRPL_ASSERT( + mWriteSet.empty(), "xrpl::NodeStore::BatchWriter::writeBatch : writes not set"); mWriteLoad = set.size(); if (set.empty()) @@ -80,8 +81,8 @@ BatchWriter::writeBatch() m_callback.writeBatch(set); - report.elapsed = - std::chrono::duration_cast(std::chrono::steady_clock::now() - before); + report.elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - before); m_scheduler.onBatchWrite(report); } diff --git a/src/libxrpl/nodestore/Database.cpp b/src/libxrpl/nodestore/Database.cpp index f393bf27c9..4e0d5be05d 100644 --- a/src/libxrpl/nodestore/Database.cpp +++ b/src/libxrpl/nodestore/Database.cpp @@ -10,7 +10,11 @@ namespace xrpl { namespace NodeStore { -Database::Database(Scheduler& scheduler, int readThreads, Section const& config, beast::Journal journal) +Database::Database( + Scheduler& scheduler, + int readThreads, + Section const& config, + beast::Journal journal) : j_(journal) , scheduler_(scheduler) , earliestLedgerSeq_(get(config, "earliest_seq", XRP_LEDGER_EARLIEST_SEQ)) @@ -136,13 +140,16 @@ Database::stop() while (readThreads_.load() != 0) { - XRPL_ASSERT(steady_clock::now() - start < 30s, "xrpl::NodeStore::Database::stop : maximum stop duration"); + XRPL_ASSERT( + steady_clock::now() - start < 30s, + "xrpl::NodeStore::Database::stop : maximum stop duration"); std::this_thread::yield(); } - JLOG(j_.debug()) << "Stop request completed in " - << duration_cast(steady_clock::now() - start).count() - << " milliseconds"; + JLOG(j_.debug()) + << "Stop request completed in " + << duration_cast(steady_clock::now() - start).count() + << " milliseconds"; } void @@ -199,7 +206,11 @@ Database::importInternal(Backend& dstBackend, Database& srcDB) // Perform a fetch and report the time it took std::shared_ptr -Database::fetchNodeObject(uint256 const& hash, std::uint32_t ledgerSeq, FetchType fetchType, bool duplicate) +Database::fetchNodeObject( + uint256 const& hash, + std::uint32_t ledgerSeq, + FetchType fetchType, + bool duplicate) { FetchReport fetchReport(fetchType); diff --git a/src/libxrpl/nodestore/DatabaseNodeImp.cpp b/src/libxrpl/nodestore/DatabaseNodeImp.cpp index 11152a2027..5596cb4853 100644 --- a/src/libxrpl/nodestore/DatabaseNodeImp.cpp +++ b/src/libxrpl/nodestore/DatabaseNodeImp.cpp @@ -22,7 +22,11 @@ DatabaseNodeImp::asyncFetch( } std::shared_ptr -DatabaseNodeImp::fetchNodeObject(uint256 const& hash, std::uint32_t, FetchReport& fetchReport, bool duplicate) +DatabaseNodeImp::fetchNodeObject( + uint256 const& hash, + std::uint32_t, + FetchReport& fetchReport, + bool duplicate) { std::shared_ptr nodeObject = nullptr; Status status; @@ -33,7 +37,8 @@ DatabaseNodeImp::fetchNodeObject(uint256 const& hash, std::uint32_t, FetchReport } catch (std::exception const& e) { - JLOG(j_.fatal()) << "fetchNodeObject " << hash << ": Exception fetching from backend: " << e.what(); + JLOG(j_.fatal()) << "fetchNodeObject " << hash + << ": Exception fetching from backend: " << e.what(); Rethrow(); } @@ -46,7 +51,8 @@ DatabaseNodeImp::fetchNodeObject(uint256 const& hash, std::uint32_t, FetchReport JLOG(j_.fatal()) << "fetchNodeObject " << hash << ": nodestore data is corrupted"; break; default: - JLOG(j_.warn()) << "fetchNodeObject " << hash << ": backend returns unknown result " << status; + JLOG(j_.warn()) << "fetchNodeObject " << hash << ": backend returns unknown result " + << status; break; } @@ -87,7 +93,8 @@ DatabaseNodeImp::fetchBatch(std::vector const& hashes) } } - auto fetchDurationUs = std::chrono::duration_cast(steady_clock::now() - before).count(); + auto fetchDurationUs = + std::chrono::duration_cast(steady_clock::now() - before).count(); updateFetchMetrics(hashes.size(), 0, fetchDurationUs); return results; } diff --git a/src/libxrpl/nodestore/DatabaseRotatingImp.cpp b/src/libxrpl/nodestore/DatabaseRotatingImp.cpp index f25b9d068e..26d8c30931 100644 --- a/src/libxrpl/nodestore/DatabaseRotatingImp.cpp +++ b/src/libxrpl/nodestore/DatabaseRotatingImp.cpp @@ -94,7 +94,11 @@ DatabaseRotatingImp::store(NodeObjectType type, Blob&& data, uint256 const& hash } std::shared_ptr -DatabaseRotatingImp::fetchNodeObject(uint256 const& hash, std::uint32_t, FetchReport& fetchReport, bool duplicate) +DatabaseRotatingImp::fetchNodeObject( + uint256 const& hash, + std::uint32_t, + FetchReport& fetchReport, + bool duplicate) { auto fetch = [&](std::shared_ptr const& backend) { Status status; diff --git a/src/libxrpl/nodestore/ManagerImp.cpp b/src/libxrpl/nodestore/ManagerImp.cpp index 9d78097aae..b749a329ff 100644 --- a/src/libxrpl/nodestore/ManagerImp.cpp +++ b/src/libxrpl/nodestore/ManagerImp.cpp @@ -44,7 +44,11 @@ ManagerImp::ManagerImp() } std::unique_ptr -ManagerImp::make_Backend(Section const& parameters, std::size_t burstSize, Scheduler& scheduler, beast::Journal journal) +ManagerImp::make_Backend( + Section const& parameters, + std::size_t burstSize, + Scheduler& scheduler, + beast::Journal journal) { std::string const type{get(parameters, "type")}; if (type.empty()) @@ -69,7 +73,8 @@ ManagerImp::make_Database( { auto backend{make_Backend(config, burstSize, scheduler, journal)}; backend->open(); - return std::make_unique(scheduler, readThreads, std::move(backend), config, journal); + return std::make_unique( + scheduler, readThreads, std::move(backend), config, journal); } void @@ -83,8 +88,8 @@ void ManagerImp::erase(Factory& factory) { std::lock_guard _(mutex_); - auto const iter = - std::find_if(list_.begin(), list_.end(), [&factory](Factory* other) { return other == &factory; }); + auto const iter = std::find_if( + list_.begin(), list_.end(), [&factory](Factory* other) { return other == &factory; }); XRPL_ASSERT(iter != list_.end(), "xrpl::NodeStore::ManagerImp::erase : valid input"); list_.erase(iter); } @@ -93,8 +98,9 @@ Factory* ManagerImp::find(std::string const& name) { std::lock_guard _(mutex_); - auto const iter = std::find_if( - list_.begin(), list_.end(), [&name](Factory* other) { return boost::iequals(name, other->getName()); }); + auto const iter = std::find_if(list_.begin(), list_.end(), [&name](Factory* other) { + return boost::iequals(name, other->getName()); + }); if (iter == list_.end()) return nullptr; return *iter; diff --git a/src/libxrpl/nodestore/backend/MemoryFactory.cpp b/src/libxrpl/nodestore/backend/MemoryFactory.cpp index 3cb8fb7f5e..8ac23a0bb6 100644 --- a/src/libxrpl/nodestore/backend/MemoryFactory.cpp +++ b/src/libxrpl/nodestore/backend/MemoryFactory.cpp @@ -46,7 +46,8 @@ public: open(std::string const& path) { std::lock_guard _(mutex_); - auto const result = map_.emplace(std::piecewise_construct, std::make_tuple(path), std::make_tuple()); + auto const result = + map_.emplace(std::piecewise_construct, std::make_tuple(path), std::make_tuple()); MemoryDB& db = result.first->second; if (db.open) Throw("already open"); diff --git a/src/libxrpl/nodestore/backend/NuDBFactory.cpp b/src/libxrpl/nodestore/backend/NuDBFactory.cpp index eb3ccb3181..e8efa464af 100644 --- a/src/libxrpl/nodestore/backend/NuDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/NuDBFactory.cpp @@ -124,7 +124,8 @@ public: if (createIfMissing) { create_directories(folder); - nudb::create(dp, kp, lp, appType, uid, salt, keyBytes_, blockSize_, 0.50, ec); + nudb::create( + dp, kp, lp, appType, uid, salt, keyBytes_, blockSize_, 0.50, ec); if (ec == nudb::errc::file_exists) ec = {}; if (ec) @@ -170,7 +171,8 @@ public: boost::filesystem::remove_all(name_, ec); if (ec) { - JLOG(j_.fatal()) << "Filesystem remove_all of " << name_ << " failed with: " << ec.message(); + JLOG(j_.fatal()) + << "Filesystem remove_all of " << name_ << " failed with: " << ec.message(); } } } @@ -241,8 +243,8 @@ public: report.writeCount = 1; auto const start = std::chrono::steady_clock::now(); do_insert(no); - report.elapsed = - std::chrono::duration_cast(std::chrono::steady_clock::now() - start); + report.elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - start); scheduler_.onBatchWrite(report); } @@ -254,8 +256,8 @@ public: auto const start = std::chrono::steady_clock::now(); for (auto const& e : batch) do_insert(e); - report.elapsed = - std::chrono::duration_cast(std::chrono::steady_clock::now() - start); + report.elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - start); scheduler_.onBatchWrite(report); } @@ -277,7 +279,11 @@ public: Throw(ec); nudb::visit( dp, - [&](void const* key, std::size_t key_bytes, void const* data, std::size_t size, nudb::error_code&) { + [&](void const* key, + std::size_t key_bytes, + void const* data, + std::size_t size, + nudb::error_code&) { nudb::detail::buffer bf; auto const result = nodeobject_decompress(data, size, bf); DecodedBlob decoded(key, result.first, result.second); @@ -356,10 +362,12 @@ private: std::size_t const parsedBlockSize = beast::lexicalCastThrow(blockSizeStr); // Validate: must be power of 2 between 4K and 32K - if (parsedBlockSize < 4096 || parsedBlockSize > 32768 || (parsedBlockSize & (parsedBlockSize - 1)) != 0) + if (parsedBlockSize < 4096 || parsedBlockSize > 32768 || + (parsedBlockSize & (parsedBlockSize - 1)) != 0) { std::stringstream s; - s << "Invalid nudb_block_size: " << parsedBlockSize << ". Must be power of 2 between 4096 and 32768."; + s << "Invalid nudb_block_size: " << parsedBlockSize + << ". Must be power of 2 between 4096 and 32768."; Throw(s.str()); } @@ -414,7 +422,8 @@ public: nudb::context& context, beast::Journal journal) override { - return std::make_unique(keyBytes, keyValues, burstSize, scheduler, context, journal); + return std::make_unique( + keyBytes, keyValues, burstSize, scheduler, context, journal); } }; diff --git a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp index a35f737528..c84c5f6982 100644 --- a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp @@ -103,7 +103,8 @@ public: if (auto const v = get(keyValues, "filter_bits")) { - bool const filter_blocks = !keyValues.exists("filter_full") || (get(keyValues, "filter_full") == 0); + bool const filter_blocks = + !keyValues.exists("filter_full") || (get(keyValues, "filter_full") == 0); table_options.filter_policy.reset(rocksdb::NewBloomFilterPolicy(v, filter_blocks)); } @@ -131,7 +132,8 @@ public: if (keyValues.exists("bg_threads")) { - m_options.env->SetBackgroundThreads(get(keyValues, "bg_threads"), rocksdb::Env::LOW); + m_options.env->SetBackgroundThreads( + get(keyValues, "bg_threads"), rocksdb::Env::LOW); } if (keyValues.exists("high_threads")) @@ -149,7 +151,8 @@ public: get_if_exists(keyValues, "block_size", table_options.block_size); - if (keyValues.exists("universal_compaction") && (get(keyValues, "universal_compaction") != 0)) + if (keyValues.exists("universal_compaction") && + (get(keyValues, "universal_compaction") != 0)) { m_options.compaction_style = rocksdb::kCompactionStyleUniversal; m_options.min_write_buffer_number_to_merge = 2; @@ -163,16 +166,19 @@ public: auto const s = rocksdb::GetBlockBasedTableOptionsFromString( config_options, table_options, get(keyValues, "bbt_options"), &table_options); if (!s.ok()) - Throw(std::string("Unable to set RocksDB bbt_options: ") + s.ToString()); + Throw( + std::string("Unable to set RocksDB bbt_options: ") + s.ToString()); } m_options.table_factory.reset(NewBlockBasedTableFactory(table_options)); if (keyValues.exists("options")) { - auto const s = rocksdb::GetOptionsFromString(m_options, get(keyValues, "options"), &m_options); + auto const s = + rocksdb::GetOptionsFromString(m_options, get(keyValues, "options"), &m_options); if (!s.ok()) - Throw(std::string("Unable to set RocksDB options: ") + s.ToString()); + Throw( + std::string("Unable to set RocksDB options: ") + s.ToString()); } std::string s1, s2; @@ -204,7 +210,8 @@ public: m_options.create_if_missing = createIfMissing; rocksdb::Status status = rocksdb::DB::Open(m_options, m_name, &db); if (!status.ok() || !db) - Throw(std::string("Unable to open/create RocksDB: ") + status.ToString()); + Throw( + std::string("Unable to open/create RocksDB: ") + status.ToString()); m_db.reset(db); } @@ -326,7 +333,8 @@ public: wb.Put( rocksdb::Slice(reinterpret_cast(encoded.getKey()), m_keyBytes), - rocksdb::Slice(reinterpret_cast(encoded.getData()), encoded.getSize())); + rocksdb::Slice( + reinterpret_cast(encoded.getData()), encoded.getSize())); } rocksdb::WriteOptions const options; @@ -425,8 +433,12 @@ public: } std::unique_ptr - createInstance(size_t keyBytes, Section const& keyValues, std::size_t, Scheduler& scheduler, beast::Journal journal) - override + createInstance( + size_t keyBytes, + Section const& keyValues, + std::size_t, + Scheduler& scheduler, + beast::Journal journal) override { return std::make_unique(keyBytes, keyValues, scheduler, journal, &m_env); } diff --git a/src/libxrpl/protocol/AMMCore.cpp b/src/libxrpl/protocol/AMMCore.cpp index bb83be2724..9061d04689 100644 --- a/src/libxrpl/protocol/AMMCore.cpp +++ b/src/libxrpl/protocol/AMMCore.cpp @@ -52,7 +52,10 @@ invalidAMMAsset(Issue const& issue, std::optional> const } NotTEC -invalidAMMAssetPair(Issue const& issue1, Issue const& issue2, std::optional> const& pair) +invalidAMMAssetPair( + Issue const& issue1, + Issue const& issue2, + std::optional> const& pair) { if (issue1 == issue2) return temBAD_AMM_TOKENS; @@ -64,7 +67,10 @@ invalidAMMAssetPair(Issue const& issue1, Issue const& issue2, std::optional> const& pair, bool validZero) +invalidAMMAmount( + STAmount const& amount, + std::optional> const& pair, + bool validZero) { if (auto const res = invalidAMMAsset(amount.issue(), pair)) return res; @@ -79,7 +85,8 @@ ammAuctionTimeSlot(std::uint64_t current, STObject const& auctionSlot) // It should be impossible for expiration to be < TOTAL_TIME_SLOT_SECS, // but check just to be safe auto const expiration = auctionSlot[sfExpiration]; - XRPL_ASSERT(expiration >= TOTAL_TIME_SLOT_SECS, "xrpl::ammAuctionTimeSlot : minimum expiration"); + XRPL_ASSERT( + expiration >= TOTAL_TIME_SLOT_SECS, "xrpl::ammAuctionTimeSlot : minimum expiration"); if (expiration >= TOTAL_TIME_SLOT_SECS) { if (auto const start = expiration - TOTAL_TIME_SLOT_SECS; current >= start) diff --git a/src/libxrpl/protocol/BuildInfo.cpp b/src/libxrpl/protocol/BuildInfo.cpp index c86ef17449..32b3431798 100644 --- a/src/libxrpl/protocol/BuildInfo.cpp +++ b/src/libxrpl/protocol/BuildInfo.cpp @@ -107,7 +107,8 @@ encodeSoftwareVersion(char const* const versionStr) if (prefix != identifier.substr(0, prefix.length())) return 0; - if (!beast::lexicalCastChecked(ret, std::string(identifier.substr(prefix.length())))) + if (!beast::lexicalCastChecked( + ret, std::string(identifier.substr(prefix.length())))) return 0; if (std::clamp(ret, lok, hik) != ret) diff --git a/src/libxrpl/protocol/Feature.cpp b/src/libxrpl/protocol/Feature.cpp index 834341f8d6..28ff1547df 100644 --- a/src/libxrpl/protocol/Feature.cpp +++ b/src/libxrpl/protocol/Feature.cpp @@ -70,7 +70,8 @@ class FeatureCollections uint256 feature; Feature() = delete; - explicit Feature(std::string const& name_, uint256 const& feature_) : name(name_), feature(feature_) + explicit Feature(std::string const& name_, uint256 const& feature_) + : name(name_), feature(feature_) { } @@ -89,9 +90,10 @@ class FeatureCollections }; // Intermediate types to help with readability - template - using feature_hashed_unique = boost::multi_index:: - hashed_unique, boost::multi_index::member>; + template + using feature_hashed_unique = boost::multi_index::hashed_unique< + boost::multi_index::tag, + boost::multi_index::member>; // Intermediate types to help with readability using feature_indexing = boost::multi_index::indexed_by< @@ -204,7 +206,8 @@ FeatureCollections::FeatureCollections() std::optional FeatureCollections::getRegisteredFeature(std::string const& name) const { - XRPL_ASSERT(readOnly.load(), "xrpl::FeatureCollections::getRegisteredFeature : startup completed"); + XRPL_ASSERT( + readOnly.load(), "xrpl::FeatureCollections::getRegisteredFeature : startup completed"); Feature const* feature = getByName(name); if (feature) return feature->feature; @@ -237,7 +240,8 @@ FeatureCollections::registerFeature(std::string const& name, Supported support, auto const getAmendmentSupport = [=]() { if (vote == VoteBehavior::Obsolete) return AmendmentSupport::Retired; - return support == Supported::yes ? AmendmentSupport::Supported : AmendmentSupport::Unsupported; + return support == Supported::yes ? AmendmentSupport::Supported + : AmendmentSupport::Unsupported; }; all.emplace(name, getAmendmentSupport()); @@ -271,7 +275,8 @@ FeatureCollections::registrationIsDone() size_t FeatureCollections::featureToBitsetIndex(uint256 const& f) const { - XRPL_ASSERT(readOnly.load(), "xrpl::FeatureCollections::featureToBitsetIndex : startup completed"); + XRPL_ASSERT( + readOnly.load(), "xrpl::FeatureCollections::featureToBitsetIndex : startup completed"); Feature const* feature = getByFeature(f); if (!feature) @@ -283,7 +288,8 @@ FeatureCollections::featureToBitsetIndex(uint256 const& f) const uint256 const& FeatureCollections::bitsetIndexToFeature(size_t i) const { - XRPL_ASSERT(readOnly.load(), "xrpl::FeatureCollections::bitsetIndexToFeature : startup completed"); + XRPL_ASSERT( + readOnly.load(), "xrpl::FeatureCollections::bitsetIndexToFeature : startup completed"); Feature const& feature = getByIndex(i); return feature.feature; } @@ -389,8 +395,10 @@ featureToName(uint256 const& f) #pragma push_macro("XRPL_RETIRE_FIX") #undef XRPL_RETIRE_FIX -#define XRPL_FEATURE(name, supported, vote) uint256 const feature##name = registerFeature(#name, supported, vote); -#define XRPL_FIX(name, supported, vote) uint256 const fix##name = registerFeature("fix" #name, supported, vote); +#define XRPL_FEATURE(name, supported, vote) \ + uint256 const feature##name = registerFeature(#name, supported, vote); +#define XRPL_FIX(name, supported, vote) \ + uint256 const fix##name = registerFeature("fix" #name, supported, vote); // clang-format off #define XRPL_RETIRE_FEATURE(name) \ diff --git a/src/libxrpl/protocol/IOUAmount.cpp b/src/libxrpl/protocol/IOUAmount.cpp index cfad753edc..eba78e6051 100644 --- a/src/libxrpl/protocol/IOUAmount.cpp +++ b/src/libxrpl/protocol/IOUAmount.cpp @@ -57,7 +57,8 @@ IOUAmount::fromNumber(Number const& number) // Need to create a default IOUAmount and assign directly so it doesn't try // to normalize, which calls fromNumber IOUAmount result{}; - std::tie(result.mantissa_, result.exponent_) = number.normalizeToRange(minMantissa, maxMantissa); + std::tie(result.mantissa_, result.exponent_) = + number.normalizeToRange(minMantissa, maxMantissa); return result; } diff --git a/src/libxrpl/protocol/Indexes.cpp b/src/libxrpl/protocol/Indexes.cpp index 33c836eab6..45ab20f057 100644 --- a/src/libxrpl/protocol/Indexes.cpp +++ b/src/libxrpl/protocol/Indexes.cpp @@ -99,15 +99,19 @@ getBookBase(Book const& book) { XRPL_ASSERT(isConsistent(book), "xrpl::getBookBase : input is consistent"); - auto const index = book.domain - ? indexHash( - LedgerNameSpace::BOOK_DIR, - book.in.currency, - book.out.currency, - book.in.account, - book.out.account, - *(book.domain)) - : indexHash(LedgerNameSpace::BOOK_DIR, book.in.currency, book.out.currency, book.in.account, book.out.account); + auto const index = book.domain ? indexHash( + LedgerNameSpace::BOOK_DIR, + book.in.currency, + book.out.currency, + book.in.account, + book.out.account, + *(book.domain)) + : indexHash( + LedgerNameSpace::BOOK_DIR, + book.in.currency, + book.out.currency, + book.in.account, + book.out.account); // Return with quality 0. auto k = keylet::quality({ltDIR_NODE, index}, 0); @@ -118,7 +122,8 @@ getBookBase(Book const& book) uint256 getQualityNext(uint256 const& uBase) { - static constexpr uint256 nextQuality("0000000000000000000000000000000000000000000000010000000000000000"); + static constexpr uint256 nextQuality( + "0000000000000000000000000000000000000000000000010000000000000000"); return uBase + nextQuality; } @@ -180,7 +185,8 @@ skip(LedgerIndex ledger) noexcept { return { ltLEDGER_HASHES, - indexHash(LedgerNameSpace::SKIP_LIST, std::uint32_t(static_cast(ledger) >> 16))}; + indexHash( + LedgerNameSpace::SKIP_LIST, std::uint32_t(static_cast(ledger) >> 16))}; } Keylet const& @@ -228,7 +234,9 @@ line(AccountID const& id0, AccountID const& id1, Currency const& currency) noexc // two accounts (smallest then largest) and hash them in that order: auto const accounts = std::minmax(id0, id1); - return {ltRIPPLE_STATE, indexHash(LedgerNameSpace::TRUST_LINE, accounts.first, accounts.second, currency)}; + return { + ltRIPPLE_STATE, + indexHash(LedgerNameSpace::TRUST_LINE, accounts.first, accounts.second, currency)}; } Keylet @@ -303,14 +311,17 @@ depositPreauth(AccountID const& owner, AccountID const& preauthorized) noexcept // Credentials should be sorted here, use credentials::makeSorted Keylet -depositPreauth(AccountID const& owner, std::set> const& authCreds) noexcept +depositPreauth( + AccountID const& owner, + std::set> const& authCreds) noexcept { std::vector hashes; hashes.reserve(authCreds.size()); for (auto const& o : authCreds) hashes.emplace_back(sha512Half(o.first, o.second)); - return {ltDEPOSIT_PREAUTH, indexHash(LedgerNameSpace::DEPOSIT_PREAUTH_CREDENTIALS, owner, hashes)}; + return { + ltDEPOSIT_PREAUTH, indexHash(LedgerNameSpace::DEPOSIT_PREAUTH_CREDENTIALS, owner, hashes)}; } //------------------------------------------------------------------------------ @@ -393,7 +404,8 @@ Keylet amm(Asset const& issue1, Asset const& issue2) noexcept { auto const& [minI, maxI] = std::minmax(issue1.get(), issue2.get()); - return amm(indexHash(LedgerNameSpace::AMM, minI.account, minI.currency, maxI.account, maxI.currency)); + return amm( + indexHash(LedgerNameSpace::AMM, minI.account, minI.currency, maxI.account, maxI.currency)); } Keylet diff --git a/src/libxrpl/protocol/Issue.cpp b/src/libxrpl/protocol/Issue.cpp index f540b52050..1a56007729 100644 --- a/src/libxrpl/protocol/Issue.cpp +++ b/src/libxrpl/protocol/Issue.cpp @@ -83,7 +83,8 @@ issueFromJson(Json::Value const& v) { if (!v.isObject()) { - Throw("issueFromJson can only be specified with an 'object' Json value"); + Throw( + "issueFromJson can only be specified with an 'object' Json value"); } if (v.isMember(jss::mpt_issuance_id)) diff --git a/src/libxrpl/protocol/Keylet.cpp b/src/libxrpl/protocol/Keylet.cpp index 18bd76440a..6f9656c4ea 100644 --- a/src/libxrpl/protocol/Keylet.cpp +++ b/src/libxrpl/protocol/Keylet.cpp @@ -8,7 +8,9 @@ namespace xrpl { bool Keylet::check(STLedgerEntry const& sle) const { - XRPL_ASSERT(sle.getType() != ltANY || sle.getType() != ltCHILD, "xrpl::Keylet::check : valid input type"); + XRPL_ASSERT( + sle.getType() != ltANY && sle.getType() != ltCHILD, + "xrpl::Keylet::check : valid input type"); if (type == ltANY) return true; diff --git a/src/libxrpl/protocol/LedgerFormats.cpp b/src/libxrpl/protocol/LedgerFormats.cpp index 8d9a24f741..2056cfab7b 100644 --- a/src/libxrpl/protocol/LedgerFormats.cpp +++ b/src/libxrpl/protocol/LedgerFormats.cpp @@ -22,7 +22,8 @@ LedgerFormats::LedgerFormats() #undef LEDGER_ENTRY #define UNWRAP(...) __VA_ARGS__ -#define LEDGER_ENTRY(tag, value, name, rpcName, fields) add(jss::name, tag, UNWRAP fields, commonFields); +#define LEDGER_ENTRY(tag, value, name, rpcName, fields) \ + add(jss::name, tag, UNWRAP fields, commonFields); #include diff --git a/src/libxrpl/protocol/MPTIssue.cpp b/src/libxrpl/protocol/MPTIssue.cpp index 9673d6071f..c2f7f1fa50 100644 --- a/src/libxrpl/protocol/MPTIssue.cpp +++ b/src/libxrpl/protocol/MPTIssue.cpp @@ -23,7 +23,8 @@ MPTIssue::getIssuer() const // MPTID is concatenation of sequence + account static_assert(sizeof(MPTID) == (sizeof(std::uint32_t) + sizeof(AccountID))); // copy from id skipping the sequence - AccountID const* account = reinterpret_cast(mptID_.data() + sizeof(std::uint32_t)); + AccountID const* account = + reinterpret_cast(mptID_.data() + sizeof(std::uint32_t)); return *account; } diff --git a/src/libxrpl/protocol/NFTokenID.cpp b/src/libxrpl/protocol/NFTokenID.cpp index deed26360a..b533fa53c0 100644 --- a/src/libxrpl/protocol/NFTokenID.cpp +++ b/src/libxrpl/protocol/NFTokenID.cpp @@ -53,11 +53,13 @@ getNFTokenIDFromPage(TxMeta const& transactionMeta) SField const& fName = node.getFName(); if (fName == sfCreatedNode) { - STArray const& toAddPrevNFTs = node.peekAtField(sfNewFields).downcast().getFieldArray(sfNFTokens); + STArray const& toAddPrevNFTs = + node.peekAtField(sfNewFields).downcast().getFieldArray(sfNFTokens); std::transform( - toAddPrevNFTs.begin(), toAddPrevNFTs.end(), std::back_inserter(finalIDs), [](STObject const& nft) { - return nft.getFieldH256(sfNFTokenID); - }); + toAddPrevNFTs.begin(), + toAddPrevNFTs.end(), + std::back_inserter(finalIDs), + [](STObject const& nft) { return nft.getFieldH256(sfNFTokenID); }); } else if (fName == sfModifiedNode) { @@ -70,22 +72,25 @@ getNFTokenIDFromPage(TxMeta const& transactionMeta) // However, there will always be NFTs listed in the final fields, // as rippled outputs all fields in final fields even if they were // not changed. - STObject const& previousFields = node.peekAtField(sfPreviousFields).downcast(); + STObject const& previousFields = + node.peekAtField(sfPreviousFields).downcast(); if (!previousFields.isFieldPresent(sfNFTokens)) continue; STArray const& toAddPrevNFTs = previousFields.getFieldArray(sfNFTokens); std::transform( - toAddPrevNFTs.begin(), toAddPrevNFTs.end(), std::back_inserter(prevIDs), [](STObject const& nft) { - return nft.getFieldH256(sfNFTokenID); - }); + toAddPrevNFTs.begin(), + toAddPrevNFTs.end(), + std::back_inserter(prevIDs), + [](STObject const& nft) { return nft.getFieldH256(sfNFTokenID); }); STArray const& toAddFinalNFTs = node.peekAtField(sfFinalFields).downcast().getFieldArray(sfNFTokens); std::transform( - toAddFinalNFTs.begin(), toAddFinalNFTs.end(), std::back_inserter(finalIDs), [](STObject const& nft) { - return nft.getFieldH256(sfNFTokenID); - }); + toAddFinalNFTs.begin(), + toAddFinalNFTs.end(), + std::back_inserter(finalIDs), + [](STObject const& nft) { return nft.getFieldH256(sfNFTokenID); }); } } @@ -96,7 +101,8 @@ getNFTokenIDFromPage(TxMeta const& transactionMeta) // Find the first NFT ID that doesn't match. We're looking for an // added NFT, so the one we want will be the mismatch in finalIDs. - auto const diff = std::mismatch(finalIDs.begin(), finalIDs.end(), prevIDs.begin(), prevIDs.end()); + auto const diff = + std::mismatch(finalIDs.begin(), finalIDs.end(), prevIDs.begin(), prevIDs.end()); // There should always be a difference so the returned finalIDs // iterator should never be end(). But better safe than sorry. @@ -112,10 +118,12 @@ getNFTokenIDFromDeletedOffer(TxMeta const& transactionMeta) std::vector tokenIDResult; for (STObject const& node : transactionMeta.getNodes()) { - if (node.getFieldU16(sfLedgerEntryType) != ltNFTOKEN_OFFER || node.getFName() != sfDeletedNode) + if (node.getFieldU16(sfLedgerEntryType) != ltNFTOKEN_OFFER || + node.getFName() != sfDeletedNode) continue; - auto const& toAddNFT = node.peekAtField(sfFinalFields).downcast().getFieldH256(sfNFTokenID); + auto const& toAddNFT = + node.peekAtField(sfFinalFields).downcast().getFieldH256(sfNFTokenID); tokenIDResult.push_back(toAddNFT); } @@ -127,7 +135,10 @@ getNFTokenIDFromDeletedOffer(TxMeta const& transactionMeta) } void -insertNFTokenID(Json::Value& response, std::shared_ptr const& transaction, TxMeta const& transactionMeta) +insertNFTokenID( + Json::Value& response, + std::shared_ptr const& transaction, + TxMeta const& transactionMeta) { if (!canHaveNFTokenID(transaction, transactionMeta)) return; diff --git a/src/libxrpl/protocol/NFTokenOfferID.cpp b/src/libxrpl/protocol/NFTokenOfferID.cpp index bbd67d710c..b1a08081c0 100644 --- a/src/libxrpl/protocol/NFTokenOfferID.cpp +++ b/src/libxrpl/protocol/NFTokenOfferID.cpp @@ -16,13 +16,16 @@ namespace xrpl { bool -canHaveNFTokenOfferID(std::shared_ptr const& serializedTx, TxMeta const& transactionMeta) +canHaveNFTokenOfferID( + std::shared_ptr const& serializedTx, + TxMeta const& transactionMeta) { if (!serializedTx) return false; TxType const tt = serializedTx->getTxnType(); - if (!(tt == ttNFTOKEN_MINT && serializedTx->isFieldPresent(sfAmount)) && tt != ttNFTOKEN_CREATE_OFFER) + if (!(tt == ttNFTOKEN_MINT && serializedTx->isFieldPresent(sfAmount)) && + tt != ttNFTOKEN_CREATE_OFFER) return false; // if the transaction failed nothing could have been delivered. @@ -37,7 +40,8 @@ getOfferIDFromCreatedOffer(TxMeta const& transactionMeta) { for (STObject const& node : transactionMeta.getNodes()) { - if (node.getFieldU16(sfLedgerEntryType) != ltNFTOKEN_OFFER || node.getFName() != sfCreatedNode) + if (node.getFieldU16(sfLedgerEntryType) != ltNFTOKEN_OFFER || + node.getFName() != sfCreatedNode) continue; return node.getFieldH256(sfLedgerIndex); diff --git a/src/libxrpl/protocol/Permissions.cpp b/src/libxrpl/protocol/Permissions.cpp index 7e592fdc7f..991f9d4d82 100644 --- a/src/libxrpl/protocol/Permissions.cpp +++ b/src/libxrpl/protocol/Permissions.cpp @@ -130,7 +130,9 @@ std::optional> const Permission::getTxFeature(TxType txType) const { auto const txFeaturesIt = txFeatureMap_.find(txType); - XRPL_ASSERT(txFeaturesIt != txFeatureMap_.end(), "xrpl::Permissions::getTxFeature : tx exists in txFeatureMap_"); + XRPL_ASSERT( + txFeaturesIt != txFeatureMap_.end(), + "xrpl::Permissions::getTxFeature : tx exists in txFeatureMap_"); if (txFeaturesIt->second == uint256{}) return std::nullopt; @@ -140,7 +142,8 @@ Permission::getTxFeature(TxType txType) const bool Permission::isDelegable(std::uint32_t const& permissionValue, Rules const& rules) const { - auto const granularPermission = getGranularName(static_cast(permissionValue)); + auto const granularPermission = + getGranularName(static_cast(permissionValue)); if (granularPermission) // granular permissions are always allowed to be delegated return true; @@ -152,7 +155,9 @@ Permission::isDelegable(std::uint32_t const& permissionValue, Rules const& rules return false; auto const txFeaturesIt = txFeatureMap_.find(txType); - XRPL_ASSERT(txFeaturesIt != txFeatureMap_.end(), "xrpl::Permissions::isDelegable : tx exists in txFeatureMap_"); + XRPL_ASSERT( + txFeaturesIt != txFeatureMap_.end(), + "xrpl::Permissions::isDelegable : tx exists in txFeatureMap_"); // Delegation is only allowed if the required amendment for the transaction // is enabled. For transactions that do not require an amendment, delegation diff --git a/src/libxrpl/protocol/Protocol.cpp b/src/libxrpl/protocol/Protocol.cpp new file mode 100644 index 0000000000..6f86f49fc6 --- /dev/null +++ b/src/libxrpl/protocol/Protocol.cpp @@ -0,0 +1,15 @@ +#include + +namespace xrpl { +bool +isVotingLedger(LedgerIndex seq) +{ + return seq % FLAG_LEDGER_INTERVAL == 0; +} + +bool +isFlagLedger(LedgerIndex seq) +{ + return seq % FLAG_LEDGER_INTERVAL == 0; +} +} // namespace xrpl diff --git a/src/libxrpl/protocol/PublicKey.cpp b/src/libxrpl/protocol/PublicKey.cpp index b336b2d4b5..3251cb84ac 100644 --- a/src/libxrpl/protocol/PublicKey.cpp +++ b/src/libxrpl/protocol/PublicKey.cpp @@ -109,9 +109,12 @@ sliceToHex(Slice const& slice) std::optional ecdsaCanonicality(Slice const& sig) { - using uint264 = boost::multiprecision::number< - boost::multiprecision:: - cpp_int_backend<264, 264, boost::multiprecision::signed_magnitude, boost::multiprecision::unchecked, void>>; + using uint264 = boost::multiprecision::number>; static uint264 const G("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); @@ -150,8 +153,9 @@ ed25519Canonical(Slice const& sig) return false; // Big-endian Order, the Ed25519 subgroup order std::uint8_t const Order[] = { - 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x14, 0xDE, 0xF9, 0xDE, 0xA2, 0xF7, 0x9C, 0xD6, 0x58, 0x12, 0x63, 0x1A, 0x5C, 0xF5, 0xD3, 0xED, + 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0xDE, 0xF9, 0xDE, 0xA2, 0xF7, + 0x9C, 0xD6, 0x58, 0x12, 0x63, 0x1A, 0x5C, 0xF5, 0xD3, 0xED, }; // Take the second half of signature // and byte-reverse it to big-endian. @@ -210,7 +214,11 @@ publicKeyType(Slice const& slice) } bool -verifyDigest(PublicKey const& publicKey, uint256 const& digest, Slice const& sig, bool mustBeFullyCanonical) noexcept +verifyDigest( + PublicKey const& publicKey, + uint256 const& digest, + Slice const& sig, + bool mustBeFullyCanonical) noexcept { if (publicKeyType(publicKey) != KeyType::secp256k1) LogicError("sign: secp256k1 required for digest signing"); @@ -230,7 +238,10 @@ verifyDigest(PublicKey const& publicKey, uint256 const& digest, Slice const& sig secp256k1_ecdsa_signature sig_imp; if (secp256k1_ecdsa_signature_parse_der( - secp256k1Context(), &sig_imp, reinterpret_cast(sig.data()), sig.size()) != 1) + secp256k1Context(), + &sig_imp, + reinterpret_cast(sig.data()), + sig.size()) != 1) return false; if (*canonicality != ECDSACanonicality::fullyCanonical) { @@ -238,11 +249,16 @@ verifyDigest(PublicKey const& publicKey, uint256 const& digest, Slice const& sig if (secp256k1_ecdsa_signature_normalize(secp256k1Context(), &sig_norm, &sig_imp) != 1) return false; return secp256k1_ecdsa_verify( - secp256k1Context(), &sig_norm, reinterpret_cast(digest.data()), &pubkey_imp) == - 1; + secp256k1Context(), + &sig_norm, + reinterpret_cast(digest.data()), + &pubkey_imp) == 1; } return secp256k1_ecdsa_verify( - secp256k1Context(), &sig_imp, reinterpret_cast(digest.data()), &pubkey_imp) == 1; + secp256k1Context(), + &sig_imp, + reinterpret_cast(digest.data()), + &pubkey_imp) == 1; } bool diff --git a/src/libxrpl/protocol/Quality.cpp b/src/libxrpl/protocol/Quality.cpp index fda0ac2e1e..ba9807318a 100644 --- a/src/libxrpl/protocol/Quality.cpp +++ b/src/libxrpl/protocol/Quality.cpp @@ -36,7 +36,9 @@ Quality::operator++(int) Quality& Quality::operator--() { - XRPL_ASSERT(m_value < std::numeric_limits::max(), "xrpl::Quality::operator--() : maximum value"); + XRPL_ASSERT( + m_value < std::numeric_limits::max(), + "xrpl::Quality::operator--() : maximum value"); ++m_value; return *this; } @@ -121,7 +123,9 @@ composed_quality(Quality const& lhs, Quality const& rhs) std::uint64_t const stored_exponent(rate.exponent() + 100); std::uint64_t const stored_mantissa(rate.mantissa()); - XRPL_ASSERT((stored_exponent > 0) && (stored_exponent <= 255), "xrpl::composed_quality : valid exponent"); + XRPL_ASSERT( + (stored_exponent > 0) && (stored_exponent <= 255), + "xrpl::composed_quality : valid exponent"); return Quality((stored_exponent << (64 - 8)) | stored_mantissa); } diff --git a/src/libxrpl/protocol/QualityFunction.cpp b/src/libxrpl/protocol/QualityFunction.cpp index db004bf478..ebc59dcc83 100644 --- a/src/libxrpl/protocol/QualityFunction.cpp +++ b/src/libxrpl/protocol/QualityFunction.cpp @@ -9,7 +9,8 @@ namespace xrpl { -QualityFunction::QualityFunction(Quality const& quality, QualityFunction::CLOBLikeTag) : m_(0), b_(0), quality_(quality) +QualityFunction::QualityFunction(Quality const& quality, QualityFunction::CLOBLikeTag) + : m_(0), b_(0), quality_(quality) { if (quality.rate() <= beast::zero) Throw("QualityFunction quality rate is 0."); diff --git a/src/libxrpl/protocol/Rules.cpp b/src/libxrpl/protocol/Rules.cpp index e649b15ea2..5a97a33185 100644 --- a/src/libxrpl/protocol/Rules.cpp +++ b/src/libxrpl/protocol/Rules.cpp @@ -39,7 +39,8 @@ setCurrentTransactionRules(std::optional r) // Make global changes associated with the rules before the value is moved. // Push the appropriate setting, instead of having the class pull every time // the value is needed. That could get expensive fast. - bool enableLargeNumbers = !r || (r->enabled(featureSingleAssetVault) || r->enabled(featureLendingProtocol)); + bool enableLargeNumbers = + !r || (r->enabled(featureSingleAssetVault) || r->enabled(featureLendingProtocol)); Number::setMantissaScale(enableLargeNumbers ? MantissaRange::large : MantissaRange::small); *getCurrentTransactionRulesRef() = std::move(r); @@ -96,7 +97,8 @@ public: } }; -Rules::Rules(std::unordered_set> const& presets) : impl_(std::make_shared(presets)) +Rules::Rules(std::unordered_set> const& presets) + : impl_(std::make_shared(presets)) { } diff --git a/src/libxrpl/protocol/SField.cpp b/src/libxrpl/protocol/SField.cpp index c04c82f2bc..8015b34e73 100644 --- a/src/libxrpl/protocol/SField.cpp +++ b/src/libxrpl/protocol/SField.cpp @@ -22,7 +22,8 @@ static SField::private_access_tag_t access; template template -TypedField::TypedField(private_access_tag_t pat, Args&&... args) : SField(pat, std::forward(args)...) +TypedField::TypedField(private_access_tag_t pat, Args&&... args) + : SField(pat, std::forward(args)...) { } @@ -36,10 +37,19 @@ TypedField::TypedField(private_access_tag_t pat, Args&&... args) : SField(pat #undef TYPED_SFIELD #define UNTYPED_SFIELD(sfName, stiSuffix, fieldValue, ...) \ - SField const sfName(access, STI_##stiSuffix, fieldValue, std::string_view(#sfName).substr(2).data(), ##__VA_ARGS__); + SField const sfName( \ + access, \ + STI_##stiSuffix, \ + fieldValue, \ + std::string_view(#sfName).substr(2).data(), \ + ##__VA_ARGS__); #define TYPED_SFIELD(sfName, stiSuffix, fieldValue, ...) \ SF_##stiSuffix const sfName( \ - access, STI_##stiSuffix, fieldValue, std::string_view(#sfName).substr(2).data(), ##__VA_ARGS__); + access, \ + STI_##stiSuffix, \ + fieldValue, \ + std::string_view(#sfName).substr(2).data(), \ + ##__VA_ARGS__); // SFields which, for historical reasons, do not follow naming conventions. SField const sfInvalid(access, -1, ""); @@ -56,7 +66,13 @@ SField const sfIndex(access, STI_UINT256, 258, "index"); #undef UNTYPED_SFIELD #pragma pop_macro("UNTYPED_SFIELD") -SField::SField(private_access_tag_t, SerializedTypeID tid, int fv, char const* fn, int meta, IsSigning signing) +SField::SField( + private_access_tag_t, + SerializedTypeID tid, + int fv, + char const* fn, + int meta, + IsSigning signing) : fieldCode(field_code(tid, fv)) , fieldType(tid) , fieldValue(fv) @@ -67,9 +83,11 @@ SField::SField(private_access_tag_t, SerializedTypeID tid, int fv, char const* f , jsonName(fieldName.c_str()) { XRPL_ASSERT( - !knownCodeToField.contains(fieldCode), "xrpl::SField::SField(tid,fv,fn,meta,signing) : fieldCode is unique"); + !knownCodeToField.contains(fieldCode), + "xrpl::SField::SField(tid,fv,fn,meta,signing) : fieldCode is unique"); XRPL_ASSERT( - !knownNameToField.contains(fieldName), "xrpl::SField::SField(tid,fv,fn,meta,signing) : fieldName is unique"); + !knownNameToField.contains(fieldName), + "xrpl::SField::SField(tid,fv,fn,meta,signing) : fieldName is unique"); knownCodeToField[fieldCode] = this; knownNameToField[fieldName] = this; } @@ -84,8 +102,10 @@ SField::SField(private_access_tag_t, int fc, char const* fn) , signingField(IsSigning::yes) , jsonName(fieldName.c_str()) { - XRPL_ASSERT(!knownCodeToField.contains(fieldCode), "xrpl::SField::SField(fc,fn) : fieldCode is unique"); - XRPL_ASSERT(!knownNameToField.contains(fieldName), "xrpl::SField::SField(fc,fn) : fieldName is unique"); + XRPL_ASSERT( + !knownCodeToField.contains(fieldCode), "xrpl::SField::SField(fc,fn) : fieldCode is unique"); + XRPL_ASSERT( + !knownNameToField.contains(fieldName), "xrpl::SField::SField(fc,fn) : fieldName is unique"); knownCodeToField[fieldCode] = this; knownNameToField[fieldName] = this; } diff --git a/src/libxrpl/protocol/SOTemplate.cpp b/src/libxrpl/protocol/SOTemplate.cpp index 23d086f493..46edf98710 100644 --- a/src/libxrpl/protocol/SOTemplate.cpp +++ b/src/libxrpl/protocol/SOTemplate.cpp @@ -8,7 +8,9 @@ namespace xrpl { -SOTemplate::SOTemplate(std::initializer_list uniqueFields, std::initializer_list commonFields) +SOTemplate::SOTemplate( + std::initializer_list uniqueFields, + std::initializer_list commonFields) : indices_(SField::getNumFields() + 1, -1) // Unmapped indices == -1 { // Add all SOElements. diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index b7c33bb907..650cc4369d 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -65,7 +65,9 @@ getInt64Value(STAmount const& amount, bool valid, char const* error) auto ret = static_cast(amount.mantissa()); - XRPL_ASSERT(static_cast(ret) == amount.mantissa(), "xrpl::getInt64Value : mantissa must roundtrip"); + XRPL_ASSERT( + static_cast(ret) == amount.mantissa(), + "xrpl::getInt64Value : mantissa must roundtrip"); if (amount.negative()) ret = -ret; @@ -178,7 +180,8 @@ STAmount::STAmount(SerialIter& sit, SField const& name) : STBase(name) canonicalize(); } -STAmount::STAmount(SField const& name, std::int64_t mantissa) : STBase(name), mAsset(xrpIssue()), mOffset(0) +STAmount::STAmount(SField const& name, std::int64_t mantissa) + : STBase(name), mAsset(xrpIssue()), mOffset(0) { set(mantissa); } @@ -193,7 +196,11 @@ STAmount::STAmount(SField const& name, std::uint64_t mantissa, bool negative) } STAmount::STAmount(SField const& name, STAmount const& from) - : STBase(name), mAsset(from.mAsset), mValue(from.mValue), mOffset(from.mOffset), mIsNegative(from.mIsNegative) + : STBase(name) + , mAsset(from.mAsset) + , mValue(from.mValue) + , mOffset(from.mOffset) + , mIsNegative(from.mIsNegative) { XRPL_ASSERT( mValue <= std::numeric_limits::max(), @@ -212,7 +219,8 @@ STAmount::STAmount(std::uint64_t mantissa, bool negative) "input"); } -STAmount::STAmount(XRPAmount const& amount) : mAsset(xrpIssue()), mOffset(0), mIsNegative(amount < beast::zero) +STAmount::STAmount(XRPAmount const& amount) + : mAsset(xrpIssue()), mOffset(0), mIsNegative(amount < beast::zero) { if (mIsNegative) mValue = unsafe_cast(-amount.drops()); @@ -440,7 +448,9 @@ getRate(STAmount const& offerOut, STAmount const& offerIn) STAmount r = divide(offerIn, offerOut, noIssue()); if (r == beast::zero) // offer is too good return 0; - XRPL_ASSERT((r.exponent() >= -100) && (r.exponent() <= 155), "xrpl::getRate : exponent inside range"); + XRPL_ASSERT( + (r.exponent() >= -100) && (r.exponent() <= 155), + "xrpl::getRate : exponent inside range"); std::uint64_t ret = r.exponent() + 100; return (ret << (64 - 8)) | r.mantissa(); } @@ -487,8 +497,10 @@ canAdd(STAmount const& a, STAmount const& b) XRPAmount A = a.xrp(); XRPAmount B = b.xrp(); - if ((B > XRPAmount{0} && A > XRPAmount{std::numeric_limits::max()} - B) || - (B < XRPAmount{0} && A < XRPAmount{std::numeric_limits::min()} - B)) + if ((B > XRPAmount{0} && + A > XRPAmount{std::numeric_limits::max()} - B) || + (B < XRPAmount{0} && + A < XRPAmount{std::numeric_limits::min()} - B)) { return false; } @@ -510,8 +522,10 @@ canAdd(STAmount const& a, STAmount const& b) { MPTAmount A = a.mpt(); MPTAmount B = b.mpt(); - if ((B > MPTAmount{0} && A > MPTAmount{std::numeric_limits::max()} - B) || - (B < MPTAmount{0} && A < MPTAmount{std::numeric_limits::min()} - B)) + if ((B > MPTAmount{0} && + A > MPTAmount{std::numeric_limits::max()} - B) || + (B < MPTAmount{0} && + A < MPTAmount{std::numeric_limits::min()} - B)) { return false; } @@ -562,7 +576,8 @@ canSubtract(STAmount const& a, STAmount const& b) return false; // Check for overflow - if (B < XRPAmount{0} && A > XRPAmount{std::numeric_limits::max()} + B) + if (B < XRPAmount{0} && + A > XRPAmount{std::numeric_limits::max()} + B) return false; return true; @@ -585,7 +600,8 @@ canSubtract(STAmount const& a, STAmount const& b) return false; // Overflow check - if (B < MPTAmount{0} && A > MPTAmount{std::numeric_limits::max()} + B) + if (B < MPTAmount{0} && + A > MPTAmount{std::numeric_limits::max()} + B) return false; return true; } @@ -698,9 +714,11 @@ STAmount::getText() const XRPL_ASSERT(post_to >= post_from, "xrpl::STAmount::getText : second distance check"); - post_to = std::find_if(std::make_reverse_iterator(post_to), std::make_reverse_iterator(post_from), [](char c) { - return c != '0'; - }).base(); + post_to = std::find_if( + std::make_reverse_iterator(post_to), + std::make_reverse_iterator(post_from), + [](char c) { return c != '0'; }) + .base(); // Assemble the output: if (pre_from == pre_to) @@ -903,7 +921,8 @@ STAmount::canonicalize() XRPL_ASSERT( (mValue == 0) || ((mOffset >= cMinOffset) && (mOffset <= cMaxOffset)), "xrpl::STAmount::canonicalize : offset inside range"); - XRPL_ASSERT((mValue != 0) || (mOffset != -100), "xrpl::STAmount::canonicalize : value or offset set"); + XRPL_ASSERT( + (mValue != 0) || (mOffset != -100), "xrpl::STAmount::canonicalize : value or offset set"); } void @@ -1092,8 +1111,8 @@ amountFromJsonNoThrow(STAmount& result, Json::Value const& jvSource) bool operator==(STAmount const& lhs, STAmount const& rhs) { - return areComparable(lhs, rhs) && lhs.negative() == rhs.negative() && lhs.exponent() == rhs.exponent() && - lhs.mantissa() == rhs.mantissa(); + return areComparable(lhs, rhs) && lhs.negative() == rhs.negative() && + lhs.exponent() == rhs.exponent() && lhs.mantissa() == rhs.mantissa(); } bool @@ -1136,7 +1155,12 @@ operator-(STAmount const& value) if (value.mantissa() == 0) return value; return STAmount( - value.getFName(), value.asset(), value.mantissa(), value.exponent(), !value.negative(), STAmount::unchecked{}); + value.getFName(), + value.asset(), + value.mantissa(), + value.exponent(), + !value.negative(), + STAmount::unchecked{}); } //------------------------------------------------------------------------------ @@ -1158,15 +1182,19 @@ muldiv(std::uint64_t multiplier, std::uint64_t multiplicand, std::uint64_t divis if (ret > std::numeric_limits::max()) { Throw( - "overflow: (" + std::to_string(multiplier) + " * " + std::to_string(multiplicand) + ") / " + - std::to_string(divisor)); + "overflow: (" + std::to_string(multiplier) + " * " + std::to_string(multiplicand) + + ") / " + std::to_string(divisor)); } return static_cast(ret); } static std::uint64_t -muldiv_round(std::uint64_t multiplier, std::uint64_t multiplicand, std::uint64_t divisor, std::uint64_t rounding) +muldiv_round( + std::uint64_t multiplier, + std::uint64_t multiplicand, + std::uint64_t divisor, + std::uint64_t rounding) { boost::multiprecision::uint128_t ret; @@ -1177,8 +1205,8 @@ muldiv_round(std::uint64_t multiplier, std::uint64_t multiplicand, std::uint64_t if (ret > std::numeric_limits::max()) { Throw( - "overflow: ((" + std::to_string(multiplier) + " * " + std::to_string(multiplicand) + ") + " + - std::to_string(rounding) + ") / " + std::to_string(divisor)); + "overflow: ((" + std::to_string(multiplier) + " * " + std::to_string(multiplicand) + + ") + " + std::to_string(rounding) + ") / " + std::to_string(divisor)); } return static_cast(ret); @@ -1223,7 +1251,10 @@ divide(STAmount const& num, STAmount const& den, Asset const& asset) // 10^32 to 10^33) followed by a division, so the result // is in the range of 10^16 to 10^15. return STAmount( - asset, muldiv(numVal, tenTo17, denVal) + 5, numOffset - denOffset - 17, num.negative() != den.negative()); + asset, + muldiv(numVal, tenTo17, denVal) + 5, + numOffset - denOffset - 17, + num.negative() != den.negative()); } STAmount @@ -1292,7 +1323,11 @@ multiply(STAmount const& v1, STAmount const& v2, Asset const& asset) // and 10^16), so their product is in the 10^30 to 10^32 // range. Dividing their product by 10^14 maintains the // precision, by scaling the result to 10^16 to 10^18. - return STAmount(asset, muldiv(value1, value2, tenTo14) + 7, offset1 + offset2 + 14, v1.negative() != v2.negative()); + return STAmount( + asset, + muldiv(value1, value2, tenTo14) + 7, + offset1 + offset2 + 14, + v1.negative() != v2.negative()); } // This is the legacy version of canonicalizeRound. It's been in use @@ -1509,7 +1544,8 @@ mulRoundImpl(STAmount const& v1, STAmount const& v2, Asset const& asset, bool ro // If the we're rounding up, we want to round up away // from zero, and if we're rounding down, truncation // is implicit. - std::uint64_t amount = muldiv_round(value1, value2, tenTo14, (resultNegative != roundUp) ? tenTo14m1 : 0); + std::uint64_t amount = + muldiv_round(value1, value2, tenTo14, (resultNegative != roundUp) ? tenTo14m1 : 0); int offset = offset1 + offset2 + 14; if (resultNegative != roundUp) @@ -1597,7 +1633,8 @@ divRoundImpl(STAmount const& num, STAmount const& den, Asset const& asset, bool // // We round away from zero if we're rounding up or // truncate if we're rounding down. - std::uint64_t amount = muldiv_round(numVal, tenTo17, denVal, (resultNegative != roundUp) ? denVal - 1 : 0); + std::uint64_t amount = + muldiv_round(numVal, tenTo17, denVal, (resultNegative != roundUp) ? denVal - 1 : 0); int offset = numOffset - denOffset - 17; diff --git a/src/libxrpl/protocol/STCurrency.cpp b/src/libxrpl/protocol/STCurrency.cpp index cfbbe509c6..1616de59b9 100644 --- a/src/libxrpl/protocol/STCurrency.cpp +++ b/src/libxrpl/protocol/STCurrency.cpp @@ -23,7 +23,8 @@ STCurrency::STCurrency(SerialIter& sit, SField const& name) : STBase{name} currency_ = sit.get160(); } -STCurrency::STCurrency(SField const& name, Currency const& currency) : STBase{name}, currency_{currency} +STCurrency::STCurrency(SField const& name, Currency const& currency) + : STBase{name}, currency_{currency} { } diff --git a/src/libxrpl/protocol/STInteger.cpp b/src/libxrpl/protocol/STInteger.cpp index ae7b3ff279..1fccee2285 100644 --- a/src/libxrpl/protocol/STInteger.cpp +++ b/src/libxrpl/protocol/STInteger.cpp @@ -20,7 +20,8 @@ namespace xrpl { template <> -STInteger::STInteger(SerialIter& sit, SField const& name) : STInteger(name, sit.get8()) +STInteger::STInteger(SerialIter& sit, SField const& name) + : STInteger(name, sit.get8()) { } @@ -72,7 +73,8 @@ STUInt8::getJson(JsonOptions) const //------------------------------------------------------------------------------ template <> -STInteger::STInteger(SerialIter& sit, SField const& name) : STInteger(name, sit.get16()) +STInteger::STInteger(SerialIter& sit, SField const& name) + : STInteger(name, sit.get16()) { } @@ -132,7 +134,8 @@ STUInt16::getJson(JsonOptions) const //------------------------------------------------------------------------------ template <> -STInteger::STInteger(SerialIter& sit, SField const& name) : STInteger(name, sit.get32()) +STInteger::STInteger(SerialIter& sit, SField const& name) + : STInteger(name, sit.get32()) { } @@ -173,7 +176,8 @@ STUInt32::getJson(JsonOptions) const //------------------------------------------------------------------------------ template <> -STInteger::STInteger(SerialIter& sit, SField const& name) : STInteger(name, sit.get64()) +STInteger::STInteger(SerialIter& sit, SField const& name) + : STInteger(name, sit.get64()) { } @@ -215,7 +219,8 @@ STUInt64::getJson(JsonOptions) const //------------------------------------------------------------------------------ template <> -STInteger::STInteger(SerialIter& sit, SField const& name) : STInteger(name, sit.get32()) +STInteger::STInteger(SerialIter& sit, SField const& name) + : STInteger(name, sit.get32()) { } diff --git a/src/libxrpl/protocol/STIssue.cpp b/src/libxrpl/protocol/STIssue.cpp index 627c61fc58..5887b5c21f 100644 --- a/src/libxrpl/protocol/STIssue.cpp +++ b/src/libxrpl/protocol/STIssue.cpp @@ -46,7 +46,10 @@ STIssue::STIssue(SerialIter& sit, SField const& name) : STBase{name} std::uint32_t sequence = sit.get32(); static_assert(MPTID::size() == sizeof(sequence) + sizeof(currencyOrAccount)); memcpy(mptID.data(), &sequence, sizeof(sequence)); - memcpy(mptID.data() + sizeof(sequence), currencyOrAccount.data(), sizeof(currencyOrAccount)); + memcpy( + mptID.data() + sizeof(sequence), + currencyOrAccount.data(), + sizeof(currencyOrAccount)); MPTIssue issue{mptID}; asset_ = issue; } diff --git a/src/libxrpl/protocol/STLedgerEntry.cpp b/src/libxrpl/protocol/STLedgerEntry.cpp index d73da2eb3a..8d0d56a737 100644 --- a/src/libxrpl/protocol/STLedgerEntry.cpp +++ b/src/libxrpl/protocol/STLedgerEntry.cpp @@ -34,20 +34,23 @@ STLedgerEntry::STLedgerEntry(Keylet const& k) : STObject(sfLedgerEntry), key_(k. if (format == nullptr) Throw( - "Attempt to create a SLE of unknown type " + std::to_string(safe_cast(k.type))); + "Attempt to create a SLE of unknown type " + + std::to_string(safe_cast(k.type))); set(format->getSOTemplate()); setFieldU16(sfLedgerEntryType, static_cast(type_)); } -STLedgerEntry::STLedgerEntry(SerialIter& sit, uint256 const& index) : STObject(sfLedgerEntry), key_(index) +STLedgerEntry::STLedgerEntry(SerialIter& sit, uint256 const& index) + : STObject(sfLedgerEntry), key_(index) { set(sit); setSLEType(); } -STLedgerEntry::STLedgerEntry(STObject const& object, uint256 const& index) : STObject(object), key_(index) +STLedgerEntry::STLedgerEntry(STObject const& object, uint256 const& index) + : STObject(object), key_(index) { setSLEType(); } @@ -55,7 +58,8 @@ STLedgerEntry::STLedgerEntry(STObject const& object, uint256 const& index) : STO void STLedgerEntry::setSLEType() { - auto format = LedgerFormats::getInstance().findByType(safe_cast(getFieldU16(sfLedgerEntryType))); + auto format = LedgerFormats::getInstance().findByType( + safe_cast(getFieldU16(sfLedgerEntryType))); if (format == nullptr) Throw("invalid ledger entry type"); @@ -114,7 +118,8 @@ STLedgerEntry::getJson(JsonOptions options) const ret[jss::index] = to_string(key_); if (getType() == ltMPTOKEN_ISSUANCE) - ret[jss::mpt_issuance_id] = to_string(makeMptID(getFieldU32(sfSequence), getAccountID(sfIssuer))); + ret[jss::mpt_issuance_id] = + to_string(makeMptID(getFieldU32(sfSequence), getAccountID(sfIssuer))); return ret; } @@ -132,7 +137,11 @@ STLedgerEntry::isThreadedType(Rules const& rules) const } bool -STLedgerEntry::thread(uint256 const& txID, std::uint32_t ledgerSeq, uint256& prevTxID, std::uint32_t& prevLedgerID) +STLedgerEntry::thread( + uint256 const& txID, + std::uint32_t ledgerSeq, + uint256& prevTxID, + std::uint32_t& prevLedgerID) { uint256 oldPrevTxID = getFieldH256(sfPreviousTxnID); @@ -142,7 +151,8 @@ STLedgerEntry::thread(uint256 const& txID, std::uint32_t ledgerSeq, uint256& pre { // this transaction is already threaded XRPL_ASSERT( - getFieldU32(sfPreviousTxnLgrSeq) == ledgerSeq, "xrpl::STLedgerEntry::thread : ledger sequence match"); + getFieldU32(sfPreviousTxnLgrSeq) == ledgerSeq, + "xrpl::STLedgerEntry::thread : ledger sequence match"); return false; } diff --git a/src/libxrpl/protocol/STNumber.cpp b/src/libxrpl/protocol/STNumber.cpp index a549a0e482..cdee274f67 100644 --- a/src/libxrpl/protocol/STNumber.cpp +++ b/src/libxrpl/protocol/STNumber.cpp @@ -50,7 +50,10 @@ STNumber::associateAsset(Asset const& a) { STTakesAsset::associateAsset(a); - XRPL_ASSERT_PARTS(getFName().shouldMeta(SField::sMD_NeedsAsset), "STNumber::associateAsset", "field needs asset"); + XRPL_ASSERT_PARTS( + getFName().shouldMeta(SField::sMD_NeedsAsset), + "STNumber::associateAsset", + "field needs asset"); roundToAsset(a, value_); } @@ -94,7 +97,8 @@ STNumber::add(Serializer& s) const } XRPL_ASSERT_PARTS( - mantissa <= std::numeric_limits::max() && mantissa >= std::numeric_limits::min(), + mantissa <= std::numeric_limits::max() && + mantissa >= std::numeric_limits::min(), "xrpl::STNumber::add", "mantissa in valid range"); s.add64(mantissa); @@ -128,7 +132,8 @@ STNumber::move(std::size_t n, void* buf) bool STNumber::isEquivalent(STBase const& t) const { - XRPL_ASSERT(t.getSType() == this->getSType(), "xrpl::STNumber::isEquivalent : field type match"); + XRPL_ASSERT( + t.getSType() == this->getSType(), "xrpl::STNumber::isEquivalent : field type match"); STNumber const& v = dynamic_cast(t); return value_ == v; } @@ -226,19 +231,22 @@ numberFromJson(SField const& field, Json::Value const& value) { parts = partsFromString(value.asString()); - XRPL_ASSERT_PARTS(!getCurrentTransactionRules(), "xrpld::numberFromJson", "Not in a Transactor context"); + XRPL_ASSERT_PARTS( + !getCurrentTransactionRules(), "xrpld::numberFromJson", "Not in a Transactor context"); // Number mantissas are much bigger than the allowable parsed values, so // it can't be out of range. static_assert( - std::numeric_limits::max() >= std::numeric_limits::max()); + std::numeric_limits::max() >= + std::numeric_limits::max()); } else { Throw("not a number"); } - return STNumber{field, Number{parts.negative, parts.mantissa, parts.exponent, Number::normalized{}}}; + return STNumber{ + field, Number{parts.negative, parts.mantissa, parts.exponent, Number::normalized{}}}; } } // namespace xrpl diff --git a/src/libxrpl/protocol/STObject.cpp b/src/libxrpl/protocol/STObject.cpp index ad5b6fe352..829f8eaeef 100644 --- a/src/libxrpl/protocol/STObject.cpp +++ b/src/libxrpl/protocol/STObject.cpp @@ -41,7 +41,8 @@ namespace xrpl { -STObject::STObject(STObject&& other) : STBase(other.getFName()), v_(std::move(other.v_)), mType(other.mType) +STObject::STObject(STObject&& other) + : STBase(other.getFName()), v_(std::move(other.v_)), mType(other.mType) { } @@ -61,7 +62,8 @@ STObject::STObject(SOTemplate const& type, SerialIter& sit, SField const& name) applyTemplate(type); // May throw } -STObject::STObject(SerialIter& sit, SField const& name, int depth) noexcept(false) : STBase(name), mType(nullptr) +STObject::STObject(SerialIter& sit, SField const& name, int depth) noexcept(false) + : STBase(name), mType(nullptr) { if (depth > 10) Throw("Maximum nesting depth of STObject exceeded"); @@ -83,7 +85,8 @@ STObject::makeInnerObject(SField const& name) if (!rules || (rules->enabled(fixInnerObjTemplate) && isAMMObj) || (rules->enabled(fixInnerObjTemplate2) && !isAMMObj)) { - if (SOTemplate const* elements = InnerObjectFormats::getInstance().findSOTemplateBySField(name)) + if (SOTemplate const* elements = + InnerObjectFormats::getInstance().findSOTemplateBySField(name)) obj.set(*elements); } return obj; @@ -160,8 +163,9 @@ STObject::applyTemplate(SOTemplate const& type) v.reserve(type.size()); for (auto const& e : type) { - auto const iter = std::find_if( - v_.begin(), v_.end(), [&](detail::STVar const& b) { return b.get().getFName() == e.sField(); }); + auto const iter = std::find_if(v_.begin(), v_.end(), [&](detail::STVar const& b) { + return b.get().getFName() == e.sField(); + }); if (iter != v_.end()) { if ((e.style() == soeDEFAULT) && iter->get().isDefault()) @@ -236,7 +240,8 @@ STObject::set(SerialIter& sit, int depth) if (fn.isInvalid()) { - JLOG(debugLog().error()) << "Unknown field: field_type=" << type << ", field_name=" << field; + JLOG(debugLog().error()) + << "Unknown field: field_type=" << type << ", field_name=" << field; Throw("Unknown field"); } @@ -252,9 +257,10 @@ STObject::set(SerialIter& sit, int depth) // duplicate fields. This is a key invariant: auto const sf = getSortedFields(*this, withAllFields); - auto const dup = std::adjacent_find(sf.cbegin(), sf.cend(), [](STBase const* lhs, STBase const* rhs) { - return lhs->getFName() == rhs->getFName(); - }); + auto const dup = + std::adjacent_find(sf.cbegin(), sf.cend(), [](STBase const* lhs, STBase const* rhs) { + return lhs->getFName() == rhs->getFName(); + }); if (dup != sf.cend()) Throw("Duplicate field detected"); @@ -333,17 +339,19 @@ STObject::isEquivalent(STBase const& t) const if (mType != nullptr && v->mType == mType) { - return std::equal(begin(), end(), v->begin(), v->end(), [](STBase const& st1, STBase const& st2) { - return (st1.getSType() == st2.getSType()) && st1.isEquivalent(st2); - }); + return std::equal( + begin(), end(), v->begin(), v->end(), [](STBase const& st1, STBase const& st2) { + return (st1.getSType() == st2.getSType()) && st1.isEquivalent(st2); + }); } auto const sf1 = getSortedFields(*this, withAllFields); auto const sf2 = getSortedFields(*v, withAllFields); - return std::equal(sf1.begin(), sf1.end(), sf2.begin(), sf2.end(), [](STBase const* st1, STBase const* st2) { - return (st1->getSType() == st2->getSType()) && st1->isEquivalent(*st2); - }); + return std::equal( + sf1.begin(), sf1.end(), sf2.begin(), sf2.end(), [](STBase const* st1, STBase const* st2) { + return (st1->getSType() == st2->getSType()) && st1->isEquivalent(*st2); + }); } uint256 diff --git a/src/libxrpl/protocol/STParsedJSON.cpp b/src/libxrpl/protocol/STParsedJSON.cpp index 878f6c3605..d72db32282 100644 --- a/src/libxrpl/protocol/STParsedJSON.cpp +++ b/src/libxrpl/protocol/STParsedJSON.cpp @@ -75,7 +75,8 @@ make_name(std::string const& object, std::string const& field) static inline Json::Value not_an_object(std::string const& object, std::string const& field) { - return RPC::make_error(rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' is not a JSON object."); + return RPC::make_error( + rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' is not a JSON object."); } static inline Json::Value @@ -93,25 +94,29 @@ not_an_array(std::string const& object) static inline Json::Value unknown_field(std::string const& object, std::string const& field) { - return RPC::make_error(rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' is unknown."); + return RPC::make_error( + rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' is unknown."); } static inline Json::Value out_of_range(std::string const& object, std::string const& field) { - return RPC::make_error(rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' is out of range."); + return RPC::make_error( + rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' is out of range."); } static inline Json::Value bad_type(std::string const& object, std::string const& field) { - return RPC::make_error(rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' has bad type."); + return RPC::make_error( + rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' has bad type."); } static inline Json::Value invalid_data(std::string const& object, std::string const& field) { - return RPC::make_error(rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' has invalid data."); + return RPC::make_error( + rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' has invalid data."); } static inline Json::Value @@ -123,19 +128,22 @@ invalid_data(std::string const& object) static inline Json::Value array_expected(std::string const& object, std::string const& field) { - return RPC::make_error(rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' must be a JSON array."); + return RPC::make_error( + rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' must be a JSON array."); } static inline Json::Value string_expected(std::string const& object, std::string const& field) { - return RPC::make_error(rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' must be a string."); + return RPC::make_error( + rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' must be a string."); } static inline Json::Value too_deep(std::string const& object) { - return RPC::make_error(rpcINVALID_PARAMS, "Field '" + object + "' exceeds nesting depth limit."); + return RPC::make_error( + rpcINVALID_PARAMS, "Field '" + object + "' exceeds nesting depth limit."); } static inline Json::Value @@ -143,14 +151,16 @@ singleton_expected(std::string const& object, unsigned int index) { return RPC::make_error( rpcINVALID_PARAMS, - "Field '" + object + "[" + std::to_string(index) + "]' must be an object with a single key/object value."); + "Field '" + object + "[" + std::to_string(index) + + "]' must be an object with a single key/object value."); } static inline Json::Value template_mismatch(SField const& sField) { return RPC::make_error( - rpcINVALID_PARAMS, "Object '" + sField.getName() + "' contents did not meet requirements for that type."); + rpcINVALID_PARAMS, + "Object '" + sField.getName() + "' contents did not meet requirements for that type."); } static inline Json::Value @@ -180,15 +190,19 @@ parseUnsigned( if (value.isString()) { ret = detail::make_stvar( - field, safe_cast(beast::lexicalCastThrow(value.asString()))); + field, + safe_cast( + beast::lexicalCastThrow(value.asString()))); } else if (value.isInt()) { - ret = detail::make_stvar(field, to_unsigned(value.asInt())); + ret = detail::make_stvar( + field, to_unsigned(value.asInt())); } else if (value.isUInt()) { - ret = detail::make_stvar(field, to_unsigned(value.asUInt())); + ret = detail::make_stvar( + field, to_unsigned(value.asUInt())); } else { @@ -229,8 +243,8 @@ parseUint16( { ret = detail::make_stvar( field, - safe_cast( - static_cast(TxFormats::getInstance().findTypeByName(strValue)))); + safe_cast(static_cast( + TxFormats::getInstance().findTypeByName(strValue)))); if (*name == sfGeneric) name = &sfTransaction; @@ -239,8 +253,8 @@ parseUint16( { ret = detail::make_stvar( field, - safe_cast( - static_cast(LedgerFormats::getInstance().findTypeByName(strValue)))); + safe_cast(static_cast( + LedgerFormats::getInstance().findTypeByName(strValue)))); if (*name == sfGeneric) name = &sfLedgerEntry; @@ -253,7 +267,8 @@ parseUint16( } } if (!ret) - return parseUnsigned(field, json_name, fieldName, name, value, error); + return parseUnsigned( + field, json_name, fieldName, name, value, error); } catch (std::exception const&) { @@ -283,7 +298,8 @@ parseUint32( if (field == sfPermissionValue) { std::string const strValue = value.asString(); - auto const granularPermission = Permission::getInstance().getGranularValue(strValue); + auto const granularPermission = + Permission::getInstance().getGranularValue(strValue); if (granularPermission) { ret = detail::make_stvar(field, *granularPermission); @@ -291,18 +307,21 @@ parseUint32( else { auto const& txType = TxFormats::getInstance().findTypeByName(strValue); - ret = detail::make_stvar(field, Permission::getInstance().txToPermissionType(txType)); + ret = detail::make_stvar( + field, Permission::getInstance().txToPermissionType(txType)); } } else { ret = detail::make_stvar( field, - safe_cast(beast::lexicalCastThrow(value.asString()))); + safe_cast( + beast::lexicalCastThrow(value.asString()))); } } if (!ret) - return parseUnsigned(field, json_name, fieldName, name, value, error); + return parseUnsigned( + field, json_name, fieldName, name, value, error); } catch (std::exception const&) { @@ -359,7 +378,8 @@ parseLeaf( return ret; } - ret = detail::make_stvar(field, static_cast(TERtoInt(*ter))); + ret = detail::make_stvar( + field, static_cast(TERtoInt(*ter))); } else { @@ -369,7 +389,8 @@ parseLeaf( } else { - ret = detail::make_stvar(field, beast::lexicalCastThrow(strValue)); + ret = detail::make_stvar( + field, beast::lexicalCastThrow(strValue)); } } else if (value.isInt()) @@ -380,7 +401,8 @@ parseLeaf( return ret; } - ret = detail::make_stvar(field, static_cast(value.asInt())); + ret = detail::make_stvar( + field, static_cast(value.asInt())); } else if (value.isUInt()) { @@ -390,7 +412,8 @@ parseLeaf( return ret; } - ret = detail::make_stvar(field, static_cast(value.asUInt())); + ret = detail::make_stvar( + field, static_cast(value.asUInt())); } else { @@ -431,7 +454,8 @@ parseLeaf( bool const useBase10 = field.shouldMeta(SField::sMD_BaseTen); // if the field is amount, serialize as base 10 - auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), val, useBase10 ? 10 : 16); + auto [p, ec] = std::from_chars( + str.data(), str.data() + str.size(), val, useBase10 ? 10 : 16); if (ec != std::errc() || (p != str.data() + str.size())) Throw("invalid data"); @@ -440,11 +464,13 @@ parseLeaf( } else if (value.isInt()) { - ret = detail::make_stvar(field, to_unsigned(value.asInt())); + ret = detail::make_stvar( + field, to_unsigned(value.asInt())); } else if (value.isUInt()) { - ret = detail::make_stvar(field, safe_cast(value.asUInt())); + ret = detail::make_stvar( + field, safe_cast(value.asUInt())); } else { @@ -561,7 +587,8 @@ parseLeaf( { if (value.isString()) { - ret = detail::make_stvar(field, beast::lexicalCastThrow(value.asString())); + ret = detail::make_stvar( + field, beast::lexicalCastThrow(value.asString())); } else if (value.isInt()) { @@ -574,7 +601,8 @@ parseLeaf( else if (value.isUInt()) { auto const uintValue = value.asUInt(); - if (uintValue > static_cast(std::numeric_limits::max())) + if (uintValue > + static_cast(std::numeric_limits::max())) { error = out_of_range(json_name, fieldName); return ret; @@ -883,10 +911,20 @@ static int const maxDepth = 64; // Forward declaration since parseObject() and parseArray() call each other. static std::optional -parseArray(std::string const& json_name, Json::Value const& json, SField const& inName, int depth, Json::Value& error); +parseArray( + std::string const& json_name, + Json::Value const& json, + SField const& inName, + int depth, + Json::Value& error); static std::optional -parseObject(std::string const& json_name, Json::Value const& json, SField const& inName, int depth, Json::Value& error) +parseObject( + std::string const& json_name, + Json::Value const& json, + SField const& inName, + int depth, + Json::Value& error) { if (!json.isObjectOrNull()) { @@ -931,7 +969,8 @@ parseObject(std::string const& json_name, Json::Value const& json, SField const& try { - auto ret = parseObject(json_name + "." + fieldName, value, field, depth + 1, error); + auto ret = parseObject( + json_name + "." + fieldName, value, field, depth + 1, error); if (!ret) return std::nullopt; data.emplace_back(std::move(*ret)); @@ -948,7 +987,8 @@ parseObject(std::string const& json_name, Json::Value const& json, SField const& case STI_ARRAY: try { - auto array = parseArray(json_name + "." + fieldName, value, field, depth + 1, error); + auto array = + parseArray(json_name + "." + fieldName, value, field, depth + 1, error); if (!array.has_value()) return std::nullopt; data.emplace_back(std::move(*array)); @@ -993,7 +1033,12 @@ parseObject(std::string const& json_name, Json::Value const& json, SField const& } static std::optional -parseArray(std::string const& json_name, Json::Value const& json, SField const& inName, int depth, Json::Value& error) +parseArray( + std::string const& json_name, + Json::Value const& json, + SField const& inName, + int depth, + Json::Value& error) { if (!json.isArrayOrNull()) { diff --git a/src/libxrpl/protocol/STTakesAsset.cpp b/src/libxrpl/protocol/STTakesAsset.cpp index ba57f4f2a8..fcf4ad749c 100644 --- a/src/libxrpl/protocol/STTakesAsset.cpp +++ b/src/libxrpl/protocol/STTakesAsset.cpp @@ -23,9 +23,13 @@ associateAsset(SLE& sle, Asset const& asset) // SField auto& ta = entry.downcast(); auto const style = sle.getStyle(ta.getFName()); - XRPL_ASSERT_PARTS(style != soeINVALID, "xrpl::associateAsset", "valid template element style"); + XRPL_ASSERT_PARTS( + style != soeINVALID, "xrpl::associateAsset", "valid template element style"); - XRPL_ASSERT_PARTS(style != soeDEFAULT || !ta.isDefault(), "xrpl::associateAsset", "non-default value"); + XRPL_ASSERT_PARTS( + style != soeDEFAULT || !ta.isDefault(), + "xrpl::associateAsset", + "non-default value"); ta.associateAsset(asset); // associateAsset in derived classes may change the underlying diff --git a/src/libxrpl/protocol/STTx.cpp b/src/libxrpl/protocol/STTx.cpp index 5dea8be56d..0c5e299702 100644 --- a/src/libxrpl/protocol/STTx.cpp +++ b/src/libxrpl/protocol/STTx.cpp @@ -61,7 +61,8 @@ getTxFormat(TxType type) if (format == nullptr) { Throw( - "Invalid transaction type " + std::to_string(safe_cast>(type))); + "Invalid transaction type " + + std::to_string(safe_cast>(type))); } return format; @@ -242,7 +243,8 @@ STTx::checkSign(Rules const& rules, STObject const& sigObject) const // multi-signing. Otherwise we're single-signing. Blob const& signingPubKey = sigObject.getFieldVL(sfSigningPubKey); - return signingPubKey.empty() ? checkMultiSign(rules, sigObject) : checkSingleSign(sigObject); + return signingPubKey.empty() ? checkMultiSign(rules, sigObject) + : checkSingleSign(sigObject); } catch (std::exception const&) { @@ -280,8 +282,8 @@ STTx::checkBatchSign(Rules const& rules) const for (auto const& signer : signers) { Blob const& signingPubKey = signer.getFieldVL(sfSigningPubKey); - auto const result = - signingPubKey.empty() ? checkBatchMultiSign(signer, rules) : checkBatchSingleSign(signer); + auto const result = signingPubKey.empty() ? checkBatchMultiSign(signer, rules) + : checkBatchSingleSign(signer); if (!result) return result; @@ -354,7 +356,11 @@ STTx::getMetaSQL(std::uint32_t inLedger, std::string const& escapedMetaData) con // VFALCO This could be a free function elsewhere std::string -STTx::getMetaSQL(Serializer rawTxn, std::uint32_t inLedger, char status, std::string const& escapedMetaData) const +STTx::getMetaSQL( + Serializer rawTxn, + std::uint32_t inLedger, + char status, + std::string const& escapedMetaData) const { static boost::format bfTrans("('%s', '%s', '%s', '%d', '%d', '%c', %s, %s)"); std::string rTxn = sqlBlobLiteral(rawTxn.peekData()); @@ -363,8 +369,9 @@ STTx::getMetaSQL(Serializer rawTxn, std::uint32_t inLedger, char status, std::st XRPL_ASSERT(format, "xrpl::STTx::getMetaSQL : non-null type format"); return str( - boost::format(bfTrans) % to_string(getTransactionID()) % format->getName() % toBase58(getAccountID(sfAccount)) % - getFieldU32(sfSequence) % inLedger % status % rTxn % escapedMetaData); + boost::format(bfTrans) % to_string(getTransactionID()) % format->getName() % + toBase58(getAccountID(sfAccount)) % getFieldU32(sfSequence) % inLedger % status % rTxn % + escapedMetaData); } static Expected @@ -468,7 +475,8 @@ multiSignHelper( if (publicKeyType(makeSlice(spk))) { Blob const signature = signer.getFieldVL(sfTxnSignature); - validSig = verify(PublicKey(makeSlice(spk)), makeMsg(accountID).slice(), makeSlice(signature)); + validSig = verify( + PublicKey(makeSlice(spk)), makeMsg(accountID).slice(), makeSlice(signature)); } } catch (std::exception const& e) @@ -479,7 +487,8 @@ multiSignHelper( } if (!validSig) return Unexpected( - std::string("Invalid signature on account ") + toBase58(accountID) + errorWhat.value_or("") + "."); + std::string("Invalid signature on account ") + toBase58(accountID) + + errorWhat.value_or("") + "."); } // All signatures verified. return {}; @@ -509,7 +518,8 @@ 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. - auto const txnAccountID = &sigObject != this ? std::nullopt : std::optional(getAccountID(sfAccount)); + auto const txnAccountID = + &sigObject != this ? std::nullopt : std::optional(getAccountID(sfAccount)); // We can ease the computational load inside the loop a bit by // pre-constructing part of the data that we hash. Fill a Serializer @@ -545,7 +555,9 @@ std::vector const& STTx::getBatchTransactionIDs() const { XRPL_ASSERT(getTxnType() == ttBATCH, "STTx::getBatchTransactionIDs : not a batch transaction"); - XRPL_ASSERT(getFieldArray(sfRawTransactions).size() != 0, "STTx::getBatchTransactionIDs : empty raw transactions"); + XRPL_ASSERT( + getFieldArray(sfRawTransactions).size() != 0, + "STTx::getBatchTransactionIDs : empty raw transactions"); // The list of inner ids is built once, then reused on subsequent calls. // After the list is built, it must always have the same size as the array @@ -681,8 +693,10 @@ invalidMPTAmountInTx(STObject const& tx) if (tx.isFieldPresent(e.sField()) && e.supportMPT() != soeMPTNone) { if (auto const& field = tx.peekAtField(e.sField()); - (field.getSType() == STI_AMOUNT && static_cast(field).holds()) || - (field.getSType() == STI_ISSUE && static_cast(field).holds())) + (field.getSType() == STI_AMOUNT && + static_cast(field).holds()) || + (field.getSType() == STI_ISSUE && + static_cast(field).holds())) { if (e.supportMPT() != soeMPTSupported) return true; @@ -699,7 +713,8 @@ isRawTransactionOkay(STObject const& st, std::string& reason) if (!st.isFieldPresent(sfRawTransactions)) return true; - if (st.isFieldPresent(sfBatchSigners) && st.getFieldArray(sfBatchSigners).size() > maxBatchTxCount) + if (st.isFieldPresent(sfBatchSigners) && + st.getFieldArray(sfBatchSigners).size() > maxBatchTxCount) { reason = "Batch Signers array exceeds max entries."; return false; diff --git a/src/libxrpl/protocol/STValidation.cpp b/src/libxrpl/protocol/STValidation.cpp index 2bea078809..f6f89d43e9 100644 --- a/src/libxrpl/protocol/STValidation.cpp +++ b/src/libxrpl/protocol/STValidation.cpp @@ -100,10 +100,14 @@ STValidation::isValid() const noexcept if (!valid_) { XRPL_ASSERT( - publicKeyType(getSignerPublic()) == KeyType::secp256k1, "xrpl::STValidation::isValid : valid key type"); + publicKeyType(getSignerPublic()) == KeyType::secp256k1, + "xrpl::STValidation::isValid : valid key type"); valid_ = verifyDigest( - getSignerPublic(), getSigningHash(), makeSlice(getFieldVL(sfSignature)), getFlags() & vfFullyCanonicalSig); + getSignerPublic(), + getSigningHash(), + makeSlice(getFieldVL(sfSignature)), + getFlags() & vfFullyCanonicalSig); } return valid_.value(); diff --git a/src/libxrpl/protocol/STVar.cpp b/src/libxrpl/protocol/STVar.cpp index d77aabc312..994077da56 100644 --- a/src/libxrpl/protocol/STVar.cpp +++ b/src/libxrpl/protocol/STVar.cpp @@ -133,7 +133,9 @@ STVar::constructST(SerializedTypeID id, int depth, Args&&... args) { construct(std::forward(args)...); } - else if constexpr (std::is_same_v...>, std::tuple>) + else if constexpr (std::is_same_v< + std::tuple...>, + std::tuple>) { construct(std::forward(args)..., depth); } diff --git a/src/libxrpl/protocol/STVector256.cpp b/src/libxrpl/protocol/STVector256.cpp index 312184dcc0..886fed5d2d 100644 --- a/src/libxrpl/protocol/STVector256.cpp +++ b/src/libxrpl/protocol/STVector256.cpp @@ -19,7 +19,8 @@ STVector256::STVector256(SerialIter& sit, SField const& name) : STBase(name) auto const slice = sit.getSlice(sit.getVLDataLength()); if (slice.size() % uint256::size() != 0) - Throw("Bad serialization for STVector256: " + std::to_string(slice.size())); + Throw( + "Bad serialization for STVector256: " + std::to_string(slice.size())); auto const cnt = slice.size() / uint256::size(); diff --git a/src/libxrpl/protocol/STXChainBridge.cpp b/src/libxrpl/protocol/STXChainBridge.cpp index ed79c28f29..85d36f9b46 100644 --- a/src/libxrpl/protocol/STXChainBridge.cpp +++ b/src/libxrpl/protocol/STXChainBridge.cpp @@ -58,7 +58,8 @@ STXChainBridge::STXChainBridge(SField const& name, Json::Value const& v) : STBas { if (!v.isObject()) { - Throw("STXChainBridge can only be specified with a 'object' Json value"); + Throw( + "STXChainBridge can only be specified with a 'object' Json value"); } auto checkExtra = [](Json::Value const& v) { @@ -172,8 +173,8 @@ STXChainBridge::isEquivalent(STBase const& t) const bool STXChainBridge::isDefault() const { - return lockingChainDoor_.isDefault() && lockingChainIssue_.isDefault() && issuingChainDoor_.isDefault() && - issuingChainIssue_.isDefault(); + return lockingChainDoor_.isDefault() && lockingChainIssue_.isDefault() && + issuingChainDoor_.isDefault() && issuingChainIssue_.isDefault(); } std::unique_ptr diff --git a/src/libxrpl/protocol/SecretKey.cpp b/src/libxrpl/protocol/SecretKey.cpp index ee112b9072..4f0963e72d 100644 --- a/src/libxrpl/protocol/SecretKey.cpp +++ b/src/libxrpl/protocol/SecretKey.cpp @@ -254,7 +254,8 @@ sign(PublicKey const& pk, SecretKey const& sk, Slice const& m) unsigned char sig[72]; size_t len = sizeof(sig); - if (secp256k1_ecdsa_signature_serialize_der(secp256k1Context(), sig, &len, &sig_imp) != 1) + if (secp256k1_ecdsa_signature_serialize_der(secp256k1Context(), sig, &len, &sig_imp) != + 1) LogicError("sign: secp256k1_ecdsa_signature_serialize_der failed"); return Buffer{sig, len}; @@ -304,13 +305,15 @@ derivePublicKey(KeyType type, SecretKey const& sk) case KeyType::secp256k1: { secp256k1_pubkey pubkey_imp; if (secp256k1_ec_pubkey_create( - secp256k1Context(), &pubkey_imp, reinterpret_cast(sk.data())) != 1) + secp256k1Context(), + &pubkey_imp, + reinterpret_cast(sk.data())) != 1) LogicError("derivePublicKey: secp256k1_ec_pubkey_create failed"); unsigned char pubkey[33]; std::size_t len = sizeof(pubkey); - if (secp256k1_ec_pubkey_serialize(secp256k1Context(), pubkey, &len, &pubkey_imp, SECP256K1_EC_COMPRESSED) != - 1) + if (secp256k1_ec_pubkey_serialize( + secp256k1Context(), pubkey, &len, &pubkey_imp, SECP256K1_EC_COMPRESSED) != 1) LogicError("derivePublicKey: secp256k1_ec_pubkey_serialize failed"); return PublicKey{Slice{pubkey, len}}; diff --git a/src/libxrpl/protocol/Seed.cpp b/src/libxrpl/protocol/Seed.cpp index 2629d08439..0e0bb7fb2b 100644 --- a/src/libxrpl/protocol/Seed.cpp +++ b/src/libxrpl/protocol/Seed.cpp @@ -81,7 +81,8 @@ parseGenericSeed(std::string const& str, bool rfc1751) return std::nullopt; if (parseBase58(str) || parseBase58(TokenType::NodePublic, str) || - parseBase58(TokenType::AccountPublic, str) || parseBase58(TokenType::NodePrivate, str) || + parseBase58(TokenType::AccountPublic, str) || + parseBase58(TokenType::NodePrivate, str) || parseBase58(TokenType::AccountSecret, str)) { return std::nullopt; diff --git a/src/libxrpl/protocol/Serializer.cpp b/src/libxrpl/protocol/Serializer.cpp index bb3eb17ae3..483e6b516f 100644 --- a/src/libxrpl/protocol/Serializer.cpp +++ b/src/libxrpl/protocol/Serializer.cpp @@ -107,7 +107,8 @@ Serializer::addFieldID(int type, int name) { int ret = mData.size(); XRPL_ASSERT( - (type > 0) && (type < 256) && (name > 0) && (name < 256), "xrpl::Serializer::addFieldID : inputs inside range"); + (type > 0) && (type < 256) && (name > 0) && (name < 256), + "xrpl::Serializer::addFieldID : inputs inside range"); if (type < 16) { @@ -366,7 +367,8 @@ SerialIter::get32() p_ += 4; used_ += 4; remain_ -= 4; - return (std::uint64_t(t[0]) << 24) + (std::uint64_t(t[1]) << 16) + (std::uint64_t(t[2]) << 8) + std::uint64_t(t[3]); + return (std::uint64_t(t[0]) << 24) + (std::uint64_t(t[1]) << 16) + (std::uint64_t(t[2]) << 8) + + std::uint64_t(t[3]); } std::uint64_t diff --git a/src/libxrpl/protocol/Sign.cpp b/src/libxrpl/protocol/Sign.cpp index fe18941940..9105be8294 100644 --- a/src/libxrpl/protocol/Sign.cpp +++ b/src/libxrpl/protocol/Sign.cpp @@ -12,7 +12,12 @@ namespace xrpl { void -sign(STObject& st, HashPrefix const& prefix, KeyType type, SecretKey const& sk, SF_VL const& sigField) +sign( + STObject& st, + HashPrefix const& prefix, + KeyType type, + SecretKey const& sk, + SF_VL const& sigField) { Serializer ss; ss.add32(prefix); diff --git a/src/libxrpl/protocol/TER.cpp b/src/libxrpl/protocol/TER.cpp index 723bbae505..5d732a5876 100644 --- a/src/libxrpl/protocol/TER.cpp +++ b/src/libxrpl/protocol/TER.cpp @@ -263,9 +263,10 @@ transCode(std::string const& token) static auto const results = [] { auto& byTer = transResults(); auto range = boost::make_iterator_range(byTer.begin(), byTer.end()); - auto tRange = - boost::adaptors::transform(range, [](auto const& r) { return std::make_pair(r.second.first, r.first); }); - std::unordered_map const byToken(tRange.begin(), tRange.end()); + auto tRange = boost::adaptors::transform( + range, [](auto const& r) { return std::make_pair(r.second.first, r.first); }); + std::unordered_map const byToken( + tRange.begin(), tRange.end()); return byToken; }(); diff --git a/src/libxrpl/protocol/TxMeta.cpp b/src/libxrpl/protocol/TxMeta.cpp index 62e62a9b5c..f4932b2af4 100644 --- a/src/libxrpl/protocol/TxMeta.cpp +++ b/src/libxrpl/protocol/TxMeta.cpp @@ -89,7 +89,8 @@ TxMeta::getAffectedAccounts() const // Meta#getAffectedAccounts for (auto const& node : nodes_) { - int index = node.getFieldIndex((node.getFName() == sfCreatedNode) ? sfNewFields : sfFinalFields); + int index = + node.getFieldIndex((node.getFName() == sfCreatedNode) ? sfNewFields : sfFinalFields); if (index != -1) { @@ -154,7 +155,8 @@ TxMeta::getAffectedNode(SLE::ref node, SField const& type) nodes_.push_back(STObject(type)); STObject& obj = nodes_.back(); - XRPL_ASSERT(obj.getFName() == type, "xrpl::TxMeta::getAffectedNode(SLE::ref) : field type match"); + XRPL_ASSERT( + obj.getFName() == type, "xrpl::TxMeta::getAffectedNode(SLE::ref) : field type match"); obj.setFieldH256(sfLedgerIndex, index); obj.setFieldU16(sfLedgerEntryType, node->getFieldU16(sfLedgerEntryType)); @@ -198,7 +200,9 @@ TxMeta::addRaw(Serializer& s, TER result, std::uint32_t index) { result_ = TERtoInt(result); index_ = index; - XRPL_ASSERT((result_ == 0) || ((result_ > 100) && (result_ <= 255)), "xrpl::TxMeta::addRaw : valid TER input"); + XRPL_ASSERT( + (result_ == 0) || ((result_ > 100) && (result_ <= 255)), + "xrpl::TxMeta::addRaw : valid TER input"); nodes_.sort([](STObject const& o1, STObject const& o2) { return o1.getFieldH256(sfLedgerIndex) < o2.getFieldH256(sfLedgerIndex); diff --git a/src/libxrpl/protocol/UintTypes.cpp b/src/libxrpl/protocol/UintTypes.cpp index ca29147989..df9eadb511 100644 --- a/src/libxrpl/protocol/UintTypes.cpp +++ b/src/libxrpl/protocol/UintTypes.cpp @@ -45,11 +45,13 @@ to_string(Currency const& currency) if ((currency & sIsoBits).isZero()) { std::string const iso( - currency.data() + detail::isoCodeOffset, currency.data() + detail::isoCodeOffset + detail::isoCodeLength); + currency.data() + detail::isoCodeOffset, + currency.data() + detail::isoCodeOffset + detail::isoCodeLength); // Specifying the system currency code using ISO-style representation // is not allowed. - if ((iso != systemCurrencyCode()) && (iso.find_first_not_of(detail::isoCharSet) == std::string::npos)) + if ((iso != systemCurrencyCode()) && + (iso.find_first_not_of(detail::isoCharSet) == std::string::npos)) { return iso; } diff --git a/src/libxrpl/protocol/XChainAttestations.cpp b/src/libxrpl/protocol/XChainAttestations.cpp index 5f109ea272..314bf9f6d3 100644 --- a/src/libxrpl/protocol/XChainAttestations.cpp +++ b/src/libxrpl/protocol/XChainAttestations.cpp @@ -227,13 +227,15 @@ AttestationClaim::validAmounts() const bool AttestationClaim::sameEvent(AttestationClaim const& rhs) const { - return AttestationClaim::sameEventHelper(*this, rhs) && tie(claimID, dst) == tie(rhs.claimID, rhs.dst); + return AttestationClaim::sameEventHelper(*this, rhs) && + tie(claimID, dst) == tie(rhs.claimID, rhs.dst); } bool operator==(AttestationClaim const& lhs, AttestationClaim const& rhs) { - return AttestationClaim::equalHelper(lhs, rhs) && tie(lhs.claimID, lhs.dst) == tie(rhs.claimID, rhs.dst); + return AttestationClaim::equalHelper(lhs, rhs) && + tie(lhs.claimID, lhs.dst) == tie(rhs.claimID, rhs.dst); } AttestationCreateAccount::AttestationCreateAccount(STObject const& o) @@ -350,7 +352,14 @@ std::vector AttestationCreateAccount::message(STXChainBridge const& bridge) const { return AttestationCreateAccount::message( - bridge, sendingAccount, sendingAmount, rewardAmount, rewardAccount, wasLockingChainSend, createCount, toCreate); + bridge, + sendingAccount, + sendingAmount, + rewardAmount, + rewardAccount, + wasLockingChainSend, + createCount, + toCreate); } bool @@ -363,7 +372,8 @@ bool AttestationCreateAccount::sameEvent(AttestationCreateAccount const& rhs) const { return AttestationCreateAccount::sameEventHelper(*this, rhs) && - std::tie(createCount, toCreate, rewardAmount) == std::tie(rhs.createCount, rhs.toCreate, rhs.rewardAmount); + std::tie(createCount, toCreate, rewardAmount) == + std::tie(rhs.createCount, rhs.toCreate, rhs.rewardAmount); } bool @@ -434,7 +444,8 @@ XChainClaimAttestation::XChainClaimAttestation(Json::Value const& v) dst = Json::getOrThrow(v, sfDestination); }; -XChainClaimAttestation::XChainClaimAttestation(XChainClaimAttestation::TSignedAttestation const& claimAtt) +XChainClaimAttestation::XChainClaimAttestation( + XChainClaimAttestation::TSignedAttestation const& claimAtt) : XChainClaimAttestation{ claimAtt.attestationSignerAccount, claimAtt.publicKey, @@ -462,11 +473,24 @@ XChainClaimAttestation::toSTObject() const bool operator==(XChainClaimAttestation const& lhs, XChainClaimAttestation const& rhs) { - return std::tie(lhs.keyAccount, lhs.publicKey, lhs.amount, lhs.rewardAccount, lhs.wasLockingChainSend, lhs.dst) == - std::tie(rhs.keyAccount, rhs.publicKey, rhs.amount, rhs.rewardAccount, rhs.wasLockingChainSend, rhs.dst); + return std::tie( + lhs.keyAccount, + lhs.publicKey, + lhs.amount, + lhs.rewardAccount, + lhs.wasLockingChainSend, + lhs.dst) == + std::tie( + rhs.keyAccount, + rhs.publicKey, + rhs.amount, + rhs.rewardAccount, + rhs.wasLockingChainSend, + rhs.dst); } -XChainClaimAttestation::MatchFields::MatchFields(XChainClaimAttestation::TSignedAttestation const& att) +XChainClaimAttestation::MatchFields::MatchFields( + XChainClaimAttestation::TSignedAttestation const& att) : amount{att.sendingAmount}, wasLockingChainSend{att.wasLockingChainSend}, dst{att.dst} { } @@ -552,7 +576,8 @@ XChainCreateAccountAttestation::toSTObject() const return o; } -XChainCreateAccountAttestation::MatchFields::MatchFields(XChainCreateAccountAttestation::TSignedAttestation const& att) +XChainCreateAccountAttestation::MatchFields::MatchFields( + XChainCreateAccountAttestation::TSignedAttestation const& att) : amount{att.sendingAmount} , rewardAmount(att.rewardAmount) , wasLockingChainSend{att.wasLockingChainSend} @@ -595,7 +620,8 @@ operator==(XChainCreateAccountAttestation const& lhs, XChainCreateAccountAttesta //------------------------------------------------------------------------------ // template -XChainAttestationsBase::XChainAttestationsBase(XChainAttestationsBase::AttCollection&& atts) +XChainAttestationsBase::XChainAttestationsBase( + XChainAttestationsBase::AttCollection&& atts) : attestations_{std::move(atts)} { } diff --git a/src/libxrpl/protocol/digest.cpp b/src/libxrpl/protocol/digest.cpp index aa5600dde0..0e03882c3c 100644 --- a/src/libxrpl/protocol/digest.cpp +++ b/src/libxrpl/protocol/digest.cpp @@ -21,7 +21,8 @@ openssl_ripemd160_hasher::operator()(void const* data, std::size_t size) noexcep RIPEMD160_Update(ctx, data, size); } -openssl_ripemd160_hasher::operator result_type() noexcept +openssl_ripemd160_hasher:: +operator result_type() noexcept { auto const ctx = reinterpret_cast(ctx_); result_type digest; @@ -45,7 +46,8 @@ openssl_sha512_hasher::operator()(void const* data, std::size_t size) noexcept SHA512_Update(ctx, data, size); } -openssl_sha512_hasher::operator result_type() noexcept +openssl_sha512_hasher:: +operator result_type() noexcept { auto const ctx = reinterpret_cast(ctx_); result_type digest; @@ -69,7 +71,8 @@ openssl_sha256_hasher::operator()(void const* data, std::size_t size) noexcept SHA256_Update(ctx, data, size); } -openssl_sha256_hasher::operator result_type() noexcept +openssl_sha256_hasher:: +operator result_type() noexcept { auto const ctx = reinterpret_cast(ctx_); result_type digest; diff --git a/src/libxrpl/protocol/tokens.cpp b/src/libxrpl/protocol/tokens.cpp index 1b73b06380..867c69a802 100644 --- a/src/libxrpl/protocol/tokens.cpp +++ b/src/libxrpl/protocol/tokens.cpp @@ -121,7 +121,8 @@ coefficients sizes greatly speeds up the multi-precision computations. namespace xrpl { -static constexpr char const* alphabetForward = "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"; +static constexpr char const* alphabetForward = + "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"; static constexpr std::array const alphabetReverse = []() { std::array map{}; @@ -412,8 +413,8 @@ b256_to_b58_be(std::span input, std::span out) // compute the base 58^10 coeffs while (cur_2_64_end > 0) { - base_58_10_coeff[num_58_10_coeffs] = - xrpl::b58_fast::detail::inplace_bigint_div_rem(base_2_64_coeff.subspan(0, cur_2_64_end), B_58_10); + base_58_10_coeff[num_58_10_coeffs] = xrpl::b58_fast::detail::inplace_bigint_div_rem( + base_2_64_coeff.subspan(0, cur_2_64_end), B_58_10); num_58_10_coeffs += 1; if (base_2_64_coeff[cur_2_64_end - 1] == 0) { @@ -441,7 +442,8 @@ b256_to_b58_be(std::span input, std::span out) { return Unexpected(TokenCodecErrc::inputTooLarge); } - std::array const b58_be = xrpl::b58_fast::detail::b58_10_to_b58_be(base_58_10_coeff[i]); + std::array const b58_be = + xrpl::b58_fast::detail::b58_10_to_b58_be(base_58_10_coeff[i]); std::size_t to_skip = 0; std::span b58_be_s{b58_be.data(), b58_be.size()}; if (skip_zeros) @@ -502,7 +504,9 @@ b58_to_b256_be(std::string_view input, std::span out) auto [num_full_coeffs, partial_coeff_len] = xrpl::b58_fast::detail::div_rem(input.size(), 10); auto const num_partial_coeffs = partial_coeff_len ? 1 : 0; auto const num_b_58_10_coeffs = num_full_coeffs + num_partial_coeffs; - XRPL_ASSERT(num_b_58_10_coeffs <= b_58_10_coeff.size(), "xrpl::b58_fast::detail::b58_to_b256_be : maximum coeff"); + XRPL_ASSERT( + num_b_58_10_coeffs <= b_58_10_coeff.size(), + "xrpl::b58_fast::detail::b58_to_b256_be : maximum coeff"); for (unsigned char c : input.substr(0, partial_coeff_len)) { auto cur_val = ::xrpl::alphabetReverse[c]; @@ -539,14 +543,16 @@ b58_to_b256_be(std::string_view input, std::span out) std::uint64_t const c = b_58_10_coeff[i]; { - auto code = xrpl::b58_fast::detail::inplace_bigint_mul(std::span(&result[0], cur_result_size + 1), B_58_10); + auto code = xrpl::b58_fast::detail::inplace_bigint_mul( + std::span(&result[0], cur_result_size + 1), B_58_10); if (code != TokenCodecErrc::success) { return Unexpected(code); } } { - auto code = xrpl::b58_fast::detail::inplace_bigint_add(std::span(&result[0], cur_result_size + 1), c); + auto code = xrpl::b58_fast::detail::inplace_bigint_add( + std::span(&result[0], cur_result_size + 1), c); if (code != TokenCodecErrc::success) { return Unexpected(code); @@ -598,7 +604,10 @@ b58_to_b256_be(std::string_view input, std::span out) } // namespace detail B58Result> -encodeBase58Token(TokenType token_type, std::span input, std::span out) +encodeBase58Token( + TokenType token_type, + std::span input, + std::span out) { constexpr std::size_t tmpBufSize = 128; std::array buf; diff --git a/src/libxrpl/rdb/SociDB.cpp b/src/libxrpl/rdb/SociDB.cpp index 2f8c5f1ac6..3ba0d4c980 100644 --- a/src/libxrpl/rdb/SociDB.cpp +++ b/src/libxrpl/rdb/SociDB.cpp @@ -25,7 +25,8 @@ getSociSqliteInit(std::string const& name, std::string const& dir, std::string c { if (name.empty()) { - Throw("Sqlite databases must specify a dir and a name. Name: " + name + " Dir: " + dir); + Throw( + "Sqlite databases must specify a dir and a name. Name: " + name + " Dir: " + dir); } boost::filesystem::path file(dir); if (is_directory(file)) @@ -53,7 +54,8 @@ DBConfig::DBConfig(std::string const& dbPath) : connectionString_(dbPath) { } -DBConfig::DBConfig(BasicConfig const& config, std::string const& dbName) : DBConfig(detail::getSociInit(config, dbName)) +DBConfig::DBConfig(BasicConfig const& config, std::string const& dbName) + : DBConfig(detail::getSociInit(config, dbName)) { } @@ -169,7 +171,11 @@ namespace { class WALCheckpointer : public Checkpointer { public: - WALCheckpointer(std::uintptr_t id, std::weak_ptr session, JobQueue& q, Logs& logs) + WALCheckpointer( + std::uintptr_t id, + std::weak_ptr session, + JobQueue& q, + Logs& logs) : id_(id), session_(std::move(session)), jobQueue_(q), j_(logs.journal("WALCheckpointer")) { if (auto [conn, keepAlive] = getConnection(); conn) @@ -285,7 +291,11 @@ protected: } // namespace std::shared_ptr -makeCheckpointer(std::uintptr_t id, std::weak_ptr session, JobQueue& queue, Logs& logs) +makeCheckpointer( + std::uintptr_t id, + std::weak_ptr session, + JobQueue& queue, + Logs& logs) { return std::make_shared(id, std::move(session), queue, logs); } diff --git a/src/libxrpl/resource/ResourceManager.cpp b/src/libxrpl/resource/ResourceManager.cpp index 787ceff768..1e7aadfa8d 100644 --- a/src/libxrpl/resource/ResourceManager.cpp +++ b/src/libxrpl/resource/ResourceManager.cpp @@ -64,7 +64,10 @@ public: } Consumer - newInboundEndpoint(beast::IP::Endpoint const& address, bool const proxy, std::string_view forwardedFor) override + newInboundEndpoint( + beast::IP::Endpoint const& address, + bool const proxy, + std::string_view forwardedFor) override { if (!proxy) return newInboundEndpoint(address); @@ -73,7 +76,8 @@ public: auto const proxiedIp = boost::asio::ip::make_address(forwardedFor, ec); if (ec) { - journal_.warn() << "forwarded for (" << forwardedFor << ") from proxy " << address.to_string() + journal_.warn() << "forwarded for (" << forwardedFor << ") from proxy " + << address.to_string() << " doesn't convert to IP endpoint: " << ec.message(); return newInboundEndpoint(address); } diff --git a/src/xrpld/rpc/detail/InfoSub.cpp b/src/libxrpl/server/InfoSub.cpp similarity index 95% rename from src/xrpld/rpc/detail/InfoSub.cpp rename to src/libxrpl/server/InfoSub.cpp index 27e3a65b2f..0ec432883d 100644 --- a/src/xrpld/rpc/detail/InfoSub.cpp +++ b/src/libxrpl/server/InfoSub.cpp @@ -1,4 +1,4 @@ -#include +#include namespace xrpl { @@ -17,7 +17,8 @@ InfoSub::InfoSub(Source& source) : m_source(source), mSeq(assign_id()) { } -InfoSub::InfoSub(Source& source, Consumer consumer) : m_consumer(consumer), m_source(source), mSeq(assign_id()) +InfoSub::InfoSub(Source& source, Consumer consumer) + : m_consumer(consumer), m_source(source), mSeq(assign_id()) { } diff --git a/src/libxrpl/server/JSONRPCUtil.cpp b/src/libxrpl/server/JSONRPCUtil.cpp index 634bb07850..d32a579d8d 100644 --- a/src/libxrpl/server/JSONRPCUtil.cpp +++ b/src/libxrpl/server/JSONRPCUtil.cpp @@ -19,9 +19,7 @@ getHTTPHeaderTimestamp() char buffer[96]; time_t now; time(&now); - struct tm now_gmt - { - }; + struct tm now_gmt{}; #ifndef _MSC_VER gmtime_r(&now, &now_gmt); #else diff --git a/src/xrpld/app/misc/detail/LoadFeeTrack.cpp b/src/libxrpl/server/LoadFeeTrack.cpp similarity index 98% rename from src/xrpld/app/misc/detail/LoadFeeTrack.cpp rename to src/libxrpl/server/LoadFeeTrack.cpp index 91a40c6a9d..e3867f36f5 100644 --- a/src/xrpld/app/misc/detail/LoadFeeTrack.cpp +++ b/src/libxrpl/server/LoadFeeTrack.cpp @@ -1,9 +1,8 @@ -#include - #include #include #include #include +#include #include diff --git a/src/libxrpl/server/Port.cpp b/src/libxrpl/server/Port.cpp index 389714a40f..9e73d9f007 100644 --- a/src/libxrpl/server/Port.cpp +++ b/src/libxrpl/server/Port.cpp @@ -163,7 +163,8 @@ populate( if (v4Net != v4Net.canonical()) { log << "The configured subnet " << v4Net.to_string() - << " is not the same as the network address, which is " << v4Net.canonical().to_string(); + << " is not the same as the network address, which is " + << v4Net.canonical().to_string(); Throw(); } nets4.push_back(v4Net); @@ -173,7 +174,8 @@ populate( if (v6Net != v6Net.canonical()) { log << "The configured subnet " << v6Net.to_string() - << " is not the same as the network address, which is " << v6Net.canonical().to_string(); + << " is not the same as the network address, which is " + << v6Net.canonical().to_string(); Throw(); } nets6.push_back(v6Net); @@ -181,7 +183,8 @@ populate( } catch (boost::system::system_error const& e) { - log << "Invalid value '" << ip << "' for key '" << field << "' in [" << section.name() << "]: " << e.what(); + log << "Invalid value '" << ip << "' for key '" << field << "' in [" << section.name() + << "]: " << e.what(); Throw(); } } @@ -201,7 +204,8 @@ parse_Port(ParsedPort& port, Section const& section, std::ostream& log) } catch (std::exception const&) { - log << "Invalid value '" << *optResult << "' for key 'ip' in [" << section.name() << "]"; + log << "Invalid value '" << *optResult << "' for key 'ip' in [" << section.name() + << "]"; Rethrow(); } } @@ -282,7 +286,8 @@ parse_Port(ParsedPort& port, Section const& section, std::ostream& log) } 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, "secure_gateway", log, port.secure_gateway_nets_v4, port.secure_gateway_nets_v6); set(port.user, "user", section); set(port.password, "password", section); @@ -296,8 +301,10 @@ parse_Port(ParsedPort& port, Section const& section, std::ostream& log) port.pmd_options.server_enable = section.value_or("permessage_deflate", true); port.pmd_options.client_max_window_bits = section.value_or("client_max_window_bits", 15); port.pmd_options.server_max_window_bits = section.value_or("server_max_window_bits", 15); - port.pmd_options.client_no_context_takeover = section.value_or("client_no_context_takeover", false); - port.pmd_options.server_no_context_takeover = section.value_or("server_no_context_takeover", false); + port.pmd_options.client_no_context_takeover = + section.value_or("client_no_context_takeover", false); + port.pmd_options.server_no_context_takeover = + section.value_or("server_no_context_takeover", false); port.pmd_options.compLevel = section.value_or("compress_level", 8); port.pmd_options.memLevel = section.value_or("memory_level", 4); } diff --git a/src/libxrpl/server/State.cpp b/src/libxrpl/server/State.cpp index 4e3a1584c2..f41a0c61b3 100644 --- a/src/libxrpl/server/State.cpp +++ b/src/libxrpl/server/State.cpp @@ -63,7 +63,8 @@ getCanDelete(soci::session& session) LedgerIndex setCanDelete(soci::session& session, LedgerIndex canDelete) { - session << "UPDATE CanDelete SET CanDeleteSeq = :canDelete WHERE Key = 1;", soci::use(canDelete); + session << "UPDATE CanDelete SET CanDeleteSeq = :canDelete WHERE Key = 1;", + soci::use(canDelete); return canDelete; } diff --git a/src/libxrpl/server/Wallet.cpp b/src/libxrpl/server/Wallet.cpp index 51f1326674..95c2e89a20 100644 --- a/src/libxrpl/server/Wallet.cpp +++ b/src/libxrpl/server/Wallet.cpp @@ -9,18 +9,24 @@ std::unique_ptr makeWalletDB(DatabaseCon::Setup const& setup, beast::Journal j) { // wallet database - return std::make_unique(setup, WalletDBName, std::array(), WalletDBInit, j); + return std::make_unique( + setup, WalletDBName, std::array(), WalletDBInit, j); } std::unique_ptr makeTestWalletDB(DatabaseCon::Setup const& setup, std::string const& dbname, beast::Journal j) { // wallet database - return std::make_unique(setup, dbname.data(), std::array(), WalletDBInit, j); + return std::make_unique( + setup, dbname.data(), std::array(), WalletDBInit, j); } void -getManifests(soci::session& session, std::string const& dbTable, ManifestCache& mCache, beast::Journal j) +getManifests( + soci::session& session, + std::string const& dbTable, + ManifestCache& mCache, + beast::Journal j) { // Load manifests stored in database std::string const sql = "SELECT RawData FROM " + dbTable + ";"; @@ -124,9 +130,11 @@ getNodeIdentity(soci::session& session) auto [newpublicKey, newsecretKey] = randomKeyPair(KeyType::secp256k1); session << str( - boost::format("INSERT INTO NodeIdentity (PublicKey,PrivateKey) " - "VALUES ('%s','%s');") % - toBase58(TokenType::NodePublic, newpublicKey) % toBase58(TokenType::NodePrivate, newsecretKey)); + boost::format( + "INSERT INTO NodeIdentity (PublicKey,PrivateKey) " + "VALUES ('%s','%s');") % + toBase58(TokenType::NodePublic, newpublicKey) % + toBase58(TokenType::NodePrivate, newsecretKey)); return {newpublicKey, newsecretKey}; } @@ -167,7 +175,10 @@ getPeerReservationTable(soci::session& session, beast::Journal j) } void -insertPeerReservation(soci::session& session, PublicKey const& nodeId, std::string const& description) +insertPeerReservation( + soci::session& session, + PublicKey const& nodeId, + std::string const& description) { auto const sNodeId = toBase58(TokenType::NodePublic, nodeId); session << "INSERT INTO PeerReservations (PublicKey, Description) " @@ -232,7 +243,10 @@ readAmendments( boost::optional amendment_name; boost::optional vote_to_veto; soci::statement st = - (session.prepare << sql, soci::into(amendment_hash), soci::into(amendment_name), soci::into(vote_to_veto)); + (session.prepare << sql, + soci::into(amendment_hash), + soci::into(amendment_name), + soci::into(vote_to_veto)); st.execute(); while (st.fetch()) { @@ -241,7 +255,11 @@ readAmendments( } void -voteAmendment(soci::session& session, uint256 const& amendment, std::string const& name, AmendmentVote vote) +voteAmendment( + soci::session& session, + uint256 const& amendment, + std::string const& name, + AmendmentVote vote) { soci::transaction tr(session); std::string sql = diff --git a/src/libxrpl/shamap/SHAMap.cpp b/src/libxrpl/shamap/SHAMap.cpp index e84a620b77..15457b2d2e 100644 --- a/src/libxrpl/shamap/SHAMap.cpp +++ b/src/libxrpl/shamap/SHAMap.cpp @@ -26,7 +26,8 @@ makeTypedLeaf(SHAMapNodeType type, boost::intrusive_ptr item, std::to_string(static_cast>(type))); } -SHAMap::SHAMap(SHAMapType t, Family& f) : f_(f), journal_(f.journal()), state_(SHAMapState::Modifying), type_(t) +SHAMap::SHAMap(SHAMapType t, Family& f) + : f_(f), journal_(f.journal()), state_(SHAMapState::Modifying), type_(t) { root_ = intr_ptr::make_shared(cowid_); } @@ -65,7 +66,10 @@ SHAMap::snapShot(bool isMutable) const } void -SHAMap::dirtyUp(SharedPtrNodeStack& stack, uint256 const& target, intr_ptr::SharedPtr child) +SHAMap::dirtyUp( + SharedPtrNodeStack& stack, + uint256 const& target, + intr_ptr::SharedPtr child) { // walk the tree up from through the inner nodes to the root_ // update hashes and links @@ -73,7 +77,8 @@ SHAMap::dirtyUp(SharedPtrNodeStack& stack, uint256 const& target, intr_ptr::Shar // child can be an inner node or a leaf XRPL_ASSERT( - (state_ != SHAMapState::Synching) && (state_ != SHAMapState::Immutable), "xrpl::SHAMap::dirtyUp : valid state"); + (state_ != SHAMapState::Synching) && (state_ != SHAMapState::Immutable), + "xrpl::SHAMap::dirtyUp : valid state"); XRPL_ASSERT(child && (child->cowid() == cowid_), "xrpl::SHAMap::dirtyUp : valid child input"); while (!stack.empty()) @@ -96,7 +101,8 @@ SHAMap::dirtyUp(SharedPtrNodeStack& stack, uint256 const& target, intr_ptr::Shar SHAMapLeafNode* SHAMap::walkTowardsKey(uint256 const& id, SharedPtrNodeStack* stack) const { - XRPL_ASSERT(stack == nullptr || stack->empty(), "xrpl::SHAMap::walkTowardsKey : empty stack input"); + XRPL_ASSERT( + stack == nullptr || stack->empty(), "xrpl::SHAMap::walkTowardsKey : empty stack input"); auto inNode = root_; SHAMapNodeID nodeID; @@ -307,11 +313,17 @@ SHAMap::descendNoStore(SHAMapInnerNode& parent, int branch) const } std::pair -SHAMap::descend(SHAMapInnerNode* parent, SHAMapNodeID const& parentID, int branch, SHAMapSyncFilter* filter) const +SHAMap::descend( + SHAMapInnerNode* parent, + SHAMapNodeID const& parentID, + int branch, + SHAMapSyncFilter* filter) const { XRPL_ASSERT(parent->isInner(), "xrpl::SHAMap::descend : valid parent input"); - XRPL_ASSERT((branch >= 0) && (branch < branchFactor), "xrpl::SHAMap::descend : valid branch input"); - XRPL_ASSERT(!parent->isEmptyBranch(branch), "xrpl::SHAMap::descend : parent branch is non-empty"); + XRPL_ASSERT( + (branch >= 0) && (branch < branchFactor), "xrpl::SHAMap::descend : valid branch input"); + XRPL_ASSERT( + !parent->isEmptyBranch(branch), "xrpl::SHAMap::descend : parent branch is non-empty"); SHAMapTreeNode* child = parent->getChildPointer(branch); @@ -430,7 +442,8 @@ SHAMap::belowHelper( return nullptr; } SHAMapLeafNode* -SHAMap::lastBelow(intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, int branch) const +SHAMap::lastBelow(intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, int branch) + const { auto init = branchFactor - 1; auto cmp = [](int i) { return i >= 0; }; @@ -439,7 +452,8 @@ SHAMap::lastBelow(intr_ptr::SharedPtr node, SharedPtrNodeStack& return belowHelper(node, stack, branch, {init, cmp, incr}); } SHAMapLeafNode* -SHAMap::firstBelow(intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, int branch) const +SHAMap::firstBelow(intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, int branch) + const { auto init = 0; auto cmp = [](int i) { return i <= branchFactor; }; @@ -483,7 +497,8 @@ SHAMap::onlyBelow(SHAMapTreeNode* node) const // An inner node must have at least one leaf // below it, unless it's the root_ auto const leaf = static_cast(node); - XRPL_ASSERT(leaf->peekItem() || (leaf == root_.get()), "xrpl::SHAMap::onlyBelow : valid inner node"); + XRPL_ASSERT( + leaf->peekItem() || (leaf == root_.get()), "xrpl::SHAMap::onlyBelow : valid inner node"); return leaf->peekItem(); } @@ -734,7 +749,8 @@ SHAMap::addGiveItem(SHAMapNodeType type, boost::intrusive_ptr // easy case, we end on an inner node auto inner = intr_ptr::static_pointer_cast(node); int branch = selectBranch(nodeID, tag); - XRPL_ASSERT(inner->isEmptyBranch(branch), "xrpl::SHAMap::addGiveItem : inner branch is empty"); + XRPL_ASSERT( + inner->isEmptyBranch(branch), "xrpl::SHAMap::addGiveItem : inner branch is empty"); inner->setChild(branch, makeTypedLeaf(type, std::move(item), cowid_)); } else @@ -743,7 +759,8 @@ SHAMap::addGiveItem(SHAMapNodeType type, boost::intrusive_ptr // items auto leaf = intr_ptr::static_pointer_cast(node); auto otherItem = leaf->peekItem(); - XRPL_ASSERT(otherItem && (tag != otherItem->key()), "xrpl::SHAMap::addGiveItem : non-null item"); + XRPL_ASSERT( + otherItem && (tag != otherItem->key()), "xrpl::SHAMap::addGiveItem : non-null item"); node = intr_ptr::make_shared(node->cowid()); @@ -1080,7 +1097,8 @@ SHAMap::dump(bool hash) const if (child) { XRPL_ASSERT( - child->getHash() == inner->getChildHash(i), "xrpl::SHAMap::dump : child hash do match"); + child->getHash() == inner->getChildHash(i), + "xrpl::SHAMap::dump : child hash do match"); stack.push({child, nodeID.getChildNodeID(i)}); } } @@ -1119,7 +1137,8 @@ SHAMap::invariants() const XRPL_ASSERT(node, "xrpl::SHAMap::invariants : non-null root node"); XRPL_ASSERT(!node->isLeaf(), "xrpl::SHAMap::invariants : root node is not leaf"); SharedPtrNodeStack stack; - for (auto leaf = peekFirstItem(stack); leaf != nullptr; leaf = peekNextItem(leaf->peekItem()->key(), stack)) + for (auto leaf = peekFirstItem(stack); leaf != nullptr; + leaf = peekNextItem(leaf->peekItem()->key(), stack)) ; node->invariants(true); } diff --git a/src/libxrpl/shamap/SHAMapDelta.cpp b/src/libxrpl/shamap/SHAMapDelta.cpp index d8aabcc67c..9a6342343f 100644 --- a/src/libxrpl/shamap/SHAMapDelta.cpp +++ b/src/libxrpl/shamap/SHAMapDelta.cpp @@ -85,9 +85,11 @@ SHAMap::walkBranch( { // otherMapItem was unmatched, must add if (isFirstMap) // this is first map, so other item is from second - differences.insert(std::make_pair(otherMapItem->key(), DeltaRef(nullptr, otherMapItem))); + differences.insert( + std::make_pair(otherMapItem->key(), DeltaRef(nullptr, otherMapItem))); else - differences.insert(std::make_pair(otherMapItem->key(), DeltaRef(otherMapItem, nullptr))); + differences.insert( + std::make_pair(otherMapItem->key(), DeltaRef(otherMapItem, nullptr))); if (--maxCount <= 0) return false; @@ -104,7 +106,8 @@ SHAMap::compare(SHAMap const& otherMap, Delta& differences, int maxCount) const // many differences throws on corrupt tables or missing nodes CAUTION: // otherMap is not locked and must be immutable - XRPL_ASSERT(isValid() && otherMap.isValid(), "xrpl::SHAMap::compare : valid state and valid input"); + XRPL_ASSERT( + isValid() && otherMap.isValid(), "xrpl::SHAMap::compare : valid state and valid input"); if (getHash() == otherMap.getHash()) return true; @@ -136,18 +139,22 @@ SHAMap::compare(SHAMap const& otherMap, Delta& differences, int maxCount) const if (ours->peekItem()->slice() != other->peekItem()->slice()) { differences.insert( - std::make_pair(ours->peekItem()->key(), DeltaRef(ours->peekItem(), other->peekItem()))); + std::make_pair( + ours->peekItem()->key(), + DeltaRef(ours->peekItem(), other->peekItem()))); if (--maxCount <= 0) return false; } } else { - differences.insert(std::make_pair(ours->peekItem()->key(), DeltaRef(ours->peekItem(), nullptr))); + differences.insert( + std::make_pair(ours->peekItem()->key(), DeltaRef(ours->peekItem(), nullptr))); if (--maxCount <= 0) return false; - differences.insert(std::make_pair(other->peekItem()->key(), DeltaRef(nullptr, other->peekItem()))); + differences.insert( + std::make_pair(other->peekItem()->key(), DeltaRef(nullptr, other->peekItem()))); if (--maxCount <= 0) return false; } @@ -276,45 +283,49 @@ SHAMap::walkMapParallel(std::vector& missingNodes, int maxMis nodeStacks[rootChildIndex].push(intr_ptr::static_pointer_cast(child)); JLOG(journal_.debug()) << "starting worker " << rootChildIndex; - workers.push_back(std::thread( - [&m, &missingNodes, &maxMissing, &exceptions, this]( - std::stack> nodeStack) { - try - { - while (!nodeStack.empty()) + workers.push_back( + std::thread( + [&m, &missingNodes, &maxMissing, &exceptions, this]( + std::stack> nodeStack) { + try { - intr_ptr::SharedPtr node = std::move(nodeStack.top()); - XRPL_ASSERT(node, "xrpl::SHAMap::walkMapParallel : non-null node"); - nodeStack.pop(); - - for (int i = 0; i < 16; ++i) + while (!nodeStack.empty()) { - if (node->isEmptyBranch(i)) - continue; - intr_ptr::SharedPtr nextNode = descendNoStore(*node, i); + intr_ptr::SharedPtr node = std::move(nodeStack.top()); + XRPL_ASSERT(node, "xrpl::SHAMap::walkMapParallel : non-null node"); + nodeStack.pop(); - if (nextNode) + for (int i = 0; i < 16; ++i) { - if (nextNode->isInner()) - nodeStack.push(intr_ptr::static_pointer_cast(nextNode)); - } - else - { - std::lock_guard l{m}; - missingNodes.emplace_back(type_, node->getChildHash(i)); - if (--maxMissing <= 0) - return; + if (node->isEmptyBranch(i)) + continue; + intr_ptr::SharedPtr nextNode = + descendNoStore(*node, i); + + if (nextNode) + { + if (nextNode->isInner()) + nodeStack.push( + intr_ptr::static_pointer_cast( + nextNode)); + } + else + { + std::lock_guard l{m}; + missingNodes.emplace_back(type_, node->getChildHash(i)); + if (--maxMissing <= 0) + return; + } } } } - } - catch (SHAMapMissingNode const& e) - { - std::lock_guard l(m); - exceptions.push_back(e); - } - }, - std::move(nodeStacks[rootChildIndex]))); + catch (SHAMapMissingNode const& e) + { + std::lock_guard l(m); + exceptions.push_back(e); + } + }, + std::move(nodeStacks[rootChildIndex]))); } for (std::thread& worker : workers) diff --git a/src/libxrpl/shamap/SHAMapInnerNode.cpp b/src/libxrpl/shamap/SHAMapInnerNode.cpp index 5ccca9c2f4..7c344d9264 100644 --- a/src/libxrpl/shamap/SHAMapInnerNode.cpp +++ b/src/libxrpl/shamap/SHAMapInnerNode.cpp @@ -64,18 +64,21 @@ SHAMapInnerNode::clone(std::uint32_t cowid) const SHAMapHash *cloneHashes, *thisHashes; intr_ptr::SharedPtr*cloneChildren, *thisChildren; // structured bindings can't be captured in c++ 17; use tie instead - std::tie(std::ignore, cloneHashes, cloneChildren) = p->hashesAndChildren_.getHashesAndChildren(); + std::tie(std::ignore, cloneHashes, cloneChildren) = + p->hashesAndChildren_.getHashesAndChildren(); std::tie(std::ignore, thisHashes, thisChildren) = hashesAndChildren_.getHashesAndChildren(); if (thisIsSparse) { int cloneChildIndex = 0; - iterNonEmptyChildIndexes( - [&](auto branchNum, auto indexNum) { cloneHashes[cloneChildIndex++] = thisHashes[indexNum]; }); + iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { + cloneHashes[cloneChildIndex++] = thisHashes[indexNum]; + }); } else { - iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { cloneHashes[branchNum] = thisHashes[indexNum]; }); + iterNonEmptyChildIndexes( + [&](auto branchNum, auto indexNum) { cloneHashes[branchNum] = thisHashes[indexNum]; }); } spinlock sl(lock_); @@ -84,13 +87,15 @@ SHAMapInnerNode::clone(std::uint32_t cowid) const if (thisIsSparse) { int cloneChildIndex = 0; - iterNonEmptyChildIndexes( - [&](auto branchNum, auto indexNum) { cloneChildren[cloneChildIndex++] = thisChildren[indexNum]; }); + iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { + cloneChildren[cloneChildIndex++] = thisChildren[indexNum]; + }); } else { - iterNonEmptyChildIndexes( - [&](auto branchNum, auto indexNum) { cloneChildren[branchNum] = thisChildren[indexNum]; }); + iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { + cloneChildren[branchNum] = thisChildren[indexNum]; + }); } return p; @@ -241,7 +246,8 @@ SHAMapInnerNode::getString(SHAMapNodeID const& id) const void SHAMapInnerNode::setChild(int m, intr_ptr::SharedPtr child) { - XRPL_ASSERT((m >= 0) && (m < branchFactor), "xrpl::SHAMapInnerNode::setChild : valid branch input"); + XRPL_ASSERT( + (m >= 0) && (m < branchFactor), "xrpl::SHAMapInnerNode::setChild : valid branch input"); XRPL_ASSERT(cowid_, "xrpl::SHAMapInnerNode::setChild : nonzero cowid"); XRPL_ASSERT(child.get() != this, "xrpl::SHAMapInnerNode::setChild : valid child input"); @@ -255,7 +261,8 @@ SHAMapInnerNode::setChild(int m, intr_ptr::SharedPtr child) auto const dstToAllocate = popcnt16(dstIsBranch); // change hashesAndChildren to remove the element, or make room for the // added element, if necessary - hashesAndChildren_ = TaggedPointer(std::move(hashesAndChildren_), isBranch_, dstIsBranch, dstToAllocate); + hashesAndChildren_ = + TaggedPointer(std::move(hashesAndChildren_), isBranch_, dstIsBranch, dstToAllocate); isBranch_ = dstIsBranch; @@ -270,14 +277,16 @@ SHAMapInnerNode::setChild(int m, intr_ptr::SharedPtr child) hash_.zero(); XRPL_ASSERT( - getBranchCount() <= hashesAndChildren_.capacity(), "xrpl::SHAMapInnerNode::setChild : maximum branch count"); + getBranchCount() <= hashesAndChildren_.capacity(), + "xrpl::SHAMapInnerNode::setChild : maximum branch count"); } // finished modifying, now make shareable void SHAMapInnerNode::shareChild(int m, intr_ptr::SharedPtr const& child) { - XRPL_ASSERT((m >= 0) && (m < branchFactor), "xrpl::SHAMapInnerNode::shareChild : valid branch input"); + XRPL_ASSERT( + (m >= 0) && (m < branchFactor), "xrpl::SHAMapInnerNode::shareChild : valid branch input"); XRPL_ASSERT(cowid_, "xrpl::SHAMapInnerNode::shareChild : nonzero cowid"); XRPL_ASSERT(child, "xrpl::SHAMapInnerNode::shareChild : non-null child input"); XRPL_ASSERT(child.get() != this, "xrpl::SHAMapInnerNode::shareChild : valid child input"); @@ -289,8 +298,11 @@ SHAMapInnerNode::shareChild(int m, intr_ptr::SharedPtr const& ch SHAMapTreeNode* SHAMapInnerNode::getChildPointer(int branch) { - XRPL_ASSERT(branch >= 0 && branch < branchFactor, "xrpl::SHAMapInnerNode::getChildPointer : valid branch input"); - XRPL_ASSERT(!isEmptyBranch(branch), "xrpl::SHAMapInnerNode::getChildPointer : non-empty branch input"); + XRPL_ASSERT( + branch >= 0 && branch < branchFactor, + "xrpl::SHAMapInnerNode::getChildPointer : valid branch input"); + XRPL_ASSERT( + !isEmptyBranch(branch), "xrpl::SHAMapInnerNode::getChildPointer : non-empty branch input"); auto const index = *getChildIndex(branch); @@ -302,7 +314,9 @@ SHAMapInnerNode::getChildPointer(int branch) intr_ptr::SharedPtr SHAMapInnerNode::getChild(int branch) { - XRPL_ASSERT(branch >= 0 && branch < branchFactor, "xrpl::SHAMapInnerNode::getChild : valid branch input"); + XRPL_ASSERT( + branch >= 0 && branch < branchFactor, + "xrpl::SHAMapInnerNode::getChild : valid branch input"); XRPL_ASSERT(!isEmptyBranch(branch), "xrpl::SHAMapInnerNode::getChild : non-empty branch input"); auto const index = *getChildIndex(branch); @@ -315,7 +329,8 @@ SHAMapInnerNode::getChild(int branch) SHAMapHash const& SHAMapInnerNode::getChildHash(int m) const { - XRPL_ASSERT((m >= 0) && (m < branchFactor), "xrpl::SHAMapInnerNode::getChildHash : valid branch input"); + XRPL_ASSERT( + (m >= 0) && (m < branchFactor), "xrpl::SHAMapInnerNode::getChildHash : valid branch input"); if (auto const i = getChildIndex(m)) return hashesAndChildren_.getHashes()[*i]; @@ -325,9 +340,13 @@ SHAMapInnerNode::getChildHash(int m) const intr_ptr::SharedPtr SHAMapInnerNode::canonicalizeChild(int branch, intr_ptr::SharedPtr node) { - XRPL_ASSERT(branch >= 0 && branch < branchFactor, "xrpl::SHAMapInnerNode::canonicalizeChild : valid branch input"); + XRPL_ASSERT( + branch >= 0 && branch < branchFactor, + "xrpl::SHAMapInnerNode::canonicalizeChild : valid branch input"); XRPL_ASSERT(node != nullptr, "xrpl::SHAMapInnerNode::canonicalizeChild : valid node input"); - XRPL_ASSERT(!isEmptyBranch(branch), "xrpl::SHAMapInnerNode::canonicalizeChild : non-empty branch input"); + XRPL_ASSERT( + !isEmptyBranch(branch), + "xrpl::SHAMapInnerNode::canonicalizeChild : non-empty branch input"); auto const childIndex = *getChildIndex(branch); auto [_, hashes, children] = hashesAndChildren_.getHashesAndChildren(); XRPL_ASSERT( @@ -362,7 +381,9 @@ SHAMapInnerNode::invariants(bool is_root) const auto const branchCount = getBranchCount(); for (int i = 0; i < branchCount; ++i) { - XRPL_ASSERT(hashes[i].isNonZero(), "xrpl::SHAMapInnerNode::invariants : nonzero hash in branch"); + XRPL_ASSERT( + hashes[i].isNonZero(), + "xrpl::SHAMapInnerNode::invariants : nonzero hash in branch"); if (children[i] != nullptr) children[i]->invariants(); ++count; diff --git a/src/libxrpl/shamap/SHAMapLeafNode.cpp b/src/libxrpl/shamap/SHAMapLeafNode.cpp index 7f449af3a7..49dd99e935 100644 --- a/src/libxrpl/shamap/SHAMapLeafNode.cpp +++ b/src/libxrpl/shamap/SHAMapLeafNode.cpp @@ -11,7 +11,10 @@ SHAMapLeafNode::SHAMapLeafNode(boost::intrusive_ptr item, std: "SHAMapItem const>, std::uint32_t) : minimum input size"); } -SHAMapLeafNode::SHAMapLeafNode(boost::intrusive_ptr item, std::uint32_t cowid, SHAMapHash const& hash) +SHAMapLeafNode::SHAMapLeafNode( + boost::intrusive_ptr item, + std::uint32_t cowid, + SHAMapHash const& hash) : SHAMapTreeNode(cowid, hash), item_(std::move(item)) { XRPL_ASSERT( diff --git a/src/libxrpl/shamap/SHAMapNodeID.cpp b/src/libxrpl/shamap/SHAMapNodeID.cpp index e8840f398d..f7cc80e250 100644 --- a/src/libxrpl/shamap/SHAMapNodeID.cpp +++ b/src/libxrpl/shamap/SHAMapNodeID.cpp @@ -36,8 +36,11 @@ depthMask(unsigned int depth) // canonicalize the hash to a node ID for this depth SHAMapNodeID::SHAMapNodeID(unsigned int depth, uint256 const& hash) : id_(hash), depth_(depth) { - XRPL_ASSERT(depth <= SHAMap::leafDepth, "xrpl::SHAMapNodeID::SHAMapNodeID : maximum depth input"); - XRPL_ASSERT(id_ == (id_ & depthMask(depth)), "xrpl::SHAMapNodeID::SHAMapNodeID : hash and depth inputs do match"); + XRPL_ASSERT( + depth <= SHAMap::leafDepth, "xrpl::SHAMapNodeID::SHAMapNodeID : maximum depth input"); + XRPL_ASSERT( + id_ == (id_ & depthMask(depth)), + "xrpl::SHAMapNodeID::SHAMapNodeID : hash and depth inputs do match"); } std::string @@ -52,7 +55,8 @@ SHAMapNodeID::getRawString() const SHAMapNodeID SHAMapNodeID::getChildNodeID(unsigned int m) const { - XRPL_ASSERT(m < SHAMap::branchFactor, "xrpl::SHAMapNodeID::getChildNodeID : valid branch input"); + XRPL_ASSERT( + m < SHAMap::branchFactor, "xrpl::SHAMapNodeID::getChildNodeID : valid branch input"); // A SHAMap has exactly 65 levels, so nodes must not exceed that // depth; if they do, this breaks the invariant of never allowing @@ -62,7 +66,8 @@ SHAMapNodeID::getChildNodeID(unsigned int m) const // We throw (but never assert) if the node is at level 64, since // entries at that depth are leaf nodes and have no children and even // constructing a child node from them would break the above invariant. - XRPL_ASSERT(depth_ <= SHAMap::leafDepth, "xrpl::SHAMapNodeID::getChildNodeID : maximum leaf depth"); + XRPL_ASSERT( + depth_ <= SHAMap::leafDepth, "xrpl::SHAMapNodeID::getChildNodeID : maximum leaf depth"); if (depth_ >= SHAMap::leafDepth) Throw("Request for child node ID of " + to_string(*this)); diff --git a/src/libxrpl/shamap/SHAMapSync.cpp b/src/libxrpl/shamap/SHAMapSync.cpp index 503505b80c..d80ddb1e43 100644 --- a/src/libxrpl/shamap/SHAMapSync.cpp +++ b/src/libxrpl/shamap/SHAMapSync.cpp @@ -6,7 +6,9 @@ namespace xrpl { void -SHAMap::visitLeaves(std::function const& item)> const& leafFunction) const +SHAMap::visitLeaves( + std::function const& item)> const& leafFunction) + const { visitNodes([&leafFunction](SHAMapTreeNode& node) { if (!node.isInner()) @@ -76,7 +78,9 @@ SHAMap::visitNodes(std::function const& function) const } void -SHAMap::visitDifferences(SHAMap const* have, std::function const& function) const +SHAMap::visitDifferences( + SHAMap const* have, + std::function const& function) const { // Visit every node in this SHAMap that is not present // in the specified SHAMap @@ -125,7 +129,10 @@ SHAMap::visitDifferences(SHAMap const* have, std::functionhasInnerNode(childID, childHash)) stack.push({static_cast(next), childID}); } - else if (!have || !have->hasLeafNode(static_cast(next)->peekItem()->key(), childHash)) + else if ( + !have || + !have->hasLeafNode( + static_cast(next)->peekItem()->key(), childHash)) { if (!function(*next)) return; @@ -169,7 +176,8 @@ SHAMap::gmn_ProcessNodes(MissingNodes& mn, MissingNodes::StackEntry& se) branch, mn.filter_, pending, - [node, nodeID, branch, &mn](intr_ptr::SharedPtr found, SHAMapHash const&) { + [node, nodeID, branch, &mn]( + intr_ptr::SharedPtr found, SHAMapHash const&) { // a read completed asynchronously std::unique_lock lock{mn.deferLock_}; mn.finishedReads_.emplace_back(node, nodeID, branch, std::move(found)); @@ -187,7 +195,8 @@ SHAMap::gmn_ProcessNodes(MissingNodes& mn, MissingNodes::StackEntry& se) fullBelow = false; // for now, not known full below mn.missingHashes_.insert(childHash); - mn.missingNodes_.emplace_back(nodeID.getChildNodeID(branch), childHash.as_uint256()); + mn.missingNodes_.emplace_back( + nodeID.getChildNodeID(branch), childHash.as_uint256()); if (--mn.max_ <= 0) return; @@ -230,7 +239,8 @@ SHAMap::gmn_ProcessDeferredReads(MissingNodes& mn) int complete = 0; while (complete != mn.deferred_) { - std::tuple> deferredNode; + std::tuple> + deferredNode; { std::unique_lock lock{mn.deferLock_}; @@ -281,7 +291,8 @@ SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) 512, // number of async reads per pass f_.getFullBelowCache()->getGeneration()); - if (!root_->isInner() || intr_ptr::static_pointer_cast(root_)->isFullBelow(mn.generation_)) + if (!root_->isInner() || + intr_ptr::static_pointer_cast(root_)->isFullBelow(mn.generation_)) { clearSynching(); return std::move(mn.missingNodes_); @@ -293,7 +304,8 @@ SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) // (randomly selected) inner node. This increases the likelihood // that the two threads will produce different request sets (which is // more efficient than sending identical requests). - MissingNodes::StackEntry pos{static_cast(root_.get()), SHAMapNodeID(), rand_int(255), 0, true}; + MissingNodes::StackEntry pos{ + static_cast(root_.get()), SHAMapNodeID(), rand_int(255), 0, true}; auto& node = std::get<0>(pos); auto& nextChild = std::get<3>(pos); auto& fullBelow = std::get<4>(pos); @@ -396,7 +408,8 @@ SHAMap::getNodeFat( if (node == nullptr || wanted != nodeID) { - JLOG(journal_.info()) << "peer requested node that is not in the map: " << wanted << " but found " << nodeID; + JLOG(journal_.info()) << "peer requested node that is not in the map: " << wanted + << " but found " << nodeID; return false; } @@ -494,7 +507,8 @@ SHAMap::addRootNode(SHAMapHash const& hash, Slice const& rootNode, SHAMapSyncFil { Serializer s; root_->serializeWithPrefix(s); - filter->gotNode(false, root_->getHash(), ledgerSeq_, std::move(s.modData()), root_->getType()); + filter->gotNode( + false, root_->getHash(), ledgerSeq_, std::move(s.modData()), root_->getType()); } return SHAMapAddNode::useful(); @@ -515,7 +529,8 @@ SHAMap::addKnownNode(SHAMapNodeID const& node, Slice const& rawNode, SHAMapSyncF SHAMapNodeID currNodeID; auto currNode = root_.get(); - while (currNode->isInner() && !static_cast(currNode)->isFullBelow(generation) && + while (currNode->isInner() && + !static_cast(currNode)->isFullBelow(generation) && (currNodeID.getDepth() < node.getDepth())) { int const branch = selectBranch(currNodeID, node.getNodeID()); @@ -554,14 +569,16 @@ SHAMap::addKnownNode(SHAMapNodeID const& node, Slice const& rawNode, SHAMapSyncF // propagate further down the line. if (newNode->isLeaf()) { - auto const& actualKey = static_cast(newNode.get())->peekItem()->key(); + auto const& actualKey = + static_cast(newNode.get())->peekItem()->key(); // Validate that this leaf belongs at the target position auto const expectedNodeID = SHAMapNodeID::createID(node.getDepth(), actualKey); if (expectedNodeID.getNodeID() != node.getNodeID()) { - JLOG(journal_.debug()) << "Leaf node position mismatch: " - << "expected=" << expectedNodeID.getNodeID() << ", actual=" << node.getNodeID(); + JLOG(journal_.debug()) + << "Leaf node position mismatch: " + << "expected=" << expectedNodeID.getNodeID() << ", actual=" << node.getNodeID(); return SHAMapAddNode::invalid(); } } @@ -569,7 +586,8 @@ SHAMap::addKnownNode(SHAMapNodeID const& node, Slice const& rawNode, SHAMapSyncF // Inner nodes must be at a level strictly less than 64 // but leaf nodes (while notionally at level 64) can be // at any depth up to and including 64: - if ((currNodeID.getDepth() > leafDepth) || (newNode->isInner() && currNodeID.getDepth() == leafDepth)) + if ((currNodeID.getDepth() > leafDepth) || + (newNode->isInner() && currNodeID.getDepth() == leafDepth)) { // Map is provably invalid state_ = SHAMapState::Invalid; @@ -581,7 +599,8 @@ SHAMap::addKnownNode(SHAMapNodeID const& node, Slice const& rawNode, SHAMapSyncF // Either this node is broken or we didn't request it (yet) JLOG(journal_.warn()) << "unable to hook node " << node; JLOG(journal_.info()) << " stuck at " << currNodeID; - JLOG(journal_.info()) << "got depth=" << node.getDepth() << ", walked to= " << currNodeID.getDepth(); + JLOG(journal_.info()) << "got depth=" << node.getDepth() + << ", walked to= " << currNodeID.getDepth(); return SHAMapAddNode::useful(); } @@ -594,7 +613,8 @@ SHAMap::addKnownNode(SHAMapNodeID const& node, Slice const& rawNode, SHAMapSyncF { Serializer s; newNode->serializeWithPrefix(s); - filter->gotNode(false, childHash, ledgerSeq_, std::move(s.modData()), newNode->getType()); + filter->gotNode( + false, childHash, ledgerSeq_, std::move(s.modData()), newNode->getType()); } return SHAMapAddNode::useful(); @@ -736,8 +756,8 @@ SHAMap::getProofPath(uint256 const& key) const return {}; } - if (auto const& node = stack.top().first; - !node || node->isInner() || intr_ptr::static_pointer_cast(node)->peekItem()->key() != key) + if (auto const& node = stack.top().first; !node || node->isInner() || + intr_ptr::static_pointer_cast(node)->peekItem()->key() != key) { JLOG(journal_.debug()) << "no path to " << key; return {}; @@ -780,7 +800,8 @@ SHAMap::verifyProofPath(uint256 const& rootHash, uint256 const& key, std::vector if (node->isInner()) { auto nodeId = SHAMapNodeID::createID(depth, key); - hash = static_cast(node.get())->getChildHash(selectBranch(nodeId, key)); + hash = static_cast(node.get()) + ->getChildHash(selectBranch(nodeId, key)); } else { diff --git a/src/libxrpl/shamap/SHAMapTreeNode.cpp b/src/libxrpl/shamap/SHAMapTreeNode.cpp index 156570a60f..9497b4dc54 100644 --- a/src/libxrpl/shamap/SHAMapTreeNode.cpp +++ b/src/libxrpl/shamap/SHAMapTreeNode.cpp @@ -114,8 +114,9 @@ SHAMapTreeNode::makeFromPrefix(Slice rawNode, SHAMapHash const& hash) // FIXME: Use SerialIter::get32? // Extract the prefix auto const type = safe_cast( - (safe_cast(rawNode[0]) << 24) + (safe_cast(rawNode[1]) << 16) + - (safe_cast(rawNode[2]) << 8) + (safe_cast(rawNode[3]))); + (safe_cast(rawNode[0]) << 24) + + (safe_cast(rawNode[1]) << 16) + (safe_cast(rawNode[2]) << 8) + + (safe_cast(rawNode[3]))); rawNode.remove_prefix(4); @@ -134,7 +135,8 @@ SHAMapTreeNode::makeFromPrefix(Slice rawNode, SHAMapHash const& hash) return makeTransactionWithMeta(rawNode, hash, hashValid); Throw( - "prefix: unknown type (" + std::to_string(safe_cast>(type)) + ")"); + "prefix: unknown type (" + + std::to_string(safe_cast>(type)) + ")"); } std::string diff --git a/src/xrpld/app/tx/detail/ApplyContext.cpp b/src/libxrpl/tx/ApplyContext.cpp similarity index 77% rename from src/xrpld/app/tx/detail/ApplyContext.cpp rename to src/libxrpl/tx/ApplyContext.cpp index c5b4d31cec..a8eca09ff2 100644 --- a/src/xrpld/app/tx/detail/ApplyContext.cpp +++ b/src/libxrpl/tx/ApplyContext.cpp @@ -1,14 +1,13 @@ -#include -#include - #include #include #include +#include +#include namespace xrpl { ApplyContext::ApplyContext( - Application& app_, + ServiceRegistry& registry_, OpenView& base, std::optional const& parentBatchId, STTx const& tx_, @@ -16,7 +15,7 @@ ApplyContext::ApplyContext( XRPAmount baseFee_, ApplyFlags flags, beast::Journal journal_) - : app(app_) + : registry(registry_) , tx(tx_) , preclaimResult(preclaimResult_) , baseFee(baseFee_) @@ -51,8 +50,11 @@ ApplyContext::size() void ApplyContext::visit( - std::function< - void(uint256 const&, bool, std::shared_ptr const&, std::shared_ptr const&)> const& func) + std::function const&, + std::shared_ptr const&)> const& func) { view_->visit(base_, func); } @@ -65,13 +67,17 @@ ApplyContext::failInvariantCheck(TER const result) // very wrong. We switch to tefINVARIANT_FAILED, which does NOT get included // in a ledger. - return (result == tecINVARIANT_FAILED || result == tefINVARIANT_FAILED) ? TER{tefINVARIANT_FAILED} - : TER{tecINVARIANT_FAILED}; + return (result == tecINVARIANT_FAILED || result == tefINVARIANT_FAILED) + ? TER{tefINVARIANT_FAILED} + : TER{tecINVARIANT_FAILED}; } template TER -ApplyContext::checkInvariantsHelper(TER const result, XRPAmount const fee, std::index_sequence) +ApplyContext::checkInvariantsHelper( + TER const result, + XRPAmount const fee, + std::index_sequence) { try { @@ -106,7 +112,8 @@ ApplyContext::checkInvariantsHelper(TER const result, XRPAmount const fee, std:: catch (std::exception const& ex) { JLOG(journal.fatal()) << "Transaction caused an exception in an invariant" - << ", ex: " << ex.what() << ", tx: " << to_string(tx.getJson(JsonOptions::none)); + << ", ex: " << ex.what() + << ", tx: " << to_string(tx.getJson(JsonOptions::none)); return failInvariantCheck(result); } @@ -118,9 +125,11 @@ TER ApplyContext::checkInvariants(TER const result, XRPAmount const fee) { XRPL_ASSERT( - isTesSuccess(result) || isTecClaim(result), "xrpl::ApplyContext::checkInvariants : is tesSUCCESS or tecCLAIM"); + isTesSuccess(result) || isTecClaim(result), + "xrpl::ApplyContext::checkInvariants : is tesSUCCESS or tecCLAIM"); - return checkInvariantsHelper(result, fee, std::make_index_sequence::value>{}); + return checkInvariantsHelper( + result, fee, std::make_index_sequence::value>{}); } } // namespace xrpl diff --git a/src/xrpld/app/tx/detail/InvariantCheck.cpp b/src/libxrpl/tx/InvariantCheck.cpp similarity index 77% rename from src/xrpld/app/tx/detail/InvariantCheck.cpp rename to src/libxrpl/tx/InvariantCheck.cpp index 24a37270ce..b94f11100b 100644 --- a/src/xrpld/app/tx/detail/InvariantCheck.cpp +++ b/src/libxrpl/tx/InvariantCheck.cpp @@ -1,9 +1,3 @@ -#include -#include -#include -#include -#include - #include #include #include @@ -21,6 +15,11 @@ #include #include #include +#include +#include +#include +#include +#include #include #include @@ -70,7 +69,8 @@ constexpr Privilege operator|(Privilege lhs, Privilege rhs) { return safe_cast( - safe_cast>(lhs) | safe_cast>(rhs)); + safe_cast>(lhs) | + safe_cast>(rhs)); } #pragma push_macro("TRANSACTION") @@ -98,13 +98,21 @@ hasPrivilege(STTx const& tx, Privilege priv) #pragma pop_macro("TRANSACTION") void -TransactionFeeCheck::visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&) +TransactionFeeCheck::visitEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const&) { // nothing to do } bool -TransactionFeeCheck::finalize(STTx const& tx, TER const, XRPAmount const fee, ReadView const&, beast::Journal const& j) +TransactionFeeCheck::finalize( + STTx const& tx, + TER const, + XRPAmount const fee, + ReadView const&, + beast::Journal const& j) { // We should never charge a negative fee if (fee.drops() < 0) @@ -125,7 +133,8 @@ TransactionFeeCheck::finalize(STTx const& tx, TER const, XRPAmount const fee, Re // authorizes. It's possible to charge less in some circumstances. if (fee > tx.getFieldAmount(sfFee).xrp()) { - JLOG(j.fatal()) << "Invariant failed: fee paid is " << fee.drops() << " exceeds fee specified in transaction."; + JLOG(j.fatal()) << "Invariant failed: fee paid is " << fee.drops() + << " exceeds fee specified in transaction."; return false; } @@ -188,7 +197,12 @@ XRPNotCreated::visitEntry( } bool -XRPNotCreated::finalize(STTx const& tx, TER const, XRPAmount const fee, ReadView const&, beast::Journal const& j) +XRPNotCreated::finalize( + STTx const& tx, + TER const, + XRPAmount const fee, + ReadView const&, + beast::Journal const& j) { // The net change should never be positive, as this would mean that the // transaction created XRP out of thin air. That's not possible. @@ -201,7 +215,8 @@ XRPNotCreated::finalize(STTx const& tx, TER const, XRPAmount const fee, ReadView // The negative of the net change should be equal to actual fee charged. if (-drops_ != fee.drops()) { - JLOG(j.fatal()) << "Invariant failed: XRP net change of " << drops_ << " doesn't match fee " << fee.drops(); + JLOG(j.fatal()) << "Invariant failed: XRP net change of " << drops_ << " doesn't match fee " + << fee.drops(); return false; } @@ -211,7 +226,10 @@ XRPNotCreated::finalize(STTx const& tx, TER const, XRPAmount const fee, ReadView //------------------------------------------------------------------------------ void -XRPBalanceChecks::visitEntry(bool, std::shared_ptr const& before, std::shared_ptr const& after) +XRPBalanceChecks::visitEntry( + bool, + std::shared_ptr const& before, + std::shared_ptr const& after) { auto isBad = [](STAmount const& balance) { if (!balance.native()) @@ -239,7 +257,12 @@ XRPBalanceChecks::visitEntry(bool, std::shared_ptr const& before, std } bool -XRPBalanceChecks::finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const& j) +XRPBalanceChecks::finalize( + STTx const&, + TER const, + XRPAmount const, + ReadView const&, + beast::Journal const& j) { if (bad_) { @@ -278,7 +301,12 @@ NoBadOffers::visitEntry( } bool -NoBadOffers::finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const& j) +NoBadOffers::finalize( + STTx const&, + TER const, + XRPAmount const, + ReadView const&, + beast::Journal const& j) { if (bad_) { @@ -366,7 +394,12 @@ NoZeroEscrow::visitEntry( } bool -NoZeroEscrow::finalize(STTx const& txn, TER const, XRPAmount const, ReadView const& rv, beast::Journal const& j) +NoZeroEscrow::finalize( + STTx const& txn, + TER const, + XRPAmount const, + ReadView const& rv, + beast::Journal const& j) { if (bad_) { @@ -453,7 +486,8 @@ AccountRootsDeletedClean::finalize( // feature is enabled. Enabled, or not, though, a fatal-level message will // be logged [[maybe_unused]] bool const enforce = view.rules().enabled(featureInvariantsV1_1) || - view.rules().enabled(featureSingleAssetVault) || view.rules().enabled(featureLendingProtocol); + view.rules().enabled(featureSingleAssetVault) || + view.rules().enabled(featureLendingProtocol); auto const objectExists = [&view, enforce, &j](auto const& keylet) { (void)enforce; @@ -468,7 +502,8 @@ AccountRootsDeletedClean::finalize( return std::to_string(sle->getType()); }(); - JLOG(j.fatal()) << "Invariant failed: account deletion left behind a " << typeName << " object"; + JLOG(j.fatal()) << "Invariant failed: account deletion left behind a " << typeName + << " object"; // The comment above starting with "assert(enforce)" explains this // assert. XRPL_ASSERT( @@ -579,7 +614,12 @@ LedgerEntryTypesMatch::visitEntry( } bool -LedgerEntryTypesMatch::finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const& j) +LedgerEntryTypesMatch::finalize( + STTx const&, + TER const, + XRPAmount const, + ReadView const&, + beast::Journal const& j) { if ((!typeMismatch_) && (!invalidTypeAdded_)) return true; @@ -600,7 +640,10 @@ LedgerEntryTypesMatch::finalize(STTx const&, TER const, XRPAmount const, ReadVie //------------------------------------------------------------------------------ void -NoXRPTrustLines::visitEntry(bool, std::shared_ptr const&, std::shared_ptr const& after) +NoXRPTrustLines::visitEntry( + bool, + std::shared_ptr const&, + std::shared_ptr const& after) { if (after && after->getType() == ltRIPPLE_STATE) { @@ -613,7 +656,12 @@ NoXRPTrustLines::visitEntry(bool, std::shared_ptr const&, std::shared } bool -NoXRPTrustLines::finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const& j) +NoXRPTrustLines::finalize( + STTx const&, + TER const, + XRPAmount const, + ReadView const&, + beast::Journal const& j) { if (!xrpTrustLine_) return true; @@ -747,7 +795,9 @@ TransfersNotFrozen::finalize( } bool -TransfersNotFrozen::isValidEntry(std::shared_ptr const& before, std::shared_ptr const& after) +TransfersNotFrozen::isValidEntry( + std::shared_ptr const& before, + std::shared_ptr const& after) { // `after` can never be null, even if the trust line is deleted. XRPL_ASSERT(after, "xrpl::TransfersNotFrozen::isValidEntry : valid after."); @@ -814,7 +864,9 @@ TransfersNotFrozen::recordBalance(Issue const& issue, BalanceChange change) } void -TransfersNotFrozen::recordBalanceChanges(std::shared_ptr const& after, STAmount const& balanceChange) +TransfersNotFrozen::recordBalanceChanges( + std::shared_ptr const& after, + STAmount const& balanceChange) { auto const balanceChangeSign = balanceChange.signum(); auto const currency = after->at(sfBalance).getCurrency(); @@ -887,7 +939,8 @@ TransfersNotFrozen::validateFrozenState( bool enforce, bool globalFreeze) { - bool const freeze = change.balanceChangeSign < 0 && change.line->isFlag(high ? lsfLowFreeze : lsfHighFreeze); + bool const freeze = + change.balanceChangeSign < 0 && change.line->isFlag(high ? lsfLowFreeze : lsfHighFreeze); bool const deepFreeze = change.line->isFlag(high ? lsfLowDeepFreeze : lsfHighDeepFreeze); bool const frozen = globalFreeze || deepFreeze || freeze; @@ -902,12 +955,13 @@ TransfersNotFrozen::validateFrozenState( if ((!isAMMLine || globalFreeze) && hasPrivilege(tx, overrideFreeze)) { JLOG(j.debug()) << "Invariant check allowing funds to be moved " - << (change.balanceChangeSign > 0 ? "to" : "from") << " a frozen trustline for AMMClawback " - << tx.getTransactionID(); + << (change.balanceChangeSign > 0 ? "to" : "from") + << " a frozen trustline for AMMClawback " << tx.getTransactionID(); return true; } - JLOG(j.fatal()) << "Invariant failed: Attempting to move frozen funds for " << tx.getTransactionID(); + JLOG(j.fatal()) << "Invariant failed: Attempting to move frozen funds for " + << tx.getTransactionID(); // The comment above starting with "assert(enforce)" explains this assert. XRPL_ASSERT( enforce, @@ -925,7 +979,10 @@ TransfersNotFrozen::validateFrozenState( //------------------------------------------------------------------------------ void -ValidNewAccountRoot::visitEntry(bool, std::shared_ptr const& before, std::shared_ptr const& after) +ValidNewAccountRoot::visitEntry( + bool, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (!before && after->getType() == ltACCOUNT_ROOT) { @@ -959,7 +1016,8 @@ ValidNewAccountRoot::finalize( { bool const pseudoAccount = (pseudoAccount_ && - (view.rules().enabled(featureSingleAssetVault) || view.rules().enabled(featureLendingProtocol))); + (view.rules().enabled(featureSingleAssetVault) || + view.rules().enabled(featureLendingProtocol))); if (pseudoAccount && !hasPrivilege(tx, createPseudoAcct)) { @@ -1006,7 +1064,8 @@ ValidNFTokenPage::visitEntry( static constexpr uint256 const& pageBits = nft::pageMask; static constexpr uint256 const accountBits = ~pageBits; - if ((before && before->getType() != ltNFTOKEN_PAGE) || (after && after->getType() != ltNFTOKEN_PAGE)) + if ((before && before->getType() != ltNFTOKEN_PAGE) || + (after && after->getType() != ltNFTOKEN_PAGE)) return; auto check = [this, isDelete](std::shared_ptr const& sle) { @@ -1075,7 +1134,8 @@ ValidNFTokenPage::visitEntry( // While an account's NFToken directory contains any NFTokens, the last // NFTokenPage (with 96 bits of 1 in the low part of the index) should // never be deleted. - if (isDelete && (before->key() & nft::pageMask) == nft::pageMask && before->isFieldPresent(sfPreviousPageMin)) + if (isDelete && (before->key() & nft::pageMask) == nft::pageMask && + before->isFieldPresent(sfPreviousPageMin)) { deletedFinalPage_ = true; } @@ -1091,8 +1151,8 @@ ValidNFTokenPage::visitEntry( // 2. This is not the last page in the directory // Then we have identified a corruption in the links between the // NFToken pages in the NFToken directory. - if ((before->key() & nft::pageMask) != nft::pageMask && before->isFieldPresent(sfNextPageMin) && - !after->isFieldPresent(sfNextPageMin)) + if ((before->key() & nft::pageMask) != nft::pageMask && + before->isFieldPresent(sfNextPageMin) && !after->isFieldPresent(sfNextPageMin)) { deletedLink_ = true; } @@ -1259,7 +1319,10 @@ NFTokenCountTracking::finalize( //------------------------------------------------------------------------------ void -ValidClawback::visitEntry(bool, std::shared_ptr const& before, std::shared_ptr const&) +ValidClawback::visitEntry( + bool, + std::shared_ptr const& before, + std::shared_ptr const&) { if (before && before->getType() == ltRIPPLE_STATE) trustlinesChanged++; @@ -1298,7 +1361,8 @@ ValidClawback::finalize( AccountID const issuer = tx.getAccountID(sfAccount); STAmount const& amount = tx.getFieldAmount(sfAmount); AccountID const& holder = amount.getIssuer(); - STAmount const holderBalance = accountHolds(view, holder, amount.getCurrency(), issuer, fhIGNORE_FREEZE, j); + STAmount const holderBalance = + accountHolds(view, holder, amount.getCurrency(), issuer, fhIGNORE_FREEZE, j); if (holderBalance.signum() < 0) { @@ -1369,13 +1433,15 @@ ValidMPTIssuance::finalize( { auto const& rules = view.rules(); [[maybe_unused]] - bool enforceCreatedByIssuer = rules.enabled(featureSingleAssetVault) || rules.enabled(featureLendingProtocol); + bool enforceCreatedByIssuer = + rules.enabled(featureSingleAssetVault) || rules.enabled(featureLendingProtocol); if (mptCreatedByIssuer_) { JLOG(j.fatal()) << "Invariant failed: MPToken created for the MPT issuer"; // The comment above starting with "assert(enforce)" explains this // assert. - XRPL_ASSERT_PARTS(enforceCreatedByIssuer, "xrpl::ValidMPTIssuance::finalize", "no issuer MPToken"); + XRPL_ASSERT_PARTS( + enforceCreatedByIssuer, "xrpl::ValidMPTIssuance::finalize", "no issuer MPToken"); if (enforceCreatedByIssuer) return false; } @@ -1427,8 +1493,8 @@ ValidMPTIssuance::finalize( // ttESCROW_FINISH may authorize an MPT, but it can't have the // mayAuthorizeMPT privilege, because that may cause // non-amendment-gated side effects. - bool const enforceEscrowFinish = - (txnType == ttESCROW_FINISH) && (view.rules().enabled(featureSingleAssetVault) || lendingProtocolEnabled); + bool const enforceEscrowFinish = (txnType == ttESCROW_FINISH) && + (view.rules().enabled(featureSingleAssetVault) || lendingProtocolEnabled); if (hasPrivilege(tx, mustAuthorizeMPT | mayAuthorizeMPT) || enforceEscrowFinish) { bool const submittedByIssuer = tx.isFieldPresent(sfHolder); @@ -1458,7 +1524,8 @@ ValidMPTIssuance::finalize( return false; } else if ( - !submittedByIssuer && hasPrivilege(tx, mustAuthorizeMPT) && (mptokensCreated_ + mptokensDeleted_ != 1)) + !submittedByIssuer && hasPrivilege(tx, mustAuthorizeMPT) && + (mptokensCreated_ + mptokensDeleted_ != 1)) { // if the holder submitted this tx, then a mptoken must be // either created or deleted. @@ -1474,7 +1541,8 @@ ValidMPTIssuance::finalize( // ttESCROW_FINISH may authorize an MPT, but it can't have the // mayAuthorizeMPT privilege, because that may cause // non-amendment-gated side effects. - XRPL_ASSERT_PARTS(!enforceEscrowFinish, "xrpl::ValidMPTIssuance::finalize", "not escrow finish tx"); + XRPL_ASSERT_PARTS( + !enforceEscrowFinish, "xrpl::ValidMPTIssuance::finalize", "not escrow finish tx"); return true; } @@ -1500,7 +1568,8 @@ ValidMPTIssuance::finalize( JLOG(j.fatal()) << "Invariant failed: a MPToken was deleted"; } - return mptIssuancesCreated_ == 0 && mptIssuancesDeleted_ == 0 && mptokensCreated_ == 0 && mptokensDeleted_ == 0; + return mptIssuancesCreated_ == 0 && mptIssuancesDeleted_ == 0 && mptokensCreated_ == 0 && + mptokensDeleted_ == 0; } //------------------------------------------------------------------------------ @@ -1529,7 +1598,8 @@ ValidPermissionedDomain::visitEntry( for (auto const& cred : sorted) { auto const& credTx = credentials[i++]; - ss.isSorted_ = (cred.first == credTx[sfIssuer]) && (cred.second == credTx[sfCredentialType]); + ss.isSorted_ = + (cred.first == credTx[sfIssuer]) && (cred.second == credTx[sfCredentialType]); if (!ss.isSorted_) break; } @@ -1648,7 +1718,8 @@ ValidPermissionedDomain::finalize( } else { - if (tx.getTxnType() != ttPERMISSIONED_DOMAIN_SET || result != tesSUCCESS || sleStatus_.empty()) + if (tx.getTxnType() != ttPERMISSIONED_DOMAIN_SET || result != tesSUCCESS || + sleStatus_.empty()) return true; return check(sleStatus_[0], j); } @@ -1691,9 +1762,10 @@ ValidPseudoAccounts::visitEntry( { std::vector const& fields = getPseudoAccountFields(); - auto const numFields = std::count_if(fields.begin(), fields.end(), [&after](SField const* sf) -> bool { - return after->isFieldPresent(*sf); - }); + auto const numFields = + std::count_if(fields.begin(), fields.end(), [&after](SField const* sf) -> bool { + return after->isFieldPresent(*sf); + }); if (numFields != 1) { std::stringstream error; @@ -1718,7 +1790,12 @@ ValidPseudoAccounts::visitEntry( } bool -ValidPseudoAccounts::finalize(STTx const& tx, TER const, XRPAmount const, ReadView const& view, beast::Journal const& j) +ValidPseudoAccounts::finalize( + STTx const& tx, + TER const, + XRPAmount const, + ReadView const& view, + beast::Journal const& j) { bool const enforce = view.rules().enabled(featureSingleAssetVault); XRPL_ASSERT( @@ -1821,7 +1898,10 @@ ValidPermissionedDEX::finalize( } void -ValidAMM::visitEntry(bool isDelete, std::shared_ptr const& before, std::shared_ptr const& after) +ValidAMM::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (isDelete) return; @@ -1861,9 +1941,11 @@ validBalances( STAmount const& lptAMMBalance, ValidAMM::ZeroAllowed zeroAllowed) { - bool const positive = amount > beast::zero && amount2 > beast::zero && lptAMMBalance > beast::zero; + bool const positive = + amount > beast::zero && amount2 > beast::zero && lptAMMBalance > beast::zero; if (zeroAllowed == ValidAMM::ZeroAllowed::Yes) - return positive || (amount == beast::zero && amount2 == beast::zero && lptAMMBalance == beast::zero); + return positive || + (amount == beast::zero && amount2 == beast::zero && lptAMMBalance == beast::zero); return positive; } @@ -1874,8 +1956,9 @@ ValidAMM::finalizeVote(bool enforce, beast::Journal const& j) const { // LPTokens and the pool can not change on vote // LCOV_EXCL_START - JLOG(j.error()) << "AMMVote invariant failed: " << lptAMMBalanceBefore_.value_or(STAmount{}) << " " - << lptAMMBalanceAfter_.value_or(STAmount{}) << " " << ammPoolChanged_; + JLOG(j.error()) << "AMMVote invariant failed: " << lptAMMBalanceBefore_.value_or(STAmount{}) + << " " << lptAMMBalanceAfter_.value_or(STAmount{}) << " " + << ammPoolChanged_; if (enforce) return false; // LCOV_EXCL_STOP @@ -1902,7 +1985,8 @@ ValidAMM::finalizeBid(bool enforce, beast::Journal const& j) const (*lptAMMBalanceAfter_ > *lptAMMBalanceBefore_ || *lptAMMBalanceAfter_ <= beast::zero)) { // LCOV_EXCL_START - JLOG(j.error()) << "AMMBid invariant failed: " << *lptAMMBalanceBefore_ << " " << *lptAMMBalanceAfter_; + JLOG(j.error()) << "AMMBid invariant failed: " << *lptAMMBalanceBefore_ << " " + << *lptAMMBalanceAfter_; if (enforce) return false; // LCOV_EXCL_STOP @@ -1912,7 +1996,11 @@ ValidAMM::finalizeBid(bool enforce, beast::Journal const& j) const } bool -ValidAMM::finalizeCreate(STTx const& tx, ReadView const& view, bool enforce, beast::Journal const& j) const +ValidAMM::finalizeCreate( + STTx const& tx, + ReadView const& view, + bool enforce, + beast::Journal const& j) const { if (!ammAccount_) { @@ -1924,8 +2012,13 @@ ValidAMM::finalizeCreate(STTx const& tx, ReadView const& view, bool enforce, bea } else { - auto const [amount, amount2] = - ammPoolHolds(view, *ammAccount_, tx[sfAmount].get(), tx[sfAmount2].get(), fhIGNORE_FREEZE, j); + auto const [amount, amount2] = ammPoolHolds( + view, + *ammAccount_, + tx[sfAmount].get(), + tx[sfAmount2].get(), + fhIGNORE_FREEZE, + j); // Create invariant: // sqrt(amount * amount2) == LPTokens // all balances are greater than zero @@ -1948,8 +2041,8 @@ ValidAMM::finalizeDelete(bool enforce, TER res, beast::Journal const& j) const if (ammAccount_) { // LCOV_EXCL_START - std::string const msg = - (res == tesSUCCESS) ? "AMM object is not deleted on tesSUCCESS" : "AMM object is changed on tecINCOMPLETE"; + std::string const msg = (res == tesSUCCESS) ? "AMM object is not deleted on tesSUCCESS" + : "AMM object is changed on tecINCOMPLETE"; JLOG(j.error()) << "AMMDelete invariant failed: " << msg; if (enforce) return false; @@ -1981,14 +2074,20 @@ ValidAMM::generalInvariant( ZeroAllowed zeroAllowed, beast::Journal const& j) const { - auto const [amount, amount2] = - ammPoolHolds(view, *ammAccount_, tx[sfAsset].get(), tx[sfAsset2].get(), fhIGNORE_FREEZE, j); + auto const [amount, amount2] = ammPoolHolds( + view, + *ammAccount_, + tx[sfAsset].get(), + tx[sfAsset2].get(), + fhIGNORE_FREEZE, + j); // Deposit and Withdrawal invariant: // sqrt(amount * amount2) >= LPTokens // all balances are greater than zero // unless on last withdrawal auto const poolProductMean = root2(amount * amount2); - bool const nonNegativeBalances = validBalances(amount, amount2, *lptAMMBalanceAfter_, zeroAllowed); + bool const nonNegativeBalances = + validBalances(amount, amount2, *lptAMMBalanceAfter_, zeroAllowed); bool const strongInvariantCheck = poolProductMean >= *lptAMMBalanceAfter_; // Allow for a small relative error if strongInvariantCheck fails auto weakInvariantCheck = [&]() { @@ -1997,9 +2096,10 @@ ValidAMM::generalInvariant( }; if (!nonNegativeBalances || (!strongInvariantCheck && !weakInvariantCheck())) { - JLOG(j.error()) << "AMM " << tx.getTxnType() << " invariant failed: " << tx.getHash(HashPrefix::transactionID) - << " " << ammPoolChanged_ << " " << amount << " " << amount2 << " " << poolProductMean << " " - << lptAMMBalanceAfter_->getText() << " " + JLOG(j.error()) << "AMM " << tx.getTxnType() + << " invariant failed: " << tx.getHash(HashPrefix::transactionID) << " " + << ammPoolChanged_ << " " << amount << " " << amount2 << " " + << poolProductMean << " " << lptAMMBalanceAfter_->getText() << " " << ((*lptAMMBalanceAfter_ == beast::zero) ? Number{1} : ((*lptAMMBalanceAfter_ - poolProductMean) / poolProductMean)); @@ -2010,7 +2110,11 @@ ValidAMM::generalInvariant( } bool -ValidAMM::finalizeDeposit(xrpl::STTx const& tx, xrpl::ReadView const& view, bool enforce, beast::Journal const& j) const +ValidAMM::finalizeDeposit( + xrpl::STTx const& tx, + xrpl::ReadView const& view, + bool enforce, + beast::Journal const& j) const { if (!ammAccount_) { @@ -2027,8 +2131,11 @@ ValidAMM::finalizeDeposit(xrpl::STTx const& tx, xrpl::ReadView const& view, bool } bool -ValidAMM::finalizeWithdraw(xrpl::STTx const& tx, xrpl::ReadView const& view, bool enforce, beast::Journal const& j) - const +ValidAMM::finalizeWithdraw( + xrpl::STTx const& tx, + xrpl::ReadView const& view, + bool enforce, + beast::Journal const& j) const { if (!ammAccount_) { @@ -2044,7 +2151,12 @@ ValidAMM::finalizeWithdraw(xrpl::STTx const& tx, xrpl::ReadView const& view, boo } bool -ValidAMM::finalize(STTx const& tx, TER const result, XRPAmount const, ReadView const& view, beast::Journal const& j) +ValidAMM::finalize( + STTx const& tx, + TER const result, + XRPAmount const, + ReadView const& view, + beast::Journal const& j) { // Delete may return tecINCOMPLETE if there are too many // trustlines to delete. @@ -2123,10 +2235,14 @@ NoModifiedUnmodifiableFields::finalize( * potential issues even when the amendment is disabled. */ enforce = view.rules().enabled(featureLendingProtocol); - bad = fieldChanged(before, after, sfLedgerEntryType) || fieldChanged(before, after, sfLedgerIndex) || - fieldChanged(before, after, sfSequence) || fieldChanged(before, after, sfOwnerNode) || - fieldChanged(before, after, sfVaultNode) || fieldChanged(before, after, sfVaultID) || - fieldChanged(before, after, sfAccount) || fieldChanged(before, after, sfOwner) || + bad = fieldChanged(before, after, sfLedgerEntryType) || + fieldChanged(before, after, sfLedgerIndex) || + fieldChanged(before, after, sfSequence) || + fieldChanged(before, after, sfOwnerNode) || + fieldChanged(before, after, sfVaultNode) || + fieldChanged(before, after, sfVaultID) || + fieldChanged(before, after, sfAccount) || + fieldChanged(before, after, sfOwner) || fieldChanged(before, after, sfManagementFeeRate) || fieldChanged(before, after, sfCoverRateMinimum) || fieldChanged(before, after, sfCoverRateLiquidation); @@ -2138,17 +2254,26 @@ NoModifiedUnmodifiableFields::finalize( * potential issues even when the amendment is disabled. */ enforce = view.rules().enabled(featureLendingProtocol); - bad = fieldChanged(before, after, sfLedgerEntryType) || fieldChanged(before, after, sfLedgerIndex) || - fieldChanged(before, after, sfSequence) || fieldChanged(before, after, sfOwnerNode) || - fieldChanged(before, after, sfLoanBrokerNode) || fieldChanged(before, after, sfLoanBrokerID) || - fieldChanged(before, after, sfBorrower) || fieldChanged(before, after, sfLoanOriginationFee) || - fieldChanged(before, after, sfLoanServiceFee) || fieldChanged(before, after, sfLatePaymentFee) || - fieldChanged(before, after, sfClosePaymentFee) || fieldChanged(before, after, sfOverpaymentFee) || - fieldChanged(before, after, sfInterestRate) || fieldChanged(before, after, sfLateInterestRate) || + bad = fieldChanged(before, after, sfLedgerEntryType) || + fieldChanged(before, after, sfLedgerIndex) || + fieldChanged(before, after, sfSequence) || + fieldChanged(before, after, sfOwnerNode) || + fieldChanged(before, after, sfLoanBrokerNode) || + fieldChanged(before, after, sfLoanBrokerID) || + fieldChanged(before, after, sfBorrower) || + fieldChanged(before, after, sfLoanOriginationFee) || + fieldChanged(before, after, sfLoanServiceFee) || + fieldChanged(before, after, sfLatePaymentFee) || + fieldChanged(before, after, sfClosePaymentFee) || + fieldChanged(before, after, sfOverpaymentFee) || + fieldChanged(before, after, sfInterestRate) || + fieldChanged(before, after, sfLateInterestRate) || fieldChanged(before, after, sfCloseInterestRate) || fieldChanged(before, after, sfOverpaymentInterestRate) || - fieldChanged(before, after, sfStartDate) || fieldChanged(before, after, sfPaymentInterval) || - fieldChanged(before, after, sfGracePeriod) || fieldChanged(before, after, sfLoanScale); + fieldChanged(before, after, sfStartDate) || + fieldChanged(before, after, sfPaymentInterval) || + fieldChanged(before, after, sfGracePeriod) || + fieldChanged(before, after, sfLoanScale); break; default: /* @@ -2161,7 +2286,8 @@ NoModifiedUnmodifiableFields::finalize( * was added. */ enforce = view.rules().enabled(featureLendingProtocol); - bad = fieldChanged(before, after, sfLedgerEntryType) || fieldChanged(before, after, sfLedgerIndex); + bad = fieldChanged(before, after, sfLedgerEntryType) || + fieldChanged(before, after, sfLedgerIndex); } XRPL_ASSERT( !bad || enforce, @@ -2169,7 +2295,8 @@ NoModifiedUnmodifiableFields::finalize( "changes or enforce invariant"); if (bad) { - JLOG(j.fatal()) << "Invariant failed: changed an unchangeable field for " << tx.getTransactionID(); + JLOG(j.fatal()) << "Invariant failed: changed an unchangeable field for " + << tx.getTransactionID(); if (enforce) return false; } @@ -2211,7 +2338,10 @@ ValidLoanBroker::visitEntry( } bool -ValidLoanBroker::goodZeroDirectory(ReadView const& view, SLE::const_ref dir, beast::Journal const& j) const +ValidLoanBroker::goodZeroDirectory( + ReadView const& view, + SLE::const_ref dir, + beast::Journal const& j) const { auto const next = dir->at(~sfIndexNext); auto const prev = dir->at(~sfIndexPrevious); @@ -2249,7 +2379,12 @@ ValidLoanBroker::goodZeroDirectory(ReadView const& view, SLE::const_ref dir, bea } bool -ValidLoanBroker::finalize(STTx const& tx, TER const, XRPAmount const, ReadView const& view, beast::Journal const& j) +ValidLoanBroker::finalize( + STTx const& tx, + TER const, + XRPAmount const, + ReadView const& view, + beast::Journal const& j) { // Loan Brokers will not exist on ledger if the Lending Protocol amendment // is not enabled, so there's no need to check it. @@ -2286,7 +2421,8 @@ ValidLoanBroker::finalize(STTx const& tx, TER const, XRPAmount const, ReadView c for (auto const& [brokerID, broker] : brokers_) { - auto const& after = broker.brokerAfter ? broker.brokerAfter : view.read(keylet::loanbroker(brokerID)); + auto const& after = + broker.brokerAfter ? broker.brokerAfter : view.read(keylet::loanbroker(brokerID)); if (!after) { @@ -2353,7 +2489,10 @@ ValidLoanBroker::finalize(STTx const& tx, TER const, XRPAmount const, ReadView c //------------------------------------------------------------------------------ void -ValidLoan::visitEntry(bool isDelete, std::shared_ptr const& before, std::shared_ptr const& after) +ValidLoan::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { if (after && after->getType() == ltLOAN) { @@ -2362,7 +2501,12 @@ ValidLoan::visitEntry(bool isDelete, std::shared_ptr const& before, s } bool -ValidLoan::finalize(STTx const& tx, TER const, XRPAmount const, ReadView const& view, beast::Journal const& j) +ValidLoan::finalize( + STTx const& tx, + TER const, + XRPAmount const, + ReadView const& view, + beast::Journal const& j) { // Loans will not exist on ledger if the Lending Protocol amendment // is not enabled, so there's no need to check it. @@ -2372,7 +2516,8 @@ ValidLoan::finalize(STTx const& tx, TER const, XRPAmount const, ReadView const& // https://github.com/Tapanito/XRPL-Standards/blob/xls-66-lending-protocol/XLS-0066d-lending-protocol/README.md#3223-invariants // If `Loan.PaymentRemaining = 0` then the loan MUST be fully paid off if (after->at(sfPaymentRemaining) == 0 && - (after->at(sfTotalValueOutstanding) != beast::zero || after->at(sfPrincipalOutstanding) != beast::zero || + (after->at(sfTotalValueOutstanding) != beast::zero || + after->at(sfPrincipalOutstanding) != beast::zero || after->at(sfManagementFeeOutstanding) != beast::zero)) { JLOG(j.fatal()) << "Invariant failed: Loan with zero payments " @@ -2381,8 +2526,10 @@ ValidLoan::finalize(STTx const& tx, TER const, XRPAmount const, ReadView const& } // If `Loan.PaymentRemaining != 0` then the loan MUST NOT be fully paid // off - if (after->at(sfPaymentRemaining) != 0 && after->at(sfTotalValueOutstanding) == beast::zero && - after->at(sfPrincipalOutstanding) == beast::zero && after->at(sfManagementFeeOutstanding) == beast::zero) + if (after->at(sfPaymentRemaining) != 0 && + after->at(sfTotalValueOutstanding) == beast::zero && + after->at(sfPrincipalOutstanding) == beast::zero && + after->at(sfManagementFeeOutstanding) == beast::zero) { JLOG(j.fatal()) << "Invariant failed: Loan with zero payments " "remaining has not been paid off"; @@ -2415,7 +2562,8 @@ ValidLoan::finalize(STTx const& tx, TER const, XRPAmount const, ReadView const& { if (after->at(*field) <= 0) { - JLOG(j.fatal()) << "Invariant failed: " << field->getName() << " is zero or negative "; + JLOG(j.fatal()) << "Invariant failed: " << field->getName() + << " is zero or negative "; return false; } } @@ -2444,7 +2592,9 @@ ValidVault::Vault::make(SLE const& from) ValidVault::Shares ValidVault::Shares::make(SLE const& from) { - XRPL_ASSERT(from.getType() == ltMPTOKEN_ISSUANCE, "ValidVault::Shares::make : from MPTokenIssuance object"); + XRPL_ASSERT( + from.getType() == ltMPTOKEN_ISSUANCE, + "ValidVault::Shares::make : from MPTokenIssuance object"); ValidVault::Shares self; self.share = MPTIssue(makeMptID(from.getFieldU32(sfSequence), from.getAccountID(sfIssuer))); @@ -2454,7 +2604,10 @@ ValidVault::Shares::make(SLE const& from) } void -ValidVault::visitEntry(bool isDelete, std::shared_ptr const& before, std::shared_ptr const& after) +ValidVault::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) { // If `before` is empty, this means an object is being created, in which // case `isDelete` must be false. Otherwise `before` and `after` are set and @@ -2508,7 +2661,8 @@ ValidVault::visitEntry(bool isDelete, std::shared_ptr const& before, // At this moment we have no way of telling if this object holds // vault shares or something else. Save it for finalize. afterMPTs_.push_back(Shares::make(*after)); - balanceDelta -= Number(static_cast(after->getFieldU64(sfOutstandingAmount))); + balanceDelta -= + Number(static_cast(after->getFieldU64(sfOutstandingAmount))); sign = 1; break; case ltMPTOKEN: @@ -2535,7 +2689,12 @@ ValidVault::visitEntry(bool isDelete, std::shared_ptr const& before, } bool -ValidVault::finalize(STTx const& tx, TER const ret, XRPAmount const fee, ReadView const& view, beast::Journal const& j) +ValidVault::finalize( + STTx const& tx, + TER const ret, + XRPAmount const fee, + ReadView const& view, + beast::Journal const& j) { bool const enforce = view.rules().enabled(featureSingleAssetVault); @@ -2707,7 +2866,8 @@ ValidVault::finalize(STTx const& tx, TER const ret, XRPAmount const fee, ReadVie else if (updatedShares->sharesTotal > updatedShares->sharesMaximum) { JLOG(j.fatal()) // - << "Invariant failed: updated shares must not exceed maximum " << updatedShares->sharesMaximum; + << "Invariant failed: updated shares must not exceed maximum " + << updatedShares->sharesMaximum; result = false; } @@ -2802,7 +2962,8 @@ ValidVault::finalize(STTx const& tx, TER const ret, XRPAmount const fee, ReadVie { if (isXRP(issue)) return get(deltas_.find(keylet::account(id).key)); - return get(deltas_.find(keylet::line(id, issue).key), id > issue.getIssuer() ? -1 : 1); + return get( + deltas_.find(keylet::line(id, issue).key), id > issue.getIssuer() ? -1 : 1); } else if constexpr (std::is_same_v) { @@ -2818,7 +2979,8 @@ ValidVault::finalize(STTx const& tx, TER const ret, XRPAmount const fee, ReadVie return ret; // Delegated transaction; no need to compensate for fees - if (auto const delegate = tx[~sfDelegate]; delegate.has_value() && *delegate != tx[sfAccount]) + if (auto const delegate = tx[~sfDelegate]; + delegate.has_value() && *delegate != tx[sfAccount]) return ret; *ret += fee.drops(); @@ -2845,459 +3007,467 @@ ValidVault::finalize(STTx const& tx, TER const ret, XRPAmount const fee, ReadVie // convenient thanks to early "return false"; the not-so-nice // alternatives are several layers of nested if/else or more complex // (i.e. brittle) if statements. - result &= - [&]() { - switch (txnType) - { - case ttVAULT_CREATE: { - bool result = true; + result &= [&]() { + switch (txnType) + { + case ttVAULT_CREATE: { + bool result = true; - if (!beforeVault_.empty()) - { - JLOG(j.fatal()) // - << "Invariant failed: create operation must not have " - "updated a vault"; - result = false; - } + if (!beforeVault_.empty()) + { + JLOG(j.fatal()) // + << "Invariant failed: create operation must not have " + "updated a vault"; + result = false; + } - if (afterVault.assetsAvailable != zero || afterVault.assetsTotal != zero || - afterVault.lossUnrealized != zero || updatedShares->sharesTotal != 0) - { - JLOG(j.fatal()) // - << "Invariant failed: created vault must be empty"; - result = false; - } + if (afterVault.assetsAvailable != zero || afterVault.assetsTotal != zero || + afterVault.lossUnrealized != zero || updatedShares->sharesTotal != 0) + { + JLOG(j.fatal()) // + << "Invariant failed: created vault must be empty"; + result = false; + } - if (afterVault.pseudoId != updatedShares->share.getIssuer()) - { - JLOG(j.fatal()) // - << "Invariant failed: shares issuer and vault " - "pseudo-account must be the same"; - result = false; - } + if (afterVault.pseudoId != updatedShares->share.getIssuer()) + { + JLOG(j.fatal()) // + << "Invariant failed: shares issuer and vault " + "pseudo-account must be the same"; + result = false; + } - auto const sleSharesIssuer = view.read(keylet::account(updatedShares->share.getIssuer())); - if (!sleSharesIssuer) - { - JLOG(j.fatal()) // - << "Invariant failed: shares issuer must exist"; + auto const sleSharesIssuer = + view.read(keylet::account(updatedShares->share.getIssuer())); + if (!sleSharesIssuer) + { + JLOG(j.fatal()) // + << "Invariant failed: shares issuer must exist"; + return false; + } + + if (!isPseudoAccount(sleSharesIssuer)) + { + JLOG(j.fatal()) // + << "Invariant failed: shares issuer must be a " + "pseudo-account"; + result = false; + } + + if (auto const vaultId = (*sleSharesIssuer)[~sfVaultID]; + !vaultId || *vaultId != afterVault.key) + { + JLOG(j.fatal()) // + << "Invariant failed: shares issuer pseudo-account " + "must point back to the vault"; + result = false; + } + + return result; + } + case ttVAULT_SET: { + bool result = true; + + XRPL_ASSERT( + !beforeVault_.empty(), "xrpl::ValidVault::finalize : set updated a vault"); + auto const& beforeVault = beforeVault_[0]; + + auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId); + if (vaultDeltaAssets) + { + JLOG(j.fatal()) << // + "Invariant failed: set must not change vault balance"; + result = false; + } + + if (beforeVault.assetsTotal != afterVault.assetsTotal) + { + JLOG(j.fatal()) << // + "Invariant failed: set must not change assets " + "outstanding"; + result = false; + } + + if (afterVault.assetsMaximum > zero && + afterVault.assetsTotal > afterVault.assetsMaximum) + { + JLOG(j.fatal()) << // + "Invariant failed: set assets outstanding must not " + "exceed assets maximum"; + result = false; + } + + if (beforeVault.assetsAvailable != afterVault.assetsAvailable) + { + JLOG(j.fatal()) << // + "Invariant failed: set must not change assets " + "available"; + result = false; + } + + if (beforeShares && updatedShares && + beforeShares->sharesTotal != updatedShares->sharesTotal) + { + JLOG(j.fatal()) << // + "Invariant failed: set must not change shares " + "outstanding"; + result = false; + } + + return result; + } + case ttVAULT_DEPOSIT: { + bool result = true; + + XRPL_ASSERT( + !beforeVault_.empty(), "xrpl::ValidVault::finalize : deposit updated a vault"); + auto const& beforeVault = beforeVault_[0]; + + auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId); + + if (!vaultDeltaAssets) + { + JLOG(j.fatal()) << // + "Invariant failed: deposit must change vault balance"; + return false; // That's all we can do + } + + if (*vaultDeltaAssets > tx[sfAmount]) + { + JLOG(j.fatal()) << // + "Invariant failed: deposit must not change vault " + "balance by more than deposited amount"; + result = false; + } + + if (*vaultDeltaAssets <= zero) + { + JLOG(j.fatal()) << // + "Invariant failed: deposit must increase vault balance"; + result = false; + } + + // Any payments (including deposits) made by the issuer + // do not change their balance, but create funds instead. + bool const issuerDeposit = [&]() -> bool { + if (vaultAsset.native()) return false; - } + return tx[sfAccount] == vaultAsset.getIssuer(); + }(); - if (!isPseudoAccount(sleSharesIssuer)) - { - JLOG(j.fatal()) // - << "Invariant failed: shares issuer must be a " - "pseudo-account"; - result = false; - } - - if (auto const vaultId = (*sleSharesIssuer)[~sfVaultID]; !vaultId || *vaultId != afterVault.key) - { - JLOG(j.fatal()) // - << "Invariant failed: shares issuer pseudo-account " - "must point back to the vault"; - result = false; - } - - return result; - } - case ttVAULT_SET: { - bool result = true; - - XRPL_ASSERT(!beforeVault_.empty(), "xrpl::ValidVault::finalize : set updated a vault"); - auto const& beforeVault = beforeVault_[0]; - - auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId); - if (vaultDeltaAssets) - { - JLOG(j.fatal()) << // - "Invariant failed: set must not change vault balance"; - result = false; - } - - if (beforeVault.assetsTotal != afterVault.assetsTotal) - { - JLOG(j.fatal()) << // - "Invariant failed: set must not change assets " - "outstanding"; - result = false; - } - - if (afterVault.assetsMaximum > zero && afterVault.assetsTotal > afterVault.assetsMaximum) - { - JLOG(j.fatal()) << // - "Invariant failed: set assets outstanding must not " - "exceed assets maximum"; - result = false; - } - - if (beforeVault.assetsAvailable != afterVault.assetsAvailable) - { - JLOG(j.fatal()) << // - "Invariant failed: set must not change assets " - "available"; - result = false; - } - - if (beforeShares && updatedShares && beforeShares->sharesTotal != updatedShares->sharesTotal) - { - JLOG(j.fatal()) << // - "Invariant failed: set must not change shares " - "outstanding"; - result = false; - } - - return result; - } - case ttVAULT_DEPOSIT: { - bool result = true; - - XRPL_ASSERT(!beforeVault_.empty(), "xrpl::ValidVault::finalize : deposit updated a vault"); - auto const& beforeVault = beforeVault_[0]; - - auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId); - - if (!vaultDeltaAssets) - { - JLOG(j.fatal()) << // - "Invariant failed: deposit must change vault balance"; - return false; // That's all we can do - } - - if (*vaultDeltaAssets > tx[sfAmount]) - { - JLOG(j.fatal()) << // - "Invariant failed: deposit must not change vault " - "balance by more than deposited amount"; - result = false; - } - - if (*vaultDeltaAssets <= zero) - { - JLOG(j.fatal()) << // - "Invariant failed: deposit must increase vault balance"; - result = false; - } - - // Any payments (including deposits) made by the issuer - // do not change their balance, but create funds instead. - bool const issuerDeposit = [&]() -> bool { - if (vaultAsset.native()) - return false; - return tx[sfAccount] == vaultAsset.getIssuer(); - }(); - - if (!issuerDeposit) - { - auto const accountDeltaAssets = deltaAssetsTxAccount(); - if (!accountDeltaAssets) - { - JLOG(j.fatal()) << // - "Invariant failed: deposit must change depositor " - "balance"; - return false; - } - - if (*accountDeltaAssets >= zero) - { - JLOG(j.fatal()) << // - "Invariant failed: deposit must decrease depositor " - "balance"; - result = false; - } - - if (*accountDeltaAssets * -1 != *vaultDeltaAssets) - { - JLOG(j.fatal()) << // - "Invariant failed: deposit must change vault and " - "depositor balance by equal amount"; - result = false; - } - } - - if (afterVault.assetsMaximum > zero && afterVault.assetsTotal > afterVault.assetsMaximum) - { - JLOG(j.fatal()) << // - "Invariant failed: deposit assets outstanding must not " - "exceed assets maximum"; - result = false; - } - - auto const accountDeltaShares = deltaShares(tx[sfAccount]); - if (!accountDeltaShares) + if (!issuerDeposit) + { + auto const accountDeltaAssets = deltaAssetsTxAccount(); + if (!accountDeltaAssets) { JLOG(j.fatal()) << // "Invariant failed: deposit must change depositor " - "shares"; - return false; // That's all we can do - } - - if (*accountDeltaShares <= zero) - { - JLOG(j.fatal()) << // - "Invariant failed: deposit must increase depositor " - "shares"; - result = false; - } - - auto const vaultDeltaShares = deltaShares(afterVault.pseudoId); - if (!vaultDeltaShares || *vaultDeltaShares == zero) - { - JLOG(j.fatal()) << // - "Invariant failed: deposit must change vault shares"; - return false; // That's all we can do - } - - if (*vaultDeltaShares * -1 != *accountDeltaShares) - { - JLOG(j.fatal()) << // - "Invariant failed: deposit must change depositor and " - "vault shares by equal amount"; - result = false; - } - - if (beforeVault.assetsTotal + *vaultDeltaAssets != afterVault.assetsTotal) - { - JLOG(j.fatal()) << "Invariant failed: deposit and assets " - "outstanding must add up"; - result = false; - } - if (beforeVault.assetsAvailable + *vaultDeltaAssets != afterVault.assetsAvailable) - { - JLOG(j.fatal()) << "Invariant failed: deposit and assets " - "available must add up"; - result = false; - } - - return result; - } - case ttVAULT_WITHDRAW: { - bool result = true; - - XRPL_ASSERT( - !beforeVault_.empty(), - "xrpl::ValidVault::finalize : withdrawal updated a " - "vault"); - auto const& beforeVault = beforeVault_[0]; - - auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId); - - if (!vaultDeltaAssets) - { - JLOG(j.fatal()) << "Invariant failed: withdrawal must " - "change vault balance"; - return false; // That's all we can do - } - - if (*vaultDeltaAssets >= zero) - { - JLOG(j.fatal()) << "Invariant failed: withdrawal must " - "decrease vault balance"; - result = false; - } - - // Any payments (including withdrawal) going to the issuer - // do not change their balance, but destroy funds instead. - bool const issuerWithdrawal = [&]() -> bool { - if (vaultAsset.native()) - return false; - auto const destination = tx[~sfDestination].value_or(tx[sfAccount]); - return destination == vaultAsset.getIssuer(); - }(); - - if (!issuerWithdrawal) - { - auto const accountDeltaAssets = deltaAssetsTxAccount(); - auto const otherAccountDelta = [&]() -> std::optional { - if (auto const destination = tx[~sfDestination]; - destination && *destination != tx[sfAccount]) - return deltaAssets(*destination); - return std::nullopt; - }(); - - if (accountDeltaAssets.has_value() == otherAccountDelta.has_value()) - { - JLOG(j.fatal()) << // - "Invariant failed: withdrawal must change one " - "destination balance"; - return false; - } - - auto const destinationDelta = // - accountDeltaAssets ? *accountDeltaAssets : *otherAccountDelta; - - if (destinationDelta <= zero) - { - JLOG(j.fatal()) << // - "Invariant failed: withdrawal must increase " - "destination balance"; - result = false; - } - - if (*vaultDeltaAssets * -1 != destinationDelta) - { - JLOG(j.fatal()) << // - "Invariant failed: withdrawal must change vault " - "and destination balance by equal amount"; - result = false; - } - } - - auto const accountDeltaShares = deltaShares(tx[sfAccount]); - if (!accountDeltaShares) - { - JLOG(j.fatal()) << // - "Invariant failed: withdrawal must change depositor " - "shares"; + "balance"; return false; } - if (*accountDeltaShares >= zero) + if (*accountDeltaAssets >= zero) { JLOG(j.fatal()) << // - "Invariant failed: withdrawal must decrease depositor " - "shares"; + "Invariant failed: deposit must decrease depositor " + "balance"; result = false; } - auto const vaultDeltaShares = deltaShares(afterVault.pseudoId); - if (!vaultDeltaShares || *vaultDeltaShares == zero) + if (*accountDeltaAssets * -1 != *vaultDeltaAssets) { JLOG(j.fatal()) << // - "Invariant failed: withdrawal must change vault shares"; + "Invariant failed: deposit must change vault and " + "depositor balance by equal amount"; + result = false; + } + } + + if (afterVault.assetsMaximum > zero && + afterVault.assetsTotal > afterVault.assetsMaximum) + { + JLOG(j.fatal()) << // + "Invariant failed: deposit assets outstanding must not " + "exceed assets maximum"; + result = false; + } + + auto const accountDeltaShares = deltaShares(tx[sfAccount]); + if (!accountDeltaShares) + { + JLOG(j.fatal()) << // + "Invariant failed: deposit must change depositor " + "shares"; + return false; // That's all we can do + } + + if (*accountDeltaShares <= zero) + { + JLOG(j.fatal()) << // + "Invariant failed: deposit must increase depositor " + "shares"; + result = false; + } + + auto const vaultDeltaShares = deltaShares(afterVault.pseudoId); + if (!vaultDeltaShares || *vaultDeltaShares == zero) + { + JLOG(j.fatal()) << // + "Invariant failed: deposit must change vault shares"; + return false; // That's all we can do + } + + if (*vaultDeltaShares * -1 != *accountDeltaShares) + { + JLOG(j.fatal()) << // + "Invariant failed: deposit must change depositor and " + "vault shares by equal amount"; + result = false; + } + + if (beforeVault.assetsTotal + *vaultDeltaAssets != afterVault.assetsTotal) + { + JLOG(j.fatal()) << "Invariant failed: deposit and assets " + "outstanding must add up"; + result = false; + } + if (beforeVault.assetsAvailable + *vaultDeltaAssets != afterVault.assetsAvailable) + { + JLOG(j.fatal()) << "Invariant failed: deposit and assets " + "available must add up"; + result = false; + } + + return result; + } + case ttVAULT_WITHDRAW: { + bool result = true; + + XRPL_ASSERT( + !beforeVault_.empty(), + "xrpl::ValidVault::finalize : withdrawal updated a " + "vault"); + auto const& beforeVault = beforeVault_[0]; + + auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId); + + if (!vaultDeltaAssets) + { + JLOG(j.fatal()) << "Invariant failed: withdrawal must " + "change vault balance"; + return false; // That's all we can do + } + + if (*vaultDeltaAssets >= zero) + { + JLOG(j.fatal()) << "Invariant failed: withdrawal must " + "decrease vault balance"; + result = false; + } + + // Any payments (including withdrawal) going to the issuer + // do not change their balance, but destroy funds instead. + bool const issuerWithdrawal = [&]() -> bool { + if (vaultAsset.native()) + return false; + auto const destination = tx[~sfDestination].value_or(tx[sfAccount]); + return destination == vaultAsset.getIssuer(); + }(); + + if (!issuerWithdrawal) + { + auto const accountDeltaAssets = deltaAssetsTxAccount(); + auto const otherAccountDelta = [&]() -> std::optional { + if (auto const destination = tx[~sfDestination]; + destination && *destination != tx[sfAccount]) + return deltaAssets(*destination); + return std::nullopt; + }(); + + if (accountDeltaAssets.has_value() == otherAccountDelta.has_value()) + { + JLOG(j.fatal()) << // + "Invariant failed: withdrawal must change one " + "destination balance"; + return false; + } + + auto const destinationDelta = // + accountDeltaAssets ? *accountDeltaAssets : *otherAccountDelta; + + if (destinationDelta <= zero) + { + JLOG(j.fatal()) << // + "Invariant failed: withdrawal must increase " + "destination balance"; + result = false; + } + + if (*vaultDeltaAssets * -1 != destinationDelta) + { + JLOG(j.fatal()) << // + "Invariant failed: withdrawal must change vault " + "and destination balance by equal amount"; + result = false; + } + } + + auto const accountDeltaShares = deltaShares(tx[sfAccount]); + if (!accountDeltaShares) + { + JLOG(j.fatal()) << // + "Invariant failed: withdrawal must change depositor " + "shares"; + return false; + } + + if (*accountDeltaShares >= zero) + { + JLOG(j.fatal()) << // + "Invariant failed: withdrawal must decrease depositor " + "shares"; + result = false; + } + + auto const vaultDeltaShares = deltaShares(afterVault.pseudoId); + if (!vaultDeltaShares || *vaultDeltaShares == zero) + { + JLOG(j.fatal()) << // + "Invariant failed: withdrawal must change vault shares"; + return false; // That's all we can do + } + + if (*vaultDeltaShares * -1 != *accountDeltaShares) + { + JLOG(j.fatal()) << // + "Invariant failed: withdrawal must change depositor " + "and vault shares by equal amount"; + result = false; + } + + // Note, vaultBalance is negative (see check above) + if (beforeVault.assetsTotal + *vaultDeltaAssets != afterVault.assetsTotal) + { + JLOG(j.fatal()) << "Invariant failed: withdrawal and " + "assets outstanding must add up"; + result = false; + } + + if (beforeVault.assetsAvailable + *vaultDeltaAssets != afterVault.assetsAvailable) + { + JLOG(j.fatal()) << "Invariant failed: withdrawal and " + "assets available must add up"; + result = false; + } + + return result; + } + case ttVAULT_CLAWBACK: { + bool result = true; + + XRPL_ASSERT( + !beforeVault_.empty(), "xrpl::ValidVault::finalize : clawback updated a vault"); + auto const& beforeVault = beforeVault_[0]; + + if (vaultAsset.native() || vaultAsset.getIssuer() != tx[sfAccount]) + { + // The owner can use clawback to force-burn shares when the + // vault is empty but there are outstanding shares + if (!(beforeShares && beforeShares->sharesTotal > 0 && + vaultHoldsNoAssets(beforeVault) && beforeVault.owner == tx[sfAccount])) + { + JLOG(j.fatal()) << // + "Invariant failed: clawback may only be performed " + "by the asset issuer, or by the vault owner of an " + "empty vault"; return false; // That's all we can do } + } - if (*vaultDeltaShares * -1 != *accountDeltaShares) + auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId); + if (vaultDeltaAssets) + { + if (*vaultDeltaAssets >= zero) { JLOG(j.fatal()) << // - "Invariant failed: withdrawal must change depositor " - "and vault shares by equal amount"; + "Invariant failed: clawback must decrease vault " + "balance"; result = false; } - // Note, vaultBalance is negative (see check above) if (beforeVault.assetsTotal + *vaultDeltaAssets != afterVault.assetsTotal) { - JLOG(j.fatal()) << "Invariant failed: withdrawal and " - "assets outstanding must add up"; + JLOG(j.fatal()) << // + "Invariant failed: clawback and assets outstanding " + "must add up"; result = false; } - if (beforeVault.assetsAvailable + *vaultDeltaAssets != afterVault.assetsAvailable) + if (beforeVault.assetsAvailable + *vaultDeltaAssets != + afterVault.assetsAvailable) { - JLOG(j.fatal()) << "Invariant failed: withdrawal and " - "assets available must add up"; + JLOG(j.fatal()) << // + "Invariant failed: clawback and assets available " + "must add up"; result = false; } - - return result; } - case ttVAULT_CLAWBACK: { - bool result = true; - - XRPL_ASSERT(!beforeVault_.empty(), "xrpl::ValidVault::finalize : clawback updated a vault"); - auto const& beforeVault = beforeVault_[0]; - - if (vaultAsset.native() || vaultAsset.getIssuer() != tx[sfAccount]) - { - // The owner can use clawback to force-burn shares when the - // vault is empty but there are outstanding shares - if (!(beforeShares && beforeShares->sharesTotal > 0 && vaultHoldsNoAssets(beforeVault) && - beforeVault.owner == tx[sfAccount])) - { - JLOG(j.fatal()) << // - "Invariant failed: clawback may only be performed " - "by the asset issuer, or by the vault owner of an " - "empty vault"; - return false; // That's all we can do - } - } - - auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId); - if (vaultDeltaAssets) - { - if (*vaultDeltaAssets >= zero) - { - JLOG(j.fatal()) << // - "Invariant failed: clawback must decrease vault " - "balance"; - result = false; - } - - if (beforeVault.assetsTotal + *vaultDeltaAssets != afterVault.assetsTotal) - { - JLOG(j.fatal()) << // - "Invariant failed: clawback and assets outstanding " - "must add up"; - result = false; - } - - if (beforeVault.assetsAvailable + *vaultDeltaAssets != afterVault.assetsAvailable) - { - JLOG(j.fatal()) << // - "Invariant failed: clawback and assets available " - "must add up"; - result = false; - } - } - else if (!vaultHoldsNoAssets(beforeVault)) - { - JLOG(j.fatal()) << // - "Invariant failed: clawback must change vault balance"; - return false; // That's all we can do - } - - auto const accountDeltaShares = deltaShares(tx[sfHolder]); - if (!accountDeltaShares) - { - JLOG(j.fatal()) << // - "Invariant failed: clawback must change holder shares"; - return false; // That's all we can do - } - - if (*accountDeltaShares >= zero) - { - JLOG(j.fatal()) << // - "Invariant failed: clawback must decrease holder " - "shares"; - result = false; - } - - auto const vaultDeltaShares = deltaShares(afterVault.pseudoId); - if (!vaultDeltaShares || *vaultDeltaShares == zero) - { - JLOG(j.fatal()) << // - "Invariant failed: clawback must change vault shares"; - return false; // That's all we can do - } - - if (*vaultDeltaShares * -1 != *accountDeltaShares) - { - JLOG(j.fatal()) << // - "Invariant failed: clawback must change holder and " - "vault shares by equal amount"; - result = false; - } - - return result; + else if (!vaultHoldsNoAssets(beforeVault)) + { + JLOG(j.fatal()) << // + "Invariant failed: clawback must change vault balance"; + return false; // That's all we can do } - case ttLOAN_SET: - case ttLOAN_MANAGE: - case ttLOAN_PAY: { - // TBD - return true; + auto const accountDeltaShares = deltaShares(tx[sfHolder]); + if (!accountDeltaShares) + { + JLOG(j.fatal()) << // + "Invariant failed: clawback must change holder shares"; + return false; // That's all we can do } - default: - // LCOV_EXCL_START - UNREACHABLE("xrpl::ValidVault::finalize : unknown transaction type"); - return false; - // LCOV_EXCL_STOP + if (*accountDeltaShares >= zero) + { + JLOG(j.fatal()) << // + "Invariant failed: clawback must decrease holder " + "shares"; + result = false; + } + + auto const vaultDeltaShares = deltaShares(afterVault.pseudoId); + if (!vaultDeltaShares || *vaultDeltaShares == zero) + { + JLOG(j.fatal()) << // + "Invariant failed: clawback must change vault shares"; + return false; // That's all we can do + } + + if (*vaultDeltaShares * -1 != *accountDeltaShares) + { + JLOG(j.fatal()) << // + "Invariant failed: clawback must change holder and " + "vault shares by equal amount"; + result = false; + } + + return result; } - }(); + + case ttLOAN_SET: + case ttLOAN_MANAGE: + case ttLOAN_PAY: { + // TBD + return true; + } + + default: + // LCOV_EXCL_START + UNREACHABLE("xrpl::ValidVault::finalize : unknown transaction type"); + return false; + // LCOV_EXCL_STOP + } + }(); if (!result) { diff --git a/src/xrpld/app/tx/detail/SignerEntries.cpp b/src/libxrpl/tx/SignerEntries.cpp similarity index 95% rename from src/xrpld/app/tx/detail/SignerEntries.cpp rename to src/libxrpl/tx/SignerEntries.cpp index 3526148638..aca1f2c19a 100644 --- a/src/xrpld/app/tx/detail/SignerEntries.cpp +++ b/src/libxrpl/tx/SignerEntries.cpp @@ -1,8 +1,8 @@ -#include - #include #include #include +#include +#include #include #include diff --git a/src/xrpld/app/tx/detail/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp similarity index 91% rename from src/xrpld/app/tx/detail/Transactor.cpp rename to src/libxrpl/tx/Transactor.cpp index b3b5d8b9bc..9da1028b3a 100644 --- a/src/xrpld/app/tx/detail/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -1,22 +1,21 @@ -#include -#include -#include -#include -#include -#include -#include -#include - #include #include +#include #include #include #include #include #include #include +#include #include #include +#include +#include +#include +#include +#include +#include namespace xrpl { @@ -33,7 +32,7 @@ preflight0(PreflightContext const& ctx, std::uint32_t flagMask) if (!isPseudoTx(ctx.tx) || ctx.tx.isFieldPresent(sfNetworkID)) { - uint32_t nodeNID = ctx.app.config().NETWORK_ID; + uint32_t nodeNID = ctx.registry.getNetworkIDService().getNetworkID(); std::optional txNID = ctx.tx[~sfNetworkID]; if (nodeNID <= 1024) @@ -65,7 +64,8 @@ preflight0(PreflightContext const& ctx, std::uint32_t flagMask) if (ctx.tx.getFlags() & flagMask) { - JLOG(ctx.j.debug()) << ctx.tx.peekAtField(sfTransactionType).getFullText() << ": invalid flags."; + JLOG(ctx.j.debug()) << ctx.tx.peekAtField(sfTransactionType).getFullText() + << ": invalid flags."; return temINVALID_FLAG; } @@ -81,7 +81,8 @@ namespace detail { NotTEC preflightCheckSigningKey(STObject const& sigObject, beast::Journal j) { - if (auto const spk = sigObject.getFieldVL(sfSigningPubKey); !spk.empty() && !publicKeyType(makeSlice(spk))) + if (auto const spk = sigObject.getFieldVL(sfSigningPubKey); + !spk.empty() && !publicKeyType(makeSlice(spk))) { JLOG(j.debug()) << "preflightCheckSigningKey: invalid signing key"; return temBAD_SIGNATURE; @@ -178,7 +179,8 @@ Transactor::preflight1(PreflightContext const& ctx, std::uint32_t flagMask) return temINVALID_FLAG; XRPL_ASSERT( - ctx.tx.isFlag(tfInnerBatchTxn) == ctx.parentBatchId.has_value() || !ctx.rules.enabled(featureBatch), + ctx.tx.isFlag(tfInnerBatchTxn) == ctx.parentBatchId.has_value() || + !ctx.rules.enabled(featureBatch), "Inner batch transaction must have a parent batch ID."); return tesSUCCESS; @@ -205,7 +207,7 @@ Transactor::preflight2(PreflightContext const& ctx) // Do not add any checks after this point that are relevant for // batch inner transactions. They will be skipped. - auto const sigValid = checkValidity(ctx.app.getHashRouter(), ctx.tx, ctx.rules, ctx.app.config()); + auto const sigValid = checkValidity(ctx.registry.getHashRouter(), ctx.tx, ctx.rules); if (sigValid.first == Validity::SigBad) { // LCOV_EXCL_START JLOG(ctx.j.debug()) << "preflight2: bad signature. " << sigValid.second; @@ -277,7 +279,8 @@ Transactor::calculateBaseFee(ReadView const& view, STTx const& tx) // Each signer adds one more baseFee to the minimum required fee // for the transaction. - std::size_t const signerCount = tx.isFieldPresent(sfSigners) ? tx.getFieldArray(sfSigners).size() : 0; + std::size_t const signerCount = + tx.isFieldPresent(sfSigners) ? tx.getFieldArray(sfSigners).size() : 0; return baseFee + (signerCount * baseFee); } @@ -304,9 +307,13 @@ Transactor::calculateOwnerReserveFee(ReadView const& view, STTx const& tx) } XRPAmount -Transactor::minimumFee(Application& app, XRPAmount baseFee, Fees const& fees, ApplyFlags flags) +Transactor::minimumFee( + ServiceRegistry& registry, + XRPAmount baseFee, + Fees const& fees, + ApplyFlags flags) { - return scaleFeeLoad(baseFee, app.getFeeTrack(), fees, flags & tapUNLIMITED); + return scaleFeeLoad(baseFee, registry.getFeeTrack(), fees, flags & tapUNLIMITED); } TER @@ -332,11 +339,12 @@ Transactor::checkFee(PreclaimContext const& ctx, XRPAmount baseFee) // Only check fee is sufficient when the ledger is open. if (ctx.view.open()) { - auto const feeDue = minimumFee(ctx.app, baseFee, ctx.view.fees(), ctx.flags); + auto const feeDue = minimumFee(ctx.registry, baseFee, ctx.view.fees(), ctx.flags); if (feePaid < feeDue) { - JLOG(ctx.j.trace()) << "Insufficient fee paid: " << to_string(feePaid) << "/" << to_string(feeDue); + JLOG(ctx.j.trace()) << "Insufficient fee paid: " << to_string(feePaid) << "/" + << to_string(feeDue); return telINSUF_FEE_P; } } @@ -344,8 +352,8 @@ Transactor::checkFee(PreclaimContext const& ctx, XRPAmount baseFee) if (feePaid == beast::zero) return tesSUCCESS; - auto const id = - ctx.tx.isFieldPresent(sfDelegate) ? ctx.tx.getAccountID(sfDelegate) : ctx.tx.getAccountID(sfAccount); + auto const id = ctx.tx.isFieldPresent(sfDelegate) ? ctx.tx.getAccountID(sfDelegate) + : ctx.tx.getAccountID(sfAccount); auto const sle = ctx.view.read(keylet::account(id)); if (!sle) return terNO_ACCOUNT; @@ -412,7 +420,8 @@ Transactor::checkSeqProxy(ReadView const& view, STTx const& tx, beast::Journal j if (!sle) { - JLOG(j.trace()) << "applyTransaction: delay: source account does not exist " << toBase58(id); + JLOG(j.trace()) << "applyTransaction: delay: source account does not exist " + << toBase58(id); return terNO_ACCOUNT; } @@ -476,7 +485,8 @@ Transactor::checkPriorTxAndLastLedger(PreclaimContext const& ctx) if (!sle) { - JLOG(ctx.j.trace()) << "applyTransaction: delay: source account does not exist " << toBase58(id); + JLOG(ctx.j.trace()) << "applyTransaction: delay: source account does not exist " + << toBase58(id); return terNO_ACCOUNT; } @@ -484,7 +494,8 @@ Transactor::checkPriorTxAndLastLedger(PreclaimContext const& ctx) (sle->getFieldH256(sfAccountTxnID) != ctx.tx.getFieldH256(sfAccountTxnID))) return tefWRONG_PRIOR; - if (ctx.tx.isFieldPresent(sfLastLedgerSequence) && (ctx.view.seq() > ctx.tx.getFieldU32(sfLastLedgerSequence))) + if (ctx.tx.isFieldPresent(sfLastLedgerSequence) && + (ctx.view.seq() > ctx.tx.getFieldU32(sfLastLedgerSequence))) return tefMAX_LEDGER; if (ctx.view.txExists(ctx.tx.getTransactionID())) @@ -511,7 +522,11 @@ Transactor::consumeSeqProxy(SLE::pointer const& sleAccount) // Remove a single Ticket from the ledger. TER -Transactor::ticketDelete(ApplyView& view, AccountID const& account, uint256 const& ticketIndex, beast::Journal j) +Transactor::ticketDelete( + ApplyView& view, + AccountID const& account, + uint256 const& ticketIndex, + beast::Journal j) { // Delete the Ticket, adjust the account root ticket count, and // reduce the owner count. @@ -585,7 +600,9 @@ Transactor::apply() // sle must exist except for transactions // that allow zero account. - XRPL_ASSERT(sle != nullptr || account_ == beast::zero, "xrpl::Transactor::apply : non-null SLE or zero account"); + XRPL_ASSERT( + sle != nullptr || account_ == beast::zero, + "xrpl::Transactor::apply : non-null SLE or zero account"); if (sle) { @@ -633,7 +650,8 @@ Transactor::checkSign( if (parentBatchId && view.rules().enabled(featureBatch)) { // Defensive Check: These values are also checked in Batch::preflight - if (sigObject.isFieldPresent(sfTxnSignature) || !pkSigner.empty() || sigObject.isFieldPresent(sfSigners)) + if (sigObject.isFieldPresent(sfTxnSignature) || !pkSigner.empty() || + sigObject.isFieldPresent(sfSigners)) { return temINVALID_FLAG; // LCOV_EXCL_LINE } @@ -664,7 +682,8 @@ Transactor::checkSign( } // Look up the account. - auto const idSigner = pkSigner.empty() ? idAccount : calcAccountID(PublicKey(makeSlice(pkSigner))); + auto const idSigner = + pkSigner.empty() ? idAccount : calcAccountID(PublicKey(makeSlice(pkSigner))); auto const sleAccount = view.read(keylet::account(idAccount)); if (!sleAccount) return terNO_ACCOUNT; @@ -675,8 +694,8 @@ Transactor::checkSign( NotTEC Transactor::checkSign(PreclaimContext const& ctx) { - auto const idAccount = - ctx.tx.isFieldPresent(sfDelegate) ? ctx.tx.getAccountID(sfDelegate) : ctx.tx.getAccountID(sfAccount); + auto const idAccount = ctx.tx.isFieldPresent(sfDelegate) ? ctx.tx.getAccountID(sfDelegate) + : ctx.tx.getAccountID(sfAccount); return checkSign(ctx.view, ctx.flags, ctx.parentBatchId, idAccount, ctx.tx, ctx.j); } @@ -692,7 +711,8 @@ Transactor::checkBatchSign(PreclaimContext const& ctx) Blob const& pkSigner = signer.getFieldVL(sfSigningPubKey); if (pkSigner.empty()) { - if (ret = checkMultiSign(ctx.view, ctx.flags, idAccount, signer, ctx.j); !isTesSuccess(ret)) + if (ret = checkMultiSign(ctx.view, ctx.flags, idAccount, signer, ctx.j); + !isTesSuccess(ret)) return ret; } else @@ -715,7 +735,8 @@ Transactor::checkBatchSign(PreclaimContext const& ctx) return tesSUCCESS; } - if (ret = checkSingleSign(ctx.view, idSigner, idAccount, sleAccount, ctx.j); !isTesSuccess(ret)) + if (ret = checkSingleSign(ctx.view, idSigner, idAccount, sleAccount, ctx.j); + !isTesSuccess(ret)) return ret; } } @@ -774,9 +795,11 @@ Transactor::checkMultiSign( // We have plans to support multiple SignerLists in the future. The // presence and defaulted value of the SignerListID field will enable that. XRPL_ASSERT( - sleAccountSigners->isFieldPresent(sfSignerListID), "xrpl::Transactor::checkMultiSign : has signer list ID"); + sleAccountSigners->isFieldPresent(sfSignerListID), + "xrpl::Transactor::checkMultiSign : has signer list ID"); XRPL_ASSERT( - sleAccountSigners->getFieldU32(sfSignerListID) == 0, "xrpl::Transactor::checkMultiSign : signer list ID is 0"); + sleAccountSigners->getFieldU32(sfSignerListID) == 0, + "xrpl::Transactor::checkMultiSign : signer list ID is 0"); auto accountSigners = SignerEntries::deserialize(*sleAccountSigners, j, "ledger"); if (!accountSigners) @@ -932,7 +955,10 @@ removeUnfundedOffers(ApplyView& view, std::vector const& offers, beast: } static void -removeExpiredNFTokenOffers(ApplyView& view, std::vector const& offers, beast::Journal viewJ) +removeExpiredNFTokenOffers( + ApplyView& view, + std::vector const& offers, + beast::Journal viewJ) { std::size_t removed = 0; @@ -958,11 +984,15 @@ removeExpiredCredentials(ApplyView& view, std::vector const& creds, bea } static void -removeDeletedTrustLines(ApplyView& view, std::vector const& trustLines, beast::Journal viewJ) +removeDeletedTrustLines( + ApplyView& view, + std::vector const& trustLines, + beast::Journal viewJ) { if (trustLines.size() > maxDeletableAMMTrustLines) { - JLOG(viewJ.error()) << "removeDeletedTrustLines: deleted trustlines exceed max " << trustLines.size(); + JLOG(viewJ.error()) << "removeDeletedTrustLines: deleted trustlines exceed max " + << trustLines.size(); return; } @@ -993,8 +1023,9 @@ Transactor::reset(XRPAmount fee) if (!txnAcct) return {tefINTERNAL, beast::zero}; - auto const payerSle = - ctx_.tx.isFieldPresent(sfDelegate) ? view().peek(keylet::account(ctx_.tx.getAccountID(sfDelegate))) : txnAcct; + auto const payerSle = ctx_.tx.isFieldPresent(sfDelegate) + ? view().peek(keylet::account(ctx_.tx.getAccountID(sfDelegate))) + : txnAcct; if (!payerSle) return {tefINTERNAL, beast::zero}; // LCOV_EXCL_LINE @@ -1002,7 +1033,8 @@ Transactor::reset(XRPAmount fee) // balance should have already been checked in checkFee / preFlight. XRPL_ASSERT( - balance != beast::zero && (!view().open() || balance >= fee), "xrpl::Transactor::reset : valid balance"); + balance != beast::zero && (!view().open() || balance >= fee), + "xrpl::Transactor::reset : valid balance"); // We retry/reject the transaction if the account balance is zero or // we're applying against an open ledger and the balance is less than @@ -1072,7 +1104,7 @@ Transactor::operator()() } #endif - if (auto const& trap = ctx_.app.trapTxID(); trap && *trap == ctx_.tx.getTransactionID()) + if (auto const& trap = ctx_.registry.trapTxID(); trap && *trap == ctx_.tx.getTransactionID()) { trapTransaction(*trap); } @@ -1102,8 +1134,8 @@ Transactor::operator()() applied = false; } else if ( - (result == tecOVERSIZE) || (result == tecKILLED) || (result == tecINCOMPLETE) || (result == tecEXPIRED) || - (isTecClaimHardFail(result, view().flags()))) + (result == tecOVERSIZE) || (result == tecKILLED) || (result == tecINCOMPLETE) || + (result == tecEXPIRED) || (isTecClaimHardFail(result, view().flags()))) { JLOG(j_.trace()) << "reapplying because of " << transToken(result); @@ -1153,7 +1185,8 @@ Transactor::operator()() removedTrustLines.push_back(index); } - if (doNFTokenOffers && before && after && (before->getType() == ltNFTOKEN_OFFER)) + if (doNFTokenOffers && before && after && + (before->getType() == ltNFTOKEN_OFFER)) expiredNFTokenOffers.push_back(index); if (doCredentials && before && after && (before->getType() == ltCREDENTIAL)) @@ -1173,16 +1206,16 @@ Transactor::operator()() // If necessary, remove any offers found unfunded during processing if ((result == tecOVERSIZE) || (result == tecKILLED)) - removeUnfundedOffers(view(), removedOffers, ctx_.app.journal("View")); + removeUnfundedOffers(view(), removedOffers, ctx_.registry.journal("View")); if (result == tecEXPIRED) - removeExpiredNFTokenOffers(view(), expiredNFTokenOffers, ctx_.app.journal("View")); + removeExpiredNFTokenOffers(view(), expiredNFTokenOffers, ctx_.registry.journal("View")); if (result == tecINCOMPLETE) - removeDeletedTrustLines(view(), removedTrustLines, ctx_.app.journal("View")); + removeDeletedTrustLines(view(), removedTrustLines, ctx_.registry.journal("View")); if (result == tecEXPIRED) - removeExpiredCredentials(view(), expiredCredentials, ctx_.app.journal("View")); + removeExpiredCredentials(view(), expiredCredentials, ctx_.registry.journal("View")); applied = isTecClaim(result); } diff --git a/src/xrpld/app/tx/detail/apply.cpp b/src/libxrpl/tx/apply.cpp similarity index 83% rename from src/xrpld/app/tx/detail/apply.cpp rename to src/libxrpl/tx/apply.cpp index 7babc415d5..def82aca18 100644 --- a/src/xrpld/app/tx/detail/apply.cpp +++ b/src/libxrpl/tx/apply.cpp @@ -1,10 +1,10 @@ -#include -#include -#include - #include +#include +#include #include #include +#include +#include namespace xrpl { @@ -18,7 +18,7 @@ constexpr HashRouterFlags SF_LOCALGOOD = HashRouterFlags::PRIVATE4; // Local ch //------------------------------------------------------------------------------ std::pair -checkValidity(HashRouter& router, STTx const& tx, Rules const& rules, Config const& config) +checkValidity(HashRouter& router, STTx const& tx, Rules const& rules) { auto const id = tx.getTransactionID(); auto const flags = router.getFlags(id); @@ -27,7 +27,8 @@ checkValidity(HashRouter& router, STTx const& tx, Rules const& rules, Config con if (tx.isFlag(tfInnerBatchTxn) && rules.enabled(featureBatch)) { // Defensive Check: These values are also checked in Batch::preflight - if (tx.isFieldPresent(sfTxnSignature) || !tx.getSigningPubKey().empty() || tx.isFieldPresent(sfSigners)) + if (tx.isFieldPresent(sfTxnSignature) || !tx.getSigningPubKey().empty() || + tx.isFieldPresent(sfSigners)) return {Validity::SigBad, "Malformed: Invalid inner batch transaction."}; // This block should probably have never been included in the @@ -107,32 +108,39 @@ forceValidity(HashRouter& router, uint256 const& txid, Validity validity) template ApplyResult -apply(Application& app, OpenView& view, PreflightChecks&& preflightChecks) +apply(ServiceRegistry& registry, OpenView& view, PreflightChecks&& preflightChecks) { NumberSO stNumberSO{view.rules().enabled(fixUniversalNumber)}; - return doApply(preclaim(preflightChecks(), app, view), app, view); + return doApply(preclaim(preflightChecks(), registry, view), registry, view); } ApplyResult -apply(Application& app, OpenView& view, STTx const& tx, ApplyFlags flags, beast::Journal j) +apply(ServiceRegistry& registry, OpenView& view, STTx const& tx, ApplyFlags flags, beast::Journal j) { - return apply(app, view, [&]() mutable { return preflight(app, view.rules(), tx, flags, j); }); + return apply( + registry, view, [&]() mutable { return preflight(registry, view.rules(), tx, flags, j); }); } ApplyResult apply( - Application& app, + ServiceRegistry& registry, OpenView& view, uint256 const& parentBatchId, STTx const& tx, ApplyFlags flags, beast::Journal j) { - return apply(app, view, [&]() mutable { return preflight(app, view.rules(), parentBatchId, tx, flags, j); }); + return apply(registry, view, [&]() mutable { + return preflight(registry, view.rules(), parentBatchId, tx, flags, j); + }); } static bool -applyBatchTransactions(Application& app, OpenView& batchView, STTx const& batchTxn, beast::Journal j) +applyBatchTransactions( + ServiceRegistry& registry, + OpenView& batchView, + STTx const& batchTxn, + beast::Journal j) { XRPL_ASSERT( batchTxn.getTxnType() == ttBATCH && batchTxn.getFieldArray(sfRawTransactions).size() != 0, @@ -141,12 +149,13 @@ applyBatchTransactions(Application& app, OpenView& batchView, STTx const& batchT auto const parentBatchId = batchTxn.getTransactionID(); auto const mode = batchTxn.getFlags(); - auto applyOneTransaction = [&app, &j, &parentBatchId, &batchView](STTx&& tx) { + auto applyOneTransaction = [®istry, &j, &parentBatchId, &batchView](STTx&& tx) { OpenView perTxBatchView(batch_view, batchView); - auto const ret = apply(app, perTxBatchView, parentBatchId, tx, tapBATCH, j); + auto const ret = apply(registry, perTxBatchView, parentBatchId, tx, tapBATCH, j); XRPL_ASSERT( - ret.applied == (isTesSuccess(ret.ter) || isTecClaim(ret.ter)), "Inner transaction should not be applied"); + ret.applied == (isTesSuccess(ret.ter) || isTecClaim(ret.ter)), + "Inner transaction should not be applied"); JLOG(j.debug()) << "BatchTrace[" << parentBatchId << "]: " << tx.getTransactionID() << " " << (ret.applied ? "applied" : "failure") << ": " << transToken(ret.ter); @@ -188,7 +197,7 @@ applyBatchTransactions(Application& app, OpenView& batchView, STTx const& batchT ApplyTransactionResult applyTransaction( - Application& app, + ServiceRegistry& registry, OpenView& view, STTx const& txn, bool retryAssured, @@ -203,7 +212,7 @@ applyTransaction( try { - auto const result = apply(app, view, txn, flags, j); + auto const result = apply(registry, view, txn, flags, j); if (result.applied) { @@ -215,7 +224,7 @@ applyTransaction( { OpenView wholeBatchView(batch_view, view); - if (applyBatchTransactions(app, wholeBatchView, txn, j)) + if (applyBatchTransactions(registry, wholeBatchView, txn, j)) wholeBatchView.apply(view); } diff --git a/src/xrpld/app/tx/detail/applySteps.cpp b/src/libxrpl/tx/applySteps.cpp similarity index 90% rename from src/xrpld/app/tx/detail/applySteps.cpp rename to src/libxrpl/tx/applySteps.cpp index 06f0db1a79..ad4a185078 100644 --- a/src/xrpld/app/tx/detail/applySteps.cpp +++ b/src/libxrpl/tx/applySteps.cpp @@ -1,4 +1,4 @@ -#include +#include #pragma push_macro("TRANSACTION") #undef TRANSACTION @@ -14,6 +14,7 @@ // DO NOT INCLUDE TRANSACTOR HEADER FILES HERE. // See the instructions at the top of transactions.macro instead. +#include #include #include @@ -130,7 +131,8 @@ invoke_preflight(PreflightContext const& ctx) { return with_txn_type(ctx.rules, ctx.tx.getTxnType(), [&]() { auto const tec = Transactor::invokePreflight(ctx); - return std::make_pair(tec, isTesSuccess(tec) ? consequences_helper(ctx) : TxConsequences{tec}); + return std::make_pair( + tec, isTesSuccess(tec) ? consequences_helper(ctx) : TxConsequences{tec}); }); } catch (UnknownTxnType const& e) @@ -224,8 +226,9 @@ invoke_calculateBaseFee(ReadView const& view, STTx const& tx) { try { - return with_txn_type( - view.rules(), tx.getTxnType(), [&]() { return T::calculateBaseFee(view, tx); }); + return with_txn_type(view.rules(), tx.getTxnType(), [&]() { + return T::calculateBaseFee(view, tx); + }); } catch (UnknownTxnType const& e) { @@ -243,7 +246,8 @@ TxConsequences::TxConsequences(NotTEC pfResult) , seqProx_(SeqProxy::sequence(0)) , sequencesConsumed_(0) { - XRPL_ASSERT(!isTesSuccess(pfResult), "xrpl::TxConsequences::TxConsequences : is not tesSUCCESS"); + XRPL_ASSERT( + !isTesSuccess(pfResult), "xrpl::TxConsequences::TxConsequences : is not tesSUCCESS"); } TxConsequences::TxConsequences(STTx const& tx) @@ -292,9 +296,14 @@ invoke_apply(ApplyContext& ctx) } PreflightResult -preflight(Application& app, Rules const& rules, STTx const& tx, ApplyFlags flags, beast::Journal j) +preflight( + ServiceRegistry& registry, + Rules const& rules, + STTx const& tx, + ApplyFlags flags, + beast::Journal j) { - PreflightContext const pfCtx(app, tx, rules, flags, j); + PreflightContext const pfCtx(registry, tx, rules, flags, j); try { return {pfCtx, invoke_preflight(pfCtx)}; @@ -308,14 +317,14 @@ preflight(Application& app, Rules const& rules, STTx const& tx, ApplyFlags flags PreflightResult preflight( - Application& app, + ServiceRegistry& registry, Rules const& rules, uint256 const& parentBatchId, STTx const& tx, ApplyFlags flags, beast::Journal j) { - PreflightContext const pfCtx(app, tx, parentBatchId, rules, flags, j); + PreflightContext const pfCtx(registry, tx, parentBatchId, rules, flags, j); try { return {pfCtx, invoke_preflight(pfCtx)}; @@ -328,7 +337,7 @@ preflight( } PreclaimResult -preclaim(PreflightResult const& preflightResult, Application& app, OpenView const& view) +preclaim(PreflightResult const& preflightResult, ServiceRegistry& registry, OpenView const& view) { std::optional ctx; if (preflightResult.rules != view.rules()) @@ -336,18 +345,23 @@ preclaim(PreflightResult const& preflightResult, Application& app, OpenView cons auto secondFlight = [&]() { if (preflightResult.parentBatchId) return preflight( - app, + registry, view.rules(), preflightResult.parentBatchId.value(), preflightResult.tx, preflightResult.flags, preflightResult.j); - return preflight(app, view.rules(), preflightResult.tx, preflightResult.flags, preflightResult.j); + return preflight( + registry, + view.rules(), + preflightResult.tx, + preflightResult.flags, + preflightResult.j); }(); ctx.emplace( - app, + registry, view, secondFlight.ter, secondFlight.tx, @@ -358,7 +372,7 @@ preclaim(PreflightResult const& preflightResult, Application& app, OpenView cons else { ctx.emplace( - app, + registry, view, preflightResult.ter, preflightResult.tx, @@ -393,7 +407,7 @@ calculateDefaultBaseFee(ReadView const& view, STTx const& tx) } ApplyResult -doApply(PreclaimResult const& preclaimResult, Application& app, OpenView& view) +doApply(PreclaimResult const& preclaimResult, ServiceRegistry& registry, OpenView& view) { if (preclaimResult.view.seq() != view.seq()) { @@ -406,7 +420,7 @@ doApply(PreclaimResult const& preclaimResult, Application& app, OpenView& view) if (!preclaimResult.likelyToClaimFee) return {preclaimResult.ter, false}; ApplyContext ctx( - app, + registry, view, preclaimResult.parentBatchId, preclaimResult.tx, diff --git a/src/xrpld/app/tx/detail/BookTip.cpp b/src/libxrpl/tx/paths/BookTip.cpp similarity index 97% rename from src/xrpld/app/tx/detail/BookTip.cpp rename to src/libxrpl/tx/paths/BookTip.cpp index 61010c0caa..f00da6d7c7 100644 --- a/src/xrpld/app/tx/detail/BookTip.cpp +++ b/src/libxrpl/tx/paths/BookTip.cpp @@ -1,4 +1,4 @@ -#include +#include namespace xrpl { diff --git a/src/xrpld/app/paths/Flow.cpp b/src/libxrpl/tx/paths/Flow.cpp similarity index 94% rename from src/xrpld/app/paths/Flow.cpp rename to src/libxrpl/tx/paths/Flow.cpp index 1f6d29bfb9..2178997049 100644 --- a/src/xrpld/app/paths/Flow.cpp +++ b/src/libxrpl/tx/paths/Flow.cpp @@ -1,13 +1,12 @@ -#include -#include -#include -#include -#include - #include #include #include #include +#include +#include +#include +#include +#include namespace xrpl { @@ -90,7 +89,8 @@ flow( if (j.trace()) { - j.trace() << "\nsrc: " << src << "\ndst: " << dst << "\nsrcIssue: " << srcIssue << "\ndstIssue: " << dstIssue; + j.trace() << "\nsrc: " << src << "\ndst: " << dst << "\nsrcIssue: " << srcIssue + << "\ndstIssue: " << dstIssue; j.trace() << "\nNumStrands: " << strands.size(); for (auto const& curStrand : strands) { diff --git a/src/xrpld/app/tx/detail/OfferStream.cpp b/src/libxrpl/tx/paths/OfferStream.cpp similarity index 89% rename from src/xrpld/app/tx/detail/OfferStream.cpp rename to src/libxrpl/tx/paths/OfferStream.cpp index 9f013de607..9d2a94e3a8 100644 --- a/src/xrpld/app/tx/detail/OfferStream.cpp +++ b/src/libxrpl/tx/paths/OfferStream.cpp @@ -1,10 +1,9 @@ -#include -#include - #include #include #include #include +#include +#include namespace xrpl { @@ -70,7 +69,8 @@ TOfferStreamBase::erase(ApplyView& view) p->setFieldV256(sfIndexes, v); view.update(p); - JLOG(j_.trace()) << "Missing offer " << tip_.index() << " removed from directory " << tip_.dir(); + JLOG(j_.trace()) << "Missing offer " << tip_.index() << " removed from directory " + << tip_.dir(); } static STAmount @@ -98,7 +98,8 @@ accountFundsHelper( // self funded return amtDefault; - return toAmount(accountHolds(view, id, issue.currency, issue.account, freezeHandling, j)); + return toAmount( + accountHolds(view, id, issue.currency, issue.account, freezeHandling, j)); } static XRPAmount @@ -110,7 +111,8 @@ accountFundsHelper( FreezeHandling freezeHandling, beast::Journal j) { - return toAmount(accountHolds(view, id, issue.currency, issue.account, freezeHandling, j)); + return toAmount( + accountHolds(view, id, issue.currency, issue.account, freezeHandling, j)); } template @@ -119,13 +121,16 @@ bool TOfferStreamBase::shouldRmSmallIncreasedQOffer() const { static_assert( - std::is_same_v || std::is_same_v, "STAmount is not supported"); + std::is_same_v || std::is_same_v, + "STAmount is not supported"); static_assert( - std::is_same_v || std::is_same_v, "STAmount is not supported"); + std::is_same_v || std::is_same_v, + "STAmount is not supported"); static_assert( - !std::is_same_v || !std::is_same_v, "Cannot have XRP/XRP offers"); + !std::is_same_v || !std::is_same_v, + "Cannot have XRP/XRP offers"); // Consider removing the offer if: // o `TakerPays` is XRP (because of XRP drops granularity) or @@ -231,8 +236,8 @@ TOfferStreamBase::step() continue; } - bool const deepFrozen = - isDeepFrozen(view_, offer_.owner(), offer_.issueIn().currency, offer_.issueIn().account); + bool const deepFrozen = isDeepFrozen( + view_, offer_.owner(), offer_.issueIn().currency, offer_.issueIn().account); if (deepFrozen) { JLOG(j_.trace()) << "Removing deep frozen unfunded offer " << entry->key(); @@ -242,7 +247,8 @@ TOfferStreamBase::step() } if (entry->isFieldPresent(sfDomainID) && - !permissioned_dex::offerInDomain(view_, entry->key(), entry->getFieldH256(sfDomainID), j_)) + !permissioned_dex::offerInDomain( + view_, entry->key(), entry->getFieldH256(sfDomainID), j_)) { JLOG(j_.trace()) << "Removing offer no longer in domain " << entry->key(); permRmOffer(entry->key()); @@ -251,7 +257,8 @@ TOfferStreamBase::step() } // Calculate owner funds - ownerFunds_ = accountFundsHelper(view_, offer_.owner(), amount.out, offer_.issueOut(), fhZERO_IF_FROZEN, j_); + ownerFunds_ = accountFundsHelper( + view_, offer_.owner(), amount.out, offer_.issueOut(), fhZERO_IF_FROZEN, j_); // Check for unfunded offer if (*ownerFunds_ <= beast::zero) @@ -259,8 +266,8 @@ TOfferStreamBase::step() // If the owner's balance in the pristine view is the same, // we haven't modified the balance and therefore the // offer is "found unfunded" versus "became unfunded" - auto const original_funds = - accountFundsHelper(cancelView_, offer_.owner(), amount.out, offer_.issueOut(), fhZERO_IF_FROZEN, j_); + auto const original_funds = accountFundsHelper( + cancelView_, offer_.owner(), amount.out, offer_.issueOut(), fhZERO_IF_FROZEN, j_); if (original_funds == *ownerFunds_) { @@ -312,8 +319,8 @@ TOfferStreamBase::step() if (rmSmallIncreasedQOffer) { - auto const original_funds = - accountFundsHelper(cancelView_, offer_.owner(), amount.out, offer_.issueOut(), fhZERO_IF_FROZEN, j_); + auto const original_funds = accountFundsHelper( + cancelView_, offer_.owner(), amount.out, offer_.issueOut(), fhZERO_IF_FROZEN, j_); if (original_funds == *ownerFunds_) { diff --git a/src/xrpld/app/paths/RippleCalc.cpp b/src/libxrpl/tx/paths/RippleCalc.cpp similarity index 84% rename from src/xrpld/app/paths/RippleCalc.cpp rename to src/libxrpl/tx/paths/RippleCalc.cpp index 0667e1971c..e87ecab90f 100644 --- a/src/xrpld/app/paths/RippleCalc.cpp +++ b/src/libxrpl/tx/paths/RippleCalc.cpp @@ -1,10 +1,9 @@ -#include -#include -#include - #include #include #include +#include +#include +#include namespace xrpl { namespace path { @@ -55,7 +54,8 @@ RippleCalc::rippleCalculate( }(); auto const sendMax = [&]() -> std::optional { - if (saMaxAmountReq >= beast::zero || saMaxAmountReq.getCurrency() != saDstAmountReq.getCurrency() || + if (saMaxAmountReq >= beast::zero || + saMaxAmountReq.getCurrency() != saDstAmountReq.getCurrency() || saMaxAmountReq.getIssuer() != uSrcAccountID) { return saMaxAmountReq; @@ -93,9 +93,9 @@ RippleCalc::rippleCalculate( } j.debug() << "RippleCalc Result> " - << " actualIn: " << flowOut.actualAmountIn << ", actualOut: " << flowOut.actualAmountOut - << ", result: " << flowOut.result() << ", dstAmtReq: " << saDstAmountReq - << ", sendMax: " << saMaxAmountReq; + << " actualIn: " << flowOut.actualAmountIn + << ", actualOut: " << flowOut.actualAmountOut << ", result: " << flowOut.result() + << ", dstAmtReq: " << saDstAmountReq << ", sendMax: " << saMaxAmountReq; flowSB.apply(view); return flowOut; diff --git a/src/xrpld/app/tx/detail/AMMBid.cpp b/src/libxrpl/tx/transactors/AMM/AMMBid.cpp similarity index 90% rename from src/xrpld/app/tx/detail/AMMBid.cpp rename to src/libxrpl/tx/transactors/AMM/AMMBid.cpp index 1d0c30c1f0..8ba7970472 100644 --- a/src/xrpld/app/tx/detail/AMMBid.cpp +++ b/src/libxrpl/tx/transactors/AMM/AMMBid.cpp @@ -1,13 +1,12 @@ -#include -#include -#include - #include #include #include #include #include #include +#include +#include +#include namespace xrpl { @@ -20,7 +19,8 @@ AMMBid::checkExtraFeatures(PreflightContext const& ctx) NotTEC AMMBid::preflight(PreflightContext const& ctx) { - if (auto const res = invalidAMMAssetPair(ctx.tx[sfAsset].get(), ctx.tx[sfAsset2].get())) + if (auto const res = + invalidAMMAssetPair(ctx.tx[sfAsset].get(), ctx.tx[sfAsset2].get())) { JLOG(ctx.j.debug()) << "AMM Bid: Invalid asset pair."; return res; @@ -168,7 +168,8 @@ applyBid(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jour return {tecINTERNAL, false}; } auto& auctionSlot = ammSle->peekFieldObject(sfAuctionSlot); - auto const current = duration_cast(ctx_.view().header().parentCloseTime.time_since_epoch()).count(); + auto const current = + duration_cast(ctx_.view().header().parentCloseTime.time_since_epoch()).count(); // Auction slot discounted fee auto const discountedFee = (*ammSle)[sfTradingFee] / AUCTION_SLOT_DISCOUNTED_FEE_FRACTION; auto const tradingFee = getFee((*ammSle)[sfTradingFee]); @@ -201,12 +202,14 @@ applyBid(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jour else auctionSlot.makeFieldAbsent(sfAuthAccounts); // Burn the remaining bid amount - auto const saBurn = adjustLPTokens(lptAMMBalance, toSTAmount(lptAMMBalance.issue(), burn), IsDeposit::No); + auto const saBurn = + adjustLPTokens(lptAMMBalance, toSTAmount(lptAMMBalance.issue(), burn), IsDeposit::No); if (saBurn >= lptAMMBalance) { // This error case should never occur. // LCOV_EXCL_START - JLOG(ctx_.journal.fatal()) << "AMM Bid: LP Token burn exceeds AMM balance " << burn << " " << lptAMMBalance; + JLOG(ctx_.journal.fatal()) + << "AMM Bid: LP Token burn exceeds AMM balance " << burn << " " << lptAMMBalance; return tecINTERNAL; // LCOV_EXCL_STOP } @@ -233,8 +236,8 @@ applyBid(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jour { if (computedPrice <= *bidMax) return std::max(computedPrice, Number(*bidMin)); - JLOG(ctx_.journal.debug()) - << "AMM Bid: not in range " << computedPrice << " " << *bidMin << " " << *bidMax; + JLOG(ctx_.journal.debug()) << "AMM Bid: not in range " << computedPrice << " " + << *bidMin << " " << *bidMax; return std::nullopt; } // Bidder pays max(bidPrice, computedPrice) @@ -246,7 +249,8 @@ applyBid(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jour { if (computedPrice <= *bidMax) return computedPrice; - JLOG(ctx_.journal.debug()) << "AMM Bid: not in range " << computedPrice << " " << *bidMax; + JLOG(ctx_.journal.debug()) + << "AMM Bid: not in range " << computedPrice << " " << *bidMax; return std::nullopt; } else @@ -294,10 +298,16 @@ applyBid(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jour if (refund > *payPrice) { // This error case should never occur. - JLOG(ctx_.journal.fatal()) << "AMM Bid: refund exceeds payPrice " << refund << " " << *payPrice; + JLOG(ctx_.journal.fatal()) + << "AMM Bid: refund exceeds payPrice " << refund << " " << *payPrice; return {tecINTERNAL, false}; } - res = accountSend(sb, account_, auctionSlot[sfAccount], toSTAmount(lpTokens.issue(), refund), ctx_.journal); + res = accountSend( + sb, + account_, + auctionSlot[sfAccount], + toSTAmount(lpTokens.issue(), refund), + ctx_.journal); if (res != tesSUCCESS) { JLOG(ctx_.journal.debug()) << "AMM Bid: failed to refund."; diff --git a/src/xrpld/app/tx/detail/AMMClawback.cpp b/src/libxrpl/tx/transactors/AMM/AMMClawback.cpp similarity index 86% rename from src/xrpld/app/tx/detail/AMMClawback.cpp rename to src/libxrpl/tx/transactors/AMM/AMMClawback.cpp index 6da899c578..c9ea1e44eb 100644 --- a/src/xrpld/app/tx/detail/AMMClawback.cpp +++ b/src/libxrpl/tx/transactors/AMM/AMMClawback.cpp @@ -1,14 +1,13 @@ -#include -#include -#include -#include - #include #include #include #include #include #include +#include +#include +#include +#include #include @@ -135,11 +134,13 @@ AMMClawback::applyGuts(Sandbox& sb) if (lpTokenBalance == beast::zero) return tecAMM_BALANCE; - if (auto const res = verifyAndAdjustLPTokenBalance(sb, lpTokenBalance, ammSle, holder); !res) + if (auto const res = verifyAndAdjustLPTokenBalance(sb, lpTokenBalance, ammSle, holder); + !res) return res.error(); // LCOV_EXCL_LINE } - auto const expected = ammHolds(sb, *ammSle, asset, asset2, FreezeHandling::fhIGNORE_FREEZE, ctx_.journal); + auto const expected = + ammHolds(sb, *ammSle, asset, asset2, FreezeHandling::fhIGNORE_FREEZE, ctx_.journal); if (!expected) return expected.error(); // LCOV_EXCL_LINE @@ -157,29 +158,40 @@ AMMClawback::applyGuts(Sandbox& sb) if (!clawAmount) // Because we are doing a two-asset withdrawal, // tfee is actually not used, so pass tfee as 0. - std::tie(result, newLPTokenBalance, amountWithdraw, amount2Withdraw) = AMMWithdraw::equalWithdrawTokens( - sb, - *ammSle, - holder, - ammAccount, - amountBalance, - amount2Balance, - lptAMMBalance, - holdLPtokens, - holdLPtokens, - 0, - FreezeHandling::fhIGNORE_FREEZE, - WithdrawAll::Yes, - mPriorBalance, - ctx_.journal); + std::tie(result, newLPTokenBalance, amountWithdraw, amount2Withdraw) = + AMMWithdraw::equalWithdrawTokens( + sb, + *ammSle, + holder, + ammAccount, + amountBalance, + amount2Balance, + lptAMMBalance, + holdLPtokens, + holdLPtokens, + 0, + FreezeHandling::fhIGNORE_FREEZE, + WithdrawAll::Yes, + mPriorBalance, + ctx_.journal); else - std::tie(result, newLPTokenBalance, amountWithdraw, amount2Withdraw) = equalWithdrawMatchingOneAmount( - sb, *ammSle, holder, ammAccount, amountBalance, amount2Balance, lptAMMBalance, holdLPtokens, *clawAmount); + std::tie(result, newLPTokenBalance, amountWithdraw, amount2Withdraw) = + equalWithdrawMatchingOneAmount( + sb, + *ammSle, + holder, + ammAccount, + amountBalance, + amount2Balance, + lptAMMBalance, + holdLPtokens, + *clawAmount); if (result != tesSUCCESS) return result; // LCOV_EXCL_LINE - auto const res = AMMWithdraw::deleteAMMAccountIfEmpty(sb, ammSle, newLPTokenBalance, asset, asset2, j_); + auto const res = + AMMWithdraw::deleteAMMAccountIfEmpty(sb, ammSle, newLPTokenBalance, asset, asset2, j_); if (!res.second) return res.first; // LCOV_EXCL_LINE diff --git a/src/xrpld/app/tx/detail/AMMCreate.cpp b/src/libxrpl/tx/transactors/AMM/AMMCreate.cpp similarity index 90% rename from src/xrpld/app/tx/detail/AMMCreate.cpp rename to src/libxrpl/tx/transactors/AMM/AMMCreate.cpp index 4634ac79e0..53933df629 100644 --- a/src/xrpld/app/tx/detail/AMMCreate.cpp +++ b/src/libxrpl/tx/transactors/AMM/AMMCreate.cpp @@ -1,14 +1,13 @@ -#include -#include -#include -#include - +#include #include #include #include #include #include #include +#include +#include +#include namespace xrpl { @@ -66,7 +65,8 @@ AMMCreate::preclaim(PreclaimContext const& ctx) auto const amount2 = ctx.tx[sfAmount2]; // Check if AMM already exists for the token pair - if (auto const ammKeylet = keylet::amm(amount.issue(), amount2.issue()); ctx.view.read(ammKeylet)) + if (auto const ammKeylet = keylet::amm(amount.issue(), amount2.issue()); + ctx.view.read(ammKeylet)) { JLOG(ctx.j.debug()) << "AMM Instance: ltAMM already exists."; return tecDUPLICATE; @@ -85,7 +85,8 @@ AMMCreate::preclaim(PreclaimContext const& ctx) } // Globally or individually frozen - if (isFrozen(ctx.view, accountID, amount.issue()) || isFrozen(ctx.view, accountID, amount2.issue())) + if (isFrozen(ctx.view, accountID, amount.issue()) || + isFrozen(ctx.view, accountID, amount2.issue())) { JLOG(ctx.j.debug()) << "AMM Instance: involves frozen asset."; return tecFROZEN; @@ -120,7 +121,9 @@ AMMCreate::preclaim(PreclaimContext const& ctx) if (isXRP(asset)) return xrpBalance < asset; return accountID != asset.issue().account && - accountHolds(ctx.view, accountID, asset.issue(), FreezeHandling::fhZERO_IF_FROZEN, ctx.j) < asset; + accountHolds( + ctx.view, accountID, asset.issue(), FreezeHandling::fhZERO_IF_FROZEN, ctx.j) < + asset; }; if (insufficientBalance(amount) || insufficientBalance(amount2)) @@ -137,13 +140,15 @@ AMMCreate::preclaim(PreclaimContext const& ctx) if (isLPToken(amount) || isLPToken(amount2)) { - JLOG(ctx.j.debug()) << "AMM Instance: can't create with LPTokens " << amount << " " << amount2; + JLOG(ctx.j.debug()) << "AMM Instance: can't create with LPTokens " << amount << " " + << amount2; return tecAMM_INVALID_TOKENS; } if (ctx.view.rules().enabled(featureSingleAssetVault)) { - if (auto const accountId = pseudoAccountAddress(ctx.view, keylet::amm(amount.issue(), amount2.issue()).key); + if (auto const accountId = + pseudoAccountAddress(ctx.view, keylet::amm(amount.issue(), amount2.issue()).key); accountId == beast::zero) return terADDRESS_COLLISION; } @@ -233,12 +238,14 @@ applyCreate(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::J } auto sendAndTrustSet = [&](STAmount const& amount) -> TER { - if (auto const res = accountSend(sb, account_, accountId, amount, ctx_.journal, WaiveTransferFee::Yes)) + if (auto const res = + accountSend(sb, account_, accountId, amount, ctx_.journal, WaiveTransferFee::Yes)) return res; // Set AMM flag on AMM trustline if (!isXRP(amount)) { - if (SLE::pointer sleRippleState = sb.peek(keylet::line(accountId, amount.issue())); !sleRippleState) + if (SLE::pointer sleRippleState = sb.peek(keylet::line(accountId, amount.issue())); + !sleRippleState) return tecINTERNAL; // LCOV_EXCL_LINE else { @@ -266,13 +273,13 @@ applyCreate(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::J return {res, false}; } - JLOG(j_.debug()) << "AMM Instance: success " << accountId << " " << ammKeylet.key << " " << lpTokens << " " - << amount << " " << amount2; + JLOG(j_.debug()) << "AMM Instance: success " << accountId << " " << ammKeylet.key << " " + << lpTokens << " " << amount << " " << amount2; auto addOrderBook = [&](Issue const& issueIn, Issue const& issueOut, std::uint64_t uRate) { Book const book{issueIn, issueOut, std::nullopt}; auto const dir = keylet::quality(keylet::book(book), uRate); if (auto const bookExisted = static_cast(sb.read(dir)); !bookExisted) - ctx_.app.getOrderBookDB().addOrderBook(book); + ctx_.registry.getOrderBookDB().addOrderBook(book); }; addOrderBook(amount.issue(), amount2.issue(), getRate(amount2, amount)); addOrderBook(amount2.issue(), amount.issue(), getRate(amount, amount2)); diff --git a/src/xrpld/app/tx/detail/AMMDelete.cpp b/src/libxrpl/tx/transactors/AMM/AMMDelete.cpp similarity index 83% rename from src/xrpld/app/tx/detail/AMMDelete.cpp rename to src/libxrpl/tx/transactors/AMM/AMMDelete.cpp index f810f57758..39b7c9a11b 100644 --- a/src/xrpld/app/tx/detail/AMMDelete.cpp +++ b/src/libxrpl/tx/transactors/AMM/AMMDelete.cpp @@ -1,10 +1,9 @@ -#include -#include - #include #include #include #include +#include +#include namespace xrpl { @@ -44,7 +43,8 @@ AMMDelete::doApply() // as we go on processing transactions. Sandbox sb(&ctx_.view()); - auto const ter = deleteAMMAccount(sb, ctx_.tx[sfAsset].get(), ctx_.tx[sfAsset2].get(), j_); + auto const ter = + deleteAMMAccount(sb, ctx_.tx[sfAsset].get(), ctx_.tx[sfAsset2].get(), j_); if (ter == tesSUCCESS || ter == tecINCOMPLETE) sb.apply(ctx_.rawView()); diff --git a/src/xrpld/app/tx/detail/AMMDeposit.cpp b/src/libxrpl/tx/transactors/AMM/AMMDeposit.cpp similarity index 84% rename from src/xrpld/app/tx/detail/AMMDeposit.cpp rename to src/libxrpl/tx/transactors/AMM/AMMDeposit.cpp index af4ce51894..ba48295851 100644 --- a/src/xrpld/app/tx/detail/AMMDeposit.cpp +++ b/src/libxrpl/tx/transactors/AMM/AMMDeposit.cpp @@ -1,12 +1,11 @@ -#include -#include -#include - #include #include #include #include #include +#include +#include +#include namespace xrpl { @@ -89,7 +88,8 @@ AMMDeposit::preflight(PreflightContext const& ctx) if (amount && amount2 && amount->issue() == amount2->issue()) { - JLOG(ctx.j.debug()) << "AMM Deposit: invalid tokens, same issue." << amount->issue() << " " << amount2->issue(); + JLOG(ctx.j.debug()) << "AMM Deposit: invalid tokens, same issue." << amount->issue() << " " + << amount2->issue(); return temBAD_AMM_TOKENS; } @@ -101,8 +101,8 @@ AMMDeposit::preflight(PreflightContext const& ctx) if (amount) { - if (auto const res = - invalidAMMAmount(*amount, std::make_optional(std::make_pair(asset, asset2)), ePrice.has_value())) + if (auto const res = invalidAMMAmount( + *amount, std::make_optional(std::make_pair(asset, asset2)), ePrice.has_value())) { JLOG(ctx.j.debug()) << "AMM Deposit: invalid amount"; return res; @@ -111,7 +111,8 @@ AMMDeposit::preflight(PreflightContext const& ctx) if (amount2) { - if (auto const res = invalidAMMAmount(*amount2, std::make_optional(std::make_pair(asset, asset2)))) + if (auto const res = + invalidAMMAmount(*amount2, std::make_optional(std::make_pair(asset, asset2)))) { JLOG(ctx.j.debug()) << "AMM Deposit: invalid amount2"; return res; @@ -121,8 +122,8 @@ AMMDeposit::preflight(PreflightContext const& ctx) // must be amount issue if (amount && ePrice) { - if (auto const res = - invalidAMMAmount(*ePrice, std::make_optional(std::make_pair(amount->issue(), amount->issue())))) + if (auto const res = invalidAMMAmount( + *ePrice, std::make_optional(std::make_pair(amount->issue(), amount->issue())))) { JLOG(ctx.j.debug()) << "AMM Deposit: invalid EPrice"; return res; @@ -150,8 +151,8 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) return terNO_AMM; } - auto const expected = - ammHolds(ctx.view, *ammSle, std::nullopt, std::nullopt, FreezeHandling::fhIGNORE_FREEZE, ctx.j); + auto const expected = ammHolds( + ctx.view, *ammSle, std::nullopt, std::nullopt, FreezeHandling::fhIGNORE_FREEZE, ctx.j); if (!expected) return expected.error(); // LCOV_EXCL_LINE auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected; @@ -171,7 +172,8 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) { if (lptAMMBalance == beast::zero) return tecAMM_EMPTY; - if (amountBalance <= beast::zero || amount2Balance <= beast::zero || lptAMMBalance < beast::zero) + if (amountBalance <= beast::zero || amount2Balance <= beast::zero || + lptAMMBalance < beast::zero) { // LCOV_EXCL_START JLOG(ctx.j.debug()) << "AMM Deposit: reserves or tokens balance is zero."; @@ -190,7 +192,8 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) { auto const lpIssue = (*ammSle)[sfLPTokenBalance].issue(); // Adjust the reserve if LP doesn't have LPToken trustline - auto const sle = ctx.view.read(keylet::line(accountID, lpIssue.account, lpIssue.currency)); + auto const sle = + ctx.view.read(keylet::line(accountID, lpIssue.account, lpIssue.currency)); if (xrpLiquid(ctx.view, accountID, !sle, ctx.j) >= deposit) return TER(tesSUCCESS); if (sle) @@ -198,7 +201,9 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) return tecINSUF_RESERVE_LINE; } return (accountID == deposit.issue().account || - accountHolds(ctx.view, accountID, deposit.issue(), FreezeHandling::fhIGNORE_FREEZE, ctx.j) >= deposit) + accountHolds( + ctx.view, accountID, deposit.issue(), FreezeHandling::fhIGNORE_FREEZE, ctx.j) >= + deposit) ? TER(tesSUCCESS) : tecUNFUNDED_AMM; }; @@ -216,8 +221,8 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) if (isFrozen(ctx.view, accountID, asset)) { - JLOG(ctx.j.debug()) << "AMM Deposit: account or currency is frozen, " << to_string(accountID) << " " - << to_string(asset.currency); + JLOG(ctx.j.debug()) << "AMM Deposit: account or currency is frozen, " + << to_string(accountID) << " " << to_string(asset.currency); return tecFROZEN; } @@ -245,28 +250,31 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) if (auto const ter = requireAuth(ctx.view, amount->issue(), accountID)) { // LCOV_EXCL_START - JLOG(ctx.j.debug()) << "AMM Deposit: account is not authorized, " << amount->issue(); + JLOG(ctx.j.debug()) + << "AMM Deposit: account is not authorized, " << amount->issue(); return ter; // LCOV_EXCL_STOP } // AMM account or currency frozen if (isFrozen(ctx.view, ammAccountID, amount->issue())) { - JLOG(ctx.j.debug()) << "AMM Deposit: AMM account or currency is frozen, " << to_string(accountID); + JLOG(ctx.j.debug()) + << "AMM Deposit: AMM account or currency is frozen, " << to_string(accountID); return tecFROZEN; } // Account frozen if (isIndividualFrozen(ctx.view, accountID, amount->issue())) { - JLOG(ctx.j.debug()) << "AMM Deposit: account is frozen, " << to_string(accountID) << " " - << to_string(amount->issue().currency); + JLOG(ctx.j.debug()) << "AMM Deposit: account is frozen, " << to_string(accountID) + << " " << to_string(amount->issue().currency); return tecFROZEN; } if (checkBalance) { if (auto const ter = balance(*amount)) { - JLOG(ctx.j.debug()) << "AMM Deposit: account has insufficient funds, " << *amount; + JLOG(ctx.j.debug()) + << "AMM Deposit: account has insufficient funds, " << *amount; return ter; } } @@ -292,7 +300,8 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) } // Equal deposit lp tokens - if (auto const lpTokens = ctx.tx[~sfLPTokenOut]; lpTokens && lpTokens->issue() != lptAMMBalance.issue()) + if (auto const lpTokens = ctx.tx[~sfLPTokenOut]; + lpTokens && lpTokens->issue() != lptAMMBalance.issue()) { JLOG(ctx.j.debug()) << "AMM Deposit: invalid LPTokens."; return temBAD_AMM_TOKENS; @@ -336,15 +345,17 @@ AMMDeposit::applyGuts(Sandbox& sb) if (!expected) return {expected.error(), false}; // LCOV_EXCL_LINE auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected; - auto const tfee = (lptAMMBalance == beast::zero) ? ctx_.tx[~sfTradingFee].value_or(0) - : getTradingFee(ctx_.view(), *ammSle, account_); + auto const tfee = (lptAMMBalance == beast::zero) + ? ctx_.tx[~sfTradingFee].value_or(0) + : getTradingFee(ctx_.view(), *ammSle, account_); auto const subTxType = ctx_.tx.getFlags() & tfDepositSubTx; auto const [result, newLPTokenBalance] = [&, &amountBalance = amountBalance, &amount2Balance = amount2Balance, - &lptAMMBalance = lptAMMBalance]() -> std::pair { + &lptAMMBalance = + lptAMMBalance]() -> std::pair { if (subTxType & tfTwoAsset) return equalDepositLimit( sb, @@ -357,11 +368,14 @@ AMMDeposit::applyGuts(Sandbox& sb) lpTokensDeposit, tfee); if (subTxType & tfOneAssetLPToken) - return singleDepositTokens(sb, ammAccountID, amountBalance, *amount, lptAMMBalance, *lpTokensDeposit, tfee); + return singleDepositTokens( + sb, ammAccountID, amountBalance, *amount, lptAMMBalance, *lpTokensDeposit, tfee); if (subTxType & tfLimitLPToken) - return singleDepositEPrice(sb, ammAccountID, amountBalance, *amount, lptAMMBalance, *ePrice, tfee); + return singleDepositEPrice( + sb, ammAccountID, amountBalance, *amount, lptAMMBalance, *ePrice, tfee); if (subTxType & tfSingleAsset) - return singleDeposit(sb, ammAccountID, amountBalance, lptAMMBalance, *amount, lpTokensDeposit, tfee); + return singleDeposit( + sb, ammAccountID, amountBalance, lptAMMBalance, *amount, lpTokensDeposit, tfee); if (subTxType & tfLPToken) return equalDepositTokens( sb, @@ -374,7 +388,8 @@ AMMDeposit::applyGuts(Sandbox& sb) amount2, tfee); if (subTxType & tfTwoAssetIfEmpty) - return equalDepositInEmptyState(sb, ammAccountID, *amount, *amount2, lptAMMBalance.issue(), tfee); + return equalDepositInEmptyState( + sb, ammAccountID, *amount, *amount2, lptAMMBalance.issue(), tfee); // should not happen. // LCOV_EXCL_START JLOG(j_.error()) << "AMM Deposit: invalid options."; @@ -384,7 +399,9 @@ AMMDeposit::applyGuts(Sandbox& sb) if (result == tesSUCCESS) { - XRPL_ASSERT(newLPTokenBalance > beast::zero, "xrpl::AMMDeposit::applyGuts : valid new LP token balance"); + XRPL_ASSERT( + newLPTokenBalance > beast::zero, + "xrpl::AMMDeposit::applyGuts : valid new LP token balance"); ammSle->setFieldAmount(sfLPTokenBalance, newLPTokenBalance); // LP depositing into AMM empty state gets the auction slot // and the voting @@ -440,14 +457,25 @@ AMMDeposit::deposit( } else if ( account_ == depositAmount.issue().account || - accountHolds(view, account_, depositAmount.issue(), FreezeHandling::fhIGNORE_FREEZE, ctx_.journal) >= - depositAmount) + accountHolds( + view, + account_, + depositAmount.issue(), + FreezeHandling::fhIGNORE_FREEZE, + ctx_.journal) >= depositAmount) return tesSUCCESS; return tecUNFUNDED_AMM; }; - auto const [amountDepositActual, amount2DepositActual, lpTokensDepositActual] = adjustAmountsByLPTokens( - amountBalance, amountDeposit, amount2Deposit, lptAMMBalance, lpTokensDeposit, tfee, IsDeposit::Yes); + auto const [amountDepositActual, amount2DepositActual, lpTokensDepositActual] = + adjustAmountsByLPTokens( + amountBalance, + amountDeposit, + amount2Deposit, + lptAMMBalance, + lpTokensDeposit, + tfee, + IsDeposit::Yes); if (lpTokensDepositActual <= beast::zero) { @@ -458,11 +486,11 @@ AMMDeposit::deposit( if (amountDepositActual < depositMin || amount2DepositActual < deposit2Min || lpTokensDepositActual < lpTokensDepositMin) { - JLOG(ctx_.journal.debug()) << "AMM Deposit: min deposit fails " << amountDepositActual << " " - << depositMin.value_or(STAmount{}) << " " - << amount2DepositActual.value_or(STAmount{}) << " " - << deposit2Min.value_or(STAmount{}) << " " << lpTokensDepositActual << " " - << lpTokensDepositMin.value_or(STAmount{}); + JLOG(ctx_.journal.debug()) + << "AMM Deposit: min deposit fails " << amountDepositActual << " " + << depositMin.value_or(STAmount{}) << " " << amount2DepositActual.value_or(STAmount{}) + << " " << deposit2Min.value_or(STAmount{}) << " " << lpTokensDepositActual << " " + << lpTokensDepositMin.value_or(STAmount{}); return {tecAMM_FAILED, STAmount{}}; } @@ -475,7 +503,8 @@ AMMDeposit::deposit( return {ter, STAmount{}}; } - auto res = accountSend(view, account_, ammAccount, amountDepositActual, ctx_.journal, WaiveTransferFee::Yes); + auto res = accountSend( + view, account_, ammAccount, amountDepositActual, ctx_.journal, WaiveTransferFee::Yes); if (res != tesSUCCESS) { JLOG(ctx_.journal.debug()) << "AMM Deposit: failed to deposit " << amountDepositActual; @@ -493,10 +522,12 @@ AMMDeposit::deposit( return {ter, STAmount{}}; } - res = accountSend(view, account_, ammAccount, *amount2DepositActual, ctx_.journal, WaiveTransferFee::Yes); + res = accountSend( + view, account_, ammAccount, *amount2DepositActual, ctx_.journal, WaiveTransferFee::Yes); if (res != tesSUCCESS) { - JLOG(ctx_.journal.debug()) << "AMM Deposit: failed to deposit " << *amount2DepositActual; + JLOG(ctx_.journal.debug()) + << "AMM Deposit: failed to deposit " << *amount2DepositActual; return {res, STAmount{}}; } } @@ -513,7 +544,10 @@ AMMDeposit::deposit( } static STAmount -adjustLPTokensOut(Rules const& rules, STAmount const& lptAMMBalance, STAmount const& lpTokensDeposit) +adjustLPTokensOut( + Rules const& rules, + STAmount const& lptAMMBalance, + STAmount const& lpTokensDeposit) { if (!rules.enabled(fixAMMv1_3)) return lpTokensDeposit; @@ -542,8 +576,10 @@ AMMDeposit::equalDepositTokens( return {tecAMM_INVALID_TOKENS, STAmount{}}; auto const frac = divide(tokensAdj, lptAMMBalance, lptAMMBalance.issue()); // amounts factor in the adjusted tokens - auto const amountDeposit = getRoundedAsset(view.rules(), amountBalance, frac, IsDeposit::Yes); - auto const amount2Deposit = getRoundedAsset(view.rules(), amount2Balance, frac, IsDeposit::Yes); + auto const amountDeposit = + getRoundedAsset(view.rules(), amountBalance, frac, IsDeposit::Yes); + auto const amount2Deposit = + getRoundedAsset(view.rules(), amount2Balance, frac, IsDeposit::Yes); return deposit( view, ammAccount, @@ -677,8 +713,8 @@ AMMDeposit::singleDeposit( std::optional const& lpTokensDepositMin, std::uint16_t tfee) { - auto const tokens = - adjustLPTokensOut(view.rules(), lptAMMBalance, lpTokensOut(amountBalance, amount, lptAMMBalance, tfee)); + auto const tokens = adjustLPTokensOut( + view.rules(), lptAMMBalance, lpTokensOut(amountBalance, amount, lptAMMBalance, tfee)); if (tokens == beast::zero) { if (!view.rules().enabled(fixAMMv1_3)) @@ -780,8 +816,8 @@ AMMDeposit::singleDepositEPrice( { if (amount != beast::zero) { - auto const tokens = - adjustLPTokensOut(view.rules(), lptAMMBalance, lpTokensOut(amountBalance, amount, lptAMMBalance, tfee)); + auto const tokens = adjustLPTokensOut( + view.rules(), lptAMMBalance, lpTokensOut(amountBalance, amount, lptAMMBalance, tfee)); if (tokens <= beast::zero) { if (!view.rules().enabled(fixAMMv1_3)) @@ -836,15 +872,17 @@ AMMDeposit::singleDepositEPrice( auto const c1 = 2 * c * f2 * f2 + 1 - 2 * d * f2; auto amtNoRoundCb = [&] { return f1 * amountBalance * solveQuadraticEq(a1, b1, c1); }; auto amtProdCb = [&] { return f1 * solveQuadraticEq(a1, b1, c1); }; - auto const amountDeposit = getRoundedAsset(view.rules(), amtNoRoundCb, amountBalance, amtProdCb, IsDeposit::Yes); + auto const amountDeposit = + getRoundedAsset(view.rules(), amtNoRoundCb, amountBalance, amtProdCb, IsDeposit::Yes); if (amountDeposit <= beast::zero) return {tecAMM_FAILED, STAmount{}}; auto tokNoRoundCb = [&] { return amountDeposit / ePrice; }; auto tokProdCb = [&] { return amountDeposit / ePrice; }; - auto const tokens = getRoundedLPTokens(view.rules(), tokNoRoundCb, lptAMMBalance, tokProdCb, IsDeposit::Yes); + auto const tokens = + getRoundedLPTokens(view.rules(), tokNoRoundCb, lptAMMBalance, tokProdCb, IsDeposit::Yes); // factor in the adjusted tokens - auto const [tokensAdj, amountDepositAdj] = - adjustAssetInByTokens(view.rules(), amountBalance, amountDeposit, lptAMMBalance, tokens, tfee); + auto const [tokensAdj, amountDepositAdj] = adjustAssetInByTokens( + view.rules(), amountBalance, amountDeposit, lptAMMBalance, tokens, tfee); if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::zero) return {tecAMM_INVALID_TOKENS, STAmount{}}; // LCOV_EXCL_LINE diff --git a/src/xrpld/app/misc/detail/AMMHelpers.cpp b/src/libxrpl/tx/transactors/AMM/AMMHelpers.cpp similarity index 92% rename from src/xrpld/app/misc/detail/AMMHelpers.cpp rename to src/libxrpl/tx/transactors/AMM/AMMHelpers.cpp index ff3474f33d..5d5af6da03 100644 --- a/src/xrpld/app/misc/detail/AMMHelpers.cpp +++ b/src/libxrpl/tx/transactors/AMM/AMMHelpers.cpp @@ -1,4 +1,4 @@ -#include +#include namespace xrpl { @@ -54,7 +54,11 @@ lpTokensOut( * (R/t2)**2 + R*(2*d/t2 - 1/f1) + d**2 - f2**2 = 0 */ STAmount -ammAssetIn(STAmount const& asset1Balance, STAmount const& lptAMMBalance, STAmount const& lpTokens, std::uint16_t tfee) +ammAssetIn( + STAmount const& asset1Balance, + STAmount const& lptAMMBalance, + STAmount const& lpTokens, + std::uint16_t tfee) { auto const f1 = feeMult(tfee); auto const f2 = feeMultHalf(tfee) / f1; @@ -114,7 +118,11 @@ lpTokensIn( * R = (t1**2 + t1*(f - 2)) / (t1*f - 1) */ STAmount -ammAssetOut(STAmount const& assetBalance, STAmount const& lptAMMBalance, STAmount const& lpTokens, std::uint16_t tfee) +ammAssetOut( + STAmount const& assetBalance, + STAmount const& lptAMMBalance, + STAmount const& lpTokens, + std::uint16_t tfee) { auto const f = getFee(tfee); Number const t1 = lpTokens / lptAMMBalance; @@ -173,7 +181,8 @@ adjustAmountsByLPTokens( if (lpTokensActual < lpTokens) { bool const ammRoundingEnabled = [&]() { - if (auto const& rules = getCurrentTransactionRules(); rules && rules->enabled(fixAMMv1_1)) + if (auto const& rules = getCurrentTransactionRules(); + rules && rules->enabled(fixAMMv1_1)) return true; return false; }(); @@ -203,13 +212,15 @@ adjustAmountsByLPTokens( return ammAssetOut(amountBalance, lptAMMBalance, lpTokensActual, tfee); }(); if (!ammRoundingEnabled) - return amountActual < amount ? std::make_tuple(amountActual, std::nullopt, lpTokensActual) - : std::make_tuple(amount, std::nullopt, lpTokensActual); + return amountActual < amount + ? std::make_tuple(amountActual, std::nullopt, lpTokensActual) + : std::make_tuple(amount, std::nullopt, lpTokensActual); else return std::make_tuple(amountActual, std::nullopt, lpTokensActual); } - XRPL_ASSERT(lpTokensActual == lpTokens, "xrpl::adjustAmountsByLPTokens : LP tokens match actual"); + XRPL_ASSERT( + lpTokensActual == lpTokens, "xrpl::adjustAmountsByLPTokens : LP tokens match actual"); return {amount, amount2, lpTokensActual}; } @@ -262,7 +273,11 @@ getRoundedAsset( } STAmount -getRoundedLPTokens(Rules const& rules, STAmount const& balance, Number const& frac, IsDeposit isDeposit) +getRoundedLPTokens( + Rules const& rules, + STAmount const& balance, + Number const& frac, + IsDeposit isDeposit) { if (!rules.enabled(fixAMMv1_3)) return toSTAmount(balance.issue(), balance * frac); @@ -348,7 +363,11 @@ adjustAssetOutByTokens( } Number -adjustFracByTokens(Rules const& rules, STAmount const& lptAMMBalance, STAmount const& tokens, Number const& frac) +adjustFracByTokens( + Rules const& rules, + STAmount const& lptAMMBalance, + STAmount const& tokens, + Number const& frac) { if (!rules.enabled(fixAMMv1_3)) return frac; diff --git a/src/xrpld/app/misc/detail/AMMUtils.cpp b/src/libxrpl/tx/transactors/AMM/AMMUtils.cpp similarity index 87% rename from src/xrpld/app/misc/detail/AMMUtils.cpp rename to src/libxrpl/tx/transactors/AMM/AMMUtils.cpp index 36a40f1709..ac67e861f1 100644 --- a/src/xrpld/app/misc/detail/AMMUtils.cpp +++ b/src/libxrpl/tx/transactors/AMM/AMMUtils.cpp @@ -1,10 +1,9 @@ -#include -#include - #include #include #include #include +#include +#include namespace xrpl { @@ -36,18 +35,21 @@ ammHolds( auto const issue2 = ammSle[sfAsset2].get(); if (optIssue1 && optIssue2) { - if (invalidAMMAssetPair(*optIssue1, *optIssue2, std::make_optional(std::make_pair(issue1, issue2)))) + if (invalidAMMAssetPair( + *optIssue1, *optIssue2, std::make_optional(std::make_pair(issue1, issue2)))) { // This error can only be hit if the AMM is corrupted // LCOV_EXCL_START - JLOG(j.debug()) << "ammHolds: Invalid optIssue1 or optIssue2 " << *optIssue1 << " " << *optIssue2; + JLOG(j.debug()) << "ammHolds: Invalid optIssue1 or optIssue2 " << *optIssue1 << " " + << *optIssue2; return std::nullopt; // LCOV_EXCL_STOP } return std::make_optional(std::make_pair(*optIssue1, *optIssue2)); } auto const singleIssue = [&issue1, &issue2, &j]( - Issue checkIssue, char const* label) -> std::optional> { + Issue checkIssue, + char const* label) -> std::optional> { if (checkIssue == issue1) return std::make_optional(std::make_pair(issue1, issue2)); else if (checkIssue == issue2) @@ -71,8 +73,8 @@ ammHolds( }(); if (!issues) return Unexpected(tecAMM_INVALID_TOKENS); - auto const [asset1, asset2] = - ammPoolHolds(view, ammSle.getAccountID(sfAccount), issues->first, issues->second, freezeHandling, j); + auto const [asset1, asset2] = ammPoolHolds( + view, ammSle.getAccountID(sfAccount), issues->first, issues->second, freezeHandling, j); return std::make_tuple(asset1, asset2, ammSle[sfLPTokenBalance]); } @@ -98,13 +100,15 @@ ammLPHolds( { amount.clear(Issue{currency, ammAccount}); JLOG(j.trace()) << "ammLPHolds: no SLE " - << " lpAccount=" << to_string(lpAccount) << " amount=" << amount.getFullText(); + << " lpAccount=" << to_string(lpAccount) + << " amount=" << amount.getFullText(); } else if (isFrozen(view, lpAccount, currency, ammAccount)) { amount.clear(Issue{currency, ammAccount}); JLOG(j.trace()) << "ammLPHolds: frozen currency " - << " lpAccount=" << to_string(lpAccount) << " amount=" << amount.getFullText(); + << " lpAccount=" << to_string(lpAccount) + << " amount=" << amount.getFullText(); } else { @@ -117,14 +121,19 @@ ammLPHolds( amount.setIssuer(ammAccount); JLOG(j.trace()) << "ammLPHolds:" - << " lpAccount=" << to_string(lpAccount) << " amount=" << amount.getFullText(); + << " lpAccount=" << to_string(lpAccount) + << " amount=" << amount.getFullText(); } return view.balanceHook(lpAccount, ammAccount, amount); } STAmount -ammLPHolds(ReadView const& view, SLE const& ammSle, AccountID const& lpAccount, beast::Journal const j) +ammLPHolds( + ReadView const& view, + SLE const& ammSle, + AccountID const& lpAccount, + beast::Journal const j) { return ammLPHolds( view, @@ -147,7 +156,8 @@ getTradingFee(ReadView const& view, SLE const& ammSle, AccountID const& account) auto const& auctionSlot = static_cast(ammSle.peekAtField(sfAuctionSlot)); // Not expired if (auto const expiration = auctionSlot[~sfExpiration]; - duration_cast(view.header().parentCloseTime.time_since_epoch()).count() < expiration) + duration_cast(view.header().parentCloseTime.time_since_epoch()).count() < + expiration) { if (auctionSlot[~sfAccount] == account) return auctionSlot[sfDiscountedFee]; @@ -184,12 +194,18 @@ ammAccountHolds(ReadView const& view, AccountID const& ammAccountID, Issue const } static TER -deleteAMMTrustLines(Sandbox& sb, AccountID const& ammAccountID, std::uint16_t maxTrustlinesToDelete, beast::Journal j) +deleteAMMTrustLines( + Sandbox& sb, + AccountID const& ammAccountID, + std::uint16_t maxTrustlinesToDelete, + beast::Journal j) { return cleanupOnAccountDelete( sb, keylet::ownerDir(ammAccountID), - [&](LedgerEntryType nodeType, uint256 const&, std::shared_ptr& sleItem) -> std::pair { + [&](LedgerEntryType nodeType, + uint256 const&, + std::shared_ptr& sleItem) -> std::pair { // Skip AMM if (nodeType == LedgerEntryType::ltAMM) return {tesSUCCESS, SkipEntry::Yes}; @@ -235,12 +251,14 @@ deleteAMMAccount(Sandbox& sb, Issue const& asset, Issue const& asset2, beast::Jo if (!sleAMMRoot) { // LCOV_EXCL_START - JLOG(j.error()) << "deleteAMMAccount: AMM account does not exist " << to_string(ammAccountID); + JLOG(j.error()) << "deleteAMMAccount: AMM account does not exist " + << to_string(ammAccountID); return tecINTERNAL; // LCOV_EXCL_STOP } - if (auto const ter = deleteAMMTrustLines(sb, ammAccountID, maxDeletableAMMTrustLines, j); ter != tesSUCCESS) + if (auto const ter = deleteAMMTrustLines(sb, ammAccountID, maxDeletableAMMTrustLines, j); + ter != tesSUCCESS) return ter; auto const ownerDirKeylet = keylet::ownerDir(ammAccountID); @@ -254,7 +272,8 @@ deleteAMMAccount(Sandbox& sb, Issue const& asset, Issue const& asset2, beast::Jo if (sb.exists(ownerDirKeylet) && !sb.emptyDirDelete(ownerDirKeylet)) { // LCOV_EXCL_START - JLOG(j.error()) << "deleteAMMAccount: cannot delete root dir node of " << toBase58(ammAccountID); + JLOG(j.error()) << "deleteAMMAccount: cannot delete root dir node of " + << toBase58(ammAccountID); return tecINTERNAL; // LCOV_EXCL_STOP } @@ -294,8 +313,9 @@ initializeFeeAuctionVote( STObject& auctionSlot = ammSle->peekFieldObject(sfAuctionSlot); auctionSlot.setAccountID(sfAccount, account); // current + sec in 24h - auto const expiration = - std::chrono::duration_cast(view.header().parentCloseTime.time_since_epoch()).count() + + auto const expiration = std::chrono::duration_cast( + view.header().parentCloseTime.time_since_epoch()) + .count() + TOTAL_TIME_SLOT_SECS; auctionSlot.setFieldU32(sfExpiration, expiration); auctionSlot.setFieldAmount(sfPrice, STAmount{lptIssue, 0}); @@ -353,8 +373,10 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE auto const lowLimit = sle->getFieldAmount(sfLowLimit); auto const highLimit = sle->getFieldAmount(sfHighLimit); - auto const isLPTrustline = lowLimit.getIssuer() == lpAccount || highLimit.getIssuer() == lpAccount; - auto const isLPTokenTrustline = lowLimit.issue() == ammIssue || highLimit.issue() == ammIssue; + auto const isLPTrustline = + lowLimit.getIssuer() == lpAccount || highLimit.getIssuer() == lpAccount; + auto const isLPTokenTrustline = + lowLimit.issue() == ammIssue || highLimit.issue() == ammIssue; // Liquidity Provider trustline if (isLPTrustline) @@ -397,7 +419,8 @@ verifyAndAdjustLPTokenBalance( return Unexpected(res.error()); else if (res.value()) { - if (withinRelativeDistance(lpTokens, ammSle->getFieldAmount(sfLPTokenBalance), Number{1, -3})) + if (withinRelativeDistance( + lpTokens, ammSle->getFieldAmount(sfLPTokenBalance), Number{1, -3})) { ammSle->setFieldAmount(sfLPTokenBalance, lpTokens); sb.update(ammSle); diff --git a/src/xrpld/app/tx/detail/AMMVote.cpp b/src/libxrpl/tx/transactors/AMM/AMMVote.cpp similarity index 92% rename from src/xrpld/app/tx/detail/AMMVote.cpp rename to src/libxrpl/tx/transactors/AMM/AMMVote.cpp index 05b23233a4..f40015ac08 100644 --- a/src/xrpld/app/tx/detail/AMMVote.cpp +++ b/src/libxrpl/tx/transactors/AMM/AMMVote.cpp @@ -1,10 +1,9 @@ -#include -#include - #include #include #include #include +#include +#include namespace xrpl { @@ -17,7 +16,8 @@ AMMVote::checkExtraFeatures(PreflightContext const& ctx) NotTEC AMMVote::preflight(PreflightContext const& ctx) { - if (auto const res = invalidAMMAssetPair(ctx.tx[sfAsset].get(), ctx.tx[sfAsset2].get())) + if (auto const res = + invalidAMMAssetPair(ctx.tx[sfAsset].get(), ctx.tx[sfAsset2].get())) { JLOG(ctx.j.debug()) << "AMM Vote: invalid asset pair."; return res; @@ -100,13 +100,15 @@ applyVote(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jou if (feeVal != 0) newEntry.setFieldU16(sfTradingFee, feeVal); newEntry.setFieldU32( - sfVoteWeight, static_cast(Number(lpTokens) * VOTE_WEIGHT_SCALE_FACTOR / lptAMMBalance)); + sfVoteWeight, + static_cast(Number(lpTokens) * VOTE_WEIGHT_SCALE_FACTOR / lptAMMBalance)); // Find an entry with the least tokens/fee. Make the order deterministic // if the tokens/fees are equal. if (!minTokens || (lpTokens < *minTokens || - (lpTokens == *minTokens && (feeVal < minFee || (feeVal == minFee && account < minAccount))))) + (lpTokens == *minTokens && + (feeVal < minFee || (feeVal == minFee && account < minAccount))))) { minTokens = lpTokens; minPos = updatedVoteSlots.size(); @@ -125,7 +127,8 @@ applyVote(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jou newEntry.setFieldU16(sfTradingFee, feeNew); newEntry.setFieldU32( sfVoteWeight, - static_cast(Number(lpTokensNew) * VOTE_WEIGHT_SCALE_FACTOR / lptAMMBalance)); + static_cast( + Number(lpTokensNew) * VOTE_WEIGHT_SCALE_FACTOR / lptAMMBalance)); newEntry.setAccountID(sfAccount, account_); num += feeNew * lpTokensNew; den += lpTokensNew; diff --git a/src/xrpld/app/tx/detail/AMMWithdraw.cpp b/src/libxrpl/tx/transactors/AMM/AMMWithdraw.cpp similarity index 84% rename from src/xrpld/app/tx/detail/AMMWithdraw.cpp rename to src/libxrpl/tx/transactors/AMM/AMMWithdraw.cpp index 58d1e066d6..3c974ee4a4 100644 --- a/src/xrpld/app/tx/detail/AMMWithdraw.cpp +++ b/src/libxrpl/tx/transactors/AMM/AMMWithdraw.cpp @@ -1,11 +1,10 @@ -#include -#include -#include - #include #include #include #include +#include +#include +#include namespace xrpl { @@ -114,7 +113,8 @@ AMMWithdraw::preflight(PreflightContext const& ctx) if (amount2) { - if (auto const res = invalidAMMAmount(*amount2, std::make_optional(std::make_pair(asset, asset2)))) + if (auto const res = + invalidAMMAmount(*amount2, std::make_optional(std::make_pair(asset, asset2)))) { JLOG(ctx.j.debug()) << "AMM Withdraw: invalid Asset2OutAmount"; return res; @@ -134,7 +134,10 @@ AMMWithdraw::preflight(PreflightContext const& ctx) } static std::optional -tokensWithdraw(STAmount const& lpTokens, std::optional const& tokensIn, std::uint32_t flags) +tokensWithdraw( + STAmount const& lpTokens, + std::optional const& tokensIn, + std::uint32_t flags) { if (flags & (tfWithdrawAll | tfOneAssetWithdrawAll)) return lpTokens; @@ -168,7 +171,8 @@ AMMWithdraw::preclaim(PreclaimContext const& ctx) auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected; if (lptAMMBalance == beast::zero) return tecAMM_EMPTY; - if (amountBalance <= beast::zero || amount2Balance <= beast::zero || lptAMMBalance < beast::zero) + if (amountBalance <= beast::zero || amount2Balance <= beast::zero || + lptAMMBalance < beast::zero) { // LCOV_EXCL_START JLOG(ctx.j.debug()) << "AMM Withdraw: reserves or tokens balance is zero."; @@ -183,25 +187,28 @@ AMMWithdraw::preclaim(PreclaimContext const& ctx) { if (amount > balance) { - JLOG(ctx.j.debug()) << "AMM Withdraw: withdrawing more than the balance, " << *amount; + JLOG(ctx.j.debug()) + << "AMM Withdraw: withdrawing more than the balance, " << *amount; return tecAMM_BALANCE; } if (auto const ter = requireAuth(ctx.view, amount->issue(), accountID)) { - JLOG(ctx.j.debug()) << "AMM Withdraw: account is not authorized, " << amount->issue(); + JLOG(ctx.j.debug()) + << "AMM Withdraw: account is not authorized, " << amount->issue(); return ter; } // AMM account or currency frozen if (isFrozen(ctx.view, ammAccountID, amount->issue())) { - JLOG(ctx.j.debug()) << "AMM Withdraw: AMM account or currency is frozen, " << to_string(accountID); + JLOG(ctx.j.debug()) + << "AMM Withdraw: AMM account or currency is frozen, " << to_string(accountID); return tecFROZEN; } // Account frozen if (isIndividualFrozen(ctx.view, accountID, amount->issue())) { - JLOG(ctx.j.debug()) << "AMM Withdraw: account is frozen, " << to_string(accountID) << " " - << to_string(amount->issue().currency); + JLOG(ctx.j.debug()) << "AMM Withdraw: account is frozen, " << to_string(accountID) + << " " << to_string(amount->issue().currency); return tecFROZEN; } } @@ -266,7 +273,8 @@ AMMWithdraw::applyGuts(Sandbox& sb) if (!accountSle) return {tecINTERNAL, false}; // LCOV_EXCL_LINE auto const lpTokens = ammLPHolds(ctx_.view(), *ammSle, ctx_.tx[sfAccount], ctx_.journal); - auto const lpTokensWithdraw = tokensWithdraw(lpTokens, ctx_.tx[~sfLPTokenIn], ctx_.tx.getFlags()); + auto const lpTokensWithdraw = + tokensWithdraw(lpTokens, ctx_.tx[~sfLPTokenIn], ctx_.tx.getFlags()); // Due to rounding, the LPTokenBalance of the last LP // might not match the LP's trustline balance @@ -294,18 +302,35 @@ AMMWithdraw::applyGuts(Sandbox& sb) auto const [result, newLPTokenBalance] = [&, &amountBalance = amountBalance, &amount2Balance = amount2Balance, - &lptAMMBalance = lptAMMBalance]() -> std::pair { + &lptAMMBalance = + lptAMMBalance]() -> std::pair { if (subTxType & tfTwoAsset) return equalWithdrawLimit( - sb, *ammSle, ammAccountID, amountBalance, amount2Balance, lptAMMBalance, *amount, *amount2, tfee); + sb, + *ammSle, + ammAccountID, + amountBalance, + amount2Balance, + lptAMMBalance, + *amount, + *amount2, + tfee); if (subTxType & tfOneAssetLPToken || subTxType & tfOneAssetWithdrawAll) return singleWithdrawTokens( - sb, *ammSle, ammAccountID, amountBalance, lptAMMBalance, *amount, *lpTokensWithdraw, tfee); + sb, + *ammSle, + ammAccountID, + amountBalance, + lptAMMBalance, + *amount, + *lpTokensWithdraw, + tfee); if (subTxType & tfLimitLPToken) return singleWithdrawEPrice( sb, *ammSle, ammAccountID, amountBalance, lptAMMBalance, *amount, *ePrice, tfee); if (subTxType & tfSingleAsset) - return singleWithdraw(sb, *ammSle, ammAccountID, amountBalance, lptAMMBalance, *amount, tfee); + return singleWithdraw( + sb, *ammSle, ammAccountID, amountBalance, lptAMMBalance, *amount, tfee); if (subTxType & tfLPToken || subTxType & tfWithdrawAll) { return equalWithdrawTokens( @@ -330,14 +355,20 @@ AMMWithdraw::applyGuts(Sandbox& sb) return {result, false}; auto const res = deleteAMMAccountIfEmpty( - sb, ammSle, newLPTokenBalance, ctx_.tx[sfAsset].get(), ctx_.tx[sfAsset2].get(), j_); + sb, + ammSle, + newLPTokenBalance, + ctx_.tx[sfAsset].get(), + ctx_.tx[sfAsset2].get(), + j_); // LCOV_EXCL_START if (!res.second) return {res.first, false}; // LCOV_EXCL_STOP - JLOG(ctx_.journal.trace()) << "AMM Withdraw: tokens " << to_string(newLPTokenBalance.iou()) << " " - << to_string(lpTokens.iou()) << " " << to_string(lptAMMBalance.iou()); + JLOG(ctx_.journal.trace()) << "AMM Withdraw: tokens " << to_string(newLPTokenBalance.iou()) + << " " << to_string(lpTokens.iou()) << " " + << to_string(lptAMMBalance.iou()); return {tesSUCCESS, true}; } @@ -406,7 +437,8 @@ AMMWithdraw::withdraw( beast::Journal const& journal) { auto const lpTokens = ammLPHolds(view, ammSle, account, journal); - auto const expected = ammHolds(view, ammSle, amountWithdraw.issue(), std::nullopt, freezeHandling, journal); + auto const expected = + ammHolds(view, ammSle, amountWithdraw.issue(), std::nullopt, freezeHandling, journal); // LCOV_EXCL_START if (!expected) return {expected.error(), STAmount{}, STAmount{}, STAmount{}}; @@ -430,8 +462,9 @@ AMMWithdraw::withdraw( if (lpTokensWithdrawActual <= beast::zero || lpTokensWithdrawActual > lpTokens) { - JLOG(journal.debug()) << "AMM Withdraw: failed to withdraw, invalid LP tokens: " << lpTokensWithdrawActual - << " " << lpTokens << " " << lpTokensAMMBalance; + JLOG(journal.debug()) << "AMM Withdraw: failed to withdraw, invalid LP tokens: " + << lpTokensWithdrawActual << " " << lpTokens << " " + << lpTokensAMMBalance; return {tecAMM_INVALID_TOKENS, STAmount{}, STAmount{}, STAmount{}}; } @@ -440,8 +473,9 @@ AMMWithdraw::withdraw( if (view.rules().enabled(fixAMMv1_1) && lpTokensWithdrawActual > lpTokensAMMBalance) { // LCOV_EXCL_START - JLOG(journal.debug()) << "AMM Withdraw: failed to withdraw, unexpected LP tokens: " << lpTokensWithdrawActual - << " " << lpTokens << " " << lpTokensAMMBalance; + JLOG(journal.debug()) << "AMM Withdraw: failed to withdraw, unexpected LP tokens: " + << lpTokensWithdrawActual << " " << lpTokens << " " + << lpTokensAMMBalance; return {tecINTERNAL, STAmount{}, STAmount{}, STAmount{}}; // LCOV_EXCL_STOP } @@ -452,7 +486,8 @@ AMMWithdraw::withdraw( { JLOG(journal.debug()) << "AMM Withdraw: failed to withdraw one side of the pool " << " curBalance: " << curBalance << " " << amountWithdrawActual - << " lpTokensBalance: " << lpTokensWithdraw << " lptBalance " << lpTokensAMMBalance; + << " lpTokensBalance: " << lpTokensWithdraw << " lptBalance " + << lpTokensAMMBalance; return {tecAMM_BALANCE, STAmount{}, STAmount{}, STAmount{}}; } @@ -463,7 +498,8 @@ AMMWithdraw::withdraw( JLOG(journal.debug()) << "AMM Withdraw: failed to withdraw all tokens " << " curBalance: " << curBalance << " " << amountWithdrawActual << " curBalance2: " << amount2WithdrawActual.value_or(STAmount{0}) - << " lpTokensBalance: " << lpTokensWithdraw << " lptBalance " << lpTokensAMMBalance; + << " lpTokensBalance: " << lpTokensWithdraw << " lptBalance " + << lpTokensAMMBalance; return {tecAMM_BALANCE, STAmount{}, STAmount{}, STAmount{}}; } @@ -474,7 +510,8 @@ AMMWithdraw::withdraw( << " curBalance: " << curBalance << " " << amountWithdrawActual << " curBalance2: " << curBalance2 << " " << (amount2WithdrawActual ? *amount2WithdrawActual : STAmount{}) - << " lpTokensBalance: " << lpTokensWithdraw << " lptBalance " << lpTokensAMMBalance; + << " lpTokensBalance: " << lpTokensWithdraw << " lptBalance " + << lpTokensAMMBalance; return {tecAMM_BALANCE, STAmount{}, STAmount{}, STAmount{}}; } @@ -493,7 +530,8 @@ AMMWithdraw::withdraw( // See also SetTrust::doApply() XRPAmount const reserve( - (ownerCount < 2) ? XRPAmount(beast::zero) : view.fees().accountReserve(ownerCount + 1)); + (ownerCount < 2) ? XRPAmount(beast::zero) + : view.fees().accountReserve(ownerCount + 1)); if (std::max(priorBalance, balance) < reserve) return tecINSUFFICIENT_RESERVE; @@ -505,7 +543,8 @@ AMMWithdraw::withdraw( return {err, STAmount{}, STAmount{}, STAmount{}}; // Withdraw amountWithdraw - auto res = accountSend(view, ammAccount, account, amountWithdrawActual, journal, WaiveTransferFee::Yes); + auto res = accountSend( + view, ammAccount, account, amountWithdrawActual, journal, WaiveTransferFee::Yes); if (res != tesSUCCESS) { // LCOV_EXCL_START @@ -520,7 +559,8 @@ AMMWithdraw::withdraw( if (auto const err = sufficientReserve(amount2WithdrawActual->issue()); err != tesSUCCESS) return {err, STAmount{}, STAmount{}, STAmount{}}; - res = accountSend(view, ammAccount, account, *amount2WithdrawActual, journal, WaiveTransferFee::Yes); + res = accountSend( + view, ammAccount, account, *amount2WithdrawActual, journal, WaiveTransferFee::Yes); if (res != tesSUCCESS) { // LCOV_EXCL_START @@ -541,7 +581,10 @@ AMMWithdraw::withdraw( } return std::make_tuple( - tesSUCCESS, lpTokensAMMBalance - lpTokensWithdrawActual, amountWithdrawActual, amount2WithdrawActual); + tesSUCCESS, + lpTokensAMMBalance - lpTokensWithdrawActual, + amountWithdrawActual, + amount2WithdrawActual); } static STAmount @@ -660,13 +703,16 @@ AMMWithdraw::equalWithdrawTokens( journal); } - auto const tokensAdj = adjustLPTokensIn(view.rules(), lptAMMBalance, lpTokensWithdraw, withdrawAll); + auto const tokensAdj = + adjustLPTokensIn(view.rules(), lptAMMBalance, lpTokensWithdraw, withdrawAll); if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::zero) return {tecAMM_INVALID_TOKENS, STAmount{}, STAmount{}, std::nullopt}; // the adjusted tokens are factored in auto const frac = divide(tokensAdj, lptAMMBalance, noIssue()); - auto const amountWithdraw = getRoundedAsset(view.rules(), amountBalance, frac, IsDeposit::No); - auto const amount2Withdraw = getRoundedAsset(view.rules(), amount2Balance, frac, IsDeposit::No); + auto const amountWithdraw = + getRoundedAsset(view.rules(), amountBalance, frac, IsDeposit::No); + auto const amount2Withdraw = + getRoundedAsset(view.rules(), amount2Balance, frac, IsDeposit::No); // LP is making equal withdrawal by tokens but the requested amount // of LP tokens is likely too small and results in one-sided pool // withdrawal due to round off. Fail so the user withdraws @@ -747,7 +793,15 @@ AMMWithdraw::equalWithdrawLimit( if (amount2Withdraw <= amount2) { return withdraw( - view, ammSle, ammAccount, amountBalance, amount, amount2Withdraw, lptAMMBalance, tokensAdj, tfee); + view, + ammSle, + ammAccount, + amountBalance, + amount, + amount2Withdraw, + lptAMMBalance, + tokensAdj, + tfee); } frac = Number{amount2} / amount2Balance; @@ -761,12 +815,23 @@ AMMWithdraw::equalWithdrawLimit( if (!view.rules().enabled(fixAMMv1_3)) { // LCOV_EXCL_START - XRPL_ASSERT(amountWithdraw <= amount, "xrpl::AMMWithdraw::equalWithdrawLimit : maximum amountWithdraw"); + XRPL_ASSERT( + amountWithdraw <= amount, + "xrpl::AMMWithdraw::equalWithdrawLimit : maximum amountWithdraw"); // LCOV_EXCL_STOP } else if (amountWithdraw > amount) return {tecAMM_FAILED, STAmount{}}; // LCOV_EXCL_LINE - return withdraw(view, ammSle, ammAccount, amountBalance, amountWithdraw, amount2, lptAMMBalance, tokensAdj, tfee); + return withdraw( + view, + ammSle, + ammAccount, + amountBalance, + amountWithdraw, + amount2, + lptAMMBalance, + tokensAdj, + tfee); } /** Withdraw single asset equivalent to the amount specified in Asset1Out. @@ -785,7 +850,10 @@ AMMWithdraw::singleWithdraw( std::uint16_t tfee) { auto const tokens = adjustLPTokensIn( - view.rules(), lptAMMBalance, lpTokensIn(amountBalance, amount, lptAMMBalance, tfee), isWithdrawAll(ctx_.tx)); + view.rules(), + lptAMMBalance, + lpTokensIn(amountBalance, amount, lptAMMBalance, tfee), + isWithdrawAll(ctx_.tx)); if (tokens == beast::zero) { if (!view.rules().enabled(fixAMMv1_3)) @@ -799,7 +867,15 @@ AMMWithdraw::singleWithdraw( if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::zero) return {tecAMM_INVALID_TOKENS, STAmount{}}; // LCOV_EXCL_LINE return withdraw( - view, ammSle, ammAccount, amountBalance, amountWithdrawAdj, std::nullopt, lptAMMBalance, tokensAdj, tfee); + view, + ammSle, + ammAccount, + amountBalance, + amountWithdrawAdj, + std::nullopt, + lptAMMBalance, + tokensAdj, + tfee); } /** withdrawal of single asset specified in Asset1Out proportional @@ -823,7 +899,8 @@ AMMWithdraw::singleWithdrawTokens( STAmount const& lpTokensWithdraw, std::uint16_t tfee) { - auto const tokensAdj = adjustLPTokensIn(view.rules(), lptAMMBalance, lpTokensWithdraw, isWithdrawAll(ctx_.tx)); + auto const tokensAdj = + adjustLPTokensIn(view.rules(), lptAMMBalance, lpTokensWithdraw, isWithdrawAll(ctx_.tx)); if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::zero) return {tecAMM_INVALID_TOKENS, STAmount{}}; // the adjusted tokens are factored in @@ -831,7 +908,15 @@ AMMWithdraw::singleWithdrawTokens( if (amount == beast::zero || amountWithdraw >= amount) { return withdraw( - view, ammSle, ammAccount, amountBalance, amountWithdraw, std::nullopt, lptAMMBalance, tokensAdj, tfee); + view, + ammSle, + ammAccount, + amountBalance, + amountWithdraw, + std::nullopt, + lptAMMBalance, + tokensAdj, + tfee); } return {tecAMM_FAILED, STAmount{}}; @@ -879,9 +964,12 @@ AMMWithdraw::singleWithdrawEPrice( // t = T*(T + A*E*(f - 2))/(T*f - A*E) Number const ae = amountBalance * ePrice; auto const f = getFee(tfee); - auto tokNoRoundCb = [&] { return lptAMMBalance * (lptAMMBalance + ae * (f - 2)) / (lptAMMBalance * f - ae); }; + auto tokNoRoundCb = [&] { + return lptAMMBalance * (lptAMMBalance + ae * (f - 2)) / (lptAMMBalance * f - ae); + }; auto tokProdCb = [&] { return (lptAMMBalance + ae * (f - 2)) / (lptAMMBalance * f - ae); }; - auto const tokensAdj = getRoundedLPTokens(view.rules(), tokNoRoundCb, lptAMMBalance, tokProdCb, IsDeposit::No); + auto const tokensAdj = + getRoundedLPTokens(view.rules(), tokNoRoundCb, lptAMMBalance, tokProdCb, IsDeposit::No); if (tokensAdj <= beast::zero) { if (!view.rules().enabled(fixAMMv1_3)) @@ -892,11 +980,20 @@ AMMWithdraw::singleWithdrawEPrice( auto amtNoRoundCb = [&] { return tokensAdj / ePrice; }; auto amtProdCb = [&] { return tokensAdj / ePrice; }; // the adjusted tokens are factored in - auto const amountWithdraw = getRoundedAsset(view.rules(), amtNoRoundCb, amount, amtProdCb, IsDeposit::No); + auto const amountWithdraw = + getRoundedAsset(view.rules(), amtNoRoundCb, amount, amtProdCb, IsDeposit::No); if (amount == beast::zero || amountWithdraw >= amount) { return withdraw( - view, ammSle, ammAccount, amountBalance, amountWithdraw, std::nullopt, lptAMMBalance, tokensAdj, tfee); + view, + ammSle, + ammAccount, + amountBalance, + amountWithdraw, + std::nullopt, + lptAMMBalance, + tokensAdj, + tfee); } return {tecAMM_FAILED, STAmount{}}; diff --git a/src/xrpld/app/tx/detail/Batch.cpp b/src/libxrpl/tx/transactors/Batch.cpp similarity index 94% rename from src/xrpld/app/tx/detail/Batch.cpp rename to src/libxrpl/tx/transactors/Batch.cpp index 34b08beb2f..67bb1f26e4 100644 --- a/src/xrpld/app/tx/detail/Batch.cpp +++ b/src/libxrpl/tx/transactors/Batch.cpp @@ -1,13 +1,13 @@ -#include -#include - #include #include #include #include #include +#include #include #include +#include +#include namespace xrpl { @@ -79,7 +79,8 @@ Batch::calculateBaseFee(ReadView const& view, STTx const& tx) // LCOV_EXCL_START if (txnFees > maxAmount - fee) { - JLOG(debugLog().error()) << "BatchTrace: XRPAmount overflow in txnFees calculation."; + JLOG(debugLog().error()) + << "BatchTrace: XRPAmount overflow in txnFees calculation."; return XRPAmount{INITIAL_XRP}; } // LCOV_EXCL_STOP @@ -207,8 +208,9 @@ Batch::preflight(PreflightContext const& ctx) // Validation Inner Batch Txns std::unordered_set uniqueHashes; std::unordered_map> accountSeqTicket; - auto checkSignatureFields = [&parentBatchId, &j = ctx.j]( - STObject const& sig, uint256 const& hash, char const* label = "") -> NotTEC { + auto checkSignatureFields = + [&parentBatchId, &j = ctx.j]( + STObject const& sig, uint256 const& hash, char const* label = "") -> NotTEC { if (sig.isFieldPresent(sfTxnSignature)) { JLOG(j.debug()) << "BatchTrace[" << parentBatchId << "]: " @@ -256,9 +258,10 @@ Batch::preflight(PreflightContext const& ctx) return temINVALID; } - if (std::any_of(disabledTxTypes.begin(), disabledTxTypes.end(), [txType](auto const& disabled) { - return txType == disabled; - })) + if (std::any_of( + disabledTxTypes.begin(), disabledTxTypes.end(), [txType](auto const& disabled) { + return txType == disabled; + })) { return temINVALID_INNER_BATCH; } @@ -279,7 +282,8 @@ Batch::preflight(PreflightContext const& ctx) if (stx.isFieldPresent(sfCounterpartySignature)) { auto const counterpartySignature = stx.getFieldObject(sfCounterpartySignature); - if (auto const ret = checkSignatureFields(counterpartySignature, hash, "counterparty signature ")) + if (auto const ret = + checkSignatureFields(counterpartySignature, hash, "counterparty signature ")) { return ret; } @@ -295,11 +299,13 @@ Batch::preflight(PreflightContext const& ctx) } auto const innerAccount = stx.getAccountID(sfAccount); - if (auto const preflightResult = xrpl::preflight(ctx.app, ctx.rules, parentBatchId, stx, tapBATCH, ctx.j); + if (auto const preflightResult = + xrpl::preflight(ctx.registry, ctx.rules, parentBatchId, stx, tapBATCH, ctx.j); preflightResult.ter != tesSUCCESS) { JLOG(ctx.j.debug()) << "BatchTrace[" << parentBatchId << "]: " - << "inner txn preflight failed: " << transHuman(preflightResult.ter) << " " + << "inner txn preflight failed: " << transHuman(preflightResult.ter) + << " " << "txID: " << hash; return temINVALID_INNER_BATCH; } @@ -374,7 +380,8 @@ Batch::preflightSigValidated(PreflightContext const& ctx) requiredSigners.insert(innerAccount); // Some transactions have a Counterparty, who must also sign the // transaction if they are not the outer account - if (auto const counterparty = rb.at(~sfCounterparty); counterparty && counterparty != outerAccount) + if (auto const counterparty = rb.at(~sfCounterparty); + counterparty && counterparty != outerAccount) requiredSigners.insert(*counterparty); } diff --git a/src/xrpld/app/tx/detail/Change.cpp b/src/libxrpl/tx/transactors/Change.cpp similarity index 85% rename from src/xrpld/app/tx/detail/Change.cpp rename to src/libxrpl/tx/transactors/Change.cpp index dbef2eadf9..315aeb89bd 100644 --- a/src/xrpld/app/tx/detail/Change.cpp +++ b/src/libxrpl/tx/transactors/Change.cpp @@ -1,14 +1,11 @@ -#include -#include -#include -#include -#include - #include +#include #include #include #include #include +#include +#include #include @@ -22,7 +19,8 @@ Transactor::invokePreflight(PreflightContext const& ctx) // The check for tfChangeMask is gated by LendingProtocol because that // feature introduced this parameter, and it's not worth adding another // amendment just for this. - if (auto const ret = preflight0(ctx, ctx.rules.enabled(featureLendingProtocol) ? tfChangeMask : 0)) + if (auto const ret = + preflight0(ctx, ctx.rules.enabled(featureLendingProtocol) ? tfChangeMask : 0)) return ret; auto account = ctx.tx.getAccountID(sfAccount); @@ -40,7 +38,8 @@ Transactor::invokePreflight(PreflightContext const& ctx) return temBAD_FEE; } - if (!ctx.tx.getSigningPubKey().empty() || !ctx.tx.getSignature().empty() || ctx.tx.isFieldPresent(sfSigners)) + if (!ctx.tx.getSigningPubKey().empty() || !ctx.tx.getSignature().empty() || + ctx.tx.isFieldPresent(sfSigners)) { JLOG(ctx.j.warn()) << "Change: Bad signature"; return temBAD_SIGNATURE; @@ -74,14 +73,17 @@ Change::preclaim(PreclaimContext const& ctx) // The ttFEE transaction format defines these fields as // optional, but once the XRPFees feature is enabled, they are // required. - if (!ctx.tx.isFieldPresent(sfBaseFeeDrops) || !ctx.tx.isFieldPresent(sfReserveBaseDrops) || + if (!ctx.tx.isFieldPresent(sfBaseFeeDrops) || + !ctx.tx.isFieldPresent(sfReserveBaseDrops) || !ctx.tx.isFieldPresent(sfReserveIncrementDrops)) return temMALFORMED; // The ttFEE transaction format defines these fields as // optional, but once the XRPFees feature is enabled, they are // forbidden. - if (ctx.tx.isFieldPresent(sfBaseFee) || ctx.tx.isFieldPresent(sfReferenceFeeUnits) || - ctx.tx.isFieldPresent(sfReserveBase) || ctx.tx.isFieldPresent(sfReserveIncrement)) + if (ctx.tx.isFieldPresent(sfBaseFee) || + ctx.tx.isFieldPresent(sfReferenceFeeUnits) || + ctx.tx.isFieldPresent(sfReserveBase) || + ctx.tx.isFieldPresent(sfReserveIncrement)) return temMALFORMED; } else @@ -90,13 +92,16 @@ Change::preclaim(PreclaimContext const& ctx) // as required. When the XRPFees feature was implemented, they // were changed to be optional. Until the feature has been // enabled, they are required. - if (!ctx.tx.isFieldPresent(sfBaseFee) || !ctx.tx.isFieldPresent(sfReferenceFeeUnits) || - !ctx.tx.isFieldPresent(sfReserveBase) || !ctx.tx.isFieldPresent(sfReserveIncrement)) + if (!ctx.tx.isFieldPresent(sfBaseFee) || + !ctx.tx.isFieldPresent(sfReferenceFeeUnits) || + !ctx.tx.isFieldPresent(sfReserveBase) || + !ctx.tx.isFieldPresent(sfReserveIncrement)) return temMALFORMED; // The ttFEE transaction format defines these fields as // optional, but without the XRPFees feature, they are // forbidden. - if (ctx.tx.isFieldPresent(sfBaseFeeDrops) || ctx.tx.isFieldPresent(sfReserveBaseDrops) || + if (ctx.tx.isFieldPresent(sfBaseFeeDrops) || + ctx.tx.isFieldPresent(sfReserveBaseDrops) || ctx.tx.isFieldPresent(sfReserveIncrementDrops)) return temDISABLED; } @@ -195,7 +200,7 @@ Change::applyAmendment() entry[sfAmendment] = amendment; entry[sfCloseTime] = view().parentCloseTime().time_since_epoch().count(); - if (!ctx_.app.getAmendmentTable().isSupported(amendment)) + if (!ctx_.registry.getAmendmentTable().isSupported(amendment)) { JLOG(j_.warn()) << "Unsupported amendment " << amendment << " received a majority."; } @@ -206,12 +211,13 @@ Change::applyAmendment() amendments.push_back(amendment); amendmentObject->setFieldV256(sfAmendments, amendments); - ctx_.app.getAmendmentTable().enable(amendment); + ctx_.registry.getAmendmentTable().enable(amendment); - if (!ctx_.app.getAmendmentTable().isSupported(amendment)) + if (!ctx_.registry.getAmendmentTable().isSupported(amendment)) { - JLOG(j_.error()) << "Unsupported amendment " << amendment << " activated: server blocked."; - ctx_.app.getOPs().setAmendmentBlocked(); + JLOG(j_.error()) << "Unsupported amendment " << amendment + << " activated: server blocked."; + ctx_.registry.getOPs().setAmendmentBlocked(); } } @@ -237,7 +243,9 @@ Change::applyFee() feeObject = std::make_shared(k); view().insert(feeObject); } - auto set = [](SLE::pointer& feeObject, STTx const& tx, auto const& field) { feeObject->at(field) = tx[field]; }; + auto set = [](SLE::pointer& feeObject, STTx const& tx, auto const& field) { + feeObject->at(field) = tx[field]; + }; if (view().rules().enabled(featureXRPFees)) { set(feeObject, ctx_.tx, sfBaseFeeDrops); @@ -272,8 +280,9 @@ Change::applyUNLModify() return tefFAILURE; } - if (!ctx_.tx.isFieldPresent(sfUNLModifyDisabling) || ctx_.tx.getFieldU8(sfUNLModifyDisabling) > 1 || - !ctx_.tx.isFieldPresent(sfLedgerSequence) || !ctx_.tx.isFieldPresent(sfUNLModifyValidator)) + if (!ctx_.tx.isFieldPresent(sfUNLModifyDisabling) || + ctx_.tx.getFieldU8(sfUNLModifyDisabling) > 1 || !ctx_.tx.isFieldPresent(sfLedgerSequence) || + !ctx_.tx.isFieldPresent(sfUNLModifyValidator)) { JLOG(j_.warn()) << "N-UNL: applyUNLModify, wrong Tx format."; return tefFAILURE; @@ -294,8 +303,8 @@ Change::applyUNLModify() return tefFAILURE; } - JLOG(j_.info()) << "N-UNL: applyUNLModify, " << (disabling ? "ToDisable" : "ToReEnable") << " seq=" << seq - << " validator data:" << strHex(validator); + JLOG(j_.info()) << "N-UNL: applyUNLModify, " << (disabling ? "ToDisable" : "ToReEnable") + << " seq=" << seq << " validator data:" << strHex(validator); auto const k = keylet::negativeUNL(); SLE::pointer negUnlObject = view().peek(k); diff --git a/src/xrpld/app/tx/detail/CancelCheck.cpp b/src/libxrpl/tx/transactors/Check/CancelCheck.cpp similarity index 95% rename from src/xrpld/app/tx/detail/CancelCheck.cpp rename to src/libxrpl/tx/transactors/Check/CancelCheck.cpp index 4ac04e9ffb..c9a947ae6a 100644 --- a/src/xrpld/app/tx/detail/CancelCheck.cpp +++ b/src/libxrpl/tx/transactors/Check/CancelCheck.cpp @@ -1,12 +1,11 @@ -#include -#include - #include #include +#include #include #include #include #include +#include namespace xrpl { @@ -62,7 +61,7 @@ CancelCheck::doApply() AccountID const srcId{sleCheck->getAccountID(sfAccount)}; AccountID const dstId{sleCheck->getAccountID(sfDestination)}; - auto viewJ = ctx_.app.journal("View"); + auto viewJ = ctx_.registry.journal("View"); // If the check is not written to self (and it shouldn't be), remove the // check from the destination account root. diff --git a/src/xrpld/app/tx/detail/CashCheck.cpp b/src/libxrpl/tx/transactors/Check/CashCheck.cpp similarity index 94% rename from src/xrpld/app/tx/detail/CashCheck.cpp rename to src/libxrpl/tx/transactors/Check/CashCheck.cpp index 9deee006d9..c459ef9b67 100644 --- a/src/xrpld/app/tx/detail/CashCheck.cpp +++ b/src/libxrpl/tx/transactors/Check/CashCheck.cpp @@ -1,13 +1,12 @@ -#include -#include -#include - #include #include +#include #include #include #include #include +#include +#include #include @@ -126,7 +125,8 @@ CashCheck::preclaim(PreclaimContext const& ctx) // Make sure the check owner holds at least value. If they have // less than value the check cannot be cashed. { - STAmount availableFunds{accountFunds(ctx.view, sleCheck->at(sfAccount), value, fhZERO_IF_FROZEN, ctx.j)}; + STAmount availableFunds{ + accountFunds(ctx.view, sleCheck->at(sfAccount), value, fhZERO_IF_FROZEN, ctx.j)}; // Note that src will have one reserve's worth of additional XRP // once the check is cashed, since the check's reserve will no @@ -148,7 +148,8 @@ CashCheck::preclaim(PreclaimContext const& ctx) auto const sleIssuer = ctx.view.read(keylet::account(issuerId)); if (!sleIssuer) { - JLOG(ctx.j.warn()) << "Can't receive IOUs from non-existent issuer: " << to_string(issuerId); + JLOG(ctx.j.warn()) + << "Can't receive IOUs from non-existent issuer: " << to_string(issuerId); return tecNO_ISSUER; } @@ -168,7 +169,8 @@ CashCheck::preclaim(PreclaimContext const& ctx) // weak ordering. Determine which entry we need to access. bool const canonical_gt(dstId > issuerId); - bool const is_authorized(sleTrustLine->at(sfFlags) & (canonical_gt ? lsfLowAuth : lsfHighAuth)); + bool const is_authorized( + sleTrustLine->at(sfFlags) & (canonical_gt ? lsfLowAuth : lsfHighAuth)); if (!is_authorized) { @@ -228,7 +230,7 @@ CashCheck::doApply() // // If it is not a check to self (as should be the case), then there's // work to do... - auto viewJ = ctx_.app.journal("View"); + auto viewJ = ctx_.registry.journal("View"); auto const optDeliverMin = ctx_.tx[~sfDeliverMin]; if (srcId != account_) @@ -257,8 +259,8 @@ CashCheck::doApply() { // Vote no. However the transaction might succeed if applied // in a different order. - JLOG(j_.trace()) << "Cash Check: Insufficient XRP: " << srcLiquid.getFullText() << " < " - << xrpDeliver.getFullText(); + JLOG(j_.trace()) << "Cash Check: Insufficient XRP: " << srcLiquid.getFullText() + << " < " << xrpDeliver.getFullText(); return tecUNFUNDED_PAYMENT; } @@ -267,7 +269,8 @@ CashCheck::doApply() ctx_.deliver(xrpDeliver); // The source account has enough XRP so make the ledger change. - if (TER const ter{transferXRP(psb, srcId, account_, xrpDeliver, viewJ)}; ter != tesSUCCESS) + if (TER const ter{transferXRP(psb, srcId, account_, xrpDeliver, viewJ)}; + ter != tesSUCCESS) { // The transfer failed. Return the error code. return ter; @@ -281,8 +284,10 @@ CashCheck::doApply() // transfer rate to account for. Since the transfer rate cannot // exceed 200%, we use 1/2 maxValue as our limit. STAmount const flowDeliver{ - optDeliverMin ? STAmount(optDeliverMin->issue(), STAmount::cMaxValue / 2, STAmount::cMaxOffset) - : ctx_.tx.getFieldAmount(sfAmount)}; + optDeliverMin + ? STAmount( + optDeliverMin->issue(), STAmount::cMaxValue / 2, STAmount::cMaxOffset) + : ctx_.tx.getFieldAmount(sfAmount)}; // If a trust line does not exist yet create one. Issue const& trustLineIssue = flowDeliver.issue(); @@ -411,7 +416,8 @@ CashCheck::doApply() // Check was cashed. If not a self send (and it shouldn't be), remove // check link from destination directory. if (srcId != account_ && - !psb.dirRemove(keylet::ownerDir(account_), sleCheck->at(sfDestinationNode), sleCheck->key(), true)) + !psb.dirRemove( + keylet::ownerDir(account_), sleCheck->at(sfDestinationNode), sleCheck->key(), true)) { // LCOV_EXCL_START JLOG(j_.fatal()) << "Unable to delete check from destination."; diff --git a/src/xrpld/app/tx/detail/CreateCheck.cpp b/src/libxrpl/tx/transactors/Check/CreateCheck.cpp similarity index 89% rename from src/xrpld/app/tx/detail/CreateCheck.cpp rename to src/libxrpl/tx/transactors/Check/CreateCheck.cpp index d10863df46..7ec4746d20 100644 --- a/src/xrpld/app/tx/detail/CreateCheck.cpp +++ b/src/libxrpl/tx/transactors/Check/CreateCheck.cpp @@ -1,11 +1,10 @@ -#include - #include #include #include #include #include #include +#include namespace xrpl { @@ -23,7 +22,8 @@ CreateCheck::preflight(PreflightContext const& ctx) STAmount const sendMax{ctx.tx.getFieldAmount(sfSendMax)}; if (!isLegalNet(sendMax) || sendMax.signum() <= 0) { - JLOG(ctx.j.warn()) << "Malformed transaction: bad sendMax amount: " << sendMax.getFullText(); + JLOG(ctx.j.warn()) << "Malformed transaction: bad sendMax amount: " + << sendMax.getFullText(); return temBAD_AMOUNT; } @@ -98,7 +98,8 @@ CreateCheck::preclaim(PreclaimContext const& ctx) if (issuerId != srcId) { // Check if the issuer froze the line - auto const sleTrust = ctx.view.read(keylet::line(srcId, issuerId, sendMax.getCurrency())); + auto const sleTrust = + ctx.view.read(keylet::line(srcId, issuerId, sendMax.getCurrency())); if (sleTrust && sleTrust->isFlag((issuerId > srcId) ? lsfHighFreeze : lsfLowFreeze)) { JLOG(ctx.j.warn()) << "Creating a check for frozen trustline."; @@ -108,7 +109,8 @@ CreateCheck::preclaim(PreclaimContext const& ctx) if (issuerId != dstId) { // Check if dst froze the line. - auto const sleTrust = ctx.view.read(keylet::line(issuerId, dstId, sendMax.getCurrency())); + auto const sleTrust = + ctx.view.read(keylet::line(issuerId, dstId, sendMax.getCurrency())); if (sleTrust && sleTrust->isFlag((dstId > issuerId) ? lsfHighFreeze : lsfLowFreeze)) { JLOG(ctx.j.warn()) << "Creating a check for destination frozen trustline."; @@ -164,15 +166,16 @@ CreateCheck::doApply() view().insert(sleCheck); - auto viewJ = ctx_.app.journal("View"); + auto viewJ = ctx_.registry.journal("View"); // If it's not a self-send (and it shouldn't be), add Check to the // destination's owner directory. if (dstAccountId != account_) { - auto const page = view().dirInsert(keylet::ownerDir(dstAccountId), checkKeylet, describeOwnerDir(dstAccountId)); + auto const page = view().dirInsert( + keylet::ownerDir(dstAccountId), checkKeylet, describeOwnerDir(dstAccountId)); - JLOG(j_.trace()) << "Adding Check to destination directory " << to_string(checkKeylet.key) << ": " - << (page ? "success" : "failure"); + JLOG(j_.trace()) << "Adding Check to destination directory " << to_string(checkKeylet.key) + << ": " << (page ? "success" : "failure"); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE @@ -181,7 +184,8 @@ CreateCheck::doApply() } { - auto const page = view().dirInsert(keylet::ownerDir(account_), checkKeylet, describeOwnerDir(account_)); + auto const page = + view().dirInsert(keylet::ownerDir(account_), checkKeylet, describeOwnerDir(account_)); JLOG(j_.trace()) << "Adding Check to owner directory " << to_string(checkKeylet.key) << ": " << (page ? "success" : "failure"); diff --git a/src/xrpld/app/tx/detail/Clawback.cpp b/src/libxrpl/tx/transactors/Clawback.cpp similarity index 83% rename from src/xrpld/app/tx/detail/Clawback.cpp rename to src/libxrpl/tx/transactors/Clawback.cpp index ad4a2f24d0..ac13cc10da 100644 --- a/src/xrpld/app/tx/detail/Clawback.cpp +++ b/src/libxrpl/tx/transactors/Clawback.cpp @@ -1,11 +1,10 @@ -#include - #include #include #include #include #include #include +#include namespace xrpl { @@ -64,8 +63,9 @@ Clawback::getFlagsMask(PreflightContext const& ctx) NotTEC Clawback::preflight(PreflightContext const& ctx) { - if (auto const ret = - std::visit([&](T const&) { return preflightHelper(ctx); }, ctx.tx[sfAmount].asset().value()); + if (auto const ret = std::visit( + [&](T const&) { return preflightHelper(ctx); }, + ctx.tx[sfAmount].asset().value()); !isTesSuccess(ret)) return ret; @@ -97,7 +97,8 @@ preclaimHelper( if (!(issuerFlagsIn & lsfAllowTrustLineClawback) || (issuerFlagsIn & lsfNoFreeze)) return tecNO_PERMISSION; - auto const sleRippleState = ctx.view.read(keylet::line(holder, issuer, clawAmount.getCurrency())); + auto const sleRippleState = + ctx.view.read(keylet::line(holder, issuer, clawAmount.getCurrency())); if (!sleRippleState) return tecNO_LINE; @@ -120,7 +121,8 @@ preclaimHelper( // We can't directly check the balance of trustline because // the available balance of a trustline is prone to new changes (eg. // XLS-34). So we must use `accountHolds`. - if (accountHolds(ctx.view, holder, clawAmount.getCurrency(), issuer, fhIGNORE_FREEZE, ctx.j) <= beast::zero) + if (accountHolds(ctx.view, holder, clawAmount.getCurrency(), issuer, fhIGNORE_FREEZE, ctx.j) <= + beast::zero) return tecINSUFFICIENT_FUNDS; return tesSUCCESS; @@ -149,7 +151,8 @@ preclaimHelper( if (!ctx.view.exists(keylet::mptoken(issuanceKey.key, holder))) return tecOBJECT_NOT_FOUND; - if (accountHolds(ctx.view, holder, clawAmount.get(), fhIGNORE_FREEZE, ahIGNORE_AUTH, ctx.j) <= + if (accountHolds( + ctx.view, holder, clawAmount.get(), fhIGNORE_FREEZE, ahIGNORE_AUTH, ctx.j) <= beast::zero) return tecINSUFFICIENT_FUNDS; @@ -176,7 +179,9 @@ Clawback::preclaim(PreclaimContext const& ctx) return tecAMM_ACCOUNT; return std::visit( - [&](T const&) { return preclaimHelper(ctx, *sleIssuer, issuer, holder, clawAmount); }, + [&](T const&) { + return preclaimHelper(ctx, *sleIssuer, issuer, holder, clawAmount); + }, ctx.tx[sfAmount].asset().value()); } @@ -199,9 +204,15 @@ applyHelper(ApplyContext& ctx) // Get the spendable balance. Must use `accountHolds`. STAmount const spendableAmount = accountHolds( - ctx.view(), holder, clawAmount.getCurrency(), clawAmount.getIssuer(), fhIGNORE_FREEZE, ctx.journal); + ctx.view(), + holder, + clawAmount.getCurrency(), + clawAmount.getIssuer(), + fhIGNORE_FREEZE, + ctx.journal); - return rippleCredit(ctx.view(), holder, issuer, std::min(spendableAmount, clawAmount), true, ctx.journal); + return rippleCredit( + ctx.view(), holder, issuer, std::min(spendableAmount, clawAmount), true, ctx.journal); } template <> @@ -213,8 +224,13 @@ applyHelper(ApplyContext& ctx) AccountID const holder = ctx.tx[sfHolder]; // Get the spendable balance. Must use `accountHolds`. - STAmount const spendableAmount = - accountHolds(ctx.view(), holder, clawAmount.get(), fhIGNORE_FREEZE, ahIGNORE_AUTH, ctx.journal); + STAmount const spendableAmount = accountHolds( + ctx.view(), + holder, + clawAmount.get(), + fhIGNORE_FREEZE, + ahIGNORE_AUTH, + ctx.journal); return rippleCredit( ctx.view(), @@ -228,7 +244,9 @@ applyHelper(ApplyContext& ctx) TER Clawback::doApply() { - return std::visit([&](T const&) { return applyHelper(ctx_); }, ctx_.tx[sfAmount].asset().value()); + return std::visit( + [&](T const&) { return applyHelper(ctx_); }, + ctx_.tx[sfAmount].asset().value()); } } // namespace xrpl diff --git a/src/xrpld/app/tx/detail/CreateTicket.cpp b/src/libxrpl/tx/transactors/CreateTicket.cpp similarity index 84% rename from src/xrpld/app/tx/detail/CreateTicket.cpp rename to src/libxrpl/tx/transactors/CreateTicket.cpp index e6965ca1cf..b1991c6e77 100644 --- a/src/xrpld/app/tx/detail/CreateTicket.cpp +++ b/src/libxrpl/tx/transactors/CreateTicket.cpp @@ -1,9 +1,9 @@ -#include - #include +#include #include #include #include +#include namespace xrpl { @@ -17,7 +17,8 @@ CreateTicket::makeTxConsequences(PreflightContext const& ctx) NotTEC CreateTicket::preflight(PreflightContext const& ctx) { - if (std::uint32_t const count = ctx.tx[sfTicketCount]; count < minValidCount || count > maxValidCount) + if (std::uint32_t const count = ctx.tx[sfTicketCount]; + count < minValidCount || count > maxValidCount) return temINVALID_COUNT; return tesSUCCESS; @@ -61,13 +62,14 @@ CreateTicket::doApply() // reserve to pay fees. std::uint32_t const ticketCount = ctx_.tx[sfTicketCount]; { - XRPAmount const reserve = view().fees().accountReserve(sleAccountRoot->getFieldU32(sfOwnerCount) + ticketCount); + XRPAmount const reserve = + view().fees().accountReserve(sleAccountRoot->getFieldU32(sfOwnerCount) + ticketCount); if (mPriorBalance < reserve) return tecINSUFFICIENT_RESERVE; } - beast::Journal viewJ{ctx_.app.journal("View")}; + beast::Journal viewJ{ctx_.registry.journal("View")}; // The starting ticket sequence is the same as the current account // root sequence. Before we got here to doApply(), the transaction @@ -77,7 +79,8 @@ CreateTicket::doApply() // Sanity check that the transaction machinery really did already // increment the account root Sequence. - if (std::uint32_t const txSeq = ctx_.tx[sfSequence]; txSeq != 0 && txSeq != (firstTicketSeq - 1)) + if (std::uint32_t const txSeq = ctx_.tx[sfSequence]; + txSeq != 0 && txSeq != (firstTicketSeq - 1)) return tefINTERNAL; // LCOV_EXCL_LINE for (std::uint32_t i = 0; i < ticketCount; ++i) @@ -90,9 +93,11 @@ CreateTicket::doApply() 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(account_), ticketKeylet, describeOwnerDir(account_)); - JLOG(j_.trace()) << "Creating ticket " << to_string(ticketKeylet.key) << ": " << (page ? "success" : "failure"); + JLOG(j_.trace()) << "Creating ticket " << to_string(ticketKeylet.key) << ": " + << (page ? "success" : "failure"); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE diff --git a/src/xrpld/app/tx/detail/Credentials.cpp b/src/libxrpl/tx/transactors/Credentials.cpp similarity index 88% rename from src/xrpld/app/tx/detail/Credentials.cpp rename to src/libxrpl/tx/transactors/Credentials.cpp index fc3019308a..ce95d8144c 100644 --- a/src/xrpld/app/tx/detail/Credentials.cpp +++ b/src/libxrpl/tx/transactors/Credentials.cpp @@ -1,5 +1,3 @@ -#include - #include #include #include @@ -7,6 +5,7 @@ #include #include #include +#include #include @@ -100,7 +99,8 @@ CredentialCreate::doApply() auto const optExp = ctx_.tx[~sfExpiration]; if (optExp) { - std::uint32_t const closeTime = ctx_.view().header().parentCloseTime.time_since_epoch().count(); + std::uint32_t const closeTime = + ctx_.view().header().parentCloseTime.time_since_epoch().count(); if (closeTime > *optExp) { @@ -117,7 +117,8 @@ CredentialCreate::doApply() return tefINTERNAL; // LCOV_EXCL_LINE { - STAmount const reserve{view().fees().accountReserve(sleIssuer->getFieldU32(sfOwnerCount) + 1)}; + STAmount const reserve{ + view().fees().accountReserve(sleIssuer->getFieldU32(sfOwnerCount) + 1)}; if (mPriorBalance < reserve) return tecINSUFFICIENT_RESERVE; } @@ -130,9 +131,10 @@ CredentialCreate::doApply() sleCred->setFieldVL(sfURI, ctx_.tx.getFieldVL(sfURI)); { - auto const page = view().dirInsert(keylet::ownerDir(account_), credentialKey, describeOwnerDir(account_)); - JLOG(j_.trace()) << "Adding Credential to owner directory " << to_string(credentialKey.key) << ": " - << (page ? "success" : "failure"); + auto const page = + view().dirInsert(keylet::ownerDir(account_), credentialKey, describeOwnerDir(account_)); + JLOG(j_.trace()) << "Adding Credential to owner directory " << to_string(credentialKey.key) + << ": " << (page ? "success" : "failure"); if (!page) return tecDIR_FULL; sleCred->setFieldU64(sfIssuerNode, *page); @@ -146,9 +148,10 @@ CredentialCreate::doApply() } else { - auto const page = view().dirInsert(keylet::ownerDir(subject), credentialKey, describeOwnerDir(subject)); - JLOG(j_.trace()) << "Adding Credential to owner directory " << to_string(credentialKey.key) << ": " - << (page ? "success" : "failure"); + auto const page = + view().dirInsert(keylet::ownerDir(subject), credentialKey, describeOwnerDir(subject)); + JLOG(j_.trace()) << "Adding Credential to owner directory " << to_string(credentialKey.key) + << ": " << (page ? "success" : "failure"); if (!page) return tecDIR_FULL; sleCred->setFieldU64(sfSubjectNode, *page); @@ -226,7 +229,8 @@ CredentialDelete::doApply() if (!sleCred) return tefINTERNAL; // LCOV_EXCL_LINE - if ((subject != account_) && (issuer != account_) && !checkExpired(sleCred, ctx_.view().header().parentCloseTime)) + if ((subject != account_) && (issuer != account_) && + !checkExpired(sleCred, ctx_.view().header().parentCloseTime)) { JLOG(j_.trace()) << "Can't delete non-expired credential."; return tecNO_PERMISSION; @@ -279,14 +283,15 @@ CredentialAccept::preclaim(PreclaimContext const& ctx) auto const sleCred = ctx.view.read(keylet::credential(subject, issuer, credType)); if (!sleCred) { - JLOG(ctx.j.warn()) << "No credential: " << to_string(subject) << ", " << to_string(issuer) << ", " << credType; + JLOG(ctx.j.warn()) << "No credential: " << to_string(subject) << ", " << to_string(issuer) + << ", " << credType; return tecNO_ENTRY; } if (sleCred->getFieldU32(sfFlags) & lsfAccepted) { - JLOG(ctx.j.warn()) << "Credential already accepted: " << to_string(subject) << ", " << to_string(issuer) << ", " - << credType; + JLOG(ctx.j.warn()) << "Credential already accepted: " << to_string(subject) << ", " + << to_string(issuer) << ", " << credType; return tecDUPLICATE; } @@ -306,7 +311,8 @@ CredentialAccept::doApply() return tefINTERNAL; // LCOV_EXCL_LINE { - STAmount const reserve{view().fees().accountReserve(sleSubject->getFieldU32(sfOwnerCount) + 1)}; + STAmount const reserve{ + view().fees().accountReserve(sleSubject->getFieldU32(sfOwnerCount) + 1)}; if (mPriorBalance < reserve) return tecINSUFFICIENT_RESERVE; } diff --git a/src/xrpld/app/tx/detail/DID.cpp b/src/libxrpl/tx/transactors/DID.cpp similarity index 89% rename from src/xrpld/app/tx/detail/DID.cpp rename to src/libxrpl/tx/transactors/DID.cpp index 7219dcf60e..ade60221df 100644 --- a/src/xrpld/app/tx/detail/DID.cpp +++ b/src/libxrpl/tx/transactors/DID.cpp @@ -1,11 +1,10 @@ -#include - #include #include #include #include #include #include +#include namespace xrpl { @@ -26,11 +25,13 @@ namespace xrpl { NotTEC DIDSet::preflight(PreflightContext const& ctx) { - if (!ctx.tx.isFieldPresent(sfURI) && !ctx.tx.isFieldPresent(sfDIDDocument) && !ctx.tx.isFieldPresent(sfData)) + if (!ctx.tx.isFieldPresent(sfURI) && !ctx.tx.isFieldPresent(sfDIDDocument) && + !ctx.tx.isFieldPresent(sfData)) return temEMPTY_DID; - if (ctx.tx.isFieldPresent(sfURI) && ctx.tx[sfURI].empty() && ctx.tx.isFieldPresent(sfDIDDocument) && - ctx.tx[sfDIDDocument].empty() && ctx.tx.isFieldPresent(sfData) && ctx.tx[sfData].empty()) + if (ctx.tx.isFieldPresent(sfURI) && ctx.tx[sfURI].empty() && + ctx.tx.isFieldPresent(sfDIDDocument) && ctx.tx[sfDIDDocument].empty() && + ctx.tx.isFieldPresent(sfData) && ctx.tx[sfData].empty()) return temEMPTY_DID; auto isTooLong = [&](auto const& sField, std::size_t length) -> bool { @@ -67,7 +68,8 @@ addSLE(ApplyContext& ctx, std::shared_ptr const& sle, AccountID const& owne // Add ledger object to owner's page { - auto page = ctx.view().dirInsert(keylet::ownerDir(owner), sle->key(), describeOwnerDir(owner)); + auto page = + ctx.view().dirInsert(keylet::ownerDir(owner), sle->key(), describeOwnerDir(owner)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE (*sle)[sfOwnerNode] = *page; @@ -102,7 +104,8 @@ DIDSet::doApply() update(sfDIDDocument); update(sfData); - if (!sleDID->isFieldPresent(sfURI) && !sleDID->isFieldPresent(sfDIDDocument) && !sleDID->isFieldPresent(sfData)) + if (!sleDID->isFieldPresent(sfURI) && !sleDID->isFieldPresent(sfDIDDocument) && + !sleDID->isFieldPresent(sfData)) { return tecEMPTY_DID; } @@ -148,7 +151,11 @@ DIDDelete::deleteSLE(ApplyContext& ctx, Keylet sleKeylet, AccountID const owner) } TER -DIDDelete::deleteSLE(ApplyView& view, std::shared_ptr sle, AccountID const owner, beast::Journal j) +DIDDelete::deleteSLE( + ApplyView& view, + std::shared_ptr sle, + AccountID const owner, + beast::Journal j) { // Remove object from owner directory if (!view.dirRemove(keylet::ownerDir(owner), (*sle)[sfOwnerNode], sle->key(), true)) diff --git a/src/xrpld/app/tx/detail/DelegateSet.cpp b/src/libxrpl/tx/transactors/Delegate/DelegateSet.cpp similarity index 91% rename from src/xrpld/app/tx/detail/DelegateSet.cpp rename to src/libxrpl/tx/transactors/Delegate/DelegateSet.cpp index 8dba3ef72e..69ec707dd2 100644 --- a/src/xrpld/app/tx/detail/DelegateSet.cpp +++ b/src/libxrpl/tx/transactors/Delegate/DelegateSet.cpp @@ -1,10 +1,9 @@ -#include - #include #include #include #include #include +#include namespace xrpl { @@ -68,7 +67,8 @@ DelegateSet::doApply() return tesSUCCESS; } - STAmount const reserve{ctx_.view().fees().accountReserve(sleOwner->getFieldU32(sfOwnerCount) + 1)}; + STAmount const reserve{ + ctx_.view().fees().accountReserve(sleOwner->getFieldU32(sfOwnerCount) + 1)}; if (mPriorBalance < reserve) return tecINSUFFICIENT_RESERVE; @@ -81,7 +81,8 @@ DelegateSet::doApply() sle->setAccountID(sfAuthorize, authAccount); sle->setFieldArray(sfPermissions, permissions); - auto const page = ctx_.view().dirInsert(keylet::ownerDir(account_), delegateKey, describeOwnerDir(account_)); + auto const page = ctx_.view().dirInsert( + keylet::ownerDir(account_), delegateKey, describeOwnerDir(account_)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE diff --git a/src/xrpld/app/misc/detail/DelegateUtils.cpp b/src/libxrpl/tx/transactors/Delegate/DelegateUtils.cpp similarity index 95% rename from src/xrpld/app/misc/detail/DelegateUtils.cpp rename to src/libxrpl/tx/transactors/Delegate/DelegateUtils.cpp index 74ec55cdee..eceb73503f 100644 --- a/src/xrpld/app/misc/detail/DelegateUtils.cpp +++ b/src/libxrpl/tx/transactors/Delegate/DelegateUtils.cpp @@ -1,6 +1,5 @@ -#include - #include +#include namespace xrpl { NotTEC diff --git a/src/xrpld/app/tx/detail/DeleteAccount.cpp b/src/libxrpl/tx/transactors/DeleteAccount.cpp similarity index 90% rename from src/xrpld/app/tx/detail/DeleteAccount.cpp rename to src/libxrpl/tx/transactors/DeleteAccount.cpp index 18961469a3..79ce03ca9a 100644 --- a/src/xrpld/app/tx/detail/DeleteAccount.cpp +++ b/src/libxrpl/tx/transactors/DeleteAccount.cpp @@ -1,11 +1,3 @@ -#include -#include -#include -#include -#include -#include -#include - #include #include #include @@ -16,6 +8,13 @@ #include #include #include +#include +#include +#include +#include +#include +#include +#include namespace xrpl { @@ -51,7 +50,7 @@ DeleteAccount::calculateBaseFee(ReadView const& view, STTx const& tx) namespace { // Define a function pointer type that can be used to delete ledger node types. using DeleterFuncPtr = TER (*)( - Application& app, + ServiceRegistry& registry, ApplyView& view, AccountID const& account, uint256 const& delIndex, @@ -61,7 +60,7 @@ using DeleterFuncPtr = TER (*)( // Local function definitions that provides signature compatibility. TER offerDelete( - Application& app, + ServiceRegistry&, ApplyView& view, AccountID const& account, uint256 const& delIndex, @@ -73,19 +72,19 @@ offerDelete( TER removeSignersFromLedger( - Application& app, + ServiceRegistry& registry, ApplyView& view, AccountID const& account, uint256 const& delIndex, std::shared_ptr const& sleDel, beast::Journal j) { - return SetSignerList::removeFromLedger(app, view, account, j); + return SetSignerList::removeFromLedger(registry, view, account, j); } TER removeTicketFromLedger( - Application&, + ServiceRegistry&, ApplyView& view, AccountID const& account, uint256 const& delIndex, @@ -97,7 +96,7 @@ removeTicketFromLedger( TER removeDepositPreauthFromLedger( - Application&, + ServiceRegistry&, ApplyView& view, AccountID const&, uint256 const& delIndex, @@ -109,7 +108,7 @@ removeDepositPreauthFromLedger( TER removeNFTokenOfferFromLedger( - Application& app, + ServiceRegistry&, ApplyView& view, AccountID const& account, uint256 const& delIndex, @@ -124,7 +123,7 @@ removeNFTokenOfferFromLedger( TER removeDIDFromLedger( - Application& app, + ServiceRegistry&, ApplyView& view, AccountID const& account, uint256 const& delIndex, @@ -136,7 +135,7 @@ removeDIDFromLedger( TER removeOracleFromLedger( - Application&, + ServiceRegistry&, ApplyView& view, AccountID const& account, uint256 const&, @@ -148,7 +147,7 @@ removeOracleFromLedger( TER removeCredentialFromLedger( - Application&, + ServiceRegistry&, ApplyView& view, AccountID const&, uint256 const&, @@ -160,7 +159,7 @@ removeCredentialFromLedger( TER removeDelegateFromLedger( - Application& app, + ServiceRegistry&, ApplyView& view, AccountID const& account, uint256 const& delIndex, @@ -247,7 +246,8 @@ DeleteAccount::preclaim(PreclaimContext const& ctx) Keylet const first = keylet::nftpage_min(account); Keylet const last = keylet::nftpage_max(account); - auto const cp = ctx.view.read(Keylet(ltNFTOKEN_PAGE, ctx.view.succ(first.key, last.key.next()).value_or(last.key))); + auto const cp = ctx.view.read( + Keylet(ltNFTOKEN_PAGE, ctx.view.succ(first.key, last.key.next()).value_or(last.key))); if (cp) return tecHAS_OBLIGATIONS; @@ -272,7 +272,8 @@ DeleteAccount::preclaim(PreclaimContext const& ctx) // their account and mints a NFToken, it is possible that the // NFTokenSequence of this NFToken is the same as the one that the // authorized minter minted in a previous ledger. - if ((*sleAccount)[~sfFirstNFTokenSequence].value_or(0) + (*sleAccount)[~sfMintedNFTokens].value_or(0) + seqDelta > + if ((*sleAccount)[~sfFirstNFTokenSequence].value_or(0) + + (*sleAccount)[~sfMintedNFTokens].value_or(0) + seqDelta > ctx.view.seq()) return tecTOO_SOON; @@ -337,7 +338,8 @@ DeleteAccount::doApply() if (ctx_.tx.isFieldPresent(sfCredentialIDs)) { - if (auto err = verifyDepositPreauth(ctx_.tx, ctx_.view(), account_, dstID, dst, ctx_.journal); + if (auto err = + verifyDepositPreauth(ctx_.tx, ctx_.view(), account_, dstID, dst, ctx_.journal); !isTesSuccess(err)) return err; } @@ -351,7 +353,7 @@ DeleteAccount::doApply() std::shared_ptr& sleItem) -> std::pair { if (auto deleter = nonObligationDeleter(nodeType)) { - TER const result{deleter(ctx_.app, view(), account_, dirEntry, sleItem, j_)}; + TER const result{deleter(ctx_.registry, view(), account_, dirEntry, sleItem, j_)}; return {result, SkipEntry::No}; } @@ -374,7 +376,8 @@ DeleteAccount::doApply() (*src)[sfBalance] = (*src)[sfBalance] - mSourceBalance; ctx_.deliver(mSourceBalance); - XRPL_ASSERT((*src)[sfBalance] == XRPAmount(0), "xrpl::DeleteAccount::doApply : source balance is zero"); + XRPL_ASSERT( + (*src)[sfBalance] == XRPAmount(0), "xrpl::DeleteAccount::doApply : source balance is zero"); // If there's still an owner directory associated with the source account // delete it. diff --git a/src/xrpld/app/tx/detail/DeleteOracle.cpp b/src/libxrpl/tx/transactors/DeleteOracle.cpp similarity index 84% rename from src/xrpld/app/tx/detail/DeleteOracle.cpp rename to src/libxrpl/tx/transactors/DeleteOracle.cpp index 9b62bffb5f..ebaffd334a 100644 --- a/src/xrpld/app/tx/detail/DeleteOracle.cpp +++ b/src/libxrpl/tx/transactors/DeleteOracle.cpp @@ -1,9 +1,8 @@ -#include - #include #include #include #include +#include namespace xrpl { @@ -19,7 +18,8 @@ DeleteOracle::preclaim(PreclaimContext const& ctx) if (!ctx.view.exists(keylet::account(ctx.tx.getAccountID(sfAccount)))) return terNO_ACCOUNT; // LCOV_EXCL_LINE - if (auto const sle = ctx.view.read(keylet::oracle(ctx.tx.getAccountID(sfAccount), ctx.tx[sfOracleDocumentID])); + if (auto const sle = ctx.view.read( + keylet::oracle(ctx.tx.getAccountID(sfAccount), ctx.tx[sfOracleDocumentID])); !sle) { JLOG(ctx.j.debug()) << "Oracle Delete: Oracle does not exist."; @@ -37,7 +37,11 @@ DeleteOracle::preclaim(PreclaimContext const& ctx) } TER -DeleteOracle::deleteOracle(ApplyView& view, std::shared_ptr const& sle, AccountID const& account, beast::Journal j) +DeleteOracle::deleteOracle( + ApplyView& view, + std::shared_ptr const& sle, + AccountID const& account, + beast::Journal j) { if (!sle) return tecINTERNAL; // LCOV_EXCL_LINE diff --git a/src/xrpld/app/tx/detail/DepositPreauth.cpp b/src/libxrpl/tx/transactors/DepositPreauth.cpp similarity index 84% rename from src/xrpld/app/tx/detail/DepositPreauth.cpp rename to src/libxrpl/tx/transactors/DepositPreauth.cpp index 4636bdb359..6857816d1f 100644 --- a/src/xrpld/app/tx/detail/DepositPreauth.cpp +++ b/src/libxrpl/tx/transactors/DepositPreauth.cpp @@ -1,11 +1,10 @@ -#include - #include #include #include #include #include #include +#include #include @@ -29,11 +28,13 @@ DepositPreauth::preflight(PreflightContext const& ctx) { bool const authArrPresent = ctx.tx.isFieldPresent(sfAuthorizeCredentials); bool const unauthArrPresent = ctx.tx.isFieldPresent(sfUnauthorizeCredentials); - int const authCredPresent = static_cast(authArrPresent) + static_cast(unauthArrPresent); + int const authCredPresent = + static_cast(authArrPresent) + static_cast(unauthArrPresent); auto const optAuth = ctx.tx[~sfAuthorize]; auto const optUnauth = ctx.tx[~sfUnauthorize]; - int const authPresent = static_cast(optAuth.has_value()) + static_cast(optUnauth.has_value()); + int const authPresent = + static_cast(optAuth.has_value()) + static_cast(optUnauth.has_value()); if (authPresent + authCredPresent != 1) { @@ -64,7 +65,8 @@ DepositPreauth::preflight(PreflightContext const& ctx) else { if (auto err = credentials::checkArray( - ctx.tx.getFieldArray(authArrPresent ? sfAuthorizeCredentials : sfUnauthorizeCredentials), + ctx.tx.getFieldArray( + authArrPresent ? sfAuthorizeCredentials : sfUnauthorizeCredentials), maxCredentialsArraySize, ctx.j); !isTesSuccess(err)) @@ -120,8 +122,10 @@ DepositPreauth::preclaim(PreclaimContext const& ctx) else if (ctx.tx.isFieldPresent(sfUnauthorizeCredentials)) { // Verify that the Preauth entry is in the ledger. - if (!ctx.view.exists(keylet::depositPreauth( - account, credentials::makeSorted(ctx.tx.getFieldArray(sfUnauthorizeCredentials))))) + if (!ctx.view.exists( + keylet::depositPreauth( + account, + credentials::makeSorted(ctx.tx.getFieldArray(sfUnauthorizeCredentials))))) return tecNO_ENTRY; } return tesSUCCESS; @@ -140,7 +144,8 @@ DepositPreauth::doApply() // check the starting balance because we want to allow dipping into the // reserve to pay fees. { - STAmount const reserve{view().fees().accountReserve(sleOwner->getFieldU32(sfOwnerCount) + 1)}; + STAmount const reserve{ + view().fees().accountReserve(sleOwner->getFieldU32(sfOwnerCount) + 1)}; if (mPriorBalance < reserve) return tecINSUFFICIENT_RESERVE; @@ -156,10 +161,11 @@ DepositPreauth::doApply() 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(account_), preauthKeylet, describeOwnerDir(account_)); - JLOG(j_.trace()) << "Adding DepositPreauth to owner directory " << to_string(preauthKeylet.key) << ": " - << (page ? "success" : "failure"); + JLOG(j_.trace()) << "Adding DepositPreauth to owner directory " + << to_string(preauthKeylet.key) << ": " << (page ? "success" : "failure"); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE @@ -185,7 +191,8 @@ DepositPreauth::doApply() // check the starting balance because we want to allow dipping into the // reserve to pay fees. { - STAmount const reserve{view().fees().accountReserve(sleOwner->getFieldU32(sfOwnerCount) + 1)}; + STAmount const reserve{ + view().fees().accountReserve(sleOwner->getFieldU32(sfOwnerCount) + 1)}; if (mPriorBalance < reserve) return tecINSUFFICIENT_RESERVE; @@ -194,7 +201,8 @@ DepositPreauth::doApply() // Preclaim already verified that the Preauth entry does not yet exist. // Create and populate the Preauth entry. - auto const sortedTX = credentials::makeSorted(ctx_.tx.getFieldArray(sfAuthorizeCredentials)); + auto const sortedTX = + credentials::makeSorted(ctx_.tx.getFieldArray(sfAuthorizeCredentials)); STArray sortedLE(sfAuthorizeCredentials, sortedTX.size()); for (auto const& p : sortedTX) { @@ -214,10 +222,11 @@ DepositPreauth::doApply() view().insert(slePreauth); - auto const page = view().dirInsert(keylet::ownerDir(account_), preauthKey, describeOwnerDir(account_)); + auto const page = + view().dirInsert(keylet::ownerDir(account_), preauthKey, describeOwnerDir(account_)); - JLOG(j_.trace()) << "Adding DepositPreauth to owner directory " << to_string(preauthKey.key) << ": " - << (page ? "success" : "failure"); + JLOG(j_.trace()) << "Adding DepositPreauth to owner directory " << to_string(preauthKey.key) + << ": " << (page ? "success" : "failure"); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE @@ -229,8 +238,8 @@ DepositPreauth::doApply() } else if (ctx_.tx.isFieldPresent(sfUnauthorizeCredentials)) { - auto const preauthKey = - keylet::depositPreauth(account_, credentials::makeSorted(ctx_.tx.getFieldArray(sfUnauthorizeCredentials))); + auto const preauthKey = keylet::depositPreauth( + account_, credentials::makeSorted(ctx_.tx.getFieldArray(sfUnauthorizeCredentials))); return DepositPreauth::removeFromLedger(view(), preauthKey.key, j_); } diff --git a/src/xrpld/app/tx/detail/Escrow.cpp b/src/libxrpl/tx/transactors/Escrow.cpp similarity index 91% rename from src/xrpld/app/tx/detail/Escrow.cpp rename to src/libxrpl/tx/transactors/Escrow.cpp index 80d1f6c9da..8ea2de24d9 100644 --- a/src/xrpld/app/tx/detail/Escrow.cpp +++ b/src/libxrpl/tx/transactors/Escrow.cpp @@ -1,11 +1,8 @@ -#include -#include -#include -#include -#include - #include #include +#include +#include +#include #include #include #include @@ -14,6 +11,8 @@ #include #include #include +#include +#include namespace xrpl { @@ -108,7 +107,8 @@ EscrowCreate::preflight(PreflightContext const& ctx) return temBAD_AMOUNT; if (auto const ret = std::visit( - [&](T const&) { return escrowCreatePreflightHelper(ctx); }, amount.asset().value()); + [&](T const&) { return escrowCreatePreflightHelper(ctx); }, + amount.asset().value()); !isTesSuccess(ret)) return ret; } @@ -124,7 +124,8 @@ EscrowCreate::preflight(PreflightContext const& ctx) // If both finish and cancel times are specified then the cancel time must // be strictly after the finish time. - if (ctx.tx[~sfCancelAfter] && ctx.tx[~sfFinishAfter] && ctx.tx[sfCancelAfter] <= ctx.tx[sfFinishAfter]) + if (ctx.tx[~sfCancelAfter] && ctx.tx[~sfFinishAfter] && + ctx.tx[sfCancelAfter] <= ctx.tx[sfFinishAfter]) return temBAD_EXPIRATION; // In the absence of a FinishAfter, the escrow can be finished @@ -264,12 +265,14 @@ escrowCreatePreclaimHelper( // If the issuer has requireAuth set, check if the account is // authorized auto const& mptIssue = amount.get(); - if (auto const ter = requireAuth(ctx.view, mptIssue, account, AuthType::WeakAuth); ter != tesSUCCESS) + if (auto const ter = requireAuth(ctx.view, mptIssue, account, AuthType::WeakAuth); + ter != tesSUCCESS) return ter; // If the issuer has requireAuth set, check if the destination is // authorized - if (auto const ter = requireAuth(ctx.view, mptIssue, dest, AuthType::WeakAuth); ter != tesSUCCESS) + if (auto const ter = requireAuth(ctx.view, mptIssue, dest, AuthType::WeakAuth); + ter != tesSUCCESS) return ter; // If the issuer has frozen the account, return tecLOCKED @@ -284,8 +287,8 @@ escrowCreatePreclaimHelper( if (auto const ter = canTransfer(ctx.view, mptIssue, account, dest); ter != tesSUCCESS) return ter; - STAmount const spendableAmount = - accountHolds(ctx.view, account, amount.get(), fhIGNORE_FREEZE, ahIGNORE_AUTH, ctx.j); + STAmount const spendableAmount = accountHolds( + ctx.view, account, amount.get(), fhIGNORE_FREEZE, ahIGNORE_AUTH, ctx.j); // If the balance is less than or equal to 0, return tecINSUFFICIENT_FUNDS if (spendableAmount <= beast::zero) @@ -323,7 +326,9 @@ EscrowCreate::preclaim(PreclaimContext const& ctx) return temDISABLED; // LCOV_EXCL_LINE if (auto const ret = std::visit( - [&](T const&) { return escrowCreatePreclaimHelper(ctx, account, dest, amount); }, + [&](T const&) { + return escrowCreatePreclaimHelper(ctx, account, dest, amount); + }, amount.asset().value()); !isTesSuccess(ret)) return ret; @@ -353,7 +358,8 @@ escrowLockApplyHelper( if (issuer == sender) return tecINTERNAL; // LCOV_EXCL_LINE - auto const ter = rippleCredit(view, sender, issuer, amount, amount.holds() ? false : true, journal); + auto const ter = rippleCredit( + view, sender, issuer, amount, amount.holds() ? false : true, journal); if (ter != tesSUCCESS) return ter; // LCOV_EXCL_LINE return tesSUCCESS; @@ -446,7 +452,8 @@ EscrowCreate::doApply() // Add escrow to sender's owner directory { - auto page = ctx_.view().dirInsert(keylet::ownerDir(account_), escrowKeylet, describeOwnerDir(account_)); + auto page = ctx_.view().dirInsert( + keylet::ownerDir(account_), escrowKeylet, describeOwnerDir(account_)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE (*slep)[sfOwnerNode] = *page; @@ -456,7 +463,8 @@ EscrowCreate::doApply() AccountID const dest = ctx_.tx[sfDestination]; if (dest != account_) { - auto page = ctx_.view().dirInsert(keylet::ownerDir(dest), escrowKeylet, describeOwnerDir(dest)); + auto page = + ctx_.view().dirInsert(keylet::ownerDir(dest), escrowKeylet, describeOwnerDir(dest)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE (*slep)[sfDestinationNode] = *page; @@ -468,7 +476,8 @@ EscrowCreate::doApply() AccountID const issuer = amount.getIssuer(); if (!isXRP(amount) && issuer != account_ && issuer != dest && !amount.holds()) { - auto page = ctx_.view().dirInsert(keylet::ownerDir(issuer), escrowKeylet, describeOwnerDir(issuer)); + auto page = + ctx_.view().dirInsert(keylet::ownerDir(issuer), escrowKeylet, describeOwnerDir(issuer)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE (*slep)[sfIssuerNode] = *page; @@ -544,7 +553,7 @@ EscrowFinish::preflightSigValidated(PreflightContext const& ctx) if (cb && fb) { - auto& router = ctx.app.getHashRouter(); + auto& router = ctx.registry.getHashRouter(); auto const id = ctx.tx.getTransactionID(); auto const flags = router.getFlags(id); @@ -582,11 +591,17 @@ EscrowFinish::calculateBaseFee(ReadView const& view, STTx const& tx) template static TER -escrowFinishPreclaimHelper(PreclaimContext const& ctx, AccountID const& dest, STAmount const& amount); +escrowFinishPreclaimHelper( + PreclaimContext const& ctx, + AccountID const& dest, + STAmount const& amount); template <> TER -escrowFinishPreclaimHelper(PreclaimContext const& ctx, AccountID const& dest, STAmount const& amount) +escrowFinishPreclaimHelper( + PreclaimContext const& ctx, + AccountID const& dest, + STAmount const& amount) { AccountID issuer = amount.getIssuer(); // If the issuer is the same as the account, return tesSUCCESS @@ -606,7 +621,10 @@ escrowFinishPreclaimHelper(PreclaimContext const& ctx, AccountID const& d template <> TER -escrowFinishPreclaimHelper(PreclaimContext const& ctx, AccountID const& dest, STAmount const& amount) +escrowFinishPreclaimHelper( + PreclaimContext const& ctx, + AccountID const& dest, + STAmount const& amount) { AccountID issuer = amount.getIssuer(); // If the issuer is the same as the dest, return tesSUCCESS @@ -622,7 +640,8 @@ escrowFinishPreclaimHelper(PreclaimContext const& ctx, AccountID const // If the issuer has requireAuth set, check if the destination is // authorized auto const& mptIssue = amount.get(); - if (auto const ter = requireAuth(ctx.view, mptIssue, dest, AuthType::WeakAuth); ter != tesSUCCESS) + if (auto const ter = requireAuth(ctx.view, mptIssue, dest, AuthType::WeakAuth); + ter != tesSUCCESS) return ter; // If the issuer has frozen the destination, return tecLOCKED @@ -637,7 +656,8 @@ EscrowFinish::preclaim(PreclaimContext const& ctx) { if (ctx.view.rules().enabled(featureCredentials)) { - if (auto const err = credentials::valid(ctx.tx, ctx.view, ctx.tx[sfAccount], ctx.j); !isTesSuccess(err)) + if (auto const err = credentials::valid(ctx.tx, ctx.view, ctx.tx[sfAccount], ctx.j); + !isTesSuccess(err)) return err; } @@ -654,7 +674,9 @@ EscrowFinish::preclaim(PreclaimContext const& ctx) if (!isXRP(amount)) { if (auto const ret = std::visit( - [&](T const&) { return escrowFinishPreclaimHelper(ctx, dest, amount); }, + [&](T const&) { + return escrowFinishPreclaimHelper(ctx, dest, amount); + }, amount.asset().value()); !isTesSuccess(ret)) return ret; @@ -781,7 +803,8 @@ escrowUnlockApplyHelper( // if the issuer is the high, then we use the low limit // otherwise we use the high limit - STAmount const lineLimit = sleRippleState->getFieldAmount(issuerHigh ? sfLowLimit : sfHighLimit); + STAmount const lineLimit = + sleRippleState->getFieldAmount(issuerHigh ? sfLowLimit : sfHighLimit); STAmount lineBalance = sleRippleState->getFieldAmount(sfBalance); @@ -834,7 +857,8 @@ escrowUnlockApplyHelper( return tecINSUFFICIENT_RESERVE; } - if (auto const ter = MPTokenAuthorize::createMPToken(view, mptID, receiver, 0); !isTesSuccess(ter)) + if (auto const ter = MPTokenAuthorize::createMPToken(view, mptID, receiver, 0); + !isTesSuccess(ter)) { return ter; // LCOV_EXCL_LINE } @@ -869,7 +893,12 @@ escrowUnlockApplyHelper( finalAmt = amount.value() - xferFee; } return rippleUnlockEscrowMPT( - view, sender, receiver, finalAmt, view.rules().enabled(fixTokenEscrowV1) ? amount : finalAmt, journal); + view, + sender, + receiver, + finalAmt, + view.rules().enabled(fixTokenEscrowV1) ? amount : finalAmt, + journal); } TER @@ -900,7 +929,7 @@ EscrowFinish::doApply() // Check cryptocondition fulfillment { auto const id = ctx_.tx.getTransactionID(); - auto flags = ctx_.app.getHashRouter().getFlags(id); + auto flags = ctx_.registry.getHashRouter().getFlags(id); auto const cb = ctx_.tx[~sfCondition]; @@ -920,7 +949,7 @@ EscrowFinish::doApply() else flags = SF_CF_INVALID; - ctx_.app.getHashRouter().setFlags(id, flags); + ctx_.registry.getHashRouter().setFlags(id, flags); // LCOV_EXCL_STOP } @@ -952,7 +981,8 @@ EscrowFinish::doApply() if (!sled) return tecNO_DST; - if (auto err = verifyDepositPreauth(ctx_.tx, ctx_.view(), account_, destID, sled, ctx_.journal); !isTesSuccess(err)) + if (auto err = verifyDepositPreauth(ctx_.tx, ctx_.view(), account_, destID, sled, ctx_.journal); + !isTesSuccess(err)) return err; AccountID const account = (*slep)[sfAccount]; @@ -990,14 +1020,24 @@ EscrowFinish::doApply() if (!ctx_.view().rules().enabled(featureTokenEscrow)) return temDISABLED; // LCOV_EXCL_LINE - Rate lockedRate = - slep->isFieldPresent(sfTransferRate) ? xrpl::Rate(slep->getFieldU32(sfTransferRate)) : parityRate; + Rate lockedRate = slep->isFieldPresent(sfTransferRate) + ? xrpl::Rate(slep->getFieldU32(sfTransferRate)) + : parityRate; auto const issuer = amount.getIssuer(); bool const createAsset = destID == account_; if (auto const ret = std::visit( [&](T const&) { return escrowUnlockApplyHelper( - ctx_.view(), lockedRate, sled, mPriorBalance, amount, issuer, account, destID, createAsset, j_); + ctx_.view(), + lockedRate, + sled, + mPriorBalance, + amount, + issuer, + account, + destID, + createAsset, + j_); }, amount.asset().value()); !isTesSuccess(ret)) @@ -1038,11 +1078,17 @@ EscrowCancel::preflight(PreflightContext const& ctx) template static TER -escrowCancelPreclaimHelper(PreclaimContext const& ctx, AccountID const& account, STAmount const& amount); +escrowCancelPreclaimHelper( + PreclaimContext const& ctx, + AccountID const& account, + STAmount const& amount); template <> TER -escrowCancelPreclaimHelper(PreclaimContext const& ctx, AccountID const& account, STAmount const& amount) +escrowCancelPreclaimHelper( + PreclaimContext const& ctx, + AccountID const& account, + STAmount const& amount) { AccountID issuer = amount.getIssuer(); // If the issuer is the same as the account, return tecINTERNAL @@ -1058,7 +1104,10 @@ escrowCancelPreclaimHelper(PreclaimContext const& ctx, AccountID const& a template <> TER -escrowCancelPreclaimHelper(PreclaimContext const& ctx, AccountID const& account, STAmount const& amount) +escrowCancelPreclaimHelper( + PreclaimContext const& ctx, + AccountID const& account, + STAmount const& amount) { AccountID issuer = amount.getIssuer(); // If the issuer is the same as the account, return tecINTERNAL @@ -1074,7 +1123,8 @@ escrowCancelPreclaimHelper(PreclaimContext const& ctx, AccountID const // If the issuer has requireAuth set, check if the account is // authorized auto const& mptIssue = amount.get(); - if (auto const ter = requireAuth(ctx.view, mptIssue, account, AuthType::WeakAuth); ter != tesSUCCESS) + if (auto const ter = requireAuth(ctx.view, mptIssue, account, AuthType::WeakAuth); + ter != tesSUCCESS) return ter; return tesSUCCESS; @@ -1096,7 +1146,9 @@ EscrowCancel::preclaim(PreclaimContext const& ctx) if (!isXRP(amount)) { if (auto const ret = std::visit( - [&](T const&) { return escrowCancelPreclaimHelper(ctx, account, amount); }, + [&](T const&) { + return escrowCancelPreclaimHelper(ctx, account, amount); + }, amount.asset().value()); !isTesSuccess(ret)) return ret; diff --git a/src/xrpld/app/tx/detail/LedgerStateFix.cpp b/src/libxrpl/tx/transactors/LedgerStateFix.cpp similarity index 94% rename from src/xrpld/app/tx/detail/LedgerStateFix.cpp rename to src/libxrpl/tx/transactors/LedgerStateFix.cpp index 43001e2fbf..28028b6f2b 100644 --- a/src/xrpld/app/tx/detail/LedgerStateFix.cpp +++ b/src/libxrpl/tx/transactors/LedgerStateFix.cpp @@ -1,10 +1,9 @@ -#include -#include - #include #include #include #include +#include +#include namespace xrpl { diff --git a/src/xrpld/app/misc/detail/LendingHelpers.cpp b/src/libxrpl/tx/transactors/Lending/LendingHelpers.cpp similarity index 88% rename from src/xrpld/app/misc/detail/LendingHelpers.cpp rename to src/libxrpl/tx/transactors/Lending/LendingHelpers.cpp index 106eeb9301..b0626b4650 100644 --- a/src/xrpld/app/misc/detail/LendingHelpers.cpp +++ b/src/libxrpl/tx/transactors/Lending/LendingHelpers.cpp @@ -1,6 +1,6 @@ -#include +#include // DO NOT REMOVE forces header file include to sort first -#include +#include namespace xrpl { @@ -60,7 +60,8 @@ loanPeriodicRate(TenthBips32 interestRate, std::uint32_t paymentInterval) bool isRounded(Asset const& asset, Number const& value, std::int32_t scale) { - return roundToAsset(asset, value, scale, Number::downward) == roundToAsset(asset, value, scale, Number::upward); + return roundToAsset(asset, value, scale, Number::downward) == + roundToAsset(asset, value, scale, Number::upward); } namespace detail { @@ -112,7 +113,10 @@ computePaymentFactor(Number const& periodicRate, std::uint32_t paymentsRemaining * Equation (7) from XLS-66 spec, Section A-2 Equation Glossary */ Number -loanPeriodicPayment(Number const& principalOutstanding, Number const& periodicRate, std::uint32_t paymentsRemaining) +loanPeriodicPayment( + Number const& principalOutstanding, + Number const& periodicRate, + std::uint32_t paymentsRemaining) { if (principalOutstanding == 0 || paymentsRemaining == 0) return 0; @@ -261,7 +265,9 @@ doPayment( "xrpl::detail::doPayment", "Full principal payment"); XRPL_ASSERT_PARTS( - totalValueOutstandingProxy == payment.trackedValueDelta, "xrpl::detail::doPayment", "Full value payment"); + totalValueOutstandingProxy == payment.trackedValueDelta, + "xrpl::detail::doPayment", + "Full value payment"); XRPL_ASSERT_PARTS( managementFeeOutstandingProxy == payment.trackedManagementFeeDelta, "xrpl::detail::doPayment", @@ -299,7 +305,9 @@ doPayment( "xrpl::detail::doPayment", "Partial principal payment"); XRPL_ASSERT_PARTS( - totalValueOutstandingProxy > payment.trackedValueDelta, "xrpl::detail::doPayment", "Partial value payment"); + totalValueOutstandingProxy > payment.trackedValueDelta, + "xrpl::detail::doPayment", + "Partial value payment"); // Management fees are expected to be relatively small, and could get to // zero before the loan is paid off XRPL_ASSERT_PARTS( @@ -317,7 +325,8 @@ doPayment( XRPL_ASSERT_PARTS( // Use an explicit cast because the template parameter can be // ValueProxy or Number - static_cast(principalOutstandingProxy) <= static_cast(totalValueOutstandingProxy), + static_cast(principalOutstandingProxy) <= + static_cast(totalValueOutstandingProxy), "xrpl::detail::doPayment", "principal does not exceed total"); @@ -328,23 +337,24 @@ doPayment( "xrpl::detail::doPayment", "fee outstanding stays valid"); - return LoanPaymentParts{// Principal paid is straightforward - it's the tracked delta - .principalPaid = payment.trackedPrincipalDelta, + return LoanPaymentParts{ + // Principal paid is straightforward - it's the tracked delta + .principalPaid = payment.trackedPrincipalDelta, - // Interest paid combines: - // 1. Tracked interest from the amortization schedule - // (derived from the tracked deltas) - // 2. Untracked interest (e.g., late payment penalties) - .interestPaid = payment.trackedInterestPart() + payment.untrackedInterest, + // Interest paid combines: + // 1. Tracked interest from the amortization schedule + // (derived from the tracked deltas) + // 2. Untracked interest (e.g., late payment penalties) + .interestPaid = payment.trackedInterestPart() + payment.untrackedInterest, - // Value change represents how the loan's total value changed beyond - // normal amortization. - .valueChange = payment.untrackedInterest, + // Value change represents how the loan's total value changed beyond + // normal amortization. + .valueChange = payment.untrackedInterest, - // Fee paid combines: - // 1. Tracked management fees from the amortization schedule - // 2. Untracked fees (e.g., late payment fees, service fees) - .feePaid = payment.trackedManagementFeeDelta + payment.untrackedManagementFee}; + // Fee paid combines: + // 1. Tracked management fees from the amortization schedule + // 2. Untracked fees (e.g., late payment fees, service fees) + .feePaid = payment.trackedManagementFeeDelta + payment.untrackedManagementFee}; } /* Simulates an overpayment to validate it won't break the loan's amortization. @@ -370,8 +380,8 @@ tryOverpayment( beast::Journal j) { // Calculate what the loan state SHOULD be theoretically (at full precision) - auto const theoreticalState = - computeTheoreticalLoanState(periodicPayment, periodicRate, paymentRemaining, managementFeeRate); + auto const theoreticalState = computeTheoreticalLoanState( + periodicPayment, periodicRate, paymentRemaining, managementFeeRate); // Calculate the accumulated rounding errors. These need to be preserved // across the re-amortization to maintain consistency with the loan's @@ -381,14 +391,20 @@ tryOverpayment( // Compute the new principal by applying the overpayment to the theoretical // principal. Use max with 0 to ensure we never go negative. - auto const newTheoreticalPrincipal = - std::max(theoreticalState.principalOutstanding - overpaymentComponents.trackedPrincipalDelta, Number{0}); + auto const newTheoreticalPrincipal = std::max( + theoreticalState.principalOutstanding - overpaymentComponents.trackedPrincipalDelta, + Number{0}); // Compute new loan properties based on the reduced principal. This // recalculates the periodic payment, total value, and management fees // for the remaining payment schedule. auto newLoanProperties = computeLoanProperties( - asset, newTheoreticalPrincipal, periodicRate, paymentRemaining, managementFeeRate, loanScale); + asset, + newTheoreticalPrincipal, + periodicRate, + paymentRemaining, + managementFeeRate, + loanScale); JLOG(j.debug()) << "new periodic payment: " << newLoanProperties.periodicPayment << ", new total value: " << newLoanProperties.loanState.valueOutstanding @@ -414,7 +430,10 @@ tryOverpayment( roundedOldState.principalOutstanding); auto const totalValueOutstanding = std::clamp( roundToAsset( - asset, principalOutstanding + newTheoreticalState.interestOutstanding(), loanScale, Number::upward), + asset, + principalOutstanding + newTheoreticalState.interestOutstanding(), + loanScale, + Number::upward), numZero, roundedOldState.valueOutstanding); auto const managementFeeOutstanding = std::clamp( @@ -454,7 +473,8 @@ tryOverpayment( // Validate that all computed properties are reasonable. These checks should // never fail under normal circumstances, but we validate defensively. - if (newLoanProperties.periodicPayment <= 0 || newLoanProperties.loanState.valueOutstanding <= 0 || + if (newLoanProperties.periodicPayment <= 0 || + newLoanProperties.loanState.valueOutstanding <= 0 || newLoanProperties.loanState.managementFeeDue < 0) { // LCOV_EXCL_START @@ -463,7 +483,8 @@ tryOverpayment( "not compute. TotalValueOutstanding: " << newLoanProperties.loanState.valueOutstanding << ", PeriodicPayment : " << newLoanProperties.periodicPayment - << ", ManagementFeeOwedToBroker: " << newLoanProperties.loanState.managementFeeDue; + << ", ManagementFeeOwedToBroker: " + << newLoanProperties.loanState.managementFeeDue; return Unexpected(tesSUCCESS); // LCOV_EXCL_STOP } @@ -504,7 +525,8 @@ tryOverpayment( .valueChange = valueChange + overpaymentComponents.untrackedInterest, // Fee paid includes both the reduction in tracked management fees // and any untracked fees on the overpayment itself - .feePaid = overpaymentComponents.untrackedManagementFee + overpaymentComponents.trackedManagementFeeDelta, + .feePaid = overpaymentComponents.untrackedManagementFee + + overpaymentComponents.trackedManagementFeeDelta, }, newLoanProperties); } @@ -535,8 +557,8 @@ doOverpayment( TenthBips16 const managementFeeRate, beast::Journal j) { - auto const loanState = - constructLoanState(totalValueOutstandingProxy, principalOutstandingProxy, managementFeeOutstandingProxy); + auto const loanState = constructLoanState( + totalValueOutstandingProxy, principalOutstandingProxy, managementFeeOutstandingProxy); auto const periodicPayment = periodicPaymentProxy; JLOG(j.debug()) << "overpayment components:" << ", totalValue before: " << *totalValueOutstandingProxy @@ -545,7 +567,8 @@ doOverpayment( << ", managementFeeDelta: " << overpaymentComponents.trackedManagementFeeDelta << ", interestPart: " << overpaymentComponents.trackedInterestPart() << ", untrackedInterest: " << overpaymentComponents.untrackedInterest - << ", totalDue: " << overpaymentComponents.totalDue << ", payments remaining :" << paymentRemaining; + << ", totalDue: " << overpaymentComponents.totalDue + << ", payments remaining :" << paymentRemaining; // Attempt to re-amortize the loan with the overpayment applied. // This modifies the temporary copies, leaving the proxies unchanged. @@ -594,9 +617,11 @@ doOverpayment( JLOG(j.debug()) << "valueChange: " << loanPaymentParts.valueChange << ", totalValue before: " << *totalValueOutstandingProxy << ", totalValue after: " << newRoundedLoanState.valueOutstanding - << ", totalValue delta: " << (totalValueOutstandingProxy - newRoundedLoanState.valueOutstanding) + << ", totalValue delta: " + << (totalValueOutstandingProxy - newRoundedLoanState.valueOutstanding) << ", principalDelta: " << overpaymentComponents.trackedPrincipalDelta - << ", principalPaid: " << loanPaymentParts.principalPaid << ", Computed difference: " + << ", principalPaid: " << loanPaymentParts.principalPaid + << ", Computed difference: " << overpaymentComponents.trackedPrincipalDelta - (totalValueOutstandingProxy - newRoundedLoanState.valueOutstanding); @@ -656,8 +681,8 @@ computeLatePayment( return Unexpected(tecTOO_SOON); // Calculate the penalty interest based on how long the payment is overdue. - auto const latePaymentInterest = - loanLatePaymentInterest(principalOutstanding, lateInterestRate, view.parentCloseTime(), nextDueDate); + auto const latePaymentInterest = loanLatePaymentInterest( + principalOutstanding, lateInterestRate, view.parentCloseTime(), nextDueDate); // Round the late interest and split it between the vault (net interest) // and the broker (management fee portion). This lambda ensures we @@ -694,14 +719,17 @@ computeLatePayment( periodic.untrackedInterest + roundedLateInterest}; XRPL_ASSERT_PARTS( - isRounded(asset, late.totalDue, loanScale), "xrpl::detail::computeLatePayment", "total due is rounded"); + isRounded(asset, late.totalDue, loanScale), + "xrpl::detail::computeLatePayment", + "total due is rounded"); // Check that the borrower provided enough funds to cover the late payment. // The late payment is more expensive than a regular payment due to the // penalties. if (amount < late.totalDue) { - JLOG(j.warn()) << "Late loan payment amount is insufficient. Due: " << late.totalDue << ", paid: " << amount; + JLOG(j.warn()) << "Late loan payment amount is insufficient. Due: " << late.totalDue + << ", paid: " << amount; return Unexpected(tecINSUFFICIENT_PAYMENT); } @@ -784,7 +812,8 @@ computeFullPayment( // Pay off all tracked outstanding balances: principal, interest, // and fees. // This marks the loan as complete (final payment). - .trackedValueDelta = principalOutstanding + totalInterestOutstanding + managementFeeOutstanding, + .trackedValueDelta = + principalOutstanding + totalInterestOutstanding + managementFeeOutstanding, .trackedPrincipalDelta = principalOutstanding, // All outstanding management fees are paid. This zeroes out the @@ -813,10 +842,13 @@ computeFullPayment( }; XRPL_ASSERT_PARTS( - isRounded(asset, full.totalDue, loanScale), "xrpl::detail::computeFullPayment", "total due is rounded"); + isRounded(asset, full.totalDue, loanScale), + "xrpl::detail::computeFullPayment", + "total due is rounded"); JLOG(j.trace()) << "computeFullPayment result: periodicPayment: " << periodicPayment - << ", periodicRate: " << periodicRate << ", paymentRemaining: " << paymentRemaining + << ", periodicRate: " << periodicRate + << ", paymentRemaining: " << paymentRemaining << ", theoreticalPrincipalOutstanding: " << theoreticalPrincipalOutstanding << ", fullPaymentInterest: " << fullPaymentInterest << ", roundedFullInterest: " << roundedFullInterest @@ -868,11 +900,13 @@ computePaymentComponents( TenthBips16 managementFeeRate) { XRPL_ASSERT_PARTS( - isRounded(asset, totalValueOutstanding, scale) && isRounded(asset, principalOutstanding, scale) && + isRounded(asset, totalValueOutstanding, scale) && + isRounded(asset, principalOutstanding, scale) && isRounded(asset, managementFeeOutstanding, scale), "xrpl::detail::computePaymentComponents", "Outstanding values are rounded"); - XRPL_ASSERT_PARTS(paymentRemaining > 0, "xrpl::detail::computePaymentComponents", "some payments remaining"); + XRPL_ASSERT_PARTS( + paymentRemaining > 0, "xrpl::detail::computePaymentComponents", "some payments remaining"); auto const roundedPeriodicPayment = roundPeriodicPayment(asset, periodicPayment, scale); @@ -891,8 +925,8 @@ computePaymentComponents( // Calculate what the loan state SHOULD be after this payment (the target). // This is computed at full precision using the theoretical amortization. - LoanState const trueTarget = - computeTheoreticalLoanState(periodicPayment, periodicRate, paymentRemaining - 1, managementFeeRate); + LoanState const trueTarget = computeTheoreticalLoanState( + periodicPayment, periodicRate, paymentRemaining - 1, managementFeeRate); // Round the target to the loan's scale to match how actual loan values // are stored. @@ -958,7 +992,8 @@ computePaymentComponents( component -= part; excess -= part; } - XRPL_ASSERT_PARTS(excess >= beast::zero, "xrpl::detail::computePaymentComponents", "excess non-negative"); + XRPL_ASSERT_PARTS( + excess >= beast::zero, "xrpl::detail::computePaymentComponents", "excess non-negative"); }; // Helper to reduce deltas when they collectively exceed a limit. // Order matters: we prefer to reduce interest first (most flexible), @@ -988,7 +1023,9 @@ computePaymentComponents( Number shortage = roundedPeriodicPayment - deltas.total(); XRPL_ASSERT_PARTS( - isRounded(asset, shortage, scale), "xrpl::detail::computePaymentComponents", "shortage is rounded"); + isRounded(asset, shortage, scale), + "xrpl::detail::computePaymentComponents", + "shortage is rounded"); if (shortage < beast::zero) { @@ -1001,7 +1038,8 @@ computePaymentComponents( // At this point, shortage >= 0 means we're paying less than the full // periodic payment (due to rounding or component caps). // shortage < 0 would mean we're trying to pay more than allowed (bug). - XRPL_ASSERT_PARTS(shortage >= beast::zero, "xrpl::detail::computePaymentComponents", "no shortage or excess"); + XRPL_ASSERT_PARTS( + shortage >= beast::zero, "xrpl::detail::computePaymentComponents", "no shortage or excess"); // Final validation that all components are valid XRPL_ASSERT_PARTS( @@ -1010,7 +1048,8 @@ computePaymentComponents( "total value adds up"); XRPL_ASSERT_PARTS( - deltas.principal >= beast::zero && deltas.principal <= currentLedgerState.principalOutstanding, + deltas.principal >= beast::zero && + deltas.principal <= currentLedgerState.principalOutstanding, "xrpl::detail::computePaymentComponents", "valid principal result"); XRPL_ASSERT_PARTS( @@ -1018,7 +1057,8 @@ computePaymentComponents( "xrpl::detail::computePaymentComponents", "valid interest result"); XRPL_ASSERT_PARTS( - deltas.managementFee >= beast::zero && deltas.managementFee <= currentLedgerState.managementFeeDue, + deltas.managementFee >= beast::zero && + deltas.managementFee <= currentLedgerState.managementFeeDue, "xrpl::detail::computePaymentComponents", "valid fee result"); @@ -1029,9 +1069,12 @@ computePaymentComponents( // Final safety clamp to ensure no value exceeds its outstanding balance return PaymentComponents{ - .trackedValueDelta = std::clamp(deltas.total(), numZero, currentLedgerState.valueOutstanding), - .trackedPrincipalDelta = std::clamp(deltas.principal, numZero, currentLedgerState.principalOutstanding), - .trackedManagementFeeDelta = std::clamp(deltas.managementFee, numZero, currentLedgerState.managementFeeDue), + .trackedValueDelta = + std::clamp(deltas.total(), numZero, currentLedgerState.valueOutstanding), + .trackedPrincipalDelta = + std::clamp(deltas.principal, numZero, currentLedgerState.principalOutstanding), + .trackedManagementFeeDelta = + std::clamp(deltas.managementFee, numZero, currentLedgerState.managementFeeDue), }; } @@ -1070,14 +1113,16 @@ computeOverpaymentComponents( // First, deduct the fixed overpayment fee from the total amount. // This reduces the effective payment that will be applied to the loan. // Equation (22) from XLS-66 spec, Section A-2 Equation Glossary - Number const overpaymentFee = roundToAsset(asset, tenthBipsOfValue(overpayment, overpaymentFeeRate), loanScale); + Number const overpaymentFee = + roundToAsset(asset, tenthBipsOfValue(overpayment, overpaymentFeeRate), loanScale); // Calculate the penalty interest on the effective payment amount. // This interest doesn't follow the normal amortization schedule - it's // a one-time charge for paying early. // Equation (20) and (21) from XLS-66 spec, Section A-2 Equation Glossary auto const [roundedOverpaymentInterest, roundedOverpaymentManagementFee] = [&]() { - auto const interest = roundToAsset(asset, tenthBipsOfValue(overpayment, overpaymentInterestRate), loanScale); + auto const interest = + roundToAsset(asset, tenthBipsOfValue(overpayment, overpaymentInterestRate), loanScale); return detail::computeInterestAndFeeParts(asset, interest, managementFeeRate, loanScale); }(); @@ -1087,8 +1132,8 @@ computeOverpaymentComponents( // reduction. detail::PaymentComponents{ .trackedValueDelta = overpayment - overpaymentFee, - .trackedPrincipalDelta = - overpayment - roundedOverpaymentInterest - roundedOverpaymentManagementFee - overpaymentFee, + .trackedPrincipalDelta = overpayment - roundedOverpaymentInterest - + roundedOverpaymentManagementFee - overpaymentFee, .trackedManagementFeeDelta = roundedOverpaymentManagementFee, .specialCase = detail::PaymentSpecialCase::extra}, // Untracked management fee is the fixed overpayment fee @@ -1155,7 +1200,8 @@ checkLoanGuards( LoanProperties const& properties, beast::Journal j) { - auto const totalInterestOutstanding = properties.loanState.valueOutstanding - principalRequested; + auto const totalInterestOutstanding = + properties.loanState.valueOutstanding - principalRequested; // Guard 1: if there is no computed total interest over the life of the // loan for a non-zero interest rate, we cannot properly amortize the // loan @@ -1192,10 +1238,12 @@ checkLoanGuards( // Guard 3: If the periodic payment is so small that it can't even be // rounded to a representable value, then the loan can't be paid. Also, // avoids dividing by 0. - auto const roundedPayment = roundPeriodicPayment(vaultAsset, properties.periodicPayment, properties.loanScale); + auto const roundedPayment = + roundPeriodicPayment(vaultAsset, properties.periodicPayment, properties.loanScale); if (roundedPayment == beast::zero) { - JLOG(j.warn()) << "Loan Periodic payment (" << properties.periodicPayment << ") rounds to 0. "; + JLOG(j.warn()) << "Loan Periodic payment (" << properties.periodicPayment + << ") rounds to 0. "; return tecPRECISION_LOSS; } @@ -1205,11 +1253,13 @@ checkLoanGuards( { NumberRoundModeGuard mg(Number::upward); - if (std::int64_t const computedPayments{properties.loanState.valueOutstanding / roundedPayment}; + if (std::int64_t const computedPayments{ + properties.loanState.valueOutstanding / roundedPayment}; computedPayments != paymentTotal) { - JLOG(j.warn()) << "Loan Periodic payment (" << properties.periodicPayment << ") rounding (" - << roundedPayment << ") on a total value of " << properties.loanState.valueOutstanding + JLOG(j.warn()) << "Loan Periodic payment (" << properties.periodicPayment + << ") rounding (" << roundedPayment << ") on a total value of " + << properties.loanState.valueOutstanding << " can not complete the loan in the specified " "number of payments (" << computedPayments << " != " << paymentTotal << ")"; @@ -1236,7 +1286,12 @@ computeFullPaymentInterest( TenthBips32 closeInterestRate) { auto const accruedInterest = detail::loanAccruedInterest( - theoreticalPrincipalOutstanding, periodicRate, parentCloseTime, startDate, prevPaymentDate, paymentInterval); + theoreticalPrincipalOutstanding, + periodicRate, + parentCloseTime, + startDate, + prevPaymentDate, + paymentInterval); XRPL_ASSERT( accruedInterest >= 0, "xrpl::detail::computeFullPaymentInterest : valid accrued " @@ -1287,7 +1342,11 @@ computeTheoreticalLoanState( { if (paymentRemaining == 0) { - return LoanState{.valueOutstanding = 0, .principalOutstanding = 0, .interestDue = 0, .managementFeeDue = 0}; + return LoanState{ + .valueOutstanding = 0, + .principalOutstanding = 0, + .interestDue = 0, + .managementFeeDue = 0}; } // Equation (30) from XLS-66 spec, Section A-2 Equation Glossary @@ -1300,7 +1359,8 @@ computeTheoreticalLoanState( Number const interestOutstandingGross = totalValueOutstanding - principalOutstanding; // Equation (32) from XLS-66 spec, Section A-2 Equation Glossary - Number const managementFeeOutstanding = tenthBipsOfValue(interestOutstandingGross, managementFeeRate); + Number const managementFeeOutstanding = + tenthBipsOfValue(interestOutstandingGross, managementFeeRate); // Equation (33) from XLS-66 spec, Section A-2 Equation Glossary Number const interestOutstandingNet = interestOutstandingGross - managementFeeOutstanding; @@ -1352,7 +1412,9 @@ LoanState constructRoundedLoanState(SLE::const_ref loan) { return constructLoanState( - loan->at(sfTotalValueOutstanding), loan->at(sfPrincipalOutstanding), loan->at(sfManagementFeeOutstanding)); + loan->at(sfTotalValueOutstanding), + loan->at(sfPrincipalOutstanding), + loan->at(sfManagementFeeOutstanding)); } /* @@ -1362,7 +1424,11 @@ constructRoundedLoanState(SLE::const_ref loan) * Equation (32) from XLS-66 spec, Section A-2 Equation Glossary */ Number -computeManagementFee(Asset const& asset, Number const& value, TenthBips32 managementFeeRate, std::int32_t scale) +computeManagementFee( + Asset const& asset, + Number const& value, + TenthBips32 managementFeeRate, + std::int32_t scale) { return roundToAsset(asset, tenthBipsOfValue(value, managementFeeRate), scale, Number::downward); } @@ -1388,7 +1454,12 @@ computeLoanProperties( auto const periodicRate = loanPeriodicRate(interestRate, paymentInterval); XRPL_ASSERT(interestRate == 0 || periodicRate > 0, "xrpl::computeLoanProperties : valid rate"); return computeLoanProperties( - asset, principalOutstanding, periodicRate, paymentsRemaining, managementFeeRate, minimumScale); + asset, + principalOutstanding, + periodicRate, + paymentsRemaining, + managementFeeRate, + minimumScale); } /* @@ -1408,7 +1479,8 @@ computeLoanProperties( TenthBips32 managementFeeRate, std::int32_t minimumScale) { - auto const periodicPayment = detail::loanPeriodicPayment(principalOutstanding, periodicRate, paymentsRemaining); + auto const periodicPayment = + detail::loanPeriodicPayment(principalOutstanding, periodicRate, paymentsRemaining); auto const [totalValueOutstanding, loanScale] = [&]() { // only round up if there should be interest @@ -1440,11 +1512,13 @@ computeLoanProperties( // Since we just figured out the loan scale, we haven't been able to // validate that the principal fits in it, so to allow this function to // succeed, round it here, and let the caller do the validation. - auto const roundedPrincipalOutstanding = roundToAsset(asset, principalOutstanding, loanScale, Number::to_nearest); + auto const roundedPrincipalOutstanding = + roundToAsset(asset, principalOutstanding, loanScale, Number::to_nearest); // Equation (31) from XLS-66 spec, Section A-2 Equation Glossary auto const totalInterestOutstanding = totalValueOutstanding - roundedPrincipalOutstanding; - auto const feeOwedToBroker = computeManagementFee(asset, totalInterestOutstanding, managementFeeRate, loanScale); + auto const feeOwedToBroker = + computeManagementFee(asset, totalInterestOutstanding, managementFeeRate, loanScale); // Compute the principal part of the first payment. This is needed // because the principal part may be rounded down to zero, which @@ -1452,11 +1526,11 @@ computeLoanProperties( auto const firstPaymentPrincipal = [&]() { // Compute the parts for the first payment. Ensure that the // principal payment will actually change the principal. - auto const startingState = - computeTheoreticalLoanState(periodicPayment, periodicRate, paymentsRemaining, managementFeeRate); + auto const startingState = computeTheoreticalLoanState( + periodicPayment, periodicRate, paymentsRemaining, managementFeeRate); - auto const firstPaymentState = - computeTheoreticalLoanState(periodicPayment, periodicRate, paymentsRemaining - 1, managementFeeRate); + auto const firstPaymentState = computeTheoreticalLoanState( + periodicPayment, periodicRate, paymentsRemaining - 1, managementFeeRate); // The unrounded principal part needs to be large enough to affect // the principal. What to do if not is left to the caller @@ -1465,7 +1539,8 @@ computeLoanProperties( return LoanProperties{ .periodicPayment = periodicPayment, - .loanState = constructLoanState(totalValueOutstanding, roundedPrincipalOutstanding, feeOwedToBroker), + .loanState = + constructLoanState(totalValueOutstanding, roundedPrincipalOutstanding, feeOwedToBroker), .loanScale = loanScale, .firstPaymentPrincipal = firstPaymentPrincipal, }; @@ -1557,8 +1632,8 @@ loanMakePayment( TenthBips32 const closeInterestRate{loan->at(sfCloseInterestRate)}; Number const closePaymentFee = roundToAsset(asset, loan->at(sfClosePaymentFee), loanScale); - LoanState const roundedLoanState = - constructLoanState(totalValueOutstandingProxy, principalOutstandingProxy, managementFeeOutstandingProxy); + LoanState const roundedLoanState = constructLoanState( + totalValueOutstandingProxy, principalOutstandingProxy, managementFeeOutstandingProxy); if (auto const fullPaymentComponents = detail::computeFullPayment( asset, @@ -1617,7 +1692,10 @@ loanMakePayment( paymentRemainingProxy, managementFeeRate), serviceFee}; - XRPL_ASSERT_PARTS(periodic.trackedPrincipalDelta >= 0, "xrpl::loanMakePayment", "regular payment valid principal"); + XRPL_ASSERT_PARTS( + periodic.trackedPrincipalDelta >= 0, + "xrpl::loanMakePayment", + "regular payment valid principal"); // ------------------------------------------------------------- // late payment handling @@ -1681,7 +1759,9 @@ loanMakePayment( { // Try to make more payments XRPL_ASSERT_PARTS( - periodic.trackedPrincipalDelta >= 0, "xrpl::loanMakePayment", "payment pays non-negative principal"); + periodic.trackedPrincipalDelta >= 0, + "xrpl::loanMakePayment", + "payment pays non-negative principal"); totalPaid += periodic.totalDue; totalParts += detail::doPayment( @@ -1696,7 +1776,8 @@ loanMakePayment( ++numPayments; XRPL_ASSERT_PARTS( - (periodic.specialCase == detail::PaymentSpecialCase::final) == (paymentRemainingProxy == 0), + (periodic.specialCase == detail::PaymentSpecialCase::final) == + (paymentRemainingProxy == 0), "xrpl::loanMakePayment", "final payment is the final payment"); @@ -1733,8 +1814,9 @@ loanMakePayment( // ------------------------------------------------------------- // overpayment handling - if (paymentType == LoanPaymentType::overpayment && loan->isFlag(lsfLoanOverpayment) && paymentRemainingProxy > 0 && - totalPaid < amount && numPayments < loanMaximumPaymentsPerTransaction) + if (paymentType == LoanPaymentType::overpayment && loan->isFlag(lsfLoanOverpayment) && + paymentRemainingProxy > 0 && totalPaid < amount && + numPayments < loanMaximumPaymentsPerTransaction) { TenthBips32 const overpaymentInterestRate{loan->at(sfOverpaymentInterestRate)}; TenthBips32 const overpaymentFeeRate{loan->at(sfOverpaymentFee)}; @@ -1744,8 +1826,14 @@ loanMakePayment( // another normal payment. But cap it just in case. Number const overpayment = std::min(amount - totalPaid, *totalValueOutstandingProxy); - detail::ExtendedPaymentComponents const overpaymentComponents = detail::computeOverpaymentComponents( - asset, loanScale, overpayment, overpaymentInterestRate, overpaymentFeeRate, managementFeeRate); + detail::ExtendedPaymentComponents const overpaymentComponents = + detail::computeOverpaymentComponents( + asset, + loanScale, + overpayment, + overpaymentInterestRate, + overpaymentFeeRate, + managementFeeRate); // Don't process an overpayment if the whole amount (or more!) // gets eaten by fees and interest. @@ -1783,13 +1871,16 @@ loanMakePayment( // Check the final results are rounded, to double-check that the // intermediate steps were rounded. XRPL_ASSERT( - isRounded(asset, totalParts.principalPaid, loanScale) && totalParts.principalPaid >= beast::zero, + isRounded(asset, totalParts.principalPaid, loanScale) && + totalParts.principalPaid >= beast::zero, "xrpl::loanMakePayment : total principal paid is valid"); XRPL_ASSERT( - isRounded(asset, totalParts.interestPaid, loanScale) && totalParts.interestPaid >= beast::zero, + isRounded(asset, totalParts.interestPaid, loanScale) && + totalParts.interestPaid >= beast::zero, "xrpl::loanMakePayment : total interest paid is valid"); XRPL_ASSERT( - isRounded(asset, totalParts.valueChange, loanScale), "xrpl::loanMakePayment : loan value change is valid"); + isRounded(asset, totalParts.valueChange, loanScale), + "xrpl::loanMakePayment : loan value change is valid"); XRPL_ASSERT( isRounded(asset, totalParts.feePaid, loanScale) && totalParts.feePaid >= beast::zero, "xrpl::loanMakePayment : fee paid is valid"); diff --git a/src/xrpld/app/tx/detail/LoanBrokerCoverClawback.cpp b/src/libxrpl/tx/transactors/Lending/LoanBrokerCoverClawback.cpp similarity index 94% rename from src/xrpld/app/tx/detail/LoanBrokerCoverClawback.cpp rename to src/libxrpl/tx/transactors/Lending/LoanBrokerCoverClawback.cpp index 7038752f8b..870af54f94 100644 --- a/src/xrpld/app/tx/detail/LoanBrokerCoverClawback.cpp +++ b/src/libxrpl/tx/transactors/Lending/LoanBrokerCoverClawback.cpp @@ -1,8 +1,7 @@ -#include +#include // -#include - #include +#include namespace xrpl { @@ -130,7 +129,10 @@ determineAsset( } Expected -determineClawAmount(SLE const& sleBroker, Asset const& vaultAsset, std::optional const& amount) +determineClawAmount( + SLE const& sleBroker, + Asset const& vaultAsset, + std::optional const& amount) { auto const maxClawAmount = [&]() { // Always round the minimum required up @@ -173,7 +175,10 @@ preclaimHelper(PreclaimContext const& ctx, SLE const& sleIssuer, STAmount template <> TER -preclaimHelper(PreclaimContext const& ctx, SLE const& sleIssuer, STAmount const& clawAmount) +preclaimHelper( + PreclaimContext const& ctx, + SLE const& sleIssuer, + STAmount const& clawAmount) { auto const issuanceKey = keylet::mptIssuance(clawAmount.get().getMptID()); auto const sleIssuance = ctx.view.read(issuanceKey); @@ -261,7 +266,9 @@ LoanBrokerCoverClawback::preclaim(PreclaimContext const& ctx) // Explicitly check the balance of the trust line / MPT to make sure the // balance is actually there. It should always match `sfCoverAvailable`, so // if there isn't, this is an internal error. - if (accountHolds(ctx.view, brokerPseudoAccountID, vaultAsset, fhIGNORE_FREEZE, ahIGNORE_AUTH, ctx.j) < clawAmount) + if (accountHolds( + ctx.view, brokerPseudoAccountID, vaultAsset, fhIGNORE_FREEZE, ahIGNORE_AUTH, ctx.j) < + clawAmount) return tecINTERNAL; // tecINSUFFICIENT_FUNDS; LCOV_EXCL_LINE // Check if the vault asset issuer has the correct flags @@ -275,7 +282,8 @@ LoanBrokerCoverClawback::preclaim(PreclaimContext const& ctx) } return std::visit( - [&](T const&) { return preclaimHelper(ctx, *sleIssuer, clawAmount); }, vaultAsset.value()); + [&](T const&) { return preclaimHelper(ctx, *sleIssuer, clawAmount); }, + vaultAsset.value()); } TER diff --git a/src/xrpld/app/tx/detail/LoanBrokerCoverDeposit.cpp b/src/libxrpl/tx/transactors/Lending/LoanBrokerCoverDeposit.cpp similarity index 96% rename from src/xrpld/app/tx/detail/LoanBrokerCoverDeposit.cpp rename to src/libxrpl/tx/transactors/Lending/LoanBrokerCoverDeposit.cpp index 3dd513414e..d112959fea 100644 --- a/src/xrpld/app/tx/detail/LoanBrokerCoverDeposit.cpp +++ b/src/libxrpl/tx/transactors/Lending/LoanBrokerCoverDeposit.cpp @@ -1,8 +1,7 @@ -#include +#include // -#include - #include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/LoanBrokerCoverWithdraw.cpp b/src/libxrpl/tx/transactors/Lending/LoanBrokerCoverWithdraw.cpp similarity index 97% rename from src/xrpld/app/tx/detail/LoanBrokerCoverWithdraw.cpp rename to src/libxrpl/tx/transactors/Lending/LoanBrokerCoverWithdraw.cpp index f2c8f28a84..43ff3659ef 100644 --- a/src/xrpld/app/tx/detail/LoanBrokerCoverWithdraw.cpp +++ b/src/libxrpl/tx/transactors/Lending/LoanBrokerCoverWithdraw.cpp @@ -1,10 +1,9 @@ -#include +#include // -#include -#include - #include #include +#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/LoanBrokerDelete.cpp b/src/libxrpl/tx/transactors/Lending/LoanBrokerDelete.cpp similarity index 89% rename from src/xrpld/app/tx/detail/LoanBrokerDelete.cpp rename to src/libxrpl/tx/transactors/Lending/LoanBrokerDelete.cpp index 7c8b6c1f64..989c26d024 100644 --- a/src/xrpld/app/tx/detail/LoanBrokerDelete.cpp +++ b/src/libxrpl/tx/transactors/Lending/LoanBrokerDelete.cpp @@ -1,8 +1,7 @@ -#include +#include // -#include - #include +#include namespace xrpl { @@ -71,7 +70,8 @@ LoanBrokerDelete::preclaim(PreclaimContext const& ctx) if (rounded != beast::zero) { // LCOV_EXCL_START - JLOG(ctx.j.warn()) << "LoanBrokerDelete: Debt total is " << debtTotal << ", which rounds to " << rounded; + JLOG(ctx.j.warn()) << "LoanBrokerDelete: Debt total is " << debtTotal + << ", which rounds to " << rounded; return tecHAS_OBLIGATIONS; // LCOV_EXCL_STOP } @@ -112,18 +112,21 @@ LoanBrokerDelete::doApply() auto const brokerPseudoID = broker->at(sfAccount); - if (!view().dirRemove(keylet::ownerDir(account_), broker->at(sfOwnerNode), broker->key(), false)) + if (!view().dirRemove( + keylet::ownerDir(account_), broker->at(sfOwnerNode), broker->key(), false)) { return tefBAD_LEDGER; // LCOV_EXCL_LINE } - if (!view().dirRemove(keylet::ownerDir(vaultPseudoID), broker->at(sfVaultNode), broker->key(), false)) + if (!view().dirRemove( + keylet::ownerDir(vaultPseudoID), broker->at(sfVaultNode), broker->key(), false)) { return tefBAD_LEDGER; // LCOV_EXCL_LINE } { auto const coverAvailable = STAmount{vaultAsset, broker->at(sfCoverAvailable)}; - if (auto const ter = accountSend(view(), brokerPseudoID, account_, coverAvailable, j_, WaiveTransferFee::Yes)) + if (auto const ter = accountSend( + view(), brokerPseudoID, account_, coverAvailable, j_, WaiveTransferFee::Yes)) return ter; } diff --git a/src/xrpld/app/tx/detail/LoanBrokerSet.cpp b/src/libxrpl/tx/transactors/Lending/LoanBrokerSet.cpp similarity index 96% rename from src/xrpld/app/tx/detail/LoanBrokerSet.cpp rename to src/libxrpl/tx/transactors/Lending/LoanBrokerSet.cpp index 9553402f15..1ede32dc23 100644 --- a/src/xrpld/app/tx/detail/LoanBrokerSet.cpp +++ b/src/libxrpl/tx/transactors/Lending/LoanBrokerSet.cpp @@ -1,8 +1,7 @@ -#include +#include // -#include - #include +#include namespace xrpl { @@ -18,7 +17,8 @@ LoanBrokerSet::preflight(PreflightContext const& ctx) using namespace Lending; auto const& tx = ctx.tx; - if (auto const data = tx[~sfData]; data && !data->empty() && !validDataLength(tx[~sfData], maxDataPayloadLength)) + if (auto const data = tx[~sfData]; + data && !data->empty() && !validDataLength(tx[~sfData], maxDataPayloadLength)) return temINVALID; if (!validNumericRange(tx[~sfManagementFeeRate], maxManagementFeeRate)) return temINVALID; @@ -140,8 +140,8 @@ LoanBrokerSet::preclaim(PreclaimContext const& ctx) { if (auto const value = tx[field]; value && STAmount{asset, *value} != *value) { - JLOG(ctx.j.warn()) << field.f->getName() << " (" << *value << ") can not be represented as a(n) " - << to_string(asset) << "."; + JLOG(ctx.j.warn()) << field.f->getName() << " (" << *value + << ") can not be represented as a(n) " << to_string(asset) << "."; return tecPRECISION_LOSS; } } diff --git a/src/xrpld/app/tx/detail/LoanDelete.cpp b/src/libxrpl/tx/transactors/Lending/LoanDelete.cpp similarity index 90% rename from src/xrpld/app/tx/detail/LoanDelete.cpp rename to src/libxrpl/tx/transactors/Lending/LoanDelete.cpp index d975834d29..fa3ccba7da 100644 --- a/src/xrpld/app/tx/detail/LoanDelete.cpp +++ b/src/libxrpl/tx/transactors/Lending/LoanDelete.cpp @@ -1,8 +1,7 @@ -#include +#include // -#include - #include +#include namespace xrpl { @@ -84,7 +83,8 @@ LoanDelete::doApply() auto const vaultAsset = vaultSle->at(sfAsset); // Remove LoanID from Directory of the LoanBroker pseudo-account. - if (!view.dirRemove(keylet::ownerDir(brokerPseudoAccount), loanSle->at(sfLoanBrokerNode), loanID, false)) + if (!view.dirRemove( + keylet::ownerDir(brokerPseudoAccount), loanSle->at(sfLoanBrokerNode), loanID, false)) return tefBAD_LEDGER; // LCOV_EXCL_LINE // Remove LoanID from Directory of the Borrower. if (!view.dirRemove(keylet::ownerDir(borrower), loanSle->at(sfOwnerNode), loanID, false)) @@ -106,8 +106,10 @@ LoanDelete::doApply() { XRPL_ASSERT_PARTS( roundToAsset( - vaultSle->at(sfAsset), debtTotalProxy, getAssetsTotalScale(vaultSle), Number::towards_zero) == - beast::zero, + vaultSle->at(sfAsset), + debtTotalProxy, + getAssetsTotalScale(vaultSle), + Number::towards_zero) == beast::zero, "xrpl::LoanDelete::doApply", "last loan, remaining debt rounds to zero"); debtTotalProxy = 0; diff --git a/src/xrpld/app/tx/detail/LoanManage.cpp b/src/libxrpl/tx/transactors/Lending/LoanManage.cpp similarity index 94% rename from src/xrpld/app/tx/detail/LoanManage.cpp rename to src/libxrpl/tx/transactors/Lending/LoanManage.cpp index 8d0a79686c..c066c4b3a9 100644 --- a/src/xrpld/app/tx/detail/LoanManage.cpp +++ b/src/libxrpl/tx/transactors/Lending/LoanManage.cpp @@ -1,9 +1,8 @@ -#include +#include // -#include - #include #include +#include namespace xrpl { @@ -70,7 +69,8 @@ LoanManage::preclaim(PreclaimContext const& ctx) JLOG(ctx.j.warn()) << "Loan is impaired. A loan can not be impaired twice."; return tecNO_PERMISSION; } - if (!(loanSle->isFlag(lsfLoanImpaired) || loanSle->isFlag(lsfLoanDefault)) && (tx.isFlag(tfLoanUnimpair))) + if (!(loanSle->isFlag(lsfLoanImpaired) || loanSle->isFlag(lsfLoanDefault)) && + (tx.isFlag(tfLoanUnimpair))) { JLOG(ctx.j.warn()) << "Loan is unimpaired. Can not be unimpaired again."; return tecNO_PERMISSION; @@ -182,7 +182,8 @@ LoanManage::defaultLoan( // LCOV_EXCL_STOP } - auto const vaultDefaultRounded = roundToAsset(vaultAsset, vaultDefaultAmount, vaultScale, Number::downward); + auto const vaultDefaultRounded = + roundToAsset(vaultAsset, vaultDefaultAmount, vaultScale, Number::downward); vaultTotalProxy -= vaultDefaultRounded; // Increase the Asset Available of the Vault by liquidated First-Loss // Capital and any unclaimed funds amount: @@ -191,9 +192,10 @@ LoanManage::defaultLoan( { auto const difference = vaultAvailableProxy - vaultTotalProxy; JLOG(j.debug()) << "Vault assets available: " << *vaultAvailableProxy << "(" - << vaultAvailableProxy.value().exponent() << "), Total: " << *vaultTotalProxy << "(" - << vaultTotalProxy.value().exponent() << "), Difference: " << difference << "(" - << difference.exponent() << ")"; + << vaultAvailableProxy.value().exponent() + << "), Total: " << *vaultTotalProxy << "(" + << vaultTotalProxy.value().exponent() << "), Difference: " << difference + << "(" << difference.exponent() << ")"; if (vaultAvailableProxy.value().exponent() - difference.exponent() > 13) { // If the difference is dust, bring the total up to match @@ -224,7 +226,8 @@ LoanManage::defaultLoan( return tefBAD_LEDGER; // LCOV_EXCL_STOP } - adjustImpreciseNumber(vaultLossUnrealizedProxy, -totalDefaultAmount, vaultAsset, vaultScale); + adjustImpreciseNumber( + vaultLossUnrealizedProxy, -totalDefaultAmount, vaultAsset, vaultScale); } view.update(vaultSle); } @@ -271,7 +274,12 @@ LoanManage::defaultLoan( } TER -LoanManage::impairLoan(ApplyView& view, SLE::ref loanSle, SLE::ref vaultSle, Asset const& vaultAsset, beast::Journal j) +LoanManage::impairLoan( + ApplyView& view, + SLE::ref loanSle, + SLE::ref vaultSle, + Asset const& vaultAsset, + beast::Journal j) { Number const lossUnrealized = owedToVault(loanSle); @@ -348,7 +356,8 @@ LoanManage::unimpairLoan( else { // loan was unimpaired after the original payment due date - loanSle->at(sfNextPaymentDueDate) = view.parentCloseTime().time_since_epoch().count() + paymentInterval; + loanSle->at(sfNextPaymentDueDate) = + view.parentCloseTime().time_since_epoch().count() + paymentInterval; } view.update(loanSle); diff --git a/src/xrpld/app/tx/detail/LoanPay.cpp b/src/libxrpl/tx/transactors/Lending/LoanPay.cpp similarity index 83% rename from src/xrpld/app/tx/detail/LoanPay.cpp rename to src/libxrpl/tx/transactors/Lending/LoanPay.cpp index 744e81d67d..6b1f2acf7c 100644 --- a/src/xrpld/app/tx/detail/LoanPay.cpp +++ b/src/libxrpl/tx/transactors/Lending/LoanPay.cpp @@ -1,12 +1,11 @@ -#include +#include // -#include -#include - #include #include #include #include +#include +#include #include @@ -35,11 +34,14 @@ LoanPay::preflight(PreflightContext const& ctx) // The loan payment flags are all mutually exclusive. If more than one is // set, the tx is malformed. - static_assert((tfLoanLatePayment | tfLoanFullPayment | tfLoanOverpayment) == ~(tfLoanPayMask | tfUniversal)); + static_assert( + (tfLoanLatePayment | tfLoanFullPayment | tfLoanOverpayment) == + ~(tfLoanPayMask | tfUniversal)); auto const flagsSet = ctx.tx.getFlags() & ~(tfLoanPayMask | tfUniversal); if (std::popcount(flagsSet) > 1) { - JLOG(ctx.j.warn()) << "Only one LoanPay flag can be set per tx. " << flagsSet << " is too many."; + JLOG(ctx.j.warn()) << "Only one LoanPay flag can be set per tx. " << flagsSet + << " is too many."; return temINVALID_FLAG; } @@ -97,8 +99,8 @@ LoanPay::calculateBaseFee(ReadView const& view, STTx const& tx) auto const scale = loanSle->at(sfLoanScale); - auto const regularPayment = - roundPeriodicPayment(asset, loanSle->at(sfPeriodicPayment), scale) + loanSle->at(sfLoanServiceFee); + auto const regularPayment = roundPeriodicPayment(asset, loanSle->at(sfPeriodicPayment), scale) + + loanSle->at(sfLoanServiceFee); // If making an overpayment, count it as a full payment because it will do // about the same amount of work, if not more. @@ -108,8 +110,9 @@ LoanPay::calculateBaseFee(ReadView const& view, STTx const& tx) // Charge one base fee per paymentsPerFeeIncrement payments, rounding up. Number::setround(Number::upward); - auto const feeIncrements = - std::max(std::int64_t(1), static_cast(numPaymentEstimate / loanPaymentsPerFeeIncrement)); + auto const feeIncrements = std::max( + std::int64_t(1), + static_cast(numPaymentEstimate / loanPaymentsPerFeeIncrement)); return feeIncrements * normalCost; } @@ -263,8 +266,10 @@ LoanPay::doApply() // the broker's solvency. NumberRoundModeGuard mg(Number::upward); return coverAvailableProxy >= - roundToAsset(asset, tenthBipsOfValue(debtTotalProxy.value(), coverRateMinimum), loanScale) && - !isDeepFrozen(view, brokerOwner, asset) && !requireAuth(view, asset, brokerOwner, AuthType::StrongAuth); + roundToAsset( + asset, tenthBipsOfValue(debtTotalProxy.value(), coverRateMinimum), loanScale) && + !isDeepFrozen(view, brokerOwner, asset) && + !requireAuth(view, asset, brokerOwner, AuthType::StrongAuth); }(); auto const brokerPayee = sendBrokerFeeToOwner ? brokerOwner : brokerPseudoAccount; @@ -312,7 +317,8 @@ LoanPay::doApply() if (!paymentParts) { - XRPL_ASSERT_PARTS(paymentParts.error(), "xrpl::LoanPay::doApply", "payment error is an error"); + XRPL_ASSERT_PARTS( + paymentParts.error(), "xrpl::LoanPay::doApply", "payment error is an error"); return paymentParts.error(); } @@ -337,7 +343,8 @@ LoanPay::doApply() "valid total paid"); XRPL_ASSERT_PARTS(paymentParts->feePaid >= 0, "xrpl::LoanPay::doApply", "valid fee paid"); - if (paymentParts->principalPaid < 0 || paymentParts->interestPaid < 0 || paymentParts->feePaid < 0) + if (paymentParts->principalPaid < 0 || paymentParts->interestPaid < 0 || + paymentParts->feePaid < 0) { // LCOV_EXCL_START JLOG(j_.fatal()) << "Loan payment computation returned invalid values."; @@ -346,7 +353,8 @@ LoanPay::doApply() } JLOG(j_.debug()) << "Loan Pay: principal paid: " << paymentParts->principalPaid - << ", interest paid: " << paymentParts->interestPaid << ", fee paid: " << paymentParts->feePaid + << ", interest paid: " << paymentParts->interestPaid + << ", fee paid: " << paymentParts->feePaid << ", value change: " << paymentParts->valueChange; //------------------------------------------------------ @@ -361,7 +369,8 @@ LoanPay::doApply() auto const vaultScale = getAssetsTotalScale(vaultSle); auto const totalPaidToVaultRaw = paymentParts->principalPaid + paymentParts->interestPaid; - auto const totalPaidToVaultRounded = roundToAsset(asset, totalPaidToVaultRaw, vaultScale, Number::downward); + auto const totalPaidToVaultRounded = + roundToAsset(asset, totalPaidToVaultRaw, vaultScale, Number::downward); XRPL_ASSERT_PARTS( !asset.integral() || totalPaidToVaultRaw == totalPaidToVaultRounded, "xrpl::LoanPay::doApply", @@ -401,7 +410,12 @@ LoanPay::doApply() { Number const assetsAvailableBefore = *assetsAvailableProxy; Number const pseudoAccountBalanceBefore = accountHolds( - view, vaultPseudoAccount, asset, FreezeHandling::fhIGNORE_FREEZE, AuthHandling::ahIGNORE_AUTH, j_); + view, + vaultPseudoAccount, + asset, + FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, + j_); XRPL_ASSERT_PARTS( assetsAvailableBefore == pseudoAccountBalanceBefore, @@ -430,11 +444,14 @@ LoanPay::doApply() JLOG(j_.debug()) << "total paid to vault raw: " << totalPaidToVaultRaw << ", total paid to vault rounded: " << totalPaidToVaultRounded - << ", total paid to broker: " << totalPaidToBroker << ", amount from transaction: " << amount; + << ", total paid to broker: " << totalPaidToBroker + << ", amount from transaction: " << amount; // Move funds XRPL_ASSERT_PARTS( - totalPaidToVaultRounded + totalPaidToBroker <= amount, "xrpl::LoanPay::doApply", "amount is sufficient"); + totalPaidToVaultRounded + totalPaidToBroker <= amount, + "xrpl::LoanPay::doApply", + "amount is sufficient"); if (!sendBrokerFeeToOwner) { @@ -456,15 +473,34 @@ LoanPay::doApply() "assets available must not be greater than assets outstanding"); #if !NDEBUG - auto const accountBalanceBefore = - accountHolds(view, account_, asset, fhIGNORE_FREEZE, ahIGNORE_AUTH, j_, SpendableHandling::shFULL_BALANCE); + auto const accountBalanceBefore = accountHolds( + view, + account_, + asset, + fhIGNORE_FREEZE, + ahIGNORE_AUTH, + j_, + SpendableHandling::shFULL_BALANCE); auto const vaultBalanceBefore = account_ == vaultPseudoAccount ? STAmount{asset, 0} : accountHolds( - view, vaultPseudoAccount, asset, fhIGNORE_FREEZE, ahIGNORE_AUTH, j_, SpendableHandling::shFULL_BALANCE); + view, + vaultPseudoAccount, + asset, + fhIGNORE_FREEZE, + ahIGNORE_AUTH, + j_, + SpendableHandling::shFULL_BALANCE); auto const brokerBalanceBefore = account_ == brokerPayee ? STAmount{asset, 0} - : accountHolds(view, brokerPayee, asset, fhIGNORE_FREEZE, ahIGNORE_AUTH, j_, SpendableHandling::shFULL_BALANCE); + : accountHolds( + view, + brokerPayee, + asset, + fhIGNORE_FREEZE, + ahIGNORE_AUTH, + j_, + SpendableHandling::shFULL_BALANCE); #endif if (totalPaidToVaultRounded != beast::zero) @@ -478,8 +514,8 @@ LoanPay::doApply() if (brokerPayee == account_) { // The broker may have deleted their holding. Recreate it if needed - if (auto const ter = - addEmptyHolding(view, brokerPayee, brokerPayeeSle->at(sfBalance).value().xrp(), asset, j_); + if (auto const ter = addEmptyHolding( + view, brokerPayee, brokerPayeeSle->at(sfBalance).value().xrp(), asset, j_); ter && ter != tecDUPLICATE) // ignore tecDUPLICATE. That means the holding already exists, // and is fine here @@ -500,29 +536,54 @@ LoanPay::doApply() #if !NDEBUG Number const assetsAvailableAfter = *assetsAvailableProxy; - Number const pseudoAccountBalanceAfter = - accountHolds(view, vaultPseudoAccount, asset, FreezeHandling::fhIGNORE_FREEZE, AuthHandling::ahIGNORE_AUTH, j_); + Number const pseudoAccountBalanceAfter = accountHolds( + view, + vaultPseudoAccount, + asset, + FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, + j_); XRPL_ASSERT_PARTS( assetsAvailableAfter == pseudoAccountBalanceAfter, "xrpl::LoanPay::doApply", "vault pseudo balance agrees after"); - auto const accountBalanceAfter = - accountHolds(view, account_, asset, fhIGNORE_FREEZE, ahIGNORE_AUTH, j_, SpendableHandling::shFULL_BALANCE); + auto const accountBalanceAfter = accountHolds( + view, + account_, + asset, + fhIGNORE_FREEZE, + ahIGNORE_AUTH, + j_, + SpendableHandling::shFULL_BALANCE); auto const vaultBalanceAfter = account_ == vaultPseudoAccount ? STAmount{asset, 0} : accountHolds( - view, vaultPseudoAccount, asset, fhIGNORE_FREEZE, ahIGNORE_AUTH, j_, SpendableHandling::shFULL_BALANCE); + view, + vaultPseudoAccount, + asset, + fhIGNORE_FREEZE, + ahIGNORE_AUTH, + j_, + SpendableHandling::shFULL_BALANCE); auto const brokerBalanceAfter = account_ == brokerPayee ? STAmount{asset, 0} - : accountHolds(view, brokerPayee, asset, fhIGNORE_FREEZE, ahIGNORE_AUTH, j_, SpendableHandling::shFULL_BALANCE); + : accountHolds( + view, + brokerPayee, + asset, + fhIGNORE_FREEZE, + ahIGNORE_AUTH, + j_, + SpendableHandling::shFULL_BALANCE); XRPL_ASSERT_PARTS( accountBalanceBefore + vaultBalanceBefore + brokerBalanceBefore == accountBalanceAfter + vaultBalanceAfter + brokerBalanceAfter, "xrpl::LoanPay::doApply", "funds are conserved (with rounding)"); - XRPL_ASSERT_PARTS(accountBalanceAfter >= beast::zero, "xrpl::LoanPay::doApply", "positive account balance"); + XRPL_ASSERT_PARTS( + accountBalanceAfter >= beast::zero, "xrpl::LoanPay::doApply", "positive account balance"); XRPL_ASSERT_PARTS( accountBalanceAfter < accountBalanceBefore || account_ == asset.getIssuer(), "xrpl::LoanPay::doApply", @@ -532,9 +593,13 @@ LoanPay::doApply() "xrpl::LoanPay::doApply", "positive vault and broker balances"); XRPL_ASSERT_PARTS( - vaultBalanceAfter >= vaultBalanceBefore, "xrpl::LoanPay::doApply", "vault balance did not decrease"); + vaultBalanceAfter >= vaultBalanceBefore, + "xrpl::LoanPay::doApply", + "vault balance did not decrease"); XRPL_ASSERT_PARTS( - brokerBalanceAfter >= brokerBalanceBefore, "xrpl::LoanPay::doApply", "broker balance did not decrease"); + brokerBalanceAfter >= brokerBalanceBefore, + "xrpl::LoanPay::doApply", + "broker balance did not decrease"); XRPL_ASSERT_PARTS( vaultBalanceAfter > vaultBalanceBefore || brokerBalanceAfter > brokerBalanceBefore, "xrpl::LoanPay::doApply", diff --git a/src/xrpld/app/tx/detail/LoanSet.cpp b/src/libxrpl/tx/transactors/Lending/LoanSet.cpp similarity index 89% rename from src/xrpld/app/tx/detail/LoanSet.cpp rename to src/libxrpl/tx/transactors/Lending/LoanSet.cpp index b7105f5df8..82a64bc89b 100644 --- a/src/xrpld/app/tx/detail/LoanSet.cpp +++ b/src/libxrpl/tx/transactors/Lending/LoanSet.cpp @@ -1,9 +1,8 @@ -#include +#include // -#include - #include #include +#include namespace xrpl { @@ -27,7 +26,8 @@ LoanSet::preflight(PreflightContext const& ctx) auto const& tx = ctx.tx; // Special case for Batch inner transactions - if (tx.isFlag(tfInnerBatchTxn) && ctx.rules.enabled(featureBatch) && !tx.isFieldPresent(sfCounterparty)) + if (tx.isFlag(tfInnerBatchTxn) && ctx.rules.enabled(featureBatch) && + !tx.isFieldPresent(sfCounterparty)) { auto const parentBatchId = ctx.parentBatchId.value_or(uint256{0}); JLOG(ctx.j.debug()) << "BatchTrace[" << parentBatchId << "]: " @@ -53,7 +53,8 @@ LoanSet::preflight(PreflightContext const& ctx) return ret; } - if (auto const data = tx[~sfData]; data && !data->empty() && !validDataLength(tx[~sfData], maxDataPayloadLength)) + if (auto const data = tx[~sfData]; + data && !data->empty() && !validDataLength(tx[~sfData], maxDataPayloadLength)) return temINVALID; for (auto const& field : {&sfLoanServiceFee, &sfLatePaymentFee, &sfClosePaymentFee}) { @@ -85,13 +86,16 @@ LoanSet::preflight(PreflightContext const& ctx) // Grace period is between min default value and payment interval else if (auto const gracePeriod = tx[~sfGracePeriod]; // !validNumericRange( - gracePeriod, paymentInterval.value_or(LoanSet::defaultPaymentInterval), defaultGracePeriod)) + gracePeriod, + paymentInterval.value_or(LoanSet::defaultPaymentInterval), + defaultGracePeriod)) return temINVALID; // Copied from preflight2 if (counterPartySig) { - if (auto const ret = xrpl::detail::preflightCheckSimulateKeys(ctx.flags, *counterPartySig, ctx.j)) + if (auto const ret = + xrpl::detail::preflightCheckSimulateKeys(ctx.flags, *counterPartySig, ctx.j)) return *ret; } @@ -125,7 +129,8 @@ LoanSet::checkSign(PreclaimContext const& ctx) if (!ctx.tx.isFieldPresent(sfCounterpartySignature)) return tesSUCCESS; auto const counterSig = ctx.tx.getFieldObject(sfCounterpartySignature); - return Transactor::checkSign(ctx.view, ctx.flags, ctx.parentBatchId, *counterSigner, counterSig, ctx.j); + return Transactor::checkSign( + ctx.view, ctx.flags, ctx.parentBatchId, *counterSigner, counterSig, ctx.j); } XRPAmount @@ -147,8 +152,9 @@ LoanSet::calculateBaseFee(ReadView const& view, STTx const& tx) std::size_t const signerCount = [&counterSig]() { // Compute defensively. Assure that "tx" cannot be accessed and cause // confusion or miscalculations. - return counterSig.isFieldPresent(sfSigners) ? counterSig.getFieldArray(sfSigners).size() - : (counterSig.isFieldPresent(sfTxnSignature) ? 1 : 0); + return counterSig.isFieldPresent(sfSigners) + ? counterSig.getFieldArray(sfSigners).size() + : (counterSig.isFieldPresent(sfTxnSignature) ? 1 : 0); }(); return normalCost + (signerCount * baseFee); @@ -158,7 +164,11 @@ std::vector> const& LoanSet::getValueFields() { static std::vector> const valueFields{ - ~sfPrincipalRequested, ~sfLoanOriginationFee, ~sfLoanServiceFee, ~sfLatePaymentFee, ~sfClosePaymentFee + ~sfPrincipalRequested, + ~sfLoanOriginationFee, + ~sfLoanServiceFee, + ~sfLatePaymentFee, + ~sfClosePaymentFee // Overpayment fee is really a rate. Don't check it here. }; @@ -276,8 +286,8 @@ LoanSet::preclaim(PreclaimContext const& ctx) { if (auto const value = tx[field]; value && STAmount{asset, *value} != *value) { - JLOG(ctx.j.warn()) << field.f->getName() << " (" << *value << ") can not be represented as a(n) " - << to_string(asset) << "."; + JLOG(ctx.j.warn()) << field.f->getName() << " (" << *value + << ") can not be represented as a(n) " << to_string(asset) << "."; return tecPRECISION_LOSS; } } @@ -383,11 +393,15 @@ LoanSet::doApply() vaultScale); LoanState const state = constructLoanState( - properties.loanState.valueOutstanding, principalRequested, properties.loanState.managementFeeDue); + properties.loanState.valueOutstanding, + principalRequested, + properties.loanState.managementFeeDue); auto const vaultMaximum = *vaultSle->at(sfAssetsMaximum); XRPL_ASSERT_PARTS( - vaultMaximum == 0 || vaultMaximum > *vaultTotalProxy, "xrpl::LoanSet::doApply", "Vault is below maximum limit"); + vaultMaximum == 0 || vaultMaximum > *vaultTotalProxy, + "xrpl::LoanSet::doApply", + "Vault is below maximum limit"); if (vaultMaximum != 0 && state.interestDue > vaultMaximum - vaultTotalProxy) { JLOG(j_.warn()) << "Loan would exceed the maximum assets of the vault"; @@ -397,16 +411,24 @@ LoanSet::doApply() // relevant for IOU assets. for (auto const& field : getValueFields()) { - if (auto const value = tx[field]; value && !isRounded(vaultAsset, *value, properties.loanScale)) + if (auto const value = tx[field]; + value && !isRounded(vaultAsset, *value, properties.loanScale)) { - JLOG(j_.warn()) << field.f->getName() << " (" << *value << ") has too much precision. Total loan value is " - << properties.loanState.valueOutstanding << " with a scale of " << properties.loanScale; + JLOG(j_.warn()) << field.f->getName() << " (" << *value + << ") has too much precision. Total loan value is " + << properties.loanState.valueOutstanding << " with a scale of " + << properties.loanScale; return tecPRECISION_LOSS; } } - if (auto const ret = - checkLoanGuards(vaultAsset, principalRequested, interestRate != beast::zero, paymentTotal, properties, j_)) + if (auto const ret = checkLoanGuards( + vaultAsset, + principalRequested, + interestRate != beast::zero, + paymentTotal, + properties, + j_)) return ret; // Check that the other computed values are valid @@ -428,7 +450,8 @@ LoanSet::doApply() auto const newDebtDelta = principalRequested + state.interestDue; auto const newDebtTotal = brokerSle->at(sfDebtTotal) + newDebtDelta; - if (auto const debtMaximum = brokerSle->at(sfDebtMaximum); debtMaximum != 0 && debtMaximum < newDebtTotal) + if (auto const debtMaximum = brokerSle->at(sfDebtMaximum); + debtMaximum != 0 && debtMaximum < newDebtTotal) { JLOG(j_.warn()) << "Loan would exceed the maximum debt limit of the LoanBroker."; return tecLIMIT_EXCEEDED; @@ -449,7 +472,8 @@ LoanSet::doApply() adjustOwnerCount(view, borrowerSle, 1, j_); { auto const ownerCount = borrowerSle->at(sfOwnerCount); - auto const balance = account_ == borrower ? mPriorBalance : borrowerSle->at(sfBalance).value().xrp(); + auto const balance = + account_ == borrower ? mPriorBalance : borrowerSle->at(sfBalance).value().xrp(); if (balance < view.fees().accountReserve(ownerCount)) return tecINSUFFICIENT_RESERVE; } @@ -461,8 +485,11 @@ LoanSet::doApply() // Create a holding for the borrower if one does not already exist. XRPL_ASSERT_PARTS( - borrower == account_ || borrower == counterparty, "xrpl::LoanSet::doApply", "borrower signed transaction"); - if (auto const ter = addEmptyHolding(view, borrower, borrowerSle->at(sfBalance).value().xrp(), vaultAsset, j_); + borrower == account_ || borrower == counterparty, + "xrpl::LoanSet::doApply", + "borrower signed transaction"); + if (auto const ter = addEmptyHolding( + view, borrower, borrowerSle->at(sfBalance).value().xrp(), vaultAsset, j_); ter && ter != tecDUPLICATE) // ignore tecDUPLICATE. That means the holding already exists, and // is fine here @@ -482,8 +509,8 @@ LoanSet::doApply() "xrpl::LoanSet::doApply", "broker owner signed transaction"); - if (auto const ter = - addEmptyHolding(view, brokerOwner, brokerOwnerSle->at(sfBalance).value().xrp(), vaultAsset, j_); + if (auto const ter = addEmptyHolding( + view, brokerOwner, brokerOwnerSle->at(sfBalance).value().xrp(), vaultAsset, j_); ter && ter != tecDUPLICATE) // ignore tecDUPLICATE. That means the holding already exists, // and is fine here diff --git a/src/xrpld/app/tx/detail/MPTokenAuthorize.cpp b/src/libxrpl/tx/transactors/MPT/MPTokenAuthorize.cpp similarity index 86% rename from src/xrpld/app/tx/detail/MPTokenAuthorize.cpp rename to src/libxrpl/tx/transactors/MPT/MPTokenAuthorize.cpp index 1eb9a0359a..846b25ca38 100644 --- a/src/xrpld/app/tx/detail/MPTokenAuthorize.cpp +++ b/src/libxrpl/tx/transactors/MPT/MPTokenAuthorize.cpp @@ -1,9 +1,8 @@ -#include - #include #include #include #include +#include namespace xrpl { @@ -36,7 +35,8 @@ MPTokenAuthorize::preclaim(PreclaimContext const& ctx) // `holderID` is NOT used if (!holderID) { - std::shared_ptr sleMpt = ctx.view.read(keylet::mptoken(ctx.tx[sfMPTokenIssuanceID], accountID)); + std::shared_ptr sleMpt = + ctx.view.read(keylet::mptoken(ctx.tx[sfMPTokenIssuanceID], accountID)); // There is an edge case where all holders have zero balance, issuance // is legally destroyed, then outstanding MPT(s) are deleted afterwards. @@ -52,7 +52,8 @@ MPTokenAuthorize::preclaim(PreclaimContext const& ctx) if ((*sleMpt)[sfMPTAmount] != 0) { - auto const sleMptIssuance = ctx.view.read(keylet::mptIssuance(ctx.tx[sfMPTokenIssuanceID])); + auto const sleMptIssuance = + ctx.view.read(keylet::mptIssuance(ctx.tx[sfMPTokenIssuanceID])); if (!sleMptIssuance) return tefINTERNAL; // LCOV_EXCL_LINE @@ -61,7 +62,8 @@ MPTokenAuthorize::preclaim(PreclaimContext const& ctx) if ((*sleMpt)[~sfLockedAmount].value_or(0) != 0) { - auto const sleMptIssuance = ctx.view.read(keylet::mptIssuance(ctx.tx[sfMPTokenIssuanceID])); + auto const sleMptIssuance = + ctx.view.read(keylet::mptIssuance(ctx.tx[sfMPTokenIssuanceID])); if (!sleMptIssuance) return tefINTERNAL; // LCOV_EXCL_LINE @@ -136,7 +138,8 @@ MPTokenAuthorize::createMPToken( { auto const mptokenKey = keylet::mptoken(mptIssuanceID, account); - auto const ownerNode = view.dirInsert(keylet::ownerDir(account), mptokenKey, describeOwnerDir(account)); + auto const ownerNode = + view.dirInsert(keylet::ownerDir(account), mptokenKey, describeOwnerDir(account)); if (!ownerNode) return tecDIR_FULL; // LCOV_EXCL_LINE @@ -157,7 +160,13 @@ MPTokenAuthorize::doApply() { auto const& tx = ctx_.tx; return authorizeMPToken( - ctx_.view(), mPriorBalance, tx[sfMPTokenIssuanceID], account_, ctx_.journal, tx.getFlags(), tx[~sfHolder]); + ctx_.view(), + mPriorBalance, + tx[sfMPTokenIssuanceID], + account_, + ctx_.journal, + tx.getFlags(), + tx[~sfHolder]); } } // namespace xrpl diff --git a/src/xrpld/app/tx/detail/MPTokenIssuanceCreate.cpp b/src/libxrpl/tx/transactors/MPT/MPTokenIssuanceCreate.cpp similarity index 90% rename from src/xrpld/app/tx/detail/MPTokenIssuanceCreate.cpp rename to src/libxrpl/tx/transactors/MPT/MPTokenIssuanceCreate.cpp index 9a9dc6a11c..ae697aa670 100644 --- a/src/xrpld/app/tx/detail/MPTokenIssuanceCreate.cpp +++ b/src/libxrpl/tx/transactors/MPT/MPTokenIssuanceCreate.cpp @@ -1,8 +1,7 @@ -#include - #include #include #include +#include namespace xrpl { @@ -10,7 +9,8 @@ bool MPTokenIssuanceCreate::checkExtraFeatures(PreflightContext const& ctx) { if (ctx.tx.isFieldPresent(sfDomainID) && - !(ctx.rules.enabled(featurePermissionedDomains) && ctx.rules.enabled(featureSingleAssetVault))) + !(ctx.rules.enabled(featurePermissionedDomains) && + ctx.rules.enabled(featureSingleAssetVault))) return false; if (ctx.tx.isFieldPresent(sfMutableFlags) && !ctx.rules.enabled(featureDynamicMPT)) @@ -81,7 +81,8 @@ MPTokenIssuanceCreate::create(ApplyView& view, beast::Journal journal, MPTCreate if (!acct) return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE - if (args.priorBalance && *(args.priorBalance) < view.fees().accountReserve((*acct)[sfOwnerCount] + 1)) + if (args.priorBalance && + *(args.priorBalance) < view.fees().accountReserve((*acct)[sfOwnerCount] + 1)) return Unexpected(tecINSUFFICIENT_RESERVE); auto const mptId = makeMptID(args.sequence, args.account); @@ -89,8 +90,8 @@ MPTokenIssuanceCreate::create(ApplyView& view, beast::Journal journal, MPTCreate // create the MPTokenIssuance { - auto const ownerNode = - view.dirInsert(keylet::ownerDir(args.account), mptIssuanceKeylet, describeOwnerDir(args.account)); + auto const ownerNode = view.dirInsert( + keylet::ownerDir(args.account), mptIssuanceKeylet, describeOwnerDir(args.account)); if (!ownerNode) return Unexpected(tecDIR_FULL); // LCOV_EXCL_LINE diff --git a/src/xrpld/app/tx/detail/MPTokenIssuanceDestroy.cpp b/src/libxrpl/tx/transactors/MPT/MPTokenIssuanceDestroy.cpp similarity index 96% rename from src/xrpld/app/tx/detail/MPTokenIssuanceDestroy.cpp rename to src/libxrpl/tx/transactors/MPT/MPTokenIssuanceDestroy.cpp index cec06c5494..acdd004bae 100644 --- a/src/xrpld/app/tx/detail/MPTokenIssuanceDestroy.cpp +++ b/src/libxrpl/tx/transactors/MPT/MPTokenIssuanceDestroy.cpp @@ -1,8 +1,7 @@ -#include - #include #include #include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/MPTokenIssuanceSet.cpp b/src/libxrpl/tx/transactors/MPT/MPTokenIssuanceSet.cpp similarity index 89% rename from src/xrpld/app/tx/detail/MPTokenIssuanceSet.cpp rename to src/libxrpl/tx/transactors/MPT/MPTokenIssuanceSet.cpp index cf3b15ed78..bacd4585d7 100644 --- a/src/xrpld/app/tx/detail/MPTokenIssuanceSet.cpp +++ b/src/libxrpl/tx/transactors/MPT/MPTokenIssuanceSet.cpp @@ -1,9 +1,8 @@ -#include -#include - #include #include #include +#include +#include namespace xrpl { @@ -11,7 +10,8 @@ bool MPTokenIssuanceSet::checkExtraFeatures(PreflightContext const& ctx) { return !ctx.tx.isFieldPresent(sfDomainID) || - (ctx.rules.enabled(featurePermissionedDomains) && ctx.rules.enabled(featureSingleAssetVault)); + (ctx.rules.enabled(featurePermissionedDomains) && + ctx.rules.enabled(featureSingleAssetVault)); } std::uint32_t @@ -92,9 +92,12 @@ MPTokenIssuanceSet::preflight(PreflightContext const& ctx) return temINVALID_FLAG; // Can not set and clear the same flag - if (std::any_of(mptMutabilityFlags.begin(), mptMutabilityFlags.end(), [mutableFlags](auto const& f) { - return (*mutableFlags & f.setFlag) && (*mutableFlags & f.clearFlag); - })) + if (std::any_of( + mptMutabilityFlags.begin(), + mptMutabilityFlags.end(), + [mutableFlags](auto const& f) { + return (*mutableFlags & f.setFlag) && (*mutableFlags & f.clearFlag); + })) return temINVALID_FLAG; // Trying to set a non-zero TransferFee and clear MPTCanTransfer @@ -153,7 +156,8 @@ MPTokenIssuanceSet::preclaim(PreclaimContext const& ctx) if (!sleMptIssuance->isFlag(lsfMPTCanLock)) { // For readability two separate `if` rather than `||` of two conditions - if (!ctx.view.rules().enabled(featureSingleAssetVault) && !ctx.view.rules().enabled(featureDynamicMPT)) + if (!ctx.view.rules().enabled(featureSingleAssetVault) && + !ctx.view.rules().enabled(featureDynamicMPT)) return tecNO_PERMISSION; else if (ctx.tx.isFlag(tfMPTLock) || ctx.tx.isFlag(tfMPTUnlock)) return tecNO_PERMISSION; @@ -191,13 +195,18 @@ MPTokenIssuanceSet::preclaim(PreclaimContext const& ctx) // the ledger. auto const currentMutableFlags = sleMptIssuance->getFieldU32(sfMutableFlags); - auto isMutableFlag = [&](std::uint32_t mutableFlag) -> bool { return currentMutableFlags & mutableFlag; }; + auto isMutableFlag = [&](std::uint32_t mutableFlag) -> bool { + return currentMutableFlags & mutableFlag; + }; if (auto const mutableFlags = ctx.tx[~sfMutableFlags]) { if (std::any_of( - mptMutabilityFlags.begin(), mptMutabilityFlags.end(), [mutableFlags, &isMutableFlag](auto const& f) { - return !isMutableFlag(f.canMutateFlag) && ((*mutableFlags & (f.setFlag | f.clearFlag))); + mptMutabilityFlags.begin(), + mptMutabilityFlags.end(), + [mutableFlags, &isMutableFlag](auto const& f) { + return !isMutableFlag(f.canMutateFlag) && + ((*mutableFlags & (f.setFlag | f.clearFlag))); })) return tecNO_PERMISSION; } @@ -290,7 +299,9 @@ MPTokenIssuanceSet::doApply() if (domainID) { // This is enforced in preflight. - XRPL_ASSERT(sle->getType() == ltMPTOKEN_ISSUANCE, "MPTokenIssuanceSet::doApply : modifying MPTokenIssuance"); + XRPL_ASSERT( + sle->getType() == ltMPTOKEN_ISSUANCE, + "MPTokenIssuanceSet::doApply : modifying MPTokenIssuance"); if (*domainID != beast::zero) { diff --git a/src/xrpld/app/tx/detail/NFTokenAcceptOffer.cpp b/src/libxrpl/tx/transactors/NFT/NFTokenAcceptOffer.cpp similarity index 87% rename from src/xrpld/app/tx/detail/NFTokenAcceptOffer.cpp rename to src/libxrpl/tx/transactors/NFT/NFTokenAcceptOffer.cpp index 349dc2c1ea..45668d4273 100644 --- a/src/xrpld/app/tx/detail/NFTokenAcceptOffer.cpp +++ b/src/libxrpl/tx/transactors/NFT/NFTokenAcceptOffer.cpp @@ -1,10 +1,9 @@ -#include -#include - #include #include #include #include +#include +#include namespace xrpl { @@ -41,7 +40,8 @@ NFTokenAcceptOffer::preflight(PreflightContext const& ctx) TER NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) { - auto const checkOffer = [&ctx](std::optional id) -> std::pair, TER> { + auto const checkOffer = + [&ctx](std::optional id) -> std::pair, TER> { if (id) { if (id->isZero()) @@ -133,13 +133,13 @@ NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) // Check if broker is allowed to receive the fee with these IOUs. if (!brokerFee->native() && ctx.view.rules().enabled(fixEnforceNFTokenTrustlineV2)) { - auto res = - nft::checkTrustlineAuthorized(ctx.view, ctx.tx[sfAccount], ctx.j, brokerFee->asset().get()); + auto res = nft::checkTrustlineAuthorized( + ctx.view, ctx.tx[sfAccount], ctx.j, brokerFee->asset().get()); if (res != tesSUCCESS) return res; - res = - nft::checkTrustlineDeepFrozen(ctx.view, ctx.tx[sfAccount], ctx.j, brokerFee->asset().get()); + res = nft::checkTrustlineDeepFrozen( + ctx.view, ctx.tx[sfAccount], ctx.j, brokerFee->asset().get()); if (res != tesSUCCESS) return res; } @@ -164,7 +164,8 @@ NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) { // If the offer has a Destination field, the acceptor must be the // Destination. - if (auto const dest = bo->at(~sfDestination); dest.has_value() && *dest != ctx.tx[sfAccount]) + if (auto const dest = bo->at(~sfDestination); + dest.has_value() && *dest != ctx.tx[sfAccount]) return tecNO_PERMISSION; } @@ -183,17 +184,20 @@ NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) // created by the broker. if (ctx.view.rules().enabled(fixEnforceNFTokenTrustlineV2) && !needed.native()) { - auto res = nft::checkTrustlineAuthorized(ctx.view, bo->at(sfOwner), ctx.j, needed.asset().get()); + auto res = nft::checkTrustlineAuthorized( + ctx.view, bo->at(sfOwner), ctx.j, needed.asset().get()); if (res != tesSUCCESS) return res; if (!so) { - res = nft::checkTrustlineAuthorized(ctx.view, ctx.tx[sfAccount], ctx.j, needed.asset().get()); + res = nft::checkTrustlineAuthorized( + ctx.view, ctx.tx[sfAccount], ctx.j, needed.asset().get()); if (res != tesSUCCESS) return res; - res = nft::checkTrustlineDeepFrozen(ctx.view, ctx.tx[sfAccount], ctx.j, needed.asset().get()); + res = nft::checkTrustlineDeepFrozen( + ctx.view, ctx.tx[sfAccount], ctx.j, needed.asset().get()); if (res != tesSUCCESS) return res; } @@ -218,7 +222,8 @@ NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) { // If the offer has a Destination field, the acceptor must be the // Destination. - if (auto const dest = so->at(~sfDestination); dest.has_value() && *dest != ctx.tx[sfAccount]) + if (auto const dest = so->at(~sfDestination); + dest.has_value() && *dest != ctx.tx[sfAccount]) return tecNO_PERMISSION; } @@ -247,21 +252,22 @@ NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) { if (ctx.view.rules().enabled(fixEnforceNFTokenTrustlineV2)) { - auto res = nft::checkTrustlineAuthorized(ctx.view, (*so)[sfOwner], ctx.j, needed.asset().get()); + auto res = nft::checkTrustlineAuthorized( + ctx.view, (*so)[sfOwner], ctx.j, needed.asset().get()); if (res != tesSUCCESS) return res; if (!bo) { - res = - nft::checkTrustlineAuthorized(ctx.view, ctx.tx[sfAccount], ctx.j, needed.asset().get()); + res = nft::checkTrustlineAuthorized( + ctx.view, ctx.tx[sfAccount], ctx.j, needed.asset().get()); if (res != tesSUCCESS) return res; } } - auto const res = - nft::checkTrustlineDeepFrozen(ctx.view, (*so)[sfOwner], ctx.j, needed.asset().get()); + auto const res = nft::checkTrustlineDeepFrozen( + ctx.view, (*so)[sfOwner], ctx.j, needed.asset().get()); if (res != tesSUCCESS) return res; } @@ -284,18 +290,21 @@ NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) // give the NFToken issuer an undesired trust line. // Issuer doesn't need a trust line to accept their own currency. if (ctx.view.rules().enabled(fixEnforceNFTokenTrustline) && - (nft::getFlags(tokenID) & nft::flagCreateTrustLines) == 0 && nftMinter != amount.getIssuer() && + (nft::getFlags(tokenID) & nft::flagCreateTrustLines) == 0 && + nftMinter != amount.getIssuer() && !ctx.view.read(keylet::line(nftMinter, amount.issue()))) return tecNO_LINE; // Check that the issuer is allowed to receive IOUs. if (ctx.view.rules().enabled(fixEnforceNFTokenTrustlineV2)) { - auto res = nft::checkTrustlineAuthorized(ctx.view, nftMinter, ctx.j, amount.asset().get()); + auto res = nft::checkTrustlineAuthorized( + ctx.view, nftMinter, ctx.j, amount.asset().get()); if (res != tesSUCCESS) return res; - res = nft::checkTrustlineDeepFrozen(ctx.view, nftMinter, ctx.j, amount.asset().get()); + res = nft::checkTrustlineDeepFrozen( + ctx.view, nftMinter, ctx.j, amount.asset().get()); if (res != tesSUCCESS) return res; } @@ -328,14 +337,18 @@ NFTokenAcceptOffer::pay(AccountID const& from, AccountID const& to, STAmount con } TER -NFTokenAcceptOffer::transferNFToken(AccountID const& buyer, AccountID const& seller, uint256 const& nftokenID) +NFTokenAcceptOffer::transferNFToken( + AccountID const& buyer, + AccountID const& seller, + uint256 const& nftokenID) { auto tokenAndPage = nft::findTokenAndPage(view(), seller, nftokenID); if (!tokenAndPage) return tecINTERNAL; // LCOV_EXCL_LINE - if (auto const ret = nft::removeToken(view(), seller, nftokenID, std::move(tokenAndPage->page)); !isTesSuccess(ret)) + if (auto const ret = nft::removeToken(view(), seller, nftokenID, std::move(tokenAndPage->page)); + !isTesSuccess(ret)) return ret; auto const sleBuyer = view().read(keylet::account(buyer)); @@ -364,7 +377,8 @@ NFTokenAcceptOffer::transferNFToken(AccountID const& buyer, AccountID const& sel auto const buyerOwnerCountAfter = sleBuyer->getFieldU32(sfOwnerCount); if (buyerOwnerCountAfter > buyerOwnerCountBefore) { - if (auto const reserve = view().fees().accountReserve(buyerOwnerCountAfter); buyerBalance < reserve) + if (auto const reserve = view().fees().accountReserve(buyerOwnerCountAfter); + buyerBalance < reserve) return tecINSUFFICIENT_RESERVE; } } @@ -427,14 +441,16 @@ NFTokenAcceptOffer::doApply() { bool foundExpired = false; - auto const deleteOfferIfExpired = [this, &foundExpired](std::shared_ptr const& offer) -> TER { + auto const deleteOfferIfExpired = + [this, &foundExpired](std::shared_ptr const& offer) -> TER { if (offer && hasExpired(view(), (*offer)[~sfExpiration])) { JLOG(j_.trace()) << "Offer is expired, deleting: " << offer->key(); if (!nft::deleteTokenOffer(view(), offer)) { // LCOV_EXCL_START - JLOG(j_.fatal()) << "Unable to delete expired offer '" << offer->key() << "': ignoring"; + JLOG(j_.fatal()) + << "Unable to delete expired offer '" << offer->key() << "': ignoring"; return tecINTERNAL; // LCOV_EXCL_STOP } @@ -464,7 +480,8 @@ NFTokenAcceptOffer::doApply() if (so && !nft::deleteTokenOffer(view(), so)) { // LCOV_EXCL_START - JLOG(j_.fatal()) << "Unable to delete sell offer '" << to_string(so->key()) << "': ignoring"; + JLOG(j_.fatal()) << "Unable to delete sell offer '" << to_string(so->key()) + << "': ignoring"; return tecINTERNAL; // LCOV_EXCL_STOP } diff --git a/src/xrpld/app/tx/detail/NFTokenBurn.cpp b/src/libxrpl/tx/transactors/NFT/NFTokenBurn.cpp similarity index 81% rename from src/xrpld/app/tx/detail/NFTokenBurn.cpp rename to src/libxrpl/tx/transactors/NFT/NFTokenBurn.cpp index a6146dcc4e..65ef9e7542 100644 --- a/src/xrpld/app/tx/detail/NFTokenBurn.cpp +++ b/src/libxrpl/tx/transactors/NFT/NFTokenBurn.cpp @@ -1,9 +1,8 @@ -#include -#include - #include #include #include +#include +#include namespace xrpl { @@ -52,7 +51,8 @@ NFTokenBurn::doApply() // Remove the token, effectively burning it: auto const ret = nft::removeToken( view(), - ctx_.tx.isFieldPresent(sfOwner) ? ctx_.tx.getAccountID(sfOwner) : ctx_.tx.getAccountID(sfAccount), + ctx_.tx.isFieldPresent(sfOwner) ? ctx_.tx.getAccountID(sfOwner) + : ctx_.tx.getAccountID(sfAccount), ctx_.tx[sfNFTokenID]); // Should never happen since preclaim() verified the token is present. @@ -69,13 +69,15 @@ NFTokenBurn::doApply() // Because the number of sell offers is likely to be less than // the number of buy offers, we prioritize the deletion of sell // offers in order to clean up sell offer directory - std::size_t const deletedSellOffers = - nft::removeTokenOffersWithLimit(view(), keylet::nft_sells(ctx_.tx[sfNFTokenID]), maxDeletableTokenOfferEntries); + std::size_t const deletedSellOffers = nft::removeTokenOffersWithLimit( + view(), keylet::nft_sells(ctx_.tx[sfNFTokenID]), maxDeletableTokenOfferEntries); if (maxDeletableTokenOfferEntries > deletedSellOffers) { nft::removeTokenOffersWithLimit( - view(), keylet::nft_buys(ctx_.tx[sfNFTokenID]), maxDeletableTokenOfferEntries - deletedSellOffers); + view(), + keylet::nft_buys(ctx_.tx[sfNFTokenID]), + maxDeletableTokenOfferEntries - deletedSellOffers); } return tesSUCCESS; diff --git a/src/xrpld/app/tx/detail/NFTokenCancelOffer.cpp b/src/libxrpl/tx/transactors/NFT/NFTokenCancelOffer.cpp similarity index 84% rename from src/xrpld/app/tx/detail/NFTokenCancelOffer.cpp rename to src/libxrpl/tx/transactors/NFT/NFTokenCancelOffer.cpp index f691a1b816..9a3e36b7c8 100644 --- a/src/xrpld/app/tx/detail/NFTokenCancelOffer.cpp +++ b/src/libxrpl/tx/transactors/NFT/NFTokenCancelOffer.cpp @@ -1,9 +1,8 @@ -#include -#include - #include #include #include +#include +#include #include @@ -18,7 +17,8 @@ NFTokenCancelOffer::getFlagsMask(PreflightContext const& ctx) NotTEC NFTokenCancelOffer::preflight(PreflightContext const& ctx) { - if (auto const& ids = ctx.tx[sfNFTokenOffers]; ids.empty() || (ids.size() > maxTokenOfferCancelCount)) + if (auto const& ids = ctx.tx[sfNFTokenOffers]; + ids.empty() || (ids.size() > maxTokenOfferCancelCount)) return temMALFORMED; // In order to prevent unnecessarily overlarge transactions, we @@ -77,10 +77,12 @@ NFTokenCancelOffer::doApply() { for (auto const& id : ctx_.tx[sfNFTokenOffers]) { - if (auto offer = view().peek(keylet::nftoffer(id)); offer && !nft::deleteTokenOffer(view(), offer)) + if (auto offer = view().peek(keylet::nftoffer(id)); + offer && !nft::deleteTokenOffer(view(), offer)) { // LCOV_EXCL_START - JLOG(j_.fatal()) << "Unable to delete token offer " << id << " (ledger " << view().seq() << ")"; + JLOG(j_.fatal()) << "Unable to delete token offer " << id << " (ledger " << view().seq() + << ")"; return tefBAD_LEDGER; // LCOV_EXCL_STOP } diff --git a/src/xrpld/app/tx/detail/NFTokenCreateOffer.cpp b/src/libxrpl/tx/transactors/NFT/NFTokenCreateOffer.cpp similarity index 89% rename from src/xrpld/app/tx/detail/NFTokenCreateOffer.cpp rename to src/libxrpl/tx/transactors/NFT/NFTokenCreateOffer.cpp index fdf2444ebc..6fe911ef5b 100644 --- a/src/xrpld/app/tx/detail/NFTokenCreateOffer.cpp +++ b/src/libxrpl/tx/transactors/NFT/NFTokenCreateOffer.cpp @@ -1,9 +1,8 @@ -#include -#include - #include #include #include +#include +#include namespace xrpl { @@ -45,7 +44,8 @@ NFTokenCreateOffer::preclaim(PreclaimContext const& ctx) uint256 const nftokenID = ctx.tx[sfNFTokenID]; std::uint32_t const txFlags = {ctx.tx.getFlags()}; - if (!nft::findToken(ctx.view, ctx.tx[(txFlags & tfSellNFToken) ? sfAccount : sfOwner], nftokenID)) + if (!nft::findToken( + ctx.view, ctx.tx[(txFlags & tfSellNFToken) ? sfAccount : sfOwner], nftokenID)) return tecNO_ENTRY; // Use implementation shared with NFTokenMint diff --git a/src/xrpld/app/tx/detail/NFTokenMint.cpp b/src/libxrpl/tx/transactors/NFT/NFTokenMint.cpp similarity index 93% rename from src/xrpld/app/tx/detail/NFTokenMint.cpp rename to src/libxrpl/tx/transactors/NFT/NFTokenMint.cpp index b00001e8fc..d8c063571b 100644 --- a/src/xrpld/app/tx/detail/NFTokenMint.cpp +++ b/src/libxrpl/tx/transactors/NFT/NFTokenMint.cpp @@ -1,11 +1,10 @@ -#include - #include #include #include #include #include #include +#include #include @@ -52,7 +51,8 @@ NFTokenMint::getFlagsMask(PreflightContext const& ctx) // if featureDynamicNFT enabled then new flag allowing mutable URI // available ? ctx.rules.enabled(featureDynamicNFT) ? tfNFTokenMintMaskWithMutable : tfNFTokenMintMask - : ctx.rules.enabled(featureDynamicNFT) ? tfNFTokenMintOldMaskWithMutable : tfNFTokenMintOldMask; + : ctx.rules.enabled(featureDynamicNFT) ? tfNFTokenMintOldMaskWithMutable + : tfNFTokenMintOldMask; return nfTokenMintMask; } @@ -226,7 +226,8 @@ NFTokenMint::doApply() std::uint32_t const acctSeq = root->at(sfSequence); root->at(sfFirstNFTokenSequence) = - ctx_.tx.isFieldPresent(sfIssuer) || ctx_.tx.getSeqProxy().isTicket() ? acctSeq : acctSeq - 1; + ctx_.tx.isFieldPresent(sfIssuer) || ctx_.tx.getSeqProxy().isTicket() ? acctSeq + : acctSeq - 1; } std::uint32_t const mintedNftCnt = (*root)[~sfMintedNFTokens].value_or(0u); @@ -251,10 +252,12 @@ NFTokenMint::doApply() if (!tokenSeq.has_value()) return (tokenSeq.error()); - std::uint32_t const ownerCountBefore = view().read(keylet::account(account_))->getFieldU32(sfOwnerCount); + std::uint32_t const ownerCountBefore = + view().read(keylet::account(account_))->getFieldU32(sfOwnerCount); // Assemble the new NFToken. - SOTemplate const* nfTokenTemplate = InnerObjectFormats::getInstance().findSOTemplateBySField(sfNFToken); + SOTemplate const* nfTokenTemplate = + InnerObjectFormats::getInstance().findSOTemplateBySField(sfNFToken); if (nfTokenTemplate == nullptr) // Should never happen. @@ -274,7 +277,8 @@ NFTokenMint::doApply() object.setFieldVL(sfURI, *uri); }); - if (TER const ret = nft::insertToken(ctx_.view(), account_, std::move(newToken)); ret != tesSUCCESS) + if (TER const ret = nft::insertToken(ctx_.view(), account_, std::move(newToken)); + ret != tesSUCCESS) return ret; if (ctx_.tx.isFieldPresent(sfAmount)) @@ -300,10 +304,12 @@ NFTokenMint::doApply() // allows NFTs to be added to the page (and burn fees) without // 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); + if (auto const ownerCountAfter = + view().read(keylet::account(account_))->getFieldU32(sfOwnerCount); ownerCountAfter > ownerCountBefore) { - if (auto const reserve = view().fees().accountReserve(ownerCountAfter); mPriorBalance < reserve) + if (auto const reserve = view().fees().accountReserve(ownerCountAfter); + mPriorBalance < reserve) return tecINSUFFICIENT_RESERVE; } return tesSUCCESS; diff --git a/src/xrpld/app/tx/detail/NFTokenModify.cpp b/src/libxrpl/tx/transactors/NFT/NFTokenModify.cpp similarity index 93% rename from src/xrpld/app/tx/detail/NFTokenModify.cpp rename to src/libxrpl/tx/transactors/NFT/NFTokenModify.cpp index 15be2d196a..316bcb0f27 100644 --- a/src/xrpld/app/tx/detail/NFTokenModify.cpp +++ b/src/libxrpl/tx/transactors/NFT/NFTokenModify.cpp @@ -1,8 +1,7 @@ -#include -#include - #include #include +#include +#include namespace xrpl { diff --git a/src/xrpld/app/tx/detail/NFTokenUtils.cpp b/src/libxrpl/tx/transactors/NFT/NFTokenUtils.cpp similarity index 88% rename from src/xrpld/app/tx/detail/NFTokenUtils.cpp rename to src/libxrpl/tx/transactors/NFT/NFTokenUtils.cpp index 5581182204..383929d54e 100644 --- a/src/xrpld/app/tx/detail/NFTokenUtils.cpp +++ b/src/libxrpl/tx/transactors/NFT/NFTokenUtils.cpp @@ -1,5 +1,3 @@ -#include - #include #include #include @@ -7,6 +5,7 @@ #include #include #include +#include #include #include @@ -24,7 +23,8 @@ locatePage(ReadView const& view, AccountID const& owner, uint256 const& id) // This NFT can only be found in the first page with a key that's strictly // greater than `first`, so look for that, up until the maximum possible // page. - return view.read(Keylet(ltNFTOKEN_PAGE, view.succ(first.key, last.key.next()).value_or(last.key))); + return view.read( + Keylet(ltNFTOKEN_PAGE, view.succ(first.key, last.key.next()).value_or(last.key))); } static std::shared_ptr @@ -36,7 +36,8 @@ locatePage(ApplyView& view, AccountID const& owner, uint256 const& id) // This NFT can only be found in the first page with a key that's strictly // greater than `first`, so look for that, up until the maximum possible // page. - return view.peek(Keylet(ltNFTOKEN_PAGE, view.succ(first.key, last.key.next()).value_or(last.key))); + return view.peek( + Keylet(ltNFTOKEN_PAGE, view.succ(first.key, last.key.next()).value_or(last.key))); } static std::shared_ptr @@ -53,7 +54,8 @@ getPageForToken( // This NFT can only be found in the first page with a key that's strictly // greater than `first`, so look for that, up until the maximum possible // page. - auto cp = view.peek(Keylet(ltNFTOKEN_PAGE, view.succ(first.key, last.key.next()).value_or(last.key))); + auto cp = + view.peek(Keylet(ltNFTOKEN_PAGE, view.succ(first.key, last.key.next()).value_or(last.key))); // A suitable page doesn't exist; we'll have to create one. if (!cp) @@ -85,12 +87,13 @@ getPageForToken( // We prefer to keep equivalent NFTs on a page boundary. That gives // any additional equivalent NFTs maximum room for expansion. // Round up the boundary until there's a non-equivalent entry. - uint256 const cmp = narr[(dirMaxTokensPerPage / 2) - 1].getFieldH256(sfNFTokenID) & nft::pageMask; + uint256 const cmp = + narr[(dirMaxTokensPerPage / 2) - 1].getFieldH256(sfNFTokenID) & nft::pageMask; // Note that the calls to find_if_not() and (later) find_if() // rely on the fact that narr is kept in sorted order. - auto splitIter = - std::find_if_not(narr.begin() + (dirMaxTokensPerPage / 2), narr.end(), [&cmp](STObject const& obj) { + auto splitIter = std::find_if_not( + narr.begin() + (dirMaxTokensPerPage / 2), narr.end(), [&cmp](STObject const& obj) { return (obj.getFieldH256(sfNFTokenID) & nft::pageMask) == cmp; }); @@ -192,7 +195,11 @@ compareTokens(uint256 const& a, uint256 const& b) } TER -changeTokenURI(ApplyView& view, AccountID const& owner, uint256 const& nftokenID, std::optional const& uri) +changeTokenURI( + ApplyView& view, + AccountID const& owner, + uint256 const& nftokenID, + std::optional const& uri) { std::shared_ptr const page = locatePage(view, owner, nftokenID); @@ -203,8 +210,9 @@ changeTokenURI(ApplyView& view, AccountID const& owner, uint256 const& nftokenID // Locate the NFT in the page STArray& arr = page->peekFieldArray(sfNFTokens); - auto const nftIter = std::find_if( - arr.begin(), arr.end(), [&nftokenID](STObject const& obj) { return (obj[sfNFTokenID] == nftokenID); }); + auto const nftIter = std::find_if(arr.begin(), arr.end(), [&nftokenID](STObject const& obj) { + return (obj[sfNFTokenID] == nftokenID); + }); if (nftIter == arr.end()) return tecINTERNAL; // LCOV_EXCL_LINE @@ -229,7 +237,11 @@ insertToken(ApplyView& view, AccountID owner, STObject&& nft) // the NFT. std::shared_ptr page = getPageForToken(view, owner, nft[sfNFTokenID], [](ApplyView& view, AccountID const& owner) { - adjustOwnerCount(view, view.peek(keylet::account(owner)), 1, beast::Journal{beast::Journal::getNullSink()}); + adjustOwnerCount( + view, + view.peek(keylet::account(owner)), + 1, + beast::Journal{beast::Journal::getNullSink()}); }); if (!page) @@ -327,14 +339,19 @@ removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID) /** Remove the token from the owner's token directory. */ TER -removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID, std::shared_ptr&& curr) +removeToken( + ApplyView& view, + AccountID const& owner, + uint256 const& nftokenID, + std::shared_ptr&& curr) { // We found a page, but the given NFT may not be in it. auto arr = curr->getFieldArray(sfNFTokens); { - auto x = std::find_if( - arr.begin(), arr.end(), [&nftokenID](STObject const& obj) { return (obj[sfNFTokenID] == nftokenID); }); + auto x = std::find_if(arr.begin(), arr.end(), [&nftokenID](STObject const& obj) { + return (obj[sfNFTokenID] == nftokenID); + }); if (x == arr.end()) return tecNO_ENTRY; @@ -352,8 +369,8 @@ removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID, s if (!page2) Throw( - "page " + to_string(page1->key()) + " has a broken " + field.getName() + " field pointing to " + - to_string(*id)); + "page " + to_string(page1->key()) + " has a broken " + field.getName() + + " field pointing to " + to_string(*id)); } return page2; @@ -380,7 +397,10 @@ removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID, s if (cnt != 0) adjustOwnerCount( - view, view.peek(keylet::account(owner)), cnt, beast::Journal{beast::Journal::getNullSink()}); + view, + view.peek(keylet::account(owner)), + cnt, + beast::Journal{beast::Journal::getNullSink()}); return tesSUCCESS; } @@ -394,7 +414,8 @@ removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID, s // 2. Fix up the link from prev's previous page. // 3. Fix up the owner count. // 4. Erase the previous page. - if (view.rules().enabled(fixNFTokenPageLinks) && ((curr->key() & nft::pageMask) == pageMask)) + if (view.rules().enabled(fixNFTokenPageLinks) && + ((curr->key() & nft::pageMask) == pageMask)) { // Copy all relevant information from prev to curr. curr->peekFieldArray(sfNFTokens) = prev->peekFieldArray(sfNFTokens); @@ -414,7 +435,10 @@ removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID, s } adjustOwnerCount( - view, view.peek(keylet::account(owner)), -1, beast::Journal{beast::Journal::getNullSink()}); + view, + view.peek(keylet::account(owner)), + -1, + beast::Journal{beast::Journal::getNullSink()}); view.update(curr); view.erase(prev); @@ -456,10 +480,16 @@ removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID, s // just in case. if (prev && next && mergePages( - view, view.peek(Keylet(ltNFTOKEN_PAGE, prev->key())), view.peek(Keylet(ltNFTOKEN_PAGE, next->key())))) + view, + view.peek(Keylet(ltNFTOKEN_PAGE, prev->key())), + view.peek(Keylet(ltNFTOKEN_PAGE, next->key())))) cnt++; - adjustOwnerCount(view, view.peek(keylet::account(owner)), -1 * cnt, beast::Journal{beast::Journal::getNullSink()}); + adjustOwnerCount( + view, + view.peek(keylet::account(owner)), + -1 * cnt, + beast::Journal{beast::Journal::getNullSink()}); return tesSUCCESS; } @@ -536,7 +566,8 @@ removeTokenOffersWithLimit(ApplyView& view, Keylet const& directory, std::size_t if (deleteTokenOffer(view, offer)) ++deletedOffersCount; else - Throw("Offer " + to_string(offerIndexes[i]) + " cannot be deleted!"); + Throw( + "Offer " + to_string(offerIndexes[i]) + " cannot be deleted!"); } if (maxDeletableOffers == deletedOffersCount) @@ -588,13 +619,15 @@ deleteTokenOffer(ApplyView& view, std::shared_ptr const& offer) auto const nftokenID = (*offer)[sfNFTokenID]; if (!view.dirRemove( - ((*offer)[sfFlags] & tfSellNFToken) ? keylet::nft_sells(nftokenID) : keylet::nft_buys(nftokenID), + ((*offer)[sfFlags] & tfSellNFToken) ? keylet::nft_sells(nftokenID) + : keylet::nft_buys(nftokenID), (*offer)[sfNFTokenOfferNode], offer->key(), false)) return false; - adjustOwnerCount(view, view.peek(keylet::account(owner)), -1, beast::Journal{beast::Journal::getNullSink()}); + adjustOwnerCount( + view, view.peek(keylet::account(owner)), -1, beast::Journal{beast::Journal::getNullSink()}); view.erase(offer); return true; @@ -607,8 +640,9 @@ repairNFTokenDirectoryLinks(ApplyView& view, AccountID const& owner) auto const last = keylet::nftpage_max(owner); - std::shared_ptr page = view.peek( - Keylet(ltNFTOKEN_PAGE, view.succ(keylet::nftpage_min(owner).key, last.key.next()).value_or(last.key))); + std::shared_ptr page = view.peek(Keylet( + ltNFTOKEN_PAGE, + view.succ(keylet::nftpage_min(owner).key, last.key.next()).value_or(last.key))); if (!page) return didRepair; @@ -642,17 +676,19 @@ repairNFTokenDirectoryLinks(ApplyView& view, AccountID const& owner) std::shared_ptr nextPage; while ( - (nextPage = - view.peek(Keylet(ltNFTOKEN_PAGE, view.succ(page->key().next(), last.key.next()).value_or(last.key))))) + (nextPage = view.peek(Keylet( + ltNFTOKEN_PAGE, view.succ(page->key().next(), last.key.next()).value_or(last.key))))) { - if (!page->isFieldPresent(sfNextPageMin) || page->getFieldH256(sfNextPageMin) != nextPage->key()) + if (!page->isFieldPresent(sfNextPageMin) || + page->getFieldH256(sfNextPageMin) != nextPage->key()) { didRepair = true; page->setFieldH256(sfNextPageMin, nextPage->key()); view.update(page); } - if (!nextPage->isFieldPresent(sfPreviousPageMin) || nextPage->getFieldH256(sfPreviousPageMin) != page->key()) + if (!nextPage->isFieldPresent(sfPreviousPageMin) || + nextPage->getFieldH256(sfPreviousPageMin) != page->key()) { didRepair = true; nextPage->setFieldH256(sfPreviousPageMin, page->key()); @@ -692,7 +728,8 @@ repairNFTokenDirectoryLinks(ApplyView& view, AccountID const& owner) auto const newPrev = view.peek(Keylet(ltNFTOKEN_PAGE, *prevLink)); if (!newPrev) Throw( - "NFTokenPage directory for " + to_string(owner) + " cannot be repaired. Unexpected link problem."); + "NFTokenPage directory for " + to_string(owner) + + " cannot be repaired. Unexpected link problem."); newPrev->at(sfNextPageMin) = nextPage->key(); view.update(newPrev); } @@ -782,7 +819,8 @@ tokenOfferCreatePreclaim( // issuer does not need a trust line to accept their fee. if (view.rules().enabled(featureNFTokenMintOffer)) { - if (nftIssuer != amount.getIssuer() && !view.read(keylet::line(nftIssuer, amount.issue()))) + if (nftIssuer != amount.getIssuer() && + !view.read(keylet::line(nftIssuer, amount.issue()))) return tecNO_LINE; } else if (!view.exists(keylet::line(nftIssuer, amount.issue()))) @@ -851,7 +889,8 @@ tokenOfferCreatePreclaim( // is authorized, even though we previously checked it's balance via // accountHolds. This is due to a possibility of existence of // unauthorized trustlines with balance - auto const res = nft::checkTrustlineAuthorized(view, acctID, j, amount.asset().get()); + auto const res = + nft::checkTrustlineAuthorized(view, acctID, j, amount.asset().get()); if (res != tesSUCCESS) return res; } @@ -872,7 +911,8 @@ tokenOfferCreateApply( std::uint32_t txFlags) { Keylet const acctKeylet = keylet::account(acctID); - if (auto const acct = view.read(acctKeylet); priorBalance < view.fees().accountReserve((*acct)[sfOwnerCount] + 1)) + if (auto const acct = view.read(acctKeylet); + priorBalance < view.fees().accountReserve((*acct)[sfOwnerCount] + 1)) return tecINSUFFICIENT_RESERVE; auto const offerID = keylet::nftoffer(acctID, seqProxy.value()); @@ -880,7 +920,8 @@ tokenOfferCreateApply( // Create the offer: { // Token offers are always added to the owner's owner directory: - auto const ownerNode = view.dirInsert(keylet::ownerDir(acctID), offerID, describeOwnerDir(acctID)); + auto const ownerNode = + view.dirInsert(keylet::ownerDir(acctID), offerID, describeOwnerDir(acctID)); if (!ownerNode) return tecDIR_FULL; // LCOV_EXCL_LINE @@ -929,7 +970,11 @@ tokenOfferCreateApply( } TER -checkTrustlineAuthorized(ReadView const& view, AccountID const id, beast::Journal const j, Issue const& issue) +checkTrustlineAuthorized( + ReadView const& view, + AccountID const id, + beast::Journal const j, + Issue const& issue) { // Only valid for custom currencies XRPL_ASSERT(!isXRP(issue.currency), "xrpl::nft::checkTrustlineAuthorized : valid to check."); @@ -977,7 +1022,11 @@ checkTrustlineAuthorized(ReadView const& view, AccountID const id, beast::Journa } TER -checkTrustlineDeepFrozen(ReadView const& view, AccountID const id, beast::Journal const j, Issue const& issue) +checkTrustlineDeepFrozen( + ReadView const& view, + AccountID const id, + beast::Journal const j, + Issue const& issue) { // Only valid for custom currencies XRPL_ASSERT(!isXRP(issue.currency), "xrpl::nft::checkTrustlineDeepFrozen : valid to check."); diff --git a/src/xrpld/app/tx/detail/CancelOffer.cpp b/src/libxrpl/tx/transactors/Offer/CancelOffer.cpp similarity index 92% rename from src/xrpld/app/tx/detail/CancelOffer.cpp rename to src/libxrpl/tx/transactors/Offer/CancelOffer.cpp index 1dc9ad0bde..3e5d2441e1 100644 --- a/src/xrpld/app/tx/detail/CancelOffer.cpp +++ b/src/libxrpl/tx/transactors/Offer/CancelOffer.cpp @@ -1,8 +1,7 @@ -#include - #include #include #include +#include namespace xrpl { @@ -54,7 +53,7 @@ CancelOffer::doApply() if (auto sleOffer = view().peek(keylet::offer(account_, offerSequence))) { JLOG(j_.debug()) << "Trying to cancel offer #" << offerSequence; - return offerDelete(view(), sleOffer, ctx_.app.journal("View")); + return offerDelete(view(), sleOffer, ctx_.registry.journal("View")); } JLOG(j_.debug()) << "Offer #" << offerSequence << " can't be found."; diff --git a/src/xrpld/app/tx/detail/CreateOffer.cpp b/src/libxrpl/tx/transactors/Offer/CreateOffer.cpp similarity index 92% rename from src/xrpld/app/tx/detail/CreateOffer.cpp rename to src/libxrpl/tx/transactors/Offer/CreateOffer.cpp index fab406189b..9516926693 100644 --- a/src/xrpld/app/tx/detail/CreateOffer.cpp +++ b/src/libxrpl/tx/transactors/Offer/CreateOffer.cpp @@ -1,16 +1,15 @@ -#include -#include -#include -#include - #include #include +#include #include #include #include #include #include #include +#include +#include +#include namespace xrpl { TxConsequences @@ -144,7 +143,7 @@ CreateOffer::preclaim(PreclaimContext const& ctx) std::uint32_t const uAccountSequence = sleCreator->getFieldU32(sfSequence); - auto viewJ = ctx.app.journal("View"); + auto viewJ = ctx.registry.journal("View"); if (isGlobalFrozen(ctx.view, uPaysIssuerID) || isGlobalFrozen(ctx.view, uGetsIssuerID)) { @@ -162,7 +161,8 @@ CreateOffer::preclaim(PreclaimContext const& ctx) // before the transaction sequence number. if (cancelSequence && (uAccountSequence <= *cancelSequence)) { - JLOG(ctx.j.debug()) << "uAccountSequenceNext=" << uAccountSequence << " uOfferSequence=" << *cancelSequence; + JLOG(ctx.j.debug()) << "uAccountSequenceNext=" << uAccountSequence + << " uOfferSequence=" << *cancelSequence; return temBAD_SEQUENCE; } @@ -176,7 +176,8 @@ CreateOffer::preclaim(PreclaimContext const& ctx) // Make sure that we are authorized to hold what the taker will pay us. if (!saTakerPays.native()) { - auto result = checkAcceptAsset(ctx.view, ctx.flags, id, ctx.j, Issue(uPaysCurrency, uPaysIssuerID)); + auto result = + checkAcceptAsset(ctx.view, ctx.flags, id, ctx.j, Issue(uPaysCurrency, uPaysIssuerID)); if (result != tesSUCCESS) return result; } @@ -207,7 +208,8 @@ CreateOffer::checkAcceptAsset( if (!issuerAccount) { - JLOG(j.debug()) << "delay: can't receive IOUs from non-existent issuer: " << to_string(issue.account); + JLOG(j.debug()) << "delay: can't receive IOUs from non-existent issuer: " + << to_string(issue.account); return (flags & tapRETRY) ? TER{terNO_ACCOUNT} : TER{tecNO_ISSUER}; } @@ -282,7 +284,8 @@ CreateOffer::flowCross( // We check this in preclaim, but when selling XRP charged fees can // cause a user's available balance to go to 0 (by causing it to dip // below the reserve) so we check this case again. - STAmount const inStartBalance = accountFunds(psb, account_, takerAmount.in, fhZERO_IF_FROZEN, j_); + STAmount const inStartBalance = + accountFunds(psb, account_, takerAmount.in, fhZERO_IF_FROZEN, j_); if (inStartBalance <= beast::zero) { // The account balance can't cover even part of the offer. @@ -300,7 +303,8 @@ CreateOffer::flowCross( gatewayXferRate = transferRate(psb, sendMax.getIssuer()); if (gatewayXferRate.value != QUALITY_ONE) { - sendMax = multiplyRound(takerAmount.in, gatewayXferRate, takerAmount.in.issue(), true); + sendMax = + multiplyRound(takerAmount.in, gatewayXferRate, takerAmount.in.issue(), true); } } @@ -345,7 +349,8 @@ CreateOffer::flowCross( // there might be a gateway transfer rate to account for. // Since the transfer rate cannot exceed 200%, we use 1/2 // maxValue for our limit. - deliver = STAmount{takerAmount.out.issue(), STAmount::cMaxValue / 2, STAmount::cMaxOffset}; + deliver = STAmount{ + takerAmount.out.issue(), STAmount::cMaxValue / 2, STAmount::cMaxOffset}; } // Call the payment engine's flow() to do the actual work. @@ -377,7 +382,8 @@ CreateOffer::flowCross( auto afterCross = takerAmount; // If !tesSUCCESS offer unchanged if (isTesSuccess(result.result())) { - STAmount const takerInBalance = accountFunds(psb, account_, takerAmount.in, fhZERO_IF_FROZEN, j_); + STAmount const takerInBalance = + accountFunds(psb, account_, takerAmount.in, fhZERO_IF_FROZEN, j_); if (takerInBalance <= beast::zero) { @@ -402,8 +408,8 @@ CreateOffer::flowCross( // gateway's transfer rate. STAmount nonGatewayAmountIn = result.actualAmountIn; if (gatewayXferRate.value != QUALITY_ONE) - nonGatewayAmountIn = - divideRound(result.actualAmountIn, gatewayXferRate, takerAmount.in.issue(), true); + nonGatewayAmountIn = divideRound( + result.actualAmountIn, gatewayXferRate, takerAmount.in.issue(), true); afterCross.in -= nonGatewayAmountIn; @@ -414,7 +420,8 @@ CreateOffer::flowCross( // what is a good threshold to check? afterCross.in.clear(); - afterCross.out = divRoundStrict(afterCross.in, rate, takerAmount.out.issue(), false); + afterCross.out = + divRoundStrict(afterCross.in, rate, takerAmount.out.issue(), false); } else { @@ -422,7 +429,9 @@ CreateOffer::flowCross( // remaining output. This too preserves the offer // Quality. afterCross.out -= result.actualAmountOut; - XRPL_ASSERT(afterCross.out >= beast::zero, "xrpl::CreateOffer::flowCross : minimum offer"); + XRPL_ASSERT( + afterCross.out >= beast::zero, + "xrpl::CreateOffer::flowCross : minimum offer"); if (afterCross.out < beast::zero) afterCross.out.clear(); afterCross.in = mulRound(afterCross.out, rate, takerAmount.in.issue(), true); @@ -489,7 +498,7 @@ CreateOffer::applyHybrid( bookArr.push_back(std::move(bookInfo)); if (!bookExists) - ctx_.app.getOrderBookDB().addOrderBook(book); + ctx_.registry.getOrderBookDB().addOrderBook(book); sleOffer->setFieldArray(sfAdditionalBooks, bookArr); return tesSUCCESS; @@ -523,7 +532,7 @@ CreateOffer::applyGuts(Sandbox& sb, Sandbox& sbCancel) // end up on the books. auto uRate = getRate(saTakerGets, saTakerPays); - auto viewJ = ctx_.app.journal("View"); + auto viewJ = ctx_.registry.journal("View"); TER result = tesSUCCESS; @@ -647,9 +656,11 @@ CreateOffer::applyGuts(Sandbox& sb, Sandbox& sbCancel) } XRPL_ASSERT( - saTakerGets.issue() == place_offer.in.issue(), "xrpl::CreateOffer::applyGuts : taker gets issue match"); + saTakerGets.issue() == place_offer.in.issue(), + "xrpl::CreateOffer::applyGuts : taker gets issue match"); XRPL_ASSERT( - saTakerPays.issue() == place_offer.out.issue(), "xrpl::CreateOffer::applyGuts : taker pays issue match"); + saTakerPays.issue() == place_offer.out.issue(), + "xrpl::CreateOffer::applyGuts : taker pays issue match"); if (takerAmount != place_offer) crossed = true; @@ -678,7 +689,8 @@ CreateOffer::applyGuts(Sandbox& sb, Sandbox& sbCancel) } XRPL_ASSERT( - saTakerPays > zero && saTakerGets > zero, "xrpl::CreateOffer::applyGuts : taker pays and gets positive"); + saTakerPays > zero && saTakerGets > zero, + "xrpl::CreateOffer::applyGuts : taker pays and gets positive"); if (result != tesSUCCESS) { @@ -742,7 +754,8 @@ CreateOffer::applyGuts(Sandbox& sb, Sandbox& sbCancel) auto const offer_index = keylet::offer(account_, offerSequence); // Add offer to owner's directory. - auto const ownerNode = sb.dirInsert(keylet::ownerDir(account_), offer_index, describeOwnerDir(account_)); + auto const ownerNode = + sb.dirInsert(keylet::ownerDir(account_), offer_index, describeOwnerDir(account_)); if (!ownerNode) { @@ -755,7 +768,8 @@ CreateOffer::applyGuts(Sandbox& sb, Sandbox& sbCancel) // Update owner count. adjustOwnerCount(sb, sleCreator, 1, viewJ); - JLOG(j_.trace()) << "adding to book: " << to_string(saTakerPays.issue()) << " : " << to_string(saTakerGets.issue()) + JLOG(j_.trace()) << "adding to book: " << to_string(saTakerPays.issue()) << " : " + << to_string(saTakerGets.issue()) << (domainID ? (" : " + to_string(*domainID)) : ""); Book const book{saTakerPays.issue(), saTakerGets.issue(), domainID}; @@ -817,7 +831,8 @@ CreateOffer::applyGuts(Sandbox& sb, Sandbox& sbCancel) // if it's a hybrid offer, set hybrid flag, and create an open dir if (bHybrid) { - auto const res = applyHybrid(sb, sleOffer, offer_index, saTakerPays, saTakerGets, setBookDir); + auto const res = + applyHybrid(sb, sleOffer, offer_index, saTakerPays, saTakerGets, setBookDir); if (res != tesSUCCESS) return {res, true}; // LCOV_EXCL_LINE } @@ -825,7 +840,7 @@ CreateOffer::applyGuts(Sandbox& sb, Sandbox& sbCancel) sb.insert(sleOffer); if (!bookExisted) - ctx_.app.getOrderBookDB().addOrderBook(book); + ctx_.registry.getOrderBookDB().addOrderBook(book); JLOG(j_.debug()) << "final result: success"; diff --git a/src/xrpld/app/tx/detail/PayChan.cpp b/src/libxrpl/tx/transactors/PayChan.cpp similarity index 93% rename from src/xrpld/app/tx/detail/PayChan.cpp rename to src/libxrpl/tx/transactors/PayChan.cpp index baa8770e53..3b29169af6 100644 --- a/src/xrpld/app/tx/detail/PayChan.cpp +++ b/src/libxrpl/tx/transactors/PayChan.cpp @@ -1,5 +1,3 @@ -#include - #include #include #include @@ -12,6 +10,7 @@ #include #include #include +#include namespace xrpl { @@ -95,7 +94,11 @@ namespace xrpl { //------------------------------------------------------------------------------ static TER -closeChannel(std::shared_ptr const& slep, ApplyView& view, uint256 const& key, beast::Journal j) +closeChannel( + std::shared_ptr const& slep, + ApplyView& view, + uint256 const& key, + beast::Journal j) { AccountID const src = (*slep)[sfAccount]; // Remove PayChan from owner directory @@ -128,7 +131,8 @@ closeChannel(std::shared_ptr const& slep, ApplyView& view, uint256 const& k if (!sle) return tefINTERNAL; // LCOV_EXCL_LINE - XRPL_ASSERT((*slep)[sfAmount] >= (*slep)[sfBalance], "xrpl::closeChannel : minimum channel amount"); + XRPL_ASSERT( + (*slep)[sfAmount] >= (*slep)[sfBalance], "xrpl::closeChannel : minimum channel amount"); (*sle)[sfBalance] = (*sle)[sfBalance] + (*slep)[sfAmount] - (*slep)[sfBalance]; adjustOwnerCount(view, sle, -1, j); view.update(sle); @@ -255,7 +259,8 @@ PayChanCreate::doApply() // Add PayChan to owner directory { - auto const page = ctx_.view().dirInsert(keylet::ownerDir(account), payChanKeylet, describeOwnerDir(account)); + auto const page = ctx_.view().dirInsert( + keylet::ownerDir(account), payChanKeylet, describeOwnerDir(account)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE (*slep)[sfOwnerNode] = *page; @@ -263,7 +268,8 @@ PayChanCreate::doApply() // Add PayChan to the recipient's owner directory { - auto const page = ctx_.view().dirInsert(keylet::ownerDir(dst), payChanKeylet, describeOwnerDir(dst)); + auto const page = + ctx_.view().dirInsert(keylet::ownerDir(dst), payChanKeylet, describeOwnerDir(dst)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE (*slep)[sfDestinationNode] = *page; @@ -310,7 +316,7 @@ PayChanFund::doApply() auto const cancelAfter = (*slep)[~sfCancelAfter]; auto const closeTime = ctx_.view().header().parentCloseTime.time_since_epoch().count(); if ((cancelAfter && closeTime >= *cancelAfter) || (expiration && closeTime >= *expiration)) - return closeChannel(slep, ctx_.view(), k.key, ctx_.app.journal("View")); + return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.journal("View")); } if (src != txAccount) @@ -319,7 +325,8 @@ PayChanFund::doApply() if (auto extend = ctx_.tx[~sfExpiration]) { - auto minExpiration = ctx_.view().header().parentCloseTime.time_since_epoch().count() + (*slep)[sfSettleDelay]; + auto minExpiration = ctx_.view().header().parentCloseTime.time_since_epoch().count() + + (*slep)[sfSettleDelay]; if (expiration && *expiration < minExpiration) minExpiration = *expiration; @@ -433,7 +440,8 @@ PayChanClaim::preclaim(PreclaimContext const& ctx) if (!ctx.view.rules().enabled(featureCredentials)) return Transactor::preclaim(ctx); - if (auto const err = credentials::valid(ctx.tx, ctx.view, ctx.tx[sfAccount], ctx.j); !isTesSuccess(err)) + if (auto const err = credentials::valid(ctx.tx, ctx.view, ctx.tx[sfAccount], ctx.j); + !isTesSuccess(err)) return err; return tesSUCCESS; @@ -455,8 +463,9 @@ PayChanClaim::doApply() { auto const cancelAfter = (*slep)[~sfCancelAfter]; auto const closeTime = ctx_.view().header().parentCloseTime.time_since_epoch().count(); - if ((cancelAfter && closeTime >= *cancelAfter) || (curExpiration && closeTime >= *curExpiration)) - return closeChannel(slep, ctx_.view(), k.key, ctx_.app.journal("View")); + if ((cancelAfter && closeTime >= *cancelAfter) || + (curExpiration && closeTime >= *curExpiration)) + return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.journal("View")); } if (txAccount != src && txAccount != dst) @@ -489,7 +498,8 @@ PayChanClaim::doApply() if (!sled) return tecNO_DST; - if (auto err = verifyDepositPreauth(ctx_.tx, ctx_.view(), txAccount, dst, sled, ctx_.journal); + if (auto err = + verifyDepositPreauth(ctx_.tx, ctx_.view(), txAccount, dst, sled, ctx_.journal); !isTesSuccess(err)) return err; @@ -513,10 +523,11 @@ PayChanClaim::doApply() { // Channel will close immediately if dry or the receiver closes if (dst == txAccount || (*slep)[sfBalance] == (*slep)[sfAmount]) - return closeChannel(slep, ctx_.view(), k.key, ctx_.app.journal("View")); + return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.journal("View")); auto const settleExpiration = - ctx_.view().header().parentCloseTime.time_since_epoch().count() + (*slep)[sfSettleDelay]; + ctx_.view().header().parentCloseTime.time_since_epoch().count() + + (*slep)[sfSettleDelay]; if (!curExpiration || *curExpiration > settleExpiration) { diff --git a/src/xrpld/app/tx/detail/Payment.cpp b/src/libxrpl/tx/transactors/Payment.cpp similarity index 91% rename from src/xrpld/app/tx/detail/Payment.cpp rename to src/libxrpl/tx/transactors/Payment.cpp index 390548b7ef..b98bbf11bd 100644 --- a/src/xrpld/app/tx/detail/Payment.cpp +++ b/src/libxrpl/tx/transactors/Payment.cpp @@ -1,8 +1,3 @@ -#include -#include -#include -#include - #include #include #include @@ -10,6 +5,10 @@ #include #include #include +#include +#include +#include +#include namespace xrpl { @@ -28,7 +27,10 @@ Payment::makeTxConsequences(PreflightContext const& ctx) } STAmount -getMaxSourceAmount(AccountID const& account, STAmount const& dstAmount, std::optional const& sendMax) +getMaxSourceAmount( + AccountID const& account, + STAmount const& dstAmount, + std::optional const& sendMax) { if (sendMax) return *sendMax; @@ -95,8 +97,9 @@ Payment::preflight(PreflightContext const& ctx) if ((mptDirect && dstAmount.asset() != maxSourceAmount.asset()) || (!mptDirect && maxSourceAmount.holds())) { - JLOG(j.trace()) << "Malformed transaction: inconsistent issues: " << dstAmount.getFullText() << " " - << maxSourceAmount.getFullText() << " " << deliverMin.value_or(STAmount{}).getFullText(); + JLOG(j.trace()) << "Malformed transaction: inconsistent issues: " << dstAmount.getFullText() + << " " << maxSourceAmount.getFullText() << " " + << deliverMin.value_or(STAmount{}).getFullText(); return temMALFORMED; } @@ -118,7 +121,8 @@ Payment::preflight(PreflightContext const& ctx) } if (hasMax && maxSourceAmount <= beast::zero) { - JLOG(j.trace()) << "Malformed transaction: bad max amount: " << maxSourceAmount.getFullText(); + JLOG(j.trace()) << "Malformed transaction: bad max amount: " + << maxSourceAmount.getFullText(); return temBAD_AMOUNT; } if (dstAmount <= beast::zero) @@ -136,8 +140,8 @@ Payment::preflight(PreflightContext const& ctx) // You're signing yourself a payment. // If hasPaths is true, you might be trying some arbitrage. JLOG(j.trace()) << "Malformed transaction: " - << "Redundant payment from " << to_string(account) << " to self without path for " - << to_string(dstAsset); + << "Redundant payment from " << to_string(account) + << " to self without path for " << to_string(dstAsset); return temREDUNDANT; } if (xrpDirect && hasMax) @@ -189,8 +193,8 @@ Payment::preflight(PreflightContext const& ctx) auto const dMin = *deliverMin; if (!isLegalNet(dMin) || dMin <= beast::zero) { - JLOG(j.trace()) << "Malformed transaction: Invalid " << jss::DeliverMin.c_str() << " amount. " - << dMin.getFullText(); + JLOG(j.trace()) << "Malformed transaction: Invalid " << jss::DeliverMin.c_str() + << " amount. " << dMin.getFullText(); return temBAD_AMOUNT; } if (dMin.asset() != dstAmount.asset()) @@ -202,8 +206,8 @@ Payment::preflight(PreflightContext const& ctx) } if (dMin > dstAmount) { - JLOG(j.trace()) << "Malformed transaction: Dst amount less than " << jss::DeliverMin.c_str() << ". " - << dMin.getFullText(); + JLOG(j.trace()) << "Malformed transaction: Dst amount less than " + << jss::DeliverMin.c_str() << ". " << dMin.getFullText(); return temBAD_AMOUNT; } } @@ -237,10 +241,12 @@ Payment::checkPermission(ReadView const& view, STTx const& tx) auto const& amountAsset = dstAmount.asset(); // Granular permissions are only valid for direct payments. - if ((tx.isFieldPresent(sfSendMax) && tx[sfSendMax].asset() != amountAsset) || tx.isFieldPresent(sfPaths)) + if ((tx.isFieldPresent(sfSendMax) && tx[sfSendMax].asset() != amountAsset) || + tx.isFieldPresent(sfPaths)) return terNO_DELEGATE_PERMISSION; - if (granularPermissions.contains(PaymentMint) && !isXRP(amountAsset) && amountAsset.getIssuer() == tx[sfAccount]) + if (granularPermissions.contains(PaymentMint) && !isXRP(amountAsset) && + amountAsset.getIssuer() == tx[sfAccount]) return tesSUCCESS; if (granularPermissions.contains(PaymentBurn) && !isXRP(amountAsset) && @@ -318,13 +324,16 @@ Payment::preclaim(PreclaimContext const& ctx) STPathSet const& paths = ctx.tx.getFieldPathSet(sfPaths); if (paths.size() > MaxPathSize || - std::any_of(paths.begin(), paths.end(), [](STPath const& path) { return path.size() > MaxPathLength; })) + std::any_of(paths.begin(), paths.end(), [](STPath const& path) { + return path.size() > MaxPathLength; + })) { return telBAD_PATH_COUNT; } } - if (auto const err = credentials::valid(ctx.tx, ctx.view, ctx.tx[sfAccount], ctx.j); !isTesSuccess(err)) + if (auto const err = credentials::valid(ctx.tx, ctx.view, ctx.tx[sfAccount], ctx.j); + !isTesSuccess(err)) return err; if (ctx.tx.isFieldPresent(sfDomainID)) @@ -357,7 +366,8 @@ Payment::doApply() bool const mptDirect = dstAmount.holds(); STAmount const maxSourceAmount = getMaxSourceAmount(account_, dstAmount, sendMax); - JLOG(j_.trace()) << "maxSourceAmount=" << maxSourceAmount.getFullText() << " dstAmount=" << dstAmount.getFullText(); + JLOG(j_.trace()) << "maxSourceAmount=" << maxSourceAmount.getFullText() + << " dstAmount=" << dstAmount.getFullText(); // Open a ledger for editing. auto const k = keylet::account(dstAccountID); @@ -392,7 +402,8 @@ Payment::doApply() // 1. If Account == Destination, or // 2. If Account is deposit preauthorized by destination. - if (auto err = verifyDepositPreauth(ctx_.tx, ctx_.view(), account_, dstAccountID, sleDst, ctx_.journal); + if (auto err = verifyDepositPreauth( + ctx_.tx, ctx_.view(), account_, dstAccountID, sleDst, ctx_.journal); !isTesSuccess(err)) return err; @@ -414,7 +425,7 @@ Payment::doApply() account_, ctx_.tx.getFieldPathSet(sfPaths), ctx_.tx[~sfDomainID], - ctx_.app.logs(), + ctx_.registry.logs(), &rcInput); // VFALCO NOTE We might not need to apply, depending // on the TER. But always applying *should* @@ -453,10 +464,12 @@ Payment::doApply() if (auto const ter = requireAuth(view(), mptIssue, dstAccountID); ter != tesSUCCESS) return ter; - if (auto const ter = canTransfer(view(), mptIssue, account_, dstAccountID); ter != tesSUCCESS) + if (auto const ter = canTransfer(view(), mptIssue, account_, dstAccountID); + ter != tesSUCCESS) return ter; - if (auto err = verifyDepositPreauth(ctx_.tx, ctx_.view(), account_, dstAccountID, sleDst, ctx_.journal); + if (auto err = verifyDepositPreauth( + ctx_.tx, ctx_.view(), account_, dstAccountID, sleDst, ctx_.journal); !isTesSuccess(err)) return err; @@ -494,7 +507,8 @@ Payment::doApply() amountDeliver = divide(maxSourceAmount, rate); } - if (requiredMaxSourceAmount > maxSourceAmount || (deliverMin && amountDeliver < *deliverMin)) + if (requiredMaxSourceAmount > maxSourceAmount || + (deliverMin && amountDeliver < *deliverMin)) return tecPATH_PARTIAL; PaymentSandbox pv(&view()); @@ -539,8 +553,9 @@ Payment::doApply() { // Vote no. However the transaction might succeed, if applied in // a different order. - JLOG(j_.trace()) << "Delay transaction: Insufficient funds: " << to_string(mPriorBalance) << " / " - << to_string(dstAmount.xrp() + mmm) << " (" << to_string(reserve) << ")"; + JLOG(j_.trace()) << "Delay transaction: Insufficient funds: " << to_string(mPriorBalance) + << " / " << to_string(dstAmount.xrp() + mmm) << " (" << to_string(reserve) + << ")"; return tecUNFUNDED_PAYMENT; } @@ -579,7 +594,8 @@ Payment::doApply() if (dstAmount > dstReserve || sleDst->getFieldAmount(sfBalance) > dstReserve) { - if (auto err = verifyDepositPreauth(ctx_.tx, ctx_.view(), account_, dstAccountID, sleDst, ctx_.journal); + if (auto err = verifyDepositPreauth( + ctx_.tx, ctx_.view(), account_, dstAccountID, sleDst, ctx_.journal); !isTesSuccess(err)) return err; } diff --git a/src/xrpld/app/misc/PermissionedDEXHelpers.cpp b/src/libxrpl/tx/transactors/PermissionedDomain/PermissionedDEXHelpers.cpp similarity index 69% rename from src/xrpld/app/misc/PermissionedDEXHelpers.cpp rename to src/libxrpl/tx/transactors/PermissionedDomain/PermissionedDEXHelpers.cpp index f88c2ab9d4..7a4fa62078 100644 --- a/src/xrpld/app/misc/PermissionedDEXHelpers.cpp +++ b/src/libxrpl/tx/transactors/PermissionedDomain/PermissionedDEXHelpers.cpp @@ -1,6 +1,5 @@ -#include - #include +#include namespace xrpl { namespace permissioned_dex { @@ -18,19 +17,25 @@ accountInDomain(ReadView const& view, AccountID const& account, Domain const& do auto const& credentials = sleDomain->getFieldArray(sfAcceptedCredentials); - bool const inDomain = std::any_of(credentials.begin(), credentials.end(), [&](auto const& credential) { - auto const sleCred = view.read(keylet::credential(account, credential[sfIssuer], credential[sfCredentialType])); - if (!sleCred || !sleCred->isFlag(lsfAccepted)) - return false; + bool const inDomain = + std::any_of(credentials.begin(), credentials.end(), [&](auto const& credential) { + auto const sleCred = view.read( + keylet::credential(account, credential[sfIssuer], credential[sfCredentialType])); + if (!sleCred || !sleCred->isFlag(lsfAccepted)) + return false; - return !credentials::checkExpired(sleCred, view.header().parentCloseTime); - }); + return !credentials::checkExpired(sleCred, view.header().parentCloseTime); + }); return inDomain; } bool -offerInDomain(ReadView const& view, uint256 const& offerID, Domain const& domainID, beast::Journal j) +offerInDomain( + ReadView const& view, + uint256 const& offerID, + Domain const& domainID, + beast::Journal j) { auto const sleOffer = view.read(keylet::offer(offerID)); diff --git a/src/xrpld/app/tx/detail/PermissionedDomainDelete.cpp b/src/libxrpl/tx/transactors/PermissionedDomain/PermissionedDomainDelete.cpp similarity index 88% rename from src/xrpld/app/tx/detail/PermissionedDomainDelete.cpp rename to src/libxrpl/tx/transactors/PermissionedDomain/PermissionedDomainDelete.cpp index f979637e27..e013bd8d2b 100644 --- a/src/xrpld/app/tx/detail/PermissionedDomainDelete.cpp +++ b/src/libxrpl/tx/transactors/PermissionedDomain/PermissionedDomainDelete.cpp @@ -1,7 +1,6 @@ -#include - #include #include +#include namespace xrpl { @@ -37,7 +36,9 @@ PermissionedDomainDelete::preclaim(PreclaimContext const& ctx) TER PermissionedDomainDelete::doApply() { - XRPL_ASSERT(ctx_.tx.isFieldPresent(sfDomainID), "xrpl::PermissionedDomainDelete::doApply : required field present"); + XRPL_ASSERT( + ctx_.tx.isFieldPresent(sfDomainID), + "xrpl::PermissionedDomainDelete::doApply : required field present"); auto const slePd = view().peek({ltPERMISSIONED_DOMAIN, ctx_.tx.at(sfDomainID)}); auto const page = (*slePd)[sfOwnerNode]; diff --git a/src/xrpld/app/tx/detail/PermissionedDomainSet.cpp b/src/libxrpl/tx/transactors/PermissionedDomain/PermissionedDomainSet.cpp similarity index 82% rename from src/xrpld/app/tx/detail/PermissionedDomainSet.cpp rename to src/libxrpl/tx/transactors/PermissionedDomain/PermissionedDomainSet.cpp index 19f68426d1..51ff4d8217 100644 --- a/src/xrpld/app/tx/detail/PermissionedDomainSet.cpp +++ b/src/libxrpl/tx/transactors/PermissionedDomain/PermissionedDomainSet.cpp @@ -1,9 +1,8 @@ -#include - #include #include #include #include +#include #include @@ -19,7 +18,9 @@ NotTEC PermissionedDomainSet::preflight(PreflightContext const& ctx) { if (auto err = credentials::checkArray( - ctx.tx.getFieldArray(sfAcceptedCredentials), maxPermissionedDomainCredentialsArraySize, ctx.j); + ctx.tx.getFieldArray(sfAcceptedCredentials), + maxPermissionedDomainCredentialsArraySize, + ctx.j); !isTesSuccess(err)) return err; @@ -47,7 +48,8 @@ PermissionedDomainSet::preclaim(PreclaimContext const& ctx) if (ctx.tx.isFieldPresent(sfDomainID)) { - auto const sleDomain = ctx.view.read(keylet::permissionedDomain(ctx.tx.getFieldH256(sfDomainID))); + auto const sleDomain = + ctx.view.read(keylet::permissionedDomain(ctx.tx.getFieldH256(sfDomainID))); if (!sleDomain) return tecNO_ENTRY; if (sleDomain->getAccountID(sfOwner) != account) @@ -65,7 +67,8 @@ PermissionedDomainSet::doApply() if (!ownerSle) return tefINTERNAL; // LCOV_EXCL_LINE - auto const sortedTxCredentials = credentials::makeSorted(ctx_.tx.getFieldArray(sfAcceptedCredentials)); + auto const sortedTxCredentials = + credentials::makeSorted(ctx_.tx.getFieldArray(sfAcceptedCredentials)); STArray sortedLE(sfAcceptedCredentials, sortedTxCredentials.size()); for (auto const& p : sortedTxCredentials) { @@ -93,7 +96,8 @@ PermissionedDomainSet::doApply() if (balance < reserve) return tecINSUFFICIENT_RESERVE; - Keylet const pdKeylet = keylet::permissionedDomain(account_, ctx_.tx.getFieldU32(sfSequence)); + Keylet const pdKeylet = + keylet::permissionedDomain(account_, ctx_.tx.getFieldU32(sfSequence)); auto slePd = std::make_shared(pdKeylet); if (!slePd) return tefINTERNAL; // LCOV_EXCL_LINE @@ -101,7 +105,8 @@ PermissionedDomainSet::doApply() slePd->setAccountID(sfOwner, account_); slePd->setFieldU32(sfSequence, ctx_.tx.getFieldU32(sfSequence)); slePd->peekFieldArray(sfAcceptedCredentials) = std::move(sortedLE); - auto const page = view().dirInsert(keylet::ownerDir(account_), pdKeylet, describeOwnerDir(account_)); + auto const page = + view().dirInsert(keylet::ownerDir(account_), pdKeylet, describeOwnerDir(account_)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE diff --git a/src/xrpld/app/tx/detail/SetAccount.cpp b/src/libxrpl/tx/transactors/SetAccount.cpp similarity index 97% rename from src/xrpld/app/tx/detail/SetAccount.cpp rename to src/libxrpl/tx/transactors/SetAccount.cpp index beca60c06b..64b52d12d5 100644 --- a/src/xrpld/app/tx/detail/SetAccount.cpp +++ b/src/libxrpl/tx/transactors/SetAccount.cpp @@ -1,7 +1,3 @@ -#include -#include -#include - #include #include #include @@ -9,6 +5,8 @@ #include #include #include +#include +#include namespace xrpl { @@ -18,15 +16,18 @@ SetAccount::makeTxConsequences(PreflightContext const& ctx) // The SetAccount may be a blocker, but only if it sets or clears // specific account flags. auto getTxConsequencesCategory = [](STTx const& tx) { - if (std::uint32_t const uTxFlags = tx.getFlags(); uTxFlags & (tfRequireAuth | tfOptionalAuth)) + if (std::uint32_t const uTxFlags = tx.getFlags(); + uTxFlags & (tfRequireAuth | tfOptionalAuth)) return TxConsequences::blocker; - if (auto const uSetFlag = tx[~sfSetFlag]; - uSetFlag && (*uSetFlag == asfRequireAuth || *uSetFlag == asfDisableMaster || *uSetFlag == asfAccountTxnID)) + if (auto const uSetFlag = tx[~sfSetFlag]; uSetFlag && + (*uSetFlag == asfRequireAuth || *uSetFlag == asfDisableMaster || + *uSetFlag == asfAccountTxnID)) return TxConsequences::blocker; if (auto const uClearFlag = tx[~sfClearFlag]; uClearFlag && - (*uClearFlag == asfRequireAuth || *uClearFlag == asfDisableMaster || *uClearFlag == asfAccountTxnID)) + (*uClearFlag == asfRequireAuth || *uClearFlag == asfDisableMaster || + *uClearFlag == asfAccountTxnID)) return TxConsequences::blocker; return TxConsequences::normal; @@ -407,7 +408,8 @@ SetAccount::doApply() // If you have set NoFreeze, you may not clear GlobalFreeze // This prevents those who have set NoFreeze from using // GlobalFreeze strategically. - if ((uSetFlag != asfGlobalFreeze) && (uClearFlag == asfGlobalFreeze) && ((uFlagsOut & lsfNoFreeze) == 0)) + if ((uSetFlag != asfGlobalFreeze) && (uClearFlag == asfGlobalFreeze) && + ((uFlagsOut & lsfNoFreeze) == 0)) { JLOG(j_.trace()) << "Clear GlobalFreeze flag"; uFlagsOut &= ~lsfGlobalFreeze; diff --git a/src/xrpld/app/tx/detail/SetOracle.cpp b/src/libxrpl/tx/transactors/SetOracle.cpp similarity index 90% rename from src/xrpld/app/tx/detail/SetOracle.cpp rename to src/libxrpl/tx/transactors/SetOracle.cpp index 73ef1c7ae2..140938e2d7 100644 --- a/src/xrpld/app/tx/detail/SetOracle.cpp +++ b/src/libxrpl/tx/transactors/SetOracle.cpp @@ -1,11 +1,10 @@ -#include - #include #include #include #include #include #include +#include namespace xrpl { @@ -13,7 +12,8 @@ static inline std::pair tokenPairKey(STObject const& pair) { return std::make_pair( - pair.getFieldCurrency(sfBaseAsset).currency(), pair.getFieldCurrency(sfQuoteAsset).currency()); + pair.getFieldCurrency(sfBaseAsset).currency(), + pair.getFieldCurrency(sfQuoteAsset).currency()); } NotTEC @@ -26,7 +26,8 @@ SetOracle::preflight(PreflightContext const& ctx) return temARRAY_TOO_LARGE; auto isInvalidLength = [&](auto const& sField, std::size_t length) { - return ctx.tx.isFieldPresent(sField) && (ctx.tx[sField].length() == 0 || ctx.tx[sField].length() > length); + return ctx.tx.isFieldPresent(sField) && + (ctx.tx[sField].length() == 0 || ctx.tx[sField].length() > length); }; if (isInvalidLength(sfProvider, maxOracleProvider) || isInvalidLength(sfURI, maxOracleURI) || @@ -46,7 +47,8 @@ SetOracle::preclaim(PreclaimContext const& ctx) // lastUpdateTime must be within maxLastUpdateTimeDelta seconds // of the last closed ledger using namespace std::chrono; - std::size_t const closeTime = duration_cast(ctx.view.header().closeTime.time_since_epoch()).count(); + std::size_t const closeTime = + duration_cast(ctx.view.header().closeTime.time_since_epoch()).count(); std::size_t const lastUpdateTime = ctx.tx[sfLastUpdateTime]; if (lastUpdateTime < epoch_offset.count()) return tecINVALID_UPDATE_TIME; @@ -57,7 +59,8 @@ SetOracle::preclaim(PreclaimContext const& ctx) lastUpdateTimeEpoch > (closeTime + maxLastUpdateTimeDelta)) return tecINVALID_UPDATE_TIME; - auto const sle = ctx.view.read(keylet::oracle(ctx.tx.getAccountID(sfAccount), ctx.tx[sfOracleDocumentID])); + auto const sle = + ctx.view.read(keylet::oracle(ctx.tx.getAccountID(sfAccount), ctx.tx[sfOracleDocumentID])); // token pairs to add/update std::set> pairs; @@ -134,7 +137,8 @@ SetOracle::preclaim(PreclaimContext const& ctx) if (pairs.size() > maxOracleDataSeries) return tecARRAY_TOO_LARGE; - auto const reserve = ctx.view.fees().accountReserve(sleSetter->getFieldU32(sfOwnerCount) + adjustReserve); + auto const reserve = + ctx.view.fees().accountReserve(sleSetter->getFieldU32(sfOwnerCount) + adjustReserve); auto const& balance = sleSetter->getFieldAmount(sfBalance); if (balance < reserve) @@ -158,7 +162,8 @@ adjustOwnerCount(ApplyContext& ctx, int count) static void setPriceDataInnerObjTemplate(STObject& obj) { - if (SOTemplate const* elements = InnerObjectFormats::getInstance().findSOTemplateBySField(sfPriceData)) + if (SOTemplate const* elements = + InnerObjectFormats::getInstance().findSOTemplateBySField(sfPriceData)) obj.set(*elements); } @@ -224,7 +229,8 @@ SetOracle::doApply() if (ctx_.tx.isFieldPresent(sfURI)) sle->setFieldVL(sfURI, ctx_.tx[sfURI]); sle->setFieldU32(sfLastUpdateTime, ctx_.tx[sfLastUpdateTime]); - if (!sle->isFieldPresent(sfOracleDocumentID) && ctx_.view().rules().enabled(fixIncludeKeyletFields)) + if (!sle->isFieldPresent(sfOracleDocumentID) && + ctx_.view().rules().enabled(fixIncludeKeyletFields)) { (*sle)[sfOracleDocumentID] = ctx_.tx[sfOracleDocumentID]; } @@ -273,7 +279,8 @@ SetOracle::doApply() sle->setFieldVL(sfAssetClass, ctx_.tx[sfAssetClass]); sle->setFieldU32(sfLastUpdateTime, ctx_.tx[sfLastUpdateTime]); - auto page = ctx_.view().dirInsert(keylet::ownerDir(account_), sle->key(), describeOwnerDir(account_)); + auto page = ctx_.view().dirInsert( + keylet::ownerDir(account_), sle->key(), describeOwnerDir(account_)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE diff --git a/src/xrpld/app/tx/detail/SetRegularKey.cpp b/src/libxrpl/tx/transactors/SetRegularKey.cpp similarity index 85% rename from src/xrpld/app/tx/detail/SetRegularKey.cpp rename to src/libxrpl/tx/transactors/SetRegularKey.cpp index 14302c67c4..e26e6b1bd5 100644 --- a/src/xrpld/app/tx/detail/SetRegularKey.cpp +++ b/src/libxrpl/tx/transactors/SetRegularKey.cpp @@ -1,8 +1,7 @@ -#include - #include #include #include +#include namespace xrpl { @@ -32,7 +31,8 @@ SetRegularKey::calculateBaseFee(ReadView const& view, STTx const& tx) NotTEC SetRegularKey::preflight(PreflightContext const& ctx) { - if (ctx.tx.isFieldPresent(sfRegularKey) && (ctx.tx.getAccountID(sfRegularKey) == ctx.tx.getAccountID(sfAccount))) + if (ctx.tx.isFieldPresent(sfRegularKey) && + (ctx.tx.getAccountID(sfRegularKey) == ctx.tx.getAccountID(sfAccount))) { return temBAD_REGKEY; } @@ -47,7 +47,7 @@ SetRegularKey::doApply() if (!sle) return tefINTERNAL; // LCOV_EXCL_LINE - if (!minimumFee(ctx_.app, ctx_.baseFee, view().fees(), view().flags())) + if (!minimumFee(ctx_.registry, ctx_.baseFee, view().fees(), view().flags())) sle->setFlag(lsfPasswordSpent); if (ctx_.tx.isFieldPresent(sfRegularKey)) diff --git a/src/xrpld/app/tx/detail/SetSignerList.cpp b/src/libxrpl/tx/transactors/SetSignerList.cpp similarity index 87% rename from src/xrpld/app/tx/detail/SetSignerList.cpp rename to src/libxrpl/tx/transactors/SetSignerList.cpp index 1864e82b99..858fb33bff 100644 --- a/src/xrpld/app/tx/detail/SetSignerList.cpp +++ b/src/libxrpl/tx/transactors/SetSignerList.cpp @@ -1,14 +1,13 @@ -#include -#include - #include #include +#include #include #include #include #include #include #include +#include #include #include @@ -77,8 +76,8 @@ SetSignerList::preflight(PreflightContext const& ctx) { // Validate our settings. auto const account = ctx.tx.getAccountID(sfAccount); - NotTEC const ter = - validateQuorumAndSignerEntries(std::get<1>(result), std::get<2>(result), account, ctx.j, ctx.rules); + NotTEC const ter = validateQuorumAndSignerEntries( + std::get<1>(result), std::get<2>(result), account, ctx.j, ctx.rules); if (ter != tesSUCCESS) { return ter; @@ -114,8 +113,12 @@ SetSignerList::preCompute() { // Get the quorum and operation info. auto result = determineOperation(ctx_.tx, view().flags(), j_); - XRPL_ASSERT(std::get<0>(result) == tesSUCCESS, "xrpl::SetSignerList::preCompute : result is tesSUCCESS"); - XRPL_ASSERT(std::get<3>(result) != unknown, "xrpl::SetSignerList::preCompute : result is known operation"); + XRPL_ASSERT( + std::get<0>(result) == tesSUCCESS, + "xrpl::SetSignerList::preCompute : result is tesSUCCESS"); + XRPL_ASSERT( + std::get<3>(result) != unknown, + "xrpl::SetSignerList::preCompute : result is known operation"); quorum_ = std::get<1>(result); signers_ = std::get<2>(result); @@ -144,14 +147,18 @@ signerCountBasedOwnerCountDelta(std::size_t entryCount, Rules const& rules) // The static_cast should always be safe since entryCount should always // be in the range from 1 to 32. // We've got a lot of room to grow. - XRPL_ASSERT(entryCount >= STTx::minMultiSigners, "xrpl::signerCountBasedOwnerCountDelta : minimum signers"); - XRPL_ASSERT(entryCount <= STTx::maxMultiSigners, "xrpl::signerCountBasedOwnerCountDelta : maximum signers"); + XRPL_ASSERT( + entryCount >= STTx::minMultiSigners, + "xrpl::signerCountBasedOwnerCountDelta : minimum signers"); + XRPL_ASSERT( + entryCount <= STTx::maxMultiSigners, + "xrpl::signerCountBasedOwnerCountDelta : maximum signers"); return 2 + static_cast(entryCount); } static TER removeSignersFromLedger( - Application& app, + ServiceRegistry& registry, ApplyView& view, Keylet const& accountKeylet, Keylet const& ownerDirKeylet, @@ -173,7 +180,8 @@ removeSignersFromLedger( if ((signers->getFlags() & lsfOneOwnerCount) == 0) { STArray const& actualList = signers->getFieldArray(sfSignerEntries); - removeFromOwnerCount = signerCountBasedOwnerCountDelta(actualList.size(), view.rules()) * -1; + removeFromOwnerCount = + signerCountBasedOwnerCountDelta(actualList.size(), view.rules()) * -1; } // Remove the node from the account directory. @@ -187,7 +195,8 @@ removeSignersFromLedger( // LCOV_EXCL_STOP } - adjustOwnerCount(view, view.peek(accountKeylet), removeFromOwnerCount, app.journal("View")); + adjustOwnerCount( + view, view.peek(accountKeylet), removeFromOwnerCount, registry.journal("View")); view.erase(signers); @@ -195,13 +204,18 @@ removeSignersFromLedger( } TER -SetSignerList::removeFromLedger(Application& app, ApplyView& view, AccountID const& account, beast::Journal j) +SetSignerList::removeFromLedger( + ServiceRegistry& registry, + ApplyView& view, + AccountID const& account, + beast::Journal j) { auto const accountKeylet = keylet::account(account); auto const ownerDirKeylet = keylet::ownerDir(account); auto const signerListKeylet = keylet::signers(account); - return removeSignersFromLedger(app, view, accountKeylet, ownerDirKeylet, signerListKeylet, j); + return removeSignersFromLedger( + registry, view, accountKeylet, ownerDirKeylet, signerListKeylet, j); } NotTEC @@ -273,7 +287,8 @@ SetSignerList::replaceSignerList() // This may be either a create or a replace. Preemptively remove any // old signer list. May reduce the reserve, so this is done before // checking the reserve. - if (TER const ter = removeSignersFromLedger(ctx_.app, view(), accountKeylet, ownerDirKeylet, signerListKeylet, j_)) + if (TER const ter = removeSignersFromLedger( + ctx_.registry, view(), accountKeylet, ownerDirKeylet, signerListKeylet, j_)) return ter; auto const sle = view().peek(accountKeylet); @@ -299,9 +314,10 @@ SetSignerList::replaceSignerList() view().insert(signerList); writeSignersToSLE(signerList, flags); - auto viewJ = ctx_.app.journal("View"); + auto viewJ = ctx_.registry.journal("View"); // Add the signer list to the account's directory. - auto const page = ctx_.view().dirInsert(ownerDirKeylet, signerListKeylet, describeOwnerDir(account_)); + auto const page = + ctx_.view().dirInsert(ownerDirKeylet, signerListKeylet, describeOwnerDir(account_)); JLOG(j_.trace()) << "Create signer list for account " << toBase58(account_) << ": " << (page ? "success" : "failure"); @@ -332,7 +348,8 @@ SetSignerList::destroySignerList() auto const ownerDirKeylet = keylet::ownerDir(account_); auto const signerListKeylet = keylet::signers(account_); - return removeSignersFromLedger(ctx_.app, view(), accountKeylet, ownerDirKeylet, signerListKeylet, j_); + return removeSignersFromLedger( + ctx_.registry, view(), accountKeylet, ownerDirKeylet, signerListKeylet, j_); } void diff --git a/src/xrpld/app/tx/detail/SetTrust.cpp b/src/libxrpl/tx/transactors/SetTrust.cpp similarity index 94% rename from src/xrpld/app/tx/detail/SetTrust.cpp rename to src/libxrpl/tx/transactors/SetTrust.cpp index ce8ca05a09..268d626432 100644 --- a/src/xrpld/app/tx/detail/SetTrust.cpp +++ b/src/libxrpl/tx/transactors/SetTrust.cpp @@ -1,6 +1,3 @@ -#include -#include - #include #include #include @@ -9,6 +6,8 @@ #include #include #include +#include +#include namespace { @@ -77,7 +76,8 @@ SetTrust::preflight(PreflightContext const& ctx) if (saLimitAmount.native()) { - JLOG(j.trace()) << "Malformed transaction: specifies native limit " << saLimitAmount.getFullText(); + JLOG(j.trace()) << "Malformed transaction: specifies native limit " + << saLimitAmount.getFullText(); return temBAD_LIMIT; } @@ -133,8 +133,8 @@ SetTrust::checkPermission(ReadView const& view, STTx const& tx) return terNO_DELEGATE_PERMISSION; auto const saLimitAmount = tx.getFieldAmount(sfLimitAmount); - auto const sleRippleState = - view.read(keylet::line(tx[sfAccount], saLimitAmount.getIssuer(), saLimitAmount.getCurrency())); + auto const sleRippleState = view.read( + keylet::line(tx[sfAccount], saLimitAmount.getIssuer(), saLimitAmount.getCurrency())); // if the trustline does not exist, granular permissions are // not allowed to create trustline @@ -153,8 +153,9 @@ SetTrust::checkPermission(ReadView const& view, STTx const& tx) // updating LimitAmount is not allowed only with granular permissions, // unless there's a new granular permission for this in the future. - auto const curLimit = tx[sfAccount] > saLimitAmount.getIssuer() ? sleRippleState->getFieldAmount(sfHighLimit) - : sleRippleState->getFieldAmount(sfLowLimit); + auto const curLimit = tx[sfAccount] > saLimitAmount.getIssuer() + ? sleRippleState->getFieldAmount(sfHighLimit) + : sleRippleState->getFieldAmount(sfLowLimit); STAmount saLimitAllow = saLimitAmount; saLimitAllow.setIssuer(tx[sfAccount]); @@ -194,7 +195,8 @@ SetTrust::preclaim(PreclaimContext const& ctx) // This might be nullptr auto const sleDst = ctx.view.read(keylet::account(uDstAccountID)); - if ((ammEnabled(ctx.view.rules()) || ctx.view.rules().enabled(featureSingleAssetVault)) && sleDst == nullptr) + if ((ammEnabled(ctx.view.rules()) || ctx.view.rules().enabled(featureSingleAssetVault)) && + sleDst == nullptr) return tecNO_DST; // If the destination has opted to disallow incoming trustlines @@ -231,7 +233,8 @@ SetTrust::preclaim(PreclaimContext const& ctx) } else if (auto const ammSle = ctx.view.read({ltAMM, sleDst->getFieldH256(sfAMMID)})) { - if (auto const lpTokens = ammSle->getFieldAmount(sfLPTokenBalance); lpTokens == beast::zero) + if (auto const lpTokens = ammSle->getFieldAmount(sfLPTokenBalance); + lpTokens == beast::zero) return tecAMM_EMPTY; else if (lpTokens.getCurrency() != saLimitAmount.getCurrency()) return tecNO_PERMISSION; @@ -276,8 +279,8 @@ SetTrust::preclaim(PreclaimContext const& ctx) auto const sleRippleState = ctx.view.read(keylet::line(id, uDstAccountID, currency)); std::uint32_t uFlags = sleRippleState ? sleRippleState->getFieldU32(sfFlags) : 0u; // Computing expected trust line state - uFlags = - computeFreezeFlags(uFlags, bHigh, bNoFreeze, bSetFreeze, bClearFreeze, bSetDeepFreeze, bClearDeepFreeze); + uFlags = computeFreezeFlags( + uFlags, bHigh, bNoFreeze, bSetFreeze, bClearFreeze, bSetDeepFreeze, bClearDeepFreeze); auto const frozen = uFlags & (bHigh ? lsfHighFreeze : lsfLowFreeze); auto const deepFrozen = uFlags & (bHigh ? lsfHighDeepFreeze : lsfLowDeepFreeze); @@ -352,7 +355,7 @@ SetTrust::doApply() bool const bSetDeepFreeze = (uTxFlags & tfSetDeepFreeze); bool const bClearDeepFreeze = (uTxFlags & tfClearDeepFreeze); - auto viewJ = ctx_.app.journal("View"); + auto viewJ = ctx_.registry.journal("View"); SLE::pointer sleDst = view().peek(keylet::account(uDstAccountID)); @@ -483,8 +486,14 @@ SetTrust::doApply() // Have to use lsfNoFreeze to maintain pre-deep freeze behavior bool const bNoFreeze = sle->isFlag(lsfNoFreeze); - uFlagsOut = - computeFreezeFlags(uFlagsOut, bHigh, bNoFreeze, bSetFreeze, bClearFreeze, bSetDeepFreeze, bClearDeepFreeze); + uFlagsOut = computeFreezeFlags( + uFlagsOut, + bHigh, + bNoFreeze, + bSetFreeze, + bClearFreeze, + bSetDeepFreeze, + bClearDeepFreeze); if (QUALITY_ONE == uLowQualityOut) uLowQualityOut = 0; @@ -496,13 +505,13 @@ SetTrust::doApply() bool const bHighDefRipple = sleHighAccount->getFlags() & lsfDefaultRipple; bool const bLowReserveSet = uLowQualityIn || uLowQualityOut || - ((uFlagsOut & lsfLowNoRipple) == 0) != bLowDefRipple || (uFlagsOut & lsfLowFreeze) || saLowLimit || - saLowBalance > beast::zero; + ((uFlagsOut & lsfLowNoRipple) == 0) != bLowDefRipple || (uFlagsOut & lsfLowFreeze) || + saLowLimit || saLowBalance > beast::zero; bool const bLowReserveClear = !bLowReserveSet; bool const bHighReserveSet = uHighQualityIn || uHighQualityOut || - ((uFlagsOut & lsfHighNoRipple) == 0) != bHighDefRipple || (uFlagsOut & lsfHighFreeze) || saHighLimit || - saHighBalance > beast::zero; + ((uFlagsOut & lsfHighNoRipple) == 0) != bHighDefRipple || (uFlagsOut & lsfHighFreeze) || + saHighLimit || saHighBalance > beast::zero; bool const bHighReserveClear = !bHighReserveSet; bool const bDefault = bLowReserveClear && bHighReserveClear; diff --git a/src/xrpld/app/tx/detail/VaultClawback.cpp b/src/libxrpl/tx/transactors/Vault/VaultClawback.cpp similarity index 89% rename from src/xrpld/app/tx/detail/VaultClawback.cpp rename to src/libxrpl/tx/transactors/Vault/VaultClawback.cpp index 5aa63fac1a..bce53c706d 100644 --- a/src/xrpld/app/tx/detail/VaultClawback.cpp +++ b/src/libxrpl/tx/transactors/Vault/VaultClawback.cpp @@ -1,5 +1,3 @@ -#include -// #include #include #include @@ -9,6 +7,8 @@ #include #include #include +#include +#include #include @@ -115,7 +115,12 @@ VaultClawback::preclaim(PreclaimContext const& ctx) if (amount != beast::zero) { Number const& sharesHeld = accountHolds( - ctx.view, holder, share, FreezeHandling::fhIGNORE_FREEZE, AuthHandling::ahIGNORE_AUTH, ctx.j); + ctx.view, + holder, + share, + FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, + ctx.j); // The VaultOwner must burn all shares if (amount != sharesHeld) @@ -219,8 +224,13 @@ VaultClawback::assetsToClawback( if (clawbackAmount == beast::zero) { - auto const sharesDestroyed = - accountHolds(view(), holder, share, FreezeHandling::fhIGNORE_FREEZE, AuthHandling::ahIGNORE_AUTH, j_); + auto const sharesDestroyed = accountHolds( + view(), + holder, + share, + FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, + j_); auto const maybeAssets = sharesToAssetsWithdraw(vault, sleShareIssuance, sharesDestroyed); if (!maybeAssets) return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE @@ -233,7 +243,8 @@ VaultClawback::assetsToClawback( try { { - auto const maybeShares = assetsToSharesWithdraw(vault, sleShareIssuance, assetsRecovered); + auto const maybeShares = + assetsToSharesWithdraw(vault, sleShareIssuance, assetsRecovered); if (!maybeShares) return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE sharesDestroyed = *maybeShares; @@ -252,14 +263,15 @@ VaultClawback::assetsToClawback( // otherwise the corresponding assets might breach the // AssetsAvailable { - auto const maybeShares = - assetsToSharesWithdraw(vault, sleShareIssuance, assetsRecovered, TruncateShares::yes); + auto const maybeShares = assetsToSharesWithdraw( + vault, sleShareIssuance, assetsRecovered, TruncateShares::yes); if (!maybeShares) return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE sharesDestroyed = *maybeShares; } - auto const maybeAssets = sharesToAssetsWithdraw(vault, sleShareIssuance, sharesDestroyed); + auto const maybeAssets = + sharesToAssetsWithdraw(vault, sleShareIssuance, sharesDestroyed); if (!maybeAssets) return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE assetsRecovered = *maybeAssets; @@ -280,7 +292,8 @@ VaultClawback::assetsToClawback( << "VaultClawback: overflow error with" << " scale=" << (int)vault->at(sfScale).value() // << ", assetsTotal=" << vault->at(sfAssetsTotal).value() - << ", sharesTotal=" << sleShareIssuance->at(sfOutstandingAmount) << ", amount=" << clawbackAmount.value(); + << ", sharesTotal=" << sleShareIssuance->at(sfOutstandingAmount) + << ", amount=" << clawbackAmount.value(); return Unexpected(tecPATH_DRY); } @@ -314,7 +327,8 @@ VaultClawback::doApply() [[maybe_unused]] auto const lossUnrealized = vault->at(sfLossUnrealized); XRPL_ASSERT( - lossUnrealized <= (assetsTotal - assetsAvailable), "xrpl::VaultClawback::doApply : loss and assets do balance"); + lossUnrealized <= (assetsTotal - assetsAvailable), + "xrpl::VaultClawback::doApply : loss and assets do balance"); AccountID holder = tx[sfHolder]; STAmount sharesDestroyed = {share}; @@ -323,8 +337,13 @@ VaultClawback::doApply() // The Owner is burning shares if (account_ == vault->at(sfOwner) && amount.asset() == share) { - sharesDestroyed = - accountHolds(view(), holder, share, FreezeHandling::fhIGNORE_FREEZE, AuthHandling::ahIGNORE_AUTH, j_); + sharesDestroyed = accountHolds( + view(), + holder, + share, + FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, + j_); } else // The Issuer is clawbacking vault assets { @@ -347,7 +366,8 @@ VaultClawback::doApply() auto const& vaultAccount = vault->at(sfAccount); // Transfer shares from holder to vault. - if (auto const ter = accountSend(view(), holder, vaultAccount, sharesDestroyed, j_, WaiveTransferFee::Yes); + if (auto const ter = + accountSend(view(), holder, vaultAccount, sharesDestroyed, j_, WaiveTransferFee::Yes); !isTesSuccess(ter)) return ter; @@ -356,7 +376,8 @@ VaultClawback::doApply() // Keep MPToken if holder is the vault owner. if (holder != vault->at(sfOwner)) { - if (auto const ter = removeEmptyHolding(view(), holder, sharesDestroyed.asset(), j_); isTesSuccess(ter)) + if (auto const ter = removeEmptyHolding(view(), holder, sharesDestroyed.asset(), j_); + isTesSuccess(ter)) { JLOG(j_.debug()) // << "VaultClawback: removed empty MPToken for vault shares" @@ -380,7 +401,8 @@ VaultClawback::doApply() if (assetsRecovered > beast::zero) { // Transfer assets from vault to issuer. - if (auto const ter = accountSend(view(), vaultAccount, account_, assetsRecovered, j_, WaiveTransferFee::Yes); + if (auto const ter = accountSend( + view(), vaultAccount, account_, assetsRecovered, j_, WaiveTransferFee::Yes); !isTesSuccess(ter)) return ter; diff --git a/src/xrpld/app/tx/detail/VaultCreate.cpp b/src/libxrpl/tx/transactors/Vault/VaultCreate.cpp similarity index 92% rename from src/xrpld/app/tx/detail/VaultCreate.cpp rename to src/libxrpl/tx/transactors/Vault/VaultCreate.cpp index 6711a7e13f..230651fd9b 100644 --- a/src/xrpld/app/tx/detail/VaultCreate.cpp +++ b/src/libxrpl/tx/transactors/Vault/VaultCreate.cpp @@ -1,7 +1,3 @@ -#include -#include -#include - #include #include #include @@ -14,6 +10,9 @@ #include #include #include +#include +#include +#include namespace xrpl { @@ -151,8 +150,9 @@ VaultCreate::doApply() if (auto ter = addEmptyHolding(view(), pseudoId, mPriorBalance, asset, j_); !isTesSuccess(ter)) return ter; - std::uint8_t const scale = - (asset.holds() || asset.native()) ? 0 : ctx_.tx[~sfScale].value_or(vaultDefaultIOUScale); + std::uint8_t const scale = (asset.holds() || asset.native()) + ? 0 + : ctx_.tx[~sfScale].value_or(vaultDefaultIOUScale); auto txFlags = tx.getFlags(); std::uint32_t mptFlags = 0; @@ -205,15 +205,16 @@ VaultCreate::doApply() view().insert(vault); // Explicitly create MPToken for the vault owner - if (auto const err = authorizeMPToken(view(), mPriorBalance, mptIssuanceID, account_, ctx_.journal); + if (auto const err = + authorizeMPToken(view(), mPriorBalance, mptIssuanceID, account_, ctx_.journal); !isTesSuccess(err)) return err; // If the vault is private, set the authorized flag for the vault owner if (txFlags & tfVaultPrivate) { - if (auto const err = - authorizeMPToken(view(), mPriorBalance, mptIssuanceID, pseudoId, ctx_.journal, {}, account_); + if (auto const err = authorizeMPToken( + view(), mPriorBalance, mptIssuanceID, pseudoId, ctx_.journal, {}, account_); !isTesSuccess(err)) return err; } diff --git a/src/xrpld/app/tx/detail/VaultDelete.cpp b/src/libxrpl/tx/transactors/Vault/VaultDelete.cpp similarity index 98% rename from src/xrpld/app/tx/detail/VaultDelete.cpp rename to src/libxrpl/tx/transactors/Vault/VaultDelete.cpp index f5c388762f..0b3aef19a8 100644 --- a/src/xrpld/app/tx/detail/VaultDelete.cpp +++ b/src/libxrpl/tx/transactors/Vault/VaultDelete.cpp @@ -1,5 +1,3 @@ -#include - #include #include #include @@ -7,6 +5,7 @@ #include #include #include +#include namespace xrpl { @@ -113,7 +112,8 @@ 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 ter = removeEmptyHolding(view(), account_, MPTIssue(shareMPTID), j_); !isTesSuccess(ter)) + if (auto const ter = removeEmptyHolding(view(), account_, MPTIssue(shareMPTID), j_); + !isTesSuccess(ter)) { // LCOV_EXCL_START JLOG(j_.error()) // diff --git a/src/xrpld/app/tx/detail/VaultDeposit.cpp b/src/libxrpl/tx/transactors/Vault/VaultDeposit.cpp similarity index 90% rename from src/xrpld/app/tx/detail/VaultDeposit.cpp rename to src/libxrpl/tx/transactors/Vault/VaultDeposit.cpp index d5fc0e4ad6..c3a9327f2a 100644 --- a/src/xrpld/app/tx/detail/VaultDeposit.cpp +++ b/src/libxrpl/tx/transactors/Vault/VaultDeposit.cpp @@ -1,6 +1,3 @@ -#include -#include - #include #include #include @@ -12,6 +9,8 @@ #include #include #include +#include +#include namespace xrpl { @@ -146,7 +145,8 @@ VaultDeposit::doApply() // Note, vault owner is always authorized if (vault->isFlag(lsfVaultPrivate) && account_ != vault->at(sfOwner)) { - if (auto const err = enforceMPTokenAuthorization(ctx_.view(), mptIssuanceID, account_, mPriorBalance, j_); + if (auto const err = enforceMPTokenAuthorization( + ctx_.view(), mptIssuanceID, account_, mPriorBalance, j_); !isTesSuccess(err)) return err; } @@ -155,8 +155,8 @@ VaultDeposit::doApply() // No authorization needed, but must ensure there is MPToken if (!view().exists(keylet::mptoken(mptIssuanceID, account_))) { - if (auto const err = - authorizeMPToken(view(), mPriorBalance, mptIssuanceID->value(), account_, ctx_.journal); + if (auto const err = authorizeMPToken( + view(), mPriorBalance, mptIssuanceID->value(), account_, ctx_.journal); !isTesSuccess(err)) return err; } @@ -165,7 +165,8 @@ VaultDeposit::doApply() if (vault->isFlag(lsfVaultPrivate)) { // This follows from the reverse of the outer enclosing if condition - XRPL_ASSERT(account_ == vault->at(sfOwner), "xrpl::VaultDeposit::doApply : account is owner"); + XRPL_ASSERT( + account_ == vault->at(sfOwner), "xrpl::VaultDeposit::doApply : account is owner"); if (auto const err = authorizeMPToken( view(), mPriorBalance, // priorBalance @@ -218,7 +219,8 @@ VaultDeposit::doApply() } XRPL_ASSERT( - sharesCreated.asset() != assetsDeposited.asset(), "xrpl::VaultDeposit::doApply : assets are not shares"); + sharesCreated.asset() != assetsDeposited.asset(), + "xrpl::VaultDeposit::doApply : assets are not shares"); vault->at(sfAssetsTotal) += assetsDeposited; vault->at(sfAssetsAvailable) += assetsDeposited; @@ -230,7 +232,8 @@ 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(), account_, vaultAccount, assetsDeposited, j_, WaiveTransferFee::Yes); !isTesSuccess(ter)) return ter; @@ -250,7 +253,8 @@ VaultDeposit::doApply() } // Transfer shares from vault to depositor. - if (auto const ter = accountSend(view(), vaultAccount, account_, sharesCreated, j_, WaiveTransferFee::Yes); + if (auto const ter = + accountSend(view(), vaultAccount, account_, sharesCreated, j_, WaiveTransferFee::Yes); !isTesSuccess(ter)) return ter; diff --git a/src/xrpld/app/tx/detail/VaultSet.cpp b/src/libxrpl/tx/transactors/Vault/VaultSet.cpp similarity index 97% rename from src/xrpld/app/tx/detail/VaultSet.cpp rename to src/libxrpl/tx/transactors/Vault/VaultSet.cpp index c0aaf5bac6..c27c9aae3c 100644 --- a/src/xrpld/app/tx/detail/VaultSet.cpp +++ b/src/libxrpl/tx/transactors/Vault/VaultSet.cpp @@ -1,5 +1,3 @@ -#include - #include #include #include @@ -9,6 +7,7 @@ #include #include #include +#include namespace xrpl { @@ -48,7 +47,8 @@ VaultSet::preflight(PreflightContext const& ctx) } } - if (!ctx.tx.isFieldPresent(sfDomainID) && !ctx.tx.isFieldPresent(sfAssetsMaximum) && !ctx.tx.isFieldPresent(sfData)) + if (!ctx.tx.isFieldPresent(sfDomainID) && !ctx.tx.isFieldPresent(sfAssetsMaximum) && + !ctx.tx.isFieldPresent(sfData)) { JLOG(ctx.j.debug()) << "VaultSet: nothing is being updated."; return temMALFORMED; diff --git a/src/xrpld/app/tx/detail/VaultWithdraw.cpp b/src/libxrpl/tx/transactors/Vault/VaultWithdraw.cpp similarity index 91% rename from src/xrpld/app/tx/detail/VaultWithdraw.cpp rename to src/libxrpl/tx/transactors/Vault/VaultWithdraw.cpp index 88616e34f8..3e468df2fc 100644 --- a/src/xrpld/app/tx/detail/VaultWithdraw.cpp +++ b/src/libxrpl/tx/transactors/Vault/VaultWithdraw.cpp @@ -1,5 +1,3 @@ -#include - #include #include #include @@ -9,6 +7,7 @@ #include #include #include +#include namespace xrpl { @@ -155,12 +154,18 @@ VaultWithdraw::doApply() << "VaultWithdraw: overflow error with" << " scale=" << (int)vault->at(sfScale).value() // << ", assetsTotal=" << vault->at(sfAssetsTotal).value() - << ", sharesTotal=" << sleIssuance->at(sfOutstandingAmount) << ", amount=" << amount.value(); + << ", sharesTotal=" << sleIssuance->at(sfOutstandingAmount) + << ", amount=" << amount.value(); return tecPATH_DRY; } - if (accountHolds(view(), account_, share, FreezeHandling::fhZERO_IF_FROZEN, AuthHandling::ahIGNORE_AUTH, j_) < - sharesRedeemed) + if (accountHolds( + view(), + account_, + share, + FreezeHandling::fhZERO_IF_FROZEN, + AuthHandling::ahIGNORE_AUTH, + j_) < sharesRedeemed) { JLOG(j_.debug()) << "VaultWithdraw: account doesn't hold enough shares"; return tecINSUFFICIENT_FUNDS; @@ -170,7 +175,8 @@ VaultWithdraw::doApply() auto assetsTotal = vault->at(sfAssetsTotal); [[maybe_unused]] auto const lossUnrealized = vault->at(sfLossUnrealized); XRPL_ASSERT( - lossUnrealized <= (assetsTotal - assetsAvailable), "xrpl::VaultWithdraw::doApply : loss and assets do balance"); + lossUnrealized <= (assetsTotal - assetsAvailable), + "xrpl::VaultWithdraw::doApply : loss and assets do balance"); // The vault must have enough assets on hand. The vault may hold assets // that it has already pledged. That is why we look at AssetAvailable @@ -187,7 +193,8 @@ 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(), account_, vaultAccount, sharesRedeemed, j_, WaiveTransferFee::Yes); !isTesSuccess(ter)) return ter; @@ -196,7 +203,8 @@ VaultWithdraw::doApply() // Keep MPToken if holder is the vault owner. if (account_ != vault->at(sfOwner)) { - if (auto const ter = removeEmptyHolding(view(), account_, sharesRedeemed.asset(), j_); isTesSuccess(ter)) + if (auto const ter = removeEmptyHolding(view(), account_, sharesRedeemed.asset(), j_); + isTesSuccess(ter)) { JLOG(j_.debug()) // << "VaultWithdraw: removed empty MPToken for vault shares" @@ -221,7 +229,8 @@ VaultWithdraw::doApply() associateAsset(*vault, vaultAsset); - return doWithdraw(view(), ctx_.tx, account_, dstAcct, vaultAccount, mPriorBalance, assetsWithdrawn, j_); + return doWithdraw( + view(), ctx_.tx, account_, dstAcct, vaultAccount, mPriorBalance, assetsWithdrawn, j_); } } // namespace xrpl diff --git a/src/xrpld/app/tx/detail/XChainBridge.cpp b/src/libxrpl/tx/transactors/XChainBridge.cpp similarity index 93% rename from src/xrpld/app/tx/detail/XChainBridge.cpp rename to src/libxrpl/tx/transactors/XChainBridge.cpp index beeab41f67..30fc9f59e1 100644 --- a/src/xrpld/app/tx/detail/XChainBridge.cpp +++ b/src/libxrpl/tx/transactors/XChainBridge.cpp @@ -1,8 +1,3 @@ -#include -#include -#include -#include - #include #include #include @@ -23,6 +18,10 @@ #include #include #include +#include +#include +#include +#include #include #include @@ -103,7 +102,8 @@ checkAttestationPublicKey( AccountID const accountFromPK = calcAccountID(pk); - if (auto const sleAttestationSigningAccount = view.read(keylet::account(attestationSignerAccount))) + if (auto const sleAttestationSigningAccount = + view.read(keylet::account(attestationSignerAccount))) { if (accountFromPK == attestationSignerAccount) { @@ -118,7 +118,8 @@ checkAttestationPublicKey( else { // regular key - if (std::optional regularKey = (*sleAttestationSigningAccount)[~sfRegularKey]; + if (std::optional regularKey = + (*sleAttestationSigningAccount)[~sfRegularKey]; regularKey != accountFromPK) { if (!regularKey) @@ -177,7 +178,8 @@ claimHelper( // part of the signers list, or their master key may have been disabled, // or their regular key may have changed attestations.erase_if([&](auto const& a) { - return checkAttestationPublicKey(view, signersList, a.keyAccount, a.publicKey, j) != tesSUCCESS; + return checkAttestationPublicKey(view, signersList, a.keyAccount, a.publicKey, j) != + tesSUCCESS; }); // Check if we have quorum for the amount specified on the new claimAtt @@ -265,8 +267,8 @@ onNewAttestations( bool changed = false; for (auto att = attBegin; att != attEnd; ++att) { - if (checkAttestationPublicKey(view, signersList, att->attestationSignerAccount, att->publicKey, j) != - tesSUCCESS) + if (checkAttestationPublicKey( + view, signersList, att->attestationSignerAccount, att->publicKey, j) != tesSUCCESS) { // The checkAttestationPublicKey is not strictly necessary here (it // should be checked in a preclaim step), but it would be bad to let @@ -295,7 +297,13 @@ onNewAttestations( } auto r = claimHelper( - attestations, view, typename TAttestation::MatchFields{*attBegin}, CheckDst::check, quorum, signersList, j); + attestations, + view, + typename TAttestation::MatchFields{*attBegin}, + CheckDst::check, + quorum, + signersList, + j); if (!r.has_value()) return {std::nullopt, changed}; @@ -382,7 +390,8 @@ transferHelper( // If the destination is the claim owner, and this is a claim // transaction, that's the dst account sending funds to itself. It // can bypass deposit auth. - bool const canBypassDepositAuth = dst == claimOwner && depositAuthPolicy == DepositAuthPolicy::dstCanBypass; + bool const canBypassDepositAuth = + dst == claimOwner && depositAuthPolicy == DepositAuthPolicy::dstCanBypass; if (!canBypassDepositAuth && (sleDst->getFlags() & lsfDepositAuth) && !psb.exists(keylet::depositPreauth(dst, src))) @@ -499,14 +508,15 @@ struct FinalizeClaimHelperResult bool isTesSuccess() const { - return mainFundsTer == tesSUCCESS && rewardTer == tesSUCCESS && (!rmSleTer || *rmSleTer == tesSUCCESS); + return mainFundsTer == tesSUCCESS && rewardTer == tesSUCCESS && + (!rmSleTer || *rmSleTer == tesSUCCESS); } TER ter() const { - if ((!mainFundsTer || *mainFundsTer == tesSUCCESS) && (!rewardTer || *rewardTer == tesSUCCESS) && - (!rmSleTer || *rmSleTer == tesSUCCESS)) + if ((!mainFundsTer || *mainFundsTer == tesSUCCESS) && + (!rewardTer || *rewardTer == tesSUCCESS) && (!rmSleTer || *rmSleTer == tesSUCCESS)) return tesSUCCESS; // if any phase return a tecINTERNAL or a tef, prefer returning those @@ -556,7 +566,7 @@ struct FinalizeClaimHelperResult the fields mean. The individual ters need to be returned instead of an overall ter because the caller needs this information if the attestation list changed or not. - */ +*/ FinalizeClaimHelperResult finalizeClaimHelper( @@ -846,7 +856,8 @@ applyClaimAttestations( { STXChainBridge::ChainType const dstChain = STXChainBridge::otherChain(srcChain); - STXChainBridge::ChainType const attDstChain = STXChainBridge::dstChain(attBegin->wasLockingChainSend); + STXChainBridge::ChainType const attDstChain = + STXChainBridge::dstChain(attBegin->wasLockingChainSend); if (attDstChain != dstChain) { @@ -856,14 +867,15 @@ applyClaimAttestations( XChainClaimAttestations curAtts{sleClaimID->getFieldArray(sfXChainClaimAttestations)}; - auto const newAttResult = - onNewAttestations(curAtts, view, &atts[0], &atts[0] + atts.size(), quorum, signersList, j); + auto const newAttResult = onNewAttestations( + curAtts, view, &atts[0], &atts[0] + atts.size(), quorum, signersList, j); // update the claim id sleClaimID->setFieldArray(sfXChainClaimAttestations, curAtts.toSTArray()); psb.update(sleClaimID); - return ScopeResult{newAttResult, (*sleClaimID)[sfSignatureReward], (*sleClaimID)[sfAccount]}; + return ScopeResult{ + newAttResult, (*sleClaimID)[sfSignatureReward], (*sleClaimID)[sfAccount]}; }(); if (!scopeResult.has_value()) @@ -891,7 +903,8 @@ applyClaimAttestations( auto const rTer = r.ter(); - if (!isTesSuccess(rTer) && (!attListChanged || rTer == tecINTERNAL || rTer == tefBAD_LEDGER)) + if (!isTesSuccess(rTer) && + (!attListChanged || rTer == tecINTERNAL || rTer == tefBAD_LEDGER)) return rTer; } @@ -947,7 +960,8 @@ applyCreateAccountAttestations( { STXChainBridge::ChainType const dstChain = STXChainBridge::otherChain(srcChain); - STXChainBridge::ChainType const attDstChain = STXChainBridge::dstChain(attBegin->wasLockingChainSend); + STXChainBridge::ChainType const attDstChain = + STXChainBridge::dstChain(attBegin->wasLockingChainSend); if (attDstChain != dstChain) { @@ -955,7 +969,8 @@ applyCreateAccountAttestations( } } - auto const claimIDKeylet = keylet::xChainCreateAccountClaimID(bridgeSpec, attBegin->createCount); + auto const claimIDKeylet = + keylet::xChainCreateAccountClaimID(bridgeSpec, attBegin->createCount); struct ScopeResult { @@ -1005,12 +1020,13 @@ applyCreateAccountAttestations( XChainCreateAccountAttestations curAtts = [&] { if (sleClaimID) - return XChainCreateAccountAttestations{sleClaimID->getFieldArray(sfXChainCreateAccountAttestations)}; + return XChainCreateAccountAttestations{ + sleClaimID->getFieldArray(sfXChainCreateAccountAttestations)}; return XChainCreateAccountAttestations{}; }(); - auto const newAttResult = - onNewAttestations(curAtts, view, &atts[0], &atts[0] + atts.size(), quorum, signersList, j); + auto const newAttResult = onNewAttestations( + curAtts, view, &atts[0], &atts[0] + atts.size(), quorum, signersList, j); if (!createCID) { @@ -1073,7 +1089,8 @@ applyCreateAccountAttestations( createdSleClaimID->setFieldArray(sfXChainCreateAccountAttestations, curAtts.toSTArray()); // Add to owner directory of the door account - auto const page = psb.dirInsert(keylet::ownerDir(doorAccount), claimIDKeylet, describeOwnerDir(doorAccount)); + auto const page = psb.dirInsert( + keylet::ownerDir(doorAccount), claimIDKeylet, describeOwnerDir(doorAccount)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE (*createdSleClaimID)[sfOwnerNode] = *page; @@ -1212,7 +1229,8 @@ attestationDoApply(ApplyContext& ctx) STXChainBridge::ChainType const srcChain = STXChainBridge::otherChain(dstChain); // signersList is a map from account id to weights - auto [signersList, quorum, slTer] = getSignersListAndQuorum(ctx.view(), *sleBridge, ctx.journal); + auto [signersList, quorum, slTer] = + getSignersListAndQuorum(ctx.view(), *sleBridge, ctx.journal); if (!isTesSuccess(slTer)) return Unexpected(slTer); @@ -1232,7 +1250,15 @@ attestationDoApply(ApplyContext& ctx) if constexpr (std::is_same_v) { return applyClaimAttestations( - ctx.view(), ctx.rawView(), &*att, &*att + 1, bridgeSpec, srcChain, signersList, quorum, ctx.journal); + ctx.view(), + ctx.rawView(), + &*att, + &*att + 1, + bridgeSpec, + srcChain, + signersList, + quorum, + ctx.journal); } else if constexpr (std::is_same_v) { @@ -1286,8 +1312,8 @@ XChainCreateBridge::preflight(PreflightContext const& ctx) } if (minAccountCreate && - ((!isXRP(*minAccountCreate) || minAccountCreate->signum() <= 0) || !isXRP(bridgeSpec.lockingChainIssue()) || - !isXRP(bridgeSpec.issuingChainIssue()))) + ((!isXRP(*minAccountCreate) || minAccountCreate->signum() <= 0) || + !isXRP(bridgeSpec.lockingChainIssue()) || !isXRP(bridgeSpec.issuingChainIssue()))) { return temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT; } @@ -1297,8 +1323,8 @@ XChainCreateBridge::preflight(PreflightContext const& ctx) // Issuing account must be the root account for XRP (which presumably // owns all the XRP). This is done so the issuing account can't "run // out" of wrapped tokens. - static auto const rootAccount = - calcAccountID(generateKeyPair(KeyType::secp256k1, generateSeed("masterpassphrase")).first); + static auto const rootAccount = calcAccountID( + generateKeyPair(KeyType::secp256k1, generateSeed("masterpassphrase")).first); if (bridgeSpec.issuingChainDoor() != rootAccount) { return temXCHAIN_BRIDGE_BAD_ISSUES; @@ -1329,14 +1355,16 @@ XChainCreateBridge::preclaim(PreclaimContext const& ctx) { auto const account = ctx.tx[sfAccount]; auto const bridgeSpec = ctx.tx[sfXChainBridge]; - STXChainBridge::ChainType const chainType = STXChainBridge::srcChain(account == bridgeSpec.lockingChainDoor()); + STXChainBridge::ChainType const chainType = + STXChainBridge::srcChain(account == bridgeSpec.lockingChainDoor()); { auto hasBridge = [&](STXChainBridge::ChainType ct) -> bool { return ctx.view.exists(keylet::bridge(bridgeSpec, ct)); }; - if (hasBridge(STXChainBridge::ChainType::issuing) || hasBridge(STXChainBridge::ChainType::locking)) + if (hasBridge(STXChainBridge::ChainType::issuing) || + hasBridge(STXChainBridge::ChainType::locking)) { return tecDUPLICATE; } @@ -1383,7 +1411,8 @@ XChainCreateBridge::doApply() if (!sleAcct) return tecINTERNAL; // LCOV_EXCL_LINE - STXChainBridge::ChainType const chainType = STXChainBridge::srcChain(account == bridgeSpec.lockingChainDoor()); + STXChainBridge::ChainType const chainType = + STXChainBridge::srcChain(account == bridgeSpec.lockingChainDoor()); Keylet const bridgeKeylet = keylet::bridge(bridgeSpec, chainType); auto const sleBridge = std::make_shared(bridgeKeylet); @@ -1399,7 +1428,8 @@ XChainCreateBridge::doApply() // Add to owner directory { - auto const page = ctx_.view().dirInsert(keylet::ownerDir(account), bridgeKeylet, describeOwnerDir(account)); + auto const page = ctx_.view().dirInsert( + keylet::ownerDir(account), bridgeKeylet, describeOwnerDir(account)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE (*sleBridge)[sfOwnerNode] = *page; @@ -1453,8 +1483,8 @@ BridgeModify::preflight(PreflightContext const& ctx) } if (minAccountCreate && - ((!isXRP(*minAccountCreate) || minAccountCreate->signum() <= 0) || !isXRP(bridgeSpec.lockingChainIssue()) || - !isXRP(bridgeSpec.issuingChainIssue()))) + ((!isXRP(*minAccountCreate) || minAccountCreate->signum() <= 0) || + !isXRP(bridgeSpec.lockingChainIssue()) || !isXRP(bridgeSpec.issuingChainIssue()))) { return temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT; } @@ -1468,7 +1498,8 @@ BridgeModify::preclaim(PreclaimContext const& ctx) auto const account = ctx.tx[sfAccount]; auto const bridgeSpec = ctx.tx[sfXChainBridge]; - STXChainBridge::ChainType const chainType = STXChainBridge::srcChain(account == bridgeSpec.lockingChainDoor()); + STXChainBridge::ChainType const chainType = + STXChainBridge::srcChain(account == bridgeSpec.lockingChainDoor()); if (!ctx.view.read(keylet::bridge(bridgeSpec, chainType))) { @@ -1491,7 +1522,8 @@ BridgeModify::doApply() if (!sleAcct) return tecINTERNAL; // LCOV_EXCL_LINE - STXChainBridge::ChainType const chainType = STXChainBridge::srcChain(account == bridgeSpec.lockingChainDoor()); + STXChainBridge::ChainType const chainType = + STXChainBridge::srcChain(account == bridgeSpec.lockingChainDoor()); auto const sleBridge = ctx_.view().peek(keylet::bridge(bridgeSpec, chainType)); if (!sleBridge) @@ -1521,7 +1553,8 @@ XChainClaim::preflight(PreflightContext const& ctx) auto const amount = ctx.tx[sfAmount]; if (amount.signum() <= 0 || - (amount.issue() != bridgeSpec.lockingChainIssue() && amount.issue() != bridgeSpec.issuingChainIssue())) + (amount.issue() != bridgeSpec.lockingChainIssue() && + amount.issue() != bridgeSpec.issuingChainIssue())) { return temBAD_AMOUNT; } @@ -1664,7 +1697,8 @@ XChainClaim::doApply() return r; }(); - auto const [signersList, quorum, slTer] = getSignersListAndQuorum(ctx_.view(), *sleBridge, ctx_.journal); + auto const [signersList, quorum, slTer] = + getSignersListAndQuorum(ctx_.view(), *sleBridge, ctx_.journal); if (!isTesSuccess(slTer)) return Unexpected(slTer); @@ -1694,7 +1728,8 @@ XChainClaim::doApply() if (!scopeResult.has_value()) return scopeResult.error(); - auto const& [rewardAccounts, rewardPoolSrc, sendingAmount, srcChain, signatureReward] = scopeResult.value(); + auto const& [rewardAccounts, rewardPoolSrc, sendingAmount, srcChain, signatureReward] = + scopeResult.value(); std::optional const dstTag = ctx_.tx[~sfDestinationTag]; auto const r = finalizeClaimHelper( @@ -1744,7 +1779,8 @@ XChainCommit::preflight(PreflightContext const& ctx) if (amount.signum() <= 0 || !isLegalNet(amount)) return temBAD_AMOUNT; - if (amount.issue() != bridgeSpec.lockingChainIssue() && amount.issue() != bridgeSpec.issuingChainIssue()) + if (amount.issue() != bridgeSpec.lockingChainIssue() && + amount.issue() != bridgeSpec.issuingChainIssue()) return temBAD_ISSUER; return tesSUCCESS; @@ -1814,7 +1850,8 @@ XChainCommit::doApply() auto const dst = (*sleBridge)[sfAccount]; // Support dipping into reserves to pay the fee - TransferHelperSubmittingAccountInfo submittingAccountInfo{account_, mPriorBalance, mSourceBalance}; + TransferHelperSubmittingAccountInfo submittingAccountInfo{ + account_, mPriorBalance, mSourceBalance}; auto const thTer = transferHelper( psb, @@ -1928,7 +1965,8 @@ XChainCreateClaimID::doApply() // Add to owner directory { - auto const page = ctx_.view().dirInsert(keylet::ownerDir(account), claimIDKeylet, describeOwnerDir(account)); + auto const page = ctx_.view().dirInsert( + keylet::ownerDir(account), claimIDKeylet, describeOwnerDir(account)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE (*sleClaimID)[sfOwnerNode] = *page; @@ -2081,7 +2119,8 @@ XChainCreateAccountCommit::doApply() auto const dst = (*sleBridge)[sfAccount]; // Support dipping into reserves to pay the fee - TransferHelperSubmittingAccountInfo submittingAccountInfo{account_, mPriorBalance, mSourceBalance}; + TransferHelperSubmittingAccountInfo submittingAccountInfo{ + account_, mPriorBalance, mSourceBalance}; STAmount const toTransfer = amount + reward; auto const thTer = transferHelper( psb, diff --git a/src/test/app/AMMCalc_test.cpp b/src/test/app/AMMCalc_test.cpp index bc50f02d3d..e6e68a95ce 100644 --- a/src/test/app/AMMCalc_test.cpp +++ b/src/test/app/AMMCalc_test.cpp @@ -1,8 +1,7 @@ #include -#include - #include +#include #include @@ -371,7 +370,8 @@ class AMMCalc_test : public beast::unit_test::suite { Account const amm("amm"); auto const LPT = amm["LPT"]; - std::cout << to_string(ammLPTokens(pool->first.in, pool->first.out, LPT).iou()) << std::endl; + std::cout << to_string(ammLPTokens(pool->first.in, pool->first.out, LPT).iou()) + << std::endl; return true; } } @@ -398,9 +398,11 @@ class AMMCalc_test : public beast::unit_test::suite env.current()->rules(), beast::Journal(beast::Journal::getNullSink())); ammOffer) - std::cout << "amm offer: " << toString(ammOffer->in) << " " << toString(ammOffer->out) - << "\nnew pool: " << toString(pool->first.in + ammOffer->in) << " " - << toString(pool->first.out - ammOffer->out) << std::endl; + std::cout << "amm offer: " << toString(ammOffer->in) << " " + << toString(ammOffer->out) + << "\nnew pool: " << toString(pool->first.in + ammOffer->in) + << " " << toString(pool->first.out - ammOffer->out) + << std::endl; else std::cout << "can't change the pool's SP quality" << std::endl; return true; diff --git a/src/test/app/AMMClawback_test.cpp b/src/test/app/AMMClawback_test.cpp index 65cf7f0a60..114a96b081 100644 --- a/src/test/app/AMMClawback_test.cpp +++ b/src/test/app/AMMClawback_test.cpp @@ -2,9 +2,8 @@ #include #include -#include - #include +#include namespace xrpl { namespace test { @@ -36,7 +35,8 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, alice, XRP(100), USD(100)); env.close(); - env(amm::ammClawback(gw, Account("unknown"), USD, XRP, std::nullopt), ter(terNO_ACCOUNT)); + env(amm::ammClawback(gw, Account("unknown"), USD, XRP, std::nullopt), + ter(terNO_ACCOUNT)); } // Test if asset pair provided does not exist. This should @@ -123,7 +123,8 @@ class AMMClawback_test : public beast::unit_test::suite // The Asset's issuer field is alice, while the Account field is gw. // This should return temMALFORMED because they do not match. - env(amm::ammClawback(gw, alice, Issue{gw["USD"].currency, alice.id()}, XRP, std::nullopt), + env(amm::ammClawback( + gw, alice, Issue{gw["USD"].currency, alice.id()}, XRP, std::nullopt), ter(temMALFORMED)); } @@ -151,7 +152,8 @@ class AMMClawback_test : public beast::unit_test::suite // The Asset's issuer subfield is gw account and Amount's issuer // subfield is alice account. Return temBAD_AMOUNT because // they do not match. - env(amm::ammClawback(gw, alice, USD, XRP, STAmount{Issue{gw["USD"].currency, alice.id()}, 1}), + env(amm::ammClawback( + gw, alice, USD, XRP, STAmount{Issue{gw["USD"].currency, alice.id()}, 1}), ter(temBAD_AMOUNT)); } @@ -177,11 +179,13 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); // Return temBAD_AMOUNT if the Amount value is less than 0. - env(amm::ammClawback(gw, alice, USD, XRP, STAmount{Issue{gw["USD"].currency, gw.id()}, -1}), + env(amm::ammClawback( + gw, alice, USD, XRP, STAmount{Issue{gw["USD"].currency, gw.id()}, -1}), ter(temBAD_AMOUNT)); // Return temBAD_AMOUNT if the Amount value is 0. - env(amm::ammClawback(gw, alice, USD, XRP, STAmount{Issue{gw["USD"].currency, gw.id()}, 0}), + env(amm::ammClawback( + gw, alice, USD, XRP, STAmount{Issue{gw["USD"].currency, gw.id()}, 0}), ter(temBAD_AMOUNT)); } @@ -232,7 +236,9 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); // Return temINVALID_FLAG when providing invalid flag. - env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), txflags(tfTwoAssetIfEmpty), ter(temINVALID_FLAG)); + env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), + txflags(tfTwoAssetIfEmpty), + ter(temINVALID_FLAG)); } // Test if tfClawTwoAssets is set when the two assets in the AMM pool @@ -262,7 +268,9 @@ class AMMClawback_test : public beast::unit_test::suite // but the issuer only issues USD in the pool. The issuer is not // allowed to set tfClawTwoAssets flag if he did not issue both // assets in the pool. - env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), txflags(tfClawTwoAssets), ter(temINVALID_FLAG)); + env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), + txflags(tfClawTwoAssets), + ter(temINVALID_FLAG)); } // Test clawing back XRP is being prohibited. @@ -365,7 +373,8 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT(amm.expectBalances(USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); // gw clawback 1000 USD from the AMM pool. env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), ter(tesSUCCESS)); @@ -522,9 +531,11 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999580, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999580, -12})); else - BEAST_EXPECT(amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999579, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999579, -12})); // gw clawback 1000 USD from the AMM pool env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), ter(tesSUCCESS)); @@ -543,9 +554,11 @@ class AMMClawback_test : public beast::unit_test::suite // 1000 USD and 1250 EUR was withdrawn from the AMM pool, so the // current balance is 3000 USD and 3750 EUR. if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances(USD(3000), EUR(3750), IOUAmount{3354101966249685, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(3000), EUR(3750), IOUAmount{3354101966249685, -12})); else - BEAST_EXPECT(amm.expectBalances(USD(3000), EUR(3750), IOUAmount{3354101966249684, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(3000), EUR(3750), IOUAmount{3354101966249684, -12})); // Alice has 3/4 of its initial lptokens Left. if (!features[fixAMMv1_3]) @@ -567,10 +580,12 @@ class AMMClawback_test : public beast::unit_test::suite STAmount{EUR, UINT64_C(3125000000000001), -12}, IOUAmount{2795084971874738, -12})); else - BEAST_EXPECT(amm.expectBalances(USD(2500), EUR(3125), IOUAmount{2795084971874737, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(2500), EUR(3125), IOUAmount{2795084971874737, -12})); if (!features[fixAMMv1_3]) - BEAST_EXPECT(env.balance(alice, EUR) == STAmount(EUR, UINT64_C(2874999999999999), -12)); + BEAST_EXPECT( + env.balance(alice, EUR) == STAmount(EUR, UINT64_C(2874999999999999), -12)); else BEAST_EXPECT(env.balance(alice, EUR) == EUR(2875)); @@ -587,7 +602,8 @@ class AMMClawback_test : public beast::unit_test::suite STAmount{EUR, UINT64_C(3123750000000002), -12}, IOUAmount{2793966937885989, -12})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances(USD(2499), EUR(3123.75), IOUAmount{2793966937885987, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(2499), EUR(3123.75), IOUAmount{2793966937885987, -12})); else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(2499000000000001), -12}, @@ -595,11 +611,13 @@ class AMMClawback_test : public beast::unit_test::suite IOUAmount{2793966937885988, -12})); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT(env.balance(alice, EUR) == STAmount(EUR, UINT64_C(2876'249999999998), -12)); + BEAST_EXPECT( + env.balance(alice, EUR) == STAmount(EUR, UINT64_C(2876'249999999998), -12)); else if (!features[fixAMMClawbackRounding]) BEAST_EXPECT(env.balance(alice, EUR) == EUR(2876.25)); else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) - BEAST_EXPECT(env.balance(alice, EUR) == STAmount(EUR, UINT64_C(2876'249999999999), -12)); + BEAST_EXPECT( + env.balance(alice, EUR) == STAmount(EUR, UINT64_C(2876'249999999999), -12)); // gw clawback 4000 USD, exceeding the current balance. We // will clawback all. @@ -667,21 +685,27 @@ class AMMClawback_test : public beast::unit_test::suite // gw2 creates AMM pool of XRP/EUR, alice and bob deposit XRP/EUR. AMM amm2(env, gw2, XRP(3000), EUR(1000), ter(tesSUCCESS)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568878, -9})); + BEAST_EXPECT( + amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568878, -9})); else - BEAST_EXPECT(amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568877, -9})); + BEAST_EXPECT( + amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568877, -9})); amm2.deposit(alice, EUR(1000), XRP(3000)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137756, -9})); + BEAST_EXPECT( + amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137756, -9})); else - BEAST_EXPECT(amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137754, -9})); + BEAST_EXPECT( + amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137754, -9})); amm2.deposit(bob, EUR(1000), XRP(3000)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm2.expectBalances(EUR(3000), XRP(9000), IOUAmount{5196152422706634, -9})); + BEAST_EXPECT( + amm2.expectBalances(EUR(3000), XRP(9000), IOUAmount{5196152422706634, -9})); else - BEAST_EXPECT(amm2.expectBalances(EUR(3000), XRP(9000), IOUAmount{5196152422706631, -9})); + BEAST_EXPECT( + amm2.expectBalances(EUR(3000), XRP(9000), IOUAmount{5196152422706631, -9})); env.close(); auto aliceXrpBalance = env.balance(alice, XRP); @@ -701,17 +725,21 @@ class AMMClawback_test : public beast::unit_test::suite // Alice gets 1000 XRP back. if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) - BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000) - XRPAmount(1))); + BEAST_EXPECT( + expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000) - XRPAmount(1))); else BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000))); aliceXrpBalance = env.balance(alice, XRP); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances(USD(2500), XRP(5000), IOUAmount{3535533905932738, -9})); + BEAST_EXPECT( + amm.expectBalances(USD(2500), XRP(5000), IOUAmount{3535533905932738, -9})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances(USD(2500), XRP(5000), IOUAmount{3535533905932737, -9})); + BEAST_EXPECT( + amm.expectBalances(USD(2500), XRP(5000), IOUAmount{3535533905932737, -9})); else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances(USD(2500), XRPAmount(5000000001), IOUAmount{3'535'533'905932738, -9})); + BEAST_EXPECT(amm.expectBalances( + USD(2500), XRPAmount(5000000001), IOUAmount{3'535'533'905932738, -9})); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{7071067811865480, -10})); @@ -735,9 +763,12 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectBalances( - STAmount{USD, UINT64_C(2490000000000001), -12}, XRP(4980), IOUAmount{3521391770309008, -9})); + STAmount{USD, UINT64_C(2490000000000001), -12}, + XRP(4980), + IOUAmount{3521391770309008, -9})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances(USD(2'490), XRP(4980), IOUAmount{3521391770309006, -9})); + BEAST_EXPECT( + amm.expectBalances(USD(2'490), XRP(4980), IOUAmount{3521391770309006, -9})); else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(2490000000000001), -12}, @@ -770,15 +801,19 @@ class AMMClawback_test : public beast::unit_test::suite else if (!features[fixAMMClawbackRounding]) BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(600))); else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) - BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(600) - XRPAmount{1})); + BEAST_EXPECT( + expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(600) - XRPAmount{1})); aliceXrpBalance = env.balance(alice, XRP); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances(EUR(2800), XRP(8400), IOUAmount{4849742261192859, -9})); + BEAST_EXPECT( + amm2.expectBalances(EUR(2800), XRP(8400), IOUAmount{4849742261192859, -9})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances(EUR(2800), XRP(8400), IOUAmount{4849742261192856, -9})); + BEAST_EXPECT( + amm2.expectBalances(EUR(2800), XRP(8400), IOUAmount{4849742261192856, -9})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances(EUR(2800), XRPAmount(8400000001), IOUAmount{4849742261192856, -9})); + BEAST_EXPECT(amm2.expectBalances( + EUR(2800), XRPAmount(8400000001), IOUAmount{4849742261192856, -9})); if (!features[fixAMMv1_3]) BEAST_EXPECT(amm2.expectLPTokens(alice, IOUAmount{1385640646055103, -9})); @@ -802,7 +837,8 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000))); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000) - XRPAmount{1})); + BEAST_EXPECT( + expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000) - XRPAmount{1})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000))); aliceXrpBalance = env.balance(alice, XRP); @@ -817,9 +853,12 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectBalances( - STAmount{USD, UINT64_C(1990000000000001), -12}, XRP(3980), IOUAmount{2814284989122460, -9})); + STAmount{USD, UINT64_C(1990000000000001), -12}, + XRP(3980), + IOUAmount{2814284989122460, -9})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances(USD(1'990), XRPAmount{3'980'000'001}, IOUAmount{2814284989122459, -9})); + BEAST_EXPECT(amm.expectBalances( + USD(1'990), XRPAmount{3'980'000'001}, IOUAmount{2814284989122459, -9})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(1990000000000001), -12}, @@ -864,11 +903,14 @@ class AMMClawback_test : public beast::unit_test::suite BEAST_EXPECT(amm2.expectLPTokens(alice, IOUAmount(0))); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137756, -9})); + BEAST_EXPECT( + amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137756, -9})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137754, -9})); + BEAST_EXPECT( + amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137754, -9})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances(EUR(2000), XRPAmount(6000000001), IOUAmount{3464101615137754, -9})); + BEAST_EXPECT(amm2.expectBalances( + EUR(2000), XRPAmount(6000000001), IOUAmount{3464101615137754, -9})); // gw2 claw back 2000 EUR from bob in amm2, which exceeds bob's // balance. All bob's lptokens will be consumed, which corresponds @@ -891,11 +933,14 @@ class AMMClawback_test : public beast::unit_test::suite BEAST_EXPECT(amm2.expectLPTokens(bob, IOUAmount(0))); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568878, -9})); + BEAST_EXPECT( + amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568878, -9})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568877, -9})); + BEAST_EXPECT( + amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568877, -9})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances(EUR(1000), XRPAmount(3000000001), IOUAmount{1732050807568877, -9})); + BEAST_EXPECT(amm2.expectBalances( + EUR(1000), XRPAmount(3000000001), IOUAmount{1732050807568877, -9})); } } @@ -954,19 +999,25 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999580, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999580, -12})); else - BEAST_EXPECT(amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999579, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999579, -12})); amm.deposit(bob, USD(2000), EUR(2500)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances(USD(6000), EUR(7500), IOUAmount{6708203932499370, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(6000), EUR(7500), IOUAmount{6708203932499370, -12})); else - BEAST_EXPECT(amm.expectBalances(USD(6000), EUR(7500), IOUAmount{6708203932499368, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(6000), EUR(7500), IOUAmount{6708203932499368, -12})); amm.deposit(carol, USD(1000), EUR(1250)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances(USD(7000), EUR(8750), IOUAmount{7826237921249265, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(7000), EUR(8750), IOUAmount{7826237921249265, -12})); else - BEAST_EXPECT(amm.expectBalances(USD(7000), EUR(8750), IOUAmount{7826237921249262, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(7000), EUR(8750), IOUAmount{7826237921249262, -12})); if (!features[fixAMMv1_3]) BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4472135954999580, -12})); @@ -1019,9 +1070,11 @@ class AMMClawback_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(bob, USD) == STAmount(USD, UINT64_C(3000000000000000), -12)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(env.balance(bob, EUR) == STAmount(EUR, UINT64_C(5000000000000001), -12)); + BEAST_EXPECT( + env.balance(bob, EUR) == STAmount(EUR, UINT64_C(5000000000000001), -12)); else - BEAST_EXPECT(env.balance(bob, EUR) == STAmount(EUR, UINT64_C(4999999999999999), -12)); + BEAST_EXPECT( + env.balance(bob, EUR) == STAmount(EUR, UINT64_C(4999999999999999), -12)); env.require(balance(carol, USD(3000))); env.require(balance(carol, EUR(2750))); @@ -1081,19 +1134,25 @@ class AMMClawback_test : public beast::unit_test::suite // gw creates AMM pool of XRP/USD, alice and bob deposit XRP/USD. AMM amm(env, gw, XRP(2000), USD(10000), ter(tesSUCCESS)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances(USD(10000), XRP(2000), IOUAmount{4472135954999580, -9})); + BEAST_EXPECT( + amm.expectBalances(USD(10000), XRP(2000), IOUAmount{4472135954999580, -9})); else - BEAST_EXPECT(amm.expectBalances(USD(10000), XRP(2000), IOUAmount{4472135954999579, -9})); + BEAST_EXPECT( + amm.expectBalances(USD(10000), XRP(2000), IOUAmount{4472135954999579, -9})); amm.deposit(alice, USD(1000), XRP(200)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances(USD(11000), XRP(2200), IOUAmount{4919349550499538, -9})); + BEAST_EXPECT( + amm.expectBalances(USD(11000), XRP(2200), IOUAmount{4919349550499538, -9})); else - BEAST_EXPECT(amm.expectBalances(USD(11000), XRP(2200), IOUAmount{4919349550499536, -9})); + BEAST_EXPECT( + amm.expectBalances(USD(11000), XRP(2200), IOUAmount{4919349550499536, -9})); amm.deposit(bob, USD(2000), XRP(400)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances(USD(13000), XRP(2600), IOUAmount{5813776741499453, -9})); + BEAST_EXPECT( + amm.expectBalances(USD(13000), XRP(2600), IOUAmount{5813776741499453, -9})); else - BEAST_EXPECT(amm.expectBalances(USD(13000), XRP(2600), IOUAmount{5813776741499451, -9})); + BEAST_EXPECT( + amm.expectBalances(USD(13000), XRP(2600), IOUAmount{5813776741499451, -9})); env.close(); auto aliceXrpBalance = env.balance(alice, XRP); @@ -1103,22 +1162,27 @@ class AMMClawback_test : public beast::unit_test::suite env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances(USD(12000), XRP(2400), IOUAmount{5366563145999495, -9})); + BEAST_EXPECT( + amm.expectBalances(USD(12000), XRP(2400), IOUAmount{5366563145999495, -9})); else - BEAST_EXPECT(amm.expectBalances(USD(12000), XRPAmount(2400000001), IOUAmount{5366563145999494, -9})); + BEAST_EXPECT(amm.expectBalances( + USD(12000), XRPAmount(2400000001), IOUAmount{5366563145999494, -9})); if (!features[fixAMMv1_3]) BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(200))); else - BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(200) - XRPAmount{1})); + BEAST_EXPECT( + expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(200) - XRPAmount{1})); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); // gw clawback all bob's USD in amm. (2000 USD / 400 XRP) env(amm::ammClawback(gw, bob, USD, XRP, std::nullopt), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances(USD(10000), XRP(2000), IOUAmount{4472135954999580, -9})); + BEAST_EXPECT( + amm.expectBalances(USD(10000), XRP(2000), IOUAmount{4472135954999580, -9})); else - BEAST_EXPECT(amm.expectBalances(USD(10000), XRPAmount(2000000001), IOUAmount{4472135954999579, -9})); + BEAST_EXPECT(amm.expectBalances( + USD(10000), XRPAmount(2000000001), IOUAmount{4472135954999579, -9})); BEAST_EXPECT(expectLedgerEntryRoot(env, bob, bobXrpBalance + XRP(400))); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(0))); @@ -1192,14 +1256,17 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3]) BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); else - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); + BEAST_EXPECT( + env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); // 250 EUR goes back to carol. BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); // gw clawback 1000 USD from bob with tfClawTwoAssets flag. // then the corresponding EUR will also be clawed back // by gw. - env(amm::ammClawback(gw, bob, USD, EUR, USD(1000)), txflags(tfClawTwoAssets), ter(tesSUCCESS)); + env(amm::ammClawback(gw, bob, USD, EUR, USD(1000)), + txflags(tfClawTwoAssets), + ter(tesSUCCESS)); env.close(); BEAST_EXPECT(amm.expectBalances(USD(12000), EUR(3000), IOUAmount(6000))); @@ -1214,11 +1281,14 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3]) BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); else - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); + BEAST_EXPECT( + env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); // gw clawback all USD from alice and set tfClawTwoAssets. - env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), txflags(tfClawTwoAssets), ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), + txflags(tfClawTwoAssets), + ter(tesSUCCESS)); env.close(); BEAST_EXPECT(amm.expectBalances(USD(4000), EUR(1000), IOUAmount(2000))); @@ -1232,7 +1302,8 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3]) BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); else - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); + BEAST_EXPECT( + env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); } @@ -1278,24 +1349,39 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, alice, gw["USD"](1000), gw2["USD"](1500), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT(amm.expectBalances(gw["USD"](1000), gw2["USD"](1500), IOUAmount{1224744871391589, -12})); + BEAST_EXPECT(amm.expectBalances( + gw["USD"](1000), gw2["USD"](1500), IOUAmount{1224744871391589, -12})); amm.deposit(bob, gw["USD"](2000), gw2["USD"](3000)); - BEAST_EXPECT(amm.expectBalances(gw["USD"](3000), gw2["USD"](4500), IOUAmount{3674234614174767, -12})); + BEAST_EXPECT(amm.expectBalances( + gw["USD"](3000), gw2["USD"](4500), IOUAmount{3674234614174767, -12})); // Issuer does not match with asset. - env(amm::ammClawback(gw, alice, gw2["USD"], gw["USD"], STAmount{Issue{gw2["USD"].currency, gw2.id()}, 500}), + env(amm::ammClawback( + gw, + alice, + gw2["USD"], + gw["USD"], + STAmount{Issue{gw2["USD"].currency, gw2.id()}, 500}), ter(temMALFORMED)); // gw2 clawback 500 gw2[USD] from alice. - env(amm::ammClawback(gw2, alice, gw2["USD"], gw["USD"], STAmount{Issue{gw2["USD"].currency, gw2.id()}, 500}), + env(amm::ammClawback( + gw2, + alice, + gw2["USD"], + gw["USD"], + STAmount{Issue{gw2["USD"].currency, gw2.id()}, 500}), ter(tesSUCCESS)); env.close(); BEAST_EXPECT(amm.expectBalances( - STAmount{gw["USD"], UINT64_C(2666666666666667), -12}, gw2["USD"](4000), IOUAmount{3265986323710904, -12})); + STAmount{gw["USD"], UINT64_C(2666666666666667), -12}, + gw2["USD"](4000), + IOUAmount{3265986323710904, -12})); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{8164965809277260, -13})); BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{2449489742783178, -12})); - BEAST_EXPECT(env.balance(alice, gw["USD"]) == STAmount(gw["USD"], UINT64_C(7333333333333333), -12)); + BEAST_EXPECT( + env.balance(alice, gw["USD"]) == STAmount(gw["USD"], UINT64_C(7333333333333333), -12)); BEAST_EXPECT(env.balance(alice, gw2["USD"]) == gw2["USD"](4500)); BEAST_EXPECT(env.balance(bob, gw["USD"]) == gw["USD"](5000)); BEAST_EXPECT(env.balance(bob, gw2["USD"]) == gw2["USD"](2000)); @@ -1304,11 +1390,14 @@ class AMMClawback_test : public beast::unit_test::suite env(amm::ammClawback(gw, bob, gw["USD"], gw2["USD"], std::nullopt), ter(tesSUCCESS)); env.close(); BEAST_EXPECT(amm.expectBalances( - STAmount{gw["USD"], UINT64_C(6666666666666670), -13}, gw2["USD"](1000), IOUAmount{8164965809277260, -13})); + STAmount{gw["USD"], UINT64_C(6666666666666670), -13}, + gw2["USD"](1000), + IOUAmount{8164965809277260, -13})); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{8164965809277260, -13})); BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(0))); - BEAST_EXPECT(env.balance(alice, gw["USD"]) == STAmount(gw["USD"], UINT64_C(7333333333333333), -12)); + BEAST_EXPECT( + env.balance(alice, gw["USD"]) == STAmount(gw["USD"], UINT64_C(7333333333333333), -12)); BEAST_EXPECT(env.balance(alice, gw2["USD"]) == gw2["USD"](4500)); BEAST_EXPECT(env.balance(bob, gw["USD"]) == gw["USD"](5000)); // Bob gets 3000 gw2["USD"] back and now his balance is 5000. @@ -1371,9 +1460,11 @@ class AMMClawback_test : public beast::unit_test::suite env(amm::ammClawback(gw, gw2, USD, EUR, USD(1000)), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3] || !features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances(USD(5000), EUR(10000), IOUAmount{7071067811865475, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(5000), EUR(10000), IOUAmount{7071067811865475, -12})); else - BEAST_EXPECT(amm.expectBalances(USD(5000), EUR(10000), IOUAmount{7071067811865474, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(5000), EUR(10000), IOUAmount{7071067811865474, -12})); BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{1414213562373095, -12})); if (!features[fixAMMv1_3] || !features[fixAMMClawbackRounding]) @@ -1392,12 +1483,17 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectBalances( - USD(4500), STAmount(EUR, UINT64_C(9000000000000001), -12), IOUAmount{6363961030678928, -12})); + USD(4500), + STAmount(EUR, UINT64_C(9000000000000001), -12), + IOUAmount{6363961030678928, -12})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances(USD(4500), EUR(9000), IOUAmount{6363961030678928, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(4500), EUR(9000), IOUAmount{6363961030678928, -12})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectBalances( - USD(4500), STAmount(EUR, UINT64_C(9000000000000001), -12), IOUAmount{6363961030678927, -12})); + USD(4500), + STAmount(EUR, UINT64_C(9000000000000001), -12), + IOUAmount{6363961030678927, -12})); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{7071067811865480, -13})); @@ -1423,12 +1519,17 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectBalances( - USD(2500), STAmount(EUR, UINT64_C(5000000000000001), -12), IOUAmount{3535533905932738, -12})); + USD(2500), + STAmount(EUR, UINT64_C(5000000000000001), -12), + IOUAmount{3535533905932738, -12})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances(USD(2500), EUR(5000), IOUAmount{3535533905932738, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(2500), EUR(5000), IOUAmount{3535533905932738, -12})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectBalances( - USD(2500), STAmount(EUR, UINT64_C(5000000000000001), -12), IOUAmount{3535533905932737, -12})); + USD(2500), + STAmount(EUR, UINT64_C(5000000000000001), -12), + IOUAmount{3535533905932737, -12})); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{7071067811865480, -13})); @@ -1518,7 +1619,8 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT(amm.expectBalances(USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); // freeze trustline env(trust(gw, alice["USD"](0), tfSetFreeze)); @@ -1581,7 +1683,8 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT(amm.expectBalances(USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); // freeze trustlines env(trust(gw, alice["USD"](0), tfSetFreeze)); @@ -1630,7 +1733,8 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT(amm.expectBalances(USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); + BEAST_EXPECT( + amm.expectBalances(USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); // global freeze env(fset(gw, asfGlobalFreeze)); @@ -1711,14 +1815,17 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3]) BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); else - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); + BEAST_EXPECT( + env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); // 250 EUR goes back to carol. BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); // gw clawback 1000 USD from bob with tfClawTwoAssets flag. // then the corresponding EUR will also be clawed back // by gw. - env(amm::ammClawback(gw, bob, USD, EUR, USD(1000)), txflags(tfClawTwoAssets), ter(tesSUCCESS)); + env(amm::ammClawback(gw, bob, USD, EUR, USD(1000)), + txflags(tfClawTwoAssets), + ter(tesSUCCESS)); env.close(); BEAST_EXPECT(amm.expectBalances(USD(12000), EUR(3000), IOUAmount(6000))); @@ -1733,11 +1840,14 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3]) BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); else - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); + BEAST_EXPECT( + env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); // gw clawback all USD from alice and set tfClawTwoAssets. - env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), txflags(tfClawTwoAssets), ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), + txflags(tfClawTwoAssets), + ter(tesSUCCESS)); env.close(); BEAST_EXPECT(amm.expectBalances(USD(4000), EUR(1000), IOUAmount(2000))); @@ -1751,7 +1861,8 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3]) BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); else - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); + BEAST_EXPECT( + env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); } } @@ -1800,11 +1911,11 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); if (!features[fixAMMv1_3]) - BEAST_EXPECT( - amm.expectBalances(STAmount(USD, UINT64_C(5656854249492380), -13), XRP(70.710678), IOUAmount(200000))); + BEAST_EXPECT(amm.expectBalances( + STAmount(USD, UINT64_C(5656854249492380), -13), XRP(70.710678), IOUAmount(200000))); else - BEAST_EXPECT( - amm.expectBalances(STAmount(USD, UINT64_C(565'685424949238), -12), XRP(70.710679), IOUAmount(200000))); + BEAST_EXPECT(amm.expectBalances( + STAmount(USD, UINT64_C(565'685424949238), -12), XRP(70.710679), IOUAmount(200000))); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); if (!features[fixAMMv1_3]) BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(29.289322))); @@ -1837,10 +1948,14 @@ class AMMClawback_test : public beast::unit_test::suite return USD; }; - auto getLPTokenBalances = - [&](auto& env, auto const& amm, auto const& account) -> std::pair { - auto const lpToken = getAccountLines(env, account, amm.lptIssue())[jss::lines][0u][jss::balance].asString(); - auto const lpTokenBalance = amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value].asString(); + auto getLPTokenBalances = [&](auto& env, + auto const& amm, + auto const& account) -> std::pair { + auto const lpToken = + getAccountLines(env, account, amm.lptIssue())[jss::lines][0u][jss::balance] + .asString(); + auto const lpTokenBalance = + amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value].asString(); return {lpToken, lpTokenBalance}; }; @@ -1871,8 +1986,8 @@ class AMMClawback_test : public beast::unit_test::suite { auto const lpBalance = IOUAmount{989, -12}; env(amm::ammClawback(gw, alice, USD, XRP, USD(1))); - BEAST_EXPECT( - amm.expectBalances(STAmount(USD, UINT64_C(7000000000000000), -28), XRPAmount(1), lpBalance)); + BEAST_EXPECT(amm.expectBalances( + STAmount(USD, UINT64_C(7000000000000000), -28), XRPAmount(1), lpBalance)); BEAST_EXPECT(amm.expectLPTokens(alice, lpBalance)); } } @@ -1913,8 +2028,8 @@ class AMMClawback_test : public beast::unit_test::suite else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) { auto const lpBalance = IOUAmount{708'9829046743238, -13}; - BEAST_EXPECT( - amm.expectBalances(STAmount(USD, UINT64_C(5013266196406999), -16), XRPAmount(1002655), lpBalance)); + BEAST_EXPECT(amm.expectBalances( + STAmount(USD, UINT64_C(5013266196406999), -16), XRPAmount(1002655), lpBalance)); BEAST_EXPECT(amm.expectLPTokens(alice, lpBalance)); } } @@ -1945,7 +2060,9 @@ class AMMClawback_test : public beast::unit_test::suite { env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt)); BEAST_EXPECT(amm.expectBalances( - STAmount(USD, UINT64_C(2410000000000000), -28), XRPAmount(1), IOUAmount{34, -11})); + STAmount(USD, UINT64_C(2410000000000000), -28), + XRPAmount(1), + IOUAmount{34, -11})); } else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) { @@ -2026,7 +2143,9 @@ class AMMClawback_test : public beast::unit_test::suite } else { - env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), txflags(tfClawTwoAssets), ter(tecINTERNAL)); + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), + txflags(tfClawTwoAssets), + ter(tecINTERNAL)); BEAST_EXPECT(amm.ammExists()); } } @@ -2061,7 +2180,9 @@ class AMMClawback_test : public beast::unit_test::suite { env(amm::ammClawback(gw, alice, USD, EUR, USD(1))); BEAST_EXPECT(amm.expectBalances( - STAmount(USD, UINT64_C(4), -15), STAmount(EUR, UINT64_C(8), -9), IOUAmount{6, -12})); + STAmount(USD, UINT64_C(4), -15), + STAmount(EUR, UINT64_C(8), -9), + IOUAmount{6, -12})); } else if (!features[fixAMMClawbackRounding]) { @@ -2074,8 +2195,8 @@ class AMMClawback_test : public beast::unit_test::suite { env(amm::ammClawback(gw, alice, USD, EUR, USD(1)), txflags(tfClawTwoAssets)); auto const lpBalance = IOUAmount{5, -12}; - BEAST_EXPECT( - amm.expectBalances(STAmount(USD, UINT64_C(4), -15), STAmount(EUR, UINT64_C(8), -9), lpBalance)); + BEAST_EXPECT(amm.expectBalances( + STAmount(USD, UINT64_C(4), -15), STAmount(EUR, UINT64_C(8), -9), lpBalance)); BEAST_EXPECT(amm.expectLPTokens(alice, lpBalance)); } } @@ -2086,11 +2207,13 @@ class AMMClawback_test : public beast::unit_test::suite { // For now, just disable SAV entirely, which locks in the small Number // mantissas - FeatureBitset const all = jtx::testable_amendments() - featureSingleAssetVault - featureLendingProtocol; + FeatureBitset const all = + jtx::testable_amendments() - featureSingleAssetVault - featureLendingProtocol; testInvalidRequest(); testFeatureDisabled(all - featureAMMClawback); - for (auto const& features : {all - fixAMMv1_3 - fixAMMClawbackRounding, all - fixAMMClawbackRounding, all}) + for (auto const& features : + {all - fixAMMv1_3 - fixAMMClawbackRounding, all - fixAMMClawbackRounding, all}) { testAMMClawbackSpecificAmount(features); testAMMClawbackExceedBalance(features); diff --git a/src/test/app/AMMExtended_test.cpp b/src/test/app/AMMExtended_test.cpp index 4eecb05905..06f82418da 100644 --- a/src/test/app/AMMExtended_test.cpp +++ b/src/test/app/AMMExtended_test.cpp @@ -5,15 +5,15 @@ #include #include -#include -#include #include -#include -#include #include #include #include +#include +#include +#include +#include #include #include @@ -66,7 +66,10 @@ private: PathSet paths(Path(XRP, USD), Path(USD)); - env(pay(alice, bob, USD(100)), json(paths.json()), sendmax(BTC(1'000)), txflags(tfPartialPayment)); + env(pay(alice, bob, USD(100)), + json(paths.json()), + sendmax(BTC(1'000)), + txflags(tfPartialPayment)); if (!features[fixAMMv1_1]) { @@ -145,7 +148,10 @@ private: AMM ammDan(env, dan, XRP(10'000), USD1(10'050)); - env(pay(alice, carol, USD2(50)), path(~USD1, bob), sendmax(XRP(50)), txflags(tfNoRippleDirect)); + env(pay(alice, carol, USD2(50)), + path(~USD1, bob), + sendmax(XRP(50)), + txflags(tfNoRippleDirect)); BEAST_EXPECT(ammDan.expectBalances(XRP(10'050), USD1(10'000), ammDan.tokens())); BEAST_EXPECT(expectLedgerEntryRoot(env, alice, XRP(20'000) - XRP(50) - txfee(env, 1))); @@ -181,7 +187,8 @@ private: // Order that can be filled env(offer(carol, XRP(100), USD(100)), txflags(tfFillOrKill), ter(tesSUCCESS)); BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'100), ammAlice.tokens())); - BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRP(30'000) + XRP(100) - txfee(env, 2))); + BEAST_EXPECT( + expectLedgerEntryRoot(env, carol, XRP(30'000) + XRP(100) - txfee(env, 2))); BEAST_EXPECT(expectHolding(env, carol, USD(29'900))); BEAST_EXPECT(expectOffers(env, carol, 0)); }, @@ -194,13 +201,16 @@ private: // and add nothing on the books. testAMM( [&](AMM& ammAlice, Env& env) { - env(offer(carol, XRP(200), USD(200)), txflags(tfImmediateOrCancel), ter(tesSUCCESS)); + env(offer(carol, XRP(200), USD(200)), + txflags(tfImmediateOrCancel), + ter(tesSUCCESS)); // AMM generates a synthetic offer of 100USD/100XRP // to match the CLOB offer quality. BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'100), ammAlice.tokens())); // +AMM - offer * fee - BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRP(30'000) + XRP(100) - txfee(env, 1))); + BEAST_EXPECT( + expectLedgerEntryRoot(env, carol, XRP(30'000) + XRP(100) - txfee(env, 1))); // AMM BEAST_EXPECT(expectHolding(env, carol, USD(29'900))); BEAST_EXPECT(expectOffers(env, carol, 0)); @@ -217,7 +227,8 @@ private: // Carol's offer should stay in the ledger. env(offer(carol, XRP(100), USD(100), tfPassive)); env.close(); - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), STAmount{USD, 10'000}, ammAlice.tokens())); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'100), STAmount{USD, 10'000}, ammAlice.tokens())); BEAST_EXPECT(expectOffers(env, carol, 1, {{{XRP(100), STAmount{USD, 100}}}})); }, {{XRP(10'100), USD(10'000)}}, @@ -236,7 +247,9 @@ private: env(offer(carol, XRP(100), USD(100), tfPassive)); env.close(); BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'900), STAmount{USD, UINT64_C(9'082'56880733945), -11}, ammAlice.tokens())); + XRP(10'900), + STAmount{USD, UINT64_C(9'082'56880733945), -11}, + ammAlice.tokens())); BEAST_EXPECT(expectOffers(env, carol, 0)); BEAST_EXPECT(expectOffers(env, alice, 1)); }, @@ -265,10 +278,12 @@ private: auto const xrpTransferred = XRPAmount{3'061'224'490}; env(offer(bob, USD(1), XRP(4'000))); - BEAST_EXPECT(ammAlice.expectBalances(XRP(150'000) + xrpTransferred, USD(49), IOUAmount{273'861'278752583, -8})); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(150'000) + xrpTransferred, USD(49), IOUAmount{273'861'278752583, -8})); BEAST_EXPECT(expectHolding(env, bob, STAmount{USD, 101})); - BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(300'000) - xrpTransferred - txfee(env, 1))); + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(300'000) - xrpTransferred - txfee(env, 1))); BEAST_EXPECT(expectOffers(env, bob, 0)); } @@ -350,12 +365,16 @@ private: // we permit partial payment env(pay(alice, alice, XRP(100)), sendmax(USD(100)), txflags(tfPartialPayment)); env.close(); - BEAST_EXPECT(ammAlice.expectBalances(XRPAmount{9'900'990'100}, USD(10'100), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount{9'900'990'100}, USD(10'100), ammAlice.tokens())); // initial 30,000 - 10,000AMM - 100pay BEAST_EXPECT(expectHolding(env, alice, USD(19'900))); // initial 30,000 - 10,0000AMM + 99.009900pay - fee*3 BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, XRP(30'000) - XRP(10'000) + XRPAmount{99'009'900} - ammCrtFee(env) - txfee(env, 2))); + env, + alice, + XRP(30'000) - XRP(10'000) + XRPAmount{99'009'900} - ammCrtFee(env) - + txfee(env, 2))); }, {{XRP(10'000), USD(10'000)}}, 0, @@ -401,7 +420,8 @@ private: env.close(); env(pay(alice, bob, XRP(100)), sendmax(USD(100))); BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'100), ammAlice.tokens())); - BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(1'000) + XRP(100) - txfee(env, 1))); + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(1'000) + XRP(100) - txfee(env, 1))); }, {{XRP(10'100), USD(10'000)}}, 0, @@ -449,8 +469,8 @@ private: jtp[0u][0u][jss::currency] = "XRP"; env(pay(alice, bob, EUR1(30)), json(jss::Paths, jtp), sendmax(USD1(333))); env.close(); - BEAST_EXPECT( - ammCarol.expectBalances(XRP(49'700), STAmount{USD1, UINT64_C(5'030'181086519115), -12}, ammCarol.tokens())); + BEAST_EXPECT(ammCarol.expectBalances( + XRP(49'700), STAmount{USD1, UINT64_C(5'030'181086519115), -12}, ammCarol.tokens())); BEAST_EXPECT(expectOffers(env, dan, 1, {{Amounts{XRP(200), EUR(20)}}})); BEAST_EXPECT(expectHolding(env, bob, STAmount{EUR1, 30})); } @@ -479,7 +499,8 @@ private: // fees: // 1 for each trust limit == 3 (alice < mtgox/amazon/bitstamp) + // 1 for payment == 4 - auto const starting_xrp = XRP(100) + env.current()->fees().accountReserve(3) + env.current()->fees().base * 4; + auto const starting_xrp = + XRP(100) + env.current()->fees().accountReserve(3) + env.current()->fees().base * 4; env.fund(starting_xrp, gw1, gw2, gw3, alice); env.fund(XRP(2'000), bob); @@ -500,8 +521,8 @@ private: // The pool gets only 100XRP for ~109.09USD, even though // it can exchange more. - BEAST_EXPECT( - ammBob.expectBalances(XRP(1'100), STAmount{USD1, UINT64_C(1'090'909090909091), -12}, ammBob.tokens())); + BEAST_EXPECT(ammBob.expectBalances( + XRP(1'100), STAmount{USD1, UINT64_C(1'090'909090909091), -12}, ammBob.tokens())); auto jrr = ledgerEntryState(env, alice, gw1, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "109.090909090909"); @@ -552,7 +573,8 @@ private: BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(9'999), ammAlice.tokens())); BEAST_EXPECT(expectOffers(env, carol, 0)); BEAST_EXPECT(expectHolding(env, carol, USD(30'101))); - BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRP(30'000) - XRP(100) - txfee(env, 1))); + BEAST_EXPECT( + expectLedgerEntryRoot(env, carol, XRP(30'000) - XRP(100) - txfee(env, 1))); }, {{XRP(9'900), USD(10'100)}}, 0, @@ -615,7 +637,8 @@ private: payment[jss::id] = env.seq(bob); payment[jss::build_path] = true; payment[jss::tx_json] = pay(bob, bob, bob["XXX"](1)); - payment[jss::tx_json][jss::Sequence] = env.current()->read(keylet::account(bob.id()))->getFieldU32(sfSequence); + payment[jss::tx_json][jss::Sequence] = + env.current()->read(keylet::account(bob.id()))->getFieldU32(sfSequence); payment[jss::tx_json][jss::Fee] = to_string(env.current()->fees().base); payment[jss::tx_json][jss::SendMax] = bob["XTS"](1.5).value().getJson(JsonOptions::none); payment[jss::tx_json][jss::Flags] = tfPartialPayment; @@ -624,14 +647,14 @@ private: BEAST_EXPECT(jrr[jss::result][jss::engine_result] == "tesSUCCESS"); if (!features[fixAMMv1_1]) { - BEAST_EXPECT( - ammAlice.expectBalances(STAmount(XTS, UINT64_C(101'010101010101), -12), XXX(99), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount(XTS, UINT64_C(101'010101010101), -12), XXX(99), ammAlice.tokens())); BEAST_EXPECT(expectHolding(env, bob, STAmount{XTS, UINT64_C(98'989898989899), -12})); } else { - BEAST_EXPECT( - ammAlice.expectBalances(STAmount(XTS, UINT64_C(101'0101010101011), -13), XXX(99), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount(XTS, UINT64_C(101'0101010101011), -13), XXX(99), ammAlice.tokens())); BEAST_EXPECT(expectHolding(env, bob, STAmount{XTS, UINT64_C(98'9898989898989), -13})); } BEAST_EXPECT(expectHolding(env, bob, XXX(101))); @@ -757,9 +780,10 @@ private: // Even though tfSell is present it doesn't matter this time. env(offer(alice, USD(2), XRP(220), tfSell | tfFillOrKill)); env.close(); + BEAST_EXPECT(ammBob.expectBalances( + XRP(20'220), STAmount{USD, UINT64_C(197'8239366963403), -13}, ammBob.tokens())); BEAST_EXPECT( - ammBob.expectBalances(XRP(20'220), STAmount{USD, UINT64_C(197'8239366963403), -13}, ammBob.tokens())); - BEAST_EXPECT(expectHolding(env, alice, STAmount{USD, UINT64_C(1'002'17606330366), -11})); + expectHolding(env, alice, STAmount{USD, UINT64_C(1'002'17606330366), -11})); BEAST_EXPECT(expectOffers(env, alice, 0)); } { @@ -772,9 +796,10 @@ private: env(offer(alice, USD(10), XRP(1'500), tfSell | tfFillOrKill)); env.close(); + BEAST_EXPECT(ammBob.expectBalances( + XRP(21'500), STAmount{USD, UINT64_C(186'046511627907), -12}, ammBob.tokens())); BEAST_EXPECT( - ammBob.expectBalances(XRP(21'500), STAmount{USD, UINT64_C(186'046511627907), -12}, ammBob.tokens())); - BEAST_EXPECT(expectHolding(env, alice, STAmount{USD, UINT64_C(1'013'953488372093), -12})); + expectHolding(env, alice, STAmount{USD, UINT64_C(1'013'953488372093), -12})); BEAST_EXPECT(expectOffers(env, alice, 0)); } { @@ -1194,7 +1219,8 @@ private: AMM ammAlice(env, alice, USD(1'000), XRP(1'050)); // Set up authorized trust line for AMM. - env(trust(gw, STAmount{Issue{USD.currency, ammAlice.ammAccount()}, 10}), txflags(tfSetfAuth)); + env(trust(gw, STAmount{Issue{USD.currency, ammAlice.ammAccount()}, 10}), + txflags(tfSetfAuth)); env.close(); env(pay(gw, bob, USD(50))); @@ -1264,7 +1290,8 @@ private: AMM ammAlice(env, alice, USD(1'000), XRP(1'050)); // Set up authorized trust line for AMM. - env(trust(gw, STAmount{Issue{USD.currency, ammAlice.ammAccount()}, 10}), txflags(tfSetfAuth)); + env(trust(gw, STAmount{Issue{USD.currency, ammAlice.ammAccount()}, 10}), + txflags(tfSetfAuth)); env.close(); // Now bob creates his offer again, which crosses with alice's AMM. @@ -1282,7 +1309,8 @@ private: using namespace jtx; // For now, just disable SAV entirely, which locks in the small Number // mantissas - FeatureBitset const all{testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; + FeatureBitset const all{ + testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; testRmFundedOffer(all); testRmFundedOffer(all - fixAMMv1_1 - fixAMMv1_3); @@ -1327,9 +1355,11 @@ private: STPathSet st; STAmount sa; STAmount da; - std::tie(st, sa, da) = find_paths(env, alice, bob, bob["AUD"](-1), std::optional(XRP(100'000'000))); + std::tie(st, sa, da) = + find_paths(env, alice, bob, bob["AUD"](-1), std::optional(XRP(100'000'000))); BEAST_EXPECT(st.empty()); - std::tie(st, sa, da) = find_paths(env, alice, bob, bob["USD"](-1), std::optional(XRP(100'000'000))); + std::tie(st, sa, da) = + find_paths(env, alice, bob, bob["USD"](-1), std::optional(XRP(100'000'000))); // Alice sends all requested 100,000,000XRP BEAST_EXPECT(sa == XRP(100'000'000)); // Bob gets ~99.99USD. This is the amount Bob @@ -1383,7 +1413,8 @@ private: { auto const& pathElem = st[0][0]; BEAST_EXPECT( - pathElem.isOffer() && pathElem.getIssuerID() == gw.id() && pathElem.getCurrency() == USD.currency); + pathElem.isOffer() && pathElem.getIssuerID() == gw.id() && + pathElem.getCurrency() == USD.currency); } } { @@ -1459,7 +1490,8 @@ private: // no path should exist for this since dest account // does not exist. auto const& send_amt = XRP(200); - std::tie(st, sa, da) = find_paths(env, A1, Account{"A0"}, send_amt, std::nullopt, xrpCurrency()); + std::tie(st, sa, da) = + find_paths(env, A1, Account{"A0"}, send_amt, std::nullopt, xrpCurrency()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(st.empty()); } @@ -1576,7 +1608,8 @@ private: // A) Borrow or repay -- // Source -> Destination (repay source issuer) auto const& send_amt = G1["HKD"](10); - std::tie(st, sa, da) = find_paths(env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency); + std::tie(st, sa, da) = + find_paths(env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency); BEAST_EXPECT(st.empty()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); @@ -1586,7 +1619,8 @@ private: // A2) Borrow or repay -- // Source -> Destination (repay destination issuer) auto const& send_amt = A1["HKD"](10); - std::tie(st, sa, da) = find_paths(env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency); + std::tie(st, sa, da) = + find_paths(env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency); BEAST_EXPECT(st.empty()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); @@ -1596,7 +1630,8 @@ private: // B) Common gateway -- // Source -> AC -> Destination auto const& send_amt = A3["HKD"](10); - std::tie(st, sa, da) = find_paths(env, A1, A3, send_amt, std::nullopt, G1["HKD"].currency); + std::tie(st, sa, da) = + find_paths(env, A1, A3, send_amt, std::nullopt, G1["HKD"].currency); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same(st, stpath(G1))); @@ -1606,18 +1641,24 @@ private: // C) Gateway to gateway -- // Source -> OB -> Destination auto const& send_amt = G2["HKD"](10); - std::tie(st, sa, da) = find_paths(env, G1, G2, send_amt, std::nullopt, G1["HKD"].currency); + std::tie(st, sa, da) = + find_paths(env, G1, G2, send_amt, std::nullopt, G1["HKD"].currency); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, G1["HKD"](10))); - BEAST_EXPECT( - same(st, stpath(IPE(G2["HKD"])), stpath(M1), stpath(M2), stpath(IPE(xrpIssue()), IPE(G2["HKD"])))); + BEAST_EXPECT(same( + st, + stpath(IPE(G2["HKD"])), + stpath(M1), + stpath(M2), + stpath(IPE(xrpIssue()), IPE(G2["HKD"])))); } { // D) User to unlinked gateway via order book -- // Source -> AC -> OB -> Destination auto const& send_amt = G2["HKD"](10); - std::tie(st, sa, da) = find_paths(env, A1, G2, send_amt, std::nullopt, G1["HKD"].currency); + std::tie(st, sa, da) = + find_paths(env, A1, G2, send_amt, std::nullopt, G1["HKD"].currency); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same( @@ -1633,7 +1674,8 @@ private: // Source -> AC -> OB to XRP -> OB from XRP -> AC -> // Destination auto const& send_amt = A2["HKD"](10); - std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, G1["HKD"].currency); + std::tie(st, sa, da) = + find_paths(env, A1, A2, send_amt, std::nullopt, G1["HKD"].currency); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same( @@ -2005,17 +2047,18 @@ private: if (!features[fixAMMv1_1]) { // 120GBP is swapped in for 107.1428USD - BEAST_EXPECT( - amm.expectBalances(GBP(1'120), STAmount{USD, UINT64_C(892'8571428571428), -13}, amm.tokens())); + BEAST_EXPECT(amm.expectBalances( + GBP(1'120), STAmount{USD, UINT64_C(892'8571428571428), -13}, amm.tokens())); } else { - BEAST_EXPECT( - amm.expectBalances(GBP(1'120), STAmount{USD, UINT64_C(892'8571428571429), -13}, amm.tokens())); + BEAST_EXPECT(amm.expectBalances( + GBP(1'120), STAmount{USD, UINT64_C(892'8571428571429), -13}, amm.tokens())); } // 25% of 85.7142USD is paid in tr fee // 85.7142*1.25 = 107.1428USD - BEAST_EXPECT(expectHolding(env, carol, STAmount(USD, UINT64_C(1'085'714285714286), -12))); + BEAST_EXPECT( + expectHolding(env, carol, STAmount(USD, UINT64_C(1'085'714285714286), -12))); } { @@ -2023,7 +2066,8 @@ private: Env env(*this, features); Account const ed("ed"); - fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'000), EUR(1'000), GBP(1'000)}); + fund( + env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'000), EUR(1'000), GBP(1'000)}); env(rate(gw, 1.25)); env.close(); @@ -2048,16 +2092,19 @@ private: BEAST_EXPECT(expectOffers(env, ed, 1, {Amounts{GBP(880), EUR(880)}})); // 25% on 96EUR is paid in tr fee 96*1.25 = 120EUR // 96EUR is swapped in for 87.5912USD - BEAST_EXPECT(amm.expectBalances(EUR(1'096), STAmount{USD, UINT64_C(912'4087591240876), -13}, amm.tokens())); + BEAST_EXPECT(amm.expectBalances( + EUR(1'096), STAmount{USD, UINT64_C(912'4087591240876), -13}, amm.tokens())); // 25% on 70.0729USD is paid in tr fee 70.0729*1.25 = 87.5912USD - BEAST_EXPECT(expectHolding(env, carol, STAmount(USD, UINT64_C(1'070'07299270073), -11))); + BEAST_EXPECT( + expectHolding(env, carol, STAmount(USD, UINT64_C(1'070'07299270073), -11))); } { // Payment via AMM, AMM Env env(*this, features); Account const ed("ed"); - fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'000), EUR(1'000), GBP(1'000)}); + fund( + env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'000), EUR(1'000), GBP(1'000)}); env(rate(gw, 1.25)); env.close(); @@ -2076,8 +2123,8 @@ private: // alice buys 107.1428EUR with 120GBP and pays 25% tr fee on // 120GBP 1,000 - 120*1.25 = 850GBP 120GBP is swapped in for // 107.1428EUR - BEAST_EXPECT( - amm1.expectBalances(GBP(1'120), STAmount{EUR, UINT64_C(892'8571428571428), -13}, amm1.tokens())); + BEAST_EXPECT(amm1.expectBalances( + GBP(1'120), STAmount{EUR, UINT64_C(892'8571428571428), -13}, amm1.tokens())); // 25% on 85.7142EUR is paid in tr fee 85.7142*1.25 = // 107.1428EUR 85.7142EUR is swapped in for 78.9473USD BEAST_EXPECT(amm2.expectBalances( @@ -2090,8 +2137,8 @@ private: // alice buys 107.1428EUR with 120GBP and pays 25% tr fee on // 120GBP 1,000 - 120*1.25 = 850GBP 120GBP is swapped in for // 107.1428EUR - BEAST_EXPECT( - amm1.expectBalances(GBP(1'120), STAmount{EUR, UINT64_C(892'8571428571429), -13}, amm1.tokens())); + BEAST_EXPECT(amm1.expectBalances( + GBP(1'120), STAmount{EUR, UINT64_C(892'8571428571429), -13}, amm1.tokens())); // 25% on 85.7142EUR is paid in tr fee 85.7142*1.25 = // 107.1428EUR 85.7142EUR is swapped in for 78.9473USD BEAST_EXPECT(amm2.expectBalances( @@ -2100,7 +2147,8 @@ private: amm2.tokens())); } // 25% on 63.1578USD is paid in tr fee 63.1578*1.25 = 78.9473USD - BEAST_EXPECT(expectHolding(env, carol, STAmount(USD, UINT64_C(1'063'157894736842), -12))); + BEAST_EXPECT( + expectHolding(env, carol, STAmount(USD, UINT64_C(1'063'157894736842), -12))); } { // AMM offer crossing @@ -2142,9 +2190,11 @@ private: // alice buys 125USD with 142.8571GBP and pays 25% tr fee // on 142.8571GBP // 1,000 - 142.8571*1.25 = 821.4285GBP - BEAST_EXPECT(expectHolding(env, alice, STAmount(GBP, UINT64_C(821'4285714285712), -13))); + BEAST_EXPECT( + expectHolding(env, alice, STAmount(GBP, UINT64_C(821'4285714285712), -13))); // 142.8571GBP is swapped in for 125USD - BEAST_EXPECT(amm.expectBalances(STAmount{GBP, UINT64_C(1'142'857142857143), -12}, USD(875), amm.tokens())); + BEAST_EXPECT(amm.expectBalances( + STAmount{GBP, UINT64_C(1'142'857142857143), -12}, USD(875), amm.tokens())); // 25% on 100USD is paid in tr fee // 100*1.25 = 125USD BEAST_EXPECT(expectHolding(env, carol, USD(1'100))); @@ -2182,10 +2232,13 @@ private: // alice buys 28.125USD with 24GBP and pays 25% tr fee // on 24GBP // 1,200 - 24*1.25 =~ 1,170GBP - BEAST_EXPECT(expectHolding(env, alice, STAmount{GBP, UINT64_C(1'169'999999999999), -12})); - // 24GBP is swapped in for 28.125USD BEAST_EXPECT( - amm.expectBalances(STAmount{GBP, UINT64_C(1'024'000000000001), -12}, USD(1'171.875), amm.tokens())); + expectHolding(env, alice, STAmount{GBP, UINT64_C(1'169'999999999999), -12})); + // 24GBP is swapped in for 28.125USD + BEAST_EXPECT(amm.expectBalances( + STAmount{GBP, UINT64_C(1'024'000000000001), -12}, + USD(1'171.875), + amm.tokens())); } // 25% on 22.5USD is paid in tr fee // 22.5*1.25 = 28.125USD @@ -2197,7 +2250,8 @@ private: Env env(*this, features); Account const ed("ed"); - fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'400), EUR(1'400), GBP(1'400)}); + fund( + env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'400), EUR(1'400), GBP(1'400)}); env(rate(gw, 1.25)); env.close(); @@ -2219,7 +2273,8 @@ private: // alice buys 70.4210EUR with 70.4210GBP via the offer // and pays 25% tr fee on 70.4210GBP // 1,400 - 70.4210*1.25 = 1400 - 88.0262 = 1311.9736GBP - BEAST_EXPECT(expectHolding(env, alice, STAmount{GBP, UINT64_C(1'311'973684210527), -12})); + BEAST_EXPECT( + expectHolding(env, alice, STAmount{GBP, UINT64_C(1'311'973684210527), -12})); // ed doesn't pay tr fee, the balances reflect consumed offer // 70.4210GBP/70.4210EUR BEAST_EXPECT(expectHolding( @@ -2246,7 +2301,8 @@ private: // alice buys 70.4210EUR with 70.4210GBP via the offer // and pays 25% tr fee on 70.4210GBP // 1,400 - 70.4210*1.25 = 1400 - 88.0262 = 1311.9736GBP - BEAST_EXPECT(expectHolding(env, alice, STAmount{GBP, UINT64_C(1'311'973684210525), -12})); + BEAST_EXPECT( + expectHolding(env, alice, STAmount{GBP, UINT64_C(1'311'973684210525), -12})); // ed doesn't pay tr fee, the balances reflect consumed offer // 70.4210GBP/70.4210EUR BEAST_EXPECT(expectHolding( @@ -2269,7 +2325,8 @@ private: amm.tokens())); } // 25% on 59.7321USD is paid in tr fee 59.7321*1.25 = 74.6651USD - BEAST_EXPECT(expectHolding(env, carol, STAmount(USD, UINT64_C(1'459'732142857143), -12))); + BEAST_EXPECT( + expectHolding(env, carol, STAmount(USD, UINT64_C(1'459'732142857143), -12))); } { // Payment via AMM and offer with limit quality, deliver less @@ -2277,7 +2334,8 @@ private: Env env(*this, features); Account const ed("ed"); - fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'400), EUR(1'400), GBP(1'400)}); + fund( + env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'400), EUR(1'400), GBP(1'400)}); env(rate(gw, 1.25)); env.close(); @@ -2299,7 +2357,8 @@ private: // alice buys 53.3322EUR with 56.3368GBP via the amm // and pays 25% tr fee on 56.3368GBP // 1,400 - 56.3368*1.25 = 1400 - 70.4210 = 1329.5789GBP - BEAST_EXPECT(expectHolding(env, alice, STAmount{GBP, UINT64_C(1'329'578947368421), -12})); + BEAST_EXPECT( + expectHolding(env, alice, STAmount{GBP, UINT64_C(1'329'578947368421), -12})); //// 25% on 56.3368EUR is paid in tr fee 56.3368*1.25 ///= 70.4210EUR // 56.3368GBP is swapped in for 53.3322EUR @@ -2313,7 +2372,8 @@ private: // alice buys 53.3322EUR with 56.3368GBP via the amm // and pays 25% tr fee on 56.3368GBP // 1,400 - 56.3368*1.25 = 1400 - 70.4210 = 1329.5789GBP - BEAST_EXPECT(expectHolding(env, alice, STAmount{GBP, UINT64_C(1'329'57894736842), -11})); + BEAST_EXPECT( + expectHolding(env, alice, STAmount{GBP, UINT64_C(1'329'57894736842), -11})); //// 25% on 56.3368EUR is paid in tr fee 56.3368*1.25 ///= 70.4210EUR // 56.3368GBP is swapped in for 53.3322EUR @@ -2337,7 +2397,8 @@ private: STAmount{EUR, UINT64_C(957'3341836734693), -13}, STAmount{USD, UINT64_C(1'340'267857142857), -12}}})); // 25% on 47.7857USD is paid in tr fee 47.7857*1.25 = 59.7321USD - BEAST_EXPECT(expectHolding(env, carol, STAmount(USD, UINT64_C(1'447'785714285714), -12))); + BEAST_EXPECT( + expectHolding(env, carol, STAmount(USD, UINT64_C(1'447'785714285714), -12))); } { // Payment via AMM, AMM with limit quality, deliver less @@ -2345,7 +2406,8 @@ private: Env env(*this, features); Account const ed("ed"); - fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'400), EUR(1'400), GBP(1'400)}); + fund( + env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'400), EUR(1'400), GBP(1'400)}); env(rate(gw, 1.25)); env.close(); @@ -2365,7 +2427,8 @@ private: // alice buys 53.3322EUR with 107.5308GBP // 25% on 86.0246GBP is paid in tr fee // 1,400 - 86.0246*1.25 = 1400 - 107.5308 = 1229.4691GBP - BEAST_EXPECT(expectHolding(env, alice, STAmount{GBP, UINT64_C(1'292'469135802469), -12})); + BEAST_EXPECT( + expectHolding(env, alice, STAmount{GBP, UINT64_C(1'292'469135802469), -12})); // 86.0246GBP is swapped in for 79.2106EUR BEAST_EXPECT(amm1.expectBalances( STAmount{GBP, UINT64_C(1'086'024691358025), -12}, @@ -2383,7 +2446,8 @@ private: // alice buys 53.3322EUR with 107.5308GBP // 25% on 86.0246GBP is paid in tr fee // 1,400 - 86.0246*1.25 = 1400 - 107.5308 = 1229.4691GBP - BEAST_EXPECT(expectHolding(env, alice, STAmount{GBP, UINT64_C(1'292'469135802466), -12})); + BEAST_EXPECT( + expectHolding(env, alice, STAmount{GBP, UINT64_C(1'292'469135802466), -12})); // 86.0246GBP is swapped in for 79.2106EUR BEAST_EXPECT(amm1.expectBalances( STAmount{GBP, UINT64_C(1'086'024691358027), -12}, @@ -2397,7 +2461,8 @@ private: amm2.tokens())); } // 25% on 66.7432USD is paid in tr fee 66.7432*1.25 = 83.4291USD - BEAST_EXPECT(expectHolding(env, carol, STAmount(USD, UINT64_C(1'466'743295019157), -12))); + BEAST_EXPECT( + expectHolding(env, carol, STAmount(USD, UINT64_C(1'466'743295019157), -12))); } { // Payment by the issuer via AMM, AMM with limit quality, @@ -2448,7 +2513,8 @@ private: amm2.tokens())); } // 25% on 81.1111USD is paid in tr fee 81.1111*1.25 = 101.3888USD - BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(1'481'111111111111), -12})); + BEAST_EXPECT( + expectHolding(env, carol, STAmount{USD, UINT64_C(1'481'111111111111), -12})); } } @@ -2599,13 +2665,22 @@ private: fund(env, gw, {alice, bob, carol}, XRP(10'000)); env.trust(USD(100), alice, bob, carol); env(pay(alice, bob, USD(10)), deliver_min(USD(10)), ter(temBAD_AMOUNT)); - env(pay(alice, bob, USD(10)), deliver_min(USD(-5)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); - env(pay(alice, bob, USD(10)), deliver_min(XRP(5)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); + env(pay(alice, bob, USD(10)), + deliver_min(USD(-5)), + txflags(tfPartialPayment), + ter(temBAD_AMOUNT)); + env(pay(alice, bob, USD(10)), + deliver_min(XRP(5)), + txflags(tfPartialPayment), + ter(temBAD_AMOUNT)); env(pay(alice, bob, USD(10)), deliver_min(Account(carol)["USD"](5)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); - env(pay(alice, bob, USD(10)), deliver_min(USD(15)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); + env(pay(alice, bob, USD(10)), + deliver_min(USD(15)), + txflags(tfPartialPayment), + ter(temBAD_AMOUNT)); env(pay(gw, carol, USD(50))); AMM ammCarol(env, carol, XRP(10), USD(15)); env(pay(alice, bob, USD(10)), @@ -2685,7 +2760,9 @@ private: env.require(balance(bob, USD(0))); env.require(balance(carol, STAmount{USD, UINT64_C(200'00000090909), -11})); BEAST_EXPECT(ammDan.expectBalances( - XRPAmount{1'100'000'001}, STAmount{USD, UINT64_C(999'99999909091), -11}, ammDan.tokens())); + XRPAmount{1'100'000'001}, + STAmount{USD, UINT64_C(999'99999909091), -11}, + ammDan.tokens())); } } } @@ -2942,7 +3019,8 @@ private: if (!BEAST_EXPECT(checkArraySize(affected, 2u))) return; auto ff = affected[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; - BEAST_EXPECT(ff[sfLowLimit.fieldName] == G1["USD"](0).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + ff[sfLowLimit.fieldName] == G1["USD"](0).value().getJson(JsonOptions::none)); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfLowFreeze)); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfHighFreeze)); env.close(); @@ -2989,7 +3067,8 @@ private: // Account without GlobalFreeze (proving operations normally // work) // test: visible offers where taker_pays is unfrozen issuer - auto offers = env.rpc("book_offers", std::string("USD/") + G1.human(), "XRP")[jss::result][jss::offers]; + auto offers = env.rpc( + "book_offers", std::string("USD/") + G1.human(), "XRP")[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 1u))) return; std::set accounts; @@ -3000,7 +3079,8 @@ private: BEAST_EXPECT(accounts.find(A2.human()) != std::end(accounts)); // test: visible offers where taker_gets is unfrozen issuer - offers = env.rpc("book_offers", "XRP", std::string("USD/") + G1.human())[jss::result][jss::offers]; + offers = env.rpc( + "book_offers", "XRP", std::string("USD/") + G1.human())[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 1u))) return; accounts.clear(); @@ -3053,11 +3133,13 @@ private: { // test: book_offers shows offers // (should these actually be filtered?) - auto offers = env.rpc("book_offers", "XRP", std::string("USD/") + G1.human())[jss::result][jss::offers]; + auto offers = env.rpc( + "book_offers", "XRP", std::string("USD/") + G1.human())[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 1u))) return; - offers = env.rpc("book_offers", std::string("USD/") + G1.human(), "XRP")[jss::result][jss::offers]; + offers = env.rpc( + "book_offers", std::string("USD/") + G1.human(), "XRP")[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 1u))) return; } @@ -3270,7 +3352,10 @@ private: AMM ammBob(env, bob, XRP(100), USD(100)); // payment path: XRP -> XRP/USD -> USD/XRP - env(pay(alice, carol, XRP(100)), path(~USD, ~XRP), txflags(tfNoRippleDirect), ter(temBAD_SEND_XRP_PATHS)); + env(pay(alice, carol, XRP(100)), + path(~USD, ~XRP), + txflags(tfNoRippleDirect), + ter(temBAD_SEND_XRP_PATHS)); } { @@ -3362,7 +3447,8 @@ private: using namespace jtx; // For now, just disable SAV entirely, which locks in the small Number // mantissas in the transaction engine - FeatureBitset const all{testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; + FeatureBitset const all{ + testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; testFalseDry(all); testBookStep(all); @@ -3378,7 +3464,8 @@ private: using namespace jtx; // For now, just disable SAV entirely, which locks in the small Number // mantissas in the transaction engine - FeatureBitset const all{testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; + FeatureBitset const all{ + testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; testStepLimit(all); testStepLimit(all - fixAMMv1_1 - fixAMMv1_3); } @@ -3389,7 +3476,8 @@ private: using namespace jtx; // For now, just disable SAV entirely, which locks in the small Number // mantissas in the transaction engine - FeatureBitset const all{testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; + FeatureBitset const all{ + testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; test_convert_all_of_an_asset(all); test_convert_all_of_an_asset(all - fixAMMv1_1 - fixAMMv1_3); } @@ -3399,7 +3487,8 @@ private: { // For now, just disable SAV entirely, which locks in the small Number // mantissas in the transaction engine - FeatureBitset const all{jtx::testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; + FeatureBitset const all{ + jtx::testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; testPayment(all); testPayIOU(); } @@ -3410,7 +3499,8 @@ private: using namespace test::jtx; // For now, just disable SAV entirely, which locks in the small Number // mantissas in the transaction engine - FeatureBitset const sa{testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; + FeatureBitset const sa{ + testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; testRippleState(sa); testGlobalFreeze(sa); testOffersWhenFrozen(sa); diff --git a/src/test/app/AMM_test.cpp b/src/test/app/AMM_test.cpp index 8a60e5f667..fc801be816 100644 --- a/src/test/app/AMM_test.cpp +++ b/src/test/app/AMM_test.cpp @@ -6,15 +6,14 @@ #include #include -#include -#include -#include -#include - #include #include #include #include +#include +#include +#include +#include #include @@ -53,7 +52,8 @@ private: // XRP to IOU, with featureSingleAssetVault testAMM( [&](AMM& ammAlice, Env&) { - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); }, {}, 0, @@ -64,7 +64,8 @@ private: // XRP to IOU, without featureSingleAssetVault testAMM( [&](AMM& ammAlice, Env&) { - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); }, {}, 0, @@ -132,8 +133,12 @@ private: 1'000); // Make sure asset comparison works. - BEAST_EXPECT(STIssue(sfAsset, STAmount(XRP(2'000)).issue()) == STIssue(sfAsset, STAmount(XRP(2'000)).issue())); - BEAST_EXPECT(STIssue(sfAsset, STAmount(XRP(2'000)).issue()) != STIssue(sfAsset, STAmount(USD(2'000)).issue())); + BEAST_EXPECT( + STIssue(sfAsset, STAmount(XRP(2'000)).issue()) == + STIssue(sfAsset, STAmount(XRP(2'000)).issue())); + BEAST_EXPECT( + STIssue(sfAsset, STAmount(XRP(2'000)).issue()) != + STIssue(sfAsset, STAmount(USD(2'000)).issue())); } void @@ -217,8 +222,9 @@ private: } // AMM already exists - testAMM( - [&](AMM& ammAlice, Env& env) { AMM ammCarol(env, carol, XRP(10'000), USD(10'000), ter(tecDUPLICATE)); }); + testAMM([&](AMM& ammAlice, Env& env) { + AMM ammCarol(env, carol, XRP(10'000), USD(10'000), ter(tecDUPLICATE)); + }); // Invalid flags { @@ -354,9 +360,17 @@ private: testAMM([&](AMM& ammAlice, Env& env) { fund(env, gw, {alice}, {EUR(10'000)}, Fund::IOUOnly); AMM ammAMMToken( - env, alice, EUR(10'000), STAmount{ammAlice.lptIssue(), 1'000'000}, ter(tecAMM_INVALID_TOKENS)); + env, + alice, + EUR(10'000), + STAmount{ammAlice.lptIssue(), 1'000'000}, + ter(tecAMM_INVALID_TOKENS)); AMM ammAMMToken1( - env, alice, STAmount{ammAlice.lptIssue(), 1'000'000}, EUR(10'000), ter(tecAMM_INVALID_TOKENS)); + env, + alice, + STAmount{ammAlice.lptIssue(), 1'000'000}, + EUR(10'000), + ter(tecAMM_INVALID_TOKENS)); }); // AMM with two LPTokens from other AMMs. @@ -366,7 +380,11 @@ private: auto const token1 = ammAlice.lptIssue(); auto const token2 = ammAlice1.lptIssue(); AMM ammAMMTokens( - env, alice, STAmount{token1, 1'000'000}, STAmount{token2, 1'000'000}, ter(tecAMM_INVALID_TOKENS)); + env, + alice, + STAmount{token1, 1'000'000}, + STAmount{token2, 1'000'000}, + ter(tecAMM_INVALID_TOKENS)); }); // Issuer has DefaultRipple disabled @@ -415,30 +433,95 @@ private: // flags, tokens, asset1In, asset2in, EPrice, tfee {tfLPToken, 1'000, std::nullopt, USD(100), std::nullopt, std::nullopt}, {tfLPToken, 1'000, XRP(100), std::nullopt, std::nullopt, std::nullopt}, - {tfLPToken, 1'000, std::nullopt, std::nullopt, STAmount{USD, 1, -1}, std::nullopt}, - {tfLPToken, std::nullopt, USD(100), std::nullopt, STAmount{USD, 1, -1}, std::nullopt}, + {tfLPToken, + 1'000, + std::nullopt, + std::nullopt, + STAmount{USD, 1, -1}, + std::nullopt}, + {tfLPToken, + std::nullopt, + USD(100), + std::nullopt, + STAmount{USD, 1, -1}, + std::nullopt}, {tfLPToken, 1'000, XRP(100), std::nullopt, STAmount{USD, 1, -1}, std::nullopt}, {tfLPToken, 1'000, std::nullopt, std::nullopt, std::nullopt, 1'000}, {tfSingleAsset, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, - {tfSingleAsset, std::nullopt, std::nullopt, USD(100), std::nullopt, std::nullopt}, - {tfSingleAsset, std::nullopt, std::nullopt, std::nullopt, STAmount{USD, 1, -1}, std::nullopt}, + {tfSingleAsset, + std::nullopt, + std::nullopt, + USD(100), + std::nullopt, + std::nullopt}, + {tfSingleAsset, + std::nullopt, + std::nullopt, + std::nullopt, + STAmount{USD, 1, -1}, + std::nullopt}, {tfSingleAsset, std::nullopt, USD(100), std::nullopt, std::nullopt, 1'000}, {tfTwoAsset, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, - {tfTwoAsset, std::nullopt, XRP(100), USD(100), STAmount{USD, 1, -1}, std::nullopt}, + {tfTwoAsset, + std::nullopt, + XRP(100), + USD(100), + STAmount{USD, 1, -1}, + std::nullopt}, {tfTwoAsset, std::nullopt, XRP(100), std::nullopt, std::nullopt, std::nullopt}, {tfTwoAsset, std::nullopt, XRP(100), USD(100), std::nullopt, 1'000}, - {tfTwoAsset, std::nullopt, std::nullopt, USD(100), STAmount{USD, 1, -1}, std::nullopt}, - {tfOneAssetLPToken, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, - {tfOneAssetLPToken, std::nullopt, XRP(100), USD(100), std::nullopt, std::nullopt}, - {tfOneAssetLPToken, std::nullopt, XRP(100), std::nullopt, STAmount{USD, 1, -1}, std::nullopt}, + {tfTwoAsset, + std::nullopt, + std::nullopt, + USD(100), + STAmount{USD, 1, -1}, + std::nullopt}, + {tfOneAssetLPToken, + 1'000, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt}, + {tfOneAssetLPToken, + std::nullopt, + XRP(100), + USD(100), + std::nullopt, + std::nullopt}, + {tfOneAssetLPToken, + std::nullopt, + XRP(100), + std::nullopt, + STAmount{USD, 1, -1}, + std::nullopt}, {tfOneAssetLPToken, 1'000, XRP(100), std::nullopt, std::nullopt, 1'000}, {tfLimitLPToken, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, {tfLimitLPToken, 1'000, USD(100), std::nullopt, std::nullopt, std::nullopt}, {tfLimitLPToken, std::nullopt, USD(100), XRP(100), std::nullopt, std::nullopt}, - {tfLimitLPToken, std::nullopt, XRP(100), std::nullopt, STAmount{USD, 1, -1}, 1'000}, - {tfTwoAssetIfEmpty, std::nullopt, std::nullopt, std::nullopt, std::nullopt, 1'000}, - {tfTwoAssetIfEmpty, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, - {tfTwoAssetIfEmpty, std::nullopt, XRP(100), USD(100), STAmount{USD, 1, -1}, std::nullopt}, + {tfLimitLPToken, + std::nullopt, + XRP(100), + std::nullopt, + STAmount{USD, 1, -1}, + 1'000}, + {tfTwoAssetIfEmpty, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + 1'000}, + {tfTwoAssetIfEmpty, + 1'000, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt}, + {tfTwoAssetIfEmpty, + std::nullopt, + XRP(100), + USD(100), + STAmount{USD, 1, -1}, + std::nullopt}, {tfTwoAssetIfEmpty | tfLPToken, std::nullopt, XRP(100), @@ -473,7 +556,8 @@ private: // Invalid tokens ammAlice.deposit(alice, 0, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); - ammAlice.deposit(alice, IOUAmount{-1}, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); + ammAlice.deposit( + alice, IOUAmount{-1}, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); { Json::Value jv = Json::objectValue; @@ -517,21 +601,28 @@ private: } // Depositing mismatched token, invalid Asset1In.issue - ammAlice.deposit(alice, GBP(100), std::nullopt, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); + ammAlice.deposit( + alice, GBP(100), std::nullopt, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); // Depositing mismatched token, invalid Asset2In.issue - ammAlice.deposit(alice, USD(100), GBP(100), std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); + ammAlice.deposit( + alice, USD(100), GBP(100), std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); // Depositing mismatched token, Asset1In.issue == Asset2In.issue - ammAlice.deposit(alice, USD(100), USD(100), std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); + ammAlice.deposit( + alice, USD(100), USD(100), std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); // Invalid amount value - ammAlice.deposit(alice, USD(0), std::nullopt, std::nullopt, std::nullopt, ter(temBAD_AMOUNT)); - ammAlice.deposit(alice, USD(-1'000), std::nullopt, std::nullopt, std::nullopt, ter(temBAD_AMOUNT)); - ammAlice.deposit(alice, USD(10), std::nullopt, USD(-1), std::nullopt, ter(temBAD_AMOUNT)); + ammAlice.deposit( + alice, USD(0), std::nullopt, std::nullopt, std::nullopt, ter(temBAD_AMOUNT)); + ammAlice.deposit( + alice, USD(-1'000), std::nullopt, std::nullopt, std::nullopt, ter(temBAD_AMOUNT)); + ammAlice.deposit( + alice, USD(10), std::nullopt, USD(-1), std::nullopt, ter(temBAD_AMOUNT)); // Bad currency - ammAlice.deposit(alice, BAD(100), std::nullopt, std::nullopt, std::nullopt, ter(temBAD_CURRENCY)); + ammAlice.deposit( + alice, BAD(100), std::nullopt, std::nullopt, std::nullopt, ter(temBAD_CURRENCY)); // Invalid Account Account bad("bad"); @@ -591,12 +682,25 @@ private: // Deposit amount is invalid // Calculated amount to deposit is 98,000,000 - ammAlice.deposit(alice, USD(0), std::nullopt, STAmount{USD, 1, -1}, std::nullopt, ter(tecUNFUNDED_AMM)); + ammAlice.deposit( + alice, + USD(0), + std::nullopt, + STAmount{USD, 1, -1}, + std::nullopt, + ter(tecUNFUNDED_AMM)); // Calculated amount is 0 - ammAlice.deposit(alice, USD(0), std::nullopt, STAmount{USD, 2'000, -6}, std::nullopt, ter(tecAMM_FAILED)); + ammAlice.deposit( + alice, + USD(0), + std::nullopt, + STAmount{USD, 2'000, -6}, + std::nullopt, + ter(tecAMM_FAILED)); // Deposit non-empty AMM - ammAlice.deposit(carol, XRP(100), USD(100), std::nullopt, tfTwoAssetIfEmpty, ter(tecAMM_NOT_EMPTY)); + ammAlice.deposit( + carol, XRP(100), USD(100), std::nullopt, tfTwoAssetIfEmpty, ter(tecAMM_NOT_EMPTY)); }); // Tiny deposit @@ -612,7 +716,12 @@ private: // Pre/post-amendment LPTokens is rounded to 0 and deposit // fails with tecAMM_INVALID_TOKENS. ammAlice.deposit( - carol, STAmount{USD, 1, -12}, std::nullopt, std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); + carol, + STAmount{USD, 1, -12}, + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecAMM_INVALID_TOKENS)); }, std::nullopt, 0, @@ -638,10 +747,13 @@ private: // If the issuer set global freeze, the holder cannot // deposit the other non-frozen token when AMMClawback is // enabled. - ammAlice.deposit(carol, XRP(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); - ammAlice.deposit(carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit( + carol, XRP(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit( + carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); ammAlice.deposit(carol, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); - ammAlice.deposit(carol, XRP(100), USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit( + carol, XRP(100), USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); }, std::nullopt, 0, @@ -660,18 +772,24 @@ private: else // Cannot deposit non-frozen token if the other token is // frozen when AMMClawback is enabled - ammAlice.deposit(carol, XRP(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit( + carol, XRP(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); ammAlice.deposit(carol, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); - ammAlice.deposit(carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit( + carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); env(trust(gw, carol["USD"](0), tfClearFreeze)); // Individually frozen AMM - env(trust(gw, STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, tfSetFreeze)); + env(trust( + gw, + STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, + tfSetFreeze)); env.close(); // Can deposit non-frozen token ammAlice.deposit(carol, XRP(100)); ammAlice.deposit(carol, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); - ammAlice.deposit(carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit( + carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); }, std::nullopt, 0, @@ -685,14 +803,19 @@ private: env(trust(gw, carol["BTC"](0), tfSetFreeze)); env.close(); ammAlice.deposit(carol, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); - ammAlice.deposit(carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit( + carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); env(trust(gw, carol["USD"](0), tfClearFreeze)); // Individually frozen AMM - env(trust(gw, STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, tfSetFreeze)); + env(trust( + gw, + STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, + tfSetFreeze)); env.close(); // Cannot deposit non-frozen token ammAlice.deposit(carol, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); - ammAlice.deposit(carol, USD(100), BTC(0.01), std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit( + carol, USD(100), BTC(0.01), std::nullopt, std::nullopt, ter(tecFROZEN)); }, {{USD(20'000), BTC(0.5)}}); @@ -717,9 +840,11 @@ private: // if featureAMMClawback is enabled, bob can not deposit XRP // because he's not authorized to hold the paired token // gw["USD"]. - amm.deposit(bob, XRP(10), std::nullopt, std::nullopt, std::nullopt, ter(tecNO_AUTH)); + amm.deposit( + bob, XRP(10), std::nullopt, std::nullopt, std::nullopt, ter(tecNO_AUTH)); else - amm.deposit(bob, XRP(10), std::nullopt, std::nullopt, std::nullopt, ter(tesSUCCESS)); + amm.deposit( + bob, XRP(10), std::nullopt, std::nullopt, std::nullopt, ter(tesSUCCESS)); } // Insufficient XRP balance @@ -728,14 +853,16 @@ private: env.close(); // Adds LPT trustline ammAlice.deposit(bob, XRP(10)); - ammAlice.deposit(bob, XRP(1'000), std::nullopt, std::nullopt, std::nullopt, ter(tecUNFUNDED_AMM)); + ammAlice.deposit( + bob, XRP(1'000), std::nullopt, std::nullopt, std::nullopt, ter(tecUNFUNDED_AMM)); }); // Insufficient USD balance testAMM([&](AMM& ammAlice, Env& env) { fund(env, gw, {bob}, {USD(1'000)}, Fund::Acct); env.close(); - ammAlice.deposit(bob, USD(1'001), std::nullopt, std::nullopt, std::nullopt, ter(tecUNFUNDED_AMM)); + ammAlice.deposit( + bob, USD(1'001), std::nullopt, std::nullopt, std::nullopt, ter(tecUNFUNDED_AMM)); }); // Insufficient USD balance by tokens @@ -791,10 +918,22 @@ private: env(offer(carol, XRP(100), USD(101))); env(offer(carol, XRP(100), USD(102))); AMM ammAlice(env, alice, XRP(1'000), USD(1'000)); - ammAlice.deposit(carol, XRP(100), std::nullopt, std::nullopt, std::nullopt, ter(tecINSUF_RESERVE_LINE)); + ammAlice.deposit( + carol, + XRP(100), + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecINSUF_RESERVE_LINE)); env(offer(carol, XRP(100), USD(103))); - ammAlice.deposit(carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecINSUF_RESERVE_LINE)); + ammAlice.deposit( + carol, + USD(100), + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecINSUF_RESERVE_LINE)); } // Insufficient reserve, IOU/IOU @@ -817,7 +956,13 @@ private: env(offer(carol, XRP(100), USD(101))); env(offer(carol, XRP(100), USD(102))); AMM ammAlice(env, alice, XRP(1'000), USD(1'000)); - ammAlice.deposit(carol, XRP(100), std::nullopt, std::nullopt, std::nullopt, ter(tecINSUF_RESERVE_LINE)); + ammAlice.deposit( + carol, + XRP(100), + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecINSUF_RESERVE_LINE)); } // Invalid min @@ -955,30 +1100,43 @@ private: // Equal deposit limit, tokens rounded to 0 testAMM( [&](AMM& amm, Env& env) { - amm.deposit(DepositArg{ - .asset1In = STAmount{USD, 1, -15}, .asset2In = XRPAmount{1}, .err = ter(tecAMM_INVALID_TOKENS)}); + amm.deposit( + DepositArg{ + .asset1In = STAmount{USD, 1, -15}, + .asset2In = XRPAmount{1}, + .err = ter(tecAMM_INVALID_TOKENS)}); }, {.pool = {{USD(1'000'000), XRP(1'000'000)}}, .features = {features - fixAMMv1_3}}); testAMM([&](AMM& amm, Env& env) { - amm.deposit(DepositArg{ - .asset1In = STAmount{USD, 1, -15}, .asset2In = XRPAmount{1}, .err = ter(tecAMM_INVALID_TOKENS)}); + amm.deposit( + DepositArg{ + .asset1In = STAmount{USD, 1, -15}, + .asset2In = XRPAmount{1}, + .err = ter(tecAMM_INVALID_TOKENS)}); }); // Single deposit by asset, tokens rounded to 0 testAMM([&](AMM& amm, Env& env) { - amm.deposit(DepositArg{.asset1In = STAmount{USD, 1, -15}, .err = ter(tecAMM_INVALID_TOKENS)}); + amm.deposit( + DepositArg{.asset1In = STAmount{USD, 1, -15}, .err = ter(tecAMM_INVALID_TOKENS)}); }); // Single deposit by tokens, tokens rounded to 0 testAMM([&](AMM& amm, Env& env) { - amm.deposit(DepositArg{ - .tokens = IOUAmount{1, -10}, .asset1In = STAmount{USD, 1, -15}, .err = ter(tecAMM_INVALID_TOKENS)}); + amm.deposit( + DepositArg{ + .tokens = IOUAmount{1, -10}, + .asset1In = STAmount{USD, 1, -15}, + .err = ter(tecAMM_INVALID_TOKENS)}); }); // Single deposit with EPrice, tokens rounded to 0 testAMM([&](AMM& amm, Env& env) { - amm.deposit(DepositArg{ - .asset1In = STAmount{USD, 1, -15}, .maxEP = STAmount{USD, 1, -1}, .err = ter(tecAMM_INVALID_TOKENS)}); + amm.deposit( + DepositArg{ + .asset1In = STAmount{USD, 1, -15}, + .maxEP = STAmount{USD, 1, -1}, + .err = ter(tecAMM_INVALID_TOKENS)}); }); } @@ -994,7 +1152,8 @@ private: testAMM([&](AMM& ammAlice, Env& env) { auto const baseFee = env.current()->fees().base; ammAlice.deposit(carol, 1'000'000); - BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); // 30,000 less deposited 1,000 BEAST_EXPECT(expectHolding(env, carol, USD(29'000))); // 30,000 less deposited 1,000 and 10 drops tx fee @@ -1040,12 +1199,15 @@ private: // initial LPTokens (1e7) + newLPTokens BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000) + depositXRP, USD(10'000) + depositUSD, IOUAmount{1, 7} + newLPTokens)); + XRP(10'000) + depositXRP, + USD(10'000) + depositUSD, + IOUAmount{1, 7} + newLPTokens)); // 30,000 less deposited depositUSD BEAST_EXPECT(expectHolding(env, carol, USD(30'000) - depositUSD)); // 30,000 less deposited depositXRP and 10 drops tx fee - BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRP(30'000) - depositXRP - txfee(env, 1))); + BEAST_EXPECT( + expectLedgerEntryRoot(env, carol, XRP(30'000) - depositXRP - txfee(env, 1))); }); } @@ -1056,44 +1218,52 @@ private: // Deposit 100USD/100XRP testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, USD(100), XRP(100)); - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0})); }); // Equal limit deposit. // Try to deposit 200USD/100XRP. Is truncated to 100USD/100XRP. testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, USD(200), XRP(100)); - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0})); }); // Try to deposit 100USD/200XRP. Is truncated to 100USD/100XRP. testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, USD(100), XRP(200)); - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0})); }); // Single deposit: 1000 USD testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, USD(1'000)); BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), STAmount{USD, UINT64_C(10'999'99999999999), -11}, IOUAmount{10'488'088'48170151, -8})); + XRP(10'000), + STAmount{USD, UINT64_C(10'999'99999999999), -11}, + IOUAmount{10'488'088'48170151, -8})); }); // Single deposit: 1000 XRP testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, XRP(1'000)); - BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(10'000), IOUAmount{10'488'088'48170151, -8})); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), USD(10'000), IOUAmount{10'488'088'48170151, -8})); }); // Single deposit: 100000 tokens worth of USD testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, 100000, USD(205)); - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'201), IOUAmount{10'100'000, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'000), USD(10'201), IOUAmount{10'100'000, 0})); }); // Single deposit: 100000 tokens worth of XRP testAMM([&](AMM& ammAlice, Env& env) { ammAlice.deposit(carol, 100'000, XRP(205)); - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'201), USD(10'000), IOUAmount{10'100'000, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'201), USD(10'000), IOUAmount{10'100'000, 0})); }); // Single deposit with EP not exceeding specified: @@ -1101,21 +1271,25 @@ private: testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, USD(1'000), std::nullopt, STAmount{USD, 1, -1}); BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), STAmount{USD, UINT64_C(10'999'99999999999), -11}, IOUAmount{10'488'088'48170151, -8})); + XRP(10'000), + STAmount{USD, UINT64_C(10'999'99999999999), -11}, + IOUAmount{10'488'088'48170151, -8})); }); // Single deposit with EP not exceeding specified: // 100USD with EP not to exceed 0.002004 (AssetIn/TokensOut) testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, USD(100), std::nullopt, STAmount{USD, 2004, -6}); - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), STAmount{USD, 10'080'16, -2}, IOUAmount{10'040'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), STAmount{USD, 10'080'16, -2}, IOUAmount{10'040'000, 0})); }); // Single deposit with EP not exceeding specified: // 0USD with EP not to exceed 0.002004 (AssetIn/TokensOut) testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, USD(0), std::nullopt, STAmount{USD, 2004, -6}); - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), STAmount{USD, 10'080'16, -2}, IOUAmount{10'040'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), STAmount{USD, 10'080'16, -2}, IOUAmount{10'040'000, 0})); }); // IOU to IOU + transfer fee @@ -1140,19 +1314,23 @@ private: testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, IOUAmount{1, -3}); BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{10'000'000'001}, STAmount{USD, UINT64_C(10'000'000001), -6}, IOUAmount{10'000'000'001, -3})); + XRPAmount{10'000'000'001}, + STAmount{USD, UINT64_C(10'000'000001), -6}, + IOUAmount{10'000'000'001, -3})); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{1, -3})); }); testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, XRPAmount{1}); - BEAST_EXPECT( - ammAlice.expectBalances(XRPAmount{10'000'000'001}, USD(10'000), IOUAmount{1'000'000'000049999, -8})); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount{10'000'000'001}, USD(10'000), IOUAmount{1'000'000'000049999, -8})); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{49999, -8})); }); testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, STAmount{USD, 1, -10}); BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), STAmount{USD, UINT64_C(10'000'00000000008), -11}, IOUAmount{10'000'000'00000004, -8})); + XRP(10'000), + STAmount{USD, UINT64_C(10'000'00000000008), -11}, + IOUAmount{10'000'000'00000004, -8})); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{4, -8})); }); @@ -1167,7 +1345,9 @@ private: BEAST_EXPECT(ammGw.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000})); ammGw.deposit(gw, USD(1'000)); BEAST_EXPECT(ammGw.expectBalances( - XRP(11'000), STAmount{USD, UINT64_C(11'999'99999999998), -11}, IOUAmount{11'489'125'29307605, -8})); + XRP(11'000), + STAmount{USD, UINT64_C(11'999'99999999998), -11}, + IOUAmount{11'489'125'29307605, -8})); } // Issuer deposit @@ -1176,34 +1356,69 @@ private: BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000})); ammAlice.deposit(gw, USD(1'000)); BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), STAmount{USD, UINT64_C(11'999'99999999998), -11}, IOUAmount{11'489'125'29307605, -8})); + XRP(11'000), + STAmount{USD, UINT64_C(11'999'99999999998), -11}, + IOUAmount{11'489'125'29307605, -8})); }); // Min deposit testAMM([&](AMM& ammAlice, Env& env) { // Equal deposit by tokens ammAlice.deposit( - carol, 1'000'000, XRP(1'000), USD(1'000), std::nullopt, tfLPToken, std::nullopt, std::nullopt); - BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); + carol, + 1'000'000, + XRP(1'000), + USD(1'000), + std::nullopt, + tfLPToken, + std::nullopt, + std::nullopt); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); }); testAMM([&](AMM& ammAlice, Env& env) { // Equal deposit by asset ammAlice.deposit( - carol, 1'000'000, XRP(1'000), USD(1'000), std::nullopt, tfTwoAsset, std::nullopt, std::nullopt); - BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); + carol, + 1'000'000, + XRP(1'000), + USD(1'000), + std::nullopt, + tfTwoAsset, + std::nullopt, + std::nullopt); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); }); testAMM([&](AMM& ammAlice, Env& env) { // Single deposit by asset ammAlice.deposit( - carol, 488'088, XRP(1'000), std::nullopt, std::nullopt, tfSingleAsset, std::nullopt, std::nullopt); - BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(10'000), IOUAmount{10'488'088'48170151, -8})); - }); - testAMM([&](AMM& ammAlice, Env& env) { - // Single deposit by asset - ammAlice.deposit( - carol, 488'088, USD(1'000), std::nullopt, std::nullopt, tfSingleAsset, std::nullopt, std::nullopt); + carol, + 488'088, + XRP(1'000), + std::nullopt, + std::nullopt, + tfSingleAsset, + std::nullopt, + std::nullopt); BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), STAmount{USD, UINT64_C(10'999'99999999999), -11}, IOUAmount{10'488'088'48170151, -8})); + XRP(11'000), USD(10'000), IOUAmount{10'488'088'48170151, -8})); + }); + testAMM([&](AMM& ammAlice, Env& env) { + // Single deposit by asset + ammAlice.deposit( + carol, + 488'088, + USD(1'000), + std::nullopt, + std::nullopt, + tfSingleAsset, + std::nullopt, + std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), + STAmount{USD, UINT64_C(10'999'99999999999), -11}, + IOUAmount{10'488'088'48170151, -8})); }); } @@ -1291,24 +1506,74 @@ private: NotTEC>> invalidOptions = { // tokens, asset1Out, asset2Out, EPrice, flags, ter - {std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, temMALFORMED}, - {std::nullopt, std::nullopt, std::nullopt, std::nullopt, tfSingleAsset | tfTwoAsset, temMALFORMED}, + {std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + temMALFORMED}, + {std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + tfSingleAsset | tfTwoAsset, + temMALFORMED}, {1'000, std::nullopt, std::nullopt, std::nullopt, tfWithdrawAll, temMALFORMED}, - {std::nullopt, USD(0), XRP(100), std::nullopt, tfWithdrawAll | tfLPToken, temMALFORMED}, - {std::nullopt, std::nullopt, USD(100), std::nullopt, tfWithdrawAll, temMALFORMED}, + {std::nullopt, + USD(0), + XRP(100), + std::nullopt, + tfWithdrawAll | tfLPToken, + temMALFORMED}, + {std::nullopt, + std::nullopt, + USD(100), + std::nullopt, + tfWithdrawAll, + temMALFORMED}, {std::nullopt, std::nullopt, std::nullopt, std::nullopt, tfWithdrawAll | tfOneAssetWithdrawAll, temMALFORMED}, - {std::nullopt, USD(100), std::nullopt, std::nullopt, tfWithdrawAll, temMALFORMED}, - {std::nullopt, std::nullopt, std::nullopt, std::nullopt, tfOneAssetWithdrawAll, temMALFORMED}, + {std::nullopt, + USD(100), + std::nullopt, + std::nullopt, + tfWithdrawAll, + temMALFORMED}, + {std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + tfOneAssetWithdrawAll, + temMALFORMED}, {1'000, std::nullopt, USD(100), std::nullopt, std::nullopt, temMALFORMED}, - {std::nullopt, std::nullopt, std::nullopt, IOUAmount{250, 0}, tfWithdrawAll, temMALFORMED}, - {1'000, std::nullopt, std::nullopt, IOUAmount{250, 0}, std::nullopt, temMALFORMED}, - {std::nullopt, std::nullopt, USD(100), IOUAmount{250, 0}, std::nullopt, temMALFORMED}, - {std::nullopt, XRP(100), USD(100), IOUAmount{250, 0}, std::nullopt, temMALFORMED}, + {std::nullopt, + std::nullopt, + std::nullopt, + IOUAmount{250, 0}, + tfWithdrawAll, + temMALFORMED}, + {1'000, + std::nullopt, + std::nullopt, + IOUAmount{250, 0}, + std::nullopt, + temMALFORMED}, + {std::nullopt, + std::nullopt, + USD(100), + IOUAmount{250, 0}, + std::nullopt, + temMALFORMED}, + {std::nullopt, + XRP(100), + USD(100), + IOUAmount{250, 0}, + std::nullopt, + temMALFORMED}, {1'000, XRP(100), USD(100), std::nullopt, std::nullopt, temMALFORMED}, {std::nullopt, XRP(100), USD(100), std::nullopt, tfWithdrawAll, temMALFORMED}}; for (auto const& it : invalidOptions) @@ -1327,7 +1592,8 @@ private: // Invalid tokens ammAlice.withdraw(alice, 0, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); - ammAlice.withdraw(alice, IOUAmount{-1}, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); + ammAlice.withdraw( + alice, IOUAmount{-1}, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); // Mismatched token, invalid Asset1Out issue ammAlice.withdraw(alice, GBP(100), std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); @@ -1392,9 +1658,11 @@ private: // Withdrawing from one side. // XRP by tokens - ammAlice.withdraw(alice, IOUAmount(9'999'999'9999, -4), XRP(0), std::nullopt, ter(tecAMM_BALANCE)); + ammAlice.withdraw( + alice, IOUAmount(9'999'999'9999, -4), XRP(0), std::nullopt, ter(tecAMM_BALANCE)); // USD by tokens - ammAlice.withdraw(alice, IOUAmount(9'999'999'9, -1), USD(0), std::nullopt, ter(tecAMM_BALANCE)); + ammAlice.withdraw( + alice, IOUAmount(9'999'999'9, -1), USD(0), std::nullopt, ter(tecAMM_BALANCE)); // XRP ammAlice.withdraw(alice, XRP(10'000), std::nullopt, std::nullopt, ter(tecAMM_BALANCE)); // USD @@ -1416,9 +1684,11 @@ private: // Post-amendment: // Most of the pool is withdrawn with remaining tiny amounts auto err = env.enabled(fixAMMv1_3) ? ter(tesSUCCESS) : ter(tecAMM_BALANCE); - ammAlice.withdraw(alice, IOUAmount{9'999'999'9999, -4}, std::nullopt, std::nullopt, err); + ammAlice.withdraw( + alice, IOUAmount{9'999'999'9999, -4}, std::nullopt, std::nullopt, err); if (env.enabled(fixAMMv1_3)) - BEAST_EXPECT(ammAlice.expectBalances(XRPAmount(1), STAmount{USD, 1, -7}, IOUAmount{1, -4})); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount(1), STAmount{USD, 1, -7}, IOUAmount{1, -4})); }, std::nullopt, 0, @@ -1434,9 +1704,11 @@ private: // this results in full withdraw of XRP pool only, // while leaving a tiny amount in USD pool. auto err = env.enabled(fixAMMv1_3) ? ter(tesSUCCESS) : ter(tecAMM_BALANCE); - ammAlice.withdraw(alice, IOUAmount{9'999'999'999999999, -9}, std::nullopt, std::nullopt, err); + ammAlice.withdraw( + alice, IOUAmount{9'999'999'999999999, -9}, std::nullopt, std::nullopt, err); if (env.enabled(fixAMMv1_3)) - BEAST_EXPECT(ammAlice.expectBalances(XRPAmount(1), STAmount{USD, 1, -11}, IOUAmount{1, -8})); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount(1), STAmount{USD, 1, -11}, IOUAmount{1, -8})); }, std::nullopt, 0, @@ -1469,7 +1741,8 @@ private: ammAlice.withdraw(alice, USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); env(trust(gw, alice["USD"](0), tfClearFreeze)); // Individually frozen AMM - env(trust(gw, STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, tfSetFreeze)); + env(trust( + gw, STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, tfSetFreeze)); // Can withdraw non-frozen token ammAlice.withdraw(alice, XRP(100)); ammAlice.withdraw(alice, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); @@ -1481,10 +1754,13 @@ private: // Single deposit of 100000 worth of tokens, // which is 10% of the pool. Carol is LP now. ammAlice.deposit(carol, 1'000'000); - BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); - ammAlice.withdraw(carol, 2'000'000, std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); - BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); + ammAlice.withdraw( + carol, 2'000'000, std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); }); // Withdraw with EPrice limit. Fails to withdraw, calculated tokens @@ -1492,7 +1768,8 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { ammAlice.deposit(carol, 1'000'000); - auto const err = env.enabled(fixAMMv1_3) ? ter(tecAMM_INVALID_TOKENS) : ter(tecAMM_FAILED); + auto const err = + env.enabled(fixAMMv1_3) ? ter(tecAMM_INVALID_TOKENS) : ter(tecAMM_FAILED); ammAlice.withdraw(carol, USD(100), std::nullopt, IOUAmount{500, 0}, err); }, std::nullopt, @@ -1504,28 +1781,32 @@ private: // to withdraw are greater than the LP shares. testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, 1'000'000); - ammAlice.withdraw(carol, USD(100), std::nullopt, IOUAmount{600, 0}, ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw( + carol, USD(100), std::nullopt, IOUAmount{600, 0}, ter(tecAMM_INVALID_TOKENS)); }); // Withdraw with EPrice limit. Fails to withdraw, amount1 // to withdraw is less than 1700USD. testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, 1'000'000); - ammAlice.withdraw(carol, USD(1'700), std::nullopt, IOUAmount{520, 0}, ter(tecAMM_FAILED)); + ammAlice.withdraw( + carol, USD(1'700), std::nullopt, IOUAmount{520, 0}, ter(tecAMM_FAILED)); }); // Deposit/Withdraw the same amount with the trading fee testAMM( [&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, USD(1'000)); - ammAlice.withdraw(carol, USD(1'000), std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw( + carol, USD(1'000), std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); }, std::nullopt, 1'000); testAMM( [&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, XRP(1'000)); - ammAlice.withdraw(carol, XRP(1'000), std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw( + carol, XRP(1'000), std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); }, std::nullopt, 1'000); @@ -1533,33 +1814,62 @@ private: // Deposit/Withdraw the same amount fails due to the tokens adjustment testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, STAmount{USD, 1, -6}); - ammAlice.withdraw(carol, STAmount{USD, 1, -6}, std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw( + carol, + STAmount{USD, 1, -6}, + std::nullopt, + std::nullopt, + ter(tecAMM_INVALID_TOKENS)); }); // Withdraw close to one side of the pool. Account's LP tokens // are rounded to all LP tokens. testAMM( [&](AMM& ammAlice, Env& env) { - auto const err = env.enabled(fixAMMv1_3) ? ter(tecINVARIANT_FAILED) : ter(tecAMM_BALANCE); + auto const err = + env.enabled(fixAMMv1_3) ? ter(tecINVARIANT_FAILED) : ter(tecAMM_BALANCE); ammAlice.withdraw( - alice, STAmount{USD, UINT64_C(9'999'999999999999), -12}, std::nullopt, std::nullopt, err); + alice, + STAmount{USD, UINT64_C(9'999'999999999999), -12}, + std::nullopt, + std::nullopt, + err); }, {.features = {all, all - fixAMMv1_3}, .noLog = true}); // Tiny withdraw testAMM([&](AMM& ammAlice, Env&) { // XRP amount to withdraw is 0 - ammAlice.withdraw(alice, IOUAmount{1, -5}, std::nullopt, std::nullopt, ter(tecAMM_FAILED)); + ammAlice.withdraw( + alice, IOUAmount{1, -5}, std::nullopt, std::nullopt, ter(tecAMM_FAILED)); // Calculated tokens to withdraw are 0 - ammAlice.withdraw(alice, std::nullopt, STAmount{USD, 1, -11}, std::nullopt, ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw( + alice, + std::nullopt, + STAmount{USD, 1, -11}, + std::nullopt, + ter(tecAMM_INVALID_TOKENS)); ammAlice.deposit(carol, STAmount{USD, 1, -10}); - ammAlice.withdraw(carol, std::nullopt, STAmount{USD, 1, -9}, std::nullopt, ter(tecAMM_INVALID_TOKENS)); - ammAlice.withdraw(carol, std::nullopt, XRPAmount{1}, std::nullopt, ter(tecAMM_INVALID_TOKENS)); - ammAlice.withdraw(WithdrawArg{.tokens = IOUAmount{1, -10}, .err = ter(tecAMM_INVALID_TOKENS)}); - ammAlice.withdraw(WithdrawArg{ - .asset1Out = STAmount{USD, 1, -15}, .asset2Out = XRPAmount{1}, .err = ter(tecAMM_INVALID_TOKENS)}); - ammAlice.withdraw(WithdrawArg{ - .tokens = IOUAmount{1, -10}, .asset1Out = STAmount{USD, 1, -15}, .err = ter(tecAMM_INVALID_TOKENS)}); + ammAlice.withdraw( + carol, + std::nullopt, + STAmount{USD, 1, -9}, + std::nullopt, + ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw( + carol, std::nullopt, XRPAmount{1}, std::nullopt, ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw( + WithdrawArg{.tokens = IOUAmount{1, -10}, .err = ter(tecAMM_INVALID_TOKENS)}); + ammAlice.withdraw( + WithdrawArg{ + .asset1Out = STAmount{USD, 1, -15}, + .asset2Out = XRPAmount{1}, + .err = ter(tecAMM_INVALID_TOKENS)}); + ammAlice.withdraw( + WithdrawArg{ + .tokens = IOUAmount{1, -10}, + .asset1Out = STAmount{USD, 1, -15}, + .err = ter(tecAMM_INVALID_TOKENS)}); }); } @@ -1578,7 +1888,8 @@ private: // Single deposit of 100000 worth of tokens, // which is 10% of the pool. Carol is LP now. ammAlice.deposit(carol, 1'000'000); - BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{1'000'000, 0})); // 30,000 less deposited 1,000 BEAST_EXPECT(expectHolding(env, carol, USD(29'000))); @@ -1589,7 +1900,8 @@ private: ammAlice.withdraw(carol, 1'000'000); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount(beast::Zero()))); BEAST_EXPECT(expectHolding(env, carol, USD(30'000))); - BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRPAmount{30'000'000'000 - 2 * baseFee})); + BEAST_EXPECT( + expectLedgerEntryRoot(env, carol, XRPAmount{30'000'000'000 - 2 * baseFee})); }); // Equal withdrawal by tokens 1000000, 10% @@ -1620,7 +1932,8 @@ private: [&](AMM& ammAlice, Env& env) { ammAlice.withdraw(alice, XRP(1'000)); if (!env.enabled(fixAMMv1_3)) - BEAST_EXPECT(ammAlice.expectBalances(XRP(9'000), USD(10'000), IOUAmount{9'486'832'98050514, -8})); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(9'000), USD(10'000), IOUAmount{9'486'832'98050514, -8})); else BEAST_EXPECT(ammAlice.expectBalances( XRPAmount{9'000'000'001}, USD(10'000), IOUAmount{9'486'832'98050514, -8})); @@ -1633,14 +1946,16 @@ private: // Single withdrawal by tokens 10000. testAMM([&](AMM& ammAlice, Env&) { ammAlice.withdraw(alice, 10'000, USD(0)); - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(9980.01), IOUAmount{9'990'000, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'000), USD(9980.01), IOUAmount{9'990'000, 0})); }); // Withdraw all tokens. testAMM([&](AMM& ammAlice, Env& env) { env(trust(carol, STAmount{ammAlice.lptIssue(), 10'000})); // Can SetTrust only for AMM LP tokens - env(trust(carol, STAmount{Issue{EUR.currency, ammAlice.ammAccount()}, 10'000}), ter(tecNO_PERMISSION)); + env(trust(carol, STAmount{Issue{EUR.currency, ammAlice.ammAccount()}, 10'000}), + ter(tecNO_PERMISSION)); env.close(); ammAlice.withdrawAll(alice); BEAST_EXPECT(!ammAlice.ammExists()); @@ -1649,14 +1964,16 @@ private: // Can create AMM for the XRP/USD pair AMM ammCarol(env, carol, XRP(10'000), USD(10'000)); - BEAST_EXPECT(ammCarol.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); + BEAST_EXPECT( + ammCarol.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); }); // Single deposit 1000USD, withdraw all tokens in USD testAMM([&](AMM& ammAlice, Env& env) { ammAlice.deposit(carol, USD(1'000)); ammAlice.withdrawAll(carol, USD(0)); - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount(beast::Zero()))); }); @@ -1665,7 +1982,9 @@ private: ammAlice.deposit(carol, USD(1'000)); ammAlice.withdrawAll(carol, XRP(0)); BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(9'090'909'091), STAmount{USD, UINT64_C(10'999'99999999999), -11}, IOUAmount{10'000'000, 0})); + XRPAmount(9'090'909'091), + STAmount{USD, UINT64_C(10'999'99999999999), -11}, + IOUAmount{10'000'000, 0})); }); // Single deposit/withdraw by the same account @@ -1681,9 +2000,11 @@ private: lpTokens = ammAlice.deposit(carol, XRPAmount(1)); ammAlice.withdraw(carol, lpTokens, XRPAmount(0)); if (!env.enabled(fixAMMv1_3)) - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'000), USD(10'000), ammAlice.tokens())); else - BEAST_EXPECT(ammAlice.expectBalances(XRPAmount(10'000'000'001), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount(10'000'000'001), USD(10'000), ammAlice.tokens())); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); }, std::nullopt, @@ -1707,7 +2028,8 @@ private: testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, 1'000'000); ammAlice.withdrawAll(carol); - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); }); // Equal deposit 10%, withdraw all tokens in USD @@ -1715,14 +2037,17 @@ private: ammAlice.deposit(carol, 1'000'000); ammAlice.withdrawAll(carol, USD(0)); BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), STAmount{USD, UINT64_C(9'090'909090909092), -12}, IOUAmount{10'000'000, 0})); + XRP(11'000), + STAmount{USD, UINT64_C(9'090'909090909092), -12}, + IOUAmount{10'000'000, 0})); }); // Equal deposit 10%, withdraw all tokens in XRP testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, 1'000'000); ammAlice.withdrawAll(carol, XRP(0)); - BEAST_EXPECT(ammAlice.expectBalances(XRPAmount(9'090'909'091), USD(11'000), IOUAmount{10'000'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount(9'090'909'091), USD(11'000), IOUAmount{10'000'000, 0})); }); // Withdraw with EPrice limit. @@ -1808,17 +2133,20 @@ private: // By tokens ammAlice.withdraw(alice, IOUAmount{1, -3}); BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{9'999'999'999}, STAmount{USD, UINT64_C(9'999'999999), -6}, IOUAmount{9'999'999'999, -3})); + XRPAmount{9'999'999'999}, + STAmount{USD, UINT64_C(9'999'999999), -6}, + IOUAmount{9'999'999'999, -3})); }); testAMM( [&](AMM& ammAlice, Env& env) { // Single XRP pool ammAlice.withdraw(alice, std::nullopt, XRPAmount{1}); if (!env.enabled(fixAMMv1_3)) - BEAST_EXPECT( - ammAlice.expectBalances(XRPAmount{9'999'999'999}, USD(10'000), IOUAmount{9'999'999'9995, -4})); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount{9'999'999'999}, USD(10'000), IOUAmount{9'999'999'9995, -4})); else - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{9'999'999'9995, -4})); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), USD(10'000), IOUAmount{9'999'999'9995, -4})); }, std::nullopt, 0, @@ -1828,14 +2156,17 @@ private: // Single USD pool ammAlice.withdraw(alice, std::nullopt, STAmount{USD, 1, -10}); BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), STAmount{USD, UINT64_C(9'999'9999999999), -10}, IOUAmount{9'999'999'99999995, -8})); + XRP(10'000), + STAmount{USD, UINT64_C(9'999'9999999999), -10}, + IOUAmount{9'999'999'99999995, -8})); }); // Withdraw close to entire pool // Equal by tokens testAMM([&](AMM& ammAlice, Env&) { ammAlice.withdraw(alice, IOUAmount{9'999'999'999, -3}); - BEAST_EXPECT(ammAlice.expectBalances(XRPAmount{1}, STAmount{USD, 1, -6}, IOUAmount{1, -3})); + BEAST_EXPECT( + ammAlice.expectBalances(XRPAmount{1}, STAmount{USD, 1, -6}, IOUAmount{1, -3})); }); // USD by tokens testAMM([&](AMM& ammAlice, Env&) { @@ -1850,7 +2181,8 @@ private: // USD testAMM([&](AMM& ammAlice, Env&) { ammAlice.withdraw(alice, STAmount{USD, UINT64_C(9'999'99999999999), -11}); - BEAST_EXPECT(ammAlice.expectBalances(XRP(10000), STAmount{USD, 1, -11}, IOUAmount{316227765, -9})); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10000), STAmount{USD, 1, -11}, IOUAmount{316227765, -9})); }); // XRP testAMM([&](AMM& ammAlice, Env&) { @@ -1867,10 +2199,17 @@ private: testAMM([&](AMM& ammAlice, Env& env) { // Invalid flags - ammAlice.vote(std::nullopt, 1'000, tfWithdrawAll, std::nullopt, std::nullopt, ter(temINVALID_FLAG)); + ammAlice.vote( + std::nullopt, + 1'000, + tfWithdrawAll, + std::nullopt, + std::nullopt, + ter(temINVALID_FLAG)); // Invalid fee. - ammAlice.vote(std::nullopt, 1'001, std::nullopt, std::nullopt, std::nullopt, ter(temBAD_FEE)); + ammAlice.vote( + std::nullopt, 1'001, std::nullopt, std::nullopt, std::nullopt, ter(temBAD_FEE)); BEAST_EXPECT(ammAlice.expectTradingFee(0)); // Invalid Account @@ -1882,7 +2221,8 @@ private: ammAlice.vote(alice, 1'000, std::nullopt, std::nullopt, {{USD, GBP}}, ter(terNO_AMM)); // Account is not LP - ammAlice.vote(carol, 1'000, std::nullopt, std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); + ammAlice.vote( + carol, 1'000, std::nullopt, std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); }); // Invalid AMM @@ -2253,7 +2593,8 @@ private: env(ammAlice.bid({.account = carol, .bidMin = 110})); BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{110})); // 110 tokens are burned. - BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{10'999'890, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{10'999'890, 0})); }, std::nullopt, 0, @@ -2267,11 +2608,13 @@ private: // Bid exactly 110. Pay 110 because the pay price is < 110. env(ammAlice.bid({.account = carol, .bidMin = 110, .bidMax = 110})); BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{110})); - BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{10'999'890})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{10'999'890})); // Bid exactly 180-200. Pay 180 because the pay price is < 180. env(ammAlice.bid({.account = alice, .bidMin = 180, .bidMax = 200})); BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{180})); - BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{10'999'814'5, -1})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{10'999'814'5, -1})); }, std::nullopt, 0, @@ -2327,10 +2670,11 @@ private: fund(env, gw, {bob}, {USD(10'000)}, Fund::Acct); ammAlice.deposit(bob, 1'000'000); if (!features[fixAMMv1_3]) - BEAST_EXPECT(ammAlice.expectBalances(XRP(12'000), USD(12'000), IOUAmount{12'000'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(12'000), USD(12'000), IOUAmount{12'000'000, 0})); else - BEAST_EXPECT( - ammAlice.expectBalances(XRPAmount{12'000'000'001}, USD(12'000), IOUAmount{12'000'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount{12'000'000'001}, USD(12'000), IOUAmount{12'000'000, 0})); // Initial state. Pay bidMin. env(ammAlice.bid({.account = carol, .bidMin = 110})).close(); @@ -2348,7 +2692,8 @@ private: // 20th Interval (expired) after close, price for 10th interval. env(ammAlice.bid({.account = bob})); - env.close(seconds(AUCTION_SLOT_TIME_INTERVALS * AUCTION_SLOT_INTERVAL_DURATION + 1)); + env.close( + seconds(AUCTION_SLOT_TIME_INTERVALS * AUCTION_SLOT_INTERVAL_DURATION + 1)); BEAST_EXPECT(ammAlice.expectAuctionSlot(0, std::nullopt, IOUAmount{127'33875, -5})); // 0 Interval. @@ -2356,10 +2701,11 @@ private: BEAST_EXPECT(ammAlice.expectAuctionSlot(0, std::nullopt, IOUAmount{110})); // ~321.09 tokens burnt on bidding fees. if (!features[fixAMMv1_3]) - BEAST_EXPECT(ammAlice.expectBalances(XRP(12'000), USD(12'000), IOUAmount{11'999'678'91, -2})); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(12'000), USD(12'000), IOUAmount{11'999'678'91, -2})); else - BEAST_EXPECT( - ammAlice.expectBalances(XRPAmount{12'000'000'001}, USD(12'000), IOUAmount{11'999'678'91, -2})); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount{12'000'000'001}, USD(12'000), IOUAmount{11'999'678'91, -2})); }, std::nullopt, 0, @@ -2391,7 +2737,8 @@ private: if (!features[fixAMMv1_3]) BEAST_EXPECT(ammAlice.expectBalances(XRP(13'000), USD(13'000), ammTokens)); else - BEAST_EXPECT(ammAlice.expectBalances(XRPAmount{13'000'000'003}, USD(13'000), ammTokens)); + BEAST_EXPECT( + ammAlice.expectBalances(XRPAmount{13'000'000'003}, USD(13'000), ammTokens)); // Discounted trade for (int i = 0; i < 10; ++i) { @@ -2405,25 +2752,37 @@ private: // carol, bob, and ed pay ~0.99USD in fees. if (!features[fixAMMv1_1]) { - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'499'00572620545), -11)); - BEAST_EXPECT(env.balance(bob, USD) == STAmount(USD, UINT64_C(18'999'00572616195), -11)); - BEAST_EXPECT(env.balance(ed, USD) == STAmount(USD, UINT64_C(18'999'00572611841), -11)); + BEAST_EXPECT( + env.balance(carol, USD) == + STAmount(USD, UINT64_C(29'499'00572620545), -11)); + BEAST_EXPECT( + env.balance(bob, USD) == STAmount(USD, UINT64_C(18'999'00572616195), -11)); + BEAST_EXPECT( + env.balance(ed, USD) == STAmount(USD, UINT64_C(18'999'00572611841), -11)); // USD pool is slightly higher because of the fees. BEAST_EXPECT(ammAlice.expectBalances( XRP(13'000), STAmount(USD, UINT64_C(13'002'98282151419), -11), ammTokens)); } else { - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'499'00572620544), -11)); - BEAST_EXPECT(env.balance(bob, USD) == STAmount(USD, UINT64_C(18'999'00572616194), -11)); - BEAST_EXPECT(env.balance(ed, USD) == STAmount(USD, UINT64_C(18'999'0057261184), -10)); + BEAST_EXPECT( + env.balance(carol, USD) == + STAmount(USD, UINT64_C(29'499'00572620544), -11)); + BEAST_EXPECT( + env.balance(bob, USD) == STAmount(USD, UINT64_C(18'999'00572616194), -11)); + BEAST_EXPECT( + env.balance(ed, USD) == STAmount(USD, UINT64_C(18'999'0057261184), -10)); // USD pool is slightly higher because of the fees. if (!features[fixAMMv1_3]) BEAST_EXPECT(ammAlice.expectBalances( - XRP(13'000), STAmount(USD, UINT64_C(13'002'98282151422), -11), ammTokens)); + XRP(13'000), + STAmount(USD, UINT64_C(13'002'98282151422), -11), + ammTokens)); else BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'003}, STAmount(USD, UINT64_C(13'002'98282151422), -11), ammTokens)); + XRPAmount{13'000'000'003}, + STAmount(USD, UINT64_C(13'002'98282151422), -11), + ammTokens)); } ammTokens = ammAlice.getLPTokensBalance(); // Trade with the fee @@ -2437,7 +2796,8 @@ private: // than the trading fee. if (!features[fixAMMv1_1]) { - BEAST_EXPECT(env.balance(dan, USD) == STAmount(USD, UINT64_C(19'490'056722744), -9)); + BEAST_EXPECT( + env.balance(dan, USD) == STAmount(USD, UINT64_C(19'490'056722744), -9)); // USD pool gains more in dan's fees. BEAST_EXPECT(ammAlice.expectBalances( XRP(13'000), STAmount{USD, UINT64_C(13'012'92609877019), -11}, ammTokens)); @@ -2451,40 +2811,58 @@ private: // carol pays 100000 drops in fees // 99900668XRP swapped in for 100USD BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'100'000'668}, STAmount{USD, UINT64_C(13'012'92609877019), -11}, ammTokens)); + XRPAmount{13'100'000'668}, + STAmount{USD, UINT64_C(13'012'92609877019), -11}, + ammTokens)); } else { if (!features[fixAMMv1_3]) - BEAST_EXPECT(env.balance(dan, USD) == STAmount(USD, UINT64_C(19'490'05672274399), -11)); + BEAST_EXPECT( + env.balance(dan, USD) == + STAmount(USD, UINT64_C(19'490'05672274399), -11)); else - BEAST_EXPECT(env.balance(dan, USD) == STAmount(USD, UINT64_C(19'490'05672274398), -11)); + BEAST_EXPECT( + env.balance(dan, USD) == + STAmount(USD, UINT64_C(19'490'05672274398), -11)); // USD pool gains more in dan's fees. if (!features[fixAMMv1_3]) BEAST_EXPECT(ammAlice.expectBalances( - XRP(13'000), STAmount{USD, UINT64_C(13'012'92609877023), -11}, ammTokens)); + XRP(13'000), + STAmount{USD, UINT64_C(13'012'92609877023), -11}, + ammTokens)); else BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'003}, STAmount{USD, UINT64_C(13'012'92609877024), -11}, ammTokens)); + XRPAmount{13'000'000'003}, + STAmount{USD, UINT64_C(13'012'92609877024), -11}, + ammTokens)); // Discounted fee payment ammAlice.deposit(carol, USD(100)); ammTokens = ammAlice.getLPTokensBalance(); if (!features[fixAMMv1_3]) BEAST_EXPECT(ammAlice.expectBalances( - XRP(13'000), STAmount{USD, UINT64_C(13'112'92609877023), -11}, ammTokens)); + XRP(13'000), + STAmount{USD, UINT64_C(13'112'92609877023), -11}, + ammTokens)); else BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'003}, STAmount{USD, UINT64_C(13'112'92609877024), -11}, ammTokens)); + XRPAmount{13'000'000'003}, + STAmount{USD, UINT64_C(13'112'92609877024), -11}, + ammTokens)); env(pay(carol, bob, USD(100)), path(~USD), sendmax(XRP(110))); env.close(); // carol pays 100000 drops in fees // 99900668XRP swapped in for 100USD if (!features[fixAMMv1_3]) BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'100'000'668}, STAmount{USD, UINT64_C(13'012'92609877023), -11}, ammTokens)); + XRPAmount{13'100'000'668}, + STAmount{USD, UINT64_C(13'012'92609877023), -11}, + ammTokens)); else BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'100'000'671}, STAmount{USD, UINT64_C(13'012'92609877024), -11}, ammTokens)); + XRPAmount{13'100'000'671}, + STAmount{USD, UINT64_C(13'012'92609877024), -11}, + ammTokens)); } // Payment with the trading fee env(pay(alice, carol, XRP(100)), path(~XRP), sendmax(USD(110))); @@ -2495,26 +2873,36 @@ private: if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'668}, STAmount{USD, UINT64_C(13'114'03663047264), -11}, ammTokens)); + XRPAmount{13'000'000'668}, + STAmount{USD, UINT64_C(13'114'03663047264), -11}, + ammTokens)); } else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'668}, STAmount{USD, UINT64_C(13'114'03663047269), -11}, ammTokens)); + XRPAmount{13'000'000'668}, + STAmount{USD, UINT64_C(13'114'03663047269), -11}, + ammTokens)); } else { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'671}, STAmount{USD, UINT64_C(13'114'03663044937), -11}, ammTokens)); + XRPAmount{13'000'000'671}, + STAmount{USD, UINT64_C(13'114'03663044937), -11}, + ammTokens)); } // Auction slot expired, no discounted fee env.close(seconds(TOTAL_TIME_SLOT_SECS + 1)); // clock is parent's based env.close(); if (!features[fixAMMv1_1]) - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'399'00572620545), -11)); + BEAST_EXPECT( + env.balance(carol, USD) == + STAmount(USD, UINT64_C(29'399'00572620545), -11)); else if (!features[fixAMMv1_3]) - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'399'00572620544), -11)); + BEAST_EXPECT( + env.balance(carol, USD) == + STAmount(USD, UINT64_C(29'399'00572620544), -11)); ammTokens = ammAlice.getLPTokensBalance(); for (int i = 0; i < 10; ++i) { @@ -2525,21 +2913,33 @@ private: // trading fees vs discounted fee. if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) { - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'389'06197177128), -11)); + BEAST_EXPECT( + env.balance(carol, USD) == + STAmount(USD, UINT64_C(29'389'06197177128), -11)); BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'668}, STAmount{USD, UINT64_C(13'123'98038490681), -11}, ammTokens)); + XRPAmount{13'000'000'668}, + STAmount{USD, UINT64_C(13'123'98038490681), -11}, + ammTokens)); } else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) { - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'389'06197177124), -11)); + BEAST_EXPECT( + env.balance(carol, USD) == + STAmount(USD, UINT64_C(29'389'06197177124), -11)); BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'668}, STAmount{USD, UINT64_C(13'123'98038490689), -11}, ammTokens)); + XRPAmount{13'000'000'668}, + STAmount{USD, UINT64_C(13'123'98038490689), -11}, + ammTokens)); } else { - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'389'06197177129), -11)); + BEAST_EXPECT( + env.balance(carol, USD) == + STAmount(USD, UINT64_C(29'389'06197177129), -11)); BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'671}, STAmount{USD, UINT64_C(13'123'98038488352), -11}, ammTokens)); + XRPAmount{13'000'000'671}, + STAmount{USD, UINT64_C(13'123'98038488352), -11}, + ammTokens)); } env(pay(carol, bob, USD(100)), path(~USD), sendmax(XRP(110))); env.close(); @@ -2549,17 +2949,23 @@ private: if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(13'100'824'790), STAmount{USD, UINT64_C(13'023'98038490681), -11}, ammTokens)); + XRPAmount(13'100'824'790), + STAmount{USD, UINT64_C(13'023'98038490681), -11}, + ammTokens)); } else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(13'100'824'790), STAmount{USD, UINT64_C(13'023'98038490689), -11}, ammTokens)); + XRPAmount(13'100'824'790), + STAmount{USD, UINT64_C(13'023'98038490689), -11}, + ammTokens)); } else { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(13'100'824'793), STAmount{USD, UINT64_C(13'023'98038488352), -11}, ammTokens)); + XRPAmount(13'100'824'793), + STAmount{USD, UINT64_C(13'023'98038488352), -11}, + ammTokens)); } }, std::nullopt, @@ -2637,7 +3043,8 @@ private: // But trades with the discounted fee since she still owns the slot. // Alice pays 10011 drops in fees env(pay(alice, bob, USD(10)), path(~USD), sendmax(XRP(11))); - BEAST_EXPECT(amm.expectBalances(XRPAmount{1'010'010'011}, USD(1'000), IOUAmount{1'004'487'562112089, -9})); + BEAST_EXPECT(amm.expectBalances( + XRPAmount{1'010'010'011}, USD(1'000), IOUAmount{1'004'487'562112089, -9})); // Bob pays the full fee ~0.1USD env(pay(bob, alice, XRP(10)), path(~XRP), sendmax(USD(11))); if (!features[fixAMMv1_1]) @@ -2668,7 +3075,8 @@ private: { auto jtx = env.jt(tx, seq(1), fee(baseFee)); env.app().config().features.erase(featureAMM); - PreflightContext pfCtx(env.app(), *jtx.stx, env.current()->rules(), tapNONE, env.journal); + PreflightContext pfCtx( + env.app(), *jtx.stx, env.current()->rules(), tapNONE, env.journal); auto pf = Transactor::invokePreflight(pfCtx); BEAST_EXPECT(pf == temDISABLED); env.app().config().features.insert(featureAMM); @@ -2678,7 +3086,8 @@ private: auto jtx = env.jt(tx, seq(1), fee(baseFee)); jtx.jv["TxnSignature"] = "deadbeef"; jtx.stx = env.ust(jtx); - PreflightContext pfCtx(env.app(), *jtx.stx, env.current()->rules(), tapNONE, env.journal); + PreflightContext pfCtx( + env.app(), *jtx.stx, env.current()->rules(), tapNONE, env.journal); auto pf = Transactor::invokePreflight(pfCtx); BEAST_EXPECT(pf != tesSUCCESS); } @@ -2688,7 +3097,8 @@ private: jtx.jv["Asset2"]["currency"] = "XRP"; jtx.jv["Asset2"].removeMember("issuer"); jtx.stx = env.ust(jtx); - PreflightContext pfCtx(env.app(), *jtx.stx, env.current()->rules(), tapNONE, env.journal); + PreflightContext pfCtx( + env.app(), *jtx.stx, env.current()->rules(), tapNONE, env.journal); auto pf = Transactor::invokePreflight(pfCtx); BEAST_EXPECT(pf == temBAD_AMM_TOKENS); } @@ -2747,21 +3157,29 @@ private: auto const pk = carol.pk(); auto const settleDelay = 100s; NetClock::time_point const cancelAfter = env.current()->header().parentCloseTime + 200s; - env(paychan::create(carol, ammAlice.ammAccount(), XRP(1'000), settleDelay, pk, cancelAfter), + env(paychan::create( + carol, ammAlice.ammAccount(), XRP(1'000), settleDelay, pk, cancelAfter), ter(tecNO_PERMISSION)); }); // Can't pay into AMM with checks. testAMM([&](AMM& ammAlice, Env& env) { - env(check::create(env.master.id(), ammAlice.ammAccount(), XRP(100)), ter(tecNO_PERMISSION)); + env(check::create(env.master.id(), ammAlice.ammAccount(), XRP(100)), + ter(tecNO_PERMISSION)); }); // Pay amounts close to one side of the pool testAMM( [&](AMM& ammAlice, Env& env) { // Can't consume whole pool - env(pay(alice, carol, USD(100)), path(~USD), sendmax(XRP(1'000'000'000)), ter(tecPATH_PARTIAL)); - env(pay(alice, carol, XRP(100)), path(~XRP), sendmax(USD(1'000'000'000)), ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(100)), + path(~USD), + sendmax(XRP(1'000'000'000)), + ter(tecPATH_PARTIAL)); + env(pay(alice, carol, XRP(100)), + path(~XRP), + sendmax(USD(1'000'000'000)), + ter(tecPATH_PARTIAL)); // Overflow env(pay(alice, carol, STAmount{USD, UINT64_C(99'999999999), -9}), path(~USD), @@ -2776,7 +3194,10 @@ private: sendmax(USD(1'000'000'000)), ter(tecPATH_PARTIAL)); // Sender doesn't have enough funds - env(pay(alice, carol, USD(99.99)), path(~USD), sendmax(XRP(1'000'000'000)), ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(99.99)), + path(~USD), + sendmax(XRP(1'000'000'000)), + ter(tecPATH_PARTIAL)); env(pay(alice, carol, STAmount{xrpIssue(), 99'990'000}), path(~XRP), sendmax(USD(1'000'000'000)), @@ -2802,7 +3223,8 @@ private: // Individually frozen AMM testAMM([&](AMM& ammAlice, Env& env) { - env(trust(gw, STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, tfSetFreeze)); + env(trust( + gw, STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, tfSetFreeze)); env.close(); env(pay(alice, carol, USD(1)), path(~USD), @@ -2837,7 +3259,8 @@ private: // For now, just disable SAV entirely, which locks in the small Number // mantissas - features = features - featureSingleAssetVault - featureLendingProtocol - featureLendingProtocol; + features = + features - featureSingleAssetVault - featureLendingProtocol - featureLendingProtocol; // Payment 100USD for 100XRP. // Force one path with tfNoRippleDirect. @@ -2845,13 +3268,17 @@ private: [&](AMM& ammAlice, Env& env) { env.fund(jtx::XRP(30'000), bob); env.close(); - env(pay(bob, carol, USD(100)), path(~USD), sendmax(XRP(100)), txflags(tfNoRippleDirect)); + env(pay(bob, carol, USD(100)), + path(~USD), + sendmax(XRP(100)), + txflags(tfNoRippleDirect)); env.close(); BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); // Initial balance 30,000 + 100 BEAST_EXPECT(expectHolding(env, carol, USD(30'100))); // Initial balance 30,000 - 100(sendmax) - 10(tx fee) - BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); }, {{XRP(10'000), USD(10'100)}}, 0, @@ -2869,7 +3296,8 @@ private: // Initial balance 30,000 + 100 BEAST_EXPECT(expectHolding(env, carol, USD(30'100))); // Initial balance 30,000 - 100(sendmax) - 10(tx fee) - BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); }, {{XRP(10'000), USD(10'100)}}, 0, @@ -2888,7 +3316,8 @@ private: // Initial balance 30,000 + 100 BEAST_EXPECT(expectHolding(env, carol, USD(30'100))); // Initial balance 30,000 - 100(sendmax) - 10(tx fee) - BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); }, {{XRP(10'000), USD(10'100)}}, 0, @@ -2912,7 +3341,8 @@ private: BEAST_EXPECT(expectHolding(env, carol, USD(30'010))); // Initial balance 30,000 - 10(limited by limitQuality) - 10(tx // fee) - BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(10) - txfee(env, 1))); + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(10) - txfee(env, 1))); // Fails because of limitQuality. Would have sent // ~98.91USD/110XRP has it not been for limitQuality. @@ -2945,8 +3375,10 @@ private: env.close(); BEAST_EXPECT(ammAlice.expectBalances(XRP(10'010), USD(10'000), ammAlice.tokens())); // 10USD - 10% transfer fee - BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(30'009'09090909091), -11})); - BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(10) - txfee(env, 1))); + BEAST_EXPECT( + expectHolding(env, carol, STAmount{USD, UINT64_C(30'009'09090909091), -11})); + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(10) - txfee(env, 1))); }, {{XRP(10'000), USD(10'010)}}, 0, @@ -2983,10 +3415,15 @@ private: auto ammUSD_EUR = AMM(env, alice, EUR(10'000), USD(10'000)); env(offer(alice, XRP(101), USD(100)), txflags(tfPassive)); env.close(); - env(pay(bob, carol, USD(100)), path(~EUR, ~USD), sendmax(XRP(102)), txflags(tfPartialPayment)); + env(pay(bob, carol, USD(100)), + path(~EUR, ~USD), + sendmax(XRP(102)), + txflags(tfPartialPayment)); env.close(); BEAST_EXPECT(ammEUR_XRP.expectBalances( - XRPAmount(10'030'082'730), STAmount(EUR, UINT64_C(9'970'007498125468), -12), ammEUR_XRP.tokens())); + XRPAmount(10'030'082'730), + STAmount(EUR, UINT64_C(9'970'007498125468), -12), + ammEUR_XRP.tokens())); if (!features[fixAMMv1_1]) { BEAST_EXPECT(ammUSD_EUR.expectBalances( @@ -2997,7 +3434,8 @@ private: // fixReducedOffersV2 changes the expected results slightly. Amounts const expectedAmounts = env.closed()->rules().enabled(fixReducedOffersV2) ? Amounts{XRPAmount(30'201'749), STAmount(USD, UINT64_C(29'90272233787816), -14)} - : Amounts{XRPAmount(30'201'749), STAmount(USD, UINT64_C(29'90272233787818), -14)}; + : Amounts{ + XRPAmount(30'201'749), STAmount(USD, UINT64_C(29'90272233787818), -14)}; BEAST_EXPECT(expectOffers(env, alice, 1, {{expectedAmounts}})); } @@ -3011,7 +3449,8 @@ private: // fixReducedOffersV2 changes the expected results slightly. Amounts const expectedAmounts = env.closed()->rules().enabled(fixReducedOffersV2) ? Amounts{XRPAmount(30'201'749), STAmount(USD, UINT64_C(29'90272233782839), -14)} - : Amounts{XRPAmount(30'201'749), STAmount(USD, UINT64_C(29'90272233782840), -14)}; + : Amounts{ + XRPAmount(30'201'749), STAmount(USD, UINT64_C(29'90272233782840), -14)}; BEAST_EXPECT(expectOffers(env, alice, 1, {{expectedAmounts}})); } @@ -3019,7 +3458,9 @@ private: BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, 30'100})); // Initial 1,000 - 30082730(AMM pool) - 70798251(offer) - 10(tx fee) BEAST_EXPECT(expectLedgerEntryRoot( - env, bob, XRP(1'000) - XRPAmount{30'082'730} - XRPAmount{70'798'251} - txfee(env, 1))); + env, + bob, + XRP(1'000) - XRPAmount{30'082'730} - XRPAmount{70'798'251} - txfee(env, 1))); } // Default path (with AMM) has a better quality than a non-default path. @@ -3036,10 +3477,15 @@ private: env.close(); env(offer(alice, EUR(100), USD(100)), txflags(tfPassive)); env.close(); - env(pay(bob, carol, USD(100)), path(~EUR, ~USD), sendmax(XRP(102)), txflags(tfPartialPayment)); + env(pay(bob, carol, USD(100)), + path(~EUR, ~USD), + sendmax(XRP(102)), + txflags(tfPartialPayment)); env.close(); BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(10'050'238'637), STAmount(USD, UINT64_C(9'950'01249687578), -11), ammAlice.tokens())); + XRPAmount(10'050'238'637), + STAmount(USD, UINT64_C(9'950'01249687578), -11), + ammAlice.tokens())); BEAST_EXPECT(expectOffers( env, alice, @@ -3049,11 +3495,14 @@ private: STAmount(EUR, UINT64_C(49'98750312422), -11), STAmount(USD, UINT64_C(49'98750312422), -11)}}})); // Initial 30,000 + 99.99999999999 - BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(30'099'99999999999), -11})); + BEAST_EXPECT( + expectHolding(env, carol, STAmount{USD, UINT64_C(30'099'99999999999), -11})); // Initial 1,000 - 50238637(AMM pool) - 50512622(offer) - 10(tx // fee) BEAST_EXPECT(expectLedgerEntryRoot( - env, bob, XRP(1'000) - XRPAmount{50'238'637} - XRPAmount{50'512'622} - txfee(env, 1))); + env, + bob, + XRP(1'000) - XRPAmount{50'238'637} - XRPAmount{50'512'622} - txfee(env, 1))); }, std::nullopt, 0, @@ -3072,20 +3521,27 @@ private: env.close(); if (!features[fixAMMv1_1]) { - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); // Initial 30,000 + 200 BEAST_EXPECT(expectHolding(env, carol, USD(30'200))); } else { BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), STAmount(USD, UINT64_C(10'000'00000000001), -11), ammAlice.tokens())); - BEAST_EXPECT(expectHolding(env, carol, STAmount(USD, UINT64_C(30'199'99999999999), -11))); + XRP(10'100), + STAmount(USD, UINT64_C(10'000'00000000001), -11), + ammAlice.tokens())); + BEAST_EXPECT(expectHolding( + env, carol, STAmount(USD, UINT64_C(30'199'99999999999), -11))); } // Initial 30,000 - 10000(AMM pool LP) - 100(AMM offer) - // - 100(offer) - 10(tx fee) - one reserve BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, XRP(30'000) - XRP(10'000) - XRP(100) - XRP(100) - ammCrtFee(env) - txfee(env, 1))); + env, + alice, + XRP(30'000) - XRP(10'000) - XRP(100) - XRP(100) - ammCrtFee(env) - + txfee(env, 1))); BEAST_EXPECT(expectOffers(env, bob, 0)); }, {{XRP(10'000), USD(10'100)}}, @@ -3121,7 +3577,8 @@ private: // Initial 1,000 + 100 BEAST_EXPECT(expectHolding(env, bob, USD(1'100))); // Initial 30,000 - 100(offer) - 10(tx fee) - BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); BEAST_EXPECT(expectOffers(env, bob, 0)); }, {{XRP(10'000), USD(10'100)}}, @@ -3182,12 +3639,19 @@ private: // quality. // AMM offer ~50USD/91XRP BEAST_EXPECT(amm.expectBalances( - XRPAmount(909'090'909), STAmount{USD, UINT64_C(550'000000055), -9}, amm.tokens())); + XRPAmount(909'090'909), + STAmount{USD, UINT64_C(550'000000055), -9}, + amm.tokens())); // Offer ~91XRP/49.99USD - BEAST_EXPECT( - expectOffers(env, carol, 1, {{Amounts{XRPAmount{9'090'909}, STAmount{USD, 4'99999995, -8}}}})); + BEAST_EXPECT(expectOffers( + env, + carol, + 1, + {{Amounts{XRPAmount{9'090'909}, STAmount{USD, 4'99999995, -8}}}})); // Carol pays 0.1% fee on ~50USD =~ 0.05USD - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'949'94999999494), -11)); + BEAST_EXPECT( + env.balance(carol, USD) == + STAmount(USD, UINT64_C(29'949'94999999494), -11)); } }, {{XRP(1'000), USD(500)}}, @@ -3202,14 +3666,14 @@ private: env.close(); if (!features[fixAMMv1_1]) { - BEAST_EXPECT( - amm.expectBalances(XRP(990), STAmount{USD, UINT64_C(505'050505050505), -12}, amm.tokens())); + BEAST_EXPECT(amm.expectBalances( + XRP(990), STAmount{USD, UINT64_C(505'050505050505), -12}, amm.tokens())); BEAST_EXPECT(expectOffers(env, carol, 0)); } else { - BEAST_EXPECT( - amm.expectBalances(XRP(990), STAmount{USD, UINT64_C(505'0505050505051), -13}, amm.tokens())); + BEAST_EXPECT(amm.expectBalances( + XRP(990), STAmount{USD, UINT64_C(505'0505050505051), -13}, amm.tokens())); BEAST_EXPECT(expectOffers(env, carol, 0)); } }, @@ -3263,9 +3727,11 @@ private: // = 58.825 = ~29941.17 // carol bought ~72.93EUR at the cost of ~70.68GBP // the offer is partially consumed - BEAST_EXPECT(expectHolding(env, carol, STAmount{GBP, UINT64_C(29'941'16770347333), -11})); + BEAST_EXPECT(expectHolding( + env, carol, STAmount{GBP, UINT64_C(29'941'16770347333), -11})); // Initial 30,000 + ~49.3(offers = 39.3(AMM) + 10(LOB)) - BEAST_EXPECT(expectHolding(env, carol, STAmount{EUR, UINT64_C(30'049'31517120716), -11})); + BEAST_EXPECT(expectHolding( + env, carol, STAmount{EUR, UINT64_C(30'049'31517120716), -11})); } else { @@ -3296,9 +3762,11 @@ private: // = 88.35 = ~29911.64 // carol bought ~72.93EUR at the cost of ~70.68GBP // the offer is partially consumed - BEAST_EXPECT(expectHolding(env, carol, STAmount{GBP, UINT64_C(29'911'64396400896), -11})); + BEAST_EXPECT(expectHolding( + env, carol, STAmount{GBP, UINT64_C(29'911'64396400896), -11})); // Initial 30,000 + ~72.93(offers = 62.93(AMM) + 10(LOB)) - BEAST_EXPECT(expectHolding(env, carol, STAmount{EUR, UINT64_C(30'072'93416277865), -11})); + BEAST_EXPECT(expectHolding( + env, carol, STAmount{EUR, UINT64_C(30'072'93416277865), -11})); } // Initial 2000 + 10 = 2010 BEAST_EXPECT(expectHolding(env, bob, GBP(2'010))); @@ -3322,7 +3790,10 @@ private: fund(env, gw, {bob}, {GBP(200), EUR(200)}, Fund::Acct); env(rate(gw, 1.25)); env.close(); - env(pay(bob, carol, EUR(100)), path(~EUR), sendmax(GBP(125)), txflags(tfPartialPayment)); + env(pay(bob, carol, EUR(100)), + path(~EUR), + sendmax(GBP(125)), + txflags(tfPartialPayment)); env.close(); BEAST_EXPECT(ammAlice.expectBalances(GBP(1'100), EUR(1'000), ammAlice.tokens())); BEAST_EXPECT(expectHolding(env, bob, GBP(75))); @@ -3407,7 +3878,12 @@ private: { Env env(*this, features); auto const ETH = gw["ETH"]; - fund(env, gw, {alice}, XRP(100'000), {EUR(50'000), BTC(50'000), ETH(50'000), USD(50'000)}); + fund( + env, + gw, + {alice}, + XRP(100'000), + {EUR(50'000), BTC(50'000), ETH(50'000), USD(50'000)}); fund(env, gw, {carol, bob}, XRP(1'000), {USD(200)}, Fund::Acct); AMM xrp_eur(env, alice, XRP(10'100), EUR(10'000)); AMM eur_btc(env, alice, EUR(10'000), BTC(10'200)); @@ -3426,7 +3902,9 @@ private: // XRP-ETH-EUR-USD // This path provides ~26.06USD/26.2XRP BEAST_EXPECT(xrp_eth.expectBalances( - XRPAmount(10'026'208'900), STAmount{ETH, UINT64_C(10'073'65779244494), -11}, xrp_eth.tokens())); + XRPAmount(10'026'208'900), + STAmount{ETH, UINT64_C(10'073'65779244494), -11}, + xrp_eth.tokens())); BEAST_EXPECT(eth_eur.expectBalances( STAmount{ETH, UINT64_C(10'926'34220755506), -11}, STAmount{EUR, UINT64_C(10'973'54232078752), -11}, @@ -3438,12 +3916,16 @@ private: // XRP-USD path // This path provides ~73.9USD/74.1XRP BEAST_EXPECT(xrp_usd.expectBalances( - XRPAmount(10'224'106'246), STAmount{USD, UINT64_C(10'126'06848287914), -11}, xrp_usd.tokens())); + XRPAmount(10'224'106'246), + STAmount{USD, UINT64_C(10'126'06848287914), -11}, + xrp_usd.tokens())); } else { BEAST_EXPECT(xrp_eth.expectBalances( - XRPAmount(10'026'208'900), STAmount{ETH, UINT64_C(10'073'65779244461), -11}, xrp_eth.tokens())); + XRPAmount(10'026'208'900), + STAmount{ETH, UINT64_C(10'073'65779244461), -11}, + xrp_eth.tokens())); BEAST_EXPECT(eth_eur.expectBalances( STAmount{ETH, UINT64_C(10'926'34220755539), -11}, STAmount{EUR, UINT64_C(10'973'5423207872), -10}, @@ -3455,7 +3937,9 @@ private: // XRP-USD path // This path provides ~73.9USD/74.1XRP BEAST_EXPECT(xrp_usd.expectBalances( - XRPAmount(10'224'106'246), STAmount{USD, UINT64_C(10'126'06848287943), -11}, xrp_usd.tokens())); + XRPAmount(10'224'106'246), + STAmount{USD, UINT64_C(10'126'06848287943), -11}, + xrp_usd.tokens())); } // XRP-EUR-BTC-USD @@ -3475,28 +3959,42 @@ private: { Env env(*this, features); auto const ETH = gw["ETH"]; - fund(env, gw, {alice}, XRP(40'000), {EUR(50'000), BTC(50'000), ETH(50'000), USD(50'000)}); + fund( + env, + gw, + {alice}, + XRP(40'000), + {EUR(50'000), BTC(50'000), ETH(50'000), USD(50'000)}); fund(env, gw, {carol, bob}, XRP(1000), {USD(200)}, Fund::Acct); AMM xrp_eur(env, alice, XRP(10'100), EUR(10'000)); AMM eur_btc(env, alice, EUR(10'000), BTC(10'200)); AMM btc_usd(env, alice, BTC(10'100), USD(10'000)); AMM xrp_eth(env, alice, XRP(10'000), ETH(10'100)); AMM eth_eur(env, alice, ETH(10'900), EUR(11'000)); - env(pay(bob, carol, USD(100)), path(~EUR, ~BTC, ~USD), path(~ETH, ~EUR, ~BTC, ~USD), sendmax(XRP(200))); + env(pay(bob, carol, USD(100)), + path(~EUR, ~BTC, ~USD), + path(~ETH, ~EUR, ~BTC, ~USD), + sendmax(XRP(200))); if (!features[fixAMMv1_1]) { // XRP-EUR-BTC-USD path provides ~17.8USD/~18.7XRP // XRP-ETH-EUR-BTC-USD path provides ~82.2USD/82.4XRP BEAST_EXPECT(xrp_eur.expectBalances( - XRPAmount(10'118'738'472), STAmount{EUR, UINT64_C(9'981'544436337968), -12}, xrp_eur.tokens())); + XRPAmount(10'118'738'472), + STAmount{EUR, UINT64_C(9'981'544436337968), -12}, + xrp_eur.tokens())); BEAST_EXPECT(eur_btc.expectBalances( STAmount{EUR, UINT64_C(10'101'16096785173), -11}, STAmount{BTC, UINT64_C(10'097'91426968066), -11}, eur_btc.tokens())); BEAST_EXPECT(btc_usd.expectBalances( - STAmount{BTC, UINT64_C(10'202'08573031934), -11}, USD(9'900), btc_usd.tokens())); + STAmount{BTC, UINT64_C(10'202'08573031934), -11}, + USD(9'900), + btc_usd.tokens())); BEAST_EXPECT(xrp_eth.expectBalances( - XRPAmount(10'082'446'397), STAmount{ETH, UINT64_C(10'017'41072778012), -11}, xrp_eth.tokens())); + XRPAmount(10'082'446'397), + STAmount{ETH, UINT64_C(10'017'41072778012), -11}, + xrp_eth.tokens())); BEAST_EXPECT(eth_eur.expectBalances( STAmount{ETH, UINT64_C(10'982'58927221988), -11}, STAmount{EUR, UINT64_C(10'917'2945958103), -10}, @@ -3505,15 +4003,21 @@ private: else { BEAST_EXPECT(xrp_eur.expectBalances( - XRPAmount(10'118'738'472), STAmount{EUR, UINT64_C(9'981'544436337923), -12}, xrp_eur.tokens())); + XRPAmount(10'118'738'472), + STAmount{EUR, UINT64_C(9'981'544436337923), -12}, + xrp_eur.tokens())); BEAST_EXPECT(eur_btc.expectBalances( STAmount{EUR, UINT64_C(10'101'16096785188), -11}, STAmount{BTC, UINT64_C(10'097'91426968059), -11}, eur_btc.tokens())); BEAST_EXPECT(btc_usd.expectBalances( - STAmount{BTC, UINT64_C(10'202'08573031941), -11}, USD(9'900), btc_usd.tokens())); + STAmount{BTC, UINT64_C(10'202'08573031941), -11}, + USD(9'900), + btc_usd.tokens())); BEAST_EXPECT(xrp_eth.expectBalances( - XRPAmount(10'082'446'397), STAmount{ETH, UINT64_C(10'017'41072777996), -11}, xrp_eth.tokens())); + XRPAmount(10'082'446'397), + STAmount{ETH, UINT64_C(10'017'41072777996), -11}, + xrp_eth.tokens())); BEAST_EXPECT(eth_eur.expectBalances( STAmount{ETH, UINT64_C(10'982'58927222004), -11}, STAmount{EUR, UINT64_C(10'917'2945958102), -10}, @@ -3542,14 +4046,20 @@ private: { // Carol gets ~29.91USD because of the AMM offers limit BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'030), STAmount{USD, UINT64_C(9'970'089730807577), -12}, ammAlice.tokens())); - BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(30'029'91026919241), -11})); + XRP(10'030), + STAmount{USD, UINT64_C(9'970'089730807577), -12}, + ammAlice.tokens())); + BEAST_EXPECT(expectHolding( + env, carol, STAmount{USD, UINT64_C(30'029'91026919241), -11})); } else { BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'030), STAmount{USD, UINT64_C(9'970'089730807827), -12}, ammAlice.tokens())); - BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(30'029'91026919217), -11})); + XRP(10'030), + STAmount{USD, UINT64_C(9'970'089730807827), -12}, + ammAlice.tokens())); + BEAST_EXPECT(expectHolding( + env, carol, STAmount{USD, UINT64_C(30'029'91026919217), -11})); } BEAST_EXPECT(expectOffers(env, alice, 1, {{{EUR(140), XRP(100)}}})); }, @@ -3572,18 +4082,23 @@ private: path(~XRP, ~USD), sendmax(EUR(400)), txflags(tfPartialPayment | tfNoRippleDirect)); - BEAST_EXPECT(ammAlice.expectBalances(XRPAmount{10'101'010'102}, USD(9'900), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount{10'101'010'102}, USD(9'900), ammAlice.tokens())); if (!features[fixAMMv1_1]) { // Carol gets ~100USD - BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(30'099'99999999999), -11})); + BEAST_EXPECT(expectHolding( + env, carol, STAmount{USD, UINT64_C(30'099'99999999999), -11})); } else { BEAST_EXPECT(expectHolding(env, carol, USD(30'100))); } - BEAST_EXPECT( - expectOffers(env, alice, 1, {{{STAmount{EUR, UINT64_C(39'1858572), -7}, XRPAmount{27'989'898}}}})); + BEAST_EXPECT(expectOffers( + env, + alice, + 1, + {{{STAmount{EUR, UINT64_C(39'1858572), -7}, XRPAmount{27'989'898}}}})); }, std::nullopt, 0, @@ -3601,16 +4116,26 @@ private: if (!features[fixAMMv1_1]) { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{10'049'825'373}, STAmount{USD, UINT64_C(10'049'92586949302), -11}, ammAlice.tokens())); + XRPAmount{10'049'825'373}, + STAmount{USD, UINT64_C(10'049'92586949302), -11}, + ammAlice.tokens())); BEAST_EXPECT(expectOffers( - env, bob, 1, {{{XRPAmount{50'074'629}, STAmount{USD, UINT64_C(50'07513050698), -11}}}})); + env, + bob, + 1, + {{{XRPAmount{50'074'629}, STAmount{USD, UINT64_C(50'07513050698), -11}}}})); } else { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{10'049'825'372}, STAmount{USD, UINT64_C(10'049'92587049303), -11}, ammAlice.tokens())); + XRPAmount{10'049'825'372}, + STAmount{USD, UINT64_C(10'049'92587049303), -11}, + ammAlice.tokens())); BEAST_EXPECT(expectOffers( - env, bob, 1, {{{XRPAmount{50'074'628}, STAmount{USD, UINT64_C(50'07512950697), -11}}}})); + env, + bob, + 1, + {{{XRPAmount{50'074'628}, STAmount{USD, UINT64_C(50'07512950697), -11}}}})); BEAST_EXPECT(expectHolding(env, carol, USD(30'100))); } } @@ -3644,7 +4169,10 @@ private: auto const baseFee = env.current()->fees().base.drops(); auto const token1 = ammAlice.lptIssue(); auto priceXRP = ammAssetOut( - STAmount{XRPAmount{10'000'000'000}}, STAmount{token1, 10'000'000}, STAmount{token1, 5'000'000}, 0); + STAmount{XRPAmount{10'000'000'000}}, + STAmount{token1, 10'000'000}, + STAmount{token1, 5'000'000}, + 0); // Carol places an order to buy LPTokens env(offer(carol, STAmount{token1, 5'000'000}, priceXRP)); // Alice places an order to sell LPTokens @@ -3665,12 +4193,15 @@ private: BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{100})); BEAST_EXPECT(accountBalance(env, carol) == std::to_string(22500000000 - 4 * baseFee)); priceXRP = ammAssetOut( - STAmount{XRPAmount{10'000'000'000}}, STAmount{token1, 9'999'900}, STAmount{token1, 4'999'900}, 0); + STAmount{XRPAmount{10'000'000'000}}, + STAmount{token1, 9'999'900}, + STAmount{token1, 4'999'900}, + 0); // Carol withdraws ammAlice.withdrawAll(carol, XRP(0)); BEAST_EXPECT(accountBalance(env, carol) == std::to_string(29999949999 - 5 * baseFee)); - BEAST_EXPECT( - ammAlice.expectBalances(XRPAmount{10'000'000'000} - priceXRP, USD(10'000), IOUAmount{5'000'000})); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount{10'000'000'000} - priceXRP, USD(10'000), IOUAmount{5'000'000})); BEAST_EXPECT(ammAlice.expectLPTokens(alice, IOUAmount{5'000'000})); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); }); @@ -3763,7 +4294,9 @@ private: testAMM([&](AMM& ammAlice, Env& env) { auto const info = env.rpc( - "json", "account_info", std::string("{\"account\": \"" + to_string(ammAlice.ammAccount()) + "\"}")); + "json", + "account_info", + std::string("{\"account\": \"" + to_string(ammAlice.ammAccount()) + "\"}")); auto const flags = info[jss::result][jss::account_data][jss::Flags].asUInt(); BEAST_EXPECT(flags == (lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth)); }); @@ -3864,14 +4397,22 @@ private: prep( [&](Env& env) { if (!features[fixAMMv1_1]) - env(offer(LP1, XRPAmount{18'095'133}, STAmount{TST, UINT64_C(1'68737984885388), -14}), + env(offer( + LP1, + XRPAmount{18'095'133}, + STAmount{TST, UINT64_C(1'68737984885388), -14}), txflags(tfPassive)); else - env(offer(LP1, XRPAmount{18'095'132}, STAmount{TST, UINT64_C(1'68737976189735), -14}), + env(offer( + LP1, + XRPAmount{18'095'132}, + STAmount{TST, UINT64_C(1'68737976189735), -14}), txflags(tfPassive)); }, [&](Env& env) { - BEAST_EXPECT(lp2TSTBalance == getAccountLines(env, LP2, TST)["lines"][0u]["balance"].asString()); + BEAST_EXPECT( + lp2TSTBalance == + getAccountLines(env, LP2, TST)["lines"][0u]["balance"].asString()); auto const offer = getAccountOffers(env, LP2)["offers"][0u]; BEAST_EXPECT(lp2TakerGets == offer["taker_gets"].asString()); BEAST_EXPECT(lp2TakerPays == offer["taker_pays"]["value"].asString()); @@ -3905,7 +4446,8 @@ private: ammAlice.vote(alice, 0); ammAlice.withdrawAll(carol, USD(0)); // Carol gets back less than the original deposit - BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(29'994'96220068281), -11})); + BEAST_EXPECT( + expectHolding(env, carol, STAmount{USD, UINT64_C(29'994'96220068281), -11})); }, {{USD(1'000), EUR(1'000)}}, 0, @@ -3917,7 +4459,8 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { auto const balance = env.balance(carol, USD); - auto tokensFee = ammAlice.deposit(carol, USD(1'000), std::nullopt, STAmount{USD, 1, -1}); + auto tokensFee = + ammAlice.deposit(carol, USD(1'000), std::nullopt, STAmount{USD, 1, -1}); auto const deposit = balance - env.balance(carol, USD); ammAlice.withdrawAll(carol, USD(0)); ammAlice.vote(alice, 0); @@ -3938,7 +4481,8 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { auto const balance = env.balance(carol, USD); - auto const tokensFee = ammAlice.deposit(carol, USD(200), std::nullopt, STAmount{USD, 2020, -6}); + auto const tokensFee = + ammAlice.deposit(carol, USD(200), std::nullopt, STAmount{USD, 2020, -6}); auto const deposit = balance - env.balance(carol, USD); ammAlice.withdrawAll(carol, USD(0)); ammAlice.vote(alice, 0); @@ -3967,7 +4511,8 @@ private: BEAST_EXPECT(ammAlice.expectTradingFee(1'000)); // Single withdrawal. Carol gets ~5USD less than deposited. ammAlice.withdrawAll(carol, USD(0)); - BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(29'994'97487437186), -11})); + BEAST_EXPECT( + expectHolding(env, carol, STAmount{USD, UINT64_C(29'994'97487437186), -11})); }, {{USD(1'000), EUR(1'000)}}, 0, @@ -3978,7 +4523,8 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { ammAlice.deposit(carol, 1'000'000); - auto const tokensFee = ammAlice.withdraw(carol, USD(100), std::nullopt, IOUAmount{520, 0}); + auto const tokensFee = + ammAlice.withdraw(carol, USD(100), std::nullopt, IOUAmount{520, 0}); // carol withdraws ~1,443.44USD auto const balanceAfterWithdraw = [&]() { if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) @@ -3997,11 +4543,17 @@ private: BEAST_EXPECT(ammAlice.expectTradingFee(0)); auto const tokensNoFee = ammAlice.withdraw(carol, deposit); if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(30'443'43891402717), -11)); + BEAST_EXPECT( + env.balance(carol, USD) == + STAmount(USD, UINT64_C(30'443'43891402717), -11)); else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(30'443'43891402716), -11)); + BEAST_EXPECT( + env.balance(carol, USD) == + STAmount(USD, UINT64_C(30'443'43891402716), -11)); else - BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(30'443'43891402713), -11)); + BEAST_EXPECT( + env.balance(carol, USD) == + STAmount(USD, UINT64_C(30'443'43891402713), -11)); // carol pays ~4008 LPTokens in fees or ~0.5% of the no-fee // LPTokens if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) @@ -4026,7 +4578,10 @@ private: BEAST_EXPECT(expectHolding(env, alice, USD(29'000))); BEAST_EXPECT(expectHolding(env, carol, USD(30'000))); // Carol pays to Alice with no fee - env(pay(carol, alice, EUR(10)), path(~EUR), sendmax(USD(10)), txflags(tfNoRippleDirect)); + env(pay(carol, alice, EUR(10)), + path(~EUR), + sendmax(USD(10)), + txflags(tfNoRippleDirect)); env.close(); // Alice has 10EUR more and Carol has 10USD less BEAST_EXPECT(expectHolding(env, alice, EUR(29'000))); @@ -4037,14 +4592,20 @@ private: ammAlice.vote(alice, 1'000); BEAST_EXPECT(ammAlice.expectTradingFee(1'000)); // Bob pays to Carol with 1% fee - env(pay(bob, carol, USD(10)), path(~USD), sendmax(EUR(15)), txflags(tfNoRippleDirect)); + env(pay(bob, carol, USD(10)), + path(~USD), + sendmax(EUR(15)), + txflags(tfNoRippleDirect)); env.close(); // Bob sends 10.1~EUR to pay 10USD - BEAST_EXPECT(expectHolding(env, bob, STAmount{EUR, UINT64_C(989'8989898989899), -13})); + BEAST_EXPECT( + expectHolding(env, bob, STAmount{EUR, UINT64_C(989'8989898989899), -13})); // Carol got 10USD BEAST_EXPECT(expectHolding(env, carol, USD(30'000))); BEAST_EXPECT(ammAlice.expectBalances( - USD(1'000), STAmount{EUR, UINT64_C(1'010'10101010101), -11}, ammAlice.tokens())); + USD(1'000), + STAmount{EUR, UINT64_C(1'010'10101010101), -11}, + ammAlice.tokens())); }, {{USD(1'000), EUR(1'010)}}, 0, @@ -4069,8 +4630,10 @@ private: env.close(); // Alice gets fewer ~4.97EUR for ~5.02USD, the difference goes // to the pool - BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(29'995'02512562814), -11})); - BEAST_EXPECT(expectHolding(env, carol, STAmount{EUR, UINT64_C(30'004'97487437186), -11})); + BEAST_EXPECT( + expectHolding(env, carol, STAmount{USD, UINT64_C(29'995'02512562814), -11})); + BEAST_EXPECT( + expectHolding(env, carol, STAmount{EUR, UINT64_C(30'004'97487437186), -11})); BEAST_EXPECT(expectOffers( env, carol, @@ -4117,9 +4680,12 @@ private: } else { - BEAST_EXPECT(expectHolding(env, bob, STAmount(EUR, UINT64_C(1989'999999999999), -12))); + BEAST_EXPECT( + expectHolding(env, bob, STAmount(EUR, UINT64_C(1989'999999999999), -12))); BEAST_EXPECT(ammAlice.expectBalances( - USD(1'000), STAmount(EUR, UINT64_C(1005'000000000001), -12), ammAlice.tokens())); + USD(1'000), + STAmount(EUR, UINT64_C(1005'000000000001), -12), + ammAlice.tokens())); } BEAST_EXPECT(expectOffers(env, carol, 0)); } @@ -4137,15 +4703,21 @@ private: BEAST_EXPECT(expectHolding(env, ed, USD(2'010))); if (!features[fixAMMv1_1]) { - BEAST_EXPECT(expectHolding(env, bob, STAmount{EUR, UINT64_C(1'989'987453007618), -12})); + BEAST_EXPECT( + expectHolding(env, bob, STAmount{EUR, UINT64_C(1'989'987453007618), -12})); BEAST_EXPECT(ammAlice.expectBalances( - USD(1'000), STAmount{EUR, UINT64_C(1'005'012546992382), -12}, ammAlice.tokens())); + USD(1'000), + STAmount{EUR, UINT64_C(1'005'012546992382), -12}, + ammAlice.tokens())); } else { - BEAST_EXPECT(expectHolding(env, bob, STAmount{EUR, UINT64_C(1'989'987453007628), -12})); + BEAST_EXPECT( + expectHolding(env, bob, STAmount{EUR, UINT64_C(1'989'987453007628), -12})); BEAST_EXPECT(ammAlice.expectBalances( - USD(1'000), STAmount{EUR, UINT64_C(1'005'012546992372), -12}, ammAlice.tokens())); + USD(1'000), + STAmount{EUR, UINT64_C(1'005'012546992372), -12}, + ammAlice.tokens())); } BEAST_EXPECT(expectOffers(env, carol, 0)); } @@ -4205,7 +4777,12 @@ private: Account const simon("simon"); Account const ben("ben"); Account const natalie("natalie"); - fund(env, gw, {bob, ed, paul, dan, chris, simon, ben, natalie}, {USD(1'500'000)}, Fund::Acct); + fund( + env, + gw, + {bob, ed, paul, dan, chris, simon, ben, natalie}, + {USD(1'500'000)}, + Fund::Acct); for (int i = 0; i < 10; ++i) { ammAlice.deposit(ben, STAmount{USD, 1, -10}); @@ -4232,18 +4809,24 @@ private: // gets everything in the pool. if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), STAmount{USD, UINT64_C(10'000'0000000013), -10}, IOUAmount{10'000'000})); + XRP(10'000), + STAmount{USD, UINT64_C(10'000'0000000013), -10}, + IOUAmount{10'000'000})); else if (features[fixAMMv1_3]) BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), STAmount{USD, UINT64_C(10'000'0000000003), -10}, IOUAmount{10'000'000})); + XRP(10'000), + STAmount{USD, UINT64_C(10'000'0000000003), -10}, + IOUAmount{10'000'000})); else - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000})); BEAST_EXPECT(expectHolding(env, ben, USD(1'500'000))); BEAST_EXPECT(expectHolding(env, simon, USD(1'500'000))); BEAST_EXPECT(expectHolding(env, chris, USD(1'500'000))); BEAST_EXPECT(expectHolding(env, dan, USD(1'500'000))); if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) - BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(30'000'00000000001), -11})); + BEAST_EXPECT(expectHolding( + env, carol, STAmount{USD, UINT64_C(30'000'00000000001), -11})); else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) BEAST_EXPECT(expectHolding(env, carol, USD(30'000))); else @@ -4251,23 +4834,28 @@ private: BEAST_EXPECT(expectHolding(env, ed, USD(1'500'000))); BEAST_EXPECT(expectHolding(env, paul, USD(1'500'000))); if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) - BEAST_EXPECT(expectHolding(env, natalie, STAmount{USD, UINT64_C(1'500'000'000000002), -9})); + BEAST_EXPECT(expectHolding( + env, natalie, STAmount{USD, UINT64_C(1'500'000'000000002), -9})); else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) - BEAST_EXPECT(expectHolding(env, natalie, STAmount{USD, UINT64_C(1'500'000'000000005), -9})); + BEAST_EXPECT(expectHolding( + env, natalie, STAmount{USD, UINT64_C(1'500'000'000000005), -9})); else BEAST_EXPECT(expectHolding(env, natalie, USD(1'500'000))); ammAlice.withdrawAll(alice); BEAST_EXPECT(!ammAlice.ammExists()); if (!features[fixAMMv1_1]) - BEAST_EXPECT(expectHolding(env, alice, STAmount{USD, UINT64_C(30'000'0000000013), -10})); + BEAST_EXPECT( + expectHolding(env, alice, STAmount{USD, UINT64_C(30'000'0000000013), -10})); else if (features[fixAMMv1_3]) - BEAST_EXPECT(expectHolding(env, alice, STAmount{USD, UINT64_C(30'000'0000000003), -10})); + BEAST_EXPECT( + expectHolding(env, alice, STAmount{USD, UINT64_C(30'000'0000000003), -10})); else BEAST_EXPECT(expectHolding(env, alice, USD(30'000))); // alice XRP balance is 30,000 initial - 50 AMMCreate fee - // 10drops fee BEAST_EXPECT( - accountBalance(env, alice) == std::to_string(29950000000 - env.current()->fees().base.drops())); + accountBalance(env, alice) == + std::to_string(29950000000 - env.current()->fees().base.drops())); }, std::nullopt, 0, @@ -4285,7 +4873,13 @@ private: Account const simon("simon"); Account const ben("ben"); Account const natalie("natalie"); - fund(env, gw, {bob, ed, paul, dan, chris, simon, ben, natalie}, XRP(2'000'000), {}, Fund::Acct); + fund( + env, + gw, + {bob, ed, paul, dan, chris, simon, ben, natalie}, + XRP(2'000'000), + {}, + Fund::Acct); for (int i = 0; i < 10; ++i) { ammAlice.deposit(ben, XRPAmount{1}); @@ -4311,7 +4905,8 @@ private: if (!features[fixAMMv1_3]) { // No round off with XRP in this test - BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000})); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000})); ammAlice.withdrawAll(alice); BEAST_EXPECT(!ammAlice.ammExists()); // 20,000 initial - (deposit+withdraw) * 10 @@ -4322,19 +4917,22 @@ private: BEAST_EXPECT(accountBalance(env, dan) == xrpBalance); // 30,000 initial - (deposit+withdraw) * 10 - BEAST_EXPECT(accountBalance(env, carol) == std::to_string(30'000'000'000 - 20 * baseFee)); + BEAST_EXPECT( + accountBalance(env, carol) == + std::to_string(30'000'000'000 - 20 * baseFee)); BEAST_EXPECT(accountBalance(env, ed) == xrpBalance); BEAST_EXPECT(accountBalance(env, paul) == xrpBalance); BEAST_EXPECT(accountBalance(env, natalie) == xrpBalance); // 30,000 initial - 50 AMMCreate fee - 10drops withdraw fee - BEAST_EXPECT(accountBalance(env, alice) == std::to_string(29'950'000'000 - baseFee)); + BEAST_EXPECT( + accountBalance(env, alice) == std::to_string(29'950'000'000 - baseFee)); } else { // post-amendment the rounding takes place to ensure // AMM invariant - BEAST_EXPECT( - ammAlice.expectBalances(XRPAmount(10'000'000'080), USD(10'000), IOUAmount{10'000'000})); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount(10'000'000'080), USD(10'000), IOUAmount{10'000'000})); ammAlice.withdrawAll(alice); BEAST_EXPECT(!ammAlice.ammExists()); auto const xrpBalance = XRP(2'000'000) - txfee(env, 20) - drops(10); @@ -4343,11 +4941,15 @@ private: BEAST_EXPECT(accountBalance(env, simon) == xrpBalanceText); BEAST_EXPECT(accountBalance(env, chris) == xrpBalanceText); BEAST_EXPECT(accountBalance(env, dan) == xrpBalanceText); - BEAST_EXPECT(accountBalance(env, carol) == std::to_string(30'000'000'000 - 20 * baseFee - 10)); + BEAST_EXPECT( + accountBalance(env, carol) == + std::to_string(30'000'000'000 - 20 * baseFee - 10)); BEAST_EXPECT(accountBalance(env, ed) == (xrpBalance + drops(2)).getText()); BEAST_EXPECT(accountBalance(env, paul) == (xrpBalance + drops(3)).getText()); BEAST_EXPECT(accountBalance(env, natalie) == (xrpBalance + drops(5)).getText()); - BEAST_EXPECT(accountBalance(env, alice) == std::to_string(29'950'000'000 - baseFee + 80)); + BEAST_EXPECT( + accountBalance(env, alice) == + std::to_string(29'950'000'000 - baseFee + 80)); } }, std::nullopt, @@ -4393,9 +4995,11 @@ private: .bidMin = 1000, }), ter(tecAMM_EMPTY)); - amm.vote(std::nullopt, 100, std::nullopt, std::nullopt, std::nullopt, ter(tecAMM_EMPTY)); + amm.vote( + std::nullopt, 100, std::nullopt, std::nullopt, std::nullopt, ter(tecAMM_EMPTY)); amm.withdraw(alice, 100, std::nullopt, std::nullopt, ter(tecAMM_EMPTY)); - amm.deposit(alice, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecAMM_EMPTY)); + amm.deposit( + alice, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecAMM_EMPTY)); env(trust(alice, STAmount{amm.lptIssue(), 10'000}), ter(tecAMM_EMPTY)); // Can deposit with tfTwoAssetIfEmpty option @@ -4473,11 +5077,15 @@ private: using namespace jtx; testAMM([&](AMM& amm, Env& env) { amm.setClose(false); - auto const info = - env.rpc("json", "account_info", std::string("{\"account\": \"" + to_string(amm.ammAccount()) + "\"}")); + auto const info = env.rpc( + "json", + "account_info", + std::string("{\"account\": \"" + to_string(amm.ammAccount()) + "\"}")); try { - BEAST_EXPECT(info[jss::result][jss::account_data][jss::AMMID].asString() == to_string(amm.ammID())); + BEAST_EXPECT( + info[jss::result][jss::account_data][jss::AMMID].asString() == + to_string(amm.ammID())); } catch (...) { @@ -4491,12 +5099,13 @@ private: for (auto const& node : affected) { if (node.isMember(sfModifiedNode.fieldName) && - node[sfModifiedNode.fieldName][sfLedgerEntryType.fieldName].asString() == "AccountRoot" && - node[sfModifiedNode.fieldName][sfFinalFields.fieldName][jss::Account].asString() == - to_string(amm.ammAccount())) + node[sfModifiedNode.fieldName][sfLedgerEntryType.fieldName].asString() == + "AccountRoot" && + node[sfModifiedNode.fieldName][sfFinalFields.fieldName][jss::Account] + .asString() == to_string(amm.ammAccount())) { - found = node[sfModifiedNode.fieldName][sfFinalFields.fieldName][jss::AMMID].asString() == - to_string(amm.ammID()); + found = node[sfModifiedNode.fieldName][sfFinalFields.fieldName][jss::AMMID] + .asString() == to_string(amm.ammID()); break; } } @@ -4566,7 +5175,10 @@ private: BEAST_EXPECT(amm->expectBalances(USD(1'000), ETH(1'000), amm->tokens())); } BEAST_EXPECT(expectHolding(env, bob, USD(2'100))); - q[i] = Quality(Amounts{ETH(2'000) - env.balance(carol, ETH), env.balance(bob, USD) - USD(2'000)}); + q[i] = Quality( + Amounts{ + ETH(2'000) - env.balance(carol, ETH), + env.balance(bob, USD) - USD(2'000)}); } // CLOB is better quality than AMM BEAST_EXPECT(q[0] > q[1]); @@ -4700,7 +5312,10 @@ private: } } BEAST_EXPECT(expectHolding(env, bob, USD(2'100))); - q[i] = Quality(Amounts{ETH(2'000) - env.balance(carol, ETH), env.balance(bob, USD) - USD(2'000)}); + q[i] = Quality( + Amounts{ + ETH(2'000) - env.balance(carol, ETH), + env.balance(bob, USD) - USD(2'000)}); } // AMM is better quality BEAST_EXPECT(q[1] > q[0]); @@ -4839,7 +5454,9 @@ private: { // Liquidity is consumed from AMM strand only BEAST_EXPECT(amm->expectBalances( - STAmount{ETH, UINT64_C(1'176'66038955758), -11}, USD(850), amm->tokens())); + STAmount{ETH, UINT64_C(1'176'66038955758), -11}, + USD(850), + amm->tokens())); } else { @@ -4867,7 +5484,9 @@ private: { // Liquidity is consumed from AMM strand only BEAST_EXPECT(amm->expectBalances( - STAmount{ETH, UINT64_C(1'176'660389557593), -12}, USD(850), amm->tokens())); + STAmount{ETH, UINT64_C(1'176'660389557593), -12}, + USD(850), + amm->tokens())); } else { @@ -4889,7 +5508,10 @@ private: }}})); } } - q[i] = Quality(Amounts{ETH(2'000) - env.balance(carol, ETH), env.balance(bob, USD) - USD(2'000)}); + q[i] = Quality( + Amounts{ + ETH(2'000) - env.balance(carol, ETH), + env.balance(bob, USD) - USD(2'000)}); } BEAST_EXPECT(q[1] > q[0]); BEAST_EXPECT(q[2] > q[0] && q[2] < q[1]); @@ -4938,7 +5560,14 @@ private: // second vote/withdraw still fail: second vote fails because // the initial trading fee is 0, consequently second withdraw fails // because the second vote fails - test(all - fixInnerObjTemplate, tefEXCEPTION, tefEXCEPTION, tefEXCEPTION, tefEXCEPTION, 0, false); + test( + all - fixInnerObjTemplate, + tefEXCEPTION, + tefEXCEPTION, + tefEXCEPTION, + tefEXCEPTION, + 0, + false); // if non-zero trading/discounted fee then vote/withdraw // don't fail whether the ledger is closed or not and // the amendment is enabled or not @@ -5108,15 +5737,21 @@ private: if (isXRP(poolIn)) { auto const takerPays = STAmount{xrpIssue(), 1}; - return Amounts{takerPays, swapAssetIn(Amounts{poolIn, poolOut}, takerPays, tfee)}; + return Amounts{ + takerPays, + swapAssetIn(Amounts{poolIn, poolOut}, takerPays, tfee)}; } else if (isXRP(poolOut)) { auto const takerGets = STAmount{xrpIssue(), 1}; - return Amounts{swapAssetOut(Amounts{poolIn, poolOut}, takerGets, tfee), takerGets}; + return Amounts{ + swapAssetOut(Amounts{poolIn, poolOut}, takerGets, tfee), + takerGets}; } - auto const takerPays = toAmount(getIssue(poolIn), Number{1, -10} * poolIn); - return Amounts{takerPays, swapAssetIn(Amounts{poolIn, poolOut}, takerPays, tfee)}; + auto const takerPays = + toAmount(getIssue(poolIn), Number{1, -10} * poolIn); + return Amounts{ + takerPays, swapAssetIn(Amounts{poolIn, poolOut}, takerPays, tfee)}; }(); BEAST_EXPECT(Quality(tinyOffer) < quality); } @@ -5583,7 +6218,8 @@ private: } else { - BEAST_EXPECT(amm.expectBalances(XRPAmount(200'000'980'005), USD(99'999.51), amm.tokens())); + BEAST_EXPECT( + amm.expectBalances(XRPAmount(200'000'980'005), USD(99'999.51), amm.tokens())); BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{XRP(1), USD(0.01)}}})); // Carol's offer crosses AMM BEAST_EXPECT(expectOffers(env, carol, 0)); @@ -5606,7 +6242,8 @@ private: env.close(); // The same result as with the blocking offer - BEAST_EXPECT(amm.expectBalances(XRPAmount(200'000'980'005), USD(99'999.51), amm.tokens())); + BEAST_EXPECT( + amm.expectBalances(XRPAmount(200'000'980'005), USD(99'999.51), amm.tokens())); // Carol's offer crosses AMM BEAST_EXPECT(expectOffers(env, carol, 0)); } @@ -5632,9 +6269,14 @@ private: else { BEAST_EXPECT(amm.expectBalances( - XRPAmount(909'090'909), STAmount{USD, UINT64_C(550'000000055), -9}, amm.tokens())); - BEAST_EXPECT( - expectOffers(env, carol, 1, {{Amounts{XRPAmount{9'090'909}, STAmount{USD, 4'99999995, -8}}}})); + XRPAmount(909'090'909), + STAmount{USD, UINT64_C(550'000000055), -9}, + amm.tokens())); + BEAST_EXPECT(expectOffers( + env, + carol, + 1, + {{Amounts{XRPAmount{9'090'909}, STAmount{USD, 4'99999995, -8}}}})); BEAST_EXPECT(expectOffers(env, bob, 1, {{Amounts{USD(1), XRPAmount(500)}}})); } } @@ -5648,9 +6290,10 @@ private: AMM amm(env, alice, XRP(1'000), USD(500)); env(offer(carol, XRP(100), USD(55))); env.close(); - BEAST_EXPECT( - amm.expectBalances(XRPAmount(909'090'909), STAmount{USD, UINT64_C(550'000000055), -9}, amm.tokens())); - BEAST_EXPECT(expectOffers(env, carol, 1, {{Amounts{XRPAmount{9'090'909}, STAmount{USD, 4'99999995, -8}}}})); + BEAST_EXPECT(amm.expectBalances( + XRPAmount(909'090'909), STAmount{USD, UINT64_C(550'000000055), -9}, amm.tokens())); + BEAST_EXPECT(expectOffers( + env, carol, 1, {{Amounts{XRPAmount{9'090'909}, STAmount{USD, 4'99999995, -8}}}})); } } @@ -5672,7 +6315,8 @@ private: BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{0})); amm.withdrawAll(carol); BEAST_EXPECT(amm.expectLPTokens(carol, IOUAmount{0})); - auto const lpToken = getAccountLines(env, gw, amm.lptIssue())[jss::lines][0u][jss::balance]; + auto const lpToken = + getAccountLines(env, gw, amm.lptIssue())[jss::lines][0u][jss::balance]; auto const lpTokenBalance = amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value]; BEAST_EXPECT(lpToken == "1414.213562373095" && lpTokenBalance == "1414.213562373"); if (!features[fixAMMv1_1]) @@ -5693,13 +6337,19 @@ private: { Env env(*this, features); auto const ABC = gw["ABC"]; - fund(env, gw, {alice, carol, bob}, XRP(1'000), {USD(1'000'000'000), ABC(1'000'000'000'000)}); + fund( + env, + gw, + {alice, carol, bob}, + XRP(1'000), + {USD(1'000'000'000), ABC(1'000'000'000'000)}); AMM amm(env, lp, ABC(2'000'000), USD(1)); amm.deposit(alice, IOUAmount{1'876123487565916, -15}); amm.deposit(carol, IOUAmount{1'000'000}); amm.withdrawAll(alice); amm.withdrawAll(carol); - auto const lpToken = getAccountLines(env, lp, amm.lptIssue())[jss::lines][0u][jss::balance]; + auto const lpToken = + getAccountLines(env, lp, amm.lptIssue())[jss::lines][0u][jss::balance]; auto const lpTokenBalance = amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value]; BEAST_EXPECT(lpToken == "1414.213562373095" && lpTokenBalance == "1414.213562373"); if (!features[fixAMMv1_1]) @@ -5795,7 +6445,8 @@ private: // allowed for clawing back from an AMM account. Please notice the // `issuer` subfield represents the account being clawed back, which // is confusing. - auto const error = features[featureSingleAssetVault] ? ter{tecPSEUDO_ACCOUNT} : ter{tecAMM_ACCOUNT}; + auto const error = + features[featureSingleAssetVault] ? ter{tecPSEUDO_ACCOUNT} : ter{tecAMM_ACCOUNT}; Issue usd(USD.issue().currency, amm.ammAccount()); auto amount = amountFromString(usd, "10"); env(claw(gw, amount), error); @@ -5834,7 +6485,8 @@ private: { Env env(*this, features); testAMMDeposit(env, [&](AMM& amm) { - amm.deposit(alice, USD(100), std::nullopt, std::nullopt, tfSingleAsset, ter(tecFROZEN)); + amm.deposit( + alice, USD(100), std::nullopt, std::nullopt, tfSingleAsset, ter(tecFROZEN)); }); } @@ -5845,7 +6497,8 @@ private: // when feature AMMClawback is enabled. Env env(*this, features); testAMMDeposit(env, [&](AMM& amm) { - amm.deposit(alice, XRP(100), std::nullopt, std::nullopt, tfSingleAsset, ter(tecFROZEN)); + amm.deposit( + alice, XRP(100), std::nullopt, std::nullopt, tfSingleAsset, ter(tecFROZEN)); }); } else @@ -5855,7 +6508,8 @@ private: // when feature AMMClawback is not enabled. Env env(*this, features); testAMMDeposit(env, [&](AMM& amm) { - amm.deposit(alice, XRP(100), std::nullopt, std::nullopt, tfSingleAsset, ter(tesSUCCESS)); + amm.deposit( + alice, XRP(100), std::nullopt, std::nullopt, tfSingleAsset, ter(tesSUCCESS)); }); } } @@ -5887,8 +6541,12 @@ private: // Equal withdraw with a limit test([&](AMM& amm) { - amm.withdraw(WithdrawArg{.account = alice, .asset1Out = EUR(0.1), .asset2Out = USD(0.1), .err = err}); - amm.withdraw(WithdrawArg{.account = alice, .asset1Out = USD(0.1), .asset2Out = EUR(0.1), .err = err}); + amm.withdraw( + WithdrawArg{ + .account = alice, .asset1Out = EUR(0.1), .asset2Out = USD(0.1), .err = err}); + amm.withdraw( + WithdrawArg{ + .account = alice, .asset1Out = USD(0.1), .asset2Out = EUR(0.1), .err = err}); }); // Single withdraw @@ -5920,7 +6578,10 @@ private: { AccountID const accountId = xrpl::pseudoAccountAddress(*env.current(), keylet.key); - env(pay(env.master.id(), accountId, XRP(1000)), seq(autofill), fee(autofill), sig(autofill)); + env(pay(env.master.id(), accountId, XRP(1000)), + seq(autofill), + fee(autofill), + sig(autofill)); } AMM ammAlice( @@ -6018,7 +6679,11 @@ private: env.close(); ammAlice.deposit(DepositArg{.account = bob, .asset1In = deposit}); - invariant(ammAlice, env, "dep1", deposit == STAmount{EUR, 1, -3} && !env.enabled(fixAMMv1_3)); + invariant( + ammAlice, + env, + "dep1", + deposit == STAmount{EUR, 1, -3} && !env.enabled(fixAMMv1_3)); }, {{GBP(30'000), EUR(30'000)}}, 0, @@ -6035,7 +6700,8 @@ private: STAmount const depositEuro{EUR, UINT64_C(10'1234567890123456), -16}; STAmount const depositGBP{GBP, UINT64_C(10'1234567890123456), -16}; - ammAlice.deposit(DepositArg{.account = bob, .asset1In = depositEuro, .asset2In = depositGBP}); + ammAlice.deposit( + DepositArg{.account = bob, .asset1In = depositEuro, .asset2In = depositGBP}); invariant(ammAlice, env, "dep2", false); }, {{GBP(30'000), EUR(30'000)}}, @@ -6054,7 +6720,9 @@ private: STAmount const depositEuro{EUR, 1, exponent}; STAmount const depositGBP{GBP, 1, exponent}; - ammAlice.deposit(DepositArg{.account = bob, .asset1In = depositEuro, .asset2In = depositGBP}); + ammAlice.deposit( + DepositArg{ + .account = bob, .asset1In = depositEuro, .asset2In = depositGBP}); invariant(ammAlice, env, "dep3", exponent != -3 && !env.enabled(fixAMMv1_3)); }, {{GBP(10'000), EUR(30'000)}}, @@ -6069,7 +6737,8 @@ private: fund(env, gw, {bob}, XRP(10'000'000), {GBP(100'000), EUR(100'000)}, Fund::Acct); env.close(); - ammAlice.deposit(DepositArg{.account = bob, .tokens = IOUAmount{10'1234567890123456, -16}}); + ammAlice.deposit( + DepositArg{.account = bob, .tokens = IOUAmount{10'1234567890123456, -16}}); invariant(ammAlice, env, "dep4", false); }, {{GBP(7'000), EUR(30'000)}}, @@ -6090,10 +6759,18 @@ private: { testAMM( [&](AMM& ammAlice, Env& env) { - fund(env, gw, {bob}, XRP(10'000'000), {GBP(100'000), EUR(1'000'000)}, Fund::Acct); + fund( + env, + gw, + {bob}, + XRP(10'000'000), + {GBP(100'000), EUR(1'000'000)}, + Fund::Acct); env.close(); - ammAlice.deposit(DepositArg{.account = bob, .tokens = tokens, .asset1In = STAmount{EUR, 1, 6}}); + ammAlice.deposit( + DepositArg{ + .account = bob, .tokens = tokens, .asset1In = STAmount{EUR, 1, 6}}); invariant(ammAlice, env, "dep5", false); }, {{GBP(7'000), EUR(30'000)}}, @@ -6150,11 +6827,12 @@ private: // tfTwoAsset withdraw mode testAMM( [&](AMM& ammAlice, Env& env) { - ammAlice.withdraw(WithdrawArg{ - .account = alice, - .asset1Out = STAmount{GBP, 3'500}, - .asset2Out = STAmount{EUR, 15'000}, - .flags = tfTwoAsset}); + ammAlice.withdraw( + WithdrawArg{ + .account = alice, + .asset1Out = STAmount{GBP, 3'500}, + .asset2Out = STAmount{EUR, 15'000}, + .flags = tfTwoAsset}); invariant(ammAlice, env, "with3", false); }, {{GBP(7'000), EUR(30'000)}}, @@ -6170,7 +6848,10 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { ammAlice.withdraw( - WithdrawArg{.account = alice, .asset1Out = STAmount{GBP, 1'234}, .flags = tfSingleAsset}); + WithdrawArg{ + .account = alice, + .asset1Out = STAmount{GBP, 1'234}, + .flags = tfSingleAsset}); invariant(ammAlice, env, "with4", false); }, {{GBP(7'000), EUR(30'000)}}, @@ -6187,7 +6868,10 @@ private: ammAlice.deposit(DepositArg{.account = bob, .asset1In = STAmount{GBP, 3'456}}); ammAlice.withdraw( - WithdrawArg{.account = bob, .asset1Out = STAmount{GBP, 1'000}, .flags = tfOneAssetWithdrawAll}); + WithdrawArg{ + .account = bob, + .asset1Out = STAmount{GBP, 1'000}, + .flags = tfOneAssetWithdrawAll}); invariant(ammAlice, env, "with5", false); }, {{GBP(7'000), EUR(30'000)}}, @@ -6198,8 +6882,12 @@ private: // tfOneAssetLPToken mode testAMM( [&](AMM& ammAlice, Env& env) { - ammAlice.withdraw(WithdrawArg{ - .account = alice, .tokens = 1'000, .asset1Out = STAmount{GBP, 100}, .flags = tfOneAssetLPToken}); + ammAlice.withdraw( + WithdrawArg{ + .account = alice, + .tokens = 1'000, + .asset1Out = STAmount{GBP, 100}, + .flags = tfOneAssetLPToken}); invariant(ammAlice, env, "with6", false); }, {{GBP(7'000), EUR(30'000)}}, @@ -6210,8 +6898,12 @@ private: // tfLimitLPToken mode testAMM( [&](AMM& ammAlice, Env& env) { - ammAlice.withdraw(WithdrawArg{ - .account = alice, .asset1Out = STAmount{GBP, 100}, .maxEP = IOUAmount{2}, .flags = tfLimitLPToken}); + ammAlice.withdraw( + WithdrawArg{ + .account = alice, + .asset1Out = STAmount{GBP, 100}, + .maxEP = IOUAmount{2}, + .flags = tfLimitLPToken}); invariant(ammAlice, env, "with7", true); }, {{GBP(7'000), EUR(30'000)}}, diff --git a/src/test/app/AccountDelete_test.cpp b/src/test/app/AccountDelete_test.cpp index 7c9a593cae..91780800e9 100644 --- a/src/test/app/AccountDelete_test.cpp +++ b/src/test/app/AccountDelete_test.cpp @@ -361,15 +361,16 @@ public: // in her directory. // Lambda to close a PayChannel. - auto payChanClose = [](jtx::Account const& account, Keylet const& payChanKeylet, PublicKey const& pk) { - Json::Value jv; - jv[jss::TransactionType] = jss::PaymentChannelClaim; - jv[jss::Flags] = tfClose; - jv[jss::Account] = account.human(); - jv[sfChannel.jsonName] = to_string(payChanKeylet.key); - jv[sfPublicKey.jsonName] = strHex(pk.slice()); - return jv; - }; + auto payChanClose = + [](jtx::Account const& account, Keylet const& payChanKeylet, PublicKey const& pk) { + Json::Value jv; + jv[jss::TransactionType] = jss::PaymentChannelClaim; + jv[jss::Flags] = tfClose; + jv[jss::Account] = account.human(); + jv[sfChannel.jsonName] = to_string(payChanKeylet.key); + jv[sfPublicKey.jsonName] = strHex(pk.slice()); + return jv; + }; env(payChanClose(alice, alicePayChanKey, alice.pk())); env.close(); @@ -732,7 +733,10 @@ public: auto const acctDelFee{drops(env.current()->fees().increment)}; // becky use credentials but they aren't accepted - env(acctdelete(becky, alice), credentials::ids({credIdx}), fee(acctDelFee), ter(tecBAD_CREDENTIALS)); + env(acctdelete(becky, alice), + credentials::ids({credIdx}), + fee(acctDelFee), + ter(tecBAD_CREDENTIALS)); env.close(); { @@ -744,7 +748,10 @@ public: } // Fail, credentials still not accepted - env(acctdelete(becky, alice), credentials::ids({credIdx}), fee(acctDelFee), ter(tecBAD_CREDENTIALS)); + env(acctdelete(becky, alice), + credentials::ids({credIdx}), + fee(acctDelFee), + ter(tecBAD_CREDENTIALS)); env.close(); // becky accept the credentials @@ -752,10 +759,16 @@ public: env.close(); // Fail, credentials doesn’t belong to carol - env(acctdelete(carol, alice), credentials::ids({credIdx}), fee(acctDelFee), ter(tecBAD_CREDENTIALS)); + env(acctdelete(carol, alice), + credentials::ids({credIdx}), + fee(acctDelFee), + ter(tecBAD_CREDENTIALS)); // Fail, no depositPreauth for provided credentials - env(acctdelete(becky, alice), credentials::ids({credIdx}), fee(acctDelFee), ter(tecNO_PERMISSION)); + env(acctdelete(becky, alice), + credentials::ids({credIdx}), + fee(acctDelFee), + ter(tecNO_PERMISSION)); env.close(); // alice create DepositPreauth Object @@ -785,7 +798,8 @@ public: // check that credential object deleted too auto const jNoCred = credentials::ledgerEntry(env, becky, carol, credType); BEAST_EXPECT( - jNoCred.isObject() && jNoCred.isMember(jss::result) && jNoCred[jss::result].isMember(jss::error) && + jNoCred.isObject() && jNoCred.isMember(jss::result) && + jNoCred[jss::result].isMember(jss::error) && jNoCred[jss::result][jss::error] == "entryNotFound"); } @@ -796,7 +810,8 @@ public: env(credentials::accept(daria, carol, credType)); env.close(); std::string const credDaria = - credentials::ledgerEntry(env, daria, carol, credType)[jss::result][jss::index].asString(); + credentials::ledgerEntry(env, daria, carol, credType)[jss::result][jss::index] + .asString(); // daria use valid credentials, which aren't required and can // delete her account @@ -807,7 +822,8 @@ public: auto const jNoCred = credentials::ledgerEntry(env, daria, carol, credType); BEAST_EXPECT( - jNoCred.isObject() && jNoCred.isMember(jss::result) && jNoCred[jss::result].isMember(jss::error) && + jNoCred.isObject() && jNoCred.isMember(jss::result) && + jNoCred[jss::result].isMember(jss::error) && jNoCred[jss::result][jss::error] == "entryNotFound"); } @@ -823,7 +839,8 @@ public: env(credentials::accept(eaton, carol, credType)); env.close(); std::string const credEaton = - credentials::ledgerEntry(env, eaton, carol, credType)[jss::result][jss::index].asString(); + credentials::ledgerEntry(env, eaton, carol, credType)[jss::result][jss::index] + .asString(); // fred make pre-authorization through authorized account env(fset(fred, asfDepositAuth)); @@ -844,7 +861,8 @@ public: auto const jNoCred = credentials::ledgerEntry(env, eaton, carol, credType); BEAST_EXPECT( - jNoCred.isObject() && jNoCred.isMember(jss::result) && jNoCred[jss::result].isMember(jss::error) && + jNoCred.isObject() && jNoCred.isMember(jss::result) && + jNoCred[jss::result].isMember(jss::error) && jNoCred[jss::result][jss::error] == "entryNotFound"); } @@ -856,7 +874,8 @@ public: env.close(); auto jv = credentials::create(john, carol, credType); - uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count() + 20; + uint32_t const t = + env.current()->header().parentCloseTime.time_since_epoch().count() + 20; jv[sfExpiration.jsonName] = t; env(jv); env.close(); @@ -869,14 +888,18 @@ public: // credentials are expired // john use credentials but can't delete account - env(acctdelete(john, alice), credentials::ids({credIdx}), fee(acctDelFee), ter(tecEXPIRED)); + env(acctdelete(john, alice), + credentials::ids({credIdx}), + fee(acctDelFee), + ter(tecEXPIRED)); env.close(); { // check that expired credential object deleted auto jv = credentials::ledgerEntry(env, john, carol, credType); BEAST_EXPECT( - jv.isObject() && jv.isMember(jss::result) && jv[jss::result].isMember(jss::error) && + jv.isObject() && jv.isMember(jss::result) && + jv[jss::result].isMember(jss::error) && jv[jss::result][jss::error] == "entryNotFound"); } } @@ -913,7 +936,10 @@ public: env(deposit::auth(alice, becky)); env.close(); - env(acctdelete(becky, alice), credentials::ids({credIdx}), fee(acctDelFee), ter(temDISABLED)); + env(acctdelete(becky, alice), + credentials::ids({credIdx}), + fee(acctDelFee), + ter(temDISABLED)); env.close(); } } @@ -957,7 +983,8 @@ public: BEAST_EXPECT(!env.le(credIdx)); auto const jv = credentials::ledgerEntry(env, becky, carol, credType); BEAST_EXPECT( - jv.isObject() && jv.isMember(jss::result) && jv[jss::result].isMember(jss::error) && + jv.isObject() && jv.isMember(jss::result) && + jv[jss::result].isMember(jss::error) && jv[jss::result][jss::error] == "entryNotFound"); } } @@ -998,7 +1025,8 @@ public: BEAST_EXPECT(!env.le(credIdx)); auto const jv = credentials::ledgerEntry(env, becky, carol, credType); BEAST_EXPECT( - jv.isObject() && jv.isMember(jss::result) && jv[jss::result].isMember(jss::error) && + jv.isObject() && jv.isMember(jss::result) && + jv[jss::result].isMember(jss::error) && jv[jss::result][jss::error] == "entryNotFound"); } } diff --git a/src/test/app/AccountTxPaging_test.cpp b/src/test/app/AccountTxPaging_test.cpp index 27078f0578..5efe307812 100644 --- a/src/test/app/AccountTxPaging_test.cpp +++ b/src/test/app/AccountTxPaging_test.cpp @@ -13,7 +13,9 @@ class AccountTxPaging_test : public beast::unit_test::suite bool checkTransaction(Json::Value const& tx, int sequence, int ledger) { - return (tx[jss::tx][jss::Sequence].asInt() == sequence && tx[jss::tx][jss::ledger_index].asInt() == ledger); + return ( + tx[jss::tx][jss::Sequence].asInt() == sequence && + tx[jss::tx][jss::ledger_index].asInt() == ledger); } auto diff --git a/src/test/app/AmendmentTable_test.cpp b/src/test/app/AmendmentTable_test.cpp index 1e4b096927..3b14c8b622 100644 --- a/src/test/app/AmendmentTable_test.cpp +++ b/src/test/app/AmendmentTable_test.cpp @@ -1,13 +1,13 @@ #include #include -#include #include #include #include #include #include +#include #include #include #include @@ -86,7 +86,8 @@ private: static std::vector makeDefaultYes(uint256 const amendment) { - std::vector result{{to_string(amendment), amendment, VoteBehavior::DefaultYes}}; + std::vector result{ + {to_string(amendment), amendment, VoteBehavior::DefaultYes}}; return result; } @@ -193,7 +194,8 @@ public: makeDefaultNo(enabled_), makeDefaultYes(vetoed_), makeObsolete(obsolete_)); - return makeTable(env.app(), majorityTime, supported, makeSection(enabled_), makeSection(vetoed_)); + return makeTable( + env.app(), majorityTime, supported, makeSection(enabled_), makeSection(vetoed_)); } void @@ -250,14 +252,16 @@ public: // Verify that unsupportedID is not in table. uint256 const unsupportedID = amendmentId(unsupported_[0]); { - Json::Value const unsupp = table->getJson(unsupportedID, true)[to_string(unsupportedID)]; + Json::Value const unsupp = + table->getJson(unsupportedID, true)[to_string(unsupportedID)]; BEAST_EXPECT(unsupp.size() == 0); } // After vetoing unsupportedID verify that it is in table. table->veto(unsupportedID); { - Json::Value const unsupp = table->getJson(unsupportedID, true)[to_string(unsupportedID)]; + Json::Value const unsupp = + table->getJson(unsupportedID, true)[to_string(unsupportedID)]; BEAST_EXPECT(unsupp[jss::vetoed].asBool()); } } @@ -388,7 +392,8 @@ public: bool const enabled = table->isEnabled(supportedID); bool const found = allEnabled.find(supportedID) != allEnabled.end(); BEAST_EXPECTS( - enabled == found, a + (enabled ? " enabled " : " disabled ") + (found ? " found" : " not found")); + enabled == found, + a + (enabled ? " enabled " : " disabled ") + (found ? " found" : " not found")); } // All supported and unVetoed amendments should be returned as desired. @@ -565,20 +570,30 @@ public: std::set enabled; majorityAmendments_t majority; - doRound(env.current()->rules(), *table, weeks{1}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{1}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(ourVotes.empty()); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(majority.empty()); uint256 const unsupportedID = amendmentId(unsupported_[0]); { - Json::Value const unsupp = table->getJson(unsupportedID, false)[to_string(unsupportedID)]; + Json::Value const unsupp = + table->getJson(unsupportedID, false)[to_string(unsupportedID)]; BEAST_EXPECT(unsupp.size() == 0); } table->veto(unsupportedID); { - Json::Value const unsupp = table->getJson(unsupportedID, false)[to_string(unsupportedID)]; + Json::Value const unsupp = + table->getJson(unsupportedID, false)[to_string(unsupportedID)]; BEAST_EXPECT(!unsupp[jss::vetoed].asBool()); } @@ -586,7 +601,15 @@ public: votes.emplace_back(testAmendment, validators.size()); - doRound(env.current()->rules(), *table, weeks{2}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{2}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(ourVotes.empty()); BEAST_EXPECT(enabled.empty()); @@ -594,7 +617,15 @@ public: // Note that the simulation code assumes others behave as we do, // so the amendment won't get enabled - doRound(env.current()->rules(), *table, weeks{5}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{5}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(ourVotes.empty()); BEAST_EXPECT(enabled.empty()); } @@ -617,20 +648,44 @@ public: std::set enabled; majorityAmendments_t majority; - doRound(env.current()->rules(), *table, weeks{1}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{1}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(ourVotes.empty()); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(majority.empty()); votes.emplace_back(testAmendment, validators.size()); - doRound(env.current()->rules(), *table, weeks{2}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{2}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(ourVotes.empty()); BEAST_EXPECT(enabled.empty()); majority[testAmendment] = hourTime(weeks{1}); - doRound(env.current()->rules(), *table, weeks{5}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{5}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(ourVotes.empty()); BEAST_EXPECT(enabled.empty()); } @@ -652,7 +707,15 @@ public: majorityAmendments_t majority; // Week 1: We should vote for all known amendments not enabled - doRound(env.current()->rules(), *table, weeks{1}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{1}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(ourVotes.size() == yes_.size()); BEAST_EXPECT(enabled.empty()); for (auto const& i : yes_) @@ -663,7 +726,15 @@ public: votes.emplace_back(amendmentId(i), validators.size()); // Week 2: We should recognize a majority - doRound(env.current()->rules(), *table, weeks{2}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{2}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(ourVotes.size() == yes_.size()); BEAST_EXPECT(enabled.empty()); @@ -671,11 +742,27 @@ public: BEAST_EXPECT(majority[amendmentId(i)] == hourTime(weeks{2})); // Week 5: We should enable the amendment - doRound(env.current()->rules(), *table, weeks{5}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{5}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(enabled.size() == yes_.size()); // Week 6: We should remove it from our votes and from having a majority - doRound(env.current()->rules(), *table, weeks{6}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{6}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(enabled.size() == yes_.size()); BEAST_EXPECT(ourVotes.empty()); for (auto const& i : yes_) @@ -690,7 +777,8 @@ public: auto const testAmendment = amendmentId("detectMajority"); test::jtx::Env env{*this, feat}; - auto table = makeTable(env, weeks(2), makeDefaultYes(testAmendment), emptySection_, emptySection_); + auto table = + makeTable(env, weeks(2), makeDefaultYes(testAmendment), emptySection_, emptySection_); auto const validators = makeValidators(16, table); @@ -705,7 +793,15 @@ public: if ((i > 0) && (i < 17)) votes.emplace_back(testAmendment, i); - doRound(env.current()->rules(), *table, weeks{i}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{i}, + validators, + votes, + ourVotes, + enabled, + majority); if (i < 13) // 13 => 13/16 = 0.8125 => > 80% { @@ -747,7 +843,8 @@ public: auto const testAmendment = amendmentId("lostMajority"); test::jtx::Env env{*this, feat}; - auto table = makeTable(env, weeks(8), makeDefaultYes(testAmendment), emptySection_, emptySection_); + auto table = + makeTable(env, weeks(8), makeDefaultYes(testAmendment), emptySection_, emptySection_); auto const validators = makeValidators(16, table); @@ -761,7 +858,15 @@ public: votes.emplace_back(testAmendment, validators.size()); - doRound(env.current()->rules(), *table, weeks{1}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{1}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(!majority.empty()); @@ -775,7 +880,15 @@ public: // Gradually reduce support votes.emplace_back(testAmendment, validators.size() - i); - doRound(env.current()->rules(), *table, weeks{i + 1}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{i + 1}, + validators, + votes, + ourVotes, + enabled, + majority); if (i < 4) // 16 - 3 = 13 => 13/16 = 0.8125 => > 80% { // 16 - 4 = 12 => 12/16 = 0.75 => < 80% @@ -802,7 +915,8 @@ public: auto const testAmendment = amendmentId("changedUNL"); test::jtx::Env env{*this, feat}; - auto table = makeTable(env, weeks(8), makeDefaultYes(testAmendment), emptySection_, emptySection_); + auto table = + makeTable(env, weeks(8), makeDefaultYes(testAmendment), emptySection_, emptySection_); std::vector> validators = makeValidators(10, table); @@ -816,7 +930,15 @@ public: votes.emplace_back(testAmendment, validators.size() - 2); - doRound(env.current()->rules(), *table, weeks{1}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{1}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(majority.empty()); @@ -832,9 +954,10 @@ public: // We need a hash_set to pass to trustChanged. hash_set trustedValidators; trustedValidators.reserve(validators.size()); - std::for_each(validators.begin(), validators.end(), [&trustedValidators](auto const& val) { - trustedValidators.insert(val.first); - }); + std::for_each( + validators.begin(), validators.end(), [&trustedValidators](auto const& val) { + trustedValidators.insert(val.first); + }); // Tell the AmendmentTable that the UNL changed. table->trustChanged(trustedValidators); @@ -850,7 +973,15 @@ public: votes.emplace_back(testAmendment, validators.size() - 2); - doRound(env.current()->rules(), *table, weeks{2}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{2}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(!majority.empty()); @@ -866,7 +997,15 @@ public: votes.emplace_back(testAmendment, validators.size() - 2); - doRound(env.current()->rules(), *table, weeks{3}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{3}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(majority.empty()); @@ -877,7 +1016,15 @@ public: votes.front().second = validators.size() - 2; - doRound(env.current()->rules(), *table, weeks{4}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{4}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(!majority.empty()); @@ -891,7 +1038,15 @@ public: votes.front().second = validators.size() - 2; - doRound(env.current()->rules(), *table, weeks{5}, validators, votes, ourVotes, enabled, majority); + doRound( + env.current()->rules(), + *table, + weeks{5}, + validators, + votes, + ourVotes, + enabled, + majority); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(majority.empty()); @@ -916,12 +1071,14 @@ public: { test::jtx::Env env{*this, feat}; auto const testAmendment = amendmentId("validatorFlapping"); - auto table = makeTable(env, weeks(1), makeDefaultYes(testAmendment), emptySection_, emptySection_); + auto table = makeTable( + env, weeks(1), makeDefaultYes(testAmendment), emptySection_, emptySection_); // Make two lists of validators, one with a missing validator, to // make it easy to simulate validator flapping. auto const allValidators = makeValidators(11, table); - decltype(allValidators) const mostValidators(allValidators.begin() + 1, allValidators.end()); + decltype(allValidators) + const mostValidators(allValidators.begin() + 1, allValidators.end()); BEAST_EXPECT(allValidators.size() == mostValidators.size() + 1); std::set enabled; @@ -963,7 +1120,8 @@ public: // no flapping. Otherwise we should only have majority // if allValidators vote -- which means there are no // missing validators. - bool const expectMajority = (delay <= 24) ? true : &thisHoursValidators == &allValidators; + bool const expectMajority = + (delay <= 24) ? true : &thisHoursValidators == &allValidators; BEAST_EXPECT(majority.empty() != expectMajority); } else @@ -993,8 +1151,9 @@ public: BEAST_EXPECT(table->needValidatedLedger(1)); std::set enabled; - std::for_each( - unsupported_.begin(), unsupported_.end(), [&enabled](auto const& s) { enabled.insert(amendmentId(s)); }); + std::for_each(unsupported_.begin(), unsupported_.end(), [&enabled](auto const& s) { + enabled.insert(amendmentId(s)); + }); majorityAmendments_t majority; table->doValidatedLedger(1, enabled, majority); @@ -1002,14 +1161,18 @@ public: BEAST_EXPECT(!table->firstUnsupportedExpected()); NetClock::duration t{1000s}; - std::for_each(unsupportedMajority_.begin(), unsupportedMajority_.end(), [&majority, &t](auto const& s) { - majority[amendmentId(s)] = NetClock::time_point{--t}; - }); + std::for_each( + unsupportedMajority_.begin(), + unsupportedMajority_.end(), + [&majority, &t](auto const& s) { + majority[amendmentId(s)] = NetClock::time_point{--t}; + }); table->doValidatedLedger(1, enabled, majority); BEAST_EXPECT(table->hasUnsupportedEnabled()); BEAST_EXPECT( - table->firstUnsupportedExpected() && *table->firstUnsupportedExpected() == NetClock::time_point{t} + w); + table->firstUnsupportedExpected() && + *table->firstUnsupportedExpected() == NetClock::time_point{t} + w); // Make sure the table knows when it needs an update. BEAST_EXPECT(!table->needValidatedLedger(256)); diff --git a/src/test/app/Batch_test.cpp b/src/test/app/Batch_test.cpp index 72f3677e3b..bd1d701381 100644 --- a/src/test/app/Batch_test.cpp +++ b/src/test/app/Batch_test.cpp @@ -2,18 +2,18 @@ #include #include -#include -#include #include -#include -#include +#include #include #include #include #include #include #include +#include +#include +#include namespace xrpl { namespace test { @@ -334,7 +334,8 @@ class Batch_test : public beast::unit_test::suite tx1[sfSigners.jsonName] = Json::arrayValue; tx1[sfSigners.jsonName][0U][sfSigner.jsonName] = Json::objectValue; tx1[sfSigners.jsonName][0U][sfSigner.jsonName][sfAccount.jsonName] = alice.human(); - tx1[sfSigners.jsonName][0U][sfSigner.jsonName][sfSigningPubKey.jsonName] = strHex(alice.pk()); + tx1[sfSigners.jsonName][0U][sfSigner.jsonName][sfSigningPubKey.jsonName] = + strHex(alice.pk()); tx1[sfSigners.jsonName][0U][sfSigner.jsonName][sfTxnSignature.jsonName] = "DEADBEEF"; env(batch::outer(alice, seq, batchFee, tfAllOrNothing), batch::inner(tx1, seq + 1), @@ -553,8 +554,10 @@ class Batch_test : public beast::unit_test::suite Serializer msg; serializeBatch(msg, tfAllOrNothing, jt.stx->getBatchTransactionIDs()); auto const sig = xrpl::sign(bob.pk(), bob.sk(), msg.slice()); - jt.jv[sfBatchSigners.jsonName][0u][sfBatchSigner.jsonName][sfAccount.jsonName] = bob.human(); - jt.jv[sfBatchSigners.jsonName][0u][sfBatchSigner.jsonName][sfSigningPubKey.jsonName] = strHex(alice.pk()); + jt.jv[sfBatchSigners.jsonName][0u][sfBatchSigner.jsonName][sfAccount.jsonName] = + bob.human(); + jt.jv[sfBatchSigners.jsonName][0u][sfBatchSigner.jsonName][sfSigningPubKey.jsonName] = + strHex(alice.pk()); jt.jv[sfBatchSigners.jsonName][0u][sfBatchSigner.jsonName][sfTxnSignature.jsonName] = strHex(Slice{sig.data(), sig.size()}); @@ -1754,9 +1757,12 @@ class Batch_test : public beast::unit_test::suite env, tesSUCCESS, batch::outer(alice, seq, batchFee, tfOnlyOne), - batch::inner(offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 1), - batch::inner(offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 2), - batch::inner(offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 3), + batch::inner( + offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 1), + batch::inner( + offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 2), + batch::inner( + offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 3), batch::inner(pay(alice, bob, XRP(100)), seq + 4), batch::inner(pay(alice, carol, XRP(100)), seq + 5), batch::inner(pay(alice, dave, XRP(100)), seq + 6)); @@ -1975,7 +1981,8 @@ class Batch_test : public beast::unit_test::suite batch::outer(alice, seq, batchFee, tfUntilFailure), batch::inner(pay(alice, bob, XRP(100)), seq + 1), batch::inner(pay(alice, carol, XRP(100)), seq + 2), - batch::inner(offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 3), + batch::inner( + offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 3), batch::inner(pay(alice, dave, XRP(100)), seq + 4)); env.close(); @@ -2163,7 +2170,8 @@ class Batch_test : public beast::unit_test::suite batch::outer(alice, seq, batchFee, tfIndependent), batch::inner(pay(alice, bob, XRP(100)), seq + 1), batch::inner(pay(alice, carol, XRP(100)), seq + 2), - batch::inner(offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 3)); + batch::inner( + offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 3)); env.close(); std::vector testCases = { @@ -2213,12 +2221,14 @@ class Batch_test : public beast::unit_test::suite std::optional expectedEnabled = std::nullopt, std::optional expectedDisabled = std::nullopt, bool expectInvalidFlag = false) { - testcase << testName << caseName << (expectInvalidFlag ? " - Expected to reach tx engine!" : ""); + testcase << testName << caseName + << (expectInvalidFlag ? " - Expected to reach tx engine!" : ""); auto const jrr = env.rpc("submit", strHex(slice))[jss::result]; - auto const expected = withBatch ? expectedEnabled.value_or( - "fails local checks: Malformed: Invalid inner batch " - "transaction.") - : expectedDisabled.value_or("fails local checks: Empty SigningPubKey."); + auto const expected = withBatch + ? expectedEnabled.value_or( + "fails local checks: Malformed: Invalid inner batch " + "transaction.") + : expectedDisabled.value_or("fails local checks: Empty SigningPubKey."); if (expectInvalidFlag) { expect( @@ -2265,7 +2275,11 @@ class Batch_test : public beast::unit_test::suite Serializer s; parsed.object->add(s); submitAndValidate( - "SigningPubKey set", s.slice(), __LINE__, std::nullopt, "fails local checks: Invalid signature."); + "SigningPubKey set", + s.slice(), + __LINE__, + std::nullopt, + "fails local checks: Invalid signature."); } // Invalid RPC Submission: Signers @@ -2280,7 +2294,11 @@ class Batch_test : public beast::unit_test::suite Serializer s; parsed.object->add(s); submitAndValidate( - "Signers set", s.slice(), __LINE__, std::nullopt, "fails local checks: Invalid Signers array size."); + "Signers set", + s.slice(), + __LINE__, + std::nullopt, + "fails local checks: Invalid Signers array size."); } { @@ -2291,7 +2309,8 @@ class Batch_test : public beast::unit_test::suite STParsedJSONObject parsed("test", jt.jv); Serializer s; parsed.object->add(s); - submitAndValidate("Fully signed", s.slice(), __LINE__, std::nullopt, std::nullopt, !withBatch); + submitAndValidate( + "Fully signed", s.slice(), __LINE__, std::nullopt, std::nullopt, !withBatch); } // Invalid RPC Submission: tfInnerBatchTxn @@ -2581,14 +2600,15 @@ class Batch_test : public beast::unit_test::suite { testcase("loan"); - bool const lendingBatchEnabled = - !std::any_of(Batch::disabledTxTypes.begin(), Batch::disabledTxTypes.end(), [](auto const& disabled) { + bool const lendingBatchEnabled = !std::any_of( + Batch::disabledTxTypes.begin(), Batch::disabledTxTypes.end(), [](auto const& disabled) { return disabled == ttLOAN_BROKER_SET; }); using namespace test::jtx; - test::jtx::Env env{*this, features | featureSingleAssetVault | featureLendingProtocol | featureMPTokensV1}; + test::jtx::Env env{ + *this, features | featureSingleAssetVault | featureLendingProtocol | featureMPTokensV1}; Account const issuer{"issuer"}; // For simplicity, lender will be the sole actor for the vault & @@ -2656,7 +2676,9 @@ class Batch_test : public beast::unit_test::suite fee(none), seq(none)), lenderSeq + 1), - batch::inner(pay(lender, loanKeylet.key, STAmount{asset, asset(500).value()}), lenderSeq + 2)); + batch::inner( + pay(lender, loanKeylet.key, STAmount{asset, asset(500).value()}), + lenderSeq + 2)); } { auto const [txIDs, batchID] = submitBatch( @@ -2671,7 +2693,9 @@ class Batch_test : public beast::unit_test::suite fee(none), seq(none)), lenderSeq + 1), - batch::inner(pay(lender, loanKeylet.key, STAmount{asset, asset(500).value()}), lenderSeq + 2)); + batch::inner( + pay(lender, loanKeylet.key, STAmount{asset, asset(500).value()}), + lenderSeq + 2)); } { auto const [txIDs, batchID] = submitBatch( @@ -2687,7 +2711,9 @@ class Batch_test : public beast::unit_test::suite fee(none), seq(none)), lenderSeq + 1), - batch::inner(pay(lender, loanKeylet.key, STAmount{asset, asset(500).value()}), lenderSeq + 2)); + batch::inner( + pay(lender, loanKeylet.key, STAmount{asset, asset(500).value()}), + lenderSeq + 2)); } { // LoanSet normally charges at least 2x base fee, but since the @@ -3827,7 +3853,8 @@ class Batch_test : public beast::unit_test::suite jt.stx->add(s); std::string reason; auto transaction = std::make_shared(jt.stx, reason, env.app()); - env.app().getOPs().processTransaction(transaction, false, true, NetworkOPs::FailHard::yes); + env.app().getOPs().processTransaction( + transaction, false, true, NetworkOPs::FailHard::yes); return transaction->getID(); }; diff --git a/src/test/app/Check_test.cpp b/src/test/app/Check_test.cpp index 42c600c22b..05c0870329 100644 --- a/src/test/app/Check_test.cpp +++ b/src/test/app/Check_test.cpp @@ -14,7 +14,8 @@ private: std::uint32_t const expiry_; public: - explicit expiration(NetClock::time_point const& expiry) : expiry_{expiry.time_since_epoch().count()} + explicit expiration(NetClock::time_point const& expiry) + : expiry_{expiry.time_since_epoch().count()} { } @@ -257,7 +258,8 @@ class Check_test : public beast::unit_test::suite * Attempt to create two checks from `from` to `to` and * require they both result in error/success code `expected` */ - auto writeTwoChecksDI = [&env, &USD, this](Account const& from, Account const& to, TER expected) { + auto writeTwoChecksDI = [&env, &USD, this]( + Account const& from, Account const& to, TER expected) { std::uint32_t const fromOwnerCount{ownerCount(env, from)}; std::uint32_t const toOwnerCount{ownerCount(env, to)}; @@ -370,7 +372,9 @@ class Check_test : public beast::unit_test::suite } // Bad expiration. - env(check::create(alice, bob, USD(50)), expiration(NetClock::time_point{}), ter(temBAD_EXPIRATION)); + env(check::create(alice, bob, USD(50)), + expiration(NetClock::time_point{}), + ter(temBAD_EXPIRATION)); env.close(); // Destination does not exist. @@ -479,7 +483,9 @@ class Check_test : public beast::unit_test::suite env.fund(env.current()->fees().accountReserve(1) - drops(1), cheri); env.close(); - env(check::create(cheri, bob, USD(50)), fee(drops(env.current()->fees().base)), ter(tecINSUFFICIENT_RESERVE)); + env(check::create(cheri, bob, USD(50)), + fee(drops(env.current()->fees().base)), + ter(tecINSUFFICIENT_RESERVE)); env.close(); env(pay(bob, cheri, drops(env.current()->fees().base + 1))); @@ -545,7 +551,8 @@ class Check_test : public beast::unit_test::suite // bob tries to cash for more than the check amount. env(check::cash(bob, chkId, checkAmount + drops(1)), ter(tecPATH_PARTIAL)); env.close(); - env(check::cash(bob, chkId, check::DeliverMin(checkAmount + drops(1))), ter(tecPATH_PARTIAL)); + env(check::cash(bob, chkId, check::DeliverMin(checkAmount + drops(1))), + ter(tecPATH_PARTIAL)); env.close(); // bob cashes exactly the check amount. This is successful @@ -1049,53 +1056,59 @@ class Check_test : public beast::unit_test::suite // There are two test lambdas: one for a Payment and one for a Check. // This shows whether a Payment and a Check behave the same. - auto testNonIssuerQPay = - [&env, &alice, &bob, &USD]( - Account const& truster, IOU const& iou, auto const& inOrOut, double pct, double amount) { - // Capture bob's and alice's balances so we can test at the end. - STAmount const aliceStart{env.balance(alice, USD.issue()).value()}; - STAmount const bobStart{env.balance(bob, USD.issue()).value()}; + auto testNonIssuerQPay = [&env, &alice, &bob, &USD]( + Account const& truster, + IOU const& iou, + auto const& inOrOut, + double pct, + double amount) { + // Capture bob's and alice's balances so we can test at the end. + STAmount const aliceStart{env.balance(alice, USD.issue()).value()}; + STAmount const bobStart{env.balance(bob, USD.issue()).value()}; - // Set the modified quality. - env(trust(truster, iou(1000)), inOrOut(pct)); - env.close(); + // Set the modified quality. + env(trust(truster, iou(1000)), inOrOut(pct)); + env.close(); - env(pay(alice, bob, USD(amount)), sendmax(USD(10))); - env.close(); - env.require(balance(alice, aliceStart - USD(10))); - env.require(balance(bob, bobStart + USD(10))); + env(pay(alice, bob, USD(amount)), sendmax(USD(10))); + env.close(); + env.require(balance(alice, aliceStart - USD(10))); + env.require(balance(bob, bobStart + USD(10))); - // Return the quality to the unmodified state so it doesn't - // interfere with upcoming tests. - env(trust(truster, iou(1000)), inOrOut(0)); - env.close(); - }; + // Return the quality to the unmodified state so it doesn't + // interfere with upcoming tests. + env(trust(truster, iou(1000)), inOrOut(0)); + env.close(); + }; - auto testNonIssuerQCheck = - [&env, &alice, &bob, &USD]( - Account const& truster, IOU const& iou, auto const& inOrOut, double pct, double amount) { - // Capture bob's and alice's balances so we can test at the end. - STAmount const aliceStart{env.balance(alice, USD.issue()).value()}; - STAmount const bobStart{env.balance(bob, USD.issue()).value()}; + auto testNonIssuerQCheck = [&env, &alice, &bob, &USD]( + Account const& truster, + IOU const& iou, + auto const& inOrOut, + double pct, + double amount) { + // Capture bob's and alice's balances so we can test at the end. + STAmount const aliceStart{env.balance(alice, USD.issue()).value()}; + STAmount const bobStart{env.balance(bob, USD.issue()).value()}; - // Set the modified quality. - env(trust(truster, iou(1000)), inOrOut(pct)); - env.close(); + // Set the modified quality. + env(trust(truster, iou(1000)), inOrOut(pct)); + env.close(); - uint256 const chkId = getCheckIndex(alice, env.seq(alice)); - env(check::create(alice, bob, USD(10))); - env.close(); + uint256 const chkId = getCheckIndex(alice, env.seq(alice)); + env(check::create(alice, bob, USD(10))); + env.close(); - env(check::cash(bob, chkId, USD(amount))); - env.close(); - env.require(balance(alice, aliceStart - USD(10))); - env.require(balance(bob, bobStart + USD(10))); + env(check::cash(bob, chkId, USD(amount))); + env.close(); + env.require(balance(alice, aliceStart - USD(10))); + env.require(balance(bob, bobStart + USD(10))); - // Return the quality to the unmodified state so it doesn't - // interfere with upcoming tests. - env(trust(truster, iou(1000)), inOrOut(0)); - env.close(); - }; + // Return the quality to the unmodified state so it doesn't + // interfere with upcoming tests. + env(trust(truster, iou(1000)), inOrOut(0)); + env.close(); + }; // pct amount testNonIssuerQPay(alice, gw["USD"], qIn, 50, 10); @@ -1292,13 +1305,16 @@ class Check_test : public beast::unit_test::suite env.close(); // Same set of failing cases for both IOU and XRP check cashing. - auto failingCases = [&env, &gw, &alice, &bob](uint256 const& chkId, STAmount const& amount) { + auto failingCases = [&env, &gw, &alice, &bob]( + uint256 const& chkId, STAmount const& amount) { // Bad fee. env(check::cash(bob, chkId, amount), fee(drops(-10)), ter(temBAD_FEE)); env.close(); // Bad flags. - env(check::cash(bob, chkId, amount), txflags(tfImmediateOrCancel), ter(temINVALID_FLAG)); + env(check::cash(bob, chkId, amount), + txflags(tfImmediateOrCancel), + ter(temINVALID_FLAG)); env.close(); // Missing both Amount and DeliverMin. @@ -1467,7 +1483,8 @@ class Check_test : public beast::unit_test::suite env.close(); env(check::cash(bob, chkIdNoDest1, USD(1)), ter(tecDST_TAG_NEEDED)); env.close(); - env(check::cash(bob, chkIdNoDest1, check::DeliverMin(USD(0.5))), ter(tecDST_TAG_NEEDED)); + env(check::cash(bob, chkIdNoDest1, check::DeliverMin(USD(0.5))), + ter(tecDST_TAG_NEEDED)); env.close(); // bob can cash a check with a destination tag. @@ -1660,7 +1677,9 @@ class Check_test : public beast::unit_test::suite env.close(); // Bad fee. - env(check::cancel(bob, getCheckIndex(alice, env.seq(alice))), fee(drops(-10)), ter(temBAD_FEE)); + env(check::cancel(bob, getCheckIndex(alice, env.seq(alice))), + fee(drops(-10)), + ter(temBAD_FEE)); env.close(); // Bad flags. @@ -1828,7 +1847,8 @@ class Check_test : public beast::unit_test::suite void verifyOwners(std::uint32_t line) const { - suite.expect(ownerCount(env, acct) == owners, "Owner count mismatch", __FILE__, line); + suite.expect( + ownerCount(env, acct) == owners, "Owner count mismatch", __FILE__, line); } // Operators to make using the class more convenient. @@ -1913,7 +1933,10 @@ class Check_test : public beast::unit_test::suite // between the same two accounts but with two different currencies. // The lambda expects the two trust lines to be largely similar. auto cmpTrustLines = [this, &env]( - Account const& acct1, Account const& acct2, IOU const& offerIou, IOU const& checkIou) { + Account const& acct1, + Account const& acct2, + IOU const& offerIou, + IOU const& checkIou) { auto const offerLine = env.le(keylet::line(acct1, acct2, offerIou.currency)); auto const checkLine = env.le(keylet::line(acct1, acct2, checkIou.currency)); if (offerLine == nullptr || checkLine == nullptr) @@ -1949,7 +1972,8 @@ class Check_test : public beast::unit_test::suite // Lambda that compares the contents of optional fields. auto cmpOptField = [this, offerLine, checkLine](auto const& sfield) { // Expect both fields to either be present or absent. - if (!BEAST_EXPECT(offerLine->isFieldPresent(sfield) == checkLine->isFieldPresent(sfield))) + if (!BEAST_EXPECT( + offerLine->isFieldPresent(sfield) == checkLine->isFieldPresent(sfield))) return; // If both fields are absent then there's nothing diff --git a/src/test/app/Credentials_test.cpp b/src/test/app/Credentials_test.cpp index 31c867c24d..3c3d8b6df8 100644 --- a/src/test/app/Credentials_test.cpp +++ b/src/test/app/Credentials_test.cpp @@ -56,12 +56,15 @@ struct Credentials_test : public beast::unit_test::suite BEAST_EXPECT(checkVL(sleCred, sfURI, uri)); auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle.isObject() && jle.isMember(jss::result) && + !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && + jle[jss::result][jss::node].isMember("LedgerEntryType") && jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && jle[jss::result][jss::node][jss::Issuer] == issuer.human() && jle[jss::result][jss::node][jss::Subject] == subject.human() && - jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType))); + jle[jss::result][jss::node]["CredentialType"] == + strHex(std::string_view(credType))); } env(credentials::accept(subject, issuer, credType)); @@ -93,7 +96,8 @@ struct Credentials_test : public beast::unit_test::suite // check no credential exists anymore auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && + jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } } @@ -114,18 +118,22 @@ struct Credentials_test : public beast::unit_test::suite BEAST_EXPECT(sleCred->getAccountID(sfSubject) == issuer.id()); BEAST_EXPECT(sleCred->getAccountID(sfIssuer) == issuer.id()); BEAST_EXPECT((sleCred->getFieldU32(sfFlags) & lsfAccepted)); - BEAST_EXPECT(sleCred->getFieldU64(sfIssuerNode) == sleCred->getFieldU64(sfSubjectNode)); + BEAST_EXPECT( + sleCred->getFieldU64(sfIssuerNode) == sleCred->getFieldU64(sfSubjectNode)); BEAST_EXPECT(ownerCount(env, issuer) == 1); BEAST_EXPECT(checkVL(sleCred, sfCredentialType, credType)); BEAST_EXPECT(checkVL(sleCred, sfURI, uri)); auto const jle = credentials::ledgerEntry(env, issuer, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle.isObject() && jle.isMember(jss::result) && + !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && + jle[jss::result][jss::node].isMember("LedgerEntryType") && jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && jle[jss::result][jss::node][jss::Issuer] == issuer.human() && jle[jss::result][jss::node][jss::Subject] == issuer.human() && - jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType))); + jle[jss::result][jss::node]["CredentialType"] == + strHex(std::string_view(credType))); } env(credentials::deleteCred(issuer, issuer, issuer, credType)); @@ -137,7 +145,8 @@ struct Credentials_test : public beast::unit_test::suite // check no credential exists anymore auto const jle = credentials::ledgerEntry(env, issuer, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && + jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } } @@ -185,7 +194,8 @@ struct Credentials_test : public beast::unit_test::suite // check no credential exists anymore auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && + jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } @@ -221,7 +231,8 @@ struct Credentials_test : public beast::unit_test::suite // check no credential exists anymore auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && + jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } @@ -255,7 +266,8 @@ struct Credentials_test : public beast::unit_test::suite // check no credential exists anymore auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && + jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } @@ -291,7 +303,8 @@ struct Credentials_test : public beast::unit_test::suite // check no credential exists anymore auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && + jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } @@ -327,7 +340,8 @@ struct Credentials_test : public beast::unit_test::suite // check no credential exists anymore auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && + jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } } @@ -348,7 +362,8 @@ struct Credentials_test : public beast::unit_test::suite BEAST_EXPECT(!ownerCount(env, issuer)); auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && + jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } } @@ -367,7 +382,8 @@ struct Credentials_test : public beast::unit_test::suite BEAST_EXPECT(!ownerCount(env, issuer)); auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && + jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } } @@ -440,19 +456,24 @@ struct Credentials_test : public beast::unit_test::suite "WULE" "fv28o37gfwEFB3872TFO8GSDSDVD"; static_assert(longURI.size() > maxCredentialURILength); - env(credentials::create(subject, issuer, credType), credentials::uri(longURI), ter(temMALFORMED)); + env(credentials::create(subject, issuer, credType), + credentials::uri(longURI), + ter(temMALFORMED)); } { testcase("Credentials fail, URI empty."); - env(credentials::create(subject, issuer, credType), credentials::uri(""), ter(temMALFORMED)); + env(credentials::create(subject, issuer, credType), + credentials::uri(""), + ter(temMALFORMED)); } { testcase("Credentials fail, expiration in the past."); auto jv = credentials::create(subject, issuer, credType); // current time in ripple epoch - 1s - uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count() - 1; + uint32_t const t = + env.current()->header().parentCloseTime.time_since_epoch().count() - 1; jv[sfExpiration.jsonName] = t; env(jv, ter(tecEXPIRED)); } @@ -476,12 +497,15 @@ struct Credentials_test : public beast::unit_test::suite // check credential still present auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle.isObject() && jle.isMember(jss::result) && + !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && + jle[jss::result][jss::node].isMember("LedgerEntryType") && jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && jle[jss::result][jss::node][jss::Issuer] == issuer.human() && jle[jss::result][jss::node][jss::Subject] == subject.human() && - jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType))); + jle[jss::result][jss::node]["CredentialType"] == + strHex(std::string_view(credType))); } { @@ -492,7 +516,10 @@ struct Credentials_test : public beast::unit_test::suite // Everything below can only be tested on open ledger. auto const res1 = directory::bumpLastPage( - env, directory::maximumPageIndex(env), keylet::ownerDir(issuer.id()), directory::adjustOwnerNode); + env, + directory::maximumPageIndex(env), + keylet::ownerDir(issuer.id()), + directory::adjustOwnerNode); BEAST_EXPECT(res1); auto const jv = credentials::create(issuer, subject, credType); @@ -503,7 +530,10 @@ struct Credentials_test : public beast::unit_test::suite // Fill subject directory env(ticket::create(subject, 63)); auto const res2 = directory::bumpLastPage( - env, directory::maximumPageIndex(env), keylet::ownerDir(subject.id()), directory::adjustOwnerNode); + env, + directory::maximumPageIndex(env), + keylet::ownerDir(subject.id()), + directory::adjustOwnerNode); BEAST_EXPECT(res2); env(jv, ter(tecDIR_FULL)); @@ -597,12 +627,15 @@ struct Credentials_test : public beast::unit_test::suite // check credential still present auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle.isObject() && jle.isMember(jss::result) && + !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && + jle[jss::result][jss::node].isMember("LedgerEntryType") && jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && jle[jss::result][jss::node][jss::Issuer] == issuer.human() && jle[jss::result][jss::node][jss::Subject] == subject.human() && - jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType))); + jle[jss::result][jss::node]["CredentialType"] == + strHex(std::string_view(credType))); } } @@ -631,12 +664,15 @@ struct Credentials_test : public beast::unit_test::suite // check credential still present auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle.isObject() && jle.isMember(jss::result) && + !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && + jle[jss::result][jss::node].isMember("LedgerEntryType") && jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && jle[jss::result][jss::node][jss::Issuer] == issuer.human() && jle[jss::result][jss::node][jss::Subject] == subject.human() && - jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType))); + jle[jss::result][jss::node]["CredentialType"] == + strHex(std::string_view(credType))); } { @@ -644,7 +680,8 @@ struct Credentials_test : public beast::unit_test::suite testcase("CredentialsAccept fail, expired credentials."); auto jv = credentials::create(subject, issuer, credType2); - uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count(); + uint32_t const t = + env.current()->header().parentCloseTime.time_since_epoch().count(); jv[sfExpiration.jsonName] = t; env(jv); env.close(); @@ -657,7 +694,8 @@ struct Credentials_test : public beast::unit_test::suite auto const jDelCred = credentials::ledgerEntry(env, subject, issuer, credType2); BEAST_EXPECT( jDelCred.isObject() && jDelCred.isMember(jss::result) && - jDelCred[jss::result].isMember(jss::error) && jDelCred[jss::result][jss::error] == "entryNotFound"); + jDelCred[jss::result].isMember(jss::error) && + jDelCred[jss::result][jss::error] == "entryNotFound"); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, subject) == 1); @@ -693,7 +731,8 @@ struct Credentials_test : public beast::unit_test::suite auto const jDelCred = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( jDelCred.isObject() && jDelCred.isMember(jss::result) && - jDelCred[jss::result].isMember(jss::error) && jDelCred[jss::result][jss::error] == "entryNotFound"); + jDelCred[jss::result].isMember(jss::error) && + jDelCred[jss::result][jss::error] == "entryNotFound"); } } } @@ -750,18 +789,22 @@ struct Credentials_test : public beast::unit_test::suite env.close(); // Other account can't delete credentials without expiration - env(credentials::deleteCred(other, subject, issuer, credType2), ter(tecNO_PERMISSION)); + env(credentials::deleteCred(other, subject, issuer, credType2), + ter(tecNO_PERMISSION)); env.close(); // check credential still present auto const jle = credentials::ledgerEntry(env, subject, issuer, credType2); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle.isObject() && jle.isMember(jss::result) && + !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && + jle[jss::result][jss::node].isMember("LedgerEntryType") && jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && jle[jss::result][jss::node][jss::Issuer] == issuer.human() && jle[jss::result][jss::node][jss::Subject] == subject.human() && - jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType2))); + jle[jss::result][jss::node]["CredentialType"] == + strHex(std::string_view(credType2))); } { @@ -769,24 +812,29 @@ struct Credentials_test : public beast::unit_test::suite auto jv = credentials::create(subject, issuer, credType); // current time in ripple epoch + 1000s - uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count() + 1000; + uint32_t const t = + env.current()->header().parentCloseTime.time_since_epoch().count() + 1000; jv[sfExpiration.jsonName] = t; env(jv); env.close(); // Other account can't delete credentials that not expired - env(credentials::deleteCred(other, subject, issuer, credType), ter(tecNO_PERMISSION)); + env(credentials::deleteCred(other, subject, issuer, credType), + ter(tecNO_PERMISSION)); env.close(); // check credential still present auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle.isObject() && jle.isMember(jss::result) && + !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && + jle[jss::result][jss::node].isMember("LedgerEntryType") && jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && jle[jss::result][jss::node][jss::Issuer] == issuer.human() && jle[jss::result][jss::node][jss::Subject] == subject.human() && - jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType))); + jle[jss::result][jss::node]["CredentialType"] == + strHex(std::string_view(credType))); } { @@ -810,7 +858,8 @@ struct Credentials_test : public beast::unit_test::suite { testcase("deleteSLE fail, bad SLE."); - auto view = std::make_shared(env.current().get(), ApplyFlags::tapNONE); + auto view = + std::make_shared(env.current().get(), ApplyFlags::tapNONE); auto ter = xrpl::credentials::deleteSLE(*view, {}, env.journal); BEAST_EXPECT(ter == tecNO_ENTRY); } @@ -945,9 +994,15 @@ struct Credentials_test : public beast::unit_test::suite { ter const expected(enabled ? TER(temINVALID_FLAG) : TER(tesSUCCESS)); - env(credentials::create(subject, issuer, credType), txflags(tfTransferable), expected); - env(credentials::accept(subject, issuer, credType), txflags(tfSellNFToken), expected); - env(credentials::deleteCred(subject, subject, issuer, credType), txflags(tfPassive), expected); + env(credentials::create(subject, issuer, credType), + txflags(tfTransferable), + expected); + env(credentials::accept(subject, issuer, credType), + txflags(tfSellNFToken), + expected); + env(credentials::deleteCred(subject, subject, issuer, credType), + txflags(tfPassive), + expected); } } } diff --git a/src/test/app/DNS_test.cpp b/src/test/app/DNS_test.cpp index 0d41c0f419..f478bc89ee 100644 --- a/src/test/app/DNS_test.cpp +++ b/src/test/app/DNS_test.cpp @@ -31,13 +31,14 @@ public: void makeRequest(endpoint_type const& lastEndpoint, bool lastStatus) { - auto onFetch = - [&](error_code const& errorCode, endpoint_type const& endpoint, xrpl::detail::response_type&& resp) { - BEAST_EXPECT(!errorCode); - lastEndpoint_ = endpoint; - resolved_[endpoint.address().to_string()]++; - cv_.notify_all(); - }; + auto onFetch = [&](error_code const& errorCode, + endpoint_type const& endpoint, + xrpl::detail::response_type&& resp) { + BEAST_EXPECT(!errorCode); + lastEndpoint_ = endpoint; + resolved_[endpoint.address().to_string()]++; + cv_.notify_all(); + }; auto sp = std::make_shared( pUrl_.domain, diff --git a/src/test/app/Delegate_test.cpp b/src/test/app/Delegate_test.cpp index 2207c83148..31a394eeeb 100644 --- a/src/test/app/Delegate_test.cpp +++ b/src/test/app/Delegate_test.cpp @@ -51,8 +51,8 @@ class Delegate_test : public beast::unit_test::suite auto const entry = delegate::entry(env, gw, alice); BEAST_EXPECT(entry[jss::result][jss::error] == "entryNotFound"); - auto const permissions = - std::vector{"Payment", "EscrowCreate", "EscrowFinish", "TrustlineAuthorize", "CheckCreate"}; + auto const permissions = std::vector{ + "Payment", "EscrowCreate", "EscrowFinish", "TrustlineAuthorize", "CheckCreate"}; env(delegate::set(gw, alice, permissions)); env.close(); @@ -62,7 +62,8 @@ class Delegate_test : public beast::unit_test::suite std::vector const& permissions, Account const& account, Account const& authorize) { - BEAST_EXPECT(!jle[jss::result].isMember(jss::error) && jle[jss::result].isMember(jss::node)); + BEAST_EXPECT( + !jle[jss::result].isMember(jss::error) && jle[jss::result].isMember(jss::node)); BEAST_EXPECT(jle[jss::result][jss::node]["LedgerEntryType"] == jss::Delegate); BEAST_EXPECT(jle[jss::result][jss::node][jss::Account] == account.human()); BEAST_EXPECT(jle[jss::result][jss::node][sfAuthorize.jsonName] == authorize.human()); @@ -71,7 +72,9 @@ class Delegate_test : public beast::unit_test::suite unsigned i = 0; for (auto const& permission : permissions) { - BEAST_EXPECT(jPermissions[i][sfPermission.jsonName][sfPermissionValue.jsonName] == permission); + BEAST_EXPECT( + jPermissions[i][sfPermission.jsonName][sfPermissionValue.jsonName] == + permission); i++; } }; @@ -80,7 +83,8 @@ class Delegate_test : public beast::unit_test::suite comparePermissions(delegate::entry(env, gw, alice), permissions, gw, alice); // gw updates permission - auto const newPermissions = std::vector{"Payment", "AMMCreate", "AMMDeposit", "AMMWithdraw"}; + auto const newPermissions = + std::vector{"Payment", "AMMCreate", "AMMDeposit", "AMMWithdraw"}; env(delegate::set(gw, alice, newPermissions)); env.close(); @@ -266,7 +270,10 @@ class Delegate_test : public beast::unit_test::suite auto bobBalance = env.balance(bob); auto carolBalance = env.balance(carol); - env(pay(alice, carol, XRP(100)), fee(XRP(2000)), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); + env(pay(alice, carol, XRP(100)), + fee(XRP(2000)), + delegate::as(bob), + ter(terNO_DELEGATE_PERMISSION)); env.close(); BEAST_EXPECT(env.balance(alice) == aliceBalance); BEAST_EXPECT(env.balance(bob) == bobBalance); @@ -297,7 +304,10 @@ class Delegate_test : public beast::unit_test::suite auto bobBalance = env.balance(bob); auto carolBalance = env.balance(carol); - env(pay(alice, carol, XRP(100)), fee(XRP(2000)), delegate::as(bob), ter(terINSUF_FEE_B)); + env(pay(alice, carol, XRP(100)), + fee(XRP(2000)), + delegate::as(bob), + ter(terINSUF_FEE_B)); env.close(); BEAST_EXPECT(env.balance(alice) == aliceBalance); BEAST_EXPECT(env.balance(bob) == bobBalance); @@ -312,7 +322,10 @@ class Delegate_test : public beast::unit_test::suite auto carolBalance = env.balance(carol); auto const feeAmt = XRP(10); - env(pay(alice, carol, XRP(20000)), fee(feeAmt), delegate::as(bob), ter(tecUNFUNDED_PAYMENT)); + env(pay(alice, carol, XRP(20000)), + fee(feeAmt), + delegate::as(bob), + ter(tecUNFUNDED_PAYMENT)); env.close(); BEAST_EXPECT(env.balance(alice) == aliceBalance); BEAST_EXPECT(env.balance(bob) == bobBalance - feeAmt); @@ -466,7 +479,9 @@ class Delegate_test : public beast::unit_test::suite env(check::create(alice, bob, XRP(10)), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); // carol does not have permission to create check - env(check::create(alice, bob, XRP(10)), delegate::as(carol), ter(terNO_DELEGATE_PERMISSION)); + env(check::create(alice, bob, XRP(10)), + delegate::as(carol), + ter(terNO_DELEGATE_PERMISSION)); } void @@ -796,24 +811,40 @@ class Delegate_test : public beast::unit_test::suite env.close(); // unsupported flags - env(trust(alice, gw["USD"](50), tfSetNoRipple), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); - env(trust(alice, gw["USD"](50), tfClearNoRipple), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); - env(trust(gw, gw["USD"](0), alice, tfSetDeepFreeze), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); - env(trust(gw, gw["USD"](0), alice, tfClearDeepFreeze), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); + env(trust(alice, gw["USD"](50), tfSetNoRipple), + delegate::as(bob), + ter(terNO_DELEGATE_PERMISSION)); + env(trust(alice, gw["USD"](50), tfClearNoRipple), + delegate::as(bob), + ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, gw["USD"](0), alice, tfSetDeepFreeze), + delegate::as(bob), + ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, gw["USD"](0), alice, tfClearDeepFreeze), + delegate::as(bob), + ter(terNO_DELEGATE_PERMISSION)); env.close(); // supported flags with wrong permission - env(trust(gw, gw["USD"](0), alice, tfSetfAuth), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); - env(trust(gw, gw["USD"](0), alice, tfSetFreeze), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, gw["USD"](0), alice, tfSetfAuth), + delegate::as(bob), + ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, gw["USD"](0), alice, tfSetFreeze), + delegate::as(bob), + ter(terNO_DELEGATE_PERMISSION)); env.close(); env(delegate::set(gw, bob, {"TrustlineAuthorize"})); env.close(); - env(trust(gw, gw["USD"](0), alice, tfClearFreeze), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, gw["USD"](0), alice, tfClearFreeze), + delegate::as(bob), + ter(terNO_DELEGATE_PERMISSION)); env.close(); // although trustline authorize is granted, bob can not change the // limit number - env(trust(gw, gw["USD"](50), alice, tfSetfAuth), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, gw["USD"](50), alice, tfSetfAuth), + delegate::as(bob), + ter(terNO_DELEGATE_PERMISSION)); env.close(); // supported flags with correct permission @@ -829,7 +860,9 @@ class Delegate_test : public beast::unit_test::suite env.close(); // but bob can not freeze trustline because he no longer has freeze // permission - env(trust(gw, gw["USD"](0), alice, tfSetFreeze), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, gw["USD"](0), alice, tfSetFreeze), + delegate::as(bob), + ter(terNO_DELEGATE_PERMISSION)); // cannot update LimitAmount with granular permission, both high and // low account @@ -883,13 +916,17 @@ class Delegate_test : public beast::unit_test::suite // add TrustSet permission and some unrelated permission env(delegate::set( - alice, bob, {"TrustlineUnfreeze", "NFTokenCreateOffer", "TrustSet", "AccountTransferRateSet"})); + alice, + bob, + {"TrustlineUnfreeze", "NFTokenCreateOffer", "TrustSet", "AccountTransferRateSet"})); env.close(); env(trust(alice, gw["USD"](50)), delegate::as(bob)); env.close(); env(delegate::set( - gw, bob, {"TrustlineUnfreeze", "NFTokenCreateOffer", "TrustSet", "AccountTransferRateSet"})); + gw, + bob, + {"TrustlineUnfreeze", "NFTokenCreateOffer", "TrustSet", "AccountTransferRateSet"})); env.close(); // since bob has TrustSet permission, he does not need @@ -919,7 +956,8 @@ class Delegate_test : public beast::unit_test::suite env(delegate::set(gw, bob, {"TrustlineAuthorize"})); env.close(); - env(trust(gw, gw["USD"](0), alice, tfSetfAuth | tfFullyCanonicalSig), delegate::as(bob)); + env(trust(gw, gw["USD"](0), alice, tfSetfAuth | tfFullyCanonicalSig), + delegate::as(bob)); } } @@ -998,7 +1036,8 @@ class Delegate_test : public beast::unit_test::suite env(jt, ter(terNO_DELEGATE_PERMISSION)); // alice give granular permission of AccountMessageKeySet to bob - env(delegate::set(alice, bob, {"AccountDomainSet", "AccountEmailHashSet", "AccountMessageKeySet"})); + env(delegate::set( + alice, bob, {"AccountDomainSet", "AccountEmailHashSet", "AccountMessageKeySet"})); env.close(); // bob can set message key for alice @@ -1015,7 +1054,10 @@ class Delegate_test : public beast::unit_test::suite env(delegate::set( alice, bob, - {"AccountDomainSet", "AccountEmailHashSet", "AccountMessageKeySet", "AccountTransferRateSet"})); + {"AccountDomainSet", + "AccountEmailHashSet", + "AccountMessageKeySet", + "AccountTransferRateSet"})); env.close(); auto jtRate = rate(alice, 2.0); jtRate[sfDelegate] = bob.human(); @@ -1057,7 +1099,8 @@ class Delegate_test : public beast::unit_test::suite jt[sfTickSize] = 7; env(jt, ter(terNO_DELEGATE_PERMISSION)); - env(delegate::set(alice, bob, {"AccountDomainSet", "AccountEmailHashSet", "AccountMessageKeySet"})); + env(delegate::set( + alice, bob, {"AccountDomainSet", "AccountEmailHashSet", "AccountMessageKeySet"})); env.close(); // bob does not have permission to set wallet locater for alice @@ -1095,7 +1138,8 @@ class Delegate_test : public beast::unit_test::suite testSetClearFlag(asfAllowTrustLineClawback); // alice gives some granular permissions to bob - env(delegate::set(alice, bob, {"AccountDomainSet", "AccountEmailHashSet", "AccountMessageKeySet"})); + env(delegate::set( + alice, bob, {"AccountDomainSet", "AccountEmailHashSet", "AccountMessageKeySet"})); env.close(); testSetClearFlag(asfDefaultRipple); @@ -1122,7 +1166,8 @@ class Delegate_test : public beast::unit_test::suite env(jt, ter(terNO_DELEGATE_PERMISSION)); // bob gives alice some permissions - env(delegate::set(bob, alice, {"AccountDomainSet", "AccountEmailHashSet", "AccountMessageKeySet"})); + env(delegate::set( + bob, alice, {"AccountDomainSet", "AccountEmailHashSet", "AccountMessageKeySet"})); env.close(); // since we can not set asfNoFreeze if asfAllowTrustLineClawback is @@ -1139,7 +1184,10 @@ class Delegate_test : public beast::unit_test::suite Account const bobKey{"bobKey", KeyType::secp256k1}; env(regkey(bob, bobKey)); env.close(); - env(fset(alice, asfDisableMaster), delegate::as(bob), sig(bob), ter(terNO_DELEGATE_PERMISSION)); + env(fset(alice, asfDisableMaster), + delegate::as(bob), + sig(bob), + ter(terNO_DELEGATE_PERMISSION)); } // tfFullyCanonicalSig won't block delegated transaction @@ -1184,18 +1232,30 @@ class Delegate_test : public beast::unit_test::suite env.close(); // delegate ledger object is not created yet - mpt.set({.account = alice, .flags = tfMPTLock, .delegate = bob, .err = terNO_DELEGATE_PERMISSION}); + mpt.set( + {.account = alice, + .flags = tfMPTLock, + .delegate = bob, + .err = terNO_DELEGATE_PERMISSION}); // alice gives granular permission to bob of MPTokenIssuanceUnlock env(delegate::set(alice, bob, {"MPTokenIssuanceUnlock"})); env.close(); // bob does not have lock permission - mpt.set({.account = alice, .flags = tfMPTLock, .delegate = bob, .err = terNO_DELEGATE_PERMISSION}); + mpt.set( + {.account = alice, + .flags = tfMPTLock, + .delegate = bob, + .err = terNO_DELEGATE_PERMISSION}); // bob now has lock permission, but does not have unlock permission env(delegate::set(alice, bob, {"MPTokenIssuanceLock"})); env.close(); mpt.set({.account = alice, .flags = tfMPTLock, .delegate = bob}); - mpt.set({.account = alice, .flags = tfMPTUnlock, .delegate = bob, .err = terNO_DELEGATE_PERMISSION}); + mpt.set( + {.account = alice, + .flags = tfMPTUnlock, + .delegate = bob, + .err = terNO_DELEGATE_PERMISSION}); // now bob can lock and unlock env(delegate::set(alice, bob, {"MPTokenIssuanceLock", "MPTokenIssuanceUnlock"})); @@ -1223,17 +1283,28 @@ class Delegate_test : public beast::unit_test::suite env.close(); mpt.set({.account = alice, .flags = tfMPTLock, .delegate = bob}); // bob does not have unlock permission - mpt.set({.account = alice, .flags = tfMPTUnlock, .delegate = bob, .err = terNO_DELEGATE_PERMISSION}); + mpt.set( + {.account = alice, + .flags = tfMPTUnlock, + .delegate = bob, + .err = terNO_DELEGATE_PERMISSION}); // alice gives bob some unrelated permission with // MPTokenIssuanceLock env(delegate::set(alice, bob, {"NFTokenMint", "MPTokenIssuanceLock", "NFTokenBurn"})); env.close(); // bob can not unlock - mpt.set({.account = alice, .flags = tfMPTUnlock, .delegate = bob, .err = terNO_DELEGATE_PERMISSION}); + mpt.set( + {.account = alice, + .flags = tfMPTUnlock, + .delegate = bob, + .err = terNO_DELEGATE_PERMISSION}); // alice add MPTokenIssuanceSet to permissions - env(delegate::set(alice, bob, {"NFTokenMint", "MPTokenIssuanceLock", "NFTokenBurn", "MPTokenIssuanceSet"})); + env(delegate::set( + alice, + bob, + {"NFTokenMint", "MPTokenIssuanceLock", "NFTokenBurn", "MPTokenIssuanceSet"})); mpt.set({.account = alice, .flags = tfMPTUnlock, .delegate = bob}); // alice can lock by herself mpt.set({.account = alice, .flags = tfMPTLock}); @@ -1309,7 +1380,11 @@ class Delegate_test : public beast::unit_test::suite auto bobBalance = env.balance(bob); auto carolBalance = env.balance(carol); - env(pay(alice, carol, XRP(100)), fee(XRP(10)), delegate::as(bob), sig(alice), ter(tefBAD_AUTH)); + env(pay(alice, carol, XRP(100)), + fee(XRP(10)), + delegate::as(bob), + sig(alice), + ter(tefBAD_AUTH)); env.close(); BEAST_EXPECT(env.balance(alice) == aliceBalance); BEAST_EXPECT(env.balance(bob) == bobBalance); @@ -1446,7 +1521,11 @@ class Delegate_test : public beast::unit_test::suite auto dariaBalance = env.balance(daria); auto edwardBalance = env.balance(edward); - env(pay(alice, carol, XRP(100)), fee(XRP(10)), delegate::as(bob), msig(daria, edward), ter(tefBAD_QUORUM)); + env(pay(alice, carol, XRP(100)), + fee(XRP(10)), + delegate::as(bob), + msig(daria, edward), + ter(tefBAD_QUORUM)); env.close(); BEAST_EXPECT(env.balance(alice) == aliceBalance); BEAST_EXPECT(env.balance(bob) == bobBalance); diff --git a/src/test/app/DeliverMin_test.cpp b/src/test/app/DeliverMin_test.cpp index 711b29cfa8..fe044353b7 100644 --- a/src/test/app/DeliverMin_test.cpp +++ b/src/test/app/DeliverMin_test.cpp @@ -25,13 +25,22 @@ public: env.trust(USD(100), "alice", "bob", "carol"); env.close(); env(pay("alice", "bob", USD(10)), deliver_min(USD(10)), ter(temBAD_AMOUNT)); - env(pay("alice", "bob", USD(10)), deliver_min(USD(-5)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); - env(pay("alice", "bob", USD(10)), deliver_min(XRP(5)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); + env(pay("alice", "bob", USD(10)), + deliver_min(USD(-5)), + txflags(tfPartialPayment), + ter(temBAD_AMOUNT)); + env(pay("alice", "bob", USD(10)), + deliver_min(XRP(5)), + txflags(tfPartialPayment), + ter(temBAD_AMOUNT)); env(pay("alice", "bob", USD(10)), deliver_min(Account("carol")["USD"](5)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); - env(pay("alice", "bob", USD(10)), deliver_min(USD(15)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); + env(pay("alice", "bob", USD(10)), + deliver_min(USD(15)), + txflags(tfPartialPayment), + ter(temBAD_AMOUNT)); env(pay(gw, "carol", USD(50))); env(offer("carol", XRP(5), USD(5))); env(pay("alice", "bob", USD(10)), diff --git a/src/test/app/DepositAuth_test.cpp b/src/test/app/DepositAuth_test.cpp index 0cd7e7449c..547d9d8b62 100644 --- a/src/test/app/DepositAuth_test.cpp +++ b/src/test/app/DepositAuth_test.cpp @@ -258,41 +258,45 @@ struct DepositAuth_test : public beast::unit_test::suite IOU const USD1(gw1["USD"]); IOU const USD2(gw2["USD"]); - auto testIssuer = - [&](FeatureBitset const& features, bool noRipplePrev, bool noRippleNext, bool withDepositAuth) { - Env env(*this, features); + auto testIssuer = [&](FeatureBitset const& features, + bool noRipplePrev, + bool noRippleNext, + bool withDepositAuth) { + Env env(*this, features); - env.fund(XRP(10000), gw1, alice, bob); - env.close(); - env(trust(gw1, alice["USD"](10), noRipplePrev ? tfSetNoRipple : 0)); - env(trust(gw1, bob["USD"](10), noRippleNext ? tfSetNoRipple : 0)); - env.trust(USD1(10), alice, bob); + env.fund(XRP(10000), gw1, alice, bob); + env.close(); + env(trust(gw1, alice["USD"](10), noRipplePrev ? tfSetNoRipple : 0)); + env(trust(gw1, bob["USD"](10), noRippleNext ? tfSetNoRipple : 0)); + env.trust(USD1(10), alice, bob); - env(pay(gw1, alice, USD1(10))); + env(pay(gw1, alice, USD1(10))); - if (withDepositAuth) - env(fset(gw1, asfDepositAuth)); + if (withDepositAuth) + env(fset(gw1, asfDepositAuth)); - TER const result = (noRippleNext && noRipplePrev) ? TER{tecPATH_DRY} : TER{tesSUCCESS}; - env(pay(alice, bob, USD1(10)), path(gw1), ter(result)); - }; + TER const result = (noRippleNext && noRipplePrev) ? TER{tecPATH_DRY} : TER{tesSUCCESS}; + env(pay(alice, bob, USD1(10)), path(gw1), ter(result)); + }; - auto testNonIssuer = - [&](FeatureBitset const& features, bool noRipplePrev, bool noRippleNext, bool withDepositAuth) { - Env env(*this, features); + auto testNonIssuer = [&](FeatureBitset const& features, + bool noRipplePrev, + bool noRippleNext, + bool withDepositAuth) { + Env env(*this, features); - env.fund(XRP(10000), gw1, gw2, alice); - env.close(); - env(trust(alice, USD1(10), noRipplePrev ? tfSetNoRipple : 0)); - env(trust(alice, USD2(10), noRippleNext ? tfSetNoRipple : 0)); - env(pay(gw2, alice, USD2(10))); + env.fund(XRP(10000), gw1, gw2, alice); + env.close(); + env(trust(alice, USD1(10), noRipplePrev ? tfSetNoRipple : 0)); + env(trust(alice, USD2(10), noRippleNext ? tfSetNoRipple : 0)); + env(pay(gw2, alice, USD2(10))); - if (withDepositAuth) - env(fset(alice, asfDepositAuth)); + if (withDepositAuth) + env(fset(alice, asfDepositAuth)); - TER const result = (noRippleNext && noRipplePrev) ? TER{tecPATH_DRY} : TER{tesSUCCESS}; - env(pay(gw1, gw2, USD2(10)), path(alice), sendmax(USD1(10)), ter(result)); - }; + TER const result = (noRippleNext && noRipplePrev) ? TER{tecPATH_DRY} : TER{tesSUCCESS}; + env(pay(gw1, gw2, USD2(10)), path(alice), sendmax(USD1(10)), ter(result)); + }; // Test every combo of noRipplePrev, noRippleNext, and withDepositAuth for (int i = 0; i < 8; ++i) @@ -742,8 +746,9 @@ struct DepositPreauth_test : public beast::unit_test::suite auto const jDP = ledgerEntryDepositPreauth(env, bob, {{issuer, credType}}); BEAST_EXPECT( - jDP.isObject() && jDP.isMember(jss::result) && !jDP[jss::result].isMember(jss::error) && - jDP[jss::result].isMember(jss::node) && jDP[jss::result][jss::node].isMember("LedgerEntryType") && + jDP.isObject() && jDP.isMember(jss::result) && + !jDP[jss::result].isMember(jss::error) && jDP[jss::result].isMember(jss::node) && + jDP[jss::result][jss::node].isMember("LedgerEntryType") && jDP[jss::result][jss::node]["LedgerEntryType"] == jss::DepositPreauth); // Alice can't pay - empty credentials array @@ -812,7 +817,8 @@ struct DepositPreauth_test : public beast::unit_test::suite } // Bob setup DepositPreauth object, duplicates is not allowed - env(deposit::authCredentials(bob, {{issuer, credType}, {issuer, credType}}), ter(temMALFORMED)); + env(deposit::authCredentials(bob, {{issuer, credType}, {issuer, credType}}), + ter(temMALFORMED)); // Bob setup DepositPreauth object env(deposit::authCredentials(bob, {{issuer, credType}})); @@ -823,12 +829,16 @@ struct DepositPreauth_test : public beast::unit_test::suite "0E0B04ED60588A758B67E21FBBE95AC5A63598BA951761DC0EC9C08D7E" "01E034"; // Alice can't pay with non-existing credentials - env(pay(alice, bob, XRP(100)), credentials::ids({invalidIdx}), ter(tecBAD_CREDENTIALS)); + env(pay(alice, bob, XRP(100)), + credentials::ids({invalidIdx}), + ter(tecBAD_CREDENTIALS)); } { // maria can't pay using valid credentials but issued for // different account - env(pay(maria, bob, XRP(100)), credentials::ids({credIdx}), ter(tecBAD_CREDENTIALS)); + env(pay(maria, bob, XRP(100)), + credentials::ids({credIdx}), + ter(tecBAD_CREDENTIALS)); } { @@ -842,7 +852,9 @@ struct DepositPreauth_test : public beast::unit_test::suite std::string const credIdx2 = jv[jss::result][jss::index].asString(); // Alice can't pay with invalid set of valid credentials - env(pay(alice, bob, XRP(100)), credentials::ids({credIdx, credIdx2}), ter(tecNO_PERMISSION)); + env(pay(alice, bob, XRP(100)), + credentials::ids({credIdx, credIdx2}), + ter(tecNO_PERMISSION)); } // Error, duplicate credentials @@ -936,7 +948,8 @@ struct DepositPreauth_test : public beast::unit_test::suite { // AuthorizeCredentials is larger than 8 elements - Account const a("a"), b("b"), c("c"), d("d"), e("e"), f("f"), g("g"), h("h"), i("i"); + Account const a("a"), b("b"), c("c"), d("d"), e("e"), f("f"), g("g"), h("h"), + i("i"); auto const& z = credType; auto jv = deposit::authCredentials( bob, {{a, z}, {b, z}, {c, z}, {d, z}, {e, z}, {f, z}, {g, z}, {h, z}, {i, z}}); @@ -972,8 +985,10 @@ struct DepositPreauth_test : public beast::unit_test::suite auto const jDP = ledgerEntryDepositPreauth(env, bob, {{issuer, credType}}); BEAST_EXPECT( - jDP.isObject() && jDP.isMember(jss::result) && !jDP[jss::result].isMember(jss::error) && - jDP[jss::result].isMember(jss::node) && jDP[jss::result][jss::node].isMember("LedgerEntryType") && + jDP.isObject() && jDP.isMember(jss::result) && + !jDP[jss::result].isMember(jss::error) && + jDP[jss::result].isMember(jss::node) && + jDP[jss::result][jss::node].isMember("LedgerEntryType") && jDP[jss::result][jss::node]["LedgerEntryType"] == jss::DepositPreauth); // Check object fields @@ -984,7 +999,8 @@ struct DepositPreauth_test : public beast::unit_test::suite { auto const& c(o[jss::Credential]); BEAST_EXPECT(c[jss::Issuer].asString() == issuer.human()); - BEAST_EXPECT(c["CredentialType"].asString() == strHex(std::string_view(credType))); + BEAST_EXPECT( + c["CredentialType"].asString() == strHex(std::string_view(credType))); } // can't create duplicate @@ -997,7 +1013,8 @@ struct DepositPreauth_test : public beast::unit_test::suite env.close(); auto const jDP = ledgerEntryDepositPreauth(env, bob, {{issuer, credType}}); BEAST_EXPECT( - jDP.isObject() && jDP.isMember(jss::result) && jDP[jss::result].isMember(jss::error) && + jDP.isObject() && jDP.isMember(jss::result) && + jDP[jss::result].isMember(jss::error) && jDP[jss::result][jss::error] == "entryNotFound"); } } @@ -1028,7 +1045,8 @@ struct DepositPreauth_test : public beast::unit_test::suite auto jv = credentials::create(alice, issuer, credType); // Current time in ripple epoch. // Every time ledger close, unittest timer increase by 10s - uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count() + 60; + uint32_t const t = + env.current()->header().parentCloseTime.time_since_epoch().count() + 60; jv[sfExpiration.jsonName] = t; env(jv); env.close(); @@ -1039,7 +1057,8 @@ struct DepositPreauth_test : public beast::unit_test::suite // Create credential which not expired jv = credentials::create(alice, issuer, credType2); - uint32_t const t2 = env.current()->header().parentCloseTime.time_since_epoch().count() + 1000; + uint32_t const t2 = + env.current()->header().parentCloseTime.time_since_epoch().count() + 1000; jv[sfExpiration.jsonName] = t2; env(jv); env.close(); @@ -1069,7 +1088,9 @@ struct DepositPreauth_test : public beast::unit_test::suite env.close(); // Ledger closed, time increased, alice can't pay anymore - env(pay(alice, bob, XRP(100)), credentials::ids({credIdx, credIdx2}), ter(tecEXPIRED)); + env(pay(alice, bob, XRP(100)), + credentials::ids({credIdx, credIdx2}), + ter(tecEXPIRED)); env.close(); { @@ -1085,13 +1106,15 @@ struct DepositPreauth_test : public beast::unit_test::suite // check that non-expired credential still present auto const jle = credentials::ledgerEntry(env, alice, issuer, credType2); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && + !jle[jss::result].isMember(jss::error) && jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && jle[jss::result][jss::node][jss::Issuer] == issuer.human() && jle[jss::result][jss::node][jss::Subject] == alice.human() && - jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType2))); + jle[jss::result][jss::node]["CredentialType"] == + strHex(std::string_view(credType2))); } BEAST_EXPECT(ownerCount(env, issuer) == 0); @@ -1100,7 +1123,8 @@ struct DepositPreauth_test : public beast::unit_test::suite { auto jv = credentials::create(gw, issuer, credType); - uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count() + 40; + uint32_t const t = + env.current()->header().parentCloseTime.time_since_epoch().count() + 40; jv[sfExpiration.jsonName] = t; env(jv); env.close(); @@ -1125,7 +1149,8 @@ struct DepositPreauth_test : public beast::unit_test::suite auto const jDelCred = credentials::ledgerEntry(env, gw, issuer, credType); BEAST_EXPECT( jDelCred.isObject() && jDelCred.isMember(jss::result) && - jDelCred[jss::result].isMember(jss::error) && jDelCred[jss::result][jss::error] == "entryNotFound"); + jDelCred[jss::result].isMember(jss::error) && + jDelCred[jss::result][jss::error] == "entryNotFound"); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, gw) == 0); @@ -1144,7 +1169,8 @@ struct DepositPreauth_test : public beast::unit_test::suite // Create credentials auto jv = credentials::create(zelda, issuer, credType); - uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count() + 50; + uint32_t const t = + env.current()->header().parentCloseTime.time_since_epoch().count() + 50; jv[sfExpiration.jsonName] = t; env(jv); env.close(); @@ -1180,19 +1206,25 @@ struct DepositPreauth_test : public beast::unit_test::suite "0E0B04ED60588A758B67E21FBBE95AC5A63598BA951761DC0EC9C08D7E" "01E034"; - env(escrow::finish(zelda, alice, seq), credentials::ids({invalidIdx}), ter(tecBAD_CREDENTIALS)); + env(escrow::finish(zelda, alice, seq), + credentials::ids({invalidIdx}), + ter(tecBAD_CREDENTIALS)); env.close(); } { // Ledger closed, time increased, zelda can't finish escrow - env(escrow::finish(zelda, alice, seq), credentials::ids({credIdx}), fee(1500), ter(tecEXPIRED)); + env(escrow::finish(zelda, alice, seq), + credentials::ids({credIdx}), + fee(1500), + ter(tecEXPIRED)); env.close(); } // check that expired credentials were deleted auto const jDelCred = credentials::ledgerEntry(env, zelda, issuer, credType); BEAST_EXPECT( - jDelCred.isObject() && jDelCred.isMember(jss::result) && jDelCred[jss::result].isMember(jss::error) && + jDelCred.isObject() && jDelCred.isMember(jss::result) && + jDelCred[jss::result].isMember(jss::error) && jDelCred[jss::result][jss::error] == "entryNotFound"); } } @@ -1213,7 +1245,14 @@ struct DepositPreauth_test : public beast::unit_test::suite env.fund(XRP(5000), stock, alice, bob); std::vector credentials = { - {"a", "a"}, {"b", "b"}, {"c", "c"}, {"d", "d"}, {"e", "e"}, {"f", "f"}, {"g", "g"}, {"h", "h"}}; + {"a", "a"}, + {"b", "b"}, + {"c", "c"}, + {"d", "d"}, + {"e", "e"}, + {"f", "f"}, + {"g", "g"}, + {"h", "h"}}; for (auto const& c : credentials) env.fund(XRP(5000), c.issuer); @@ -1244,7 +1283,8 @@ struct DepositPreauth_test : public beast::unit_test::suite auto issuer = c[jss::Issuer].asString(); if (BEAST_EXPECT(pubKey2Acc.contains(issuer))) - readCreds.emplace_back(pubKey2Acc.at(issuer), c["CredentialType"].asString()); + readCreds.emplace_back( + pubKey2Acc.at(issuer), c["CredentialType"].asString()); } BEAST_EXPECT(std::ranges::is_sorted(readCreds)); @@ -1270,7 +1310,8 @@ struct DepositPreauth_test : public beast::unit_test::suite testcase("Check duplicate credentials."); { // check duplicates in depositPreauth params - std::vector copyCredentials(credentials.begin(), credentials.end() - 1); + std::vector copyCredentials( + credentials.begin(), credentials.end() - 1); std::ranges::shuffle(copyCredentials, gen); for (auto const& c : copyCredentials) @@ -1290,7 +1331,9 @@ struct DepositPreauth_test : public beast::unit_test::suite env.close(); credentialIDs.push_back( - credentials::ledgerEntry(env, alice, c.issuer, c.credType)[jss::result][jss::index].asString()); + credentials::ledgerEntry( + env, alice, c.issuer, c.credType)[jss::result][jss::index] + .asString()); } // check duplicates in payment params diff --git a/src/test/app/Discrepancy_test.cpp b/src/test/app/Discrepancy_test.cpp index b56cb5b7c6..08a8a01753 100644 --- a/src/test/app/Discrepancy_test.cpp +++ b/src/test/app/Discrepancy_test.cpp @@ -69,9 +69,14 @@ class Discrepancy_test : public beast::unit_test::suite env.close(); test::PathSet payPaths{ - test::Path{A2["JPY"], A2}, test::Path{XRP, A2["JPY"], A2}, test::Path{A6, XRP, A2["JPY"], A2}}; + test::Path{A2["JPY"], A2}, + test::Path{XRP, A2["JPY"], A2}, + test::Path{A6, XRP, A2["JPY"], A2}}; - env(pay(A1, A1, A2["JPY"](1000)), json(payPaths.json()), txflags(tfPartialPayment), sendmax(A3["CNY"](56))); + env(pay(A1, A1, A2["JPY"](1000)), + json(payPaths.json()), + txflags(tfPartialPayment), + sendmax(A3["CNY"](56))); env.close(); Json::Value jrq2; @@ -96,14 +101,18 @@ class Discrepancy_test : public beast::unit_test::suite if (node && node[sfLedgerEntryType.fieldName] == jss::AccountRoot) { - Json::Value prevFields = node.isMember(sfPreviousFields.fieldName) ? node[sfPreviousFields.fieldName] - : node[sfNewFields.fieldName]; - Json::Value finalFields = node.isMember(sfFinalFields.fieldName) ? node[sfFinalFields.fieldName] - : node[sfNewFields.fieldName]; + Json::Value prevFields = node.isMember(sfPreviousFields.fieldName) + ? node[sfPreviousFields.fieldName] + : node[sfNewFields.fieldName]; + Json::Value finalFields = node.isMember(sfFinalFields.fieldName) + ? node[sfFinalFields.fieldName] + : node[sfNewFields.fieldName]; if (prevFields) - sumPrev += beast::lexicalCastThrow(prevFields[sfBalance.fieldName].asString()); + sumPrev += beast::lexicalCastThrow( + prevFields[sfBalance.fieldName].asString()); if (finalFields) - sumFinal += beast::lexicalCastThrow(finalFields[sfBalance.fieldName].asString()); + sumFinal += beast::lexicalCastThrow( + finalFields[sfBalance.fieldName].asString()); } } // the difference in balances (final and prev) should be the diff --git a/src/test/app/EscrowToken_test.cpp b/src/test/app/EscrowToken_test.cpp index 1f3b3bab70..5cbeb0b94a 100644 --- a/src/test/app/EscrowToken_test.cpp +++ b/src/test/app/EscrowToken_test.cpp @@ -1,7 +1,5 @@ #include -#include - #include #include #include @@ -9,6 +7,7 @@ #include #include #include +#include #include #include @@ -232,7 +231,10 @@ struct EscrowToken_test : public beast::unit_test::suite auto const USD = gw["USD"]; env.fund(XRP(5000), alice, bob, gw); - env(escrow::create(alice, bob, USD(1)), escrow::finish_time(env.now() + 1s), fee(XRP(-1)), ter(temBAD_FEE)); + env(escrow::create(alice, bob, USD(1)), + escrow::finish_time(env.now() + 1s), + fee(XRP(-1)), + ter(temBAD_FEE)); env.close(); } @@ -542,7 +544,8 @@ struct EscrowToken_test : public beast::unit_test::suite env(pay(gw, bob, USD(1))); env.close(); - bool const largeMantissa = features[featureSingleAssetVault] || features[featureLendingProtocol]; + bool const largeMantissa = + features[featureSingleAssetVault] || features[featureLendingProtocol]; // alice cannot create escrow for 1/10 iou - precision loss env(escrow::create(alice, bob, USD(1)), @@ -974,7 +977,8 @@ struct EscrowToken_test : public beast::unit_test::suite env(escrow::create(alice, alice, USD(1'000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 500s)); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const aa = env.le(keylet::escrow(alice.id(), aseq)); BEAST_EXPECT(aa); @@ -993,7 +997,8 @@ struct EscrowToken_test : public beast::unit_test::suite env(escrow::create(bob, bob, USD(1'000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 2s)); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const bb = env.le(keylet::escrow(bob.id(), bseq)); BEAST_EXPECT(bb); @@ -1014,7 +1019,8 @@ struct EscrowToken_test : public beast::unit_test::suite env(escrow::finish(alice, alice, aseq)); { BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), aseq))); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); @@ -1033,7 +1039,8 @@ struct EscrowToken_test : public beast::unit_test::suite env(escrow::cancel(bob, bob, bseq)); { BEAST_EXPECT(!env.le(keylet::escrow(bob.id(), bseq))); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); @@ -1061,12 +1068,14 @@ struct EscrowToken_test : public beast::unit_test::suite auto const bseq = env.seq(bob); env(escrow::create(alice, bob, USD(1'000)), escrow::finish_time(env.now() + 1s)); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); env(escrow::create(bob, carol, USD(1'000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 2s)); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const ab = env.le(keylet::escrow(alice.id(), aseq)); @@ -1160,7 +1169,8 @@ struct EscrowToken_test : public beast::unit_test::suite env(escrow::create(alice, gw, USD(1'000)), escrow::finish_time(env.now() + 1s)); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); env(escrow::create(gw, carol, USD(1'000)), escrow::finish_time(env.now() + 1s), @@ -2004,7 +2014,8 @@ struct EscrowToken_test : public beast::unit_test::suite env(pay(gw, bob, USD(1))); env.close(); - bool const largeMantissa = features[featureSingleAssetVault] || features[featureLendingProtocol]; + bool const largeMantissa = + features[featureSingleAssetVault] || features[featureLendingProtocol]; // alice cannot create escrow for 1/10 iou - precision loss env(escrow::create(alice, bob, USD(1)), @@ -2050,7 +2061,8 @@ struct EscrowToken_test : public beast::unit_test::suite env.fund(XRP(5000), bob); MPTTester mptGw(env, gw, {.holders = {alice}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); auto const MPT = mptGw["MPT"]; env(pay(gw, alice, MPT(10'000))); @@ -2104,11 +2116,16 @@ struct EscrowToken_test : public beast::unit_test::suite Json::Value jv = escrow::create(alice, bob, XRP(1)); jv.removeMember(jss::Amount); - jv[jss::Amount][jss::mpt_issuance_id] = "00000004A407AF5856CCF3C42619DAA925813FC955C72983"; + jv[jss::Amount][jss::mpt_issuance_id] = + "00000004A407AF5856CCF3C42619DAA925813FC955C72983"; jv[jss::Amount][jss::value] = "-1"; auto const result = withMPT ? ter(temBAD_AMOUNT) : ter(temDISABLED); - env(jv, escrow::condition(escrow::cb1), escrow::finish_time(env.now() + 1s), fee(baseFee * 150), result); + env(jv, + escrow::condition(escrow::cb1), + escrow::finish_time(env.now() + 1s), + fee(baseFee * 150), + result); env.close(); } @@ -2121,7 +2138,8 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2153,7 +2171,8 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); auto const MPT = mptGw["MPT"]; env(pay(gw, alice, MPT(10'000))); @@ -2179,7 +2198,8 @@ struct EscrowToken_test : public beast::unit_test::suite auto const mpt = xrpl::test::jtx::MPT(alice.name(), makeMptID(env.seq(alice), alice)); Json::Value jv = escrow::create(alice, bob, mpt(2)); - jv[jss::Amount][jss::mpt_issuance_id] = "00000004A407AF5856CCF3C42619DAA925813FC955C72983"; + jv[jss::Amount][jss::mpt_issuance_id] = + "00000004A407AF5856CCF3C42619DAA925813FC955C72983"; env(jv, escrow::condition(escrow::cb1), escrow::finish_time(env.now() + 1s), @@ -2222,7 +2242,8 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); auto const MPT = mptGw["MPT"]; env(escrow::create(alice, bob, MPT(4)), @@ -2243,7 +2264,9 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); + {.ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = gw, .holder = alice}); auto const MPT = mptGw["MPT"]; @@ -2271,7 +2294,9 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); + {.ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = gw, .holder = alice}); mptGw.authorize({.account = bob}); @@ -2302,7 +2327,9 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); + {.ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2331,7 +2358,9 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); + {.ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2384,7 +2413,8 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2408,7 +2438,8 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2442,7 +2473,9 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); + {.ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = gw, .holder = alice}); mptGw.authorize({.account = bob}); @@ -2511,7 +2544,9 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); + {.ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2560,7 +2595,8 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); MPTTester mptGw(env, gw, {.holders = {alice}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); auto const MPT = mptGw["MPT"]; env(pay(gw, alice, MPT(10'000))); @@ -2593,7 +2629,8 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); MPTTester mptGw(env, gw, {.holders = {alice}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); auto const MPT = mptGw["MPT"]; env(pay(gw, alice, MPT(10'000))); @@ -2627,7 +2664,8 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); MPTTester mptGw(env, gw, {.holders = {alice}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); auto const MPT = mptGw["MPT"]; env(pay(gw, alice, MPT(10'000))); @@ -2667,7 +2705,9 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); + {.ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = gw, .holder = alice}); mptGw.authorize({.account = bob}); @@ -2735,7 +2775,8 @@ struct EscrowToken_test : public beast::unit_test::suite env.fund(XRP(5000), bob); MPTTester mptGw(env, gw, {.holders = {alice, carol}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = carol}); auto const MPT = mptGw["MPT"]; @@ -2909,7 +2950,8 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2943,7 +2985,8 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(alice, MPT) == preAliceMPT - MPT(1)); BEAST_EXPECT(mptEscrowed(env, alice, MPT) == 0); - BEAST_EXPECT(!env.le(keylet::mptoken(MPT.mpt(), alice))->isFieldPresent(sfLockedAmount)); + BEAST_EXPECT( + !env.le(keylet::mptoken(MPT.mpt(), alice))->isFieldPresent(sfLockedAmount)); BEAST_EXPECT(env.balance(bob, MPT) == preBobMPT + MPT(1)); BEAST_EXPECT(mptEscrowed(env, bob, MPT) == 0); BEAST_EXPECT(env.balance(gw, MPT) == outstandingMPT); @@ -2960,7 +3003,8 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3032,7 +3076,8 @@ struct EscrowToken_test : public beast::unit_test::suite Env env{*this, features}; MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3045,7 +3090,8 @@ struct EscrowToken_test : public beast::unit_test::suite env(escrow::create(alice, alice, MPT(1'000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 500s)); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const aa = env.le(keylet::escrow(alice.id(), aseq)); BEAST_EXPECT(aa); @@ -3064,7 +3110,8 @@ struct EscrowToken_test : public beast::unit_test::suite env(escrow::create(bob, bob, MPT(1'000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 2s)); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const bb = env.le(keylet::escrow(bob.id(), bseq)); BEAST_EXPECT(bb); @@ -3079,7 +3126,8 @@ struct EscrowToken_test : public beast::unit_test::suite env(escrow::finish(alice, alice, aseq)); { BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), aseq))); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); @@ -3094,7 +3142,8 @@ struct EscrowToken_test : public beast::unit_test::suite env(escrow::cancel(bob, bob, bseq)); { BEAST_EXPECT(!env.le(keylet::escrow(bob.id(), bseq))); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); @@ -3107,7 +3156,8 @@ struct EscrowToken_test : public beast::unit_test::suite Env env{*this, features}; MPTTester mptGw(env, gw, {.holders = {alice, bob, carol}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); mptGw.authorize({.account = carol}); @@ -3120,12 +3170,14 @@ struct EscrowToken_test : public beast::unit_test::suite auto const bseq = env.seq(bob); env(escrow::create(alice, bob, MPT(1'000)), escrow::finish_time(env.now() + 1s)); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); env(escrow::create(bob, carol, MPT(1'000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 2s)); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const ab = env.le(keylet::escrow(alice.id(), aseq)); @@ -3204,7 +3256,8 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); auto const MPT = mptGw["MPT"]; env(pay(gw, alice, MPT(10'000))); @@ -3266,7 +3319,10 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.transferFee = 25000, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + {.transferFee = 25000, + .ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3318,7 +3374,10 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.transferFee = 25000, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + {.transferFee = 25000, + .ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3361,7 +3420,10 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.transferFee = 25000, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + {.transferFee = 25000, + .ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3414,7 +3476,9 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); + {.ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = gw, .holder = alice}); mptGw.authorize({.account = bob}); @@ -3454,7 +3518,10 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); + mptGw.create( + {.ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3570,7 +3637,8 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3618,7 +3686,8 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); MPTTester mptGw(env, gw, {.holders = {alice}}); - mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); auto const MPT = mptGw["MPT"]; env(pay(gw, alice, MPT(10'000))); @@ -3637,7 +3706,8 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(alice, MPT) == MPT(0)); BEAST_EXPECT(mptEscrowed(env, alice, MPT) == 10); - mptGw.authorize({.account = alice, .flags = tfMPTUnauthorize, .err = tecHAS_OBLIGATIONS}); + mptGw.authorize( + {.account = alice, .flags = tfMPTUnauthorize, .err = tecHAS_OBLIGATIONS}); env(escrow::finish(bob, alice, seq1), escrow::condition(escrow::cb1), @@ -3700,7 +3770,8 @@ public: { using namespace test::jtx; FeatureBitset const all{testable_amendments()}; - for (FeatureBitset const& feats : {all - featureSingleAssetVault - featureLendingProtocol, all}) + for (FeatureBitset const& feats : + {all - featureSingleAssetVault - featureLendingProtocol, all}) { testIOUWithFeats(feats); testMPTWithFeats(feats); diff --git a/src/test/app/Escrow_test.cpp b/src/test/app/Escrow_test.cpp index 652049270f..4538f2d751 100644 --- a/src/test/app/Escrow_test.cpp +++ b/src/test/app/Escrow_test.cpp @@ -1,12 +1,11 @@ #include -#include - #include #include #include #include #include +#include #include #include @@ -91,7 +90,9 @@ struct Escrow_test : public beast::unit_test::suite auto const ts = env.now() + 117s; auto const seq = env.seq("alice"); - env(escrow::create("alice", "bob", XRP(1000)), escrow::condition(escrow::cb1), escrow::cancel_time(ts)); + env(escrow::create("alice", "bob", XRP(1000)), + escrow::condition(escrow::cb1), + escrow::cancel_time(ts)); // Advance the ledger, verifying that the cancel won't complete // prematurely. @@ -121,7 +122,9 @@ struct Escrow_test : public beast::unit_test::suite auto const cts = env.now() + 192s; auto const seq = env.seq("alice"); - env(escrow::create("alice", "bob", XRP(1000)), escrow::finish_time(fts), escrow::cancel_time(cts)); + env(escrow::create("alice", "bob", XRP(1000)), + escrow::finish_time(fts), + escrow::cancel_time(cts)); // Advance the ledger, verifying that the finish and cancel won't // complete prematurely. @@ -150,7 +153,9 @@ struct Escrow_test : public beast::unit_test::suite auto const cts = env.now() + 184s; auto const seq = env.seq("alice"); - env(escrow::create("alice", "bob", XRP(1000)), escrow::finish_time(fts), escrow::cancel_time(cts)); + env(escrow::create("alice", "bob", XRP(1000)), + escrow::finish_time(fts), + escrow::cancel_time(cts)); // Advance the ledger, verifying that the finish and cancel won't // complete prematurely. @@ -192,12 +197,17 @@ struct Escrow_test : public beast::unit_test::suite // Check to make sure that we correctly detect if tags are really // required: env(fset(bob, asfRequireDest)); - env(escrow::create(alice, bob, XRP(1000)), escrow::finish_time(env.now() + 1s), ter(tecDST_TAG_NEEDED)); + env(escrow::create(alice, bob, XRP(1000)), + escrow::finish_time(env.now() + 1s), + ter(tecDST_TAG_NEEDED)); // set source and dest tags auto const seq = env.seq(alice); - env(escrow::create(alice, bob, XRP(1000)), escrow::finish_time(env.now() + 1s), stag(1), dtag(2)); + env(escrow::create(alice, bob, XRP(1000)), + escrow::finish_time(env.now() + 1s), + stag(1), + dtag(2)); auto const sle = env.le(keylet::escrow(alice.id(), seq)); BEAST_EXPECT(sle); @@ -298,7 +308,9 @@ struct Escrow_test : public beast::unit_test::suite ter(temINVALID_FLAG)); // Finish time is in the past - env(escrow::create("alice", "bob", XRP(1000)), escrow::finish_time(env.now() - 5s), ter(tecNO_PERMISSION)); + env(escrow::create("alice", "bob", XRP(1000)), + escrow::finish_time(env.now() - 5s), + ter(tecNO_PERMISSION)); // Cancel time is in the past env(escrow::create("alice", "bob", XRP(1000)), @@ -307,7 +319,9 @@ struct Escrow_test : public beast::unit_test::suite ter(tecNO_PERMISSION)); // no destination account - env(escrow::create("alice", "carol", XRP(1000)), escrow::finish_time(env.now() + 1s), ter(tecNO_DST)); + env(escrow::create("alice", "carol", XRP(1000)), + escrow::finish_time(env.now() + 1s), + ter(tecNO_DST)); env.fund(XRP(5000), "carol"); @@ -323,17 +337,25 @@ struct Escrow_test : public beast::unit_test::suite } // Sending zero or no XRP: - env(escrow::create("alice", "carol", XRP(0)), escrow::finish_time(env.now() + 1s), ter(temBAD_AMOUNT)); - env(escrow::create("alice", "carol", XRP(-1000)), escrow::finish_time(env.now() + 1s), ter(temBAD_AMOUNT)); + env(escrow::create("alice", "carol", XRP(0)), + escrow::finish_time(env.now() + 1s), + ter(temBAD_AMOUNT)); + env(escrow::create("alice", "carol", XRP(-1000)), + escrow::finish_time(env.now() + 1s), + ter(temBAD_AMOUNT)); // Fail if neither CancelAfter nor FinishAfter are specified: env(escrow::create("alice", "carol", XRP(1)), ter(temBAD_EXPIRATION)); // Fail if neither a FinishTime nor a condition are attached: - env(escrow::create("alice", "carol", XRP(1)), escrow::cancel_time(env.now() + 1s), ter(temMALFORMED)); + env(escrow::create("alice", "carol", XRP(1)), + escrow::cancel_time(env.now() + 1s), + ter(temMALFORMED)); // Fail if FinishAfter has already passed: - env(escrow::create("alice", "carol", XRP(1)), escrow::finish_time(env.now() - 1s), ter(tecNO_PERMISSION)); + env(escrow::create("alice", "carol", XRP(1)), + escrow::finish_time(env.now() - 1s), + ter(tecNO_PERMISSION)); // If both CancelAfter and FinishAfter are set, then CancelAfter must // be strictly later than FinishAfter. @@ -369,10 +391,14 @@ struct Escrow_test : public beast::unit_test::suite auto const accountIncrement = drops(env.current()->fees().increment); env.fund(accountReserve + accountIncrement + XRP(50), "daniel"); - env(escrow::create("daniel", "bob", XRP(51)), escrow::finish_time(env.now() + 1s), ter(tecUNFUNDED)); + env(escrow::create("daniel", "bob", XRP(51)), + escrow::finish_time(env.now() + 1s), + ter(tecUNFUNDED)); env.fund(accountReserve + accountIncrement + XRP(50), "evan"); - env(escrow::create("evan", "bob", XRP(50)), escrow::finish_time(env.now() + 1s), ter(tecUNFUNDED)); + env(escrow::create("evan", "bob", XRP(50)), + escrow::finish_time(env.now() + 1s), + ter(tecUNFUNDED)); env.fund(accountReserve, "frank"); env(escrow::create("frank", "bob", XRP(1)), @@ -383,7 +409,9 @@ struct Escrow_test : public beast::unit_test::suite { // Specify incorrect sequence number env.fund(XRP(5000), "hannah"); auto const seq = env.seq("hannah"); - env(escrow::create("hannah", "hannah", XRP(10)), escrow::finish_time(env.now() + 1s), fee(150 * baseFee)); + env(escrow::create("hannah", "hannah", XRP(10)), + escrow::finish_time(env.now() + 1s), + fee(150 * baseFee)); env.close(); env(escrow::finish("hannah", "hannah", seq + 7), fee(150 * baseFee), ter(tecNO_TARGET)); } @@ -1009,8 +1037,12 @@ struct Escrow_test : public beast::unit_test::suite // Assemble finish that is missing the Condition or the Fulfillment // since either both must be present, or neither can: - env(escrow::finish("bob", "alice", seq), escrow::condition(escrow::cb3), ter(temMALFORMED)); - env(escrow::finish("bob", "alice", seq), escrow::fulfillment(escrow::fb3), ter(temMALFORMED)); + env(escrow::finish("bob", "alice", seq), + escrow::condition(escrow::cb3), + ter(temMALFORMED)); + env(escrow::finish("bob", "alice", seq), + escrow::fulfillment(escrow::fb3), + ter(temMALFORMED)); // Now finish it. env(escrow::finish("bob", "alice", seq), @@ -1025,10 +1057,11 @@ struct Escrow_test : public beast::unit_test::suite Env env(*this, features); env.fund(XRP(5000), "alice", "bob"); - std::array cb = {{0xA2, 0x2B, 0x80, 0x20, 0x42, 0x4A, 0x70, 0x49, 0x49, 0x52, 0x92, 0x67, - 0xB6, 0x21, 0xB3, 0xD7, 0x91, 0x19, 0xD7, 0x29, 0xB2, 0x38, 0x2C, 0xED, - 0x8B, 0x29, 0x6C, 0x3C, 0x02, 0x8F, 0xA9, 0x7D, 0x35, 0x0F, 0x6D, 0x07, - 0x81, 0x03, 0x06, 0x34, 0xD2, 0x82, 0x02, 0x03, 0xC8}}; + std::array cb = { + {0xA2, 0x2B, 0x80, 0x20, 0x42, 0x4A, 0x70, 0x49, 0x49, 0x52, 0x92, 0x67, + 0xB6, 0x21, 0xB3, 0xD7, 0x91, 0x19, 0xD7, 0x29, 0xB2, 0x38, 0x2C, 0xED, + 0x8B, 0x29, 0x6C, 0x3C, 0x02, 0x8F, 0xA9, 0x7D, 0x35, 0x0F, 0x6D, 0x07, + 0x81, 0x03, 0x06, 0x34, 0xD2, 0x82, 0x02, 0x03, 0xC8}}; // FIXME: this transaction should, eventually, return temDISABLED // instead of temMALFORMED. @@ -1060,7 +1093,8 @@ struct Escrow_test : public beast::unit_test::suite env(escrow::create(alice, alice, XRP(1000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 500s)); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const aa = env.le(keylet::escrow(alice.id(), aseq)); BEAST_EXPECT(aa); @@ -1074,7 +1108,8 @@ struct Escrow_test : public beast::unit_test::suite env(escrow::create(bruce, bruce, XRP(1000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 2s)); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const bb = env.le(keylet::escrow(bruce.id(), bseq)); BEAST_EXPECT(bb); @@ -1089,7 +1124,8 @@ struct Escrow_test : public beast::unit_test::suite env(escrow::finish(alice, alice, aseq)); { BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), aseq))); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 0); @@ -1104,7 +1140,8 @@ struct Escrow_test : public beast::unit_test::suite env(escrow::cancel(bruce, bruce, bseq)); { BEAST_EXPECT(!env.le(keylet::escrow(bruce.id(), bseq))); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); xrpl::Dir bod(*env.current(), keylet::ownerDir(bruce.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 0); @@ -1120,12 +1157,14 @@ struct Escrow_test : public beast::unit_test::suite auto const bseq = env.seq(bruce); env(escrow::create(alice, bruce, XRP(1000)), escrow::finish_time(env.now() + 1s)); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); env(escrow::create(bruce, carol, XRP(1000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 2s)); - BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); + BEAST_EXPECT( + (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const ab = env.le(keylet::escrow(alice.id(), aseq)); @@ -1205,8 +1244,12 @@ struct Escrow_test : public beast::unit_test::suite { auto const jtx = env.jt( - escrow::create("alice", "carol", XRP(1000)), escrow::finish_time(env.now() + 1s), seq(1), fee(baseFee)); - auto const pf = preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); + escrow::create("alice", "carol", XRP(1000)), + escrow::finish_time(env.now() + 1s), + seq(1), + fee(baseFee)); + auto const pf = + preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); BEAST_EXPECT(pf.ter == tesSUCCESS); BEAST_EXPECT(!pf.consequences.isBlocker()); BEAST_EXPECT(pf.consequences.fee() == drops(baseFee)); @@ -1215,7 +1258,8 @@ struct Escrow_test : public beast::unit_test::suite { auto const jtx = env.jt(escrow::cancel("bob", "alice", 3), seq(1), fee(baseFee)); - auto const pf = preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); + auto const pf = + preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); BEAST_EXPECT(pf.ter == tesSUCCESS); BEAST_EXPECT(!pf.consequences.isBlocker()); BEAST_EXPECT(pf.consequences.fee() == drops(baseFee)); @@ -1224,7 +1268,8 @@ struct Escrow_test : public beast::unit_test::suite { auto const jtx = env.jt(escrow::finish("bob", "alice", 3), seq(1), fee(baseFee)); - auto const pf = preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); + auto const pf = + preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); BEAST_EXPECT(pf.ter == tesSUCCESS); BEAST_EXPECT(!pf.consequences.isBlocker()); BEAST_EXPECT(pf.consequences.fee() == drops(baseFee)); @@ -1272,7 +1317,9 @@ struct Escrow_test : public beast::unit_test::suite auto const ts = env.now() + 97s; std::uint32_t const escrowSeq = aliceTicket; - env(escrow::create(alice, bob, XRP(1000)), escrow::finish_time(ts), ticket::use(aliceTicket)); + env(escrow::create(alice, bob, XRP(1000)), + escrow::finish_time(ts), + ticket::use(aliceTicket)); BEAST_EXPECT(env.seq(alice) == aliceRootSeq); env.require(tickets(alice, 0)); env.require(tickets(bob, bobTicketCount)); @@ -1289,10 +1336,15 @@ struct Escrow_test : public beast::unit_test::suite } // bob tries to re-use a ticket, which is rejected. - env(escrow::finish(bob, alice, escrowSeq), fee(150 * baseFee), ticket::use(bobTicket), ter(tefNO_TICKET)); + env(escrow::finish(bob, alice, escrowSeq), + fee(150 * baseFee), + ticket::use(bobTicket), + ter(tefNO_TICKET)); // bob uses one of his remaining tickets. Success! - env(escrow::finish(bob, alice, escrowSeq), fee(150 * baseFee), ticket::use(--bobTicket)); + env(escrow::finish(bob, alice, escrowSeq), + fee(150 * baseFee), + ticket::use(--bobTicket)); env.close(); BEAST_EXPECT(env.seq(bob) == bobRootSeq); } @@ -1354,7 +1406,9 @@ struct Escrow_test : public beast::unit_test::suite BEAST_EXPECT(env.seq(bob) == bobRootSeq); // Verify that the cancel succeeds. - env(escrow::cancel(bob, alice, escrowSeq), fee(150 * baseFee), ticket::use(bobTicket++)); + env(escrow::cancel(bob, alice, escrowSeq), + fee(150 * baseFee), + ticket::use(bobTicket++)); env.close(); BEAST_EXPECT(env.seq(bob) == bobRootSeq); @@ -1420,7 +1474,9 @@ struct Escrow_test : public beast::unit_test::suite env.close(); // Fail, credentials not accepted - env(escrow::finish(carol, alice, seq), credentials::ids({credIdx}), ter(tecBAD_CREDENTIALS)); + env(escrow::finish(carol, alice, seq), + credentials::ids({credIdx}), + ter(tecBAD_CREDENTIALS)); env.close(); @@ -1428,10 +1484,14 @@ struct Escrow_test : public beast::unit_test::suite env.close(); // Fail, credentials doesn’t belong to root account - env(escrow::finish(dillon, alice, seq), credentials::ids({credIdx}), ter(tecBAD_CREDENTIALS)); + env(escrow::finish(dillon, alice, seq), + credentials::ids({credIdx}), + ter(tecBAD_CREDENTIALS)); // Fail, no depositPreauth - env(escrow::finish(carol, alice, seq), credentials::ids({credIdx}), ter(tecNO_PERMISSION)); + env(escrow::finish(carol, alice, seq), + credentials::ids({credIdx}), + ter(tecNO_PERMISSION)); env(deposit::authCredentials(bob, {{zelda, credType}})); env.close(); @@ -1480,7 +1540,8 @@ struct Escrow_test : public beast::unit_test::suite env(credentials::accept(bob, zelda, credType2)); env.close(); auto const credIdxBob = - credentials::ledgerEntry(env, bob, zelda, credType2)[jss::result][jss::index].asString(); + credentials::ledgerEntry(env, bob, zelda, credType2)[jss::result][jss::index] + .asString(); auto const seq = env.seq(alice); env(escrow::create(alice, bob, XRP(1000)), escrow::finish_time(env.now() + 1s)); diff --git a/src/test/app/FeeVote_test.cpp b/src/test/app/FeeVote_test.cpp index 15dd385d65..360def1abf 100644 --- a/src/test/app/FeeVote_test.cpp +++ b/src/test/app/FeeVote_test.cpp @@ -2,7 +2,6 @@ #include #include -#include #include #include @@ -11,6 +10,7 @@ #include #include #include +#include namespace xrpl { namespace test { @@ -36,18 +36,24 @@ createFeeTx(Rules const& rules, std::uint32_t seq, FeeSettingsFields const& fiel if (rules.enabled(featureXRPFees)) { // New XRPFees format - all three fields are REQUIRED - obj.setFieldAmount(sfBaseFeeDrops, fields.baseFeeDrops ? *fields.baseFeeDrops : XRPAmount{0}); - obj.setFieldAmount(sfReserveBaseDrops, fields.reserveBaseDrops ? *fields.reserveBaseDrops : XRPAmount{0}); obj.setFieldAmount( - sfReserveIncrementDrops, fields.reserveIncrementDrops ? *fields.reserveIncrementDrops : XRPAmount{0}); + sfBaseFeeDrops, fields.baseFeeDrops ? *fields.baseFeeDrops : XRPAmount{0}); + obj.setFieldAmount( + sfReserveBaseDrops, + fields.reserveBaseDrops ? *fields.reserveBaseDrops : XRPAmount{0}); + obj.setFieldAmount( + sfReserveIncrementDrops, + fields.reserveIncrementDrops ? *fields.reserveIncrementDrops : XRPAmount{0}); } else { // Legacy format - all four fields are REQUIRED obj.setFieldU64(sfBaseFee, fields.baseFee ? *fields.baseFee : 0); obj.setFieldU32(sfReserveBase, fields.reserveBase ? *fields.reserveBase : 0); - obj.setFieldU32(sfReserveIncrement, fields.reserveIncrement ? *fields.reserveIncrement : 0); - obj.setFieldU32(sfReferenceFeeUnits, fields.referenceFeeUnits ? *fields.referenceFeeUnits : 0); + obj.setFieldU32( + sfReserveIncrement, fields.reserveIncrement ? *fields.reserveIncrement : 0); + obj.setFieldU32( + sfReferenceFeeUnits, fields.referenceFeeUnits ? *fields.referenceFeeUnits : 0); } }; return STTx(ttFEE, fill); @@ -112,7 +118,10 @@ applyFeeAndTestResult(jtx::Env& env, OpenView& view, STTx const& tx) } bool -verifyFeeObject(std::shared_ptr const& ledger, Rules const& rules, FeeSettingsFields const& expected) +verifyFeeObject( + std::shared_ptr const& ledger, + Rules const& rules, + FeeSettingsFields const& expected) { auto const feeObject = ledger->read(keylet::fees()); if (!feeObject) @@ -127,19 +136,22 @@ verifyFeeObject(std::shared_ptr const& ledger, Rules const& rules, if (rules.enabled(featureXRPFees)) { if (feeObject->isFieldPresent(sfBaseFee) || feeObject->isFieldPresent(sfReserveBase) || - feeObject->isFieldPresent(sfReserveIncrement) || feeObject->isFieldPresent(sfReferenceFeeUnits)) + feeObject->isFieldPresent(sfReserveIncrement) || + feeObject->isFieldPresent(sfReferenceFeeUnits)) return false; if (!checkEquality(sfBaseFeeDrops, expected.baseFeeDrops.value_or(XRPAmount{0}))) return false; if (!checkEquality(sfReserveBaseDrops, expected.reserveBaseDrops.value_or(XRPAmount{0}))) return false; - if (!checkEquality(sfReserveIncrementDrops, expected.reserveIncrementDrops.value_or(XRPAmount{0}))) + if (!checkEquality( + sfReserveIncrementDrops, expected.reserveIncrementDrops.value_or(XRPAmount{0}))) return false; } else { - if (feeObject->isFieldPresent(sfBaseFeeDrops) || feeObject->isFieldPresent(sfReserveBaseDrops) || + if (feeObject->isFieldPresent(sfBaseFeeDrops) || + feeObject->isFieldPresent(sfReserveBaseDrops) || feeObject->isFieldPresent(sfReserveIncrementDrops)) return false; @@ -186,7 +198,8 @@ class FeeVote_test : public beast::unit_test::suite } { Section config; - config.append({"reference_fee = 50", "account_reserve = 1234567", "owner_reserve = 1234"}); + config.append( + {"reference_fee = 50", "account_reserve = 1234567", "owner_reserve = 1234"}); auto setup = setup_FeeVote(config); BEAST_EXPECT(setup.reference_fee == 50); BEAST_EXPECT(setup.account_reserve == 1234567); @@ -194,7 +207,8 @@ class FeeVote_test : public beast::unit_test::suite } { Section config; - config.append({"reference_fee = blah", "account_reserve = yada", "owner_reserve = foo"}); + config.append( + {"reference_fee = blah", "account_reserve = yada", "owner_reserve = foo"}); // Illegal values are ignored, and the defaults left unchanged auto setup = setup_FeeVote(config); BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); @@ -203,7 +217,8 @@ class FeeVote_test : public beast::unit_test::suite } { Section config; - config.append({"reference_fee = -50", "account_reserve = -1234567", "owner_reserve = -1234"}); + config.append( + {"reference_fee = -50", "account_reserve = -1234567", "owner_reserve = -1234"}); // Illegal values are ignored, and the defaults left unchanged auto setup = setup_FeeVote(config); BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); @@ -211,10 +226,13 @@ class FeeVote_test : public beast::unit_test::suite BEAST_EXPECT(setup.owner_reserve == static_cast(-1234)); } { - auto const big64 = - std::to_string(static_cast(std::numeric_limits::max()) + 1); + auto const big64 = std::to_string( + static_cast(std::numeric_limits::max()) + 1); Section config; - config.append({"reference_fee = " + big64, "account_reserve = " + big64, "owner_reserve = " + big64}); + config.append( + {"reference_fee = " + big64, + "account_reserve = " + big64, + "owner_reserve = " + big64}); // Illegal values are ignored, and the defaults left unchanged auto setup = setup_FeeVote(config); BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); @@ -232,7 +250,10 @@ class FeeVote_test : public beast::unit_test::suite { jtx::Env env(*this, jtx::testable_amendments() - featureXRPFees); auto ledger = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + env.app().config(), + std::vector{}, + env.app().getNodeFamily()); // Create the next ledger to apply transaction to ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); @@ -240,7 +261,10 @@ class FeeVote_test : public beast::unit_test::suite // Test successful fee transaction with legacy fields FeeSettingsFields fields{ - .baseFee = 10, .reserveBase = 200000, .reserveIncrement = 50000, .referenceFeeUnits = 10}; + .baseFee = 10, + .reserveBase = 200000, + .reserveIncrement = 50000, + .referenceFeeUnits = 10}; auto feeTx = createFeeTx(ledger->rules(), ledger->seq(), fields); OpenView accum(ledger.get()); @@ -255,7 +279,10 @@ class FeeVote_test : public beast::unit_test::suite { jtx::Env env(*this, jtx::testable_amendments() | featureXRPFees); auto ledger = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + env.app().config(), + std::vector{}, + env.app().getNodeFamily()); // Create the next ledger to apply transaction to ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); @@ -284,7 +311,10 @@ class FeeVote_test : public beast::unit_test::suite { jtx::Env env(*this, jtx::testable_amendments() - featureXRPFees); auto ledger = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + env.app().config(), + std::vector{}, + env.app().getNodeFamily()); // Create the next ledger to apply transaction to ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); @@ -302,7 +332,10 @@ class FeeVote_test : public beast::unit_test::suite { jtx::Env env(*this, jtx::testable_amendments() | featureXRPFees); auto ledger = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + env.app().config(), + std::vector{}, + env.app().getNodeFamily()); // Create the next ledger to apply transaction to ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); @@ -452,7 +485,8 @@ class FeeVote_test : public beast::unit_test::suite ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); // Apply partial update (only some fields) - FeeSettingsFields fields2{.baseFeeDrops = XRPAmount{20}, .reserveBaseDrops = XRPAmount{200000}}; + FeeSettingsFields fields2{ + .baseFeeDrops = XRPAmount{20}, .reserveBaseDrops = XRPAmount{200000}}; auto feeTx2 = createFeeTx(ledger->rules(), ledger->seq(), fields2); { @@ -509,7 +543,10 @@ class FeeVote_test : public beast::unit_test::suite auto feeVote = make_FeeVote(setup, env.app().journal("FeeVote")); auto ledger = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + env.app().config(), + std::vector{}, + env.app().getNodeFamily()); auto sec = randomSecretKey(); auto pub = derivePublicKey(KeyType::secp256k1, sec); @@ -535,7 +572,10 @@ class FeeVote_test : public beast::unit_test::suite auto feeVote = make_FeeVote(setup, env.app().journal("FeeVote")); auto ledger = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + env.app().config(), + std::vector{}, + env.app().getNodeFamily()); auto sec = randomSecretKey(); auto pub = derivePublicKey(KeyType::secp256k1, sec); @@ -634,7 +674,8 @@ class FeeVote_test : public beast::unit_test::suite // 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(sfReserveIncrementDrops) == XRPAmount{setup.owner_reserve}); + BEAST_EXPECT( + feeTx.getFieldAmount(sfReserveIncrementDrops) == XRPAmount{setup.owner_reserve}); } void diff --git a/src/test/app/FixNFTokenPageLinks_test.cpp b/src/test/app/FixNFTokenPageLinks_test.cpp index 88f368e9cf..67dadac5e1 100644 --- a/src/test/app/FixNFTokenPageLinks_test.cpp +++ b/src/test/app/FixNFTokenPageLinks_test.cpp @@ -1,10 +1,9 @@ #include -#include -#include - #include #include +#include +#include namespace xrpl { @@ -40,7 +39,8 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // creation of NFT pages that are completely full. This lambda // tells us the taxon value we should pass in in order for the // internal representation to match the passed in value. - auto internalTaxon = [this, &env](Account const& acct, std::uint32_t taxon) -> std::uint32_t { + auto internalTaxon = [this, &env]( + Account const& acct, std::uint32_t taxon) -> std::uint32_t { std::uint32_t tokenSeq = [this, &env, &acct]() { auto const le = env.le(acct); if (BEAST_EXPECT(le)) @@ -86,7 +86,8 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite for (Json::UInt i = 0; i < acctObjs.size(); ++i) { if (BEAST_EXPECT( - acctObjs[i].isMember(sfNFTokens.jsonName) && acctObjs[i][sfNFTokens.jsonName].isArray())) + acctObjs[i].isMember(sfNFTokens.jsonName) && + acctObjs[i][sfNFTokens.jsonName].isArray())) { BEAST_EXPECT(acctObjs[i][sfNFTokens.jsonName].size() == 32); ++pageCount; @@ -138,7 +139,10 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // Invalid flags. auto const linkFixFee = drops(env.current()->fees().increment); - env(ledgerStateFix::nftPageLinks(alice, alice), fee(linkFixFee), txflags(tfPassive), ter(temINVALID_FLAG)); + env(ledgerStateFix::nftPageLinks(alice, alice), + fee(linkFixFee), + txflags(tfPassive), + ter(temINVALID_FLAG)); { // ledgerStateFix::nftPageLinks requires an Owner field. @@ -303,7 +307,8 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // bob's "middle" page is still present, but has lost the // NextPageMin field. { - auto bobMiddleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(bob), bobMiddleNFTokenPageIndex)); + auto bobMiddleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(bob), bobMiddleNFTokenPageIndex)); if (!BEAST_EXPECT(bobMiddleNFTokenPage)) return; @@ -352,7 +357,8 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // carol's "middle" page is still present, but has lost the // NextPageMin field. - auto carolMiddleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(carol), carolMiddleNFTokenPageIndex)); + auto carolMiddleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(carol), carolMiddleNFTokenPageIndex)); if (!BEAST_EXPECT(carolMiddleNFTokenPage)) return; @@ -453,7 +459,8 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite } // alice's middle page should be gone. - BEAST_EXPECT(!env.le(keylet::nftpage(keylet::nftpage_min(alice), aliceMiddleNFTokenPageIndex))); + BEAST_EXPECT( + !env.le(keylet::nftpage(keylet::nftpage_min(alice), aliceMiddleNFTokenPageIndex))); BEAST_EXPECT(nftCount(env, alice) == 32); BEAST_EXPECT(ownerCount(env, alice) == 1); @@ -469,7 +476,8 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // bob's "middle" page is still present and missing NextPageMin. { - auto bobMiddleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(bob), bobMiddleNFTokenPageIndex)); + auto bobMiddleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(bob), bobMiddleNFTokenPageIndex)); if (!BEAST_EXPECT(bobMiddleNFTokenPage)) return; @@ -493,8 +501,9 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite BEAST_EXPECT(bobLastNFTokenPage->at(sfPreviousPageMin) != bobMiddleNFTokenPageIndex); BEAST_EXPECT(!bobLastNFTokenPage->isFieldPresent(sfNextPageMin)); - auto const bobNewFirstNFTokenPage = - env.le(keylet::nftpage(keylet::nftpage_min(bob), bobLastNFTokenPage->at(sfPreviousPageMin))); + auto const bobNewFirstNFTokenPage = env.le( + keylet::nftpage( + keylet::nftpage_min(bob), bobLastNFTokenPage->at(sfPreviousPageMin))); if (!BEAST_EXPECT(bobNewFirstNFTokenPage)) return; @@ -562,8 +571,9 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite BEAST_EXPECT(!carolLastNFTokenPage->isFieldPresent(sfNextPageMin)); // carol also has a "first" page that includes a NextPageMin field. - auto carolFirstNFTokenPage = - env.le(keylet::nftpage(keylet::nftpage_min(carol), carolMiddleNFTokenPage->at(sfPreviousPageMin))); + auto carolFirstNFTokenPage = env.le( + keylet::nftpage( + keylet::nftpage_min(carol), carolMiddleNFTokenPage->at(sfPreviousPageMin))); if (!BEAST_EXPECT(carolFirstNFTokenPage)) return; diff --git a/src/test/app/Flow_test.cpp b/src/test/app/Flow_test.cpp index 551bd117d8..c56cef39f8 100644 --- a/src/test/app/Flow_test.cpp +++ b/src/test/app/Flow_test.cpp @@ -1,20 +1,24 @@ #include #include -#include -#include #include #include #include #include #include +#include +#include namespace xrpl { namespace test { bool -getNoRippleFlag(jtx::Env const& env, jtx::Account const& src, jtx::Account const& dst, Currency const& cur) +getNoRippleFlag( + jtx::Env const& env, + jtx::Account const& src, + jtx::Account const& dst, + Currency const& cur) { if (auto sle = env.le(keylet::line(src, dst, cur))) { @@ -104,7 +108,10 @@ struct Flow_test : public beast::unit_test::suite // alice will redeem to bob; a transfer fee will be charged env(pay(bob, alice, USDB(6))); - env(pay(alice, dan, USDC(5)), path(bob, carol), sendmax(USDA(6)), txflags(tfNoRippleDirect)); + env(pay(alice, dan, USDC(5)), + path(bob, carol), + sendmax(USDA(6)), + txflags(tfNoRippleDirect)); env.require(balance(dan, USDC(5))); env.require(balance(alice, USDB(0.5))); } @@ -120,7 +127,10 @@ struct Flow_test : public beast::unit_test::suite env.trust(USDC(10), dan); env(rate(bob, 1.1)); - env(pay(alice, dan, USDC(5)), path(bob, carol), sendmax(USDA(6)), txflags(tfNoRippleDirect)); + env(pay(alice, dan, USDC(5)), + path(bob, carol), + sendmax(USDA(6)), + txflags(tfNoRippleDirect)); env.require(balance(dan, USDC(5))); env.require(balance(bob, USDA(5))); } @@ -140,7 +150,10 @@ struct Flow_test : public beast::unit_test::suite // Pay alice so she redeems to carol and a transfer fee is charged env(pay(carol, alice, USDC(10))); - env(pay(alice, erin, USDD(5)), path(carol, dan), path(bob, dan), txflags(tfNoRippleDirect)); + env(pay(alice, erin, USDD(5)), + path(carol, dan), + path(bob, dan), + txflags(tfNoRippleDirect)); env.require(balance(erin, USDD(5))); env.require(balance(dan, USDB(5))); @@ -194,10 +207,14 @@ struct Flow_test : public beast::unit_test::suite env(pay(alice, bob, USDA(100))); env.require(balance(bob, USDA(100))); - env(pay(dan, carol, USDA(10)), path(bob), sendmax(USDD(100)), txflags(tfNoRippleDirect)); + env(pay(dan, carol, USDA(10)), + path(bob), + sendmax(USDD(100)), + txflags(tfNoRippleDirect)); env.require(balance(bob, USDA(90))); if (bobAliceQOut > bobDanQIn) - env.require(balance(bob, USDD(10.0 * double(bobAliceQOut) / double(bobDanQIn)))); + env.require( + balance(bob, USDD(10.0 * double(bobAliceQOut) / double(bobDanQIn)))); else env.require(balance(bob, USDD(10))); env.require(balance(carol, USDA(10))); @@ -519,7 +536,8 @@ struct Flow_test : public beast::unit_test::suite bookDirStr.erase(0, 48); return std::stoull(bookDirStr, nullptr, 16); }(); - std::uint64_t const actualRate = getRate(usdOffer->at(sfTakerGets), usdOffer->at(sfTakerPays)); + std::uint64_t const actualRate = + getRate(usdOffer->at(sfTakerGets), usdOffer->at(sfTakerPays)); // We expect the actual rate of the offer to be worse // (larger) than the rate of the book page holding the @@ -824,7 +842,10 @@ struct Flow_test : public beast::unit_test::suite // Consuming the offer changes the owner count, which could also cause // liquidity to decrease in the forward pass auto const toSend = consumeOffer ? USD(10) : USD(9); - env(pay(alice, alice, toSend), path(~USD), sendmax(XRP(20000)), txflags(tfPartialPayment | tfNoRippleDirect)); + env(pay(alice, alice, toSend), + path(~USD), + sendmax(XRP(20000)), + txflags(tfPartialPayment | tfNoRippleDirect)); } void @@ -850,7 +871,10 @@ struct Flow_test : public beast::unit_test::suite STAmount tinyAmt3{USD.issue(), 9000000000000003ll, -17, false, STAmount::unchecked{}}; env(offer(gw, drops(9000000000), tinyAmt3)); - env(pay(alice, bob, tinyAmt1), path(~USD), sendmax(drops(9000000000)), txflags(tfNoRippleDirect)); + env(pay(alice, bob, tinyAmt1), + path(~USD), + sendmax(drops(9000000000)), + txflags(tfNoRippleDirect)); BEAST_EXPECT(!isOffer(env, gw, XRP(0), USD(0))); } @@ -873,7 +897,10 @@ struct Flow_test : public beast::unit_test::suite env(pay(gw, alice, tinyAmt1)); env(offer(gw, tinyAmt3, drops(9000000000))); - env(pay(alice, bob, drops(9000000000)), path(~XRP), sendmax(USD(1)), txflags(tfNoRippleDirect)); + env(pay(alice, bob, drops(9000000000)), + path(~XRP), + sendmax(USD(1)), + txflags(tfNoRippleDirect)); BEAST_EXPECT(!isOffer(env, gw, USD(0), XRP(0))); } @@ -930,7 +957,10 @@ struct Flow_test : public beast::unit_test::suite STAmount{USD.issue(), std::uint64_t(1700000000000000ull), -14, false}, XRP(.001))); - env(pay(alice, bob, XRP(10000)), path(~XRP), sendmax(USD(100)), txflags(tfPartialPayment | tfNoRippleDirect)); + env(pay(alice, bob, XRP(10000)), + path(~XRP), + sendmax(USD(100)), + txflags(tfPartialPayment | tfNoRippleDirect)); } void diff --git a/src/test/app/Freeze_test.cpp b/src/test/app/Freeze_test.cpp index 9d7db52e56..6f89163c04 100644 --- a/src/test/app/Freeze_test.cpp +++ b/src/test/app/Freeze_test.cpp @@ -73,7 +73,8 @@ class Freeze_test : public beast::unit_test::suite if (!BEAST_EXPECT(checkArraySize(affected, 2u))) return; auto ff = affected[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; - BEAST_EXPECT(ff[sfLowLimit.fieldName] == G1["USD"](0).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + ff[sfLowLimit.fieldName] == G1["USD"](0).value().getJson(JsonOptions::none)); BEAST_EXPECT(ff[jss::Flags].asUInt() & lsfLowFreeze); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfHighFreeze)); env.close(); @@ -87,8 +88,10 @@ class Freeze_test : public beast::unit_test::suite if (!BEAST_EXPECT(checkArraySize(affected, 5u))) return; auto ff = affected[3u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; - BEAST_EXPECT(ff[sfHighLimit.fieldName] == bob["USD"](100).value().getJson(JsonOptions::none)); - auto amt = STAmount{Issue{to_currency("USD"), noAccount()}, -15}.value().getJson(JsonOptions::none); + BEAST_EXPECT( + ff[sfHighLimit.fieldName] == bob["USD"](100).value().getJson(JsonOptions::none)); + auto amt = STAmount{Issue{to_currency("USD"), noAccount()}, -15}.value().getJson( + JsonOptions::none); BEAST_EXPECT(ff[sfBalance.fieldName] == amt); env.close(); } @@ -149,7 +152,8 @@ class Freeze_test : public beast::unit_test::suite if (!BEAST_EXPECT(checkArraySize(affected, 2u))) return; auto ff = affected[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; - BEAST_EXPECT(ff[sfLowLimit.fieldName] == G1["USD"](0).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + ff[sfLowLimit.fieldName] == G1["USD"](0).value().getJson(JsonOptions::none)); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfLowFreeze)); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfHighFreeze)); env.close(); @@ -320,7 +324,8 @@ class Freeze_test : public beast::unit_test::suite env(trust(G1, A1["USD"](0), tfSetFreeze | tfClearFreeze), ter(tecNO_PERMISSION)); env(trust(G1, A1["USD"](0), tfSetFreeze | tfClearDeepFreeze), ter(tecNO_PERMISSION)); env(trust(G1, A1["USD"](0), tfSetDeepFreeze | tfClearFreeze), ter(tecNO_PERMISSION)); - env(trust(G1, A1["USD"](0), tfSetDeepFreeze | tfClearDeepFreeze), ter(tecNO_PERMISSION)); + env(trust(G1, A1["USD"](0), tfSetDeepFreeze | tfClearDeepFreeze), + ter(tecNO_PERMISSION)); } else { @@ -388,7 +393,8 @@ class Freeze_test : public beast::unit_test::suite { // Account without GlobalFreeze (proving operations normally work) // test: visible offers where taker_pays is unfrozen issuer - auto offers = env.rpc("book_offers", std::string("USD/") + G1.human(), "XRP")[jss::result][jss::offers]; + auto offers = env.rpc( + "book_offers", std::string("USD/") + G1.human(), "XRP")[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 2u))) return; std::set accounts; @@ -400,7 +406,8 @@ class Freeze_test : public beast::unit_test::suite BEAST_EXPECT(accounts.find(G1.human()) != std::end(accounts)); // test: visible offers where taker_gets is unfrozen issuer - offers = env.rpc("book_offers", "XRP", std::string("USD/") + G1.human())[jss::result][jss::offers]; + offers = env.rpc( + "book_offers", "XRP", std::string("USD/") + G1.human())[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 2u))) return; accounts.clear(); @@ -458,11 +465,13 @@ class Freeze_test : public beast::unit_test::suite // test: book_offers shows offers // (should these actually be filtered?) - offers = env.rpc("book_offers", "XRP", std::string("USD/") + G1.human())[jss::result][jss::offers]; + offers = env.rpc( + "book_offers", "XRP", std::string("USD/") + G1.human())[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 2u))) return; - offers = env.rpc("book_offers", std::string("USD/") + G1.human(), "XRP")[jss::result][jss::offers]; + offers = env.rpc( + "book_offers", std::string("USD/") + G1.human(), "XRP")[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 2u))) return; } @@ -629,7 +638,8 @@ class Freeze_test : public beast::unit_test::suite auto offers = getAccountOffers(env, A3)[jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 1u))) return; - BEAST_EXPECT(offers[0u][jss::taker_gets] == G1["USD"](999).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + offers[0u][jss::taker_gets] == G1["USD"](999).value().getJson(JsonOptions::none)); // test: someone else creates an offer providing liquidity env(offer(A4, XRP(999), G1["USD"](999))); @@ -950,11 +960,19 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 cannot send USD using XRP through A2 offer - env(pay(A1, G1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); + env(pay(A1, G1, USD(10)), + path(~USD), + sendmax(XRP(11)), + txflags(tfNoRippleDirect), + ter(tecPATH_PARTIAL)); env.close(); // test: G1 cannot send USD using XRP through A2 offer - env(pay(G1, A1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); + env(pay(G1, A1, USD(10)), + path(~USD), + sendmax(XRP(11)), + txflags(tfNoRippleDirect), + ter(tecPATH_PARTIAL)); env.close(); env(trust(G1, A2["USD"](0), tfClearFreeze)); @@ -968,11 +986,19 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 cannot send USD using XRP through A2 offer - env(pay(A1, G1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); + env(pay(A1, G1, USD(10)), + path(~USD), + sendmax(XRP(11)), + txflags(tfNoRippleDirect), + ter(tecPATH_PARTIAL)); env.close(); // test: G1 cannot send USD using XRP through A2 offer - env(pay(G1, A1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); + env(pay(G1, A1, USD(10)), + path(~USD), + sendmax(XRP(11)), + txflags(tfNoRippleDirect), + ter(tecPATH_PARTIAL)); env.close(); env(trust(G1, A2["USD"](0), tfClearFreeze | tfClearDeepFreeze)); @@ -1005,11 +1031,19 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 cannot send USD using XRP through A2 offer - env(pay(A1, G1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); + env(pay(A1, G1, USD(10)), + path(~USD), + sendmax(XRP(11)), + txflags(tfNoRippleDirect), + ter(tecPATH_PARTIAL)); env.close(); // test: G1 cannot send USD using XRP through A2 offer - env(pay(G1, A1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); + env(pay(G1, A1, USD(10)), + path(~USD), + sendmax(XRP(11)), + txflags(tfNoRippleDirect), + ter(tecPATH_PARTIAL)); env.close(); env(trust(A2, limit, tfClearFreeze | tfClearDeepFreeze)); @@ -1049,11 +1083,19 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 cannot send XRP using USD through A2 offer - env(pay(A1, G1, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); + env(pay(A1, G1, XRP(10)), + path(~XRP), + sendmax(USD(11)), + txflags(tfNoRippleDirect), + ter(tecPATH_PARTIAL)); env.close(); // test: G1 cannot send XRP using USD through A2 offer - env(pay(G1, A1, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); + env(pay(G1, A1, XRP(10)), + path(~XRP), + sendmax(USD(11)), + txflags(tfNoRippleDirect), + ter(tecPATH_PARTIAL)); env.close(); env(trust(G1, A2["USD"](0), tfClearFreeze | tfClearDeepFreeze)); @@ -1086,11 +1128,19 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 cannot send XRP using USD through A2 offer - env(pay(A1, G1, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); + env(pay(A1, G1, XRP(10)), + path(~XRP), + sendmax(USD(11)), + txflags(tfNoRippleDirect), + ter(tecPATH_PARTIAL)); env.close(); // test: G1 cannot send XRP using USD through A2 offer - env(pay(G1, A1, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); + env(pay(G1, A1, XRP(10)), + path(~XRP), + sendmax(USD(11)), + txflags(tfNoRippleDirect), + ter(tecPATH_PARTIAL)); env.close(); env(trust(A2, limit, tfClearFreeze | tfClearDeepFreeze)); @@ -1556,7 +1606,11 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: cannot use USD to make payment - env(pay(A1, A2, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect), ter(tecPATH_DRY)); + env(pay(A1, A2, XRP(10)), + path(~XRP), + sendmax(USD(11)), + txflags(tfNoRippleDirect), + ter(tecPATH_DRY)); env.close(); // test: can still receive USD payments. @@ -1583,11 +1637,19 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: cannot use USD to make payment - env(pay(A1, A2, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect), ter(tecPATH_DRY)); + env(pay(A1, A2, XRP(10)), + path(~XRP), + sendmax(USD(11)), + txflags(tfNoRippleDirect), + ter(tecPATH_DRY)); env.close(); // test: cannot receive USD payments. - env(pay(A2, A1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect), ter(tecPATH_DRY)); + env(pay(A2, A1, USD(10)), + path(~USD), + sendmax(XRP(11)), + txflags(tfNoRippleDirect), + ter(tecPATH_DRY)); env.close(); // test: can still receive XRP payments. @@ -1784,7 +1846,9 @@ class Freeze_test : public beast::unit_test::suite env(token::createOffer(A1, nftID, USD(11)), token::owner(A2)); env.close(); - env(token::brokerOffers(broker, buyIdx, sellIdx), token::brokerFee(USD(1)), ter(tecFROZEN)); + env(token::brokerOffers(broker, buyIdx, sellIdx), + token::brokerFee(USD(1)), + ter(tecFROZEN)); env.close(); } @@ -1819,7 +1883,11 @@ class Freeze_test : public beast::unit_test::suite // Helper function to extract trustline flags from open ledger uint32_t - getTrustlineFlags(test::jtx::Env& env, size_t expectedArraySize, size_t expectedArrayIndex, bool modified = true) + getTrustlineFlags( + test::jtx::Env& env, + size_t expectedArraySize, + size_t expectedArrayIndex, + bool modified = true) { using namespace test::jtx; auto const affected = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; @@ -1828,10 +1896,14 @@ class Freeze_test : public beast::unit_test::suite if (modified) { - return affected[expectedArrayIndex][sfModifiedNode.fieldName][sfFinalFields.fieldName][jss::Flags].asUInt(); + return affected[expectedArrayIndex][sfModifiedNode.fieldName][sfFinalFields.fieldName] + [jss::Flags] + .asUInt(); } - return affected[expectedArrayIndex][sfCreatedNode.fieldName][sfNewFields.fieldName][jss::Flags].asUInt(); + return affected[expectedArrayIndex][sfCreatedNode.fieldName][sfNewFields.fieldName] + [jss::Flags] + .asUInt(); } // Helper function that returns the index of the next check on account @@ -1842,7 +1914,10 @@ class Freeze_test : public beast::unit_test::suite } uint256 - createNFTSellOffer(test::jtx::Env& env, test::jtx::Account const& account, test::jtx::PrettyAmount const& currency) + createNFTSellOffer( + test::jtx::Env& env, + test::jtx::Account const& account, + test::jtx::PrettyAmount const& currency) { using namespace test::jtx; uint256 const nftID{token::getNextID(env, account, 0u, tfTransferable)}; diff --git a/src/test/app/HashRouter_test.cpp b/src/test/app/HashRouter_test.cpp index 03bb28e35a..753922a67d 100644 --- a/src/test/app/HashRouter_test.cpp +++ b/src/test/app/HashRouter_test.cpp @@ -1,8 +1,9 @@ -#include +#include #include #include #include +#include namespace xrpl { namespace test { diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index 7558c951b0..a01026c8ef 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -2,9 +2,6 @@ #include #include -#include -#include - #include #include #include @@ -17,6 +14,8 @@ #include #include #include +#include +#include #include @@ -29,17 +28,20 @@ class Invariants_test : public beast::unit_test::suite // on the ledger after creating two accounts, but before closing it, and // before the Precheck function. These should only be valid functions, and // not direct manipulations. Preclose is not commonly used. - using Preclose = std::function; + using Preclose = std::function< + bool(test::jtx::Account const& a, test::jtx::Account const& b, test::jtx::Env& env)>; // this is common setup/method for running a failing invariant check. The // precheck function is used to manipulate the ApplyContext with view // changes that will cause the check to fail. - using Precheck = std::function; + using Precheck = std::function< + bool(test::jtx::Account const& a, test::jtx::Account const& b, ApplyContext& ac)>; static FeatureBitset defaultAmendments() { - return xrpl::test::jtx::testable_amendments() | featureInvariantsV1_1 | featureSingleAssetVault; + return xrpl::test::jtx::testable_amendments() | featureInvariantsV1_1 | + featureSingleAssetVault; } /** Run a specific test case to put the ledger into a state that will be @@ -70,7 +72,14 @@ class Invariants_test : public beast::unit_test::suite TxAccount setTxAccount = TxAccount::None) { return doInvariantCheck( - test::jtx::Env(*this, defaultAmendments()), expect_logs, precheck, fee, tx, ters, preclose, setTxAccount); + test::jtx::Env(*this, defaultAmendments()), + expect_logs, + precheck, + fee, + tx, + ters, + preclose, + setTxAccount); } void @@ -152,7 +161,8 @@ class Invariants_test : public beast::unit_test::suite using namespace test::jtx; testcase << "XRP created"; doInvariantCheck( - {{"XRP net change was positive: 500"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + {{"XRP net change was positive: 500"}}, + [](Account const& A1, Account const&, ApplyContext& ac) { // put a single account in the view and "manufacture" some XRP auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) @@ -171,18 +181,20 @@ class Invariants_test : public beast::unit_test::suite testcase << "account root removed"; // An account was deleted, but not by an AccountDelete transaction. - doInvariantCheck({{"an account root was deleted"}}, [](Account const& A1, Account const&, ApplyContext& ac) { - // remove an account from the view - auto sle = ac.view().peek(keylet::account(A1.id())); - if (!sle) - return false; - // Clear the balance so the "account deletion left behind a - // non-zero balance" check doesn't trip earlier than the desired - // check. - sle->at(sfBalance) = beast::zero; - ac.view().erase(sle); - return true; - }); + doInvariantCheck( + {{"an account root was deleted"}}, + [](Account const& A1, Account const&, ApplyContext& ac) { + // remove an account from the view + auto sle = ac.view().peek(keylet::account(A1.id())); + if (!sle) + return false; + // Clear the balance so the "account deletion left behind a + // non-zero balance" check doesn't trip earlier than the desired + // check. + sle->at(sfBalance) = beast::zero; + ac.view().erase(sle); + return true; + }); // Successful AccountDelete transaction that didn't delete an account. // @@ -379,7 +391,8 @@ class Invariants_test : public beast::unit_test::suite BEAST_EXPECT(sle->at(~sfAMMID)); BEAST_EXPECT(sle->at(~sfAMMID) == ammKey); - for (auto const& trustKeylet : {keylet::line(ammAcctID, A1["USD"]), keylet::line(A1, ammIssue)}) + for (auto const& trustKeylet : + {keylet::line(ammAcctID, A1["USD"]), keylet::line(A1, ammIssue)}) { if (auto const line = ac.view().peek(trustKeylet); !line) { @@ -390,8 +403,12 @@ class Invariants_test : public beast::unit_test::suite STAmount const lowLimit = line->at(sfLowLimit); STAmount const highLimit = line->at(sfHighLimit); BEAST_EXPECT( - trustDelete(ac.view(), line, lowLimit.getIssuer(), highLimit.getIssuer(), ac.journal) == - tesSUCCESS); + trustDelete( + ac.view(), + line, + lowLimit.getIssuer(), + highLimit.getIssuer(), + ac.journal) == tesSUCCESS); } } @@ -400,8 +417,10 @@ class Invariants_test : public beast::unit_test::suite return false; auto const ownerDirKeylet = keylet::ownerDir(ammAcctID); - BEAST_EXPECT(ac.view().dirRemove(ownerDirKeylet, ammSle->at(sfOwnerNode), ammKey, false)); - BEAST_EXPECT(!ac.view().exists(ownerDirKeylet) || ac.view().emptyDirDelete(ownerDirKeylet)); + BEAST_EXPECT( + ac.view().dirRemove(ownerDirKeylet, ammSle->at(sfOwnerNode), ammKey, false)); + BEAST_EXPECT( + !ac.view().exists(ownerDirKeylet) || ac.view().emptyDirDelete(ownerDirKeylet)); // Clear the balance so the "account deletion left behind a // non-zero balance" check doesn't trip earlier than the desired @@ -444,7 +463,8 @@ class Invariants_test : public beast::unit_test::suite }); doInvariantCheck( - {{"invalid ledger entry type added"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + {{"invalid ledger entry type added"}}, + [](Account const& A1, Account const&, ApplyContext& ac) { // add an entry in the table with an SLE of an invalid type auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) @@ -453,7 +473,8 @@ class Invariants_test : public beast::unit_test::suite // make a dummy escrow ledger entry, then change the type to an // unsupported value so that the valid type invariant check // will fail. - auto const sleNew = std::make_shared(keylet::escrow(A1, (*sle)[sfSequence] + 2)); + auto const sleNew = + std::make_shared(keylet::escrow(A1, (*sle)[sfSequence] + 2)); // We don't use ltNICKNAME directly since it's marked deprecated // to prevent accidental use elsewhere. @@ -469,9 +490,11 @@ class Invariants_test : public beast::unit_test::suite using namespace test::jtx; testcase << "trust lines with XRP not allowed"; doInvariantCheck( - {{"an XRP trust line was created"}}, [](Account const& A1, Account const& A2, ApplyContext& ac) { + {{"an XRP trust line was created"}}, + [](Account const& A1, Account const& A2, ApplyContext& ac) { // create simple trust SLE with xrp currency - auto const sleNew = std::make_shared(keylet::line(A1, A2, xrpIssue().currency)); + auto const sleNew = + std::make_shared(keylet::line(A1, A2, xrpIssue().currency)); ac.view().insert(sleNew); return true; }); @@ -594,17 +617,20 @@ class Invariants_test : public beast::unit_test::suite return true; }; - auto const changeBalances = - [&](Account const& A1, Account const& A2, ApplyContext& ac, int A1Balance, int A2Balance) { - auto const sleA1 = ac.view().peek(keylet::line(A1, G1["USD"])); - auto const sleA2 = ac.view().peek(keylet::line(A2, G1["USD"])); + auto const changeBalances = [&](Account const& A1, + Account const& A2, + ApplyContext& ac, + int A1Balance, + int A2Balance) { + auto const sleA1 = ac.view().peek(keylet::line(A1, G1["USD"])); + auto const sleA2 = ac.view().peek(keylet::line(A2, G1["USD"])); - sleA1->setFieldAmount(sfBalance, G1["USD"](A1Balance)); - sleA2->setFieldAmount(sfBalance, G1["USD"](A2Balance)); + sleA1->setFieldAmount(sfBalance, G1["USD"](A1Balance)); + sleA2->setFieldAmount(sfBalance, G1["USD"](A2Balance)); - ac.view().update(sleA1); - ac.view().update(sleA2); - }; + ac.view().update(sleA1); + ac.view().update(sleA2); + }; // test: imitating frozen A1 making a payment to A2. doInvariantCheck( @@ -678,7 +704,8 @@ class Invariants_test : public beast::unit_test::suite }); doInvariantCheck( - {{"incorrect account XRP balance"}, {"XRP net change of -1000000001 doesn't match fee 0"}}, + {{"incorrect account XRP balance"}, + {"XRP net change of -1000000001 doesn't match fee 0"}}, [this](Account const& A1, Account const&, ApplyContext& ac) { // balance is negative auto const sle = ac.view().peek(keylet::account(A1.id())); @@ -710,7 +737,8 @@ class Invariants_test : public beast::unit_test::suite XRPAmount{INITIAL_XRP}); doInvariantCheck( - {{"fee paid is 20 exceeds fee specified in transaction."}, {"XRP net change of 0 doesn't match fee 20"}}, + {{"fee paid is 20 exceeds fee specified in transaction."}, + {"XRP net change of 0 doesn't match fee 20"}}, [](Account const&, Account const&, ApplyContext&) { return true; }, XRPAmount{20}, STTx{ttACCOUNT_SET, [](STObject& tx) { tx.setFieldAmount(sfFee, XRPAmount{10}); }}); @@ -722,46 +750,49 @@ class Invariants_test : public beast::unit_test::suite using namespace test::jtx; testcase << "no bad offers"; - doInvariantCheck({{"offer with a bad amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { - // offer with negative takerpays - auto const sle = ac.view().peek(keylet::account(A1.id())); - if (!sle) - return false; - auto sleNew = std::make_shared(keylet::offer(A1.id(), (*sle)[sfSequence])); - sleNew->setAccountID(sfAccount, A1.id()); - sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]); - sleNew->setFieldAmount(sfTakerPays, XRP(-1)); - ac.view().insert(sleNew); - return true; - }); + doInvariantCheck( + {{"offer with a bad amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + // offer with negative takerpays + auto const sle = ac.view().peek(keylet::account(A1.id())); + if (!sle) + return false; + auto sleNew = std::make_shared(keylet::offer(A1.id(), (*sle)[sfSequence])); + sleNew->setAccountID(sfAccount, A1.id()); + sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]); + sleNew->setFieldAmount(sfTakerPays, XRP(-1)); + ac.view().insert(sleNew); + return true; + }); - doInvariantCheck({{"offer with a bad amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { - // offer with negative takergets - auto const sle = ac.view().peek(keylet::account(A1.id())); - if (!sle) - return false; - auto sleNew = std::make_shared(keylet::offer(A1.id(), (*sle)[sfSequence])); - sleNew->setAccountID(sfAccount, A1.id()); - sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]); - sleNew->setFieldAmount(sfTakerPays, A1["USD"](10)); - sleNew->setFieldAmount(sfTakerGets, XRP(-1)); - ac.view().insert(sleNew); - return true; - }); + doInvariantCheck( + {{"offer with a bad amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + // offer with negative takergets + auto const sle = ac.view().peek(keylet::account(A1.id())); + if (!sle) + return false; + auto sleNew = std::make_shared(keylet::offer(A1.id(), (*sle)[sfSequence])); + sleNew->setAccountID(sfAccount, A1.id()); + sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]); + sleNew->setFieldAmount(sfTakerPays, A1["USD"](10)); + sleNew->setFieldAmount(sfTakerGets, XRP(-1)); + ac.view().insert(sleNew); + return true; + }); - doInvariantCheck({{"offer with a bad amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { - // offer XRP to XRP - auto const sle = ac.view().peek(keylet::account(A1.id())); - if (!sle) - return false; - auto sleNew = std::make_shared(keylet::offer(A1.id(), (*sle)[sfSequence])); - sleNew->setAccountID(sfAccount, A1.id()); - sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]); - sleNew->setFieldAmount(sfTakerPays, XRP(10)); - sleNew->setFieldAmount(sfTakerGets, XRP(11)); - ac.view().insert(sleNew); - return true; - }); + doInvariantCheck( + {{"offer with a bad amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + // offer XRP to XRP + auto const sle = ac.view().peek(keylet::account(A1.id())); + if (!sle) + return false; + auto sleNew = std::make_shared(keylet::offer(A1.id(), (*sle)[sfSequence])); + sleNew->setAccountID(sfAccount, A1.id()); + sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]); + sleNew->setFieldAmount(sfTakerPays, XRP(10)); + sleNew->setFieldAmount(sfTakerGets, XRP(11)); + ac.view().insert(sleNew); + return true; + }); } void @@ -771,7 +802,8 @@ class Invariants_test : public beast::unit_test::suite testcase << "no zero escrow"; doInvariantCheck( - {{"XRP net change of -1000000 doesn't match fee 0"}, {"escrow specifies invalid amount"}}, + {{"XRP net change of -1000000 doesn't match fee 0"}, + {"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // escrow with negative amount auto const sle = ac.view().peek(keylet::account(A1.id())); @@ -784,7 +816,8 @@ class Invariants_test : public beast::unit_test::suite }); doInvariantCheck( - {{"XRP net change was positive: 100000000000000001"}, {"escrow specifies invalid amount"}}, + {{"XRP net change was positive: 100000000000000001"}, + {"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // escrow with too-large amount auto const sle = ac.view().peek(keylet::account(A1.id())); @@ -800,7 +833,8 @@ class Invariants_test : public beast::unit_test::suite // IOU < 0 doInvariantCheck( - {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, + [](Account const& A1, Account const&, ApplyContext& ac) { // escrow with too-little iou auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) @@ -816,7 +850,8 @@ class Invariants_test : public beast::unit_test::suite // IOU bad currency doInvariantCheck( - {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, + [](Account const& A1, Account const&, ApplyContext& ac) { // escrow with bad iou currency auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) @@ -832,7 +867,8 @@ class Invariants_test : public beast::unit_test::suite // MPT < 0 doInvariantCheck( - {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, + [](Account const& A1, Account const&, ApplyContext& ac) { // escrow with too-little mpt auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) @@ -848,7 +884,8 @@ class Invariants_test : public beast::unit_test::suite // MPT OutstandingAmount < 0 doInvariantCheck( - {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, + [](Account const& A1, Account const&, ApplyContext& ac) { // mptissuance outstanding is negative auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) @@ -863,7 +900,8 @@ class Invariants_test : public beast::unit_test::suite // MPT LockedAmount < 0 doInvariantCheck( - {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, + [](Account const& A1, Account const&, ApplyContext& ac) { // mptissuance locked is less than locked auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) @@ -878,7 +916,8 @@ class Invariants_test : public beast::unit_test::suite // MPT OutstandingAmount < LockedAmount doInvariantCheck( - {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, + [](Account const& A1, Account const&, ApplyContext& ac) { // mptissuance outstanding is less than locked auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) @@ -894,7 +933,8 @@ class Invariants_test : public beast::unit_test::suite // MPT MPTAmount < 0 doInvariantCheck( - {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, + [](Account const& A1, Account const&, ApplyContext& ac) { // mptoken amount is negative auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) @@ -909,7 +949,8 @@ class Invariants_test : public beast::unit_test::suite // MPT LockedAmount < 0 doInvariantCheck( - {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, + [](Account const& A1, Account const&, ApplyContext& ac) { // mptoken locked amount is negative auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) @@ -929,15 +970,17 @@ class Invariants_test : public beast::unit_test::suite using namespace test::jtx; testcase << "valid new account root"; - doInvariantCheck({{"account root created illegally"}}, [](Account const&, Account const&, ApplyContext& ac) { - // Insert a new account root created by a non-payment into - // the view. - Account const A3{"A3"}; - Keylet const acctKeylet = keylet::account(A3); - auto const sleNew = std::make_shared(acctKeylet); - ac.view().insert(sleNew); - return true; - }); + doInvariantCheck( + {{"account root created illegally"}}, + [](Account const&, Account const&, ApplyContext& ac) { + // Insert a new account root created by a non-payment into + // the view. + Account const A3{"A3"}; + Keylet const acctKeylet = keylet::account(A3); + auto const sleNew = std::make_shared(acctKeylet); + ac.view().insert(sleNew); + return true; + }); doInvariantCheck( {{"multiple accounts created in a single transaction"}}, @@ -980,7 +1023,8 @@ class Invariants_test : public beast::unit_test::suite auto const sleNew = std::make_shared(acctKeylet); sleNew->setFieldU32(sfSequence, 0); sleNew->setFieldH256(sfAMMID, uint256(1)); - sleNew->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDefaultRipple); + sleNew->setFieldU32( + sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDefaultRipple); ac.view().insert(sleNew); return true; }, @@ -1025,7 +1069,9 @@ class Invariants_test : public beast::unit_test::suite auto const sleNew = std::make_shared(acctKeylet); sleNew->setFieldU32(sfSequence, 0); sleNew->setFieldH256(sfAMMID, uint256(1)); - sleNew->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth | lsfRequireDestTag); + sleNew->setFieldU32( + sfFlags, + lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth | lsfRequireDestTag); ac.view().insert(sleNew); return true; }, @@ -1040,9 +1086,11 @@ class Invariants_test : public beast::unit_test::suite testcase << "NFTokenPage"; // lambda that returns an STArray of NFTokenIDs. - uint256 const firstNFTID("0000000000000000000000000000000000000001FFFFFFFFFFFFFFFF00000000"); + uint256 const firstNFTID( + "0000000000000000000000000000000000000001FFFFFFFFFFFFFFFF00000000"); auto makeNFTokenIDs = [&firstNFTID](unsigned int nftCount) { - SOTemplate const* nfTokenTemplate = InnerObjectFormats::getInstance().findSOTemplateBySField(sfNFToken); + SOTemplate const* nfTokenTemplate = + InnerObjectFormats::getInstance().findSOTemplateBySField(sfNFToken); uint256 nftID(firstNFTID); STArray ret; @@ -1058,7 +1106,8 @@ class Invariants_test : public beast::unit_test::suite }; doInvariantCheck( - {{"NFT page has invalid size"}}, [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { + {{"NFT page has invalid size"}}, + [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { auto nftPage = std::make_shared(keylet::nftpage_max(A1)); nftPage->setFieldArray(sfNFTokens, makeNFTokenIDs(0)); @@ -1067,7 +1116,8 @@ class Invariants_test : public beast::unit_test::suite }); doInvariantCheck( - {{"NFT page has invalid size"}}, [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { + {{"NFT page has invalid size"}}, + [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { auto nftPage = std::make_shared(keylet::nftpage_max(A1)); nftPage->setFieldArray(sfNFTokens, makeNFTokenIDs(33)); @@ -1076,7 +1126,8 @@ class Invariants_test : public beast::unit_test::suite }); doInvariantCheck( - {{"NFTs on page are not sorted"}}, [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { + {{"NFTs on page are not sorted"}}, + [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { STArray nfTokens = makeNFTokenIDs(2); std::iter_swap(nfTokens.begin(), nfTokens.begin() + 1); @@ -1088,7 +1139,8 @@ class Invariants_test : public beast::unit_test::suite }); doInvariantCheck( - {{"NFT contains empty URI"}}, [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { + {{"NFT contains empty URI"}}, + [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { STArray nfTokens = makeNFTokenIDs(1); nfTokens[0].setFieldVL(sfURI, Blob{}); @@ -1136,8 +1188,8 @@ class Invariants_test : public beast::unit_test::suite {{"NFT page is improperly linked"}}, [&makeNFTokenIDs](Account const& A1, Account const& A2, ApplyContext& ac) { STArray nfTokens = makeNFTokenIDs(1); - auto nftPage = std::make_shared( - keylet::nftpage(keylet::nftpage_max(A1), ++(nfTokens[0].getFieldH256(sfNFTokenID)))); + auto nftPage = std::make_shared(keylet::nftpage( + keylet::nftpage_max(A1), ++(nfTokens[0].getFieldH256(sfNFTokenID)))); nftPage->setFieldArray(sfNFTokens, std::move(nfTokens)); nftPage->setFieldH256(sfNextPageMin, keylet::nftpage_max(A2).key); @@ -1146,10 +1198,11 @@ class Invariants_test : public beast::unit_test::suite }); doInvariantCheck( - {{"NFT found in incorrect page"}}, [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { + {{"NFT found in incorrect page"}}, + [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { STArray nfTokens = makeNFTokenIDs(2); - auto nftPage = std::make_shared( - keylet::nftpage(keylet::nftpage_max(A1), (nfTokens[1].getFieldH256(sfNFTokenID)))); + auto nftPage = std::make_shared(keylet::nftpage( + keylet::nftpage_max(A1), (nfTokens[1].getFieldH256(sfNFTokenID)))); nftPage->setFieldArray(sfNFTokens, std::move(nfTokens)); ac.view().insert(nftPage); @@ -1384,12 +1437,14 @@ class Invariants_test : public beast::unit_test::suite std::initializer_list goodTers = {tesSUCCESS, tesSUCCESS}; - std::vector badMoreThan1{{"transaction affected more than 1 permissioned domain entry."}}; + std::vector badMoreThan1{ + {"transaction affected more than 1 permissioned domain entry."}}; std::vector emptyV; std::vector badNoDomains{{"no domain objects affected by"}}; std::vector badNotDeleted{{"domain object modified, but not deleted by "}}; std::vector badDeleted{{"domain object deleted by"}}; - std::vector badTx{{"domain object(s) affected by an unauthorized transaction."}}; + std::vector badTx{ + {"domain object(s) affected by an unauthorized transaction."}}; { testcase << "PermissionedDomain set 2 domains "; @@ -1961,7 +2016,8 @@ class Invariants_test : public beast::unit_test::suite for (auto const& mod : mods) { doInvariantCheck( - {{"changed an unchangeable field"}}, [&](Account const& A1, Account const&, ApplyContext& ac) { + {{"changed an unchangeable field"}}, + [&](Account const& A1, Account const&, ApplyContext& ac) { auto sle = ac.view().peek(keylet::account(A1.id())); if (!sle) return false; @@ -1988,7 +2044,8 @@ class Invariants_test : public beast::unit_test::suite // Initialize with a placeholder value because there's no default // ctor Keylet loanBrokerKeylet = keylet::amendments(); - Preclose createLoanBroker = [&, this](Account const& alice, Account const& issuer, Env& env) { + Preclose createLoanBroker = [&, this]( + Account const& alice, Account const& issuer, Env& env) { PrettyAsset const asset = [&]() { switch (assetType) { @@ -2002,7 +2059,8 @@ class Invariants_test : public beast::unit_test::suite case Asset::MPT: { MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); + mptt.create( + {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); PrettyAsset const mptAsset = mptt.issuanceID(); mptt.authorize({.account = alice}); env(pay(issuer, alice, mptAsset(1000))); @@ -2051,7 +2109,8 @@ class Invariants_test : public beast::unit_test::suite { // Create the directory BEAST_EXPECT( - ::xrpl::directory::createRoot(ac.view(), dirKeylet, loanBrokerKeylet.key, describe) == 0); + ::xrpl::directory::createRoot( + ac.view(), dirKeylet, loanBrokerKeylet.key, describe) == 0); sleDir = ac.view().peek(dirKeylet); } @@ -2155,7 +2214,8 @@ class Invariants_test : public beast::unit_test::suite // failure. STVector256 indexes; - ::xrpl::directory::insertKey(ac.view(), sleDir, 0, false, indexes, slePseudo->key()); + ::xrpl::directory::insertKey( + ac.view(), sleDir, 0, false, indexes, slePseudo->key()); return true; }, @@ -2230,12 +2290,14 @@ class Invariants_test : public beast::unit_test::suite if (args.assetsTotal) (*sleVault)[sfAssetsTotal] = *(*sleVault)[sfAssetsTotal] + *args.assetsTotal; if (args.assetsAvailable) - (*sleVault)[sfAssetsAvailable] = *(*sleVault)[sfAssetsAvailable] + *args.assetsAvailable; + (*sleVault)[sfAssetsAvailable] = + *(*sleVault)[sfAssetsAvailable] + *args.assetsAvailable; ac.update(sleVault); if (args.sharesTotal) { - (*sleShares)[sfOutstandingAmount] = *(*sleShares)[sfOutstandingAmount] + *args.sharesTotal; + (*sleShares)[sfOutstandingAmount] = + *(*sleShares)[sfOutstandingAmount] + *args.sharesTotal; ac.update(sleShares); } @@ -2248,7 +2310,8 @@ class Invariants_test : public beast::unit_test::suite auto slePseudoAccount = ac.peek(keylet::account(pseudoId)); if (!slePseudoAccount) return false; - (*slePseudoAccount)[sfBalance] = *(*slePseudoAccount)[sfBalance] + *args.vaultAssets; + (*slePseudoAccount)[sfBalance] = + *(*slePseudoAccount)[sfBalance] + *args.vaultAssets; ac.update(slePseudoAccount); } else if (assets.holds()) @@ -2395,8 +2458,8 @@ class Invariants_test : public beast::unit_test::suite auto const sequence = ac.view().seq(); auto const vaultKeylet = keylet::vault(A1.id(), sequence); auto sleVault = std::make_shared(vaultKeylet); - auto const vaultPage = - ac.view().dirInsert(keylet::ownerDir(A1.id()), sleVault->key(), describeOwnerDir(A1.id())); + auto const vaultPage = ac.view().dirInsert( + keylet::ownerDir(A1.id()), sleVault->key(), describeOwnerDir(A1.id())); sleVault->setFieldU64(sfOwnerNode, *vaultPage); ac.view().insert(sleVault); return true; @@ -2467,8 +2530,8 @@ class Invariants_test : public beast::unit_test::suite auto const insertVault = [&](Account const A) { auto const vaultKeylet = keylet::vault(A.id(), sequence); auto sleVault = std::make_shared(vaultKeylet); - auto const vaultPage = - ac.view().dirInsert(keylet::ownerDir(A.id()), sleVault->key(), describeOwnerDir(A.id())); + auto const vaultPage = ac.view().dirInsert( + keylet::ownerDir(A.id()), sleVault->key(), describeOwnerDir(A.id())); sleVault->setFieldU64(sfOwnerNode, *vaultPage); ac.view().insert(sleVault); }; @@ -2750,7 +2813,8 @@ class Invariants_test : public beast::unit_test::suite precloseXrp); doInvariantCheck( - {"vault transaction must not change loss unrealized", "set must not change assets outstanding"}, + {"vault transaction must not change loss unrealized", + "set must not change assets outstanding"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust(ac.view(), keylet, args(A2.id(), 0, [&](Adjustments& sample) { @@ -2770,11 +2834,13 @@ class Invariants_test : public beast::unit_test::suite "vault transaction must not change loss unrealized"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), keylet, args(A2.id(), 100, [&](Adjustments& sample) { sample.lossUnrealized = 13; })); + return adjust(ac.view(), keylet, args(A2.id(), 100, [&](Adjustments& sample) { + sample.lossUnrealized = 13; + })); }, XRPAmount{}, - STTx{ttVAULT_DEPOSIT, [](STObject& tx) { tx.setFieldAmount(sfAmount, XRPAmount(200)); }}, + STTx{ + ttVAULT_DEPOSIT, [](STObject& tx) { tx.setFieldAmount(sfAmount, XRPAmount(200)); }}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, precloseXrp, TxAccount::A2); @@ -2783,8 +2849,9 @@ class Invariants_test : public beast::unit_test::suite {"set assets outstanding must not exceed assets maximum"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), keylet, args(A2.id(), 0, [&](Adjustments& sample) { sample.assetsMaximum = 1; })); + return adjust(ac.view(), keylet, args(A2.id(), 0, [&](Adjustments& sample) { + sample.assetsMaximum = 1; + })); }, XRPAmount{}, STTx{ttVAULT_SET, [](STObject& tx) {}}, @@ -2796,8 +2863,9 @@ class Invariants_test : public beast::unit_test::suite {"assets maximum must be positive"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), keylet, args(A2.id(), 0, [&](Adjustments& sample) { sample.assetsMaximum = -1; })); + return adjust(ac.view(), keylet, args(A2.id(), 0, [&](Adjustments& sample) { + sample.assetsMaximum = -1; + })); }, XRPAmount{}, STTx{ttVAULT_SET, [](STObject& tx) {}}, @@ -3039,8 +3107,8 @@ class Invariants_test : public beast::unit_test::suite auto const sequence = ac.view().seq(); auto const vaultKeylet = keylet::vault(A1.id(), sequence); auto sleVault = std::make_shared(vaultKeylet); - auto const vaultPage = - ac.view().dirInsert(keylet::ownerDir(A1.id()), sleVault->key(), describeOwnerDir(A1.id())); + auto const vaultPage = ac.view().dirInsert( + keylet::ownerDir(A1.id()), sleVault->key(), describeOwnerDir(A1.id())); sleVault->setFieldU64(sfOwnerNode, *vaultPage); auto pseudoId = pseudoAccountAddress(ac.view(), vaultKeylet.key); @@ -3053,15 +3121,16 @@ class Invariants_test : public beast::unit_test::suite ? 0 // : sequence; sleAccount->setFieldU32(sfSequence, seqno); - sleAccount->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); + sleAccount->setFieldU32( + sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); sleAccount->setFieldH256(sfVaultID, vaultKeylet.key); ac.view().insert(sleAccount); auto const sharesMptId = makeMptID(sequence, pseudoId); auto const sharesKeylet = keylet::mptIssuance(sharesMptId); auto sleShares = std::make_shared(sharesKeylet); - auto const sharesPage = - ac.view().dirInsert(keylet::ownerDir(pseudoId), sharesKeylet, describeOwnerDir(pseudoId)); + auto const sharesPage = ac.view().dirInsert( + keylet::ownerDir(pseudoId), sharesKeylet, describeOwnerDir(pseudoId)); sleShares->setFieldU64(sfOwnerNode, *sharesPage); sleShares->at(sfFlags) = 0; @@ -3094,8 +3163,8 @@ class Invariants_test : public beast::unit_test::suite auto const sequence = ac.view().seq(); auto const vaultKeylet = keylet::vault(A1.id(), sequence); auto sleVault = std::make_shared(vaultKeylet); - auto const vaultPage = - ac.view().dirInsert(keylet::ownerDir(A1.id()), sleVault->key(), describeOwnerDir(A1.id())); + auto const vaultPage = ac.view().dirInsert( + keylet::ownerDir(A1.id()), sleVault->key(), describeOwnerDir(A1.id())); sleVault->setFieldU64(sfOwnerNode, *vaultPage); auto pseudoId = pseudoAccountAddress(ac.view(), vaultKeylet.key); @@ -3108,7 +3177,8 @@ class Invariants_test : public beast::unit_test::suite ? 0 // : sequence; sleAccount->setFieldU32(sfSequence, seqno); - sleAccount->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); + sleAccount->setFieldU32( + sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); // sleAccount->setFieldH256(sfVaultID, vaultKeylet.key); // Setting wrong vault key sleAccount->setFieldH256(sfVaultID, uint256(42)); @@ -3117,8 +3187,8 @@ class Invariants_test : public beast::unit_test::suite auto const sharesMptId = makeMptID(sequence, pseudoId); auto const sharesKeylet = keylet::mptIssuance(sharesMptId); auto sleShares = std::make_shared(sharesKeylet); - auto const sharesPage = - ac.view().dirInsert(keylet::ownerDir(pseudoId), sharesKeylet, describeOwnerDir(pseudoId)); + auto const sharesPage = ac.view().dirInsert( + keylet::ownerDir(pseudoId), sharesKeylet, describeOwnerDir(pseudoId)); sleShares->setFieldU64(sfOwnerNode, *sharesPage); sleShares->at(sfFlags) = 0; @@ -3152,15 +3222,15 @@ class Invariants_test : public beast::unit_test::suite auto const sequence = ac.view().seq(); auto const vaultKeylet = keylet::vault(A1.id(), sequence); auto sleVault = std::make_shared(vaultKeylet); - auto const vaultPage = - ac.view().dirInsert(keylet::ownerDir(A1.id()), sleVault->key(), describeOwnerDir(A1.id())); + auto const vaultPage = ac.view().dirInsert( + keylet::ownerDir(A1.id()), sleVault->key(), describeOwnerDir(A1.id())); sleVault->setFieldU64(sfOwnerNode, *vaultPage); auto const sharesMptId = makeMptID(sequence, A2.id()); auto const sharesKeylet = keylet::mptIssuance(sharesMptId); auto sleShares = std::make_shared(sharesKeylet); - auto const sharesPage = - ac.view().dirInsert(keylet::ownerDir(A2.id()), sharesKeylet, describeOwnerDir(A2.id())); + auto const sharesPage = ac.view().dirInsert( + keylet::ownerDir(A2.id()), sharesKeylet, describeOwnerDir(A2.id())); sleShares->setFieldU64(sfOwnerNode, *sharesPage); sleShares->at(sfFlags) = 0; @@ -3192,8 +3262,9 @@ class Invariants_test : public beast::unit_test::suite {"deposit must change vault balance"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), keylet, args(A2.id(), 0, [](Adjustments& sample) { sample.vaultAssets.reset(); })); + return adjust(ac.view(), keylet, args(A2.id(), 0, [](Adjustments& sample) { + sample.vaultAssets.reset(); + })); }, XRPAmount{}, STTx{ttVAULT_DEPOSIT, [](STObject&) {}}, @@ -3204,11 +3275,13 @@ class Invariants_test : public beast::unit_test::suite {"deposit assets outstanding must not exceed assets maximum"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), keylet, args(A2.id(), 200, [&](Adjustments& sample) { sample.assetsMaximum = 1; })); + return adjust(ac.view(), keylet, args(A2.id(), 200, [&](Adjustments& sample) { + sample.assetsMaximum = 1; + })); }, XRPAmount{}, - STTx{ttVAULT_DEPOSIT, [](STObject& tx) { tx.setFieldAmount(sfAmount, XRPAmount(200)); }}, + STTx{ + ttVAULT_DEPOSIT, [](STObject& tx) { tx.setFieldAmount(sfAmount, XRPAmount(200)); }}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, precloseXrp, TxAccount::A2); @@ -3296,8 +3369,9 @@ class Invariants_test : public beast::unit_test::suite {"deposit must change depositor shares"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), keylet, args(A2.id(), 10, [&](Adjustments& sample) { sample.accountShares.reset(); })); + return adjust(ac.view(), keylet, args(A2.id(), 10, [&](Adjustments& sample) { + sample.accountShares.reset(); + })); }, XRPAmount{}, STTx{ttVAULT_DEPOSIT, [](STObject& tx) { tx[sfAmount] = XRPAmount(10); }}, @@ -3310,8 +3384,9 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), keylet, args(A2.id(), 10, [](Adjustments& sample) { sample.sharesTotal = 0; })); + return adjust(ac.view(), keylet, args(A2.id(), 10, [](Adjustments& sample) { + sample.sharesTotal = 0; + })); }, XRPAmount{}, STTx{ttVAULT_DEPOSIT, [](STObject& tx) { tx[sfAmount] = XRPAmount(10); }}, @@ -3345,8 +3420,9 @@ class Invariants_test : public beast::unit_test::suite ac.view().update(sleA3); auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), keylet, args(A2.id(), 10, [&](Adjustments& sample) { sample.assetsTotal = 11; })); + return adjust(ac.view(), keylet, args(A2.id(), 10, [&](Adjustments& sample) { + sample.assetsTotal = 11; + })); }, XRPAmount{2000}, STTx{ @@ -3361,7 +3437,8 @@ class Invariants_test : public beast::unit_test::suite TxAccount::A2); doInvariantCheck( - {"deposit and assets outstanding must add up", "deposit and assets available must add up"}, + {"deposit and assets outstanding must add up", + "deposit and assets available must add up"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust(ac.view(), keylet, args(A2.id(), 10, [&](Adjustments& sample) { @@ -3380,8 +3457,9 @@ class Invariants_test : public beast::unit_test::suite {"withdrawal must change vault balance"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), keylet, args(A2.id(), 0, [](Adjustments& sample) { sample.vaultAssets.reset(); })); + return adjust(ac.view(), keylet, args(A2.id(), 0, [](Adjustments& sample) { + sample.vaultAssets.reset(); + })); }, XRPAmount{}, STTx{ttVAULT_WITHDRAW, [](STObject&) {}}, @@ -3452,8 +3530,9 @@ class Invariants_test : public beast::unit_test::suite {"withdrawal must change one destination balance"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - if (!adjust( - ac.view(), keylet, args(A2.id(), -10, [&](Adjustments& sample) { *sample.vaultAssets -= 5; }))) + if (!adjust(ac.view(), keylet, args(A2.id(), -10, [&](Adjustments& sample) { + *sample.vaultAssets -= 5; + }))) return false; auto sleA3 = ac.view().peek(keylet::account(A3.id())); if (!sleA3) @@ -3472,8 +3551,9 @@ class Invariants_test : public beast::unit_test::suite {"withdrawal must change depositor shares"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), keylet, args(A2.id(), -10, [&](Adjustments& sample) { sample.accountShares.reset(); })); + return adjust(ac.view(), keylet, args(A2.id(), -10, [&](Adjustments& sample) { + sample.accountShares.reset(); + })); }, XRPAmount{}, STTx{ttVAULT_WITHDRAW, [](STObject&) {}}, @@ -3485,8 +3565,9 @@ class Invariants_test : public beast::unit_test::suite {"withdrawal must change vault shares"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), keylet, args(A2.id(), -10, [](Adjustments& sample) { sample.sharesTotal = 0; })); + return adjust(ac.view(), keylet, args(A2.id(), -10, [](Adjustments& sample) { + sample.sharesTotal = 0; + })); }, XRPAmount{}, STTx{ttVAULT_WITHDRAW, [](STObject&) {}}, @@ -3512,7 +3593,8 @@ class Invariants_test : public beast::unit_test::suite TxAccount::A2); doInvariantCheck( - {"withdrawal and assets outstanding must add up", "withdrawal and assets available must add up"}, + {"withdrawal and assets outstanding must add up", + "withdrawal and assets available must add up"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust(ac.view(), keylet, args(A2.id(), -10, [&](Adjustments& sample) { @@ -3534,8 +3616,9 @@ class Invariants_test : public beast::unit_test::suite ac.view().update(sleA3); auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), keylet, args(A2.id(), -10, [&](Adjustments& sample) { sample.assetsTotal = -7; })); + return adjust(ac.view(), keylet, args(A2.id(), -10, [&](Adjustments& sample) { + sample.assetsTotal = -7; + })); }, XRPAmount{2000}, STTx{ @@ -3616,8 +3699,9 @@ class Invariants_test : public beast::unit_test::suite {"clawback must change vault balance"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq() - 2); - return adjust( - ac.view(), keylet, args(A2.id(), -1, [&](Adjustments& sample) { sample.vaultAssets.reset(); })); + return adjust(ac.view(), keylet, args(A2.id(), -1, [&](Adjustments& sample) { + sample.vaultAssets.reset(); + })); }, XRPAmount{}, STTx{ttVAULT_CLAWBACK, [&](STObject& tx) { tx[sfAccount] = A3.id(); }}, @@ -3654,8 +3738,9 @@ class Invariants_test : public beast::unit_test::suite "clawback must change vault shares"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq() - 2); - return adjust( - ac.view(), keylet, args(A4.id(), 10, [&](Adjustments& sample) { sample.sharesTotal = 0; })); + return adjust(ac.view(), keylet, args(A4.id(), 10, [&](Adjustments& sample) { + sample.sharesTotal = 0; + })); }, XRPAmount{}, STTx{ @@ -3671,8 +3756,9 @@ class Invariants_test : public beast::unit_test::suite {"clawback must change holder shares"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq() - 2); - return adjust( - ac.view(), keylet, args(A4.id(), -10, [&](Adjustments& sample) { sample.accountShares.reset(); })); + return adjust(ac.view(), keylet, args(A4.id(), -10, [&](Adjustments& sample) { + sample.accountShares.reset(); + })); }, XRPAmount{}, STTx{ diff --git a/src/test/app/LPTokenTransfer_test.cpp b/src/test/app/LPTokenTransfer_test.cpp index 055b72ebe6..15a8837c4f 100644 --- a/src/test/app/LPTokenTransfer_test.cpp +++ b/src/test/app/LPTokenTransfer_test.cpp @@ -97,7 +97,10 @@ class LPTokenTransfer_test : public jtx::AMMTest { // with fixFrozenLPTokenTransfer, alice fails to consume carol's // offer since carol's USD is frozen - env(pay(alice, bob, STAmount{lpIssue, 10}), txflags(tfPartialPayment), sendmax(XRP(10)), ter(tecPATH_DRY)); + env(pay(alice, bob, STAmount{lpIssue, 10}), + txflags(tfPartialPayment), + sendmax(XRP(10)), + ter(tecPATH_DRY)); env.close(); BEAST_EXPECT(expectOffers(env, carol, 1)); @@ -106,7 +109,9 @@ class LPTokenTransfer_test : public jtx::AMMTest env.close(); // alice successfully consumes carol's offer - env(pay(alice, bob, STAmount{lpIssue, 10}), txflags(tfPartialPayment), sendmax(XRP(10))); + env(pay(alice, bob, STAmount{lpIssue, 10}), + txflags(tfPartialPayment), + sendmax(XRP(10))); env.close(); BEAST_EXPECT(expectOffers(env, carol, 0)); } @@ -114,7 +119,9 @@ class LPTokenTransfer_test : public jtx::AMMTest { // without fixFrozenLPTokenTransfer, alice can consume carol's offer // even when carol's USD is frozen - env(pay(alice, bob, STAmount{lpIssue, 10}), txflags(tfPartialPayment), sendmax(XRP(10))); + env(pay(alice, bob, STAmount{lpIssue, 10}), + txflags(tfPartialPayment), + sendmax(XRP(10))); env.close(); BEAST_EXPECT(expectOffers(env, carol, 0)); } @@ -136,7 +143,9 @@ class LPTokenTransfer_test : public jtx::AMMTest env.close(); // alice successfully consumes carol's offer - env(pay(alice, bob, XRP(10)), txflags(tfPartialPayment), sendmax(STAmount{lpIssue, 10})); + env(pay(alice, bob, XRP(10)), + txflags(tfPartialPayment), + sendmax(STAmount{lpIssue, 10})); env.close(); BEAST_EXPECT(expectOffers(env, carol, 0)); } @@ -169,7 +178,9 @@ class LPTokenTransfer_test : public jtx::AMMTest // sell lptoken when one of the assets is frozen // carol can't create an offer to sell lptoken - env(offer(carol, XRP(10), STAmount{lpIssue, 10}), txflags(tfPassive), ter(tecUNFUNDED_OFFER)); + env(offer(carol, XRP(10), STAmount{lpIssue, 10}), + txflags(tfPassive), + ter(tecUNFUNDED_OFFER)); env.close(); BEAST_EXPECT(expectOffers(env, carol, 0)); @@ -361,7 +372,9 @@ class LPTokenTransfer_test : public jtx::AMMTest // bob fails to create a buy offer with lptoken for carol's nft // since bob's USD is frozen - env(token::createOffer(bob, nftID, STAmount{lpIssue, 10}), token::owner(carol), ter(tecUNFUNDED_OFFER)); + env(token::createOffer(bob, nftID, STAmount{lpIssue, 10}), + token::owner(carol), + ter(tecUNFUNDED_OFFER)); env.close(); // gateway unfreezes bob's USD diff --git a/src/test/app/LedgerHistory_test.cpp b/src/test/app/LedgerHistory_test.cpp index eeca551f35..93ab4a6210 100644 --- a/src/test/app/LedgerHistory_test.cpp +++ b/src/test/app/LedgerHistory_test.cpp @@ -3,11 +3,11 @@ #include #include -#include #include #include #include +#include #include #include @@ -37,7 +37,10 @@ public: { assert(!stx); return std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + env.app().config(), + std::vector{}, + env.app().getNodeFamily()); } auto res = std::make_shared(*prev, prev->header().closeTime + closeOffset); @@ -56,7 +59,10 @@ public: res->unshare(); // Accept ledger - res->setAccepted(res->header().closeTime, res->header().closeTimeResolution, true /* close time correct*/); + res->setAccepted( + res->header().closeTime, + res->header().closeTimeResolution, + true /* close time correct*/); lh.insert(res, false); return res; } @@ -84,7 +90,10 @@ public: // Close time mismatch { bool found = false; - Env env{*this, envconfig(), std::make_unique("MISMATCH on close time", &found)}; + Env env{ + *this, + envconfig(), + std::make_unique("MISMATCH on close time", &found)}; LedgerHistory lh{beast::insight::NullCollector::New(), env.app()}; auto const genesis = makeLedger({}, env, lh, 0s); auto const ledgerA = makeLedger(genesis, env, lh, 4s); @@ -100,7 +109,10 @@ public: // Prior ledger mismatch { bool found = false; - Env env{*this, envconfig(), std::make_unique("MISMATCH on prior ledger", &found)}; + Env env{ + *this, + envconfig(), + std::make_unique("MISMATCH on prior ledger", &found)}; LedgerHistory lh{beast::insight::NullCollector::New(), env.app()}; auto const genesis = makeLedger({}, env, lh, 0s); auto const ledgerA = makeLedger(genesis, env, lh, 4s); @@ -119,8 +131,8 @@ public: // somehow generate different ledgers for (bool const txBug : {true, false}) { - std::string const msg = - txBug ? "MISMATCH with same consensus transaction set" : "MISMATCH on consensus transaction set"; + std::string const msg = txBug ? "MISMATCH with same consensus transaction set" + : "MISMATCH on consensus transaction set"; bool found = false; Env env{*this, envconfig(), std::make_unique(msg, &found)}; LedgerHistory lh{beast::insight::NullCollector::New(), env.app()}; @@ -141,7 +153,8 @@ public: lh.builtLedger(ledgerA, txAlice.stx->getTransactionID(), {}); // Simulate the bug by claiming ledgerB had the same consensus hash // as ledgerA, but somehow generated different ledgers - lh.validatedLedger(ledgerB, txBug ? txAlice.stx->getTransactionID() : txBob.stx->getTransactionID()); + lh.validatedLedger( + ledgerB, txBug ? txAlice.stx->getTransactionID() : txBob.stx->getTransactionID()); BEAST_EXPECT(found); } diff --git a/src/test/app/LedgerLoad_test.cpp b/src/test/app/LedgerLoad_test.cpp index b4e84a3123..0a1ffc024a 100644 --- a/src/test/app/LedgerLoad_test.cpp +++ b/src/test/app/LedgerLoad_test.cpp @@ -82,7 +82,8 @@ class LedgerLoad_test : public beast::unit_test::suite BEAST_EXPECT(retval.hashes.size() == 41); retval.trapTxHash = [&]() { - auto const txs = env.rpc("ledger", std::to_string(41), "tx")[jss::result][jss::ledger][jss::transactions]; + auto const txs = env.rpc( + "ledger", std::to_string(41), "tx")[jss::result][jss::ledger][jss::transactions]; BEAST_EXPECT(txs.isArray() && txs.size() > 0); uint256 tmp; BEAST_EXPECT(tmp.parseHex(txs[0u][jss::hash].asString())); @@ -109,7 +110,9 @@ class LedgerLoad_test : public beast::unit_test::suite nullptr, beast::severities::kDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; - BEAST_EXPECT(sd.ledger[jss::ledger][jss::accountState].size() == jrb[jss::ledger][jss::accountState].size()); + BEAST_EXPECT( + sd.ledger[jss::ledger][jss::accountState].size() == + jrb[jss::ledger][jss::accountState].size()); } void @@ -132,7 +135,8 @@ class LedgerLoad_test : public beast::unit_test::suite except([&] { Env env( *this, - envconfig(ledgerConfig, sd.dbPath, "badfile.json", StartUpType::LOAD_FILE, std::nullopt), + envconfig( + ledgerConfig, sd.dbPath, "badfile.json", StartUpType::LOAD_FILE, std::nullopt), nullptr, beast::severities::kDisabled); }); @@ -153,7 +157,12 @@ class LedgerLoad_test : public beast::unit_test::suite except([&] { Env env( *this, - envconfig(ledgerConfig, sd.dbPath, ledgerFileCorrupt.string(), StartUpType::LOAD_FILE, std::nullopt), + envconfig( + ledgerConfig, + sd.dbPath, + ledgerFileCorrupt.string(), + StartUpType::LOAD_FILE, + std::nullopt), nullptr, beast::severities::kDisabled); }); @@ -175,7 +184,9 @@ class LedgerLoad_test : public beast::unit_test::suite beast::severities::kDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; BEAST_EXPECT(jrb[jss::ledger][jss::accountState].size() == 98); - BEAST_EXPECT(jrb[jss::ledger][jss::accountState].size() <= sd.ledger[jss::ledger][jss::accountState].size()); + BEAST_EXPECT( + jrb[jss::ledger][jss::accountState].size() <= + sd.ledger[jss::ledger][jss::accountState].size()); } void @@ -199,7 +210,9 @@ class LedgerLoad_test : public beast::unit_test::suite env.close(); auto const closed = env.rpc("ledger", "current", "full")[jss::result]; BEAST_EXPECT(closed[jss::ledger][jss::accountState].size() == 98); - BEAST_EXPECT(closed[jss::ledger][jss::accountState].size() <= sd.ledger[jss::ledger][jss::accountState].size()); + BEAST_EXPECT( + closed[jss::ledger][jss::accountState].size() <= + sd.ledger[jss::ledger][jss::accountState].size()); } void @@ -223,7 +236,9 @@ class LedgerLoad_test : public beast::unit_test::suite env.close(); auto const closed = env.rpc("ledger", "current", "full")[jss::result]; BEAST_EXPECT(closed[jss::ledger][jss::accountState].size() == 98); - BEAST_EXPECT(closed[jss::ledger][jss::accountState].size() <= sd.ledger[jss::ledger][jss::accountState].size()); + BEAST_EXPECT( + closed[jss::ledger][jss::accountState].size() <= + sd.ledger[jss::ledger][jss::accountState].size()); } void @@ -269,7 +284,9 @@ class LedgerLoad_test : public beast::unit_test::suite nullptr, beast::severities::kDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; - BEAST_EXPECT(sd.ledger[jss::ledger][jss::accountState].size() == jrb[jss::ledger][jss::accountState].size()); + BEAST_EXPECT( + sd.ledger[jss::ledger][jss::accountState].size() == + jrb[jss::ledger][jss::accountState].size()); } void @@ -285,7 +302,9 @@ class LedgerLoad_test : public beast::unit_test::suite nullptr, beast::severities::kDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; - BEAST_EXPECT(sd.ledger[jss::ledger][jss::accountState].size() == jrb[jss::ledger][jss::accountState].size()); + BEAST_EXPECT( + sd.ledger[jss::ledger][jss::accountState].size() == + jrb[jss::ledger][jss::accountState].size()); } public: diff --git a/src/test/app/LedgerMaster_test.cpp b/src/test/app/LedgerMaster_test.cpp index eb346288c2..50a8a2ed02 100644 --- a/src/test/app/LedgerMaster_test.cpp +++ b/src/test/app/LedgerMaster_test.cpp @@ -79,8 +79,9 @@ class LedgerMaster_test : public beast::unit_test::suite auto result = env.app().getLedgerMaster().txnIdFromIndex(startLegSeq, txnIndex); BEAST_EXPECT( *result == - uint256("277F4FD89C20B92457FEF05FF63F6405563AD0563C73D967A29727" - "72679ADC65")); + uint256( + "277F4FD89C20B92457FEF05FF63F6405563AD0563C73D967A29727" + "72679ADC65")); } // success (second tx) { @@ -88,8 +89,9 @@ class LedgerMaster_test : public beast::unit_test::suite auto result = env.app().getLedgerMaster().txnIdFromIndex(startLegSeq + 1, txnIndex); BEAST_EXPECT( *result == - uint256("293DF7335EBBAF4420D52E70ABF470EB4C5792CAEA2F91F76193C2" - "819F538FDE")); + uint256( + "293DF7335EBBAF4420D52E70ABF470EB4C5792CAEA2F91F76193C2" + "819F538FDE")); } } diff --git a/src/test/app/LedgerReplay_test.cpp b/src/test/app/LedgerReplay_test.cpp index 229cad21c9..5568a90d03 100644 --- a/src/test/app/LedgerReplay_test.cpp +++ b/src/test/app/LedgerReplay_test.cpp @@ -41,7 +41,8 @@ struct LedgerReplay_test : public beast::unit_test::suite auto const lastClosed = ledgerMaster.getClosedLedger(); auto const lastClosedParent = ledgerMaster.getLedgerByHash(lastClosed->header().parentHash); - auto const replayed = buildLedger(LedgerReplay(lastClosedParent, lastClosed), tapNONE, env.app(), env.journal); + auto const replayed = buildLedger( + LedgerReplay(lastClosedParent, lastClosed), tapNONE, env.app(), env.journal); BEAST_EXPECT(replayed->header().hash == lastClosed->header().hash); } @@ -60,7 +61,10 @@ enum class InboundLedgersBehavior { class MagicInboundLedgers : public InboundLedgers { public: - MagicInboundLedgers(LedgerMaster& ledgerSource, LedgerMaster& ledgerSink, InboundLedgersBehavior bhvr) + MagicInboundLedgers( + LedgerMaster& ledgerSource, + LedgerMaster& ledgerSink, + InboundLedgersBehavior bhvr) : ledgerSource(ledgerSource), ledgerSink(ledgerSink), bhvr(bhvr) { } @@ -92,7 +96,10 @@ public: } virtual bool - gotLedgerData(LedgerHash const& ledgerHash, std::shared_ptr, std::shared_ptr) override + gotLedgerData( + LedgerHash const& ledgerHash, + std::shared_ptr, + std::shared_ptr) override { return false; } @@ -174,7 +181,8 @@ class TestPeer : public Peer { public: TestPeer(bool enableLedgerReplay) - : ledgerReplayEnabled_(enableLedgerReplay), nodePublicKey_(derivePublicKey(KeyType::ed25519, randomSecretKey())) + : ledgerReplayEnabled_(enableLedgerReplay) + , nodePublicKey_(derivePublicKey(KeyType::ed25519, randomSecretKey())) { } @@ -322,7 +330,10 @@ struct TestPeerSet : public PeerSet LedgerReplayMsgHandler& other, PeerSetBehavior bhvr, bool enableLedgerReplay) - : local(me), remote(other), dummyPeer(std::make_shared(enableLedgerReplay)), behavior(bhvr) + : local(me) + , remote(other) + , dummyPeer(std::make_shared(enableLedgerReplay)) + , behavior(bhvr) { } @@ -337,8 +348,10 @@ struct TestPeerSet : public PeerSet } void - sendRequest(::google::protobuf::Message const& msg, protocol::MessageType type, std::shared_ptr const& peer) - override + sendRequest( + ::google::protobuf::Message const& msg, + protocol::MessageType type, + std::shared_ptr const& peer) override { int dropRate = 0; if (behavior == PeerSetBehavior::Drop50) @@ -356,7 +369,8 @@ struct TestPeerSet : public PeerSet return; auto request = std::make_shared( dynamic_cast(msg)); - auto reply = std::make_shared(remote.processProofPathRequest(request)); + auto reply = std::make_shared( + remote.processProofPathRequest(request)); local.processProofPathResponse(reply); if (behavior == PeerSetBehavior::Repeat) local.processProofPathResponse(reply); @@ -367,8 +381,8 @@ struct TestPeerSet : public PeerSet return; auto request = std::make_shared( dynamic_cast(msg)); - auto reply = - std::make_shared(remote.processReplayDeltaRequest(request)); + auto reply = std::make_shared( + remote.processReplayDeltaRequest(request)); local.processReplayDeltaResponse(reply); if (behavior == PeerSetBehavior::Repeat) local.processReplayDeltaResponse(reply); @@ -403,7 +417,10 @@ public: LedgerReplayMsgHandler& other, PeerSetBehavior bhvr, PeerFeature peerFeature) - : local(me), remote(other), behavior(bhvr), enableLedgerReplay(peerFeature == PeerFeature::LedgerReplayEnabled) + : local(me) + , remote(other) + , behavior(bhvr) + , enableLedgerReplay(peerFeature == PeerFeature::LedgerReplayEnabled) { } @@ -493,7 +510,8 @@ struct LedgerServer updateIdx(); env(pay(accounts[fromIdx], accounts[toIdx], - jtx::drops(ledgerMaster.getClosedLedger()->fees().base) + jtx::XRP(param.txAmount)), + jtx::drops(ledgerMaster.getClosedLedger()->fees().base) + + jtx::XRP(param.txAmount)), jtx::seq(jtx::autofill), jtx::fee(jtx::autofill), jtx::sig(jtx::autofill)); @@ -553,7 +571,11 @@ public: , replayer( env.app(), inboundLedgers, - std::make_unique(clientMsgHandler, serverMsgHandler, behavior, peerFeature)) + std::make_unique( + clientMsgHandler, + serverMsgHandler, + behavior, + peerFeature)) { } @@ -778,7 +800,10 @@ public: using namespace beast::severities; void -logAll(LedgerServer& server, LedgerReplayClient& client, beast::severities::Severity level = Severity::kTrace) +logAll( + LedgerServer& server, + LedgerReplayClient& client, + beast::severities::Severity level = Severity::kTrace) { server.app.logs().threshold(level); client.app.logs().threshold(level); @@ -843,8 +868,8 @@ struct LedgerReplayer_test : public beast::unit_test::suite auto request = std::make_shared(); request->set_ledgerhash(l->header().hash.data(), l->header().hash.size()); request->set_type(protocol::TMLedgerMapType::lmACCOUNT_STATE); - auto reply = - std::make_shared(server.msgHandler.processProofPathRequest(request)); + auto reply = std::make_shared( + server.msgHandler.processProofPathRequest(request)); BEAST_EXPECT(reply->has_error()); BEAST_EXPECT(!server.msgHandler.processProofPathResponse(reply)); } @@ -855,8 +880,8 @@ struct LedgerReplayer_test : public beast::unit_test::suite request->set_key(keylet::skip().key.data(), keylet::skip().key.size()); uint256 hash(1234567); request->set_ledgerhash(hash.data(), hash.size()); - auto reply = - std::make_shared(server.msgHandler.processProofPathRequest(request)); + auto reply = std::make_shared( + server.msgHandler.processProofPathRequest(request)); BEAST_EXPECT(reply->has_error()); } @@ -867,8 +892,8 @@ struct LedgerReplayer_test : public beast::unit_test::suite request->set_type(protocol::TMLedgerMapType::lmACCOUNT_STATE); request->set_key(keylet::skip().key.data(), keylet::skip().key.size()); // generate response - auto reply = - std::make_shared(server.msgHandler.processProofPathRequest(request)); + auto reply = std::make_shared( + server.msgHandler.processProofPathRequest(request)); BEAST_EXPECT(!reply->has_error()); BEAST_EXPECT(server.msgHandler.processProofPathResponse(reply)); @@ -899,15 +924,15 @@ struct LedgerReplayer_test : public beast::unit_test::suite { // request, missing hash auto request = std::make_shared(); - auto reply = - std::make_shared(server.msgHandler.processReplayDeltaRequest(request)); + auto reply = std::make_shared( + server.msgHandler.processReplayDeltaRequest(request)); BEAST_EXPECT(reply->has_error()); BEAST_EXPECT(!server.msgHandler.processReplayDeltaResponse(reply)); // request, wrong hash uint256 hash(1234567); request->set_ledgerhash(hash.data(), hash.size()); - reply = - std::make_shared(server.msgHandler.processReplayDeltaRequest(request)); + reply = std::make_shared( + server.msgHandler.processReplayDeltaRequest(request)); BEAST_EXPECT(reply->has_error()); BEAST_EXPECT(!server.msgHandler.processReplayDeltaResponse(reply)); } @@ -916,8 +941,8 @@ struct LedgerReplayer_test : public beast::unit_test::suite // good request auto request = std::make_shared(); request->set_ledgerhash(l->header().hash.data(), l->header().hash.size()); - auto reply = - std::make_shared(server.msgHandler.processReplayDeltaRequest(request)); + auto reply = std::make_shared( + server.msgHandler.processReplayDeltaRequest(request)); BEAST_EXPECT(!reply->has_error()); BEAST_EXPECT(server.msgHandler.processReplayDeltaResponse(reply)); @@ -1034,7 +1059,8 @@ struct LedgerReplayer_test : public beast::unit_test::suite beast::IP::Address addr = boost::asio::ip::make_address("172.1.1.100"); jtx::Env serverEnv(*this); serverEnv.app().config().LEDGER_REPLAY = server; - auto http_resp = xrpl::makeResponse(true, http_request, addr, addr, uint256{1}, 1, {1, 0}, serverEnv.app()); + auto http_resp = xrpl::makeResponse( + true, http_request, addr, addr, uint256{1}, 1, {1, 0}, serverEnv.app()); auto const clientResult = peerFeatureEnabled(http_resp, FEATURE_LEDGER_REPLAY, client); if (clientResult != expecting) return false; @@ -1088,7 +1114,11 @@ struct LedgerReplayer_test : public beast::unit_test::suite { testcase("all the ledgers from InboundLedgers"); NetworkOfTwo net( - *this, {totalReplay + 1}, PeerSetBehavior::DropAll, InboundLedgersBehavior::Good, PeerFeature::None); + *this, + {totalReplay + 1}, + PeerSetBehavior::DropAll, + InboundLedgersBehavior::Good, + PeerFeature::None); auto l = net.server.ledgerMaster.getClosedLedger(); uint256 finalHash = l->header().hash; @@ -1166,8 +1196,8 @@ struct LedgerReplayer_test : public beast::unit_test::suite net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); std::vector deltaStatuses; - BEAST_EXPECT( - net.client.checkStatus(finalHash, totalReplay, TaskStatus::NotDone, TaskStatus::NotDone, deltaStatuses)); + BEAST_EXPECT(net.client.checkStatus( + finalHash, totalReplay, TaskStatus::NotDone, TaskStatus::NotDone, deltaStatuses)); BEAST_EXPECT(net.client.countsAsExpected(1, 1, 0)); net.client.replayer.stop(); @@ -1229,11 +1259,15 @@ struct LedgerReplayer_test : public beast::unit_test::suite l->header(), // wrong ledger info std::map>()); BEAST_EXPECT(net.client.taskStatus(delta) == TaskStatus::Failed); - BEAST_EXPECT(net.client.taskStatus(net.client.findTask(finalHash, totalReplay)) == TaskStatus::Failed); + BEAST_EXPECT( + net.client.taskStatus(net.client.findTask(finalHash, totalReplay)) == + TaskStatus::Failed); // add another task net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay + 1); - BEAST_EXPECT(net.client.taskStatus(net.client.findTask(finalHash, totalReplay + 1)) == TaskStatus::Failed); + BEAST_EXPECT( + net.client.taskStatus(net.client.findTask(finalHash, totalReplay + 1)) == + TaskStatus::Failed); } void @@ -1281,7 +1315,8 @@ struct LedgerReplayer_test : public beast::unit_test::suite // partial overlap l = net.server.ledgerMaster.getLedgerByHash(l->header().parentHash); auto finalHash_moreEarly = l->header().parentHash; - net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash_moreEarly, totalReplay); + net.client.replayer.replay( + InboundLedger::Reason::GENERIC, finalHash_moreEarly, totalReplay); BEAST_EXPECT(net.client.waitAndCheckStatus( finalHash_moreEarly, totalReplay, @@ -1424,14 +1459,19 @@ struct LedgerReplayerLong_test : public beast::unit_test::suite for (int i = 0; i < rounds; ++i) { - net.client.replayer.replay(InboundLedger::Reason::GENERIC, finishHashes[i], totalReplay); + net.client.replayer.replay( + InboundLedger::Reason::GENERIC, finishHashes[i], totalReplay); } std::vector deltaStatuses(totalReplay - 1, TaskStatus::Completed); for (int i = 0; i < rounds; ++i) { BEAST_EXPECT(net.client.waitAndCheckStatus( - finishHashes[i], totalReplay, TaskStatus::Completed, TaskStatus::Completed, deltaStatuses)); + finishHashes[i], + totalReplay, + TaskStatus::Completed, + TaskStatus::Completed, + deltaStatuses)); } BEAST_EXPECT(net.client.waitForLedgers(finishHashes[0], totalReplay * rounds)); diff --git a/src/test/app/LendingHelpers_test.cpp b/src/test/app/LendingHelpers_test.cpp index 58e4c5aaa4..aae60a252a 100644 --- a/src/test/app/LendingHelpers_test.cpp +++ b/src/test/app/LendingHelpers_test.cpp @@ -5,13 +5,12 @@ #include #include -#include -#include -#include -#include - #include #include +#include +#include +#include +#include #include #include @@ -64,7 +63,8 @@ class LendingHelpers_test : public beast::unit_test::suite { testcase("computeRaisedRate: " + tc.name); - auto const computedRaisedRate = computeRaisedRate(tc.periodicRate, tc.paymentsRemaining); + auto const computedRaisedRate = + computeRaisedRate(tc.periodicRate, tc.paymentsRemaining); BEAST_EXPECTS( computedRaisedRate == tc.expectedRaisedRate, "Raised rate mismatch: expected " + to_string(tc.expectedRaisedRate) + ", got " + @@ -116,11 +116,12 @@ class LendingHelpers_test : public beast::unit_test::suite { testcase("computePaymentFactor: " + tc.name); - auto const computedPaymentFactor = computePaymentFactor(tc.periodicRate, tc.paymentsRemaining); + auto const computedPaymentFactor = + computePaymentFactor(tc.periodicRate, tc.paymentsRemaining); BEAST_EXPECTS( computedPaymentFactor == tc.expectedPaymentFactor, - "Payment factor mismatch: expected " + to_string(tc.expectedPaymentFactor) + ", got " + - to_string(computedPaymentFactor)); + "Payment factor mismatch: expected " + to_string(tc.expectedPaymentFactor) + + ", got " + to_string(computedPaymentFactor)); } } @@ -178,8 +179,8 @@ class LendingHelpers_test : public beast::unit_test::suite loanPeriodicPayment(tc.principalOutstanding, tc.periodicRate, tc.paymentsRemaining); BEAST_EXPECTS( computedPeriodicPayment == tc.expectedPeriodicPayment, - "Periodic payment mismatch: expected " + to_string(tc.expectedPeriodicPayment) + ", got " + - to_string(computedPeriodicPayment)); + "Periodic payment mismatch: expected " + to_string(tc.expectedPeriodicPayment) + + ", got " + to_string(computedPeriodicPayment)); } } @@ -233,11 +234,12 @@ class LendingHelpers_test : public beast::unit_test::suite { testcase("loanPrincipalFromPeriodicPayment: " + tc.name); - auto const computedPrincipalOutstanding = - loanPrincipalFromPeriodicPayment(tc.periodicPayment, tc.periodicRate, tc.paymentsRemaining); + auto const computedPrincipalOutstanding = loanPrincipalFromPeriodicPayment( + tc.periodicPayment, tc.periodicRate, tc.paymentsRemaining); BEAST_EXPECTS( computedPrincipalOutstanding == tc.expectedPrincipalOutstanding, - "Principal outstanding mismatch: expected " + to_string(tc.expectedPrincipalOutstanding) + ", got " + + "Principal outstanding mismatch: expected " + + to_string(tc.expectedPrincipalOutstanding) + ", got " + to_string(computedPrincipalOutstanding)); } } @@ -264,7 +266,12 @@ class LendingHelpers_test : public beast::unit_test::suite auto const expectedPrincipalPortion = Number{400}; // 1,000 - 100 - 500 auto const components = detail::computeOverpaymentComponents( - IOU, loanScale, overpayment, overpaymentInterestRate, overpaymentFeeRate, managementFeeRate); + IOU, + loanScale, + overpayment, + overpaymentInterestRate, + overpaymentFeeRate, + managementFeeRate); BEAST_EXPECT(components.untrackedManagementFee == expectedOverpaymentFee); @@ -275,11 +282,12 @@ class LendingHelpers_test : public beast::unit_test::suite BEAST_EXPECT(components.trackedManagementFeeDelta == expectedOverpaymentManagementFee); BEAST_EXPECT(components.trackedPrincipalDelta == expectedPrincipalPortion); BEAST_EXPECT( - components.trackedManagementFeeDelta + components.untrackedInterest == expectedOverpaymentInterestGross); + components.trackedManagementFeeDelta + components.untrackedInterest == + expectedOverpaymentInterestGross); BEAST_EXPECT( - components.trackedManagementFeeDelta + components.untrackedInterest + components.trackedPrincipalDelta + - components.untrackedManagementFee == + components.trackedManagementFeeDelta + components.untrackedInterest + + components.trackedPrincipalDelta + components.untrackedManagementFee == overpayment); } @@ -328,11 +336,12 @@ class LendingHelpers_test : public beast::unit_test::suite computeInterestAndFeeParts(IOU, tc.interest, tc.managementFeeRate, loanScale); BEAST_EXPECTS( computedInterestPart == tc.expectedInterestPart, - "Interest part mismatch: expected " + to_string(tc.expectedInterestPart) + ", got " + - to_string(computedInterestPart)); + "Interest part mismatch: expected " + to_string(tc.expectedInterestPart) + + ", got " + to_string(computedInterestPart)); BEAST_EXPECTS( computedFeePart == tc.expectedFeePart, - "Fee part mismatch: expected " + to_string(tc.expectedFeePart) + ", got " + to_string(computedFeePart)); + "Fee part mismatch: expected " + to_string(tc.expectedFeePart) + ", got " + + to_string(computedFeePart)); } } @@ -399,11 +408,14 @@ class LendingHelpers_test : public beast::unit_test::suite testcase("loanLatePaymentInterest: " + tc.name); auto const computedLateInterest = loanLatePaymentInterest( - tc.principalOutstanding, tc.lateInterestRate, tc.parentCloseTime, tc.nextPaymentDueDate); + tc.principalOutstanding, + tc.lateInterestRate, + tc.parentCloseTime, + tc.nextPaymentDueDate); BEAST_EXPECTS( computedLateInterest == tc.expectedLateInterest, - "Late interest mismatch: expected " + to_string(tc.expectedLateInterest) + ", got " + - to_string(computedLateInterest)); + "Late interest mismatch: expected " + to_string(tc.expectedLateInterest) + + ", got " + to_string(computedLateInterest)); } } @@ -490,8 +502,8 @@ class LendingHelpers_test : public beast::unit_test::suite tc.paymentInterval); BEAST_EXPECTS( computedAccruedInterest == tc.expectedAccruedInterest, - "Accrued interest mismatch: expected " + to_string(tc.expectedAccruedInterest) + ", got " + - to_string(computedAccruedInterest)); + "Accrued interest mismatch: expected " + to_string(tc.expectedAccruedInterest) + + ", got " + to_string(computedAccruedInterest)); } } @@ -566,7 +578,8 @@ class LendingHelpers_test : public beast::unit_test::suite tc.closeInterestRate); BEAST_EXPECTS( computedFullPaymentInterest == tc.expectedFullPaymentInterest, - "Full payment interest mismatch: expected " + to_string(tc.expectedFullPaymentInterest) + ", got " + + "Full payment interest mismatch: expected " + + to_string(tc.expectedFullPaymentInterest) + ", got " + to_string(computedFullPaymentInterest)); } } @@ -596,7 +609,13 @@ class LendingHelpers_test : public beast::unit_test::suite asset, loanScale, overpaymentAmount, TenthBips32(0), TenthBips32(0), managementFeeRate); auto const loanProperties = computeLoanProperties( - asset, loanPrincipal, loanInterestRate, paymentInterval, paymentsRemaining, managementFeeRate, loanScale); + asset, + loanPrincipal, + loanInterestRate, + paymentInterval, + paymentsRemaining, + managementFeeRate, + loanScale); auto const ret = tryOverpayment( asset, @@ -625,7 +644,8 @@ class LendingHelpers_test : public beast::unit_test::suite BEAST_EXPECTS( actualPaymentParts.interestPaid == 0, - " interestPaid mismatch: expected 0, got " + to_string(actualPaymentParts.interestPaid)); + " interestPaid mismatch: expected 0, got " + + to_string(actualPaymentParts.interestPaid)); BEAST_EXPECTS( actualPaymentParts.principalPaid == overpaymentAmount, @@ -647,8 +667,9 @@ class LendingHelpers_test : public beast::unit_test::suite actualPaymentParts.principalPaid == loanProperties.loanState.principalOutstanding - newState.principalOutstanding, " principalPaid mismatch: expected " + - to_string(loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + ", got " + - to_string(actualPaymentParts.principalPaid)); + to_string( + loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + + ", got " + to_string(actualPaymentParts.principalPaid)); } void @@ -679,7 +700,13 @@ class LendingHelpers_test : public beast::unit_test::suite managementFeeRate); auto const loanProperties = computeLoanProperties( - asset, loanPrincipal, loanInterestRate, paymentInterval, paymentsRemaining, managementFeeRate, loanScale); + asset, + loanPrincipal, + loanInterestRate, + paymentInterval, + paymentsRemaining, + managementFeeRate, + loanScale); auto const ret = tryOverpayment( asset, @@ -708,11 +735,13 @@ class LendingHelpers_test : public beast::unit_test::suite BEAST_EXPECTS( actualPaymentParts.principalPaid == 45, - " principalPaid mismatch: expected 45, got `" + to_string(actualPaymentParts.principalPaid)); + " principalPaid mismatch: expected 45, got `" + + to_string(actualPaymentParts.principalPaid)); BEAST_EXPECTS( actualPaymentParts.interestPaid == 0, - " interestPaid mismatch: expected 0, got " + to_string(actualPaymentParts.interestPaid)); + " interestPaid mismatch: expected 0, got " + + to_string(actualPaymentParts.interestPaid)); // =========== VALIDATE STATE CHANGES =========== // With no Loan interest, interest outstanding should not change @@ -731,8 +760,9 @@ class LendingHelpers_test : public beast::unit_test::suite actualPaymentParts.principalPaid == loanProperties.loanState.principalOutstanding - newState.principalOutstanding, " principalPaid mismatch: expected " + - to_string(loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + ", got " + - to_string(actualPaymentParts.principalPaid)); + to_string( + loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + + ", got " + to_string(actualPaymentParts.principalPaid)); } void @@ -763,7 +793,13 @@ class LendingHelpers_test : public beast::unit_test::suite managementFeeRate); auto const loanProperties = computeLoanProperties( - asset, loanPrincipal, loanInterestRate, paymentInterval, paymentsRemaining, managementFeeRate, loanScale); + asset, + loanPrincipal, + loanInterestRate, + paymentInterval, + paymentsRemaining, + managementFeeRate, + loanScale); auto const ret = tryOverpayment( asset, @@ -796,23 +832,27 @@ class LendingHelpers_test : public beast::unit_test::suite BEAST_EXPECTS( actualPaymentParts.principalPaid == 50, - " principalPaid mismatch: expected 50, got `" + to_string(actualPaymentParts.principalPaid)); + " principalPaid mismatch: expected 50, got `" + + to_string(actualPaymentParts.principalPaid)); // with no interest portion, interest paid should be zero BEAST_EXPECTS( actualPaymentParts.interestPaid == 0, - " interestPaid mismatch: expected 0, got " + to_string(actualPaymentParts.interestPaid)); + " interestPaid mismatch: expected 0, got " + + to_string(actualPaymentParts.interestPaid)); // =========== VALIDATE STATE CHANGES =========== BEAST_EXPECTS( actualPaymentParts.principalPaid == loanProperties.loanState.principalOutstanding - newState.principalOutstanding, " principalPaid mismatch: expected " + - to_string(loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + ", got " + - to_string(actualPaymentParts.principalPaid)); + to_string( + loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + + ", got " + to_string(actualPaymentParts.principalPaid)); BEAST_EXPECTS( - actualPaymentParts.valueChange == newState.interestDue - loanProperties.loanState.interestDue, + actualPaymentParts.valueChange == + newState.interestDue - loanProperties.loanState.interestDue, " valueChange mismatch: expected " + to_string(newState.interestDue - loanProperties.loanState.interestDue) + ", got " + to_string(actualPaymentParts.valueChange)); @@ -852,7 +892,13 @@ class LendingHelpers_test : public beast::unit_test::suite managementFeeRate); auto const loanProperties = computeLoanProperties( - asset, loanPrincipal, loanInterestRate, paymentInterval, paymentsRemaining, managementFeeRate, loanScale); + asset, + loanPrincipal, + loanInterestRate, + paymentInterval, + paymentsRemaining, + managementFeeRate, + loanScale); auto const ret = tryOverpayment( asset, @@ -874,15 +920,17 @@ class LendingHelpers_test : public beast::unit_test::suite // with overpayment interest portion, interest paid should be 5 BEAST_EXPECTS( actualPaymentParts.interestPaid == 5, - " interestPaid mismatch: expected 5, got " + to_string(actualPaymentParts.interestPaid)); + " interestPaid mismatch: expected 5, got " + + to_string(actualPaymentParts.interestPaid)); // With overpayment interest portion, value change should equal the // interest decrease plus overpayment interest portion BEAST_EXPECTS( - (actualPaymentParts.valueChange == Number{-205922, -5} + actualPaymentParts.interestPaid), + (actualPaymentParts.valueChange == + Number{-205922, -5} + actualPaymentParts.interestPaid), " valueChange mismatch: expected " + - to_string(actualPaymentParts.valueChange - actualPaymentParts.interestPaid) + ", got " + - to_string(actualPaymentParts.valueChange)); + to_string(actualPaymentParts.valueChange - actualPaymentParts.interestPaid) + + ", got " + to_string(actualPaymentParts.valueChange)); // with no fee portion, fee paid should be zero BEAST_EXPECTS( @@ -891,15 +939,17 @@ class LendingHelpers_test : public beast::unit_test::suite BEAST_EXPECTS( actualPaymentParts.principalPaid == 45, - " principalPaid mismatch: expected 45, got `" + to_string(actualPaymentParts.principalPaid)); + " principalPaid mismatch: expected 45, got `" + + to_string(actualPaymentParts.principalPaid)); // =========== VALIDATE STATE CHANGES =========== BEAST_EXPECTS( actualPaymentParts.principalPaid == loanProperties.loanState.principalOutstanding - newState.principalOutstanding, " principalPaid mismatch: expected " + - to_string(loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + ", got " + - to_string(actualPaymentParts.principalPaid)); + to_string( + loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + + ", got " + to_string(actualPaymentParts.principalPaid)); // The change in interest is equal to the value change sans the // overpayment interest @@ -908,7 +958,8 @@ class LendingHelpers_test : public beast::unit_test::suite newState.interestDue - loanProperties.loanState.interestDue, " valueChange mismatch: expected " + to_string( - newState.interestDue - loanProperties.loanState.interestDue + actualPaymentParts.interestPaid) + + newState.interestDue - loanProperties.loanState.interestDue + + actualPaymentParts.interestPaid) + ", got " + to_string(actualPaymentParts.valueChange)); // With no Loan management fee, management fee due should not change @@ -948,7 +999,13 @@ class LendingHelpers_test : public beast::unit_test::suite managementFeeRate); auto const loanProperties = computeLoanProperties( - asset, loanPrincipal, loanInterestRate, paymentInterval, paymentsRemaining, managementFeeRate, loanScale); + asset, + loanPrincipal, + loanInterestRate, + paymentInterval, + paymentsRemaining, + managementFeeRate, + loanScale); auto const ret = tryOverpayment( asset, @@ -972,14 +1029,17 @@ class LendingHelpers_test : public beast::unit_test::suite // overpayment interest portion first, so interest paid remains 4.5 BEAST_EXPECTS( (actualPaymentParts.interestPaid == Number{45, -1}), - " interestPaid mismatch: expected 4.5, got " + to_string(actualPaymentParts.interestPaid)); + " interestPaid mismatch: expected 4.5, got " + + to_string(actualPaymentParts.interestPaid)); // With overpayment interest portion, value change should equal the // interest decrease plus overpayment interest portion BEAST_EXPECTS( - (actualPaymentParts.valueChange == Number{-18533, -4} + actualPaymentParts.interestPaid), - " valueChange mismatch: expected " + to_string(Number{-18533, -4} + actualPaymentParts.interestPaid) + - ", got " + to_string(actualPaymentParts.valueChange)); + (actualPaymentParts.valueChange == + Number{-18533, -4} + actualPaymentParts.interestPaid), + " valueChange mismatch: expected " + + to_string(Number{-18533, -4} + actualPaymentParts.interestPaid) + ", got " + + to_string(actualPaymentParts.valueChange)); // While there is no overpayment fee, fee paid should equal the // management fee charged against the overpayment interest portion @@ -989,21 +1049,25 @@ class LendingHelpers_test : public beast::unit_test::suite BEAST_EXPECTS( actualPaymentParts.principalPaid == 45, - " principalPaid mismatch: expected 45, got `" + to_string(actualPaymentParts.principalPaid)); + " principalPaid mismatch: expected 45, got `" + + to_string(actualPaymentParts.principalPaid)); // =========== VALIDATE STATE CHANGES =========== BEAST_EXPECTS( actualPaymentParts.principalPaid == loanProperties.loanState.principalOutstanding - newState.principalOutstanding, " principalPaid mismatch: expected " + - to_string(loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + ", got " + - to_string(actualPaymentParts.principalPaid)); + to_string( + loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + + ", got " + to_string(actualPaymentParts.principalPaid)); // Note that the management fee value change is not captured, as this // value is not needed to correctly update the Vault state. BEAST_EXPECTS( - (newState.managementFeeDue - loanProperties.loanState.managementFeeDue == Number{-20592, -5}), - " management fee change mismatch: expected " + to_string(Number{-20592, -5}) + ", got " + + (newState.managementFeeDue - loanProperties.loanState.managementFeeDue == + Number{-20592, -5}), + " management fee change mismatch: expected " + to_string(Number{-20592, -5}) + + ", got " + to_string(newState.managementFeeDue - loanProperties.loanState.managementFeeDue)); BEAST_EXPECTS( @@ -1042,7 +1106,13 @@ class LendingHelpers_test : public beast::unit_test::suite managementFeeRate); auto const loanProperties = computeLoanProperties( - asset, loanPrincipal, loanInterestRate, paymentInterval, paymentsRemaining, managementFeeRate, loanScale); + asset, + loanPrincipal, + loanInterestRate, + paymentInterval, + paymentsRemaining, + managementFeeRate, + loanScale); auto const ret = tryOverpayment( asset, @@ -1066,14 +1136,17 @@ class LendingHelpers_test : public beast::unit_test::suite // overpayment interest portion first, so interest paid remains 4.5 BEAST_EXPECTS( (actualPaymentParts.interestPaid == Number{45, -1}), - " interestPaid mismatch: expected 4.5, got " + to_string(actualPaymentParts.interestPaid)); + " interestPaid mismatch: expected 4.5, got " + + to_string(actualPaymentParts.interestPaid)); // With overpayment interest portion, value change should equal the // interest decrease plus overpayment interest portion BEAST_EXPECTS( - (actualPaymentParts.valueChange == Number{-164737, -5} + actualPaymentParts.interestPaid), - " valueChange mismatch: expected " + to_string(Number{-164737, -5} + actualPaymentParts.interestPaid) + - ", got " + to_string(actualPaymentParts.valueChange)); + (actualPaymentParts.valueChange == + Number{-164737, -5} + actualPaymentParts.interestPaid), + " valueChange mismatch: expected " + + to_string(Number{-164737, -5} + actualPaymentParts.interestPaid) + ", got " + + to_string(actualPaymentParts.valueChange)); // While there is no overpayment fee, fee paid should equal the // management fee charged against the overpayment interest portion @@ -1083,7 +1156,8 @@ class LendingHelpers_test : public beast::unit_test::suite BEAST_EXPECTS( actualPaymentParts.principalPaid == 40, - " principalPaid mismatch: expected 40, got `" + to_string(actualPaymentParts.principalPaid)); + " principalPaid mismatch: expected 40, got `" + + to_string(actualPaymentParts.principalPaid)); // =========== VALIDATE STATE CHANGES =========== @@ -1091,14 +1165,17 @@ class LendingHelpers_test : public beast::unit_test::suite actualPaymentParts.principalPaid == loanProperties.loanState.principalOutstanding - newState.principalOutstanding, " principalPaid mismatch: expected " + - to_string(loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + ", got " + - to_string(actualPaymentParts.principalPaid)); + to_string( + loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + + ", got " + to_string(actualPaymentParts.principalPaid)); // Note that the management fee value change is not captured, as this // value is not needed to correctly update the Vault state. BEAST_EXPECTS( - (newState.managementFeeDue - loanProperties.loanState.managementFeeDue == Number{-18304, -5}), - " management fee change mismatch: expected " + to_string(Number{-18304, -5}) + ", got " + + (newState.managementFeeDue - loanProperties.loanState.managementFeeDue == + Number{-18304, -5}), + " management fee change mismatch: expected " + to_string(Number{-18304, -5}) + + ", got " + to_string(newState.managementFeeDue - loanProperties.loanState.managementFeeDue)); BEAST_EXPECTS( diff --git a/src/test/app/LoadFeeTrack_test.cpp b/src/test/app/LoadFeeTrack_test.cpp index 61174fc9e9..fed76288ef 100644 --- a/src/test/app/LoadFeeTrack_test.cpp +++ b/src/test/app/LoadFeeTrack_test.cpp @@ -1,8 +1,8 @@ -#include #include #include #include +#include namespace xrpl { diff --git a/src/test/app/LoanBroker_test.cpp b/src/test/app/LoanBroker_test.cpp index 58052e3fb1..31cfb5c231 100644 --- a/src/test/app/LoanBroker_test.cpp +++ b/src/test/app/LoanBroker_test.cpp @@ -1,8 +1,7 @@ #include -#include - #include +#include namespace xrpl { namespace test { @@ -12,7 +11,8 @@ class LoanBroker_test : public beast::unit_test::suite // Ensure that all the features needed for Lending Protocol are included, // even if they are set to unsupported. FeatureBitset const all{ - jtx::testable_amendments() | featureMPTokensV1 | featureSingleAssetVault | featureLendingProtocol}; + jtx::testable_amendments() | featureMPTokensV1 | featureSingleAssetVault | + featureLendingProtocol}; void testDisabled() @@ -50,7 +50,10 @@ class LoanBroker_test : public beast::unit_test::suite env(coverClawback(alice), ter(temDISABLED)); env(coverClawback(alice), loanBrokerID(brokerKeylet.key), ter(temDISABLED)); env(coverClawback(alice), amount(asset(0)), ter(temDISABLED)); - env(coverClawback(alice), loanBrokerID(brokerKeylet.key), amount(asset(1000)), ter(temDISABLED)); + env(coverClawback(alice), + loanBrokerID(brokerKeylet.key), + amount(asset(1000)), + ter(temDISABLED)); // 4. LoanBrokerDelete env(del(alice, brokerKeylet.key), ter(temDISABLED)); }; @@ -166,7 +169,8 @@ class LoanBroker_test : public beast::unit_test::suite // log << "Pseudo-account after create: " // << to_string(pseudo->getJson()) << std::endl // << std::endl; - BEAST_EXPECT(pseudo->at(sfFlags) == (lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth)); + BEAST_EXPECT( + pseudo->at(sfFlags) == (lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth)); BEAST_EXPECT(pseudo->at(sfSequence) == 0); BEAST_EXPECT(pseudo->at(sfBalance) == beast::zero); BEAST_EXPECT(pseudo->at(sfOwnerCount) == (vault.asset.raw().native() ? 0 : 1)); @@ -209,16 +213,17 @@ class LoanBroker_test : public beast::unit_test::suite } } - auto verifyCoverAmount = [&env, &vault, &pseudoAccount, &broker, &keylet, this](auto n) { - using namespace jtx; + auto verifyCoverAmount = + [&env, &vault, &pseudoAccount, &broker, &keylet, this](auto n) { + using namespace jtx; - if (BEAST_EXPECT(broker = env.le(keylet))) - { - auto const amount = vault.asset(n); - BEAST_EXPECT(broker->at(sfCoverAvailable) == amount.number()); - env.require(balance(pseudoAccount, amount)); - } - }; + if (BEAST_EXPECT(broker = env.le(keylet))) + { + auto const amount = vault.asset(n); + BEAST_EXPECT(broker->at(sfCoverAvailable) == amount.number()); + env.require(balance(pseudoAccount, amount)); + } + }; // Test Cover funding before allowing alterations env(coverDeposit(alice, uint256(0), vault.asset(10)), ter(temINVALID)); @@ -254,7 +259,9 @@ class LoanBroker_test : public beast::unit_test::suite env(coverClawback(alice), amount(ghostIouAsset(1)), ter(tecNO_ENTRY)); env(coverClawback(alice), amount(badIouAsset(1)), ter(tecOBJECT_NOT_FOUND)); // Pseudo-account is not for a broker - env(coverClawback(alice), amount(vaultPseudoIouAsset(1)), ter(tecOBJECT_NOT_FOUND)); + env(coverClawback(alice), + amount(vaultPseudoIouAsset(1)), + ter(tecOBJECT_NOT_FOUND)); // If we specify a pseudo-account as the IOU amount, it // needs to match the loan broker env(coverClawback(issuer), @@ -300,11 +307,15 @@ class LoanBroker_test : public beast::unit_test::suite if (!vault.asset.raw().native()) { TER const expected = vault.asset.raw().holds() ? tecNO_AUTH : tecNO_LINE; - env(coverWithdraw(alice, keylet.key, vault.asset(1)), destination(bystander), ter(expected)); + env(coverWithdraw(alice, keylet.key, vault.asset(1)), + destination(bystander), + ter(expected)); } // Can not withdraw to the zero address - env(coverWithdraw(alice, keylet.key, vault.asset(1)), destination(AccountID{}), ter(temMALFORMED)); + env(coverWithdraw(alice, keylet.key, vault.asset(1)), + destination(AccountID{}), + ter(temMALFORMED)); // Withdraw some of the cover amount env(coverWithdraw(alice, keylet.key, vault.asset(7))); @@ -343,7 +354,12 @@ class LoanBroker_test : public beast::unit_test::suite // Issuer claws it all back in various different ways for (auto const& tx : { // defer autofills until submission time - env.json(coverClawback(issuer), loanBrokerID(keylet.key), fee(none), seq(none), sig(none)), + env.json( + coverClawback(issuer), + loanBrokerID(keylet.key), + fee(none), + seq(none), + sig(none)), env.json( coverClawback(issuer), loanBrokerID(keylet.key), @@ -397,7 +413,10 @@ class LoanBroker_test : public beast::unit_test::suite // Verify that fields get removed when set to default values // Debt maximum: explicit 0 // Data: explicit empty - env(set(alice, vault.vaultID), loanBrokerID(broker->key()), debtMaximum(Number(0)), data("")); + env(set(alice, vault.vaultID), + loanBrokerID(broker->key()), + debtMaximum(Number(0)), + data("")); env.close(); // Check the updated fields @@ -445,7 +464,8 @@ class LoanBroker_test : public beast::unit_test::suite BEAST_EXPECT(!pseudo); } auto const expectedBalance = aliceBalance + coverFunds - - (aliceBalance.value().native() ? STAmount(env.current()->fees().base.value()) : vault.asset(0)); + (aliceBalance.value().native() ? STAmount(env.current()->fees().base.value()) + : vault.asset(0)); env.require(balance(alice, expectedBalance)); env.require(balance(pseudoAccount, vault.asset(none))); } @@ -569,13 +589,21 @@ class LoanBroker_test : public beast::unit_test::suite env(set(evan, vault.vaultID, ~tfUniversal), ter(temINVALID_FLAG)); // field length validation // sfData: good length, bad account - env(set(evan, vault.vaultID), data(std::string(maxDataPayloadLength, 'X')), ter(tecNO_PERMISSION)); + env(set(evan, vault.vaultID), + data(std::string(maxDataPayloadLength, 'X')), + ter(tecNO_PERMISSION)); // sfData: too long - env(set(evan, vault.vaultID), data(std::string(maxDataPayloadLength + 1, 'Y')), ter(temINVALID)); + env(set(evan, vault.vaultID), + data(std::string(maxDataPayloadLength + 1, 'Y')), + ter(temINVALID)); // sfManagementFeeRate: good value, bad account - env(set(evan, vault.vaultID), managementFeeRate(maxManagementFeeRate), ter(tecNO_PERMISSION)); + env(set(evan, vault.vaultID), + managementFeeRate(maxManagementFeeRate), + ter(tecNO_PERMISSION)); // sfManagementFeeRate: too big - env(set(evan, vault.vaultID), managementFeeRate(maxManagementFeeRate + TenthBips16(10)), ter(temINVALID)); + env(set(evan, vault.vaultID), + managementFeeRate(maxManagementFeeRate + TenthBips16(10)), + ter(temINVALID)); // sfCoverRateMinimum and sfCoverRateLiquidation are linked // Cover: good value, bad account env(set(evan, vault.vaultID), @@ -646,11 +674,20 @@ class LoanBroker_test : public beast::unit_test::suite // fields that can't be changed // LoanBrokerID - env(set(alice, vault.vaultID), loanBrokerID(nextKeylet.key), ter(tecNO_ENTRY), THISLINE); + env(set(alice, vault.vaultID), + loanBrokerID(nextKeylet.key), + ter(tecNO_ENTRY), + THISLINE); // VaultID - env(set(alice, nextKeylet.key), loanBrokerID(broker->key()), ter(tecNO_ENTRY), THISLINE); + env(set(alice, nextKeylet.key), + loanBrokerID(broker->key()), + ter(tecNO_ENTRY), + THISLINE); // Owner - env(set(evan, vault.vaultID), loanBrokerID(broker->key()), ter(tecNO_PERMISSION), THISLINE); + env(set(evan, vault.vaultID), + loanBrokerID(broker->key()), + ter(tecNO_PERMISSION), + THISLINE); // ManagementFeeRate env(set(alice, vault.vaultID), loanBrokerID(broker->key()), @@ -709,7 +746,8 @@ class LoanBroker_test : public beast::unit_test::suite Number const expected = STAmount{vault.asset, Number(175, -1)}; auto const actual = broker->at(sfDebtMaximum); BEAST_EXPECTS( - actual == expected, "Expected: " + to_string(expected) + ", Actual: " + to_string(actual)); + actual == expected, + "Expected: " + to_string(expected) + ", Actual: " + to_string(actual)); }); lifecycle( @@ -743,7 +781,10 @@ class LoanBroker_test : public beast::unit_test::suite }, [&](SLE::const_ref broker) { // Reset Data & Debt maximum to default values - env(set(alice, vault.vaultID), loanBrokerID(broker->key()), data(""), debtMaximum(Number(0))); + env(set(alice, vault.vaultID), + loanBrokerID(broker->key()), + data(""), + debtMaximum(Number(0))); }, [&](SLE::const_ref broker) { // Check the updated fields @@ -759,7 +800,8 @@ class LoanBroker_test : public beast::unit_test::suite void testLoanBroker( - std::function getAsset, + std::function + getAsset, LoanBrokerTest brokerTest) { using namespace jtx; @@ -795,7 +837,8 @@ class LoanBroker_test : public beast::unit_test::suite if (vaultInfo.vaultID == uint256{}) return; - env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = asset(50)}), THISLINE); + env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = asset(50)}), + THISLINE); env.close(); auto const brokerKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); @@ -835,17 +878,22 @@ class LoanBroker_test : public beast::unit_test::suite testZeroBrokerID([&]() { return coverDeposit(alice, brokerKeylet.key, asset(10)); }); // preclaim: tecWRONG_ASSET - env(coverDeposit(alice, brokerKeylet.key, issuer["BAD"](10)), ter(tecWRONG_ASSET), THISLINE); + env(coverDeposit(alice, brokerKeylet.key, issuer["BAD"](10)), + ter(tecWRONG_ASSET), + THISLINE); // preclaim: tecINSUFFICIENT_FUNDS env(pay(alice, issuer, asset(100'000 - 50)), THISLINE); env.close(); - env(coverDeposit(alice, brokerKeylet.key, vaultInfo.asset(10)), ter(tecINSUFFICIENT_FUNDS)); + env(coverDeposit(alice, brokerKeylet.key, vaultInfo.asset(10)), + ter(tecINSUFFICIENT_FUNDS)); // preclaim: tecFROZEN env(fset(issuer, asfGlobalFreeze), THISLINE); env.close(); - env(coverDeposit(alice, brokerKeylet.key, vaultInfo.asset(10)), ter(tecFROZEN), THISLINE); + env(coverDeposit(alice, brokerKeylet.key, vaultInfo.asset(10)), + ter(tecFROZEN), + THISLINE); } else // Fund the cover deposit @@ -858,36 +906,53 @@ class LoanBroker_test : public beast::unit_test::suite testZeroBrokerID([&]() { return coverWithdraw(alice, brokerKeylet.key, asset(10)); }); // preclaim: tecWRONG_ASSET - env(coverWithdraw(alice, brokerKeylet.key, issuer["BAD"](10)), ter(tecWRONG_ASSET), THISLINE); + env(coverWithdraw(alice, brokerKeylet.key, issuer["BAD"](10)), + ter(tecWRONG_ASSET), + THISLINE); // preclaim: tecNO_DST Account const bogus{"bogus"}; - env(coverWithdraw(alice, brokerKeylet.key, asset(10)), destination(bogus), ter(tecNO_DST), THISLINE); + env(coverWithdraw(alice, brokerKeylet.key, asset(10)), + destination(bogus), + ter(tecNO_DST), + THISLINE); // preclaim: tecDST_TAG_NEEDED Account const dest{"dest"}; env.fund(XRP(1'000), dest); env(fset(dest, asfRequireDest), THISLINE); env.close(); - env(coverWithdraw(alice, brokerKeylet.key, asset(10)), destination(dest), ter(tecDST_TAG_NEEDED), THISLINE); + env(coverWithdraw(alice, brokerKeylet.key, asset(10)), + destination(dest), + ter(tecDST_TAG_NEEDED), + THISLINE); // preclaim: tecNO_PERMISSION env(fclear(dest, asfRequireDest), THISLINE); env(fset(dest, asfDepositAuth), THISLINE); env.close(); - env(coverWithdraw(alice, brokerKeylet.key, asset(10)), destination(dest), ter(tecNO_PERMISSION), THISLINE); + env(coverWithdraw(alice, brokerKeylet.key, asset(10)), + destination(dest), + ter(tecNO_PERMISSION), + THISLINE); // preclaim: tecFROZEN env(trust(dest, asset(1'000)), THISLINE); env(fclear(dest, asfDepositAuth), THISLINE); env(fset(issuer, asfGlobalFreeze), THISLINE); env.close(); - env(coverWithdraw(alice, brokerKeylet.key, asset(10)), destination(dest), ter(tecFROZEN), THISLINE); + env(coverWithdraw(alice, brokerKeylet.key, asset(10)), + destination(dest), + ter(tecFROZEN), + THISLINE); // preclaim:: tecFROZEN (deep frozen) env(fclear(issuer, asfGlobalFreeze), THISLINE); env(trust(issuer, asset(1'000), dest, tfSetFreeze | tfSetDeepFreeze), THISLINE); - env(coverWithdraw(alice, brokerKeylet.key, asset(10)), destination(dest), ter(tecFROZEN), THISLINE); + env(coverWithdraw(alice, brokerKeylet.key, asset(10)), + destination(dest), + ter(tecFROZEN), + THISLINE); // preclaim: tecPSEUDO_ACCOUNT env(coverWithdraw(alice, brokerKeylet.key, asset(10)), @@ -900,7 +965,10 @@ class LoanBroker_test : public beast::unit_test::suite { // preflight: temINVALID (empty/zero broker id) testZeroBrokerID([&]() { - return env.json(coverClawback(alice), loanBrokerID(brokerKeylet.key), amount(vaultInfo.asset(2))); + return env.json( + coverClawback(alice), + loanBrokerID(brokerKeylet.key), + amount(vaultInfo.asset(2))); }); if (asset.holds()) @@ -967,9 +1035,13 @@ class LoanBroker_test : public beast::unit_test::suite if (brokerTest == Set) { // preflight: temINVALID (empty/zero broker id) - testZeroBrokerID([&]() { return env.json(set(alice, vaultInfo.vaultID), loanBrokerID(brokerKeylet.key)); }); + testZeroBrokerID([&]() { + return env.json(set(alice, vaultInfo.vaultID), loanBrokerID(brokerKeylet.key)); + }); // preflight: temINVALID (empty/zero vault id) - testZeroVaultID([&]() { return env.json(set(alice, vaultInfo.vaultID), loanBrokerID(brokerKeylet.key)); }); + testZeroVaultID([&]() { + return env.json(set(alice, vaultInfo.vaultID), loanBrokerID(brokerKeylet.key)); + }); if (asset.holds()) { @@ -982,7 +1054,8 @@ class LoanBroker_test : public beast::unit_test::suite env.close(); } - auto const amt = env.balance(alice) - env.current()->fees().accountReserve(env.ownerCount(alice)); + auto const amt = + env.balance(alice) - env.current()->fees().accountReserve(env.ownerCount(alice)); env(pay(alice, issuer, amt), THISLINE); // preclaim:: tecINSUFFICIENT_RESERVE @@ -1196,7 +1269,10 @@ class LoanBroker_test : public beast::unit_test::suite // Can't unauthorize Vault pseudo-account asset.authorize( - {.account = issuer, .holder = vaultInfo.pseudoAccount, .flags = tfMPTUnauthorize, .err = tecNO_PERMISSION}); + {.account = issuer, + .holder = vaultInfo.pseudoAccount, + .flags = tfMPTUnauthorize, + .err = tecNO_PERMISSION}); auto forUnauthAuth = [&](auto&& doTx) { for (auto const flag : {tfMPTUnauthorize, 0u}) @@ -1211,13 +1287,15 @@ class LoanBroker_test : public beast::unit_test::suite // Can't deposit into Vault if the vault owner is not authorized forUnauthAuth([&](bool authorized) { auto const err = !authorized ? ter(tecNO_AUTH) : ter(tesSUCCESS); - env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = asset(51)}), err); + env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = asset(51)}), + err); }); // Can't withdraw from Vault if the vault owner is not authorized forUnauthAuth([&](bool authorized) { auto const err = !authorized ? ter(tecNO_AUTH) : ter(tesSUCCESS); - env(vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = asset(1)}), err); + env(vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = asset(1)}), + err); }); auto const brokerKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); @@ -1231,7 +1309,10 @@ class LoanBroker_test : public beast::unit_test::suite // Can't unauthorize LoanBroker pseudo-account asset.authorize( - {.account = issuer, .holder = brokerPseudo, .flags = tfMPTUnauthorize, .err = tecNO_PERMISSION}); + {.account = issuer, + .holder = brokerPseudo, + .flags = tfMPTUnauthorize, + .err = tecNO_PERMISSION}); // Can't cover deposit into Vault if the vault owner is not authorized forUnauthAuth([&](bool authorized) { @@ -1246,8 +1327,9 @@ class LoanBroker_test : public beast::unit_test::suite }); // Issuer can always cover clawback. The holder authorization is n/a. - forUnauthAuth( - [&](bool) { env(coverClawback(issuer), loanBrokerID(brokerKeylet.key), amount(vaultInfo.asset(1))); }); + forUnauthAuth([&](bool) { + env(coverClawback(issuer), loanBrokerID(brokerKeylet.key), amount(vaultInfo.asset(1))); + }); } void @@ -1289,7 +1371,8 @@ class LoanBroker_test : public beast::unit_test::suite if (vaultInfo.vaultID == uint256{}) return; - env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = asset(50)}), THISLINE); + env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = asset(50)}), + THISLINE); env.close(); auto const brokerKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); @@ -1377,7 +1460,8 @@ class LoanBroker_test : public beast::unit_test::suite env(tx); env.close(); - env(vault.deposit({.depositor = broker, .id = keylet.key, .amount = deposit}), ter(err)); + env(vault.deposit({.depositor = broker, .id = keylet.key, .amount = deposit}), + ter(err)); env.close(); auto const brokerKeylet = keylet::loanbroker(broker, env.seq(broker)); @@ -1618,7 +1702,8 @@ class LoanBroker_test : public beast::unit_test::suite .authHolder = true, .maxAmt = 5'000}); // unauthorize dest - tester.authorize({.account = issuer, .holder = dest, .flags = tfMPTUnauthorize}); + tester.authorize( + {.account = issuer, .holder = dest, .flags = tfMPTUnauthorize}); return tester; } case ReachedMAX: { @@ -1670,7 +1755,8 @@ class LoanBroker_test : public beast::unit_test::suite if (err != tesSUCCESS) { - env(vault.withdraw({.depositor = broker, .id = keylet.key, .amount = token(1'000)})); + env(vault.withdraw( + {.depositor = broker, .id = keylet.key, .amount = token(1'000)})); } // Test LoanBroker withdraw diff --git a/src/test/app/Loan_test.cpp b/src/test/app/Loan_test.cpp index 5deb1f179c..607e84abeb 100644 --- a/src/test/app/Loan_test.cpp +++ b/src/test/app/Loan_test.cpp @@ -3,14 +3,12 @@ #include #include -#include -#include -#include -#include - #include #include -// cspell: words LOANTODO +#include +#include +#include +#include #include @@ -23,7 +21,8 @@ protected: // Ensure that all the features needed for Lending Protocol are included, // even if they are set to unsupported. FeatureBitset const all{ - jtx::testable_amendments() | featureMPTokensV1 | featureSingleAssetVault | featureLendingProtocol}; + jtx::testable_amendments() | featureMPTokensV1 | featureSingleAssetVault | + featureLendingProtocol}; std::string const iouCurrency{"IOU"}; @@ -173,7 +172,11 @@ protected: using namespace jtx; using namespace jtx::loan; - JTx jt{loan::set(account, broker.brokerID, broker.asset(principalRequest).number(), flags.value_or(0))}; + JTx jt{loan::set( + account, + broker.brokerID, + broker.asset(principalRequest).number(), + flags.value_or(0))}; sig(sfCounterpartySignature, counter)(env, jt); @@ -274,21 +277,25 @@ protected: std::uint32_t ownerCount) const { using namespace jtx; - if (auto brokerSle = env.le(keylet::loanbroker(broker.brokerID)); env.test.BEAST_EXPECT(brokerSle)) + if (auto brokerSle = env.le(keylet::loanbroker(broker.brokerID)); + env.test.BEAST_EXPECT(brokerSle)) { TenthBips16 const managementFeeRate{brokerSle->at(sfManagementFeeRate)}; auto const brokerDebt = brokerSle->at(sfDebtTotal); auto const expectedDebt = principalOutstanding + interestOwed; env.test.BEAST_EXPECT(brokerDebt == expectedDebt); env.test.BEAST_EXPECT( - env.balance(pseudoAccount, broker.asset).number() == brokerSle->at(sfCoverAvailable)); + env.balance(pseudoAccount, broker.asset).number() == + brokerSle->at(sfCoverAvailable)); env.test.BEAST_EXPECT(brokerSle->at(sfOwnerCount) == ownerCount); - if (auto vaultSle = env.le(keylet::vault(brokerSle->at(sfVaultID))); env.test.BEAST_EXPECT(vaultSle)) + if (auto vaultSle = env.le(keylet::vault(brokerSle->at(sfVaultID))); + env.test.BEAST_EXPECT(vaultSle)) { Account const vaultPseudo{"vaultPseudoAccount", vaultSle->at(sfAccount)}; env.test.BEAST_EXPECT( - vaultSle->at(sfAssetsAvailable) == env.balance(vaultPseudo, broker.asset).number()); + vaultSle->at(sfAssetsAvailable) == + env.balance(vaultPseudo, broker.asset).number()); if (ownerCount == 0) { // Allow some slop for rounding IOUs @@ -318,10 +325,12 @@ protected: auto const borrowerScale = std::max(loanScale, balanceBefore.number().exponent()); STAmount const balanceChangeAmount{ - broker.asset, roundToAsset(broker.asset, expectedPayment + adjustment, borrowerScale)}; + broker.asset, + roundToAsset(broker.asset, expectedPayment + adjustment, borrowerScale)}; { auto const difference = roundToScale( - env.balance(account, broker.asset) - (balanceBefore - balanceChangeAmount), borrowerScale); + env.balance(account, broker.asset) - (balanceBefore - balanceChangeAmount), + borrowerScale); env.test.expect( roundToScale(difference, loanScale) >= beast::zero, "Balance before: " + to_string(balanceBefore.value()) + @@ -354,7 +363,8 @@ protected: env.test.BEAST_EXPECT(loan->at(sfLoanScale) == loanScale); env.test.BEAST_EXPECT(loan->at(sfTotalValueOutstanding) == totalValue); env.test.BEAST_EXPECT(loan->at(sfPrincipalOutstanding) == principalOutstanding); - env.test.BEAST_EXPECT(loan->at(sfManagementFeeOutstanding) == managementFeeOutstanding); + env.test.BEAST_EXPECT( + loan->at(sfManagementFeeOutstanding) == managementFeeOutstanding); env.test.BEAST_EXPECT(loan->at(sfPeriodicPayment) == periodicPayment); env.test.BEAST_EXPECT(loan->at(sfFlags) == flags); @@ -362,9 +372,16 @@ protected: auto const interestRate = TenthBips32{loan->at(sfInterestRate)}; auto const paymentInterval = loan->at(sfPaymentInterval); - checkBroker(principalOutstanding, ls.interestDue, interestRate, paymentInterval, paymentRemaining, 1); + checkBroker( + principalOutstanding, + ls.interestDue, + interestRate, + paymentInterval, + paymentRemaining, + 1); - if (auto brokerSle = env.le(keylet::loanbroker(broker.brokerID)); env.test.BEAST_EXPECT(brokerSle)) + if (auto brokerSle = env.le(keylet::loanbroker(broker.brokerID)); + env.test.BEAST_EXPECT(brokerSle)) { if (auto vaultSle = env.le(keylet::vault(brokerSle->at(sfVaultID))); env.test.BEAST_EXPECT(vaultSle)) @@ -372,7 +389,8 @@ protected: if ((flags & lsfLoanImpaired) && !(flags & lsfLoanDefault)) { env.test.BEAST_EXPECT( - vaultSle->at(sfLossUnrealized) == totalValue - managementFeeOutstanding); + vaultSle->at(sfLossUnrealized) == + totalValue - managementFeeOutstanding); } else { @@ -495,13 +513,16 @@ protected: BEAST_EXPECT(state.principalOutstanding == broker.asset(1000).value()); BEAST_EXPECT( state.loanScale >= - (broker.asset.integral() ? 0 : std::max(broker.vaultScale(env), state.principalOutstanding.exponent()))); + (broker.asset.integral() + ? 0 + : std::max(broker.vaultScale(env), state.principalOutstanding.exponent()))); BEAST_EXPECT(state.paymentInterval == 600); { NumberRoundModeGuard mg(Number::upward); BEAST_EXPECT( state.totalValue == - roundToAsset(broker.asset, state.periodicPayment * state.paymentRemaining, state.loanScale)); + roundToAsset( + broker.asset, state.periodicPayment * state.paymentRemaining, state.loanScale)); } BEAST_EXPECT( state.managementFeeOutstanding == @@ -519,14 +540,17 @@ protected: bool canImpairLoan(jtx::Env const& env, BrokerInfo const& broker, LoanState const& state) { - if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); + BEAST_EXPECT(brokerSle)) { - if (auto const vaultSle = env.le(keylet::vault(brokerSle->at(sfVaultID))); BEAST_EXPECT(vaultSle)) + if (auto const vaultSle = env.le(keylet::vault(brokerSle->at(sfVaultID))); + BEAST_EXPECT(vaultSle)) { // log << vaultSle->getJson() << std::endl; - auto const assetsUnavailable = vaultSle->at(sfAssetsTotal) - vaultSle->at(sfAssetsAvailable); - auto const unrealizedLoss = - vaultSle->at(sfLossUnrealized) + state.totalValue - state.managementFeeOutstanding; + auto const assetsUnavailable = + vaultSle->at(sfAssetsTotal) - vaultSle->at(sfAssetsAvailable); + auto const unrealizedLoss = vaultSle->at(sfLossUnrealized) + state.totalValue - + state.managementFeeOutstanding; if (!BEAST_EXPECT(unrealizedLoss <= assetsUnavailable)) { @@ -560,7 +584,8 @@ protected: case AssetType::IOU: { PrettyAsset const asset{issuer[iouCurrency]}; - auto const limit = asset(100 * (brokerParams.vaultDeposit + brokerParams.coverDeposit)); + auto const limit = + asset(100 * (brokerParams.vaultDeposit + brokerParams.coverDeposit)); if (lender != issuer) env(trust(lender, limit)); if (borrower != issuer) @@ -618,7 +643,13 @@ protected: auto const total = loanParams.payTotal.value_or(LoanSet::defaultPaymentTotal); auto const feeRate = brokerParams.managementFeeRate; auto const props = computeLoanProperties( - asset, principal, interest, interval, total, feeRate, asset(brokerParams.vaultDeposit).number().exponent()); + asset, + principal, + interest, + interval, + total, + feeRate, + asset(brokerParams.vaultDeposit).number().exponent()); log << "Loan properties:\n" << "\tPrincipal: " << principal << std::endl << "\tInterest rate: " << interest << std::endl @@ -733,15 +764,19 @@ protected: // Add extra for transaction fees and reserves, if appropriate, or a // tiny amount for the extra paid in each transaction auto const totalNeeded = state.totalValue + (serviceFee * state.paymentRemaining) + - (broker.asset.native() ? Number( - baseFee * state.paymentRemaining + - env.current()->fees().accountReserve(env.ownerCount(borrower))) - : broker.asset(15).number()); + (broker.asset.native() + ? Number( + baseFee * state.paymentRemaining + + env.current()->fees().accountReserve(env.ownerCount(borrower))) + : broker.asset(15).number()); auto const shortage = totalNeeded - borrowerBalance.number(); if (shortage > beast::zero && (broker.asset.native() || issuer != borrower)) - env(pay((broker.asset.native() ? env.master : issuer), borrower, STAmount{broker.asset, shortage})); + env( + pay((broker.asset.native() ? env.master : issuer), + borrower, + STAmount{broker.asset, shortage})); } void @@ -787,7 +822,8 @@ protected: // the below BEAST_EXPECTs may not hold across assets. auto const periodicRate = loanPeriodicRate(state.interestRate, state.paymentInterval); STAmount const roundedPeriodicPayment{ - broker.asset, roundPeriodicPayment(broker.asset, state.periodicPayment, state.loanScale)}; + broker.asset, + roundPeriodicPayment(broker.asset, state.periodicPayment, state.loanScale)}; if (!showStepBalances) log << currencyLabel << " Payment components: " @@ -799,13 +835,17 @@ protected: << std::endl; // Include the service fee - STAmount const totalDue = roundToScale(roundedPeriodicPayment + serviceFee, state.loanScale, Number::upward); + STAmount const totalDue = + roundToScale(roundedPeriodicPayment + serviceFee, state.loanScale, Number::upward); - auto currentRoundedState = - constructLoanState(state.totalValue, state.principalOutstanding, state.managementFeeOutstanding); + auto currentRoundedState = constructLoanState( + state.totalValue, state.principalOutstanding, state.managementFeeOutstanding); { auto const raw = computeTheoreticalLoanState( - state.periodicPayment, periodicRate, state.paymentRemaining, broker.params.managementFeeRate); + state.periodicPayment, + periodicRate, + state.paymentRemaining, + broker.params.managementFeeRate); if (showStepBalances) { @@ -813,15 +853,17 @@ protected: << "\n\tTotal value: " << currentRoundedState.valueOutstanding << "\n\tPrincipal: " << currentRoundedState.principalOutstanding << "\n\tInterest: " << currentRoundedState.interestDue - << "\n\tMgmt fee: " << currentRoundedState.managementFeeDue << "\n\tPayments remaining " - << state.paymentRemaining << std::endl; + << "\n\tMgmt fee: " << currentRoundedState.managementFeeDue + << "\n\tPayments remaining " << state.paymentRemaining << std::endl; } else { - log << currencyLabel << " Loan starting state: " << state.paymentRemaining << ", " << raw.interestDue - << ", " << raw.principalOutstanding << ", " << raw.managementFeeDue << ", " - << currentRoundedState.valueOutstanding << ", " << currentRoundedState.principalOutstanding << ", " - << currentRoundedState.interestDue << ", " << currentRoundedState.managementFeeDue << std::endl; + log << currencyLabel << " Loan starting state: " << state.paymentRemaining << ", " + << raw.interestDue << ", " << raw.principalOutstanding << ", " + << raw.managementFeeDue << ", " << currentRoundedState.valueOutstanding << ", " + << currentRoundedState.principalOutstanding << ", " + << currentRoundedState.interestDue << ", " + << currentRoundedState.managementFeeDue << std::endl; } } @@ -843,7 +885,10 @@ protected: std::size_t totalPaymentsMade = 0; xrpl::LoanState currentTrueState = computeTheoreticalLoanState( - state.periodicPayment, periodicRate, state.paymentRemaining, broker.params.managementFeeRate); + state.periodicPayment, + periodicRate, + state.paymentRemaining, + broker.params.managementFeeRate); auto validateBorrowerBalance = [&]() { if (borrower == issuer || !paymentParams.validateBalances) @@ -851,7 +896,9 @@ protected: auto const totalSpent = (totalPaid.trackedValueDelta + totalFeesPaid + (broker.asset.native() ? Number(baseFee) * totalPaymentsMade : numZero)); - BEAST_EXPECT(env.balance(borrower, broker.asset).number() == borrowerInitialBalance - totalSpent); + BEAST_EXPECT( + env.balance(borrower, broker.asset).number() == + borrowerInitialBalance - totalSpent); }; auto const defaultRound = broker.asset.integral() ? 3 : 0; @@ -887,9 +934,13 @@ protected: paymentComponents.trackedManagementFeeDelta); xrpl::LoanState const nextTrueState = computeTheoreticalLoanState( - state.periodicPayment, periodicRate, state.paymentRemaining - 1, broker.params.managementFeeRate); + state.periodicPayment, + periodicRate, + state.paymentRemaining - 1, + broker.params.managementFeeRate); detail::LoanStateDeltas const deltas = currentTrueState - nextTrueState; - BEAST_EXPECT(deltas.total() == deltas.principal + deltas.interest + deltas.managementFee); + BEAST_EXPECT( + deltas.total() == deltas.principal + deltas.interest + deltas.managementFee); BEAST_EXPECT( paymentComponents.specialCase == detail::PaymentSpecialCase::final || deltas.total() == state.periodicPayment || @@ -898,16 +949,19 @@ protected: if (!showStepBalances) log << currencyLabel << " Payment components: " << state.paymentRemaining << ", " - << deltas.interest << ", " << deltas.principal << ", " << deltas.managementFee << ", " - << paymentComponents.trackedValueDelta << ", " << paymentComponents.trackedPrincipalDelta << ", " - << paymentComponents.trackedInterestPart() << ", " << paymentComponents.trackedManagementFeeDelta - << ", " - << (paymentComponents.specialCase == detail::PaymentSpecialCase::final ? "final" - : paymentComponents.specialCase == detail::PaymentSpecialCase::extra ? "extra" - : "none") + << deltas.interest << ", " << deltas.principal << ", " << deltas.managementFee + << ", " << paymentComponents.trackedValueDelta << ", " + << paymentComponents.trackedPrincipalDelta << ", " + << paymentComponents.trackedInterestPart() << ", " + << paymentComponents.trackedManagementFeeDelta << ", " + << (paymentComponents.specialCase == detail::PaymentSpecialCase::final ? "final" + : paymentComponents.specialCase == detail::PaymentSpecialCase::extra + ? "extra" + : "none") << std::endl; - auto const totalDueAmount = STAmount{broker.asset, paymentComponents.trackedValueDelta + serviceFee}; + auto const totalDueAmount = + STAmount{broker.asset, paymentComponents.trackedValueDelta + serviceFee}; if (paymentParams.validateBalances) { @@ -919,7 +973,8 @@ protected: // IOUs, the difference should be dust. Number const diff = totalDue - totalDueAmount; BEAST_EXPECT( - paymentComponents.specialCase == detail::PaymentSpecialCase::final || diff == beast::zero || + paymentComponents.specialCase == detail::PaymentSpecialCase::final || + diff == beast::zero || (diff > beast::zero && ((broker.asset.integral() && (static_cast(diff) < 3)) || (state.loanScale - diff.exponent() > 13)))); @@ -950,7 +1005,11 @@ protected: // Check the result verifyLoanStatus.checkPayment( - state.loanScale, borrower, borrowerBalanceBeforePayment, totalDueAmount, adjustment); + state.loanScale, + borrower, + borrowerBalanceBeforePayment, + totalDueAmount, + adjustment); } if (showStepBalances) @@ -964,11 +1023,14 @@ protected: log << currencyLabel << " Loan balances: " << "\n\tAmount taken: " << paymentComponents.trackedValueDelta << "\n\tTotal value: " << current.valueOutstanding - << " (true: " << truncate(nextTrueState.valueOutstanding) << ", error: " << truncate(errors.total()) + << " (true: " << truncate(nextTrueState.valueOutstanding) + << ", error: " << truncate(errors.total()) << ")\n\tPrincipal: " << current.principalOutstanding << " (true: " << truncate(nextTrueState.principalOutstanding) - << ", error: " << truncate(errors.principal) << ")\n\tInterest: " << current.interestDue - << " (true: " << truncate(nextTrueState.interestDue) << ", error: " << truncate(errors.interest) + << ", error: " << truncate(errors.principal) + << ")\n\tInterest: " << current.interestDue + << " (true: " << truncate(nextTrueState.interestDue) + << ", error: " << truncate(errors.interest) << ")\n\tMgmt fee: " << current.managementFeeDue << " (true: " << truncate(nextTrueState.managementFeeDue) << ", error: " << truncate(errors.managementFee) << ")\n\tPayments remaining " @@ -1010,14 +1072,15 @@ protected: BEAST_EXPECT(state.paymentRemaining == 0); BEAST_EXPECT(state.principalOutstanding == 0); - auto const initialInterestDue = - initialState.totalValue - (initialState.principalOutstanding + initialState.managementFeeOutstanding); + auto const initialInterestDue = initialState.totalValue - + (initialState.principalOutstanding + initialState.managementFeeOutstanding); if (paymentParams.validateBalances) { // Make sure all the payments add up BEAST_EXPECT(totalPaid.trackedValueDelta == initialState.totalValue); BEAST_EXPECT(totalPaid.trackedPrincipalDelta == initialState.principalOutstanding); - BEAST_EXPECT(totalPaid.trackedManagementFeeDelta == initialState.managementFeeOutstanding); + BEAST_EXPECT( + totalPaid.trackedManagementFeeDelta == initialState.managementFeeOutstanding); // This is almost a tautology given the previous checks, but // check it anyway for completeness. BEAST_EXPECT(totalInterestPaid == initialInterestDue); @@ -1035,19 +1098,24 @@ protected: << " (initial: " << truncate(initialState.totalValue) << ", error: " << truncate(initialState.totalValue - totalPaid.trackedValueDelta) << ")\n\tPrincipal: " << totalPaid.trackedPrincipalDelta - << " (initial: " << truncate(initialState.principalOutstanding) - << ", error: " << truncate(initialState.principalOutstanding - totalPaid.trackedPrincipalDelta) - << ")\n\tInterest: " << totalInterestPaid << " (initial: " << truncate(initialInterestDue) + << " (initial: " << truncate(initialState.principalOutstanding) << ", error: " + << truncate(initialState.principalOutstanding - totalPaid.trackedPrincipalDelta) + << ")\n\tInterest: " << totalInterestPaid + << " (initial: " << truncate(initialInterestDue) << ", error: " << truncate(initialInterestDue - totalInterestPaid) << ")\n\tMgmt fee: " << totalPaid.trackedManagementFeeDelta - << " (initial: " << truncate(initialState.managementFeeOutstanding) - << ", error: " << truncate(initialState.managementFeeOutstanding - totalPaid.trackedManagementFeeDelta) + << " (initial: " << truncate(initialState.managementFeeOutstanding) << ", error: " + << truncate( + initialState.managementFeeOutstanding - totalPaid.trackedManagementFeeDelta) << ")\n\tTotal payments made: " << totalPaymentsMade << std::endl; } } void - runLoan(AssetType assetType, BrokerParameters const& brokerParams, LoanParameters const& loanParams) + runLoan( + AssetType assetType, + BrokerParameters const& brokerParams, + LoanParameters const& loanParams) { using namespace jtx; @@ -1057,7 +1125,8 @@ protected: Env env(*this, all); - auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); + auto loanResult = + createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); if (!BEAST_EXPECT(loanResult)) return; @@ -1104,7 +1173,8 @@ protected: std::uint32_t flags, // The end of life callback is expected to take the loan to 0 payments // remaining, one way or another - std::function toEndOfLife) + std::function + toEndOfLife) { auto const [keylet, loanSequence] = [&]() { auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); @@ -1194,7 +1264,8 @@ protected: auto const startDate = env.current()->header().parentCloseTime.time_since_epoch().count(); - if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); + BEAST_EXPECT(brokerSle)) { BEAST_EXPECT(brokerSle->at(sfOwnerCount) == 1); } @@ -1209,16 +1280,19 @@ protected: BEAST_EXPECT( env.balance(borrower, broker.asset).value() == - borrowerStartbalance.value() + principalRequestAmount - originationFeeAmount - adjustment.value()); + borrowerStartbalance.value() + principalRequestAmount - originationFeeAmount - + adjustment.value()); } - auto const loanFlags = createJtx.stx->isFlag(tfLoanOverpayment) ? lsfLoanOverpayment : LedgerSpecificFlags(0); + auto const loanFlags = + createJtx.stx->isFlag(tfLoanOverpayment) ? lsfLoanOverpayment : LedgerSpecificFlags(0); if (auto loan = env.le(keylet); BEAST_EXPECT(loan)) { // log << "loan after create: " << to_string(loan->getJson()) // << std::endl; - BEAST_EXPECT(loan->isFlag(lsfLoanOverpayment) == createJtx.stx->isFlag(tfLoanOverpayment)); + BEAST_EXPECT( + loan->isFlag(lsfLoanOverpayment) == createJtx.stx->isFlag(tfLoanOverpayment)); BEAST_EXPECT(loan->at(sfLoanSequence) == loanSequence); BEAST_EXPECT(loan->at(sfBorrower) == borrower.id()); BEAST_EXPECT(loan->at(sfLoanBrokerID) == broker.brokerID); @@ -1239,7 +1313,9 @@ protected: BEAST_EXPECT(loan->at(sfPaymentRemaining) == *loanParams.payTotal); BEAST_EXPECT( loan->at(sfLoanScale) >= - (broker.asset.integral() ? 0 : std::max(broker.vaultScale(env), principalRequestAmount.exponent()))); + (broker.asset.integral() + ? 0 + : std::max(broker.vaultScale(env), principalRequestAmount.exponent()))); BEAST_EXPECT(loan->at(sfPrincipalOutstanding) == principalRequestAmount); } @@ -1282,7 +1358,8 @@ protected: env(manage(lender, keylet.key, tfLoanUnimpair | tfLoanImpair), ter(temINVALID_FLAG)); env(manage(lender, keylet.key, tfLoanImpair | tfLoanDefault), ter(temINVALID_FLAG)); env(manage(lender, keylet.key, tfLoanUnimpair | tfLoanDefault), ter(temINVALID_FLAG)); - env(manage(lender, keylet.key, tfLoanUnimpair | tfLoanImpair | tfLoanDefault), ter(temINVALID_FLAG)); + env(manage(lender, keylet.key, tfLoanUnimpair | tfLoanImpair | tfLoanDefault), + ter(temINVALID_FLAG)); // invalid loan ID env(manage(lender, broker.brokerID, tfLoanImpair), ter(tecNO_ENTRY)); // Loan is unimpaired, can't unimpair it again @@ -1294,9 +1371,11 @@ protected: // Check the vault bool const canImpair = canImpairLoan(env, broker, state); // Impair the loan, if possible - env(manage(lender, keylet.key, tfLoanImpair), canImpair ? ter(tesSUCCESS) : ter(tecLIMIT_EXCEEDED)); + env(manage(lender, keylet.key, tfLoanImpair), + canImpair ? ter(tesSUCCESS) : ter(tecLIMIT_EXCEEDED)); // Unimpair the loan - env(manage(lender, keylet.key, tfLoanUnimpair), canImpair ? ter(tesSUCCESS) : ter(tecNO_PERMISSION)); + env(manage(lender, keylet.key, tfLoanUnimpair), + canImpair ? ter(tesSUCCESS) : ter(tecNO_PERMISSION)); auto const nextDueDate = startDate + *loanParams.payInterval; @@ -1360,10 +1439,13 @@ protected: // No loans left verifyLoanStatus.checkBroker(0, 0, *loanParams.interest, 1, 0, 0); - BEAST_EXPECT(env.balance(borrower, broker.asset).value() == borrowerStartingBalance.value() - adjustment); + BEAST_EXPECT( + env.balance(borrower, broker.asset).value() == + borrowerStartingBalance.value() - adjustment); BEAST_EXPECT(env.ownerCount(borrower) == borrowerOwnerCount); - if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); + BEAST_EXPECT(brokerSle)) { BEAST_EXPECT(brokerSle->at(sfOwnerCount) == 0); } @@ -1372,7 +1454,11 @@ protected: std::string getCurrencyLabel(Asset const& asset) { - return (asset.native() ? "XRP" : asset.holds() ? "IOU" : asset.holds() ? "MPT" : "Unknown"); + return ( + asset.native() ? "XRP" + : asset.holds() ? "IOU" + : asset.holds() ? "MPT" + : "Unknown"); } /** Wrapper to run a series of lifecycle tests for a given asset and loan @@ -1400,8 +1486,8 @@ protected: auto const currencyLabel = getCurrencyLabel(asset); auto const caseLabel = [&]() { std::stringstream ss; - ss << "Lifecycle: " << loanAmount << " " << currencyLabel << " Scale interest to: " << interestExponent - << " "; + ss << "Lifecycle: " << loanAmount << " " << currencyLabel + << " Scale interest to: " << interestExponent << " "; return ss.str(); }(); testcase << caseLabel; @@ -1730,7 +1816,8 @@ protected: env(trust(issuer, holder[iouCurrency](0), tfSetFreeze | tfSetDeepFreeze)); }; auto unfreeze = [&](Account const& holder) { - env(trust(issuer, holder[iouCurrency](0), tfClearFreeze | tfClearDeepFreeze)); + env(trust( + issuer, holder[iouCurrency](0), tfClearFreeze | tfClearDeepFreeze)); }; return std::make_tuple(freeze, deepfreeze, unfreeze, tecFROZEN); } @@ -1819,7 +1906,8 @@ protected: std::string testData; auto coverAvailable = [&env, this](uint256 const& brokerID, Number const& expected) { - if (auto const brokerSle = env.le(keylet::loanbroker(brokerID)); BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(brokerID)); + BEAST_EXPECT(brokerSle)) { auto const available = brokerSle->at(sfCoverAvailable); BEAST_EXPECT(available == expected); @@ -1828,18 +1916,22 @@ protected: return Number{}; }; auto getDefaultInfo = [&env, this](LoanState const& state, BrokerInfo const& broker) { - if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); + BEAST_EXPECT(brokerSle)) { BEAST_EXPECT( - state.loanScale >= (broker.asset.integral() - ? 0 - : std::max(broker.vaultScale(env), state.principalOutstanding.exponent()))); + state.loanScale >= + (broker.asset.integral() + ? 0 + : std::max( + broker.vaultScale(env), state.principalOutstanding.exponent()))); NumberRoundModeGuard mg(Number::upward); auto const defaultAmount = roundToAsset( broker.asset, std::min( tenthBipsOfValue( - tenthBipsOfValue(brokerSle->at(sfDebtTotal), broker.params.coverRateMin), + tenthBipsOfValue( + brokerSle->at(sfDebtTotal), broker.params.coverRateMin), broker.params.coverRateLiquidation), state.totalValue - state.managementFeeOutstanding), state.loanScale); @@ -1853,13 +1945,15 @@ protected: Number const& startingCoverAvailable, Number const& amountToBeCovered) { coverAvailable(broker.brokerID, startingCoverAvailable - amountToBeCovered); - env(loanBroker::coverDeposit(brokerAcct, broker.brokerID, STAmount{broker.asset, amountToBeCovered})); + env(loanBroker::coverDeposit( + brokerAcct, broker.brokerID, STAmount{broker.asset, amountToBeCovered})); coverAvailable(broker.brokerID, startingCoverAvailable); env.close(); }; auto defaultImmediately = [&](std::uint32_t baseFlag, bool impair = true) { - return [&, impair, baseFlag](Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { + return [&, impair, baseFlag]( + Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { // toEndOfLife // // Default the loan @@ -1869,8 +1963,8 @@ protected: BEAST_EXPECT(state.flags == baseFlag); auto const& broker = verifyLoanStatus.broker; - auto const startingCoverAvailable = - coverAvailable(broker.brokerID, broker.asset(broker.params.coverDeposit).number()); + auto const startingCoverAvailable = coverAvailable( + broker.brokerID, broker.asset(broker.params.coverDeposit).number()); if (impair) { @@ -1939,7 +2033,8 @@ protected: verifyLoanStatus(state); // Send some bogus pay transactions - env(pay(borrower, keylet::loan(uint256(0)).key, broker.asset(10), txFlags), ter(temINVALID)); + env(pay(borrower, keylet::loan(uint256(0)).key, broker.asset(10), txFlags), + ter(temINVALID)); // broker.asset(80) is less than a single payment, but all these // checks fail before that matters env(pay(borrower, loanKeylet.key, broker.asset(-80), txFlags), ter(temBAD_AMOUNT)); @@ -1985,12 +2080,14 @@ protected: ter(temINVALID_FLAG)); { - auto const otherAsset = broker.asset.raw() == assets[0].raw() ? assets[1] : assets[0]; + auto const otherAsset = + broker.asset.raw() == assets[0].raw() ? assets[1] : assets[0]; env(pay(borrower, loanKeylet.key, otherAsset(100), txFlags), ter(tecWRONG_ASSET)); } // Amount doesn't cover a single payment - env(pay(borrower, loanKeylet.key, STAmount{broker.asset, 1}, txFlags), ter(tecINSUFFICIENT_PAYMENT)); + env(pay(borrower, loanKeylet.key, STAmount{broker.asset, 1}, txFlags), + ter(tecINSUFFICIENT_PAYMENT)); // Get the balance after these failed transactions take // fees @@ -2005,7 +2102,9 @@ protected: // balance XRPAmount const badFee{ baseFee * - (borrowerBalanceBeforePayment.number() * 2 / state.periodicPayment / loanPaymentsPerFeeIncrement + 1)}; + (borrowerBalanceBeforePayment.number() * 2 / state.periodicPayment / + loanPaymentsPerFeeIncrement + + 1)}; env(pay(borrower, loanKeylet.key, STAmount{broker.asset, borrowerBalanceBeforePayment.number() * 2}, @@ -2031,7 +2130,8 @@ protected: state.principalOutstanding = 0; state.totalValue = 0; state.managementFeeOutstanding = 0; - state.previousPaymentDate = state.nextPaymentDate + state.paymentInterval * (numPayments - 1); + state.previousPaymentDate = + state.nextPaymentDate + state.paymentInterval * (numPayments - 1); state.nextPaymentDate = 0; verifyLoanStatus(state); @@ -2044,7 +2144,8 @@ protected: }; auto fullPayment = [&](std::uint32_t baseFlag) { - return [&, baseFlag](Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { + return [&, baseFlag]( + Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { // toEndOfLife // auto state = getCurrentState(env, broker, loanKeylet, verifyLoanStatus); @@ -2062,63 +2163,92 @@ protected: // the below BEAST_EXPECTs may not hold across assets. Number const interval = state.paymentInterval; auto const periodicRate = interval * Number(12, -2) / secondsInYear; - BEAST_EXPECT(periodicRate == Number(2283105022831050228ULL, -24, Number::normalized{})); + BEAST_EXPECT( + periodicRate == Number(2283105022831050228ULL, -24, Number::normalized{})); STAmount const principalOutstanding{broker.asset, state.principalOutstanding}; STAmount const accruedInterest{ broker.asset, state.principalOutstanding * periodicRate * loanAge / interval}; BEAST_EXPECT(accruedInterest == broker.asset(Number(1141552511415525, -19))); - STAmount const prepaymentPenalty{broker.asset, state.principalOutstanding * Number(36, -3)}; + STAmount const prepaymentPenalty{ + broker.asset, state.principalOutstanding * Number(36, -3)}; BEAST_EXPECT(prepaymentPenalty == broker.asset(36)); STAmount const closePaymentFee = broker.asset(4); auto const payoffAmount = roundToScale( - principalOutstanding + accruedInterest + prepaymentPenalty + closePaymentFee, state.loanScale); + principalOutstanding + accruedInterest + prepaymentPenalty + closePaymentFee, + state.loanScale); BEAST_EXPECT( payoffAmount == - roundToAsset(broker.asset, broker.asset(Number(1040000114155251, -12)).number(), state.loanScale)); + roundToAsset( + broker.asset, + broker.asset(Number(1040000114155251, -12)).number(), + state.loanScale)); // The terms of this loan actually make the early payoff // more expensive than just making payments - BEAST_EXPECT(payoffAmount > state.paymentRemaining * (state.periodicPayment + broker.asset(2).value())); + BEAST_EXPECT( + payoffAmount > + state.paymentRemaining * (state.periodicPayment + broker.asset(2).value())); - singlePayment(loanKeylet, verifyLoanStatus, state, payoffAmount, 1, baseFlag, tfLoanFullPayment); + singlePayment( + loanKeylet, + verifyLoanStatus, + state, + payoffAmount, + 1, + baseFlag, + tfLoanFullPayment); }; }; auto combineAllPayments = [&](std::uint32_t baseFlag) { - return [&, baseFlag](Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { - // toEndOfLife - // + return + [&, baseFlag](Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { + // toEndOfLife + // - auto state = getCurrentState(env, broker, loanKeylet, verifyLoanStatus); - env.close(); + auto state = getCurrentState(env, broker, loanKeylet, verifyLoanStatus); + env.close(); - BEAST_EXPECT( - STAmount(broker.asset, state.periodicPayment) == broker.asset(Number(8333457002039338267, -17))); + BEAST_EXPECT( + STAmount(broker.asset, state.periodicPayment) == + broker.asset(Number(8333457002039338267, -17))); - // Make all the payments in one transaction - // service fee is 2 - auto const startingPayments = state.paymentRemaining; - STAmount const payoffAmount = [&]() { - NumberRoundModeGuard mg(Number::upward); - auto const rawPayoff = startingPayments * (state.periodicPayment + broker.asset(2).value()); - STAmount payoffAmount{broker.asset, rawPayoff}; - BEAST_EXPECTS(payoffAmount == broker.asset(Number(1024014840244721, -12)), to_string(payoffAmount)); - BEAST_EXPECT(payoffAmount > state.principalOutstanding); + // Make all the payments in one transaction + // service fee is 2 + auto const startingPayments = state.paymentRemaining; + STAmount const payoffAmount = [&]() { + NumberRoundModeGuard mg(Number::upward); + auto const rawPayoff = + startingPayments * (state.periodicPayment + broker.asset(2).value()); + STAmount payoffAmount{broker.asset, rawPayoff}; + BEAST_EXPECTS( + payoffAmount == broker.asset(Number(1024014840244721, -12)), + to_string(payoffAmount)); + BEAST_EXPECT(payoffAmount > state.principalOutstanding); - payoffAmount = roundToScale(payoffAmount, state.loanScale); + payoffAmount = roundToScale(payoffAmount, state.loanScale); - return payoffAmount; - }(); + return payoffAmount; + }(); - auto const totalPayoffValue = state.totalValue + startingPayments * broker.asset(2).value(); - STAmount const totalPayoffAmount{broker.asset, totalPayoffValue}; + auto const totalPayoffValue = + state.totalValue + startingPayments * broker.asset(2).value(); + STAmount const totalPayoffAmount{broker.asset, totalPayoffValue}; - BEAST_EXPECTS( - totalPayoffAmount == payoffAmount, - "Payoff amount: " + to_string(payoffAmount) + ". Total Value: " + to_string(totalPayoffAmount)); + BEAST_EXPECTS( + totalPayoffAmount == payoffAmount, + "Payoff amount: " + to_string(payoffAmount) + + ". Total Value: " + to_string(totalPayoffAmount)); - singlePayment(loanKeylet, verifyLoanStatus, state, payoffAmount, state.paymentRemaining, baseFlag, 0); - }; + singlePayment( + loanKeylet, + verifyLoanStatus, + state, + payoffAmount, + state.paymentRemaining, + baseFlag, + 0); + }; }; // There are a lot of fields that can be set on a loan, but most @@ -2273,9 +2403,11 @@ protected: // the below BEAST_EXPECTs may not hold across assets. Number const interval = state.paymentInterval; auto const periodicRate = interval * Number(12, -2) / secondsInYear; - BEAST_EXPECT(periodicRate == Number(2283105022831050228, -24, Number::normalized{})); + BEAST_EXPECT( + periodicRate == Number(2283105022831050228, -24, Number::normalized{})); STAmount const roundedPeriodicPayment{ - broker.asset, roundPeriodicPayment(broker.asset, state.periodicPayment, state.loanScale)}; + broker.asset, + roundPeriodicPayment(broker.asset, state.periodicPayment, state.loanScale)}; testcase << currencyLabel << " Payment components: " << "Payments remaining, rawInterest, rawPrincipal, " @@ -2292,8 +2424,8 @@ protected: Number::upward)); // 83334570.01162141 // Include the service fee - STAmount const totalDue = - roundToScale(roundedPeriodicPayment + serviceFee, state.loanScale, Number::upward); + STAmount const totalDue = roundToScale( + roundedPeriodicPayment + serviceFee, state.loanScale, Number::upward); // Only check the first payment since the rounding // may drift as payments are made BEAST_EXPECT( @@ -2305,33 +2437,47 @@ protected: { auto const raw = computeTheoreticalLoanState( - state.periodicPayment, periodicRate, state.paymentRemaining, broker.params.managementFeeRate); + state.periodicPayment, + periodicRate, + state.paymentRemaining, + broker.params.managementFeeRate); auto const rounded = constructLoanState( - state.totalValue, state.principalOutstanding, state.managementFeeOutstanding); - testcase << currencyLabel << " Loan starting state: " << state.paymentRemaining << ", " - << raw.interestDue << ", " << raw.principalOutstanding << ", " << raw.managementFeeDue - << ", " << rounded.valueOutstanding << ", " << rounded.principalOutstanding << ", " - << rounded.interestDue << ", " << rounded.managementFeeDue; + state.totalValue, + state.principalOutstanding, + state.managementFeeOutstanding); + testcase << currencyLabel << " Loan starting state: " << state.paymentRemaining + << ", " << raw.interestDue << ", " << raw.principalOutstanding << ", " + << raw.managementFeeDue << ", " << rounded.valueOutstanding << ", " + << rounded.principalOutstanding << ", " << rounded.interestDue << ", " + << rounded.managementFeeDue; } // Try to pay a little extra to show that it's _not_ // taken - STAmount const transactionAmount = STAmount{broker.asset, totalDue} + broker.asset(10); + STAmount const transactionAmount = + STAmount{broker.asset, totalDue} + broker.asset(10); // Only check the first payment since the rounding // may drift as payments are made BEAST_EXPECT( transactionAmount == roundToScale( - broker.asset(Number(9533457002039400, -14), Number::upward), state.loanScale, Number::upward)); + broker.asset(Number(9533457002039400, -14), Number::upward), + state.loanScale, + Number::upward)); auto const initialState = state; detail::PaymentComponents totalPaid{ - .trackedValueDelta = 0, .trackedPrincipalDelta = 0, .trackedManagementFeeDelta = 0}; + .trackedValueDelta = 0, + .trackedPrincipalDelta = 0, + .trackedManagementFeeDelta = 0}; Number totalInterestPaid = 0; std::size_t totalPaymentsMade = 0; xrpl::LoanState currentTrueState = computeTheoreticalLoanState( - state.periodicPayment, periodicRate, state.paymentRemaining, broker.params.managementFeeRate); + state.periodicPayment, + periodicRate, + state.paymentRemaining, + broker.params.managementFeeRate); while (state.paymentRemaining > 0) { @@ -2360,17 +2506,21 @@ protected: broker.params.managementFeeRate); detail::LoanStateDeltas const deltas = currentTrueState - nextTrueState; - testcase << currencyLabel << " Payment components: " << state.paymentRemaining << ", " - << deltas.interest << ", " << deltas.principal << ", " << deltas.managementFee << ", " - << paymentComponents.trackedValueDelta << ", " << paymentComponents.trackedPrincipalDelta - << ", " << paymentComponents.trackedInterestPart() << ", " + testcase << currencyLabel << " Payment components: " << state.paymentRemaining + << ", " << deltas.interest << ", " << deltas.principal << ", " + << deltas.managementFee << ", " << paymentComponents.trackedValueDelta + << ", " << paymentComponents.trackedPrincipalDelta << ", " + << paymentComponents.trackedInterestPart() << ", " << paymentComponents.trackedManagementFeeDelta << ", " - << (paymentComponents.specialCase == detail::PaymentSpecialCase::final ? "final" - : paymentComponents.specialCase == detail::PaymentSpecialCase::extra ? "extra" - : "none"); + << (paymentComponents.specialCase == detail::PaymentSpecialCase::final + ? "final" + : paymentComponents.specialCase == + detail::PaymentSpecialCase::extra + ? "extra" + : "none"); - auto const totalDueAmount = - STAmount{broker.asset, paymentComponents.trackedValueDelta + serviceFee.number()}; + auto const totalDueAmount = STAmount{ + broker.asset, paymentComponents.trackedValueDelta + serviceFee.number()}; // Due to the rounding algorithms to keep the interest and // principal in sync with "true" values, the computed amount @@ -2380,14 +2530,16 @@ protected: // IOUs, the difference should be after the 8th digit. Number const diff = totalDue - totalDueAmount; BEAST_EXPECT( - paymentComponents.specialCase == detail::PaymentSpecialCase::final || diff == beast::zero || + paymentComponents.specialCase == detail::PaymentSpecialCase::final || + diff == beast::zero || (diff > beast::zero && ((broker.asset.integral() && (static_cast(diff) < 3)) || (state.loanScale - diff.exponent() > 13)))); BEAST_EXPECT( paymentComponents.trackedValueDelta == - paymentComponents.trackedPrincipalDelta + paymentComponents.trackedInterestPart() + + paymentComponents.trackedPrincipalDelta + + paymentComponents.trackedInterestPart() + paymentComponents.trackedManagementFeeDelta); BEAST_EXPECT( paymentComponents.specialCase == detail::PaymentSpecialCase::final || @@ -2395,7 +2547,8 @@ protected: BEAST_EXPECT( state.paymentRemaining < 12 || - roundToAsset(broker.asset, deltas.principal, state.loanScale, Number::upward) == + roundToAsset( + broker.asset, deltas.principal, state.loanScale, Number::upward) == roundToScale( broker.asset(Number(8333228691531218890, -17), Number::upward), state.loanScale, @@ -2409,7 +2562,8 @@ protected: BEAST_EXPECT( paymentComponents.specialCase == detail::PaymentSpecialCase::final || (state.periodicPayment.exponent() - - (deltas.principal + deltas.interest + deltas.managementFee - state.periodicPayment) + (deltas.principal + deltas.interest + deltas.managementFee - + state.periodicPayment) .exponent()) > 14); auto const borrowerBalanceBeforePayment = env.balance(borrower, broker.asset); @@ -2434,7 +2588,11 @@ protected: // Check the result verifyLoanStatus.checkPayment( - state.loanScale, borrower, borrowerBalanceBeforePayment, totalDueAmount, adjustment); + state.loanScale, + borrower, + borrowerBalanceBeforePayment, + totalDueAmount, + adjustment); --state.paymentRemaining; state.previousPaymentDate = state.nextPaymentDate; @@ -2455,7 +2613,8 @@ protected: totalPaid.trackedValueDelta += paymentComponents.trackedValueDelta; totalPaid.trackedPrincipalDelta += paymentComponents.trackedPrincipalDelta; - totalPaid.trackedManagementFeeDelta += paymentComponents.trackedManagementFeeDelta; + totalPaid.trackedManagementFeeDelta += + paymentComponents.trackedManagementFeeDelta; totalInterestPaid += paymentComponents.trackedInterestPart(); ++totalPaymentsMade; @@ -2469,13 +2628,15 @@ protected: // Make sure all the payments add up BEAST_EXPECT(totalPaid.trackedValueDelta == initialState.totalValue); BEAST_EXPECT(totalPaid.trackedPrincipalDelta == initialState.principalOutstanding); - BEAST_EXPECT(totalPaid.trackedManagementFeeDelta == initialState.managementFeeOutstanding); + BEAST_EXPECT( + totalPaid.trackedManagementFeeDelta == initialState.managementFeeOutstanding); // This is almost a tautology given the previous checks, but // check it anyway for completeness. BEAST_EXPECT( totalInterestPaid == initialState.totalValue - - (initialState.principalOutstanding + initialState.managementFeeOutstanding)); + (initialState.principalOutstanding + + initialState.managementFeeOutstanding)); BEAST_EXPECT(totalPaymentsMade == initialState.paymentRemaining); // Can't impair or default a paid off loan @@ -2503,7 +2664,8 @@ protected: auto const start = clock_type::now(); timed(); - auto const duration = std::chrono::duration_cast(clock_type::now() - start); + auto const duration = + std::chrono::duration_cast(clock_type::now() - start); log << label << " took " << duration.count() << "ms" << std::endl; @@ -2532,7 +2694,8 @@ protected: STAmount const totalDue{ broker.asset, - roundPeriodicPayment(broker.asset, state.periodicPayment + serviceFee, state.loanScale)}; + roundPeriodicPayment( + broker.asset, state.periodicPayment + serviceFee, state.loanScale)}; // Make a single payment time("single payment", [&]() { env(pay(borrower, loanKeylet.key, totalDue)); }); @@ -2542,7 +2705,9 @@ protected: auto const numPayments = (state.paymentRemaining - 2); STAmount const bigPayment{broker.asset, totalDue * numPayments}; XRPAmount const bigFee{baseFee * (numPayments / loanPaymentsPerFeeIncrement + 1)}; - time("ten payments", [&]() { env(pay(borrower, loanKeylet.key, bigPayment), fee(bigFee)); }); + time("ten payments", [&]() { + env(pay(borrower, loanKeylet.key, bigPayment), fee(bigFee)); + }); env.close(); time("final payment", [&]() { @@ -2645,7 +2810,9 @@ protected: MPTTester mptt{env, issuer, mptInitNoFund}; auto const none = LedgerSpecificFlags(0); - mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock | (args.requireAuth ? tfMPTRequireAuth : none)}); + mptt.create( + {.flags = tfMPTCanTransfer | tfMPTCanLock | + (args.requireAuth ? tfMPTRequireAuth : none)}); env.close(); PrettyAsset mptAsset = mptt.issuanceID(); mptt.authorize({.account = lender}); @@ -3148,7 +3315,8 @@ protected: Number const principalRequest = broker.asset(1'000).value(); Vault vault{env}; auto tx = vault.set({.owner = lender, .id = broker.vaultID}); - tx[sfAssetsMaximum] = BrokerParameters::defaults().vaultDeposit + broker.asset(1).number(); + tx[sfAssetsMaximum] = + BrokerParameters::defaults().vaultDeposit + broker.asset(1).number(); env(tx); env.close(); @@ -3223,8 +3391,8 @@ protected: std::vector brokers; for (auto const& asset : assets) { - brokers.emplace_back( - createVaultAndBroker(env, asset, lender, BrokerParameters{.data = "spam spam spam spam"})); + brokers.emplace_back(createVaultAndBroker( + env, asset, lender, BrokerParameters{.data = "spam spam spam spam"})); } // Create and update Loans @@ -3239,13 +3407,15 @@ protected: } } - if (auto brokerSle = env.le(keylet::loanbroker(broker.brokerID)); BEAST_EXPECT(brokerSle)) + if (auto brokerSle = env.le(keylet::loanbroker(broker.brokerID)); + BEAST_EXPECT(brokerSle)) { BEAST_EXPECT(brokerSle->at(sfOwnerCount) == 0); BEAST_EXPECT(brokerSle->at(sfDebtTotal) == 0); auto const coverAvailable = brokerSle->at(sfCoverAvailable); - env(loanBroker::coverWithdraw(lender, broker.brokerID, STAmount(broker.asset, coverAvailable))); + env(loanBroker::coverWithdraw( + lender, broker.brokerID, STAmount(broker.asset, coverAvailable))); env.close(); brokerSle = env.le(keylet::loanbroker(broker.brokerID)); @@ -3291,8 +3461,8 @@ protected: // The LoanSet json can be created without a counterparty signature, // but it will not pass preflight - auto createJson = - env.json(set(lender, broker.brokerID, broker.asset(principalRequest).value()), fee(loanSetFee)); + auto createJson = env.json( + set(lender, broker.brokerID, broker.asset(principalRequest).value()), fee(loanSetFee)); env(createJson, ter(temBAD_SIGNER)); // Adding an empty counterparty signature object also fails, but @@ -3309,7 +3479,9 @@ protected: BEAST_EXPECT(jr.isMember(jss::result)); auto const jResult = jr[jss::result]; BEAST_EXPECT(jResult[jss::error] == "invalidTransaction"); - BEAST_EXPECT(jResult[jss::error_exception] == "fails local checks: Transaction has bad signature."); + BEAST_EXPECT( + jResult[jss::error_exception] == + "fails local checks: Transaction has bad signature."); } // Copy the transaction signature into the counterparty signature. @@ -3396,8 +3568,8 @@ protected: // From FIND-001 testcase << "Batch Bypass Counterparty"; - bool const lendingBatchEnabled = - !std::any_of(Batch::disabledTxTypes.begin(), Batch::disabledTxTypes.end(), [](auto const& disabled) { + bool const lendingBatchEnabled = !std::any_of( + Batch::disabledTxTypes.begin(), Batch::disabledTxTypes.end(), [](auto const& disabled) { return disabled == ttLOAN_BROKER_SET; }); @@ -3479,7 +3651,8 @@ protected: BrokerInfo broker{createVaultAndBroker(env, xrpAsset, lender, brokerParams)}; - if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); + BEAST_EXPECT(brokerSle)) { BEAST_EXPECT(brokerSle->at(sfDebtMaximum) == 0); } @@ -3632,7 +3805,8 @@ protected: lowerFee(); auto const jSubmit = env.rpc("submit", txSignBlob); BEAST_EXPECT( - jSubmit.isMember(jss::result) && jSubmit[jss::result].isMember(jss::engine_result) && + jSubmit.isMember(jss::result) && + jSubmit[jss::result].isMember(jss::engine_result) && jSubmit[jss::result][jss::engine_result].asString() == "tesSUCCESS"); lowerFee(); @@ -3656,7 +3830,8 @@ protected: }(); auto const jSignBorrower = env.rpc("json", "sign", to_string(borrowerSignParams)); BEAST_EXPECT( - jSignBorrower.isMember(jss::result) && jSignBorrower[jss::result].isMember(jss::error) && + jSignBorrower.isMember(jss::result) && + jSignBorrower[jss::result].isMember(jss::error) && jSignBorrower[jss::result][jss::error] == "invalidParams" && jSignBorrower[jss::result].isMember(jss::error_message) && jSignBorrower[jss::result][jss::error_message] == "Destination"); @@ -3689,7 +3864,8 @@ protected: }(); auto const jSignBorrower = env.rpc("json", "sign", to_string(borrowerSignParams)); BEAST_EXPECTS( - jSignBorrower.isMember(jss::result) && jSignBorrower[jss::result].isMember(jss::tx_json), + jSignBorrower.isMember(jss::result) && + jSignBorrower[jss::result].isMember(jss::tx_json), to_string(jSignBorrower)); auto const txBorrowerSignResult = jSignBorrower[jss::result][jss::tx_json]; auto const txBorrowerSignBlob = jSignBorrower[jss::result][jss::tx_blob].asString(); @@ -3720,7 +3896,9 @@ protected: return params; }(); auto const jSignLender = env.rpc("json", "sign", to_string(lenderSignParams)); - BEAST_EXPECT(jSignLender.isMember(jss::result) && jSignLender[jss::result].isMember(jss::tx_json)); + BEAST_EXPECT( + jSignLender.isMember(jss::result) && + jSignLender[jss::result].isMember(jss::tx_json)); auto const txLenderSignResult = jSignLender[jss::result][jss::tx_json]; auto const txLenderSignBlob = jSignLender[jss::result][jss::tx_blob].asString(); @@ -3739,7 +3917,8 @@ protected: jSubmitBlobResult[jss::engine_result].asString() == "tecNO_ENTRY", to_string(jSubmitBlobResult)); - BEAST_EXPECT(!jSubmitBlob.isMember(jss::error) && !jSubmitBlobResult.isMember(jss::error)); + BEAST_EXPECT( + !jSubmitBlob.isMember(jss::error) && !jSubmitBlobResult.isMember(jss::error)); // 4-alt. Lender submits the transaction json originally // received from the Borrower. It gets signed, but is now a @@ -3758,7 +3937,8 @@ protected: jSubmitJsonResult[jss::engine_result].asString() == "tefPAST_SEQ", to_string(jSubmitJsonResult)); - BEAST_EXPECT(!jSubmitJson.isMember(jss::error) && !jSubmitJsonResult.isMember(jss::error)); + BEAST_EXPECT( + !jSubmitJson.isMember(jss::error) && !jSubmitJsonResult.isMember(jss::error)); BEAST_EXPECT(jSubmitBlobTx == jSubmitJsonTx); } @@ -3790,7 +3970,9 @@ protected: return params; }(); auto const jSignLender = env.rpc("json", "sign", to_string(lenderSignParams)); - BEAST_EXPECT(jSignLender.isMember(jss::result) && jSignLender[jss::result].isMember(jss::tx_json)); + BEAST_EXPECT( + jSignLender.isMember(jss::result) && + jSignLender[jss::result].isMember(jss::tx_json)); auto const txLenderSignResult = jSignLender[jss::result][jss::tx_json]; auto const txLenderSignBlob = jSignLender[jss::result][jss::tx_blob].asString(); @@ -3820,7 +4002,9 @@ protected: return params; }(); auto const jSignBorrower = env.rpc("json", "sign", to_string(borrowerSignParams)); - BEAST_EXPECT(jSignBorrower.isMember(jss::result) && jSignBorrower[jss::result].isMember(jss::tx_json)); + BEAST_EXPECT( + jSignBorrower.isMember(jss::result) && + jSignBorrower[jss::result].isMember(jss::tx_json)); auto const txBorrowerSignResult = jSignBorrower[jss::result][jss::tx_json]; auto const txBorrowerSignBlob = jSignBorrower[jss::result][jss::tx_blob].asString(); @@ -3839,7 +4023,8 @@ protected: jSubmitBlobResult[jss::engine_result].asString() == "tecNO_ENTRY", to_string(jSubmitBlobResult)); - BEAST_EXPECT(!jSubmitBlob.isMember(jss::error) && !jSubmitBlobResult.isMember(jss::error)); + BEAST_EXPECT( + !jSubmitBlob.isMember(jss::error) && !jSubmitBlobResult.isMember(jss::error)); // 4-alt. Borrower submits the transaction json originally // received from the Lender. It gets signed, but is now a @@ -3858,7 +4043,8 @@ protected: jSubmitJsonResult[jss::engine_result].asString() == "tefPAST_SEQ", to_string(jSubmitJsonResult)); - BEAST_EXPECT(!jSubmitJson.isMember(jss::error) && !jSubmitJsonResult.isMember(jss::error)); + BEAST_EXPECT( + !jSubmitJson.isMember(jss::error) && !jSubmitJsonResult.isMember(jss::error)); BEAST_EXPECT(jSubmitBlobTx == jSubmitJsonTx); } @@ -3880,10 +4066,12 @@ protected: Env env(*this); auto getCoverBalance = [&](BrokerInfo const& brokerInfo, auto const& accountField) { - if (auto const le = env.le(keylet::loanbroker(brokerInfo.brokerID)); BEAST_EXPECT(le)) + if (auto const le = env.le(keylet::loanbroker(brokerInfo.brokerID)); + BEAST_EXPECT(le)) { auto const account = le->at(accountField); - if (auto const sleLine = env.le(keylet::line(account, IOU)); BEAST_EXPECT(sleLine)) + if (auto const sleLine = env.le(keylet::line(account, IOU)); + BEAST_EXPECT(sleLine)) { STAmount balance = sleLine->at(sfBalance); if (account > issuer.id()) @@ -4060,7 +4248,8 @@ protected: env.close(); auto const pseudoBroker = [&]() -> std::optional { - if (auto brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); BEAST_EXPECT(brokerSle)) + if (auto brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); + BEAST_EXPECT(brokerSle)) { return Account{"pseudo", brokerSle->at(sfAccount)}; } @@ -4074,7 +4263,12 @@ protected: // Lender and pseudoaccount must both be frozen env(trust(issuer, lender["IOU"](1'000), lender, tfSetFreeze | tfSetDeepFreeze), THISLINE); - env(trust(issuer, (*pseudoBroker)["IOU"](1'000), *pseudoBroker, tfSetFreeze | tfSetDeepFreeze), THISLINE); + env(trust( + issuer, + (*pseudoBroker)["IOU"](1'000), + *pseudoBroker, + tfSetFreeze | tfSetDeepFreeze), + THISLINE); env.close(); // preclaim: tecFROZEN due to deep frozen @@ -4121,108 +4315,120 @@ protected: }; // preflight: - testWrapper( - [&](Env& env, BrokerInfo const& brokerInfo, jtx::fee const& loanSetFee, Number const& debtMaximumRequest) { - // first temBAD_SIGNER: TODO - // invalid grace period - { - // zero grace period - env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), - sig(sfCounterpartySignature, lender), - gracePeriod(0), - loanSetFee, - ter(temINVALID)); - - // grace period less than default minimum - env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), - sig(sfCounterpartySignature, lender), - gracePeriod(LoanSet::defaultGracePeriod - 1), - loanSetFee, - ter(temINVALID)); - - // grace period greater than payment interval - env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), - sig(sfCounterpartySignature, lender), - paymentInterval(120), - gracePeriod(121), - loanSetFee, - ter(temINVALID)); - } - // empty/zero broker ID - { - auto jv = set(borrower, uint256{}, debtMaximumRequest); - - auto testZeroBrokerID = [&](std::string const& id, std::uint32_t flags = 0) { - // empty broker ID - jv[sfLoanBrokerID] = id; - env(jv, sig(sfCounterpartySignature, lender), loanSetFee, txflags(flags), ter(temINVALID)); - }; - // empty broker ID - testZeroBrokerID(std::string("")); - // zero broker ID - // needs a flag to distinguish the parsed STTx from the prior - // test - testZeroBrokerID(to_string(uint256{}), tfFullyCanonicalSig); - } - - // preflightCheckSigningKey() failure: - // can it happen? the signature is checked before transactor - // executes - - JTx tx = env.jt( - set(borrower, brokerInfo.brokerID, debtMaximumRequest), + testWrapper([&](Env& env, + BrokerInfo const& brokerInfo, + jtx::fee const& loanSetFee, + Number const& debtMaximumRequest) { + // first temBAD_SIGNER: TODO + // invalid grace period + { + // zero grace period + env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), sig(sfCounterpartySignature, lender), - loanSetFee); - STTx local = *(tx.stx); - auto counterpartySig = local.getFieldObject(sfCounterpartySignature); - auto badPubKey = counterpartySig.getFieldVL(sfSigningPubKey); - badPubKey[20] ^= 0xAA; - counterpartySig.setFieldVL(sfSigningPubKey, badPubKey); - local.setFieldObject(sfCounterpartySignature, counterpartySig); - Json::Value jvResult; - jvResult[jss::tx_blob] = strHex(local.getSerializer().slice()); - auto res = env.rpc("json", "submit", to_string(jvResult))["result"]; - BEAST_EXPECT( - res[jss::error] == "invalidTransaction" && - res[jss::error_exception] == "fails local checks: Counterparty: Invalid signature."); - }); + gracePeriod(0), + loanSetFee, + ter(temINVALID)); + + // grace period less than default minimum + env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), + sig(sfCounterpartySignature, lender), + gracePeriod(LoanSet::defaultGracePeriod - 1), + loanSetFee, + ter(temINVALID)); + + // grace period greater than payment interval + env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), + sig(sfCounterpartySignature, lender), + paymentInterval(120), + gracePeriod(121), + loanSetFee, + ter(temINVALID)); + } + // empty/zero broker ID + { + auto jv = set(borrower, uint256{}, debtMaximumRequest); + + auto testZeroBrokerID = [&](std::string const& id, std::uint32_t flags = 0) { + // empty broker ID + jv[sfLoanBrokerID] = id; + env(jv, + sig(sfCounterpartySignature, lender), + loanSetFee, + txflags(flags), + ter(temINVALID)); + }; + // empty broker ID + testZeroBrokerID(std::string("")); + // zero broker ID + // needs a flag to distinguish the parsed STTx from the prior + // test + testZeroBrokerID(to_string(uint256{}), tfFullyCanonicalSig); + } + + // preflightCheckSigningKey() failure: + // can it happen? the signature is checked before transactor + // executes + + JTx tx = env.jt( + set(borrower, brokerInfo.brokerID, debtMaximumRequest), + sig(sfCounterpartySignature, lender), + loanSetFee); + STTx local = *(tx.stx); + auto counterpartySig = local.getFieldObject(sfCounterpartySignature); + auto badPubKey = counterpartySig.getFieldVL(sfSigningPubKey); + badPubKey[20] ^= 0xAA; + counterpartySig.setFieldVL(sfSigningPubKey, badPubKey); + local.setFieldObject(sfCounterpartySignature, counterpartySig); + Json::Value jvResult; + jvResult[jss::tx_blob] = strHex(local.getSerializer().slice()); + auto res = env.rpc("json", "submit", to_string(jvResult))["result"]; + BEAST_EXPECT( + res[jss::error] == "invalidTransaction" && + res[jss::error_exception] == + "fails local checks: Counterparty: Invalid signature."); + }); // preclaim: - testWrapper( - [&](Env& env, BrokerInfo const& brokerInfo, jtx::fee const& loanSetFee, Number const& debtMaximumRequest) { - // canAddHoldingFailure (IOU only, if MPT doesn't have - // MPTCanTransfer set, then can't create Vault/LoanBroker, - // and LoanSet will fail with different error - env(fclear(issuer, asfDefaultRipple)); - env.close(); - env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), - sig(sfCounterpartySignature, lender), - loanSetFee, - ter(terNO_RIPPLE)); - }); + testWrapper([&](Env& env, + BrokerInfo const& brokerInfo, + jtx::fee const& loanSetFee, + Number const& debtMaximumRequest) { + // canAddHoldingFailure (IOU only, if MPT doesn't have + // MPTCanTransfer set, then can't create Vault/LoanBroker, + // and LoanSet will fail with different error + env(fclear(issuer, asfDefaultRipple)); + env.close(); + env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), + sig(sfCounterpartySignature, lender), + loanSetFee, + ter(terNO_RIPPLE)); + }); // doApply: - testWrapper( - [&](Env& env, BrokerInfo const& brokerInfo, jtx::fee const& loanSetFee, Number const& debtMaximumRequest) { - auto const amt = env.balance(borrower) - env.current()->fees().accountReserve(env.ownerCount(borrower)); - env(pay(borrower, issuer, amt)); + testWrapper([&](Env& env, + BrokerInfo const& brokerInfo, + jtx::fee const& loanSetFee, + Number const& debtMaximumRequest) { + auto const amt = env.balance(borrower) - + env.current()->fees().accountReserve(env.ownerCount(borrower)); + env(pay(borrower, issuer, amt)); - // tecINSUFFICIENT_RESERVE - env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), - sig(sfCounterpartySignature, lender), - loanSetFee, - ter(tecINSUFFICIENT_RESERVE)); + // tecINSUFFICIENT_RESERVE + env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), + sig(sfCounterpartySignature, lender), + loanSetFee, + ter(tecINSUFFICIENT_RESERVE)); - // addEmptyHolding failure - env(pay(issuer, borrower, amt)); - env(fset(issuer, asfGlobalFreeze)); - env.close(); + // addEmptyHolding failure + env(pay(issuer, borrower, amt)); + env(fset(issuer, asfGlobalFreeze)); + env.close(); - env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), - sig(sfCounterpartySignature, lender), - loanSetFee, - ter(tecFROZEN)); - }); + env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), + sig(sfCounterpartySignature, lender), + loanSetFee, + ter(tecFROZEN)); + }); } void @@ -4360,17 +4566,22 @@ protected: verifyLoanStatus(originalState); Number const payment{3'269'349'176'470'588, -12}; - XRPAmount const payFee{baseFee * ((payment / originalState.periodicPayment) / loanPaymentsPerFeeIncrement + 1)}; - auto loanPayTx = env.json(pay(borrower, keylet.key, STAmount{broker.asset, payment}), fee(payFee)); + XRPAmount const payFee{ + baseFee * + ((payment / originalState.periodicPayment) / loanPaymentsPerFeeIncrement + 1)}; + auto loanPayTx = + env.json(pay(borrower, keylet.key, STAmount{broker.asset, payment}), fee(payFee)); BEAST_EXPECT(to_string(payment) == "3269.349176470588"); env(loanPayTx, ter(tesSUCCESS)); env.close(); auto const newState = getCurrentState(env, broker, keylet); - BEAST_EXPECT(isRounded(broker.asset, newState.managementFeeOutstanding, originalState.loanScale)); + BEAST_EXPECT( + isRounded(broker.asset, newState.managementFeeOutstanding, originalState.loanScale)); BEAST_EXPECT(newState.managementFeeOutstanding < originalState.managementFeeOutstanding); BEAST_EXPECT(isRounded(broker.asset, newState.totalValue, originalState.loanScale)); - BEAST_EXPECT(isRounded(broker.asset, newState.principalOutstanding, originalState.loanScale)); + BEAST_EXPECT( + isRounded(broker.asset, newState.principalOutstanding, originalState.loanScale)); } void @@ -4504,12 +4715,15 @@ protected: Number const amount{395937, -2}; loanPayTx["Amount"]["value"] = to_string(amount); XRPAmount const payFee{ - baseFee * std::int64_t(amount / stateBefore.periodicPayment / loanPaymentsPerFeeIncrement + 1)}; + baseFee * + std::int64_t(amount / stateBefore.periodicPayment / loanPaymentsPerFeeIncrement + 1)}; env(loanPayTx, ter(tesSUCCESS), fee(payFee)); env.close(); auto const stateAfter = getCurrentState(env, broker, keylet); - BEAST_EXPECT(stateAfter.paymentRemaining == stateBefore.paymentRemaining - loanMaximumPaymentsPerTransaction); + BEAST_EXPECT( + stateAfter.paymentRemaining == + stateBefore.paymentRemaining - loanMaximumPaymentsPerTransaction); } void @@ -4580,7 +4794,8 @@ protected: auto loanPayTx = env.json(pay(borrower, keylet.key, STAmount{broker.asset, Number{}})); Number const amount{3074'745'058'823'529, -12}; BEAST_EXPECT(to_string(amount) == "3074.745058823529"); - XRPAmount const payFee{baseFee * (amount / stateBefore.periodicPayment / loanPaymentsPerFeeIncrement + 1)}; + XRPAmount const payFee{ + baseFee * (amount / stateBefore.periodicPayment / loanPaymentsPerFeeIncrement + 1)}; loanPayTx["Amount"]["value"] = to_string(amount); env(loanPayTx, fee(payFee), ter(tesSUCCESS)); env.close(); @@ -4590,7 +4805,8 @@ protected: auto loanPayTx = env.json(pay(borrower, keylet.key, STAmount{broker.asset, Number{}})); Number const amount{6732'118'170'944'051, -12}; BEAST_EXPECT(to_string(amount) == "6732.118170944051"); - XRPAmount const payFee{baseFee * (amount / stateBefore.periodicPayment / loanPaymentsPerFeeIncrement + 1)}; + XRPAmount const payFee{ + baseFee * (amount / stateBefore.periodicPayment / loanPaymentsPerFeeIncrement + 1)}; loanPayTx["Amount"]["value"] = to_string(amount); env(loanPayTx, fee(payFee), ter(tesSUCCESS)); env.close(); @@ -4683,13 +4899,16 @@ protected: auto loanPayTx = env.json(pay(borrower, keylet.key, STAmount{broker.asset, Number{}})); Number const amount{9924'81, -2}; BEAST_EXPECT(to_string(amount) == "9924.81"); - XRPAmount const payFee{baseFee * (amount / stateBefore.periodicPayment / loanPaymentsPerFeeIncrement + 1)}; + XRPAmount const payFee{ + baseFee * (amount / stateBefore.periodicPayment / loanPaymentsPerFeeIncrement + 1)}; loanPayTx["Amount"]["value"] = to_string(amount); env(loanPayTx, fee(payFee), ter(tesSUCCESS)); env.close(); auto const stateAfter = getCurrentState(env, broker, keylet); - BEAST_EXPECT(stateAfter.paymentRemaining == stateBefore.paymentRemaining - loanMaximumPaymentsPerTransaction); + BEAST_EXPECT( + stateAfter.paymentRemaining == + stateBefore.paymentRemaining - loanMaximumPaymentsPerTransaction); } void @@ -4752,7 +4971,9 @@ protected: auto const baseFee = env.current()->fees().base; - auto parentCloseTime = [&]() { return env.current()->parentCloseTime().time_since_epoch().count(); }; + auto parentCloseTime = [&]() { + return env.current()->parentCloseTime().time_since_epoch().count(); + }; auto maxLoanTime = [&]() { auto const startDate = parentCloseTime(); @@ -4786,7 +5007,8 @@ protected: auto const interval = maxLoanTime() + 1; auto const total = 1; auto const grace = interval; - auto createJson = env.json(baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); + auto createJson = env.json( + baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); // The grace period can't be larger than the interval. env(createJson, sig(sfCounterpartySignature, lender), ter(tecKILLED)); @@ -4817,7 +5039,8 @@ protected: auto const total = 60; auto const interval = (maxLoanTime() - total) / total; auto const grace = interval; - auto createJson = env.json(baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); + auto createJson = env.json( + baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); env(createJson, sig(sfCounterpartySignature, lender), ter(tecKILLED)); env.close(); @@ -4831,7 +5054,8 @@ protected: auto const grace = 100; auto const interval = maxLoanTime() - grace; auto const total = 1; - auto createJson = env.json(baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); + auto createJson = env.json( + baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); env(createJson, sig(sfCounterpartySignature, lender), ter(tesSUCCESS)); env.close(); @@ -4858,7 +5082,8 @@ protected: auto const grace = 5'000; auto const interval = maxTime - closeStartDate - grace; auto const total = 1; - auto createJson = env.json(baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); + auto createJson = env.json( + baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); env(createJson, sig(sfCounterpartySignature, lender), ter(tesSUCCESS)); env.close(); @@ -4903,7 +5128,8 @@ protected: auto const keylet = keylet::loan(broker.brokerID, loanSequence); auto const interval = maxLoanTime / total; - auto createJson = env.json(baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); + auto createJson = env.json( + baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); env(createJson, sig(sfCounterpartySignature, lender), ter(tesSUCCESS)); env.close(); @@ -4920,7 +5146,8 @@ protected: NumberRoundModeGuard mg{Number::upward}; Number const payment = beforeState.periodicPayment * (total - 1); XRPAmount const payFee{baseFee * ((total - 1) / loanPaymentsPerFeeIncrement + 1)}; - STAmount const paymentAmount = roundToScale(STAmount{broker.asset, payment}, beforeState.loanScale); + STAmount const paymentAmount = + roundToScale(STAmount{broker.asset, payment}, beforeState.loanScale); auto loanPayTx = env.json(pay(borrower, keylet.key, paymentAmount), fee(payFee)); env(loanPayTx, ter(tesSUCCESS)); env.close(); @@ -5167,18 +5394,20 @@ protected: Number const closePaymentFeeRounded = roundToAsset(broker.asset, loanSle->at(sfClosePaymentFee), state.loanScale); - Number const latePaymentFeeRounded = roundToAsset(broker.asset, loanSle->at(sfLatePaymentFee), state.loanScale); + Number const latePaymentFeeRounded = + roundToAsset(broker.asset, loanSle->at(sfLatePaymentFee), state.loanScale); - auto const roundedLoanState = - constructLoanState(state.totalValue, state.principalOutstanding, state.managementFeeOutstanding); + auto const roundedLoanState = constructLoanState( + state.totalValue, state.principalOutstanding, state.managementFeeOutstanding); Number const totalInterestOutstanding = roundedLoanState.interestDue; auto const periodicRate = loanPeriodicRate(interestRateValue, state.paymentInterval); - auto const rawLoanState = - computeTheoreticalLoanState(state.periodicPayment, periodicRate, state.paymentRemaining, managementFeeRate); + auto const rawLoanState = computeTheoreticalLoanState( + state.periodicPayment, periodicRate, state.paymentRemaining, managementFeeRate); auto const parentCloseTime = env.current()->parentCloseTime(); - auto const startDateSeconds = static_cast(state.startDate.time_since_epoch().count()); + auto const startDateSeconds = + static_cast(state.startDate.time_since_epoch().count()); Number const fullPaymentInterest = computeFullPaymentInterest( rawLoanState.principalOutstanding, @@ -5189,9 +5418,10 @@ protected: startDateSeconds, closeInterestRateValue); - Number const roundedFullInterestAmount = roundToAsset(broker.asset, fullPaymentInterest, state.loanScale); - Number const roundedFullManagementFee = - computeManagementFee(broker.asset, roundedFullInterestAmount, managementFeeRate, state.loanScale); + Number const roundedFullInterestAmount = + roundToAsset(broker.asset, fullPaymentInterest, state.loanScale); + Number const roundedFullManagementFee = computeManagementFee( + broker.asset, roundedFullInterestAmount, managementFeeRate, state.loanScale); Number const roundedFullInterest = roundedFullInterestAmount - roundedFullManagementFee; Number const trackedValueDelta = @@ -5203,16 +5433,19 @@ protected: Number const baseFullDue = trackedValueDelta + untrackedInterest + untrackedManagementFee; BEAST_EXPECT(baseFullDue == roundToAsset(broker.asset, baseFullDue, state.loanScale)); - auto const overdueSeconds = parentCloseTime.time_since_epoch().count() - state.nextPaymentDate; + auto const overdueSeconds = + parentCloseTime.time_since_epoch().count() - state.nextPaymentDate; if (!BEAST_EXPECT(overdueSeconds > 0)) return; Number const overdueRate = loanPeriodicRate(lateInterestRateValue, overdueSeconds); Number const lateInterestRaw = state.principalOutstanding * overdueRate; - Number const lateInterestRounded = roundToAsset(broker.asset, lateInterestRaw, state.loanScale); - Number const lateManagementFeeRounded = - computeManagementFee(broker.asset, lateInterestRounded, managementFeeRate, state.loanScale); - Number const penaltyDue = lateInterestRounded + lateManagementFeeRounded + latePaymentFeeRounded; + Number const lateInterestRounded = + roundToAsset(broker.asset, lateInterestRaw, state.loanScale); + Number const lateManagementFeeRounded = computeManagementFee( + broker.asset, lateInterestRounded, managementFeeRate, state.loanScale); + Number const penaltyDue = + lateInterestRounded + lateManagementFeeRounded + latePaymentFeeRounded; BEAST_EXPECT(penaltyDue > Number{}); auto const balanceBefore = env.balance(borrower, broker.asset).number(); @@ -5289,7 +5522,8 @@ protected: BEAST_EXPECT(debtOutstanding > Number{}); BEAST_EXPECT(coverAvailableBefore > Number{}); - log << "debt=" << to_string(debtOutstanding) << " cover_available=" << to_string(coverAvailableBefore); + log << "debt=" << to_string(debtOutstanding) + << " cover_available=" << to_string(coverAvailableBefore); env(coverClawback(issuer, 0), loanBrokerID(broker.brokerID)); env.close(); @@ -5421,14 +5655,17 @@ protected: BEAST_EXPECT(brokerSle2); auto const closePaymentFee = loanSle ? loanSle->at(sfClosePaymentFee) : Number{}; - auto const closeInterestRate = loanSle ? TenthBips32{loanSle->at(sfCloseInterestRate)} : TenthBips32{}; - auto const managementFeeRate = brokerSle2 ? TenthBips16{brokerSle2->at(sfManagementFeeRate)} : TenthBips16{}; + auto const closeInterestRate = + loanSle ? TenthBips32{loanSle->at(sfCloseInterestRate)} : TenthBips32{}; + auto const managementFeeRate = + brokerSle2 ? TenthBips16{brokerSle2->at(sfManagementFeeRate)} : TenthBips16{}; Number const periodicRate2 = loanPeriodicRate(after.interestRate, after.paymentInterval); // Accrued + prepayment-penalty interest based on current periodic // schedule auto const fullPaymentInterest = computeFullPaymentInterest( - detail::loanPrincipalFromPeriodicPayment(after.periodicPayment, periodicRate2, after.paymentRemaining), + detail::loanPrincipalFromPeriodicPayment( + after.periodicPayment, periodicRate2, after.paymentRemaining), periodicRate2, env.current()->parentCloseTime(), after.paymentInterval, @@ -5437,38 +5674,47 @@ protected: closeInterestRate); // Round to asset scale and split interest/fee parts - auto const roundedInterest = roundToAsset(asset.raw(), fullPaymentInterest, after.loanScale); + auto const roundedInterest = + roundToAsset(asset.raw(), fullPaymentInterest, after.loanScale); Number const roundedFullMgmtFee = computeManagementFee(asset.raw(), roundedInterest, managementFeeRate, after.loanScale); Number const roundedFullInterest = roundedInterest - roundedFullMgmtFee; // Show both signed and unsigned deltas to highlight the underflow. - auto const nowSecs = static_cast(env.current()->parentCloseTime().time_since_epoch().count()); - auto const startSecs = static_cast(after.startDate.time_since_epoch().count()); + auto const nowSecs = + static_cast(env.current()->parentCloseTime().time_since_epoch().count()); + auto const startSecs = + static_cast(after.startDate.time_since_epoch().count()); auto const lastPaymentDate = std::max(after.previousPaymentDate, startSecs); - auto const signedDelta = static_cast(nowSecs) - static_cast(lastPaymentDate); + auto const signedDelta = + static_cast(nowSecs) - static_cast(lastPaymentDate); auto const unsignedDelta = static_cast(nowSecs - lastPaymentDate); - log << "PoC window: prev=" << after.previousPaymentDate << " start=" << startSecs << " now=" << nowSecs - << " signedDelta=" << signedDelta << " unsignedDelta=" << unsignedDelta << std::endl; + log << "PoC window: prev=" << after.previousPaymentDate << " start=" << startSecs + << " now=" << nowSecs << " signedDelta=" << signedDelta + << " unsignedDelta=" << unsignedDelta << std::endl; // Reference (clamped) computation: emulate a non-negative accrual // window by clamping prevPaymentDate to 'now' for the full-pay path. auto const prevClamped = std::min(after.previousPaymentDate, nowSecs); auto const fullPaymentInterestClamped = computeFullPaymentInterest( - detail::loanPrincipalFromPeriodicPayment(after.periodicPayment, periodicRate2, after.paymentRemaining), + detail::loanPrincipalFromPeriodicPayment( + after.periodicPayment, periodicRate2, after.paymentRemaining), periodicRate2, env.current()->parentCloseTime(), after.paymentInterval, prevClamped, startSecs, closeInterestRate); - auto const roundedInterestClamped = roundToAsset(asset.raw(), fullPaymentInterestClamped, after.loanScale); - Number const roundedFullMgmtFeeClamped = - computeManagementFee(asset.raw(), roundedInterestClamped, managementFeeRate, after.loanScale); - Number const roundedFullInterestClamped = roundedInterestClamped - roundedFullMgmtFeeClamped; + auto const roundedInterestClamped = + roundToAsset(asset.raw(), fullPaymentInterestClamped, after.loanScale); + Number const roundedFullMgmtFeeClamped = computeManagementFee( + asset.raw(), roundedInterestClamped, managementFeeRate, after.loanScale); + Number const roundedFullInterestClamped = + roundedInterestClamped - roundedFullMgmtFeeClamped; STAmount const fullDueClamped{ asset, - after.principalOutstanding + roundedFullInterestClamped + roundedFullMgmtFeeClamped + closePaymentFee}; + after.principalOutstanding + roundedFullInterestClamped + roundedFullMgmtFeeClamped + + closePaymentFee}; // Collect vault NAV before closing payment auto const vaultId2 = brokerSle2 ? brokerSle2->at(sfVaultID) : uint256{}; @@ -5478,11 +5724,14 @@ protected: Number const assetsTotalBefore = vaultBefore ? vaultBefore->at(sfAssetsTotal) : Number{}; STAmount const fullDue{ - asset, after.principalOutstanding + roundedFullInterest + roundedFullMgmtFee + closePaymentFee}; + asset, + after.principalOutstanding + roundedFullInterest + roundedFullMgmtFee + + closePaymentFee}; log << "PoC payoff: principalOutstanding=" << after.principalOutstanding - << " roundedFullInterest=" << roundedFullInterest << " roundedFullMgmtFee=" << roundedFullMgmtFee - << " closeFee=" << closePaymentFee << " fullDue=" << to_string(fullDue.getJson()) << std::endl; + << " roundedFullInterest=" << roundedFullInterest + << " roundedFullMgmtFee=" << roundedFullMgmtFee << " closeFee=" << closePaymentFee + << " fullDue=" << to_string(fullDue.getJson()) << std::endl; log << "PoC reference (clamped): roundedFullInterestClamped=" << roundedFullInterestClamped << " roundedFullMgmtFeeClamped=" << roundedFullMgmtFeeClamped << " fullDueClamped=" << to_string(fullDueClamped.getJson()) << std::endl; @@ -5500,7 +5749,8 @@ protected: if (vaultAfter) { auto const assetsTotalAfter = vaultAfter->at(sfAssetsTotal); - log << "PoC NAV: assetsTotalBefore=" << assetsTotalBefore << " assetsTotalAfter=" << assetsTotalAfter + log << "PoC NAV: assetsTotalBefore=" << assetsTotalBefore + << " assetsTotalAfter=" << assetsTotalAfter << " delta=" << (assetsTotalAfter - assetsTotalBefore) << std::endl; // Value-based proof: underflowed window yields a payoff larger than @@ -5632,8 +5882,12 @@ protected: // after loan creation the assets total and available should // reflect the value of the loan BEAST_EXPECT(assetsAvail < assetsTotal); - BEAST_EXPECT(assetsAvail == broker.asset(brokerParams.vaultDeposit - loanParams.principalRequest).number()); - BEAST_EXPECT(assetsTotal == broker.asset(brokerParams.vaultDeposit + state.interestDue).number()); + BEAST_EXPECT( + assetsAvail == + broker.asset(brokerParams.vaultDeposit - loanParams.principalRequest).number()); + BEAST_EXPECT( + assetsTotal == + broker.asset(brokerParams.vaultDeposit + state.interestDue).number()); } // Step 7: Trigger default (dust adjustment will occur) @@ -5686,7 +5940,8 @@ protected: Env env(*this, all); - auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); + auto loanResult = + createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); if (!BEAST_EXPECT(loanResult)) return; @@ -5756,7 +6011,8 @@ protected: Env env(*this, all); - auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); + auto loanResult = + createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); if (!BEAST_EXPECT(loanResult)) return; @@ -5818,7 +6074,8 @@ protected: env(tx, txfee); env.close(); - env(vault.deposit({.depositor = depositor, .id = vaultKeyLet.key, .amount = XRP(1'000)}), txfee); + env(vault.deposit({.depositor = depositor, .id = vaultKeyLet.key, .amount = XRP(1'000)}), + txfee); env.close(); auto const brokerKeyLet = keylet::loanbroker(lender.id(), env.seq(lender)); @@ -5844,7 +6101,9 @@ protected: if (auto loan = env.le(loanKeylet); env.test.BEAST_EXPECT(loan)) { - env(loan::pay(borrower, loanKeylet.key, XRPAmount(150'001)), txflags(tfLoanOverpayment), txfee); + env(loan::pay(borrower, loanKeylet.key, XRPAmount(150'001)), + txflags(tfLoanOverpayment), + txfee); env.close(); } } @@ -5893,7 +6152,8 @@ protected: env.close(); // Verify DebtTotal is exactly 804 - if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); + BEAST_EXPECT(brokerSle)) { log << *brokerSle << std::endl; BEAST_EXPECT(brokerSle->at(sfDebtTotal) == Number(804)); @@ -5901,7 +6161,8 @@ protected: // Attempt to withdraw 2 XRP to self, leaving 80 XRP CoverAvailable. // The minimum is 80.4 XRP, which rounds up to 81 XRP, so this fails. - env(coverWithdraw(lender, brokerInfo.brokerID, xrpAsset(2).value()), ter(tecINSUFFICIENT_FUNDS)); + env(coverWithdraw(lender, brokerInfo.brokerID, xrpAsset(2).value()), + ter(tecINSUFFICIENT_FUNDS)); BEAST_EXPECT(env.ter() == tecINSUFFICIENT_FUNDS); env.close(); @@ -5912,7 +6173,8 @@ protected: env.close(); // Validate CoverAvailable == 80 XRP and DebtTotal remains 804 - if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); + BEAST_EXPECT(brokerSle)) { log << *brokerSle << std::endl; BEAST_EXPECT(brokerSle->at(sfCoverAvailable) == xrpAsset(81).value()); @@ -5955,7 +6217,8 @@ protected: Env env(*this, all); - auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); + auto loanResult = + createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); if (!BEAST_EXPECT(loanResult)) return; @@ -6011,7 +6274,9 @@ protected: env(tx, txFee); env.close(); - env(vault.deposit({.depositor = depositor, .id = vaultKeylet.key, .amount = initialVault}), txFee); + env(vault.deposit( + {.depositor = depositor, .id = vaultKeylet.key, .amount = initialVault}), + txFee); env.close(); auto const brokerKeylet = keylet::loanbroker(broker.id(), env.seq(broker)); @@ -6063,7 +6328,8 @@ protected: // service fee transfer in both cases. for (auto const& borrowerAcct : {broker, borrower_}) { - testLoanAsset([&](Env&) -> STAmount { return STAmount{XRPAmount{200'000}}; }, borrowerAcct); + testLoanAsset( + [&](Env&) -> STAmount { return STAmount{XRPAmount{200'000}}; }, borrowerAcct); testLoanAsset( [&](Env& env) -> STAmount { auto const IOU = issuer["USD"]; @@ -6077,7 +6343,11 @@ protected: borrowerAcct); testLoanAsset( [&](Env& env) -> STAmount { - MPTTester mpt({.env = env, .issuer = issuer, .holders = {broker, depositor}, .pay = 100'000'000}); + MPTTester mpt( + {.env = env, + .issuer = issuer, + .holders = {broker, depositor}, + .pay = 100'000'000}); return mpt(200'000); }, borrowerAcct); @@ -6100,13 +6370,15 @@ protected: .coverRateMin = TenthBips32{0}, .managementFeeRate = TenthBips16{0}, .coverRateLiquidation = TenthBips32{0}}; - LoanParameters const loanParams{.account = lender, .counter = issuer, .principalRequest = Number{10000}}; + LoanParameters const loanParams{ + .account = lender, .counter = issuer, .principalRequest = Number{10000}}; auto const assetType = AssetType::IOU; Env env(*this, all); - auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, issuer); + auto loanResult = + createLoan(env, assetType, brokerParams, loanParams, issuer, lender, issuer); if (!BEAST_EXPECT(loanResult)) return; @@ -6161,7 +6433,8 @@ protected: Env env(*this, makeConfig(), all, nullptr, beast::severities::Severity::kWarning); - auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); + auto loanResult = + createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); if (!BEAST_EXPECT(loanResult)) return; @@ -6175,7 +6448,10 @@ protected: auto const state = getCurrentState(env, broker, loanKeylet); env(loan::pay( - borrower, loanKeylet.key, STAmount{broker.asset, state.periodicPayment * 3 / 2 + 1}, tfLoanOverpayment)); + borrower, + loanKeylet.key, + STAmount{broker.asset, state.periodicPayment * 3 / 2 + 1}, + tfLoanOverpayment)); env.close(); PaymentParameters paymentParams{ @@ -6184,7 +6460,15 @@ protected: }; makeLoanPayments( - env, broker, loanParams, loanKeylet, verifyLoanStatus, issuer, lender, borrower, paymentParams); + env, + broker, + loanParams, + loanKeylet, + verifyLoanStatus, + issuer, + lender, + borrower, + paymentParams); } void @@ -6215,9 +6499,10 @@ protected: auto const loanSetFee = fee(env.current()->fees().base * 2); - auto const loanKeylet = - keylet::loan(result.brokerKeylet().key, (env.le(result.brokerKeylet()))->at(sfLoanSequence)); - env(loan::set(borrower, result.brokerKeylet().key, asset(10'000).value(), tfLoanOverpayment), + auto const loanKeylet = keylet::loan( + result.brokerKeylet().key, (env.le(result.brokerKeylet()))->at(sfLoanSequence)); + env(loan::set( + borrower, result.brokerKeylet().key, asset(10'000).value(), tfLoanOverpayment), sig(sfCounterpartySignature, lender), loan::paymentInterval(86400 * 30), loan::paymentTotal(3), @@ -6234,7 +6519,8 @@ protected: BEAST_EXPECTS( env.balance(lender) - loanBrokerBalanceBefore == expectedOverpaymentManagementFee, - "overpayment management fee missmatch; expected:" + to_string(expectedOverpaymentManagementFee) + + "overpayment management fee missmatch; expected:" + + to_string(expectedOverpaymentManagementFee) + " got: " + to_string(env.balance(lender) - loanBrokerBalanceBefore)); } @@ -6296,7 +6582,8 @@ protected: // Verify trustline is still deleted BEAST_EXPECT(env.le(brokerTrustline) == nullptr); // Verify the service fee went to the broker pseudo-account - if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); + BEAST_EXPECT(brokerSle)) { Account const pseudo("pseudo-account", brokerSle->at(sfAccount)); auto const balance = env.balance(pseudo, IOU); @@ -6376,7 +6663,8 @@ protected: // Verify the MPT is still unauthorized. BEAST_EXPECT(env.le(brokerMpt) == nullptr); // Verify the service fee went to the broker pseudo-account - if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); + BEAST_EXPECT(brokerSle)) { Account const pseudo("pseudo-account", brokerSle->at(sfAccount)); auto const balance = env.balance(pseudo, MPT); @@ -6478,7 +6766,8 @@ protected: // Verify broker is still not authorized env(pay(issuer, broker, MPT(1'000)), ter(tecNO_AUTH)); // Verify the service fee went to the broker pseudo-account - if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); + BEAST_EXPECT(brokerSle)) { Account const pseudo("pseudo-account", brokerSle->at(sfAccount)); auto const balance = env.balance(pseudo, MPT); @@ -6579,7 +6868,8 @@ protected: env.close(); PrettyAsset const asset = xrpIssue(); - auto const vaultDepositAmount = asset(200'000); // Enough for 2 x 50k loans plus interest/fees + auto const vaultDepositAmount = + asset(200'000); // Enough for 2 x 50k loans plus interest/fees auto const brokerInfo = createVaultAndBroker( env, diff --git a/src/test/app/MPToken_test.cpp b/src/test/app/MPToken_test.cpp index 965dd86475..5a46331aa9 100644 --- a/src/test/app/MPToken_test.cpp +++ b/src/test/app/MPToken_test.cpp @@ -42,7 +42,11 @@ class MPToken_test : public beast::unit_test::suite // tries to set a txfee while not enabling in the flag mptAlice.create( - {.maxAmt = 100, .assetScale = 0, .transferFee = 1, .metadata = "test", .err = temMALFORMED}); + {.maxAmt = 100, + .assetScale = 0, + .transferFee = 1, + .metadata = "test", + .err = temMALFORMED}); if (!features[featureSingleAssetVault]) { @@ -70,7 +74,11 @@ class MPToken_test : public beast::unit_test::suite { // tries to set DomainID when RequireAuth is not set mptAlice.create( - {.maxAmt = 100, .assetScale = 0, .metadata = "test", .domainID = uint256(42), .err = temMALFORMED}); + {.maxAmt = 100, + .assetScale = 0, + .metadata = "test", + .domainID = uint256(42), + .err = temMALFORMED}); // tries to set zero DomainID mptAlice.create( @@ -100,10 +108,20 @@ class MPToken_test : public beast::unit_test::suite .err = temMALFORMED}); // empty metadata returns error - mptAlice.create({.maxAmt = 100, .assetScale = 0, .transferFee = 0, .metadata = "", .err = temMALFORMED}); + mptAlice.create( + {.maxAmt = 100, + .assetScale = 0, + .transferFee = 0, + .metadata = "", + .err = temMALFORMED}); // MaximumAmount of 0 returns error - mptAlice.create({.maxAmt = 0, .assetScale = 1, .transferFee = 1, .metadata = "test", .err = temMALFORMED}); + mptAlice.create( + {.maxAmt = 0, + .assetScale = 1, + .transferFee = 1, + .metadata = "test", + .err = temMALFORMED}); // MaximumAmount larger than 63 bit returns error mptAlice.create( @@ -140,8 +158,8 @@ class MPToken_test : public beast::unit_test::suite .transferFee = 10, .metadata = "123", .ownerCount = 1, - .flags = tfMPTCanLock | tfMPTRequireAuth | tfMPTCanEscrow | tfMPTCanTrade | tfMPTCanTransfer | - tfMPTCanClawback}); + .flags = tfMPTCanLock | tfMPTRequireAuth | tfMPTCanEscrow | tfMPTCanTrade | + tfMPTCanTransfer | tfMPTCanClawback}); // Get the hash for the most recent transaction. std::string const txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; @@ -175,13 +193,14 @@ class MPToken_test : public beast::unit_test::suite .transferFee = 10, .metadata = "123", .ownerCount = 1, - .flags = tfMPTCanLock | tfMPTRequireAuth | tfMPTCanEscrow | tfMPTCanTrade | tfMPTCanTransfer | - tfMPTCanClawback, + .flags = tfMPTCanLock | tfMPTRequireAuth | tfMPTCanEscrow | tfMPTCanTrade | + tfMPTCanTransfer | tfMPTCanClawback, .domainID = domainId1, }); // Get the hash for the most recent transaction. - std::string const txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; + std::string const txHash{ + env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; Json::Value const result = env.rpc("tx", txHash)[jss::result]; BEAST_EXPECT(result[sfMaximumAmount.getJsonName()] == "9223372036854775807"); @@ -214,7 +233,10 @@ class MPToken_test : public beast::unit_test::suite Env env{*this, features}; MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.destroy({.id = makeMptID(env.seq(alice), alice), .ownerCount = 0, .err = tecOBJECT_NOT_FOUND}); + mptAlice.destroy( + {.id = makeMptID(env.seq(alice), alice), + .ownerCount = 0, + .err = tecOBJECT_NOT_FOUND}); mptAlice.create({.ownerCount = 1}); @@ -267,7 +289,8 @@ class MPToken_test : public beast::unit_test::suite Env env{*this, features - featureMPTokensV1}; MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.authorize({.account = bob, .id = makeMptID(env.seq(alice), alice), .err = temDISABLED}); + mptAlice.authorize( + {.account = bob, .id = makeMptID(env.seq(alice), alice), .err = temDISABLED}); } // Validate fields in MPTokenAuthorize (preflight) @@ -329,7 +352,8 @@ class MPToken_test : public beast::unit_test::suite // bob tries to delete his MPToken, but fails since he still // holds tokens - mptAlice.authorize({.account = bob, .flags = tfMPTUnauthorize, .err = tecHAS_OBLIGATIONS}); + mptAlice.authorize( + {.account = bob, .flags = tfMPTUnauthorize, .err = tecHAS_OBLIGATIONS}); // bob pays back alice 100 tokens mptAlice.pay(bob, alice, 100); @@ -341,7 +365,10 @@ class MPToken_test : public beast::unit_test::suite // bob receives error when he tries to delete his MPToken that has // already been deleted mptAlice.authorize( - {.account = bob, .holderCount = 0, .flags = tfMPTUnauthorize, .err = tecOBJECT_NOT_FOUND}); + {.account = bob, + .holderCount = 0, + .flags = tfMPTUnauthorize, + .err = tecOBJECT_NOT_FOUND}); } // Test bad scenarios with allow-listing in MPTokenAuthorize (preclaim) @@ -390,7 +417,8 @@ class MPToken_test : public beast::unit_test::suite // 1 drop BEAST_EXPECT(incReserve > XRPAmount(1)); - MPTTester mptAlice1(env, alice, {.holders = {bob}, .xrpHolders = acctReserve + (incReserve - 1)}); + MPTTester mptAlice1( + env, alice, {.holders = {bob}, .xrpHolders = acctReserve + (incReserve - 1)}); mptAlice1.create(); MPTTester mptAlice2(env, alice, {.fund = false}); @@ -456,7 +484,8 @@ class MPToken_test : public beast::unit_test::suite mptAlice.authorize({.account = alice, .holder = bob}); // Unauthorize bob's mptoken - mptAlice.authorize({.account = alice, .holder = bob, .holderCount = 1, .flags = tfMPTUnauthorize}); + mptAlice.authorize( + {.account = alice, .holder = bob, .holderCount = 1, .flags = tfMPTUnauthorize}); mptAlice.authorize({.account = bob, .holderCount = 0, .flags = tfMPTUnauthorize}); } @@ -495,7 +524,8 @@ class MPToken_test : public beast::unit_test::suite Env env{*this, features - featureMPTokensV1}; MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.set({.account = bob, .id = makeMptID(env.seq(alice), alice), .err = temDISABLED}); + mptAlice.set( + {.account = bob, .id = makeMptID(env.seq(alice), alice), .err = temDISABLED}); env.enableFeature(featureMPTokensV1); @@ -512,7 +542,11 @@ class MPToken_test : public beast::unit_test::suite // test invalid flags - nothing is being changed mptAlice.set({.account = alice, .flags = 0x00000000, .err = tecNO_PERMISSION}); - mptAlice.set({.account = alice, .holder = bob, .flags = 0x00000000, .err = tecNO_PERMISSION}); + mptAlice.set( + {.account = alice, + .holder = bob, + .flags = 0x00000000, + .err = tecNO_PERMISSION}); // cannot set DomainID since SAV is not enabled mptAlice.set({.account = alice, .domainID = uint256(42), .err = temDISABLED}); @@ -522,7 +556,8 @@ class MPToken_test : public beast::unit_test::suite // test invalid flags - nothing is being changed mptAlice.set({.account = alice, .flags = 0x00000000, .err = temMALFORMED}); - mptAlice.set({.account = alice, .holder = bob, .flags = 0x00000000, .err = temMALFORMED}); + mptAlice.set( + {.account = alice, .holder = bob, .flags = 0x00000000, .err = temMALFORMED}); if (!features[featurePermissionedDomains] || !features[featureSingleAssetVault]) { @@ -532,16 +567,22 @@ class MPToken_test : public beast::unit_test::suite else if (features[featureSingleAssetVault]) { // cannot set DomainID since Holder is set - mptAlice.set({.account = alice, .holder = bob, .domainID = uint256(42), .err = temMALFORMED}); + mptAlice.set( + {.account = alice, + .holder = bob, + .domainID = uint256(42), + .err = temMALFORMED}); } } // set both lock and unlock flags at the same time will fail - mptAlice.set({.account = alice, .flags = tfMPTLock | tfMPTUnlock, .err = temINVALID_FLAG}); + mptAlice.set( + {.account = alice, .flags = tfMPTLock | tfMPTUnlock, .err = temINVALID_FLAG}); // if the holder is the same as the acct that submitted the tx, // tx fails - mptAlice.set({.account = alice, .holder = alice, .flags = tfMPTLock, .err = temMALFORMED}); + mptAlice.set( + {.account = alice, .holder = alice, .flags = tfMPTLock, .err = temMALFORMED}); } // Validate fields in MPTokenIssuanceSet (preclaim) @@ -561,11 +602,13 @@ class MPToken_test : public beast::unit_test::suite // issuer tries to lock a bob's mptoken that has disabled // locking - mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTLock, .err = tecNO_PERMISSION}); + mptAlice.set( + {.account = alice, .holder = bob, .flags = tfMPTLock, .err = tecNO_PERMISSION}); // issuer tries to unlock a bob's mptoken that has disabled // locking - mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTUnlock, .err = tecNO_PERMISSION}); + mptAlice.set( + {.account = alice, .holder = bob, .flags = tfMPTUnlock, .err = tecNO_PERMISSION}); } // Validate fields in MPTokenIssuanceSet (preclaim) @@ -576,7 +619,10 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); // alice trying to set when the mptissuance doesn't exist yet - mptAlice.set({.id = makeMptID(env.seq(alice), alice), .flags = tfMPTLock, .err = tecOBJECT_NOT_FOUND}); + mptAlice.set( + {.id = makeMptID(env.seq(alice), alice), + .flags = tfMPTLock, + .err = tecOBJECT_NOT_FOUND}); // create a mptokenissuance with locking mptAlice.create({.ownerCount = 1, .flags = tfMPTCanLock}); @@ -621,9 +667,11 @@ class MPToken_test : public beast::unit_test::suite mptAlice.set({.domainID = uint256(42), .err = tecOBJECT_NOT_FOUND}); // Trying to lock but locking is disabled - mptAlice.set({.flags = tfMPTUnlock, .domainID = uint256(42), .err = tecNO_PERMISSION}); + mptAlice.set( + {.flags = tfMPTUnlock, .domainID = uint256(42), .err = tecNO_PERMISSION}); - mptAlice.set({.flags = tfMPTUnlock, .domainID = beast::zero, .err = tecNO_PERMISSION}); + mptAlice.set( + {.flags = tfMPTUnlock, .domainID = beast::zero, .err = tecNO_PERMISSION}); } } } @@ -673,13 +721,18 @@ class MPToken_test : public beast::unit_test::suite // Delete bob's mptoken even though it is locked mptAlice.authorize({.account = bob, .flags = tfMPTUnauthorize}); - mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTUnlock, .err = tecOBJECT_NOT_FOUND}); + mptAlice.set( + {.account = alice, + .holder = bob, + .flags = tfMPTUnlock, + .err = tecOBJECT_NOT_FOUND}); return; } // Cannot delete locked MPToken - mptAlice.authorize({.account = bob, .flags = tfMPTUnauthorize, .err = tecNO_PERMISSION}); + mptAlice.authorize( + {.account = bob, .flags = tfMPTUnauthorize, .err = tecNO_PERMISSION}); // alice unlocks mptissuance mptAlice.set({.account = alice, .flags = tfMPTUnlock}); @@ -706,7 +759,8 @@ class MPToken_test : public beast::unit_test::suite Account const credIssuer1{"credIssuer1"}; env.fund(XRP(1000), credIssuer1); - pdomain::Credentials const credentials1{{.issuer = credIssuer1, .credType = credType}}; + pdomain::Credentials const credentials1{ + {.issuer = credIssuer1, .credType = credType}}; env(pdomain::setTx(credIssuer1, credentials1)); return [&]() { @@ -719,7 +773,8 @@ class MPToken_test : public beast::unit_test::suite Account const credIssuer2{"credIssuer2"}; env.fund(XRP(1000), credIssuer2); - pdomain::Credentials const credentials2{{.issuer = credIssuer2, .credType = credType}}; + pdomain::Credentials const credentials2{ + {.issuer = credIssuer2, .credType = credType}}; env(pdomain::setTx(credIssuer2, credentials2)); return [&]() { @@ -861,7 +916,9 @@ class MPToken_test : public beast::unit_test::suite payment[jss::build_path] = true; auto jrr = env.rpc("json", "submit", to_string(payment)); BEAST_EXPECT(jrr[jss::result][jss::error] == "invalidParams"); - BEAST_EXPECT(jrr[jss::result][jss::error_message] == "Field 'build_path' not allowed in this context."); + BEAST_EXPECT( + jrr[jss::result][jss::error_message] == + "Field 'build_path' not allowed in this context."); } // Can't pay negative amount @@ -925,7 +982,8 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTRequireAuth | tfMPTCanTransfer}); + mptAlice.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTRequireAuth | tfMPTCanTransfer}); mptAlice.authorize({.account = bob}); @@ -939,7 +997,8 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTRequireAuth | tfMPTCanTransfer}); + mptAlice.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTRequireAuth | tfMPTCanTransfer}); // bob creates an empty MPToken mptAlice.authorize({.account = bob}); @@ -968,7 +1027,8 @@ class MPToken_test : public beast::unit_test::suite env.fund(XRP(1000), credIssuer1, bob); auto const domainId1 = [&]() { - pdomain::Credentials const credentials1{{.issuer = credIssuer1, .credType = credType}}; + pdomain::Credentials const credentials1{ + {.issuer = credIssuer1, .credType = credType}}; env(pdomain::setTx(credIssuer1, credentials1)); return [&]() { @@ -1009,7 +1069,8 @@ class MPToken_test : public beast::unit_test::suite env.fund(XRP(1000), credIssuer1, bob); auto const domainId1 = [&]() { - pdomain::Credentials const credentials1{{.issuer = credIssuer1, .credType = credType}}; + pdomain::Credentials const credentials1{ + {.issuer = credIssuer1, .credType = credType}}; env(pdomain::setTx(credIssuer1, credentials1)); return [&]() { @@ -1065,7 +1126,8 @@ class MPToken_test : public beast::unit_test::suite env.fund(XRP(1000), credIssuer1, credIssuer2, bob, carol); auto const domainId1 = [&]() { - pdomain::Credentials const credentials{{.issuer = credIssuer1, .credType = credType}}; + pdomain::Credentials const credentials{ + {.issuer = credIssuer1, .credType = credType}}; env(pdomain::setTx(credIssuer1, credentials)); return [&]() { @@ -1076,7 +1138,8 @@ class MPToken_test : public beast::unit_test::suite auto const domainId2 = [&]() { pdomain::Credentials const credentials{ - {.issuer = credIssuer1, .credType = credType}, {.issuer = credIssuer2, .credType = credType}}; + {.issuer = credIssuer1, .credType = credType}, + {.issuer = credIssuer2, .credType = credType}}; env(pdomain::setTx(credIssuer2, credentials)); return [&]() { @@ -1254,7 +1317,11 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); // Transfer fee is 10% - mptAlice.create({.transferFee = 10'000, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); + mptAlice.create( + {.transferFee = 10'000, + .ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanTransfer}); // Holders create MPToken mptAlice.authorize({.account = bob}); @@ -1343,7 +1410,10 @@ class MPToken_test : public beast::unit_test::suite txflags(tfPartialPayment), ter(tecPATH_PARTIAL)); // Payment succeeds if deliver amount >= deliverMin - env(pay(bob, alice, MPT(100)), sendmax(MPT(99)), deliver_min(MPT(99)), txflags(tfPartialPayment)); + env(pay(bob, alice, MPT(100)), + sendmax(MPT(99)), + deliver_min(MPT(99)), + txflags(tfPartialPayment)); } // Issuer fails trying to send more than the maximum amount allowed @@ -1352,7 +1422,8 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create({.maxAmt = 100, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); + mptAlice.create( + {.maxAmt = 100, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); mptAlice.authorize({.account = bob}); @@ -1403,7 +1474,11 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); mptAlice.create( - {.maxAmt = 10'000, .transferFee = 100, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); + {.maxAmt = 10'000, + .transferFee = 100, + .ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanTransfer}); auto const MPT = mptAlice["MPT"]; mptAlice.authorize({.account = bob}); @@ -1418,13 +1493,18 @@ class MPToken_test : public beast::unit_test::suite auto const meta = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; // Issuer got 10 in the transfer fees BEAST_EXPECT( - meta[0u][sfModifiedNode.fieldName][sfFinalFields.fieldName][sfOutstandingAmount.fieldName] == "9990"); + meta[0u][sfModifiedNode.fieldName][sfFinalFields.fieldName] + [sfOutstandingAmount.fieldName] == "9990"); // Destination account got 9'990 - BEAST_EXPECT(meta[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName][sfMPTAmount.fieldName] == "9990"); + BEAST_EXPECT( + meta[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName] + [sfMPTAmount.fieldName] == "9990"); // Source account spent 10'000 BEAST_EXPECT( - meta[2u][sfModifiedNode.fieldName][sfPreviousFields.fieldName][sfMPTAmount.fieldName] == "10000"); - BEAST_EXPECT(!meta[2u][sfModifiedNode.fieldName][sfFinalFields.fieldName].isMember(sfMPTAmount.fieldName)); + meta[2u][sfModifiedNode.fieldName][sfPreviousFields.fieldName] + [sfMPTAmount.fieldName] == "10000"); + BEAST_EXPECT(!meta[2u][sfModifiedNode.fieldName][sfFinalFields.fieldName].isMember( + sfMPTAmount.fieldName)); // payment between the holders fails without // partial payment @@ -1437,7 +1517,11 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); - mptAlice.create({.maxAmt = maxMPTokenAmount, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); + mptAlice.create( + {.maxAmt = maxMPTokenAmount, + .ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanTransfer}); auto const MPT = mptAlice["MPT"]; mptAlice.authorize({.account = bob}); @@ -1565,7 +1649,8 @@ class MPToken_test : public beast::unit_test::suite env.close(); MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTRequireAuth | tfMPTCanTransfer}); + mptAlice.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTRequireAuth | tfMPTCanTransfer}); env(pay(diana, bob, XRP(500))); env.close(); @@ -1640,7 +1725,8 @@ class MPToken_test : public beast::unit_test::suite env.close(); MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTRequireAuth | tfMPTCanTransfer}); + mptAlice.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTRequireAuth | tfMPTCanTransfer}); env(pay(diana, bob, XRP(500))); env.close(); @@ -1769,10 +1855,12 @@ class MPToken_test : public beast::unit_test::suite Json::Value jv; jv[jss::TransactionType] = jss::AMMCreate; jv[jss::Account] = alice.human(); - jv[jss::Amount] = - (field.fieldName == sfAmount.fieldName) ? mpt.getJson(JsonOptions::none) : "100000000"; - jv[jss::Amount2] = - (field.fieldName == sfAmount2.fieldName) ? mpt.getJson(JsonOptions::none) : "100000000"; + jv[jss::Amount] = (field.fieldName == sfAmount.fieldName) + ? mpt.getJson(JsonOptions::none) + : "100000000"; + jv[jss::Amount2] = (field.fieldName == sfAmount2.fieldName) + ? mpt.getJson(JsonOptions::none) + : "100000000"; jv[jss::TradingFee] = 0; test(jv, field.fieldName); }; @@ -1821,7 +1909,10 @@ class MPToken_test : public beast::unit_test::suite test(jv, field.fieldName); }; for (SField const& field : - {toSFieldRef(sfBidMin), toSFieldRef(sfBidMax), toSFieldRef(sfAsset), toSFieldRef(sfAsset2)}) + {toSFieldRef(sfBidMin), + toSFieldRef(sfBidMax), + toSFieldRef(sfAsset), + toSFieldRef(sfAsset2)}) ammBid(field); // AMMClawback auto ammClawback = [&](SField const& field) { @@ -1832,7 +1923,8 @@ class MPToken_test : public beast::unit_test::suite setMPTFields(field, jv); test(jv, field.fieldName); }; - for (SField const& field : {toSFieldRef(sfAmount), toSFieldRef(sfAsset), toSFieldRef(sfAsset2)}) + for (SField const& field : + {toSFieldRef(sfAmount), toSFieldRef(sfAsset), toSFieldRef(sfAsset2)}) ammClawback(field); // AMMDelete auto ammDelete = [&](SField const& field) { @@ -1965,13 +2057,14 @@ class MPToken_test : public beast::unit_test::suite } // XChainAddClaimAttestation { - Json::Value const jv = claim_attestation(alice, jvb, alice, mpt, alice, true, 1, alice, signer(alice)); + Json::Value const jv = + claim_attestation(alice, jvb, alice, mpt, alice, true, 1, alice, signer(alice)); test(jv, jss::Amount.c_str()); } // XChainAddAccountCreateAttestation { - Json::Value jv = - create_account_attestation(alice, jvb, alice, mpt, XRP(10), alice, false, 1, alice, signer(alice)); + Json::Value jv = create_account_attestation( + alice, jvb, alice, mpt, XRP(10), alice, false, 1, alice, signer(alice)); for (auto const& field : {sfAmount.fieldName, sfSignatureReward.fieldName}) { jv[field] = mpt.getJson(JsonOptions::none); @@ -1997,12 +2090,14 @@ class MPToken_test : public beast::unit_test::suite jv[jss::Account] = alice.human(); jv[sfXChainBridge.fieldName] = jvb; jv[sfSignatureReward.fieldName] = rewardAmount.getJson(JsonOptions::none); - jv[sfMinAccountCreateAmount.fieldName] = minAccountAmount.getJson(JsonOptions::none); + jv[sfMinAccountCreateAmount.fieldName] = + minAccountAmount.getJson(JsonOptions::none); test(jv, field); }; auto reward = STAmount{sfSignatureReward, mpt}; auto minAmount = STAmount{sfMinAccountCreateAmount, USD(10)}; - for (SField const& field : {std::ref(sfSignatureReward), std::ref(sfMinAccountCreateAmount)}) + for (SField const& field : + {std::ref(sfSignatureReward), std::ref(sfMinAccountCreateAmount)}) { bridgeTx(jss::XChainCreateBridge, reward, minAmount, field.fieldName); bridgeTx(jss::XChainModifyBridge, reward, minAmount, field.fieldName); @@ -2140,7 +2235,8 @@ class MPToken_test : public beast::unit_test::suite env.close(); MPTTester mptAlice(env, alice, {.holders = {bob}}); - auto const fakeMpt = xrpl::test::jtx::MPT(alice.name(), makeMptID(env.seq(alice), alice)); + auto const fakeMpt = + xrpl::test::jtx::MPT(alice.name(), makeMptID(env.seq(alice), alice)); // issuer tries to clawback MPT where issuance doesn't exist env(claw(alice, fakeMpt(5), bob), ter(tecOBJECT_NOT_FOUND)); @@ -2228,7 +2324,8 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); // alice creates issuance - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock | tfMPTCanClawback}); + mptAlice.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock | tfMPTCanClawback}); // bob creates a MPToken mptAlice.authorize({.account = bob}); @@ -2250,7 +2347,8 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); // alice creates issuance - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock | tfMPTCanClawback}); + mptAlice.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock | tfMPTCanClawback}); // bob creates a MPToken mptAlice.authorize({.account = bob}); @@ -2272,7 +2370,8 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); // alice creates issuance - mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback | tfMPTRequireAuth}); + mptAlice.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback | tfMPTRequireAuth}); // bob creates a MPToken mptAlice.authorize({.account = bob}); @@ -2482,13 +2581,28 @@ class MPToken_test : public beast::unit_test::suite auto const mptID = makeMptID(env.seq(alice), alice); // Holder is not allowed when MutableFlags is present - mptAlice.set({.account = alice, .holder = bob, .id = mptID, .mutableFlags = 2, .err = temMALFORMED}); + mptAlice.set( + {.account = alice, + .holder = bob, + .id = mptID, + .mutableFlags = 2, + .err = temMALFORMED}); // Holder is not allowed when MPTokenMetadata is present - mptAlice.set({.account = alice, .holder = bob, .id = mptID, .metadata = "test", .err = temMALFORMED}); + mptAlice.set( + {.account = alice, + .holder = bob, + .id = mptID, + .metadata = "test", + .err = temMALFORMED}); // Holder is not allowed when TransferFee is present - mptAlice.set({.account = alice, .holder = bob, .id = mptID, .transferFee = 100, .err = temMALFORMED}); + mptAlice.set( + {.account = alice, + .holder = bob, + .id = mptID, + .transferFee = 100, + .err = temMALFORMED}); } // Can not set Flags when MutableFlags, MPTokenMetadata or @@ -2498,16 +2612,20 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); mptAlice.create( {.ownerCount = 1, - .mutableFlags = tmfMPTCanMutateMetadata | tmfMPTCanMutateCanLock | tmfMPTCanMutateTransferFee}); + .mutableFlags = tmfMPTCanMutateMetadata | tmfMPTCanMutateCanLock | + tmfMPTCanMutateTransferFee}); // Setting flags is not allowed when MutableFlags is present - mptAlice.set({.account = alice, .flags = tfMPTCanLock, .mutableFlags = 2, .err = temMALFORMED}); + mptAlice.set( + {.account = alice, .flags = tfMPTCanLock, .mutableFlags = 2, .err = temMALFORMED}); // Setting flags is not allowed when MPTokenMetadata is present - mptAlice.set({.account = alice, .flags = tfMPTCanLock, .metadata = "test", .err = temMALFORMED}); + mptAlice.set( + {.account = alice, .flags = tfMPTCanLock, .metadata = "test", .err = temMALFORMED}); // setting flags is not allowed when TransferFee is present - mptAlice.set({.account = alice, .flags = tfMPTCanLock, .transferFee = 100, .err = temMALFORMED}); + mptAlice.set( + {.account = alice, .flags = tfMPTCanLock, .transferFee = 100, .err = temMALFORMED}); } // Flags being 0 or tfFullyCanonicalSig is fine @@ -2522,7 +2640,11 @@ class MPToken_test : public beast::unit_test::suite .mutableFlags = tmfMPTCanMutateTransferFee | tmfMPTCanMutateMetadata}); mptAlice.set({.account = alice, .flags = 0, .transferFee = 100, .metadata = "test"}); - mptAlice.set({.account = alice, .flags = tfFullyCanonicalSig, .transferFee = 200, .metadata = "test2"}); + mptAlice.set( + {.account = alice, + .flags = tfFullyCanonicalSig, + .transferFee = 200, + .metadata = "test2"}); } // Invalid MutableFlags @@ -2533,7 +2655,8 @@ class MPToken_test : public beast::unit_test::suite for (auto const flags : {10000, 0, 5000}) { - mptAlice.set({.account = alice, .id = mptID, .mutableFlags = flags, .err = temINVALID_FLAG}); + mptAlice.set( + {.account = alice, .id = mptID, .mutableFlags = flags, .err = temINVALID_FLAG}); } } @@ -2551,11 +2674,16 @@ class MPToken_test : public beast::unit_test::suite tmfMPTSetCanTransfer | tmfMPTClearCanTransfer, tmfMPTSetCanClawback | tmfMPTClearCanClawback, tmfMPTSetCanLock | tmfMPTClearCanLock | tmfMPTClearCanTrade, - tmfMPTSetCanTransfer | tmfMPTClearCanTransfer | tmfMPTSetCanEscrow | tmfMPTClearCanClawback}; + tmfMPTSetCanTransfer | tmfMPTClearCanTransfer | tmfMPTSetCanEscrow | + tmfMPTClearCanClawback}; for (auto const& mutableFlags : flagCombinations) { - mptAlice.set({.account = alice, .id = mptID, .mutableFlags = mutableFlags, .err = temINVALID_FLAG}); + mptAlice.set( + {.account = alice, + .id = mptID, + .mutableFlags = mutableFlags, + .err = temINVALID_FLAG}); } } @@ -2582,7 +2710,8 @@ class MPToken_test : public beast::unit_test::suite for (auto const& mutableFlag : mutableFlags) { - mptAlice.set({.account = alice, .mutableFlags = mutableFlag, .err = tecNO_PERMISSION}); + mptAlice.set( + {.account = alice, .mutableFlags = mutableFlag, .err = tecNO_PERMISSION}); } } @@ -2615,7 +2744,10 @@ class MPToken_test : public beast::unit_test::suite mptAlice.create({.ownerCount = 1, .mutableFlags = tmfMPTCanMutateTransferFee}); mptAlice.set( - {.account = alice, .id = mptID, .transferFee = maxTransferFee + 1, .err = temBAD_TRANSFER_FEE}); + {.account = alice, + .id = mptID, + .transferFee = maxTransferFee + 1, + .err = temBAD_TRANSFER_FEE}); } // Test setting non-zero transfer fee and clearing MPTCanTransfer at the @@ -2633,12 +2765,16 @@ class MPToken_test : public beast::unit_test::suite // Can not set non-zero transfer fee and clear MPTCanTransfer at the // same time mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearCanTransfer, .transferFee = 1, .err = temMALFORMED}); + {.account = alice, + .mutableFlags = tmfMPTClearCanTransfer, + .transferFee = 1, + .err = temMALFORMED}); // Can set transfer fee to zero and clear MPTCanTransfer at the same // time. tfMPTCanTransfer will be cleared and TransferFee field will // be removed. - mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanTransfer, .transferFee = 0}); + mptAlice.set( + {.account = alice, .mutableFlags = tmfMPTClearCanTransfer, .transferFee = 0}); BEAST_EXPECT(!mptAlice.isTransferFeePresent()); } @@ -2647,7 +2783,9 @@ class MPToken_test : public beast::unit_test::suite Env env{*this, features}; MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create({.ownerCount = 1, .mutableFlags = tmfMPTCanMutateTransferFee | tmfMPTCanMutateCanTransfer}); + mptAlice.create( + {.ownerCount = 1, + .mutableFlags = tmfMPTCanMutateTransferFee | tmfMPTCanMutateCanTransfer}); mptAlice.set({.account = alice, .transferFee = 100, .err = tecNO_PERMISSION}); @@ -2655,7 +2793,10 @@ class MPToken_test : public beast::unit_test::suite // at the same time. MPTCanTransfer must be set first, then transfer // fee can be set in a separate transaction. mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTSetCanTransfer, .transferFee = 100, .err = tecNO_PERMISSION}); + {.account = alice, + .mutableFlags = tmfMPTSetCanTransfer, + .transferFee = 100, + .err = tecNO_PERMISSION}); } // Can not mutate transfer fee when it is not mutable @@ -2677,7 +2818,8 @@ class MPToken_test : public beast::unit_test::suite mptAlice.create( {.ownerCount = 1, - .mutableFlags = tmfMPTCanMutateCanTrade | tmfMPTCanMutateCanTransfer | tmfMPTCanMutateMetadata}); + .mutableFlags = tmfMPTCanMutateCanTrade | tmfMPTCanMutateCanTransfer | + tmfMPTCanMutateMetadata}); // Can not mutate transfer fee mptAlice.set({.account = alice, .transferFee = 100, .err = tecNO_PERMISSION}); @@ -2695,7 +2837,8 @@ class MPToken_test : public beast::unit_test::suite // Can not mutate flags which are not mutable for (auto const& mutableFlag : invalidFlags) { - mptAlice.set({.account = alice, .mutableFlags = mutableFlag, .err = tecNO_PERMISSION}); + mptAlice.set( + {.account = alice, .mutableFlags = mutableFlag, .err = tecNO_PERMISSION}); } // Can mutate MPTCanTrade @@ -2724,7 +2867,8 @@ class MPToken_test : public beast::unit_test::suite { Env env{*this, features}; MPTTester mptAlice(env, alice); - mptAlice.create({.metadata = "test", .ownerCount = 1, .mutableFlags = tmfMPTCanMutateMetadata}); + mptAlice.create( + {.metadata = "test", .ownerCount = 1, .mutableFlags = tmfMPTCanMutateMetadata}); std::vector metadatas = { "mutate metadata", @@ -2774,7 +2918,9 @@ class MPToken_test : public beast::unit_test::suite // Test flag toggling { - auto testFlagToggle = [&](std::uint32_t createFlags, std::uint32_t setFlags, std::uint32_t clearFlags) { + auto testFlagToggle = [&](std::uint32_t createFlags, + std::uint32_t setFlags, + std::uint32_t clearFlags) { Env env{*this, features}; MPTTester mptAlice(env, alice); @@ -2793,11 +2939,14 @@ class MPToken_test : public beast::unit_test::suite }; testFlagToggle(tmfMPTCanMutateCanLock, tfMPTCanLock, tmfMPTClearCanLock); - testFlagToggle(tmfMPTCanMutateRequireAuth, tmfMPTSetRequireAuth, tmfMPTClearRequireAuth); + testFlagToggle( + tmfMPTCanMutateRequireAuth, tmfMPTSetRequireAuth, tmfMPTClearRequireAuth); testFlagToggle(tmfMPTCanMutateCanEscrow, tmfMPTSetCanEscrow, tmfMPTClearCanEscrow); testFlagToggle(tmfMPTCanMutateCanTrade, tmfMPTSetCanTrade, tmfMPTClearCanTrade); - testFlagToggle(tmfMPTCanMutateCanTransfer, tmfMPTSetCanTransfer, tmfMPTClearCanTransfer); - testFlagToggle(tmfMPTCanMutateCanClawback, tmfMPTSetCanClawback, tmfMPTClearCanClawback); + testFlagToggle( + tmfMPTCanMutateCanTransfer, tmfMPTSetCanTransfer, tmfMPTClearCanTransfer); + testFlagToggle( + tmfMPTCanMutateCanClawback, tmfMPTSetCanClawback, tmfMPTClearCanClawback); } } @@ -2818,7 +2967,8 @@ class MPToken_test : public beast::unit_test::suite {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock | tfMPTCanTransfer, - .mutableFlags = tmfMPTCanMutateCanLock | tmfMPTCanMutateCanTrade | tmfMPTCanMutateTransferFee}); + .mutableFlags = tmfMPTCanMutateCanLock | tmfMPTCanMutateCanTrade | + tmfMPTCanMutateTransferFee}); mptAlice.authorize({.account = bob, .holderCount = 1}); // Lock bob's mptoken @@ -2841,7 +2991,8 @@ class MPToken_test : public beast::unit_test::suite {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanLock | tmfMPTCanMutateCanClawback | tmfMPTCanMutateMetadata}); + .mutableFlags = tmfMPTCanMutateCanLock | tmfMPTCanMutateCanClawback | + tmfMPTCanMutateMetadata}); mptAlice.authorize({.account = bob, .holderCount = 1}); // Lock issuance @@ -2864,7 +3015,8 @@ class MPToken_test : public beast::unit_test::suite {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanLock | tmfMPTCanMutateCanClawback | tmfMPTCanMutateMetadata}); + .mutableFlags = tmfMPTCanMutateCanLock | tmfMPTCanMutateCanClawback | + tmfMPTCanMutateMetadata}); mptAlice.authorize({.account = bob, .holderCount = 1}); // Can lock and unlock @@ -2879,8 +3031,10 @@ class MPToken_test : public beast::unit_test::suite // Can not lock or unlock mptAlice.set({.account = alice, .flags = tfMPTLock, .err = tecNO_PERMISSION}); mptAlice.set({.account = alice, .flags = tfMPTUnlock, .err = tecNO_PERMISSION}); - mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTLock, .err = tecNO_PERMISSION}); - mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTUnlock, .err = tecNO_PERMISSION}); + mptAlice.set( + {.account = alice, .holder = bob, .flags = tfMPTLock, .err = tecNO_PERMISSION}); + mptAlice.set( + {.account = alice, .holder = bob, .flags = tfMPTUnlock, .err = tecNO_PERMISSION}); // Set MPTCanLock again mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanLock}); @@ -2904,7 +3058,10 @@ class MPToken_test : public beast::unit_test::suite Account const bob("bob"); MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create({.ownerCount = 1, .flags = tfMPTRequireAuth, .mutableFlags = tmfMPTCanMutateRequireAuth}); + mptAlice.create( + {.ownerCount = 1, + .flags = tfMPTRequireAuth, + .mutableFlags = tmfMPTCanMutateRequireAuth}); mptAlice.authorize({.account = bob}); mptAlice.authorize({.account = alice, .holder = bob}); @@ -2952,7 +3109,10 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {carol, bob}}); mptAlice.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer, .mutableFlags = tmfMPTCanMutateCanEscrow}); + {.ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanTransfer, + .mutableFlags = tmfMPTCanMutateCanEscrow}); mptAlice.authorize({.account = carol}); mptAlice.authorize({.account = bob}); @@ -2998,7 +3158,9 @@ class MPToken_test : public beast::unit_test::suite Env env{*this, features}; MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); - mptAlice.create({.ownerCount = 1, .mutableFlags = tmfMPTCanMutateCanTransfer | tmfMPTCanMutateTransferFee}); + mptAlice.create( + {.ownerCount = 1, + .mutableFlags = tmfMPTCanMutateCanTransfer | tmfMPTCanMutateTransferFee}); mptAlice.authorize({.account = bob}); mptAlice.authorize({.account = carol}); @@ -3015,7 +3177,10 @@ class MPToken_test : public beast::unit_test::suite // Can not set non-zero transfer fee even when trying to set // MPTCanTransfer at the same time mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTSetCanTransfer, .transferFee = 100, .err = tecNO_PERMISSION}); + {.account = alice, + .mutableFlags = tmfMPTSetCanTransfer, + .transferFee = 100, + .err = tecNO_PERMISSION}); // Alice sets MPTCanTransfer mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanTransfer}); @@ -3076,7 +3241,8 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create({.ownerCount = 1, .holderCount = 0, .mutableFlags = tmfMPTCanMutateCanClawback}); + mptAlice.create( + {.ownerCount = 1, .holderCount = 0, .mutableFlags = tmfMPTCanMutateCanClawback}); // Bob creates an MPToken mptAlice.authorize({.account = bob}); diff --git a/src/test/app/Manifest_test.cpp b/src/test/app/Manifest_test.cpp index 5b7e34ad5b..a790584ac2 100644 --- a/src/test/app/Manifest_test.cpp +++ b/src/test/app/Manifest_test.cpp @@ -87,7 +87,12 @@ public: } std::string - makeManifestString(PublicKey const& pk, SecretKey const& sk, PublicKey const& spk, SecretKey const& ssk, int seq) + makeManifestString( + PublicKey const& pk, + SecretKey const& sk, + PublicKey const& spk, + SecretKey const& ssk, + int seq) { STObject st(sfGeneric); st[sfSequence] = seq; @@ -112,7 +117,8 @@ public: st[sfSequence] = std::numeric_limits::max(); st[sfPublicKey] = pk; - sign(st, HashPrefix::manifest, type, invalidSig ? randomSecretKey() : sk, sfMasterSignature); + sign( + st, HashPrefix::manifest, type, invalidSig ? randomSecretKey() : sk, sfMasterSignature); BEAST_EXPECT(invalidSig ^ verify(st, HashPrefix::manifest, pk, sfMasterSignature)); Serializer s; @@ -130,7 +136,8 @@ public: st[sfSequence] = std::numeric_limits::max(); st[sfPublicKey] = pk; - sign(st, HashPrefix::manifest, type, invalidSig ? randomSecretKey() : sk, sfMasterSignature); + sign( + st, HashPrefix::manifest, type, invalidSig ? randomSecretKey() : sk, sfMasterSignature); BEAST_EXPECT(invalidSig ^ verify(st, HashPrefix::manifest, pk, sfMasterSignature)); Serializer s; @@ -164,7 +171,8 @@ public: sign(st, HashPrefix::manifest, stype, ssk); BEAST_EXPECT(verify(st, HashPrefix::manifest, spk)); - sign(st, HashPrefix::manifest, type, invalidSig ? randomSecretKey() : sk, sfMasterSignature); + sign( + st, HashPrefix::manifest, type, invalidSig ? randomSecretKey() : sk, sfMasterSignature); BEAST_EXPECT(invalidSig ^ verify(st, HashPrefix::manifest, pk, sfMasterSignature)); Serializer s; @@ -199,7 +207,8 @@ public: auto dbCon = makeTestWalletDB(setup, dbName, env.journal); - auto getPopulatedManifests = [](ManifestCache const& cache) -> std::vector { + auto getPopulatedManifests = + [](ManifestCache const& cache) -> std::vector { std::vector result; result.reserve(32); cache.for_each_manifest([&result](Manifest const& man) { result.push_back(&man); }); @@ -220,14 +229,17 @@ public: { // save should not store untrusted master keys to db // except for revocations - m.save(*dbCon, "ValidatorManifests", [&unl](PublicKey const& pubKey) { return unl->listed(pubKey); }); + m.save(*dbCon, "ValidatorManifests", [&unl](PublicKey const& pubKey) { + return unl->listed(pubKey); + }); ManifestCache loaded; loaded.load(*dbCon, "ValidatorManifests"); // check that all loaded manifests are revocations - std::vector const loadedManifests(sort(getPopulatedManifests(loaded))); + std::vector const loadedManifests( + sort(getPopulatedManifests(loaded))); for (auto const& man : loadedManifests) BEAST_EXPECT(man->revoked()); @@ -241,20 +253,24 @@ public: s1.push_back(toBase58(TokenType::NodePublic, man->masterKey)); unl->load({}, s1, keys); - m.save(*dbCon, "ValidatorManifests", [&unl](PublicKey const& pubKey) { return unl->listed(pubKey); }); + m.save(*dbCon, "ValidatorManifests", [&unl](PublicKey const& pubKey) { + return unl->listed(pubKey); + }); ManifestCache loaded; loaded.load(*dbCon, "ValidatorManifests"); // check that the manifest caches are the same - std::vector const loadedManifests(sort(getPopulatedManifests(loaded))); + std::vector const loadedManifests( + sort(getPopulatedManifests(loaded))); if (inManifests.size() == loadedManifests.size()) { - BEAST_EXPECT(std::equal( - inManifests.begin(), - inManifests.end(), - loadedManifests.begin(), - [](Manifest const* lhs, Manifest const* rhs) { return *lhs == *rhs; })); + BEAST_EXPECT( + std::equal( + inManifests.begin(), + inManifests.end(), + loadedManifests.begin(), + [](Manifest const* lhs, Manifest const* rhs) { return *lhs == *rhs; })); } else { @@ -267,7 +283,8 @@ public: std::vector const emptyRevocation; std::string const badManifest = "bad manifest"; - BEAST_EXPECT(!loaded.load(*dbCon, "ValidatorManifests", badManifest, emptyRevocation)); + BEAST_EXPECT( + !loaded.load(*dbCon, "ValidatorManifests", badManifest, emptyRevocation)); auto const sk = randomSecretKey(); auto const pk = derivePublicKey(KeyType::ed25519, sk); @@ -275,7 +292,8 @@ public: std::string const cfgManifest = makeManifestString(pk, sk, kp.first, kp.second, 0); - BEAST_EXPECT(loaded.load(*dbCon, "ValidatorManifests", cfgManifest, emptyRevocation)); + BEAST_EXPECT( + loaded.load(*dbCon, "ValidatorManifests", cfgManifest, emptyRevocation)); } { // load config revocation @@ -283,23 +301,29 @@ public: std::string const emptyManifest; std::vector const badRevocation = {"bad revocation"}; - BEAST_EXPECT(!loaded.load(*dbCon, "ValidatorManifests", emptyManifest, badRevocation)); + BEAST_EXPECT( + !loaded.load(*dbCon, "ValidatorManifests", emptyManifest, badRevocation)); auto const sk = randomSecretKey(); auto const keyType = KeyType::ed25519; auto const pk = derivePublicKey(keyType, sk); auto const kp = randomKeyPair(KeyType::secp256k1); - std::vector const nonRevocation = {makeManifestString(pk, sk, kp.first, kp.second, 0)}; + std::vector const nonRevocation = { + makeManifestString(pk, sk, kp.first, kp.second, 0)}; - BEAST_EXPECT(!loaded.load(*dbCon, "ValidatorManifests", emptyManifest, nonRevocation)); + BEAST_EXPECT( + !loaded.load(*dbCon, "ValidatorManifests", emptyManifest, nonRevocation)); BEAST_EXPECT(!loaded.revoked(pk)); - std::vector const badSigRevocation = {makeRevocationString(sk, keyType, true)}; - BEAST_EXPECT(!loaded.load(*dbCon, "ValidatorManifests", emptyManifest, badSigRevocation)); + std::vector const badSigRevocation = { + makeRevocationString(sk, keyType, true)}; + BEAST_EXPECT( + !loaded.load(*dbCon, "ValidatorManifests", emptyManifest, badSigRevocation)); BEAST_EXPECT(!loaded.revoked(pk)); std::vector const cfgRevocation = {makeRevocationString(sk, keyType)}; - BEAST_EXPECT(loaded.load(*dbCon, "ValidatorManifests", emptyManifest, cfgRevocation)); + BEAST_EXPECT( + loaded.load(*dbCon, "ValidatorManifests", emptyManifest, cfgRevocation)); BEAST_EXPECT(loaded.revoked(pk)); } @@ -349,7 +373,8 @@ public: auto const kp0 = randomKeyPair(KeyType::secp256k1); BEAST_EXPECT( ManifestDisposition::accepted == - cache.applyManifest(makeManifest(sk, KeyType::ed25519, kp0.second, KeyType::secp256k1, 0))); + cache.applyManifest( + makeManifest(sk, KeyType::ed25519, kp0.second, KeyType::secp256k1, 0))); BEAST_EXPECT(cache.getSigningKey(pk) == kp0.first); BEAST_EXPECT(cache.getMasterKey(kp0.first) == pk); @@ -360,7 +385,8 @@ public: auto const kp1 = randomKeyPair(KeyType::secp256k1); BEAST_EXPECT( ManifestDisposition::accepted == - cache.applyManifest(makeManifest(sk, KeyType::ed25519, kp1.second, KeyType::secp256k1, 1))); + cache.applyManifest( + makeManifest(sk, KeyType::ed25519, kp1.second, KeyType::secp256k1, 1))); BEAST_EXPECT(cache.getSigningKey(pk) == kp1.first); BEAST_EXPECT(cache.getMasterKey(kp1.first) == pk); BEAST_EXPECT(cache.getMasterKey(kp0.first) == kp0.first); @@ -369,7 +395,8 @@ public: // applied with the same signing key but a higher sequence BEAST_EXPECT( ManifestDisposition::badEphemeralKey == - cache.applyManifest(makeManifest(sk, KeyType::ed25519, kp1.second, KeyType::secp256k1, 2))); + cache.applyManifest( + makeManifest(sk, KeyType::ed25519, kp1.second, KeyType::secp256k1, 2))); BEAST_EXPECT(cache.getSigningKey(pk) == kp1.first); BEAST_EXPECT(cache.getMasterKey(kp1.first) == pk); BEAST_EXPECT(cache.getMasterKey(kp0.first) == kp0.first); @@ -377,7 +404,9 @@ public: // getSigningKey should return std::nullopt for a revoked master public // key getMasterKey should return std::nullopt for an ephemeral public // key from a revoked master public key - BEAST_EXPECT(ManifestDisposition::accepted == cache.applyManifest(makeRevocation(sk, KeyType::ed25519))); + BEAST_EXPECT( + ManifestDisposition::accepted == + cache.applyManifest(makeRevocation(sk, KeyType::ed25519))); BEAST_EXPECT(cache.revoked(pk)); BEAST_EXPECT(cache.getSigningKey(pk) == pk); BEAST_EXPECT(cache.getMasterKey(kp0.first) == kp0.first); @@ -390,8 +419,8 @@ public: testcase("validator token"); { - auto const valSecret = - parseBase58(TokenType::NodePrivate, "paQmjZ37pKKPMrgadBLsuf9ab7Y7EUNzh27LQrZqoexpAs31nJi"); + auto const valSecret = parseBase58( + TokenType::NodePrivate, "paQmjZ37pKKPMrgadBLsuf9ab7Y7EUNzh27LQrZqoexpAs31nJi"); // Format token string to test trim() std::vector const tokenBlob = { @@ -481,13 +510,29 @@ public: std::uint32_t sequence = 0; // public key with invalid type - std::array const badKey{0x99, 0x30, 0xE7, 0xFC, 0x9D, 0x56, 0xBB, 0x25, 0xD6, 0x89, 0x3B, - 0xA3, 0xF3, 0x17, 0xAE, 0x5B, 0xCF, 0x33, 0xB3, 0x29, 0x1B, 0xD6, - 0x3D, 0xB3, 0x26, 0x54, 0xA3, 0x13, 0x22, 0x2F, 0x7F, 0xD0, 0x20}; + std::array const badKey{ + 0x99, 0x30, 0xE7, 0xFC, 0x9D, 0x56, 0xBB, 0x25, 0xD6, 0x89, 0x3B, + 0xA3, 0xF3, 0x17, 0xAE, 0x5B, 0xCF, 0x33, 0xB3, 0x29, 0x1B, 0xD6, + 0x3D, 0xB3, 0x26, 0x54, 0xA3, 0x13, 0x22, 0x2F, 0x7F, 0xD0, 0x20}; // Short public key: std::array const shortKey{ - 0x03, 0x30, 0xE7, 0xFC, 0x9D, 0x56, 0xBB, 0x25, 0xD6, 0x89, 0x3B, 0xA3, 0xF3, 0x17, 0xAE, 0x5B}; + 0x03, + 0x30, + 0xE7, + 0xFC, + 0x9D, + 0x56, + 0xBB, + 0x25, + 0xD6, + 0x89, + 0x3B, + 0xA3, + 0xF3, + 0x17, + 0xAE, + 0x5B}; auto toString = [](STObject const& st) { Serializer s; @@ -529,8 +574,8 @@ public: }; { - testcase << "deserializeManifest: normal manifest (" << to_string(keyType) << " + " - << to_string(sKeyType) << ")"; + testcase << "deserializeManifest: normal manifest (" << to_string(keyType) + << " + " << to_string(sKeyType) << ")"; { // valid manifest without domain auto const st = buildManifestObject(++sequence, std::nullopt); @@ -669,13 +714,13 @@ public: } { - testcase << "deserializeManifest: revocation manifest (" << to_string(keyType) << " + " - << to_string(sKeyType) << ")"; + testcase << "deserializeManifest: revocation manifest (" << to_string(keyType) + << " + " << to_string(sKeyType) << ")"; // valid revocation { - auto const st = - buildManifestObject(std::numeric_limits::max(), std::nullopt, true, true); + auto const st = buildManifestObject( + std::numeric_limits::max(), std::nullopt, true, true); auto const m = toString(st); auto const manifest = deserializeManifest(m); @@ -693,20 +738,20 @@ public: } { // can't specify an ephemeral signing key - auto const st = - buildManifestObject(std::numeric_limits::max(), std::nullopt, true, false); + auto const st = buildManifestObject( + std::numeric_limits::max(), std::nullopt, true, false); BEAST_EXPECT(!deserializeManifest(toString(st))); } { // can't specify an ephemeral signature - auto const st = - buildManifestObject(std::numeric_limits::max(), std::nullopt, false, true); + auto const st = buildManifestObject( + std::numeric_limits::max(), std::nullopt, false, true); BEAST_EXPECT(!deserializeManifest(toString(st))); } { // can't specify an ephemeral key & signature - auto const st = - buildManifestObject(std::numeric_limits::max(), std::nullopt, false, false); + auto const st = buildManifestObject( + std::numeric_limits::max(), std::nullopt, false, false); BEAST_EXPECT(!deserializeManifest(toString(st))); } @@ -804,16 +849,20 @@ public: auto const pk_a = derivePublicKey(KeyType::ed25519, sk_a); auto const kp_a0 = randomKeyPair(KeyType::secp256k1); auto const kp_a1 = randomKeyPair(KeyType::secp256k1); - auto const s_a0 = makeManifest(sk_a, KeyType::ed25519, kp_a0.second, KeyType::secp256k1, 0); - auto const s_a1 = makeManifest(sk_a, KeyType::ed25519, kp_a1.second, KeyType::secp256k1, 1); - auto const s_a2 = makeManifest(sk_a, KeyType::ed25519, kp_a1.second, KeyType::secp256k1, 2); + auto const s_a0 = + makeManifest(sk_a, KeyType::ed25519, kp_a0.second, KeyType::secp256k1, 0); + auto const s_a1 = + makeManifest(sk_a, KeyType::ed25519, kp_a1.second, KeyType::secp256k1, 1); + auto const s_a2 = + makeManifest(sk_a, KeyType::ed25519, kp_a1.second, KeyType::secp256k1, 2); auto const s_aMax = makeRevocation(sk_a, KeyType::ed25519); auto const sk_b = randomSecretKey(); auto const kp_b0 = randomKeyPair(KeyType::secp256k1); auto const kp_b1 = randomKeyPair(KeyType::secp256k1); auto const kp_b2 = randomKeyPair(KeyType::secp256k1); - auto const s_b0 = makeManifest(sk_b, KeyType::ed25519, kp_b0.second, KeyType::secp256k1, 0); + auto const s_b0 = + makeManifest(sk_b, KeyType::ed25519, kp_b0.second, KeyType::secp256k1, 0); auto const s_b1 = makeManifest( sk_b, KeyType::ed25519, @@ -821,7 +870,8 @@ public: KeyType::secp256k1, 1, true); // invalidSig - auto const s_b2 = makeManifest(sk_b, KeyType::ed25519, kp_b2.second, KeyType::ed25519, 2); + auto const s_b2 = + makeManifest(sk_b, KeyType::ed25519, kp_b2.second, KeyType::ed25519, 2); auto const fake = s_b2.serialized + '\0'; @@ -858,7 +908,8 @@ public: BEAST_EXPECT(cache.applyManifest(clone(s_b1)) == ManifestDisposition::invalid); BEAST_EXPECT(cache.applyManifest(clone(s_b2)) == ManifestDisposition::accepted); - auto const s_c0 = makeManifest(kp_b2.second, KeyType::ed25519, randomSecretKey(), KeyType::ed25519, 47); + auto const s_c0 = makeManifest( + kp_b2.second, KeyType::ed25519, randomSecretKey(), KeyType::ed25519, 47); BEAST_EXPECT(cache.applyManifest(clone(s_c0)) == ManifestDisposition::badMasterKey); } diff --git a/src/test/app/MultiSign_test.cpp b/src/test/app/MultiSign_test.cpp index 3d732ee2e0..adfcb12ee0 100644 --- a/src/test/app/MultiSign_test.cpp +++ b/src/test/app/MultiSign_test.cpp @@ -84,7 +84,14 @@ public: Json::Value bigSigners = signers( alice, 1, - {{bogie, 1}, {demon, 1}, {ghost, 1}, {haunt, 1}, {jinni, 1}, {phase, 1}, {shade, 1}, {spook, 1}}); + {{bogie, 1}, + {demon, 1}, + {ghost, 1}, + {haunt, 1}, + {jinni, 1}, + {phase, 1}, + {shade, 1}, + {spook, 1}}); env(bigSigners, ter(tecINSUFFICIENT_RESERVE)); env.close(); env.require(owners(alice, 1)); @@ -129,7 +136,14 @@ public: env(signers( alice, 1, - {{bogie, 1}, {demon, 1}, {ghost, 1}, {haunt, 1}, {jinni, 1}, {phase, 1}, {demon, 1}, {spook, 1}}), + {{bogie, 1}, + {demon, 1}, + {ghost, 1}, + {haunt, 1}, + {jinni, 1}, + {phase, 1}, + {demon, 1}, + {spook, 1}}), ter(temBAD_SIGNER)); // Set a quorum of zero. Should fail. @@ -139,7 +153,14 @@ public: env(signers( alice, 9, - {{bogie, 1}, {demon, 1}, {ghost, 1}, {haunt, 1}, {jinni, 1}, {phase, 1}, {shade, 1}, {spook, 1}}), + {{bogie, 1}, + {demon, 1}, + {ghost, 1}, + {haunt, 1}, + {jinni, 1}, + {phase, 1}, + {shade, 1}, + {spook, 1}}), ter(temBAD_QUORUM)); // clang-format off @@ -243,7 +264,14 @@ public: env(signers( alice, 1, - {{bogie, 1}, {demon, 1}, {ghost, 1}, {haunt, 1}, {jinni, 1}, {phase, 1}, {shade, 1}, {spook, 1}})); + {{bogie, 1}, + {demon, 1}, + {ghost, 1}, + {haunt, 1}, + {jinni, 1}, + {phase, 1}, + {shade, 1}, + {spook, 1}})); env.close(); env.require(owners(alice, 1)); @@ -264,7 +292,9 @@ public: // This should work. aliceSeq = env.seq(alice); - env(noop(alice), msig(bogie, demon, ghost, haunt, jinni, phase, shade, spook), fee(9 * baseFee)); + env(noop(alice), + msig(bogie, demon, ghost, haunt, jinni, phase, shade, spook), + fee(9 * baseFee)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); @@ -300,7 +330,9 @@ public: msig phantoms{bogie, demon}; std::reverse(phantoms.signers.begin(), phantoms.signers.end()); std::uint32_t const aliceSeq = env.seq(alice); - env(noop(alice), phantoms, rpc("invalidTransaction", "fails local checks: Unsorted Signers array.")); + env(noop(alice), + phantoms, + rpc("invalidTransaction", "fails local checks: Unsorted Signers array.")); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq); } @@ -510,7 +542,9 @@ public: auto jrr = env.rpc("json", "sign_for", to_string(jv_one))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT(jrr[jss::error_message] == "When multi-signing 'tx_json.SigningPubKey' must be empty."); + BEAST_EXPECT( + jrr[jss::error_message] == + "When multi-signing 'tx_json.SigningPubKey' must be empty."); } { @@ -535,7 +569,8 @@ public: jrr = env.rpc("json", "submit_multisigned", to_string(jv_submit))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT(jrr[jss::error_message] == "Invalid Fee field. Fees must be greater than zero."); + BEAST_EXPECT( + jrr[jss::error_message] == "Invalid Fee field. Fees must be greater than zero."); } { @@ -703,7 +738,11 @@ public: BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); // Require all signers to sign. - env(signers(alice, 0x3FFFC, {{becky, 0xFFFF}, {cheri, 0xFFFF}, {daria, 0xFFFF}, {jinni, 0xFFFF}}), sig(alie)); + env(signers( + alice, + 0x3FFFC, + {{becky, 0xFFFF}, {cheri, 0xFFFF}, {daria, 0xFFFF}, {jinni, 0xFFFF}}), + sig(alie)); env.close(); env.require(owners(alice, 1)); @@ -743,7 +782,10 @@ public: // One signer short should fail. aliceSeq = env.seq(alice); - env(noop(alice), msig(becky, cheri, haunt, jinni, phase, shade, spook), fee(8 * baseFee), ter(tefBAD_QUORUM)); + env(noop(alice), + msig(becky, cheri, haunt, jinni, phase, shade, spook), + fee(8 * baseFee), + ter(tefBAD_QUORUM)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq); @@ -915,7 +957,10 @@ public: BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); // Multisign a ttTRUST_SET - env(trust("alice", USD(100)), msig(becky, bogie), fee(3 * baseFee), require(lines("alice", 1))); + env(trust("alice", USD(100)), + msig(becky, bogie), + fee(3 * baseFee), + require(lines("alice", 1))); env.close(); env.require(owners(alice, 2)); @@ -940,7 +985,9 @@ public: } // Multisign a ttSIGNER_LIST_SET. - env(signers(alice, 3, {{becky, 1}, {bogie, 1}, {demon, 1}}), msig(becky, bogie), fee(3 * baseFee)); + env(signers(alice, 3, {{becky, 1}, {bogie, 1}, {demon, 1}}), + msig(becky, bogie), + fee(3 * baseFee)); env.close(); env.require(owners(alice, 2)); } @@ -974,7 +1021,9 @@ public: STTx local = *(tx.stx); local.setFieldVL(sfSigningPubKey, Blob()); // Empty SigningPubKey auto const info = submitSTTx(local); - BEAST_EXPECT(info[jss::result][jss::error_exception] == "fails local checks: Empty SigningPubKey."); + BEAST_EXPECT( + info[jss::result][jss::error_exception] == + "fails local checks: Empty SigningPubKey."); } { // Single-sign, but invalidate the signature. @@ -986,7 +1035,9 @@ public: local.setFieldVL(sfTxnSignature, badSig); // Signature should fail. auto const info = submitSTTx(local); - BEAST_EXPECT(info[jss::result][jss::error_exception] == "fails local checks: Invalid signature."); + BEAST_EXPECT( + info[jss::result][jss::error_exception] == + "fails local checks: Invalid signature."); } { // Single-sign, but invalidate the sequence number. @@ -997,7 +1048,9 @@ public: local.setFieldU32(sfSequence, seq + 1); // Signature should fail. auto const info = submitSTTx(local); - BEAST_EXPECT(info[jss::result][jss::error_exception] == "fails local checks: Invalid signature."); + BEAST_EXPECT( + info[jss::result][jss::error_exception] == + "fails local checks: Invalid signature."); } { // Multisign, but leave a nonempty sfSigningPubKey. @@ -1006,7 +1059,8 @@ public: local[sfSigningPubKey] = alice.pk(); // Insert sfSigningPubKey auto const info = submitSTTx(local); BEAST_EXPECT( - info[jss::result][jss::error_exception] == "fails local checks: Cannot both single- and multi-sign."); + info[jss::result][jss::error_exception] == + "fails local checks: Cannot both single- and multi-sign."); } { // Both multi- and single-sign with an empty SigningPubKey. @@ -1016,7 +1070,8 @@ public: local.setFieldVL(sfSigningPubKey, Blob()); // Empty SigningPubKey auto const info = submitSTTx(local); BEAST_EXPECT( - info[jss::result][jss::error_exception] == "fails local checks: Cannot both single- and multi-sign."); + info[jss::result][jss::error_exception] == + "fails local checks: Cannot both single- and multi-sign."); } { // Multisign but invalidate one of the signatures. @@ -1030,8 +1085,8 @@ public: // Signature should fail. auto const info = submitSTTx(local); BEAST_EXPECT( - info[jss::result][jss::error_exception].asString().find("Invalid signature on account r") != - std::string::npos); + info[jss::result][jss::error_exception].asString().find( + "Invalid signature on account r") != std::string::npos); } { // Multisign with an empty signers array should fail. @@ -1039,7 +1094,9 @@ public: STTx local = *(tx.stx); local.peekFieldArray(sfSigners).clear(); // Empty Signers array. auto const info = submitSTTx(local); - BEAST_EXPECT(info[jss::result][jss::error_exception] == "fails local checks: Invalid Signers array size."); + BEAST_EXPECT( + info[jss::result][jss::error_exception] == + "fails local checks: Invalid Signers array size."); } { JTx tx = env.jt( @@ -1082,14 +1139,18 @@ public: bogie)); STTx local = *(tx.stx); auto const info = submitSTTx(local); - BEAST_EXPECT(info[jss::result][jss::error_exception] == "fails local checks: Invalid Signers array size."); + BEAST_EXPECT( + info[jss::result][jss::error_exception] == + "fails local checks: Invalid Signers array size."); } { // The account owner may not multisign for themselves. JTx tx = env.jt(noop(alice), fee(2 * baseFee), msig(alice)); STTx local = *(tx.stx); auto const info = submitSTTx(local); - BEAST_EXPECT(info[jss::result][jss::error_exception] == "fails local checks: Invalid multisigner."); + BEAST_EXPECT( + info[jss::result][jss::error_exception] == + "fails local checks: Invalid multisigner."); } { // No duplicate multisignatures allowed. @@ -1097,7 +1158,8 @@ public: STTx local = *(tx.stx); auto const info = submitSTTx(local); BEAST_EXPECT( - info[jss::result][jss::error_exception] == "fails local checks: Duplicate Signers not allowed."); + info[jss::result][jss::error_exception] == + "fails local checks: Duplicate Signers not allowed."); } { // Multisignatures must be submitted in sorted order. @@ -1108,7 +1170,9 @@ public: std::reverse(signers.begin(), signers.end()); // Signature should fail. auto const info = submitSTTx(local); - BEAST_EXPECT(info[jss::result][jss::error_exception] == "fails local checks: Unsorted Signers array."); + BEAST_EXPECT( + info[jss::result][jss::error_exception] == + "fails local checks: Unsorted Signers array."); } } @@ -1248,7 +1312,8 @@ public: BEAST_EXPECT(hash1 != hash2); // Submit the result of the two signatures. - Json::Value jvResult = env.rpc("json", "submit_multisigned", to_string(jvSubmit[jss::result])); + Json::Value jvResult = + env.rpc("json", "submit_multisigned", to_string(jvSubmit[jss::result])); BEAST_EXPECT(jvResult[jss::result][jss::status].asString() == "success"); BEAST_EXPECT(jvResult[jss::result][jss::engine_result].asString() == "tesSUCCESS"); @@ -1262,7 +1327,8 @@ public: Json::Value jvTx = env.rpc("tx", hash2); BEAST_EXPECT(jvTx[jss::result][jss::status].asString() == "success"); BEAST_EXPECT(jvTx[jss::result][jss::validated].asString() == "true"); - BEAST_EXPECT(jvTx[jss::result][jss::meta][sfTransactionResult.jsonName].asString() == "tesSUCCESS"); + BEAST_EXPECT( + jvTx[jss::result][jss::meta][sfTransactionResult.jsonName].asString() == "tesSUCCESS"); } void diff --git a/src/test/app/NFTokenAuth_test.cpp b/src/test/app/NFTokenAuth_test.cpp index 1e7afc9bb0..6fc92bc6cd 100644 --- a/src/test/app/NFTokenAuth_test.cpp +++ b/src/test/app/NFTokenAuth_test.cpp @@ -1,6 +1,6 @@ #include -#include +#include namespace xrpl { @@ -335,7 +335,9 @@ public: if (features[fixEnforceNFTokenTrustlineV2]) { // test: G1 requires authorization of broker, no trust line exists - env(token::brokerOffers(broker, buyIdx, sellIdx), token::brokerFee(USD(1)), ter(tecNO_LINE)); + env(token::brokerOffers(broker, buyIdx, sellIdx), + token::brokerFee(USD(1)), + ter(tecNO_LINE)); env.close(); // trust line created, but not authorized @@ -343,7 +345,9 @@ public: env.close(); // test: G1 requires authorization of broker - env(token::brokerOffers(broker, buyIdx, sellIdx), token::brokerFee(USD(1)), ter(tecNO_AUTH)); + env(token::brokerOffers(broker, buyIdx, sellIdx), + token::brokerFee(USD(1)), + ter(tecNO_AUTH)); env.close(); // test: can still be brokered without broker fee. @@ -413,7 +417,9 @@ public: if (features[fixEnforceNFTokenTrustlineV2]) { // test: G1 requires authorization of A2 - env(token::brokerOffers(broker, buyIdx, sellIdx), token::brokerFee(USD(1)), ter(tecNO_AUTH)); + env(token::brokerOffers(broker, buyIdx, sellIdx), + token::brokerFee(USD(1)), + ter(tecNO_AUTH)); env.close(); } } @@ -464,7 +470,9 @@ public: if (features[fixEnforceNFTokenTrustlineV2]) { // test: G1 requires authorization of broker, no trust line exists - env(token::brokerOffers(broker, buyIdx, sellIdx), token::brokerFee(USD(1)), ter(tecNO_LINE)); + env(token::brokerOffers(broker, buyIdx, sellIdx), + token::brokerFee(USD(1)), + ter(tecNO_LINE)); env.close(); // trust line created, but not authorized @@ -472,7 +480,9 @@ public: env.close(); // test: G1 requires authorization of A2 - env(token::brokerOffers(broker, buyIdx, sellIdx), token::brokerFee(USD(1)), ter(tecNO_AUTH)); + env(token::brokerOffers(broker, buyIdx, sellIdx), + token::brokerFee(USD(1)), + ter(tecNO_AUTH)); env.close(); // test: cannot be brokered even without broker fee. diff --git a/src/test/app/NFTokenBurn_test.cpp b/src/test/app/NFTokenBurn_test.cpp index 915bb6ec79..c75e22e954 100644 --- a/src/test/app/NFTokenBurn_test.cpp +++ b/src/test/app/NFTokenBurn_test.cpp @@ -1,9 +1,8 @@ #include -#include - #include #include +#include #include @@ -33,7 +32,9 @@ class NFTokenBurn_test : public beast::unit_test::suite { using namespace test::jtx; uint256 const nftokenID = token::getNextID(env, owner, 0, tfTransferable); - env(token::mint(owner, 0), token::uri(std::string(maxTokenURILength, 'u')), txflags(tfTransferable)); + env(token::mint(owner, 0), + token::uri(std::string(maxTokenURILength, 'u')), + txflags(tfTransferable)); env.close(); offerIndexes.reserve(tokenCancelCount); @@ -81,10 +82,12 @@ class NFTokenBurn_test : public beast::unit_test::suite } for (Json::UInt i = 0; i < state.size(); ++i) { - if (state[i].isMember(sfNFTokens.jsonName) && state[i][sfNFTokens.jsonName].isArray()) + if (state[i].isMember(sfNFTokens.jsonName) && + state[i][sfNFTokens.jsonName].isArray()) { std::uint32_t tokenCount = state[i][sfNFTokens.jsonName].size(); - std::cout << tokenCount << " NFtokens in page " << state[i][jss::index].asString() << std::endl; + std::cout << tokenCount << " NFtokens in page " + << state[i][jss::index].asString() << std::endl; if (vol == noisy) { @@ -93,10 +96,14 @@ class NFTokenBurn_test : public beast::unit_test::suite else { if (tokenCount > 0) - std::cout << "first: " << state[i][sfNFTokens.jsonName][0u].toStyledString() << std::endl; + std::cout + << "first: " << state[i][sfNFTokens.jsonName][0u].toStyledString() + << std::endl; if (tokenCount > 1) - std::cout << "last: " << state[i][sfNFTokens.jsonName][tokenCount - 1].toStyledString() - << std::endl; + std::cout + << "last: " + << state[i][sfNFTokens.jsonName][tokenCount - 1].toStyledString() + << std::endl; } } } @@ -154,13 +161,15 @@ class NFTokenBurn_test : public beast::unit_test::suite // effect of random numbers, but we want the test to run the same // way each time. std::mt19937 engine; - std::uniform_int_distribution feeDist(decltype(maxTransferFee){}, maxTransferFee); + std::uniform_int_distribution feeDist( + decltype(maxTransferFee){}, maxTransferFee); alice.nfts.reserve(105); while (alice.nfts.size() < 105) { std::uint16_t const xferFee = feeDist(engine); - alice.nfts.push_back(token::getNextID(env, alice, 0u, tfTransferable | tfBurnable, xferFee)); + alice.nfts.push_back( + token::getNextID(env, alice, 0u, tfTransferable | tfBurnable, xferFee)); env(token::mint(alice), txflags(tfTransferable | tfBurnable), token::xferFee(xferFee)); env.close(); } @@ -169,7 +178,8 @@ class NFTokenBurn_test : public beast::unit_test::suite while (minter.nfts.size() < 105) { std::uint16_t const xferFee = feeDist(engine); - minter.nfts.push_back(token::getNextID(env, alice, 0u, tfTransferable | tfBurnable, xferFee)); + minter.nfts.push_back( + token::getNextID(env, alice, 0u, tfTransferable | tfBurnable, xferFee)); env(token::mint(minter), txflags(tfTransferable | tfBurnable), token::xferFee(xferFee), @@ -214,8 +224,12 @@ class NFTokenBurn_test : public beast::unit_test::suite for (uint256 nft : owner.nfts) { // Create sell offers for owner. - env(token::createOffer(owner, nft, drops(1)), txflags(tfSellNFToken), token::destination(other1)); - env(token::createOffer(owner, nft, drops(1)), txflags(tfSellNFToken), token::destination(other2)); + env(token::createOffer(owner, nft, drops(1)), + txflags(tfSellNFToken), + token::destination(other1)); + env(token::createOffer(owner, nft, drops(1)), + txflags(tfSellNFToken), + token::destination(other2)); env.close(); // Create buy offers for other1 and other2. @@ -357,7 +371,8 @@ class NFTokenBurn_test : public beast::unit_test::suite int pageCount = 0; for (Json::UInt i = 0; i < state.size(); ++i) { - if (state[i].isMember(sfNFTokens.jsonName) && state[i][sfNFTokens.jsonName].isArray()) + if (state[i].isMember(sfNFTokens.jsonName) && + state[i][sfNFTokens.jsonName].isArray()) { BEAST_EXPECT(state[i][sfNFTokens.jsonName].size() == 32); ++pageCount; @@ -418,12 +433,14 @@ class NFTokenBurn_test : public beast::unit_test::suite return; uint256 const middleNFTokenPageIndex = lastNFTokenPage->at(sfPreviousPageMin); - auto middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); + auto middleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; uint256 const firstNFTokenPageIndex = middleNFTokenPage->at(sfPreviousPageMin); - auto firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); + auto firstNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); if (!BEAST_EXPECT(firstNFTokenPage)) return; @@ -463,12 +480,14 @@ class NFTokenBurn_test : public beast::unit_test::suite BEAST_EXPECT(lastNFTokenPage->getFieldArray(sfNFTokens).size() == 32); // The "middle" page should be gone. - middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); + middleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); BEAST_EXPECT(!middleNFTokenPage); // The "first" page should still be present and linked to // the last page. - firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); + firstNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); BEAST_EXPECT(firstNFTokenPage); BEAST_EXPECT(!firstNFTokenPage->isFieldPresent(sfPreviousPageMin)); BEAST_EXPECT(firstNFTokenPage->at(~sfNextPageMin) == lastNFTokenPage->key()); @@ -484,7 +503,8 @@ class NFTokenBurn_test : public beast::unit_test::suite // The "middle" page is still present, but has lost the // NextPageMin field. - middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); + middleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; BEAST_EXPECT(middleNFTokenPage->isFieldPresent(sfPreviousPageMin)); @@ -517,12 +537,14 @@ class NFTokenBurn_test : public beast::unit_test::suite return; uint256 const middleNFTokenPageIndex = lastNFTokenPage->at(sfPreviousPageMin); - auto middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); + auto middleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; uint256 const firstNFTokenPageIndex = middleNFTokenPage->at(sfPreviousPageMin); - auto firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); + auto firstNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); if (!BEAST_EXPECT(firstNFTokenPage)) return; @@ -537,15 +559,18 @@ class NFTokenBurn_test : public beast::unit_test::suite // Verify that middle page is gone and the links in the two // remaining pages are correct. - middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); + middleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); BEAST_EXPECT(!middleNFTokenPage); lastNFTokenPage = env.le(keylet::nftpage_max(alice)); BEAST_EXPECT(!lastNFTokenPage->isFieldPresent(sfNextPageMin)); BEAST_EXPECT(lastNFTokenPage->getFieldH256(sfPreviousPageMin) == firstNFTokenPageIndex); - firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); - BEAST_EXPECT(firstNFTokenPage->getFieldH256(sfNextPageMin) == keylet::nftpage_max(alice).key); + firstNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); + BEAST_EXPECT( + firstNFTokenPage->getFieldH256(sfNextPageMin) == keylet::nftpage_max(alice).key); BEAST_EXPECT(!firstNFTokenPage->isFieldPresent(sfPreviousPageMin)); // Burn the remaining nfts. @@ -573,12 +598,14 @@ class NFTokenBurn_test : public beast::unit_test::suite return; uint256 const middleNFTokenPageIndex = lastNFTokenPage->at(sfPreviousPageMin); - auto middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); + auto middleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; uint256 const firstNFTokenPageIndex = middleNFTokenPage->at(sfPreviousPageMin); - auto firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); + auto firstNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); if (!BEAST_EXPECT(firstNFTokenPage)) return; @@ -592,11 +619,13 @@ class NFTokenBurn_test : public beast::unit_test::suite } // Verify the first page is gone. - firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); + firstNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); BEAST_EXPECT(!firstNFTokenPage); // Check the links in the other two pages. - middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); + middleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; BEAST_EXPECT(!middleNFTokenPage->isFieldPresent(sfPreviousPageMin)); @@ -630,11 +659,13 @@ class NFTokenBurn_test : public beast::unit_test::suite BEAST_EXPECT(lastNFTokenPage->getFieldArray(sfNFTokens).size() == 32); // The "middle" page should be gone. - middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); + middleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); BEAST_EXPECT(!middleNFTokenPage); // The "first" page should still be gone. - firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); + firstNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); BEAST_EXPECT(!firstNFTokenPage); } else @@ -647,7 +678,8 @@ class NFTokenBurn_test : public beast::unit_test::suite // The "middle" page is still present, but has lost the // NextPageMin field. - middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); + middleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; BEAST_EXPECT(!middleNFTokenPage->isFieldPresent(sfPreviousPageMin)); @@ -697,7 +729,8 @@ class NFTokenBurn_test : public beast::unit_test::suite STTx tx{ttACCOUNT_SET, [](STObject&) {}}; test::StreamSink sink{beast::severities::kWarning}; beast::Journal jlog{sink}; - ApplyContext ac{env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, tapNONE, jlog}; + ApplyContext ac{ + env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, tapNONE, jlog}; // Verify that the last page is present and contains one NFT. auto lastNFTokenPage = ac.view().peek(keylet::nftpage_max(alice)); @@ -718,8 +751,8 @@ class NFTokenBurn_test : public beast::unit_test::suite // uncomment to log the invariant failure message // log << " --> " << sink.messages().str() << std::endl; BEAST_EXPECT( - sink.messages().str().find("Last NFT page deleted with non-empty directory") != - std::string::npos); + sink.messages().str().find( + "Last NFT page deleted with non-empty directory") != std::string::npos); } } { @@ -729,12 +762,15 @@ class NFTokenBurn_test : public beast::unit_test::suite STTx tx{ttACCOUNT_SET, [](STObject&) {}}; test::StreamSink sink{beast::severities::kWarning}; beast::Journal jlog{sink}; - ApplyContext ac{env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, tapNONE, jlog}; + ApplyContext ac{ + env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, tapNONE, jlog}; // Verify that the middle page is present. auto lastNFTokenPage = ac.view().peek(keylet::nftpage_max(alice)); auto middleNFTokenPage = ac.view().peek( - keylet::nftpage(keylet::nftpage_min(alice), lastNFTokenPage->getFieldH256(sfPreviousPageMin))); + keylet::nftpage( + keylet::nftpage_min(alice), + lastNFTokenPage->getFieldH256(sfPreviousPageMin))); BEAST_EXPECT(middleNFTokenPage); // Remove the NextMinPage link from the middle page to fire @@ -751,7 +787,8 @@ class NFTokenBurn_test : public beast::unit_test::suite BEAST_EXPECT(sink.messages().str().starts_with("Invariant failed:")); // uncomment to log the invariant failure message // log << " --> " << sink.messages().str() << std::endl; - BEAST_EXPECT(sink.messages().str().find("Lost NextMinPage link") != std::string::npos); + BEAST_EXPECT( + sink.messages().str().find("Lost NextMinPage link") != std::string::npos); } } } @@ -780,7 +817,8 @@ class NFTokenBurn_test : public beast::unit_test::suite // When the token is burned, 498 sell offers and 1 buy offer are // removed. In total, 499 offers are removed std::vector offerIndexes; - auto const nftokenID = createNftAndOffers(env, alice, offerIndexes, maxDeletableTokenOfferEntries - 2); + auto const nftokenID = + createNftAndOffers(env, alice, offerIndexes, maxDeletableTokenOfferEntries - 2); // Verify all sell offers are present in the ledger. for (uint256 const& offerIndex : offerIndexes) @@ -826,7 +864,8 @@ class NFTokenBurn_test : public beast::unit_test::suite // After we burn the token, 500 of the sell offers should be // removed, and one is left over std::vector offerIndexes; - auto const nftokenID = createNftAndOffers(env, alice, offerIndexes, maxDeletableTokenOfferEntries + 1); + auto const nftokenID = + createNftAndOffers(env, alice, offerIndexes, maxDeletableTokenOfferEntries + 1); // Verify all sell offers are present in the ledger. for (uint256 const& offerIndex : offerIndexes) @@ -869,7 +908,8 @@ class NFTokenBurn_test : public beast::unit_test::suite // are removed. // In total, 500 offers are removed std::vector offerIndexes; - auto const nftokenID = createNftAndOffers(env, alice, offerIndexes, maxDeletableTokenOfferEntries - 1); + auto const nftokenID = + createNftAndOffers(env, alice, offerIndexes, maxDeletableTokenOfferEntries - 1); // Verify all sell offers are present in the ledger. for (uint256 const& offerIndex : offerIndexes) @@ -988,7 +1028,8 @@ class NFTokenBurn_test : public beast::unit_test::suite int pageCount = 0; for (Json::UInt i = 0; i < state.size(); ++i) { - if (state[i].isMember(sfNFTokens.jsonName) && state[i][sfNFTokens.jsonName].isArray()) + if (state[i].isMember(sfNFTokens.jsonName) && + state[i][sfNFTokens.jsonName].isArray()) { BEAST_EXPECT(state[i][sfNFTokens.jsonName].size() == 32); ++pageCount; @@ -1013,12 +1054,14 @@ class NFTokenBurn_test : public beast::unit_test::suite return; uint256 const middleNFTokenPageIndex = lastNFTokenPage->at(sfPreviousPageMin); - auto middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); + auto middleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; uint256 const firstNFTokenPageIndex = middleNFTokenPage->at(sfPreviousPageMin); - auto firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); + auto firstNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); if (!BEAST_EXPECT(firstNFTokenPage)) return; @@ -1048,7 +1091,8 @@ class NFTokenBurn_test : public beast::unit_test::suite // The "middle" page is still present, but has lost the // NextPageMin field. - middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); + middleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; BEAST_EXPECT(middleNFTokenPage->isFieldPresent(sfPreviousPageMin)); diff --git a/src/test/app/NFTokenDir_test.cpp b/src/test/app/NFTokenDir_test.cpp index 65bd97ec32..c186a3d9e5 100644 --- a/src/test/app/NFTokenDir_test.cpp +++ b/src/test/app/NFTokenDir_test.cpp @@ -1,10 +1,9 @@ #include -#include - #include #include #include +#include #include @@ -44,10 +43,12 @@ class NFTokenDir_test : public beast::unit_test::suite } for (Json::UInt i = 0; i < state.size(); ++i) { - if (state[i].isMember(sfNFTokens.jsonName) && state[i][sfNFTokens.jsonName].isArray()) + if (state[i].isMember(sfNFTokens.jsonName) && + state[i][sfNFTokens.jsonName].isArray()) { std::uint32_t tokenCount = state[i][sfNFTokens.jsonName].size(); - std::cout << tokenCount << " NFtokens in page " << state[i][jss::index].asString() << std::endl; + std::cout << tokenCount << " NFtokens in page " + << state[i][jss::index].asString() << std::endl; if (vol == noisy) { @@ -56,10 +57,14 @@ class NFTokenDir_test : public beast::unit_test::suite else { if (tokenCount > 0) - std::cout << "first: " << state[i][sfNFTokens.jsonName][0u].toStyledString() << std::endl; + std::cout + << "first: " << state[i][sfNFTokens.jsonName][0u].toStyledString() + << std::endl; if (tokenCount > 1) - std::cout << "last: " << state[i][sfNFTokens.jsonName][tokenCount - 1].toStyledString() - << std::endl; + std::cout + << "last: " + << state[i][sfNFTokens.jsonName][tokenCount - 1].toStyledString() + << std::endl; } } } @@ -139,7 +144,8 @@ class NFTokenDir_test : public beast::unit_test::suite // with identical 96-low-bits are all kept on the same page. // Lambda that exercises the lopsided splits. - auto exerciseLopsided = [this, &features](std::initializer_list seeds) { + auto exerciseLopsided = [this, + &features](std::initializer_list seeds) { Env env{*this, features}; // Eventually all of the NFTokens will be owned by buyer. @@ -152,7 +158,8 @@ class NFTokenDir_test : public beast::unit_test::suite accounts.reserve(seeds.size()); for (std::string_view seed : seeds) { - Account const& account = accounts.emplace_back(Account::base58Seed, std::string(seed)); + Account const& account = + accounts.emplace_back(Account::base58Seed, std::string(seed)); env.fund(XRP(10000), account); // Do not close the ledger inside the loop. If accounts are @@ -170,13 +177,16 @@ class NFTokenDir_test : public beast::unit_test::suite for (Account const& account : accounts) { // Mint the NFT. - uint256 const& nftID = nftIDs.emplace_back(token::getNextID(env, account, 0, tfTransferable)); + uint256 const& nftID = + nftIDs.emplace_back(token::getNextID(env, account, 0, tfTransferable)); env(token::mint(account, 0), txflags(tfTransferable)); env.close(); // Create an offer to give the NFT to buyer for free. offers.emplace_back(keylet::nftoffer(account, env.seq(account)).key); - env(token::createOffer(account, nftID, XRP(0)), token::destination(buyer), txflags((tfSellNFToken))); + env(token::createOffer(account, nftID, XRP(0)), + token::destination(buyer), + txflags((tfSellNFToken))); } env.close(); @@ -352,7 +362,8 @@ class NFTokenDir_test : public beast::unit_test::suite accounts.reserve(seeds.size()); for (std::string_view seed : seeds) { - Account const& account = accounts.emplace_back(Account::base58Seed, std::string(seed)); + Account const& account = + accounts.emplace_back(Account::base58Seed, std::string(seed)); env.fund(XRP(10000), account); // Do not close the ledger inside the loop. If accounts are @@ -370,13 +381,16 @@ class NFTokenDir_test : public beast::unit_test::suite for (Account const& account : accounts) { // Mint the NFT. - uint256 const& nftID = nftIDs.emplace_back(token::getNextID(env, account, 0, tfTransferable)); + uint256 const& nftID = + nftIDs.emplace_back(token::getNextID(env, account, 0, tfTransferable)); env(token::mint(account, 0), txflags(tfTransferable)); env.close(); // Create an offer to give the NFT to buyer for free. offers.emplace_back(keylet::nftoffer(account, env.seq(account)).key); - env(token::createOffer(account, nftID, XRP(0)), token::destination(buyer), txflags((tfSellNFToken))); + env(token::createOffer(account, nftID, XRP(0)), + token::destination(buyer), + txflags((tfSellNFToken))); } env.close(); @@ -596,13 +610,16 @@ class NFTokenDir_test : public beast::unit_test::suite for (Account const& account : accounts) { // Mint the NFT. - uint256 const& nftID = nftIDs.emplace_back(token::getNextID(env, account, 0, tfTransferable)); + uint256 const& nftID = + nftIDs.emplace_back(token::getNextID(env, account, 0, tfTransferable)); env(token::mint(account, 0), txflags(tfTransferable)); env.close(); // Create an offer to give the NFT to buyer for free. offers.emplace_back(keylet::nftoffer(account, env.seq(account)).key); - env(token::createOffer(account, nftID, XRP(0)), token::destination(buyer), txflags((tfSellNFToken))); + env(token::createOffer(account, nftID, XRP(0)), + token::destination(buyer), + txflags((tfSellNFToken))); } env.close(); @@ -764,14 +781,16 @@ class NFTokenDir_test : public beast::unit_test::suite // Mint the NFT. Tweak the taxon so zero is always stored. std::uint32_t taxon = toUInt32(nft::cipheredTaxon(i, nft::toTaxon(0))); - uint256 const& nftID = - nftIDsByPage[i].emplace_back(token::getNextID(env, account, taxon, tfTransferable)); + uint256 const& nftID = nftIDsByPage[i].emplace_back( + token::getNextID(env, account, taxon, tfTransferable)); env(token::mint(account, taxon), txflags(tfTransferable)); env.close(); // Create an offer to give the NFT to buyer for free. offers[i].emplace_back(keylet::nftoffer(account, env.seq(account)).key); - env(token::createOffer(account, nftID, XRP(0)), token::destination(buyer), txflags((tfSellNFToken))); + env(token::createOffer(account, nftID, XRP(0)), + token::destination(buyer), + txflags((tfSellNFToken))); } } env.close(); @@ -906,7 +925,8 @@ class NFTokenDir_test : public beast::unit_test::suite return env.rpc("json", "account_objects", to_string(params)); }(); BEAST_EXPECT( - remainingOffers.isMember(jss::result) && remainingOffers[jss::result].isMember(jss::account_objects) && + remainingOffers.isMember(jss::result) && + remainingOffers[jss::result].isMember(jss::account_objects) && remainingOffers[jss::result][jss::account_objects].size() == 0); } diff --git a/src/test/app/NFToken_test.cpp b/src/test/app/NFToken_test.cpp index 1b9ce82d4a..6d30fc6854 100644 --- a/src/test/app/NFToken_test.cpp +++ b/src/test/app/NFToken_test.cpp @@ -1,10 +1,9 @@ #include -#include - #include #include #include +#include #include @@ -165,22 +164,25 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // A lambda that checks alice's ownerCount, mintedCount, and // burnedCount all in one fell swoop. - auto checkAliceOwnerMintedBurned = - [&env, this, &alice](std::uint32_t owners, std::uint32_t minted, std::uint32_t burned, int line) { - auto oneCheck = [line, this](char const* type, std::uint32_t found, std::uint32_t exp) { - if (found == exp) - pass(); - else - { - std::stringstream ss; - ss << "Wrong " << type << " count. Found: " << found << "; Expected: " << exp; - fail(ss.str(), __FILE__, line); - } - }; - oneCheck("owner", ownerCount(env, alice), owners); - oneCheck("minted", mintedCount(env, alice), minted); - oneCheck("burned", burnedCount(env, alice), burned); + auto checkAliceOwnerMintedBurned = [&env, this, &alice]( + std::uint32_t owners, + std::uint32_t minted, + std::uint32_t burned, + int line) { + auto oneCheck = [line, this](char const* type, std::uint32_t found, std::uint32_t exp) { + if (found == exp) + pass(); + else + { + std::stringstream ss; + ss << "Wrong " << type << " count. Found: " << found << "; Expected: " << exp; + fail(ss.str(), __FILE__, line); + } }; + oneCheck("owner", ownerCount(env, alice), owners); + oneCheck("minted", mintedCount(env, alice), minted); + oneCheck("burned", burnedCount(env, alice), burned); + }; // alice still does not have enough XRP for the reserve of an NFT // page. @@ -264,16 +266,18 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite std::uint32_t minterMinted, std::uint32_t minterBurned, int line) { - auto oneCheck = [this](char const* type, std::uint32_t found, std::uint32_t exp, int line) { - if (found == exp) - pass(); - else - { - std::stringstream ss; - ss << "Wrong " << type << " count. Found: " << found << "; Expected: " << exp; - fail(ss.str(), __FILE__, line); - } - }; + auto oneCheck = + [this](char const* type, std::uint32_t found, std::uint32_t exp, int line) { + if (found == exp) + pass(); + else + { + std::stringstream ss; + ss << "Wrong " << type << " count. Found: " << found + << "; Expected: " << exp; + fail(ss.str(), __FILE__, line); + } + }; oneCheck("alice owner", ownerCount(env, alice), aliceOwners, line); oneCheck("alice minted", mintedCount(env, alice), aliceMinted, line); oneCheck("alice burned", burnedCount(env, alice), aliceBurned, line); @@ -292,7 +296,10 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // minter still does not have enough XRP for the reserve of an NFT // page. Just for grins (and code coverage), minter mints NFTs that // include a URI. - env(token::mint(minter), token::issuer(alice), token::uri("uri"), ter(tecINSUFFICIENT_RESERVE)); + env(token::mint(minter), + token::issuer(alice), + token::uri("uri"), + ter(tecINSUFFICIENT_RESERVE)); env.close(); checkMintersOwnerMintedBurned(0, 33, nftSeq, 0, 0, 0, __LINE__); @@ -320,7 +327,10 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // That NFT page is full. Creating an additional NFT page requires // additional reserve. - env(token::mint(minter), token::issuer(alice), token::uri("uri"), ter(tecINSUFFICIENT_RESERVE)); + env(token::mint(minter), + token::issuer(alice), + token::uri("uri"), + ter(tecINSUFFICIENT_RESERVE)); env.close(); checkMintersOwnerMintedBurned(0, 65, nftSeq, 1, 0, 0, __LINE__); @@ -463,7 +473,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(token::mint(alice, 0u), token::uri(""), ter(temMALFORMED)); // Invalid URI: too long. - env(token::mint(alice, 0u), token::uri(std::string(maxTokenURILength + 1, 'q')), ter(temMALFORMED)); + env(token::mint(alice, 0u), + token::uri(std::string(maxTokenURILength + 1, 'q')), + ter(temMALFORMED)); //---------------------------------------------------------------------- // preclaim @@ -577,17 +589,23 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // buyer tries to create an NFTokenOffer, but doesn't have the reserve. - env(token::createOffer(buyer, nftAlice0ID, XRP(1000)), token::owner(alice), ter(tecINSUFFICIENT_RESERVE)); + env(token::createOffer(buyer, nftAlice0ID, XRP(1000)), + token::owner(alice), + ter(tecINSUFFICIENT_RESERVE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); // Set a negative fee. - env(token::createOffer(buyer, nftAlice0ID, XRP(1000)), fee(STAmount(10ull, true)), ter(temBAD_FEE)); + env(token::createOffer(buyer, nftAlice0ID, XRP(1000)), + fee(STAmount(10ull, true)), + ter(temBAD_FEE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); // Set an invalid flag. - env(token::createOffer(buyer, nftAlice0ID, XRP(1000)), txflags(0x00008000), ter(temINVALID_FLAG)); + env(token::createOffer(buyer, nftAlice0ID, XRP(1000)), + txflags(0x00008000), + ter(temINVALID_FLAG)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); @@ -599,7 +617,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, buyer) == 0); // Set a bad expiration. - env(token::createOffer(buyer, nftAlice0ID, buyer["USD"](1)), token::expiration(0), ter(temBAD_EXPIRATION)); + env(token::createOffer(buyer, nftAlice0ID, buyer["USD"](1)), + token::expiration(0), + ter(temBAD_EXPIRATION)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); @@ -618,7 +638,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, alice) == 1); // An owner may not offer to buy their own token. - env(token::createOffer(alice, nftXrpOnlyID, XRP(1000)), token::owner(alice), ter(temMALFORMED)); + env(token::createOffer(alice, nftXrpOnlyID, XRP(1000)), + token::owner(alice), + ter(temMALFORMED)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 1); @@ -664,7 +686,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, buyer) == 0); // buyer must have the funds to pay for their offer. - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tecNO_LINE)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), + token::owner(alice), + ter(tecNO_LINE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); @@ -674,7 +698,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // Issuer (alice) must have a trust line for the offered funds. - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tecNO_LINE)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), + token::owner(alice), + ter(tecNO_LINE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -684,7 +710,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Issuer (alice) must have a trust line for the offered funds and // the trust line may not be frozen. - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tecFROZEN)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), + token::owner(alice), + ter(tecFROZEN)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -703,7 +731,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(trust(gw, buyer["AUD"](999), tfSetFreeze)); env.close(); - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tecFROZEN)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), + token::owner(alice), + ter(tecFROZEN)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -713,7 +743,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(trust(buyer, gwAUD(1000))); env.close(); - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tecUNFUNDED_OFFER)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), + token::owner(alice), + ter(tecUNFUNDED_OFFER)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); // the trust line. @@ -726,7 +758,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // However buyer doesn't have enough XRP to cover the reserve for // an NFT offer. - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tecINSUFFICIENT_RESERVE)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), + token::owner(alice), + ter(tecINSUFFICIENT_RESERVE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -735,7 +769,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(pay(env.master, buyer, XRP(50) + drops(baseFee * 12 - 1))); env.close(); - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tecINSUFFICIENT_RESERVE)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), + token::owner(alice), + ter(tecINSUFFICIENT_RESERVE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -745,7 +781,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // We don't care whether the offer is fully funded until the offer is // accepted. Success at last! - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tesSUCCESS)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), + token::owner(alice), + ter(tesSUCCESS)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 2); } @@ -782,12 +820,16 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // preflight // Set a negative fee. - env(token::cancelOffer(buyer, {buyerOfferIndex}), fee(STAmount(10ull, true)), ter(temBAD_FEE)); + env(token::cancelOffer(buyer, {buyerOfferIndex}), + fee(STAmount(10ull, true)), + ter(temBAD_FEE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); // Set an invalid flag. - env(token::cancelOffer(buyer, {buyerOfferIndex}), txflags(0x00008000), ter(temINVALID_FLAG)); + env(token::cancelOffer(buyer, {buyerOfferIndex}), + txflags(0x00008000), + ter(temINVALID_FLAG)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -941,12 +983,16 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // preflight // Set a negative fee. - env(token::acceptSellOffer(buyer, noXferOfferIndex), fee(STAmount(10ull, true)), ter(temBAD_FEE)); + env(token::acceptSellOffer(buyer, noXferOfferIndex), + fee(STAmount(10ull, true)), + ter(temBAD_FEE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Set an invalid flag. - env(token::acceptSellOffer(buyer, noXferOfferIndex), txflags(0x00008000), ter(temINVALID_FLAG)); + env(token::acceptSellOffer(buyer, noXferOfferIndex), + txflags(0x00008000), + ter(temINVALID_FLAG)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); @@ -1062,18 +1108,21 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // gw attempts to broker offers that are not for the same token. - env(token::brokerOffers(gw, buyerOfferIndex, xrpOnlyOfferIndex), ter(tecNFTOKEN_BUY_SELL_MISMATCH)); + env(token::brokerOffers(gw, buyerOfferIndex, xrpOnlyOfferIndex), + ter(tecNFTOKEN_BUY_SELL_MISMATCH)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // gw attempts to broker offers that are not for the same currency. - env(token::brokerOffers(gw, buyerOfferIndex, plainOfferIndex), ter(tecNFTOKEN_BUY_SELL_MISMATCH)); + env(token::brokerOffers(gw, buyerOfferIndex, plainOfferIndex), + ter(tecNFTOKEN_BUY_SELL_MISMATCH)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // In a brokered offer, the buyer must offer greater than or // equal to the selling price. - env(token::brokerOffers(gw, buyerOfferIndex, audOfferIndex), ter(tecINSUFFICIENT_PAYMENT)); + env(token::brokerOffers(gw, buyerOfferIndex, audOfferIndex), + ter(tecINSUFFICIENT_PAYMENT)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); @@ -1136,7 +1185,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, alice) == aliceCount); // An account can't accept its own offer. - env(token::acceptBuyOffer(buyer, buyerOfferIndex), ter(tecCANT_ACCEPT_OWN_NFTOKEN_OFFER)); + env(token::acceptBuyOffer(buyer, buyerOfferIndex), + ter(tecCANT_ACCEPT_OWN_NFTOKEN_OFFER)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); @@ -1182,12 +1232,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Don't accept a sell offer without the sell flag set. - env(token::acceptSellOffer(alice, buyerOfferIndex), ter(tecNFTOKEN_OFFER_TYPE_MISMATCH)); + env(token::acceptSellOffer(alice, buyerOfferIndex), + ter(tecNFTOKEN_OFFER_TYPE_MISMATCH)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == aliceCount); // An account can't accept its own offer. - env(token::acceptSellOffer(alice, plainOfferIndex), ter(tecCANT_ACCEPT_OWN_NFTOKEN_OFFER)); + env(token::acceptSellOffer(alice, plainOfferIndex), + ter(tecCANT_ACCEPT_OWN_NFTOKEN_OFFER)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); @@ -1383,17 +1435,22 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Set flagOnlyXRP and offers using IOUs are rejected. { - uint256 const nftOnlyXrpID{token::getNextID(env, alice, 0u, tfOnlyXRP | tfTransferable)}; + uint256 const nftOnlyXrpID{ + token::getNextID(env, alice, 0u, tfOnlyXRP | tfTransferable)}; env(token::mint(alice, 0u), txflags(tfOnlyXRP | tfTransferable)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 2); - env(token::createOffer(alice, nftOnlyXrpID, gwAUD(50)), txflags(tfSellNFToken), ter(temBAD_AMOUNT)); + env(token::createOffer(alice, nftOnlyXrpID, gwAUD(50)), + txflags(tfSellNFToken), + ter(temBAD_AMOUNT)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 2); BEAST_EXPECT(ownerCount(env, buyer) == 1); - env(token::createOffer(buyer, nftOnlyXrpID, gwAUD(50)), token::owner(alice), ter(temBAD_AMOUNT)); + env(token::createOffer(buyer, nftOnlyXrpID, gwAUD(50)), + token::owner(alice), + ter(temBAD_AMOUNT)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -1455,7 +1512,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // fee will not allow creating offers that use IOUs for payment. for (std::uint32_t xferFee : {0, 1}) { - uint256 const nftNoAutoTrustID{token::getNextID(env, alice, 0u, tfTransferable, xferFee)}; + uint256 const nftNoAutoTrustID{ + token::getNextID(env, alice, 0u, tfTransferable, xferFee)}; env(token::mint(alice, 0u), token::xferFee(xferFee), txflags(tfTransferable)); env.close(); @@ -1476,7 +1534,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // cheri offers to buy the nft for CAD. uint256 const cheriOfferIndex = keylet::nftoffer(cheri, env.seq(cheri)).key; - env(token::createOffer(cheri, nftNoAutoTrustID, gwCAD(100)), token::owner(becky), ter(createOfferTER)); + env(token::createOffer(cheri, nftNoAutoTrustID, gwCAD(100)), + token::owner(becky), + ter(createOfferTER)); env.close(); // To keep things tidy, cancel the offers. @@ -1542,13 +1602,15 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // flagCreateTrustLines will work for preestablished trust lines. { std::uint16_t transferFee = 5000; // 5% - uint256 const nftNoAutoTrustID{token::getNextID(env, alice, 0u, tfTransferable, transferFee)}; + uint256 const nftNoAutoTrustID{ + token::getNextID(env, alice, 0u, tfTransferable, transferFee)}; env(token::mint(alice, 0u), token::xferFee(transferFee), txflags(tfTransferable)); env.close(); // alice sells the nft using AUD. uint256 const aliceSellOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftNoAutoTrustID, gwAUD(200)), txflags(tfSellNFToken)); + env(token::createOffer(alice, nftNoAutoTrustID, gwAUD(200)), + txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(cheri, aliceSellOfferIndex)); env.close(); @@ -1559,10 +1621,13 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(alice, gwAUD) == gwAUD(210)); // cheri can't sell the NFT for EUR, but can for CAD. - env(token::createOffer(cheri, nftNoAutoTrustID, gwEUR(50)), txflags(tfSellNFToken), ter(tecNO_LINE)); + env(token::createOffer(cheri, nftNoAutoTrustID, gwEUR(50)), + txflags(tfSellNFToken), + ter(tecNO_LINE)); env.close(); uint256 const cheriSellOfferIndex = keylet::nftoffer(cheri, env.seq(cheri)).key; - env(token::createOffer(cheri, nftNoAutoTrustID, gwCAD(100)), txflags(tfSellNFToken)); + env(token::createOffer(cheri, nftNoAutoTrustID, gwCAD(100)), + txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(becky, cheriSellOfferIndex)); env.close(); @@ -2179,7 +2244,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(pay(becky, gw, env.balance(becky, gwXAU))); env.close(); - STAmount const startXAUBalance(gwXAU.issue(), STAmount::cMinValue, STAmount::cMinOffset + 5); + STAmount const startXAUBalance( + gwXAU.issue(), STAmount::cMinValue, STAmount::cMinOffset + 5); env(pay(gw, alice, startXAUBalance)); env(pay(gw, minter, startXAUBalance)); env(pay(gw, becky, startXAUBalance)); @@ -2285,18 +2351,28 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite else { std::stringstream ss; - ss << "Taxon recovery failed from nftID " << to_string(nftID) << ". Expected: " << taxon - << "; got: " << gotTaxon; + ss << "Taxon recovery failed from nftID " << to_string(nftID) + << ". Expected: " << taxon << "; got: " << gotTaxon; fail(ss.str()); } }; uint256 const nftAliceID = token::getID( - env, alice, taxon, rand_int(), rand_int(), rand_int()); + env, + alice, + taxon, + rand_int(), + rand_int(), + rand_int()); check(taxon, nftAliceID); uint256 const nftBeckyID = token::getID( - env, becky, taxon, rand_int(), rand_int(), rand_int()); + env, + becky, + taxon, + rand_int(), + rand_int(), + rand_int()); check(taxon, nftBeckyID); } } @@ -2388,9 +2464,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite sortedNFTs.reserve(nfts.size()); for (std::size_t i = 0; i < nfts.size(); ++i) sortedNFTs.push_back(nfts[i]); - std::sort(sortedNFTs.begin(), sortedNFTs.end(), [](Json::Value const& lhs, Json::Value const& rhs) { - return lhs[jss::nft_serial] < rhs[jss::nft_serial]; - }); + std::sort( + sortedNFTs.begin(), + sortedNFTs.end(), + [](Json::Value const& lhs, Json::Value const& rhs) { + return lhs[jss::nft_serial] < rhs[jss::nft_serial]; + }); for (std::size_t i = 0; i < entries.size(); ++i) { @@ -2438,16 +2517,24 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // for canceling offers. { uint256 const offerMinterToIssuer = keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), token::destination(issuer), txflags(tfSellNFToken)); + env(token::createOffer(minter, nftokenID, drops(1)), + token::destination(issuer), + txflags(tfSellNFToken)); uint256 const offerMinterToBuyer = keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), token::destination(buyer), txflags(tfSellNFToken)); + env(token::createOffer(minter, nftokenID, drops(1)), + token::destination(buyer), + txflags(tfSellNFToken)); uint256 const offerIssuerToMinter = keylet::nftoffer(issuer, env.seq(issuer)).key; - env(token::createOffer(issuer, nftokenID, drops(1)), token::owner(minter), token::destination(minter)); + env(token::createOffer(issuer, nftokenID, drops(1)), + token::owner(minter), + token::destination(minter)); uint256 const offerIssuerToBuyer = keylet::nftoffer(issuer, env.seq(issuer)).key; - env(token::createOffer(issuer, nftokenID, drops(1)), token::owner(minter), token::destination(buyer)); + env(token::createOffer(issuer, nftokenID, drops(1)), + token::owner(minter), + token::destination(buyer)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 2); @@ -2486,7 +2573,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // accepting that offer. { uint256 const offerMinterSellsToBuyer = keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), token::destination(buyer), txflags(tfSellNFToken)); + env(token::createOffer(minter, nftokenID, drops(1)), + token::destination(buyer), + txflags(tfSellNFToken)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 2); @@ -2512,7 +2601,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // accepting that offer. { uint256 const offerMinterBuysFromBuyer = keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), token::owner(buyer), token::destination(buyer)); + env(token::createOffer(minter, nftokenID, drops(1)), + token::owner(buyer), + token::destination(buyer)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 1); @@ -2537,7 +2628,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // destination must act as a broker. The NFToken owner may not // simply accept the offer. uint256 const offerBuyerBuysFromMinter = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID, drops(1)), token::owner(minter), token::destination(broker)); + env(token::createOffer(buyer, nftokenID, drops(1)), + token::owner(minter), + token::destination(broker)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 1); @@ -2558,7 +2651,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // to another account. { uint256 const offerMinterToBroker = keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), token::destination(broker), txflags(tfSellNFToken)); + env(token::createOffer(minter, nftokenID, drops(1)), + token::destination(broker), + txflags(tfSellNFToken)); uint256 const offerBuyerToMinter = keylet::nftoffer(buyer, env.seq(buyer)).key; env(token::createOffer(buyer, nftokenID, drops(1)), token::owner(minter)); @@ -2571,7 +2666,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { // issuer cannot broker the offers, because they are not the // Destination. - env(token::brokerOffers(issuer, offerBuyerToMinter, offerMinterToBroker), ter(tecNO_PERMISSION)); + env(token::brokerOffers(issuer, offerBuyerToMinter, offerMinterToBroker), + ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 2); @@ -2592,7 +2688,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // does match. { uint256 const offerBuyerToMinter = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID, drops(1)), token::destination(minter), txflags(tfSellNFToken)); + env(token::createOffer(buyer, nftokenID, drops(1)), + token::destination(minter), + txflags(tfSellNFToken)); uint256 const offerMinterToBuyer = keylet::nftoffer(minter, env.seq(minter)).key; env(token::createOffer(minter, nftokenID, drops(1)), token::owner(buyer)); @@ -2608,14 +2706,16 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { // Cannot broker offers when the sell destination is not the // buyer. - env(token::brokerOffers(broker, offerIssuerToBuyer, offerBuyerToMinter), ter(tecNO_PERMISSION)); + env(token::brokerOffers(broker, offerIssuerToBuyer, offerBuyerToMinter), + ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 1); BEAST_EXPECT(ownerCount(env, minter) == 1); BEAST_EXPECT(ownerCount(env, buyer) == 2); - env(token::brokerOffers(broker, offerMinterToBuyer, offerBuyerToMinter), ter(tecNO_PERMISSION)); + env(token::brokerOffers(broker, offerMinterToBuyer, offerBuyerToMinter), + ter(tecNO_PERMISSION)); env.close(); // Buyer is successful with acceptOffer. @@ -2644,15 +2744,20 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // then that destination can broker the offers. { uint256 const offerMinterToBroker = keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), token::destination(broker), txflags(tfSellNFToken)); + env(token::createOffer(minter, nftokenID, drops(1)), + token::destination(broker), + txflags(tfSellNFToken)); uint256 const offerBuyerToBroker = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID, drops(1)), token::owner(minter), token::destination(broker)); + env(token::createOffer(buyer, nftokenID, drops(1)), + token::owner(minter), + token::destination(broker)); { // Cannot broker offers when the sell destination is not the // buyer or the broker. - env(token::brokerOffers(issuer, offerBuyerToBroker, offerMinterToBroker), ter(tecNO_PERMISSION)); + env(token::brokerOffers(issuer, offerBuyerToBroker, offerMinterToBroker), + ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 2); @@ -2715,7 +2820,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { uint256 const offerIndex = keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), token::destination(buyer), txflags(tfSellNFToken)); + env(token::createOffer(minter, nftokenID, drops(1)), + token::destination(buyer), + txflags(tfSellNFToken)); env.close(); env(token::cancelOffer(minter, {offerIndex})); @@ -2726,7 +2833,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { uint256 const offerIndex = keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), token::destination(buyer), txflags(tfSellNFToken)); + env(token::createOffer(minter, nftokenID, drops(1)), + token::destination(buyer), + txflags(tfSellNFToken)); env.close(); env(fset(buyer, asfDisallowIncomingNFTokenOffer)); @@ -2743,7 +2852,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { uint256 const offerIndex = keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), token::destination(buyer), txflags(tfSellNFToken)); + env(token::createOffer(minter, nftokenID, drops(1)), + token::destination(buyer), + txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(buyer, offerIndex)); @@ -2758,13 +2869,17 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // a random offer to buy the token { - env(token::createOffer(alice, nftokenID, drops(1)), token::owner(buyer), ter(tecNO_PERMISSION)); + env(token::createOffer(alice, nftokenID, drops(1)), + token::owner(buyer), + ter(tecNO_PERMISSION)); env.close(); } // minter offer to buy the token { - env(token::createOffer(minter, nftokenID, drops(1)), token::owner(buyer), ter(tecNO_PERMISSION)); + env(token::createOffer(minter, nftokenID, drops(1)), + token::owner(buyer), + ter(tecNO_PERMISSION)); env.close(); } @@ -2774,7 +2889,10 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // enable flag env(fset(buyer, asfDisallowIncomingNFTokenOffer)); // a sell offer from the minter to the buyer should be rejected - env(token::mint(minter), token::amount(drops(1)), token::destination(buyer), ter(tecNO_PERMISSION)); + env(token::mint(minter), + token::amount(drops(1)), + token::destination(buyer), + ter(tecNO_PERMISSION)); env.close(); // disable flag @@ -2831,10 +2949,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite txflags(tfSellNFToken)); uint256 const offerIssuerToMinter = keylet::nftoffer(issuer, env.seq(issuer)).key; - env(token::createOffer(issuer, nftokenID0, drops(1)), token::owner(minter), token::expiration(expiration)); + env(token::createOffer(issuer, nftokenID0, drops(1)), + token::owner(minter), + token::expiration(expiration)); uint256 const offerBuyerToMinter = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, drops(1)), token::owner(minter), token::expiration(expiration)); + env(token::createOffer(buyer, nftokenID0, drops(1)), + token::owner(minter), + token::expiration(expiration)); env.close(); issuerCount = 1; minterCount = 3; @@ -2963,7 +3085,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Transfer nftokenID0 back to minter so we start the next test in // a simple place. uint256 const offerSellBack = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, XRP(0)), txflags(tfSellNFToken), token::destination(minter)); + env(token::createOffer(buyer, nftokenID0, XRP(0)), + txflags(tfSellNFToken), + token::destination(minter)); env.close(); env(token::acceptSellOffer(minter, offerSellBack)); buyerCount--; @@ -2980,11 +3104,15 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite std::uint32_t const expiration = lastClose(env) + 25; uint256 const offer0 = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, drops(1)), token::owner(minter), token::expiration(expiration)); + env(token::createOffer(buyer, nftokenID0, drops(1)), + token::owner(minter), + token::expiration(expiration)); buyerCount++; uint256 const offer1 = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID1, drops(1)), token::owner(minter), token::expiration(expiration)); + env(token::createOffer(buyer, nftokenID1, drops(1)), + token::owner(minter), + token::expiration(expiration)); buyerCount++; env.close(); BEAST_EXPECT(lastClose(env) < expiration); @@ -3045,7 +3173,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Transfer nftokenID0 back to minter so we start the next test in // a simple place. uint256 const offerSellBack = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, XRP(0)), txflags(tfSellNFToken), token::destination(minter)); + env(token::createOffer(buyer, nftokenID0, XRP(0)), + txflags(tfSellNFToken), + token::destination(minter)); env.close(); env(token::acceptSellOffer(minter, offerSellBack)); env.close(); @@ -3137,7 +3267,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Transfer nftokenID0 back to minter so we start the next test in // a simple place. uint256 const offerSellBack = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, XRP(0)), txflags(tfSellNFToken), token::destination(minter)); + env(token::createOffer(buyer, nftokenID0, XRP(0)), + txflags(tfSellNFToken), + token::destination(minter)); env.close(); env(token::acceptSellOffer(minter, offerSellBack)); env.close(); @@ -3160,10 +3292,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(token::createOffer(minter, nftokenID1, drops(1)), txflags(tfSellNFToken)); uint256 const buyOffer0 = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, drops(1)), token::expiration(expiration), token::owner(minter)); + env(token::createOffer(buyer, nftokenID0, drops(1)), + token::expiration(expiration), + token::owner(minter)); uint256 const buyOffer1 = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID1, drops(1)), token::expiration(expiration), token::owner(minter)); + env(token::createOffer(buyer, nftokenID1, drops(1)), + token::expiration(expiration), + token::owner(minter)); env.close(); BEAST_EXPECT(lastClose(env) < expiration); @@ -3212,7 +3348,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Transfer nftokenID0 back to minter so we start the next test in // a simple place. uint256 const offerSellBack = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, XRP(0)), txflags(tfSellNFToken), token::destination(minter)); + env(token::createOffer(buyer, nftokenID0, XRP(0)), + txflags(tfSellNFToken), + token::destination(minter)); env.close(); env(token::acceptSellOffer(minter, offerSellBack)); env.close(); @@ -3239,10 +3377,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite txflags(tfSellNFToken)); uint256 const buyOffer0 = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, drops(1)), token::expiration(expiration), token::owner(minter)); + env(token::createOffer(buyer, nftokenID0, drops(1)), + token::expiration(expiration), + token::owner(minter)); uint256 const buyOffer1 = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID1, drops(1)), token::expiration(expiration), token::owner(minter)); + env(token::createOffer(buyer, nftokenID1, drops(1)), + token::expiration(expiration), + token::owner(minter)); env.close(); BEAST_EXPECT(lastClose(env) < expiration); @@ -3282,7 +3424,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Transfer nftokenID0 back to minter so we start the next test in // a simple place. uint256 const offerSellBack = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, XRP(0)), txflags(tfSellNFToken), token::destination(minter)); + env(token::createOffer(buyer, nftokenID0, XRP(0)), + txflags(tfSellNFToken), + token::destination(minter)); env.close(); env(token::acceptSellOffer(minter, offerSellBack)); env.close(); @@ -3341,7 +3485,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // should be cancellable by the creator and the destination. uint256 const dest1OfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftokenID, XRP(1000)), token::destination(becky), txflags(tfSellNFToken)); + env(token::createOffer(alice, nftokenID, XRP(1000)), + token::destination(becky), + txflags(tfSellNFToken)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 2); @@ -3357,7 +3503,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // alice can cancel her own offer, even if becky is the destination. uint256 const dest2OfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftokenID, XRP(1000)), token::destination(becky), txflags(tfSellNFToken)); + env(token::createOffer(alice, nftokenID, XRP(1000)), + token::destination(becky), + txflags(tfSellNFToken)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 2); @@ -3538,13 +3686,17 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Lambda to check owner count of all accounts is one. auto checkOwnerCountIsOne = - [this, &env](std::initializer_list> accounts, int line) { + [this, &env]( + std::initializer_list> accounts, + int line) { for (Account const& acct : accounts) { - if (std::uint32_t ownerCount = test::jtx::ownerCount(env, acct); ownerCount != 1) + if (std::uint32_t ownerCount = test::jtx::ownerCount(env, acct); + ownerCount != 1) { std::stringstream ss; - ss << "Account " << acct.human() << " expected ownerCount == 1. Got " << ownerCount; + ss << "Account " << acct.human() << " expected ownerCount == 1. Got " + << ownerCount; fail(ss.str(), __FILE__, line); } } @@ -3553,7 +3705,10 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Lambda that mints an NFT and returns the nftID. auto mintNFT = [&env, &issuer, &minter](std::uint16_t xferFee = 0) { uint256 const nftID = token::getNextID(env, issuer, 0, tfTransferable, xferFee); - env(token::mint(minter, 0), token::issuer(issuer), token::xferFee(xferFee), txflags(tfTransferable)); + env(token::mint(minter, 0), + token::issuer(issuer), + token::xferFee(xferFee), + txflags(tfTransferable)); env.close(); return nftID; }; @@ -3633,7 +3788,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite auto const issuerBalance = env.balance(issuer); // Broker charges a 0.5 XRP brokerFee. - env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), token::brokerFee(XRP(0.5))); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), + token::brokerFee(XRP(0.5))); env.close(); // Note that minter's XRP balance goes up even though they @@ -3717,7 +3873,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite auto const issuerBalance = env.balance(issuer); // Broker charges a 0.75 XRP brokerFee. - env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), token::brokerFee(XRP(0.75))); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), + token::brokerFee(XRP(0.75))); env.close(); // Note that, with a 50% transfer fee, issuer gets 1/2 of what's @@ -3737,7 +3894,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // gwXAU(amount). auto setXAUBalance = [this, &gw, &gwXAU, &env]( - std::initializer_list> accounts, int amount, int line) { + std::initializer_list> accounts, + int amount, + int line) { for (Account const& acct : accounts) { auto const xauAmt = gwXAU(amount); @@ -3755,7 +3914,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite if (env.balance(acct, gwXAU) != xauAmt) { std::stringstream ss; - ss << "Unable to set " << acct.human() << " account balance to gwXAU(" << amount << ")"; + ss << "Unable to set " << acct.human() << " account balance to gwXAU(" + << amount << ")"; this->fail(ss.str(), __FILE__, line); } } @@ -3782,7 +3942,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // broker attempts to broker the offers but cannot. - env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), ter(tecINSUFFICIENT_FUNDS)); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), + ter(tecINSUFFICIENT_FUNDS)); env.close(); // Cancel buyer's bad offer so the next test starts in a @@ -3798,7 +3959,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // broker attempts to broker the offers but cannot. - env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), ter(tecINSUFFICIENT_PAYMENT)); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), + ter(tecINSUFFICIENT_PAYMENT)); env.close(); // Cancel buyer's bad offer so the next test starts in a @@ -3856,7 +4018,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // broker attempts to broker the offers but cannot. - env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), ter(tecINSUFFICIENT_FUNDS)); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), + ter(tecINSUFFICIENT_FUNDS)); env.close(); // Cancel buyer's bad offer so the next test starts in a @@ -3872,7 +4035,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // broker attempts to broker the offers but cannot. - env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), ter(tecINSUFFICIENT_PAYMENT)); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), + ter(tecINSUFFICIENT_PAYMENT)); env.close(); // Cancel buyer's bad offer so the next test starts in a @@ -3894,7 +4058,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // broker charges the full difference between the two offers and // succeeds. - env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), token::brokerFee(gwXAU(100))); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), + token::brokerFee(gwXAU(100))); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 1); @@ -3932,7 +4097,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // broker charges half difference between the two offers and // succeeds. 25% of the remaining difference goes to issuer. // The rest goes to minter. - env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), token::brokerFee(gwXAU(50))); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), + token::brokerFee(gwXAU(50))); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 1); @@ -3965,7 +4131,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(token::createOffer(buyer, nftID, gwXAU(1000)), token::owner(minter)); env.close(); - env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), token::brokerFee(gwXAU(50))); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), + token::brokerFee(gwXAU(50))); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 1); BEAST_EXPECT(ownerCount(env, minter) == 1); @@ -4101,7 +4268,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // NFTokenCreateOffer BEAST_EXPECT(ownerCount(env, buyer) == 10); uint256 const offerIndex0 = keylet::nftoffer(buyer, buyerTicketSeq).key; - env(token::createOffer(buyer, nftId, XRP(1)), token::owner(issuer), ticket::use(buyerTicketSeq++)); + env(token::createOffer(buyer, nftId, XRP(1)), + token::owner(issuer), + ticket::use(buyerTicketSeq++)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 10); BEAST_EXPECT(ticketCount(env, buyer) == 9); @@ -4114,7 +4283,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // NFTokenCreateOffer. buyer tries again. uint256 const offerIndex1 = keylet::nftoffer(buyer, buyerTicketSeq).key; - env(token::createOffer(buyer, nftId, XRP(2)), token::owner(issuer), ticket::use(buyerTicketSeq++)); + env(token::createOffer(buyer, nftId, XRP(2)), + token::owner(issuer), + ticket::use(buyerTicketSeq++)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 8); BEAST_EXPECT(ticketCount(env, buyer) == 7); @@ -4257,7 +4428,11 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // A lambda that validates nft_XXX_offers query responses. - auto checkOffers = [this, &env, &nftID](char const* request, int expectCount, int expectMarkerCount, int line) { + auto checkOffers = [this, &env, &nftID]( + char const* request, + int expectCount, + int expectMarkerCount, + int line) { int markerCount = 0; Json::Value allOffers(Json::arrayValue); std::string marker; @@ -4277,9 +4452,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // If there are no offers for the NFT we get an error if (expectCount == 0) { - if (expect(nftOffers.isMember(jss::result), "expected \"result\"", __FILE__, line)) + if (expect( + nftOffers.isMember(jss::result), "expected \"result\"", __FILE__, line)) { - if (expect(nftOffers[jss::result].isMember(jss::error), "expected \"error\"", __FILE__, line)) + if (expect( + nftOffers[jss::result].isMember(jss::error), + "expected \"error\"", + __FILE__, + line)) { expect( nftOffers[jss::result][jss::error].asString() == "objectNotFound", @@ -4312,7 +4492,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite } while (!marker.empty()); // Verify the contents of allOffers makes sense. - expect(allOffers.size() == expectCount, "Unexpected returned offer count", __FILE__, line); + expect( + allOffers.size() == expectCount, "Unexpected returned offer count", __FILE__, line); expect(markerCount == expectMarkerCount, "Unexpected marker count", __FILE__, line); std::optional globalFlags; std::set offerIndexes; @@ -4323,7 +4504,11 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite if (!globalFlags) globalFlags = offer[jss::flags].asInt(); - expect(*globalFlags == offer[jss::flags].asInt(), "Inconsistent flags returned", __FILE__, line); + expect( + *globalFlags == offer[jss::flags].asInt(), + "Inconsistent flags returned", + __FILE__, + line); // The test conditions should produce unique indexes and // amounts for all offers. @@ -4331,7 +4516,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite amounts.insert(offer[jss::amount].asString()); } - expect(offerIndexes.size() == expectCount, "Duplicate indexes returned?", __FILE__, line); + expect( + offerIndexes.size() == expectCount, "Duplicate indexes returned?", __FILE__, line); expect(amounts.size() == expectCount, "Duplicate amounts returned?", __FILE__, line); }; @@ -4452,19 +4638,27 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Make offers with negative amounts for the NFTs uint256 const sellNegXrpOfferIndex = keylet::nftoffer(issuer, env.seq(issuer)).key; - env(token::createOffer(issuer, nftID0, XRP(-2)), txflags(tfSellNFToken), ter(offerCreateTER)); + env(token::createOffer(issuer, nftID0, XRP(-2)), + txflags(tfSellNFToken), + ter(offerCreateTER)); env.close(); uint256 const sellNegIouOfferIndex = keylet::nftoffer(issuer, env.seq(issuer)).key; - env(token::createOffer(issuer, nftID1, gwXAU(-2)), txflags(tfSellNFToken), ter(offerCreateTER)); + env(token::createOffer(issuer, nftID1, gwXAU(-2)), + txflags(tfSellNFToken), + ter(offerCreateTER)); env.close(); uint256 const buyNegXrpOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID0, XRP(-1)), token::owner(issuer), ter(offerCreateTER)); + env(token::createOffer(buyer, nftID0, XRP(-1)), + token::owner(issuer), + ter(offerCreateTER)); env.close(); uint256 const buyNegIouOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID1, gwXAU(-1)), token::owner(issuer), ter(offerCreateTER)); + env(token::createOffer(buyer, nftID1, gwXAU(-1)), + token::owner(issuer), + ter(offerCreateTER)); env.close(); { @@ -4487,9 +4681,11 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite TER const offerAcceptTER = tecOBJECT_NOT_FOUND; // Brokered offers. - env(token::brokerOffers(gw, buyNegXrpOfferIndex, sellNegXrpOfferIndex), ter(offerAcceptTER)); + env(token::brokerOffers(gw, buyNegXrpOfferIndex, sellNegXrpOfferIndex), + ter(offerAcceptTER)); env.close(); - env(token::brokerOffers(gw, buyNegIouOfferIndex, sellNegIouOfferIndex), ter(offerAcceptTER)); + env(token::brokerOffers(gw, buyNegIouOfferIndex, sellNegIouOfferIndex), + ter(offerAcceptTER)); env.close(); } } @@ -4547,57 +4743,66 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(rate(gw, 1.02)); env.close(); - auto expectInitialState = [this, &env, &buyer, &minter, &secondarySeller, &broker, &gw, &gwXAU, &gwXPB]() { - // Buyer should have XAU 1000, XPB 0 - // Minter should have XAU 0, XPB 0 - // Secondary seller should have XAU 0, XPB 0 - // Broker should have XAU 5000, XPB 0 - BEAST_EXPECT(env.balance(buyer, gwXAU) == gwXAU(1000)); - BEAST_EXPECT(env.balance(buyer, gwXPB) == gwXPB(0)); - BEAST_EXPECT(env.balance(minter, gwXAU) == gwXAU(0)); - BEAST_EXPECT(env.balance(minter, gwXPB) == gwXPB(0)); - BEAST_EXPECT(env.balance(secondarySeller, gwXAU) == gwXAU(0)); - BEAST_EXPECT(env.balance(secondarySeller, gwXPB) == gwXPB(0)); - BEAST_EXPECT(env.balance(broker, gwXAU) == gwXAU(5000)); - BEAST_EXPECT(env.balance(broker, gwXPB) == gwXPB(0)); - BEAST_EXPECT(env.balance(gw, buyer["XAU"]) == gwXAU(-1000)); - BEAST_EXPECT(env.balance(gw, buyer["XPB"]) == gwXPB(0)); - BEAST_EXPECT(env.balance(gw, minter["XAU"]) == gwXAU(0)); - BEAST_EXPECT(env.balance(gw, minter["XPB"]) == gwXPB(0)); - BEAST_EXPECT(env.balance(gw, secondarySeller["XAU"]) == gwXAU(0)); - BEAST_EXPECT(env.balance(gw, secondarySeller["XPB"]) == gwXPB(0)); - BEAST_EXPECT(env.balance(gw, broker["XAU"]) == gwXAU(-5000)); - BEAST_EXPECT(env.balance(gw, broker["XPB"]) == gwXPB(0)); - }; - - auto reinitializeTrustLineBalances = - [&expectInitialState, &env, &buyer, &minter, &secondarySeller, &broker, &gw, &gwXAU, &gwXPB]() { - if (auto const difference = gwXAU(1000) - env.balance(buyer, gwXAU); difference > gwXAU(0)) - env(pay(gw, buyer, difference)); - if (env.balance(buyer, gwXPB) > gwXPB(0)) - env(pay(buyer, gw, env.balance(buyer, gwXPB))); - if (env.balance(minter, gwXAU) > gwXAU(0)) - env(pay(minter, gw, env.balance(minter, gwXAU))); - if (env.balance(minter, gwXPB) > gwXPB(0)) - env(pay(minter, gw, env.balance(minter, gwXPB))); - if (env.balance(secondarySeller, gwXAU) > gwXAU(0)) - env(pay(secondarySeller, gw, env.balance(secondarySeller, gwXAU))); - if (env.balance(secondarySeller, gwXPB) > gwXPB(0)) - env(pay(secondarySeller, gw, env.balance(secondarySeller, gwXPB))); - auto brokerDiff = gwXAU(5000) - env.balance(broker, gwXAU); - if (brokerDiff > gwXAU(0)) - env(pay(gw, broker, brokerDiff)); - else if (brokerDiff < gwXAU(0)) - { - brokerDiff.negate(); - env(pay(broker, gw, brokerDiff)); - } - if (env.balance(broker, gwXPB) > gwXPB(0)) - env(pay(broker, gw, env.balance(broker, gwXPB))); - env.close(); - expectInitialState(); + auto expectInitialState = + [this, &env, &buyer, &minter, &secondarySeller, &broker, &gw, &gwXAU, &gwXPB]() { + // Buyer should have XAU 1000, XPB 0 + // Minter should have XAU 0, XPB 0 + // Secondary seller should have XAU 0, XPB 0 + // Broker should have XAU 5000, XPB 0 + BEAST_EXPECT(env.balance(buyer, gwXAU) == gwXAU(1000)); + BEAST_EXPECT(env.balance(buyer, gwXPB) == gwXPB(0)); + BEAST_EXPECT(env.balance(minter, gwXAU) == gwXAU(0)); + BEAST_EXPECT(env.balance(minter, gwXPB) == gwXPB(0)); + BEAST_EXPECT(env.balance(secondarySeller, gwXAU) == gwXAU(0)); + BEAST_EXPECT(env.balance(secondarySeller, gwXPB) == gwXPB(0)); + BEAST_EXPECT(env.balance(broker, gwXAU) == gwXAU(5000)); + BEAST_EXPECT(env.balance(broker, gwXPB) == gwXPB(0)); + BEAST_EXPECT(env.balance(gw, buyer["XAU"]) == gwXAU(-1000)); + BEAST_EXPECT(env.balance(gw, buyer["XPB"]) == gwXPB(0)); + BEAST_EXPECT(env.balance(gw, minter["XAU"]) == gwXAU(0)); + BEAST_EXPECT(env.balance(gw, minter["XPB"]) == gwXPB(0)); + BEAST_EXPECT(env.balance(gw, secondarySeller["XAU"]) == gwXAU(0)); + BEAST_EXPECT(env.balance(gw, secondarySeller["XPB"]) == gwXPB(0)); + BEAST_EXPECT(env.balance(gw, broker["XAU"]) == gwXAU(-5000)); + BEAST_EXPECT(env.balance(gw, broker["XPB"]) == gwXPB(0)); }; + auto reinitializeTrustLineBalances = [&expectInitialState, + &env, + &buyer, + &minter, + &secondarySeller, + &broker, + &gw, + &gwXAU, + &gwXPB]() { + if (auto const difference = gwXAU(1000) - env.balance(buyer, gwXAU); + difference > gwXAU(0)) + env(pay(gw, buyer, difference)); + if (env.balance(buyer, gwXPB) > gwXPB(0)) + env(pay(buyer, gw, env.balance(buyer, gwXPB))); + if (env.balance(minter, gwXAU) > gwXAU(0)) + env(pay(minter, gw, env.balance(minter, gwXAU))); + if (env.balance(minter, gwXPB) > gwXPB(0)) + env(pay(minter, gw, env.balance(minter, gwXPB))); + if (env.balance(secondarySeller, gwXAU) > gwXAU(0)) + env(pay(secondarySeller, gw, env.balance(secondarySeller, gwXAU))); + if (env.balance(secondarySeller, gwXPB) > gwXPB(0)) + env(pay(secondarySeller, gw, env.balance(secondarySeller, gwXPB))); + auto brokerDiff = gwXAU(5000) - env.balance(broker, gwXAU); + if (brokerDiff > gwXAU(0)) + env(pay(gw, broker, brokerDiff)); + else if (brokerDiff < gwXAU(0)) + { + brokerDiff.negate(); + env(pay(broker, gw, brokerDiff)); + } + if (env.balance(broker, gwXPB) > gwXPB(0)) + env(pay(broker, gw, env.balance(broker, gwXPB))); + env.close(); + expectInitialState(); + }; + auto mintNFT = [&env](Account const& minter, int transferFee = 0) { uint256 const nftID = token::getNextID(env, minter, 0, tfTransferable, transferFee); env(token::mint(minter), token::xferFee(transferFee), txflags(tfTransferable)); @@ -4847,7 +5052,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite reinitializeTrustLineBalances(); auto const nftID = mintNFT(gw); auto const offerID = createSellOffer(gw, nftID, gwXAU(2000)); - env(token::acceptSellOffer(buyer, offerID), ter(static_cast(tecINSUFFICIENT_FUNDS))); + env(token::acceptSellOffer(buyer, offerID), + ter(static_cast(tecINSUFFICIENT_FUNDS))); env.close(); expectInitialState(); } @@ -4858,7 +5064,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite reinitializeTrustLineBalances(); auto const nftID = mintNFT(gw); auto const offerID = createBuyOffer(buyer, gw, nftID, gwXAU(2000)); - env(token::acceptBuyOffer(gw, offerID), ter(static_cast(tecINSUFFICIENT_FUNDS))); + env(token::acceptBuyOffer(gw, offerID), + ter(static_cast(tecINSUFFICIENT_FUNDS))); env.close(); expectInitialState(); } @@ -4868,7 +5075,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite reinitializeTrustLineBalances(); auto const nftID = mintNFT(minter); auto const offerID = createSellOffer(minter, nftID, gwXPB(10)); - env(token::acceptSellOffer(buyer, offerID), ter(static_cast(tecINSUFFICIENT_FUNDS))); + env(token::acceptSellOffer(buyer, offerID), + ter(static_cast(tecINSUFFICIENT_FUNDS))); env.close(); expectInitialState(); } @@ -4877,9 +5085,10 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // have no trust line for and buyer has none of (buyside). reinitializeTrustLineBalances(); auto const nftID = mintNFT(minter); - auto const offerID = - createBuyOffer(buyer, minter, nftID, gwXPB(10), {static_cast(tecUNFUNDED_OFFER)}); - env(token::acceptBuyOffer(minter, offerID), ter(static_cast(tecOBJECT_NOT_FOUND))); + auto const offerID = createBuyOffer( + buyer, minter, nftID, gwXPB(10), {static_cast(tecUNFUNDED_OFFER)}); + env(token::acceptBuyOffer(minter, offerID), + ter(static_cast(tecOBJECT_NOT_FOUND))); env.close(); expectInitialState(); } @@ -5137,7 +5346,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(token::createOffer(bob, nftId, XRP(5)), token::owner(alice)); uint256 const aliceSellOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId, XRP(0)), token::destination(bob), txflags(tfSellNFToken)); + env(token::createOffer(alice, nftId, XRP(0)), + token::destination(bob), + txflags(tfSellNFToken)); env.close(); // bob accepts alice's offer but forgets to remove the old buy offer. @@ -5197,8 +5408,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // within . auto incLgrSeqForFixNftRemint = [&](Env& env, Account const& acct) { int delta = 0; - auto const deletableLgrSeq = - (*env.le(acct))[~sfFirstNFTokenSequence].value_or(0) + (*env.le(acct))[sfMintedNFTokens] + 255; + auto const deletableLgrSeq = (*env.le(acct))[~sfFirstNFTokenSequence].value_or(0) + + (*env.le(acct))[sfMintedNFTokens] + 255; if (deletableLgrSeq > openLedgerSeq(env)) delta = deletableLgrSeq - openLedgerSeq(env); @@ -5618,32 +5829,47 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { // The destination may not be the account submitting the // transaction. - env(token::mint(alice), token::amount(XRP(1000)), token::destination(alice), ter(temMALFORMED)); + env(token::mint(alice), + token::amount(XRP(1000)), + token::destination(alice), + ter(temMALFORMED)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); // The destination must be an account already established in the // ledger. - env(token::mint(alice), token::amount(XRP(1000)), token::destination(Account("demon")), ter(tecNO_DST)); + env(token::mint(alice), + token::amount(XRP(1000)), + token::destination(Account("demon")), + ter(tecNO_DST)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); } { // Set a bad expiration. - env(token::mint(alice), token::amount(XRP(1000)), token::expiration(0), ter(temBAD_EXPIRATION)); + env(token::mint(alice), + token::amount(XRP(1000)), + token::expiration(0), + ter(temBAD_EXPIRATION)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); // The new NFTokenOffer may not have passed its expiration time. - env(token::mint(alice), token::amount(XRP(1000)), token::expiration(lastClose(env)), ter(tecEXPIRED)); + env(token::mint(alice), + token::amount(XRP(1000)), + token::expiration(lastClose(env)), + ter(tecEXPIRED)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); } { // Set an invalid amount. - env(token::mint(alice), token::amount(buyer["USD"](1)), txflags(tfOnlyXRP), ter(temBAD_AMOUNT)); + env(token::mint(alice), + token::amount(buyer["USD"](1)), + txflags(tfOnlyXRP), + ter(temBAD_AMOUNT)); env(token::mint(alice), token::amount(buyer["USD"](0)), ter(temBAD_AMOUNT)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); @@ -5660,7 +5886,10 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // If the IOU issuer and the NFToken issuer are the same, // then that issuer does not need a trust line to accept their // fee. - env(token::mint(gw), token::amount(gwAUD(1000)), txflags(tfTransferable), token::xferFee(10)); + env(token::mint(gw), + token::amount(gwAUD(1000)), + txflags(tfTransferable), + token::xferFee(10)); env.close(); // Give alice the needed trust line, but freeze it. @@ -5945,7 +6174,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Alice creates sell offer and set broker as destination uint256 const offerAliceToBroker = keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId, drops(1)), token::destination(broker), txflags(tfSellNFToken)); + env(token::createOffer(alice, nftId, drops(1)), + token::destination(broker), + txflags(tfSellNFToken)); env.close(); verifyNFTokenOfferID(offerAliceToBroker); @@ -6267,7 +6498,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Alice creates sell offer and set broker as destination uint256 const offerAliceToBroker = keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId, XRP(1)), token::destination(broker), txflags(tfSellNFToken)); + env(token::createOffer(alice, nftId, XRP(1)), + token::destination(broker), + txflags(tfSellNFToken)); env.close(); // Bob creates buy offer @@ -6279,7 +6512,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Returns insufficient funds, because bob burnt tx fee when he // created his buy offer, which makes his spendable balance to be // less than the required amount. - env(token::brokerOffers(broker, offerBobToBroker, offerAliceToBroker), ter(tecINSUFFICIENT_FUNDS)); + env(token::brokerOffers(broker, offerBobToBroker, offerAliceToBroker), + ter(tecINSUFFICIENT_FUNDS)); env.close(); // send Bob `base fee` drops @@ -6334,7 +6568,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Otherwise we can't create NFTokens with tfTrustLine enabled. FeatureBitset const localFeatures = features - fixRemoveNFTokenAutoTrustLine; for (FeatureBitset feats : - {localFeatures - fixEnforceNFTokenTrustline, localFeatures | fixEnforceNFTokenTrustline}) + {localFeatures - fixEnforceNFTokenTrustline, + localFeatures | fixEnforceNFTokenTrustline}) { Env env{*this, feats}; env.fund(XRP(1000), issuer, becky, cheri, gw); @@ -6349,11 +6584,15 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // issuer creates two NFTs: one with and one without AutoTrustLine. std::uint16_t xferFee = 5000; // 5% - uint256 const nftAutoTrustID{token::getNextID(env, issuer, 0u, tfTransferable | tfTrustLine, xferFee)}; - env(token::mint(issuer, 0u), token::xferFee(xferFee), txflags(tfTransferable | tfTrustLine)); + uint256 const nftAutoTrustID{ + token::getNextID(env, issuer, 0u, tfTransferable | tfTrustLine, xferFee)}; + env(token::mint(issuer, 0u), + token::xferFee(xferFee), + txflags(tfTransferable | tfTrustLine)); env.close(); - uint256 const nftNoAutoTrustID{token::getNextID(env, issuer, 0u, tfTransferable, xferFee)}; + uint256 const nftNoAutoTrustID{ + token::getNextID(env, issuer, 0u, tfTransferable, xferFee)}; env(token::mint(issuer, 0u), token::xferFee(xferFee), txflags(tfTransferable)); env.close(); @@ -6378,7 +6617,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Creating an offer for the NFToken without tfTrustLine fails // because issuer does not have a trust line for AUD. - env(token::createOffer(becky, nftNoAutoTrustID, gwAUD(100)), txflags(tfSellNFToken), ter(tecNO_LINE)); + env(token::createOffer(becky, nftNoAutoTrustID, gwAUD(100)), + txflags(tfSellNFToken), + ter(tecNO_LINE)); env.close(); // issuer creates a trust line. Now the offer create for the @@ -6499,8 +6740,11 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // issuer creates two NFTs: one with and one without AutoTrustLine. std::uint16_t xferFee = 5000; // 5% - uint256 const nftAutoTrustID{token::getNextID(env, issuer, 0u, tfTransferable | tfTrustLine, xferFee)}; - env(token::mint(issuer, 0u), token::xferFee(xferFee), txflags(tfTransferable | tfTrustLine)); + uint256 const nftAutoTrustID{ + token::getNextID(env, issuer, 0u, tfTransferable | tfTrustLine, xferFee)}; + env(token::mint(issuer, 0u), + token::xferFee(xferFee), + txflags(tfTransferable | tfTrustLine)); env.close(); uint256 const nftNoAutoTrustID{token::getNextID(env, issuer, 0u, tfTransferable, xferFee)}; @@ -6528,7 +6772,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Without featureNFTokenMintOffer becky simply can't // create an offer for a non-tfTrustLine NFToken that would // pay the transfer fee in issuer's own IOU. - env(token::createOffer(becky, nftNoAutoTrustID, isISU(100)), txflags(tfSellNFToken), ter(tecNO_LINE)); + env(token::createOffer(becky, nftNoAutoTrustID, isISU(100)), + txflags(tfSellNFToken), + ter(tecNO_LINE)); env.close(); // And issuer can't create a trust line to themselves. @@ -6656,7 +6902,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // Invalid URI length > 256 - env(token::modify(issuer, nftId), token::uri(std::string(maxTokenURILength + 1, 'q')), ter(temMALFORMED)); + env(token::modify(issuer, nftId), + token::uri(std::string(maxTokenURILength + 1, 'q')), + ter(temMALFORMED)); env.close(); } { @@ -6888,7 +7136,8 @@ class NFTokenDisallowIncoming_test : public NFTokenBaseUtil_test void run() override { - testWithFeats(allFeatures - fixNFTokenReserve - featureNFTokenMintOffer - featureDynamicNFT); + testWithFeats( + allFeatures - fixNFTokenReserve - featureNFTokenMintOffer - featureDynamicNFT); } }; diff --git a/src/test/app/NetworkID_test.cpp b/src/test/app/NetworkID_test.cpp index 5fddc8f641..a37f8342e1 100644 --- a/src/test/app/NetworkID_test.cpp +++ b/src/test/app/NetworkID_test.cpp @@ -3,6 +3,7 @@ #include #include +#include #include namespace xrpl { @@ -58,7 +59,7 @@ public: // test mainnet { test::jtx::Env env{*this, makeNetworkConfig(0)}; - BEAST_EXPECT(env.app().config().NETWORK_ID == 0); + BEAST_EXPECT(env.app().getNetworkIDService().getNetworkID() == 0); // try to submit a txn without network id, this should work Json::Value jv; @@ -81,7 +82,7 @@ public: // NetworkID { test::jtx::Env env{*this, makeNetworkConfig(1024)}; - BEAST_EXPECT(env.app().config().NETWORK_ID == 1024); + BEAST_EXPECT(env.app().getNetworkIDService().getNetworkID() == 1024); // try to submit a txn without network id, this should work Json::Value jv; @@ -101,7 +102,7 @@ public: // absent networkid { test::jtx::Env env{*this, makeNetworkConfig(1025)}; - BEAST_EXPECT(env.app().config().NETWORK_ID == 1025); + BEAST_EXPECT(env.app().getNetworkIDService().getNetworkID() == 1025); { env.fund(XRP(200), alice); // try to submit a txn without network id, this should not work @@ -115,7 +116,8 @@ public: Serializer s; jt.stx->add(s); BEAST_EXPECT( - env.rpc("submit", strHex(s.slice()))[jss::result][jss::engine_result] == "telREQUIRES_NETWORK_ID"); + env.rpc("submit", strHex(s.slice()))[jss::result][jss::engine_result] == + "telREQUIRES_NETWORK_ID"); env.close(); } diff --git a/src/test/app/NetworkOPs_test.cpp b/src/test/app/NetworkOPs_test.cpp index ffca1ed79d..a176279444 100644 --- a/src/test/app/NetworkOPs_test.cpp +++ b/src/test/app/NetworkOPs_test.cpp @@ -2,7 +2,7 @@ #include #include -#include +#include namespace xrpl { namespace test { @@ -28,7 +28,8 @@ public: { using namespace jtx; auto const alice = Account{"alice"}; - Env env{*this, envconfig(), std::make_unique(&logs), beast::severities::kAll}; + Env env{ + *this, envconfig(), std::make_unique(&logs), beast::severities::kAll}; env.memoize(env.master); env.memoize(alice); diff --git a/src/test/app/OfferStream_test.cpp b/src/test/app/OfferStream_test.cpp index 218653a5d4..becb190513 100644 --- a/src/test/app/OfferStream_test.cpp +++ b/src/test/app/OfferStream_test.cpp @@ -1,6 +1,5 @@ -#include - #include +#include namespace xrpl { diff --git a/src/test/app/Offer_test.cpp b/src/test/app/Offer_test.cpp index 4847b7edb0..d22d907322 100644 --- a/src/test/app/Offer_test.cpp +++ b/src/test/app/Offer_test.cpp @@ -95,10 +95,14 @@ public: PathSet paths(Path(XRP, USD), Path(USD)); - env(pay(alice, bob, USD(100)), json(paths.json()), sendmax(BTC(1000)), txflags(tfPartialPayment)); + env(pay(alice, bob, USD(100)), + json(paths.json()), + sendmax(BTC(1000)), + txflags(tfPartialPayment)); env.require(balance(bob, USD(100))); - BEAST_EXPECT(!isOffer(env, carol, BTC(1), USD(100)) && isOffer(env, carol, BTC(49), XRP(49))); + BEAST_EXPECT( + !isOffer(env, carol, BTC(1), USD(100)) && isOffer(env, carol, BTC(49), XRP(49))); } void @@ -131,18 +135,24 @@ public: // cancel the offer above and replace it with a new offer auto const offer2Seq = env.seq(alice); - env(offer(alice, XRP(300), USD(100)), json(jss::OfferSequence, offer1Seq), require(offers(alice, 1))); + env(offer(alice, XRP(300), USD(100)), + json(jss::OfferSequence, offer1Seq), + require(offers(alice, 1))); env.close(); - BEAST_EXPECT(isOffer(env, alice, XRP(300), USD(100)) && !isOffer(env, alice, XRP(500), USD(100))); + BEAST_EXPECT( + isOffer(env, alice, XRP(300), USD(100)) && !isOffer(env, alice, XRP(500), USD(100))); // Test canceling non-existent offer. // auto const offer3Seq = env.seq (alice); - env(offer(alice, XRP(400), USD(200)), json(jss::OfferSequence, offer1Seq), require(offers(alice, 2))); + env(offer(alice, XRP(400), USD(200)), + json(jss::OfferSequence, offer1Seq), + require(offers(alice, 2))); env.close(); - BEAST_EXPECT(isOffer(env, alice, XRP(300), USD(100)) && isOffer(env, alice, XRP(400), USD(200))); + BEAST_EXPECT( + isOffer(env, alice, XRP(300), USD(100)) && isOffer(env, alice, XRP(400), USD(200))); // Test cancellation now with OfferCancel tx auto const offer4Seq = env.seq(alice); @@ -266,7 +276,10 @@ public: // stAmountCalcSwitchover2 was inactive.) env(offer(erin, drops(2), USD(1))); - env(pay(alice, bob, USD(1)), path(~USD), sendmax(XRP(102)), txflags(tfNoRippleDirect | tfPartialPayment)); + env(pay(alice, bob, USD(1)), + path(~USD), + sendmax(XRP(102)), + txflags(tfNoRippleDirect | tfPartialPayment)); env.require(offers(carol, 0), offers(dan, 1)); @@ -321,15 +334,19 @@ public: env(offer(alice, USD(1), aliceTakerGets)); env.close(); - env.require(offers(carol, 0), balance(carol, - initialCarolUSD)); // offer is removed but not taken + env.require( + offers(carol, 0), + balance( + carol, + initialCarolUSD)); // offer is removed but not taken if (crossBothOffers) { env.require(offers(alice, 0), balance(alice, USD(1))); // alice's offer is crossed } else { - env.require(offers(alice, 1), balance(alice, USD(0))); // alice's offer is not crossed + env.require( + offers(alice, 1), balance(alice, USD(0))); // alice's offer is not crossed } } @@ -353,11 +370,16 @@ public: env.close(); env.require(offers(bob, 1), offers(carol, 1)); - std::uint32_t const flags = partialPayment ? (tfNoRippleDirect | tfPartialPayment) : tfNoRippleDirect; + std::uint32_t const flags = + partialPayment ? (tfNoRippleDirect | tfPartialPayment) : tfNoRippleDirect; TER const expectedTer = partialPayment ? TER{tesSUCCESS} : TER{tecPATH_PARTIAL}; - env(pay(alice, bob, USD(5)), path(~USD), sendmax(XRP(1)), txflags(flags), ter(expectedTer)); + env(pay(alice, bob, USD(5)), + path(~USD), + sendmax(XRP(1)), + txflags(flags), + ter(expectedTer)); env.close(); if (expectedTer == tesSUCCESS) @@ -434,15 +456,19 @@ public: env(offer(alice, USD(1), aliceTakerGets)); env.close(); - env.require(offers(carol, 0), balance(carol, - initialCarolUSD)); // offer is removed but not taken + env.require( + offers(carol, 0), + balance( + carol, + initialCarolUSD)); // offer is removed but not taken if (crossBothOffers) { env.require(offers(alice, 0), balance(alice, USD(1))); // alice's offer is crossed } else { - env.require(offers(alice, 1), balance(alice, USD(0))); // alice's offer is not crossed + env.require( + offers(alice, 1), balance(alice, USD(0))); // alice's offer is not crossed } } @@ -469,11 +495,16 @@ public: env.close(); env.require(offers(bob, 1), offers(carol, 1)); - std::uint32_t const flags = partialPayment ? (tfNoRippleDirect | tfPartialPayment) : tfNoRippleDirect; + std::uint32_t const flags = + partialPayment ? (tfNoRippleDirect | tfPartialPayment) : tfNoRippleDirect; TER const expectedTer = partialPayment ? TER{tesSUCCESS} : TER{tecPATH_PARTIAL}; - env(pay(alice, bob, USD(5)), path(~USD), sendmax(EUR(10)), txflags(flags), ter(expectedTer)); + env(pay(alice, bob, USD(5)), + path(~USD), + sendmax(EUR(10)), + txflags(flags), + ter(expectedTer)); env.close(); if (expectedTer == tesSUCCESS) @@ -556,7 +587,10 @@ public: env(offer(dan, XRP(50), USD1(50))); - env(pay(alice, carol, USD2(50)), path(~USD1, bob), sendmax(XRP(50)), txflags(tfNoRippleDirect)); + env(pay(alice, carol, USD2(50)), + path(~USD1, bob), + sendmax(XRP(50)), + txflags(tfNoRippleDirect)); env.require(balance(alice, xrpMinusFee(env, 10000 - 50))); env.require(balance(bob, USD1(100))); @@ -710,7 +744,9 @@ public: env.close(); // bob creates an offer that expires before the next ledger close. - env(offer(bob, USD(500), XRP(500)), json(sfExpiration.fieldName, lastClose(env) + 1), ter(tesSUCCESS)); + env(offer(bob, USD(500), XRP(500)), + json(sfExpiration.fieldName, lastClose(env) + 1), + ter(tesSUCCESS)); // The offer expires (it's not removed yet). env.close(); @@ -769,11 +805,16 @@ public: // No cross: { TER const expectedCode = tecKILLED; - env(offer(alice, XRP(1000), USD(1000)), txflags(tfImmediateOrCancel), ter(expectedCode)); + env(offer(alice, XRP(1000), USD(1000)), + txflags(tfImmediateOrCancel), + ter(expectedCode)); } env.require( - balance(alice, startBalance - f - f), balance(alice, USD(1000)), owners(alice, 1), offers(alice, 0)); + balance(alice, startBalance - f - f), + balance(alice, USD(1000)), + owners(alice, 1), + offers(alice, 0)); // Partially cross: env(offer(bob, USD(50), XRP(50)), ter(tesSUCCESS)); @@ -913,11 +954,15 @@ public: env.close(); // Order that has invalid flags - env(offer(alice, USD(1000), XRP(1000)), txflags(tfImmediateOrCancel + 1), ter(temINVALID_FLAG)); + env(offer(alice, USD(1000), XRP(1000)), + txflags(tfImmediateOrCancel + 1), + ter(temINVALID_FLAG)); env.require(balance(alice, startBalance), owners(alice, 0), offers(alice, 0)); // Order with incompatible flags - env(offer(alice, USD(1000), XRP(1000)), txflags(tfImmediateOrCancel | tfFillOrKill), ter(temINVALID_FLAG)); + env(offer(alice, USD(1000), XRP(1000)), + txflags(tfImmediateOrCancel | tfFillOrKill), + ter(temINVALID_FLAG)); env.require(balance(alice, startBalance), owners(alice, 0), offers(alice, 0)); // Sell and buy the same asset @@ -952,7 +997,9 @@ public: // Offer with a bad offer sequence { - env(offer(alice, USD(1000), XRP(1000)), json(jss::OfferSequence, std::uint32_t(0)), ter(temBAD_SEQUENCE)); + env(offer(alice, USD(1000), XRP(1000)), + json(jss::OfferSequence, std::uint32_t(0)), + ter(temBAD_SEQUENCE)); env.require(owners(alice, 1), offers(alice, 0)); } @@ -991,22 +1038,40 @@ public: env(trust(alice, usdOffer), ter(tesSUCCESS)); env(pay(gw, alice, usdOffer), ter(tesSUCCESS)); env.close(); - env.require(balance(alice, startBalance - f), balance(alice, usdOffer), offers(alice, 0), owners(alice, 1)); + env.require( + balance(alice, startBalance - f), + balance(alice, usdOffer), + offers(alice, 0), + owners(alice, 1)); - env(offer(alice, xrpOffer, usdOffer), json(sfExpiration.fieldName, lastClose(env)), ter(tecEXPIRED)); + env(offer(alice, xrpOffer, usdOffer), + json(sfExpiration.fieldName, lastClose(env)), + ter(tecEXPIRED)); - env.require(balance(alice, startBalance - f - f), balance(alice, usdOffer), offers(alice, 0), owners(alice, 1)); + env.require( + balance(alice, startBalance - f - f), + balance(alice, usdOffer), + offers(alice, 0), + owners(alice, 1)); env.close(); // Add an offer that expires before the next ledger close - env(offer(alice, xrpOffer, usdOffer), json(sfExpiration.fieldName, lastClose(env) + 1), ter(tesSUCCESS)); + env(offer(alice, xrpOffer, usdOffer), + json(sfExpiration.fieldName, lastClose(env) + 1), + ter(tesSUCCESS)); env.require( - balance(alice, startBalance - f - f - f), balance(alice, usdOffer), offers(alice, 1), owners(alice, 2)); + balance(alice, startBalance - f - f - f), + balance(alice, usdOffer), + offers(alice, 1), + owners(alice, 2)); // The offer expires (it's not removed yet) env.close(); env.require( - balance(alice, startBalance - f - f - f), balance(alice, usdOffer), offers(alice, 1), owners(alice, 2)); + balance(alice, startBalance - f - f - f), + balance(alice, usdOffer), + offers(alice, 1), + owners(alice, 2)); // Add offer - the expired offer is removed env(offer(bob, usdOffer, xrpOffer), ter(tesSUCCESS)); @@ -1198,7 +1263,8 @@ public: // This is one of the few tests where fixReducedOffersV2 changes the // results. So test both with and without fixReducedOffersV2. - for (FeatureBitset localFeatures : {features - fixReducedOffersV2, features | fixReducedOffersV2}) + for (FeatureBitset localFeatures : + {features - fixReducedOffersV2, features | fixReducedOffersV2}) { Env env{*this, localFeatures}; @@ -1242,7 +1308,8 @@ public: BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "50"); jrr = ledgerEntryState(env, bob, gw, "USD"); - BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-2710505431213761e-33"); + BEAST_EXPECT( + jrr[jss::node][sfBalance.fieldName][jss::value] == "-2710505431213761e-33"); // create crossing offer std::uint32_t const bobOfferSeq = env.seq(bob); @@ -1254,7 +1321,8 @@ public: // offer does not cross alice's offer and goes straight into // the ledger. jrr = ledgerEntryState(env, bob, gw, "USD"); - BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-2710505431213761e-33"); + BEAST_EXPECT( + jrr[jss::node][sfBalance.fieldName][jss::value] == "-2710505431213761e-33"); Json::Value const bobOffer = ledgerEntryOffer(env, bob, bobOfferSeq)[jss::node]; BEAST_EXPECT(bobOffer[sfTakerGets.jsonName][jss::value] == "1"); @@ -1280,14 +1348,17 @@ public: jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "0"); BEAST_EXPECT( - env.balance(bob, xrpIssue()) == bob_initial_balance - env.current()->fees().base * 2 + crossingDelta); + env.balance(bob, xrpIssue()) == + bob_initial_balance - env.current()->fees().base * 2 + crossingDelta); } } void testOfferCrossWithXRP(bool reverse_order, FeatureBitset features) { - testcase(std::string("Offer Crossing with XRP, ") + (reverse_order ? "Reverse" : "Normal") + " order"); + testcase( + std::string("Offer Crossing with XRP, ") + (reverse_order ? "Reverse" : "Normal") + + " order"); using namespace jtx; @@ -1323,14 +1394,18 @@ public: jrr = ledgerEntryRoot(env, bob); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == - to_string((XRP(10000) - XRP(reverse_order ? 4000 : 3000) - env.current()->fees().base * 2).xrp())); + to_string( + (XRP(10000) - XRP(reverse_order ? 4000 : 3000) - env.current()->fees().base * 2) + .xrp())); jrr = ledgerEntryState(env, alice, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-499"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == - to_string((XRP(10000) + XRP(reverse_order ? 4000 : 3000) - env.current()->fees().base * 2).xrp())); + to_string( + (XRP(10000) + XRP(reverse_order ? 4000 : 3000) - env.current()->fees().base * 2) + .xrp())); } void @@ -1714,7 +1789,8 @@ public: BEAST_EXPECT(jro[jss::node][jss::TakerPays] == USD(20).value().getJson(JsonOptions::none)); jro = ledgerEntryOffer(env, dan, danOfferSeq); - BEAST_EXPECT(jro[jss::node][jss::TakerGets] == gw2["EUR"](20).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jro[jss::node][jss::TakerGets] == gw2["EUR"](20).value().getJson(JsonOptions::none)); BEAST_EXPECT(jro[jss::node][jss::TakerPays] == XRP(200).value().getText()); } @@ -1809,7 +1885,8 @@ public: // fees: // 1 for each trust limit == 3 (alice < mtgox/amazon/bitstamp) + // 1 for payment == 4 - auto const starting_xrp = XRP(100) + env.current()->fees().accountReserve(3) + env.current()->fees().base * 4; + auto const starting_xrp = + XRP(100) + env.current()->fees().accountReserve(3) + env.current()->fees().base * 4; env.fund(starting_xrp, gw1, gw2, gw3, alice, bob); env.close(); @@ -1831,7 +1908,8 @@ public: BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "100"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName] == STAmount(env.current()->fees().accountReserve(3)).getText()); + jrr[jss::node][sfBalance.fieldName] == + STAmount(env.current()->fees().accountReserve(3)).getText()); jrr = ledgerEntryState(env, bob, gw1, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-400"); @@ -1904,7 +1982,8 @@ public: auto const bob = Account{"bob"}; auto const USD = gw["USD"]; - auto const starting_xrp = XRP(100) + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2; + auto const starting_xrp = + XRP(100) + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2; env.fund(starting_xrp, gw, alice, bob); env.close(); @@ -1924,7 +2003,8 @@ public: BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-100"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName] == STAmount(env.current()->fees().accountReserve(1)).getText()); + jrr[jss::node][sfBalance.fieldName] == + STAmount(env.current()->fees().accountReserve(1)).getText()); jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-400"); @@ -1944,7 +2024,8 @@ public: auto const bob = Account{"bob"}; auto const USD = gw["USD"]; - auto const starting_xrp = XRP(100) + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2; + auto const starting_xrp = + XRP(100) + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2; env.fund(starting_xrp, gw, alice, bob); env.close(); @@ -1966,7 +2047,8 @@ public: BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-200"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName] == STAmount(env.current()->fees().accountReserve(1)).getText()); + jrr[jss::node][sfBalance.fieldName] == + STAmount(env.current()->fees().accountReserve(1)).getText()); jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-300"); @@ -1987,7 +2069,8 @@ public: auto const XTS = gw["XTS"]; auto const XXX = gw["XXX"]; - auto const starting_xrp = XRP(100.1) + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2; + auto const starting_xrp = + XRP(100.1) + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2; env.fund(starting_xrp, gw, alice, bob); env.close(); @@ -2012,7 +2095,8 @@ public: payment[jss::id] = env.seq(bob); payment[jss::build_path] = true; payment[jss::tx_json] = pay(bob, bob, bob["XXX"](1)); - payment[jss::tx_json][jss::Sequence] = env.current()->read(keylet::account(bob.id()))->getFieldU32(sfSequence); + payment[jss::tx_json][jss::Sequence] = + env.current()->read(keylet::account(bob.id()))->getFieldU32(sfSequence); payment[jss::tx_json][jss::Fee] = to_string(env.current()->fees().base); payment[jss::tx_json][jss::SendMax] = bob["XTS"](1.5).value().getJson(JsonOptions::none); auto jrr = wsc->invoke("submit", payment); @@ -2043,7 +2127,10 @@ public: // a trust line defined). If the trustline is not defaulted then the tests // will not pass. void - verifyDefaultTrustline(jtx::Env& env, jtx::Account const& account, jtx::PrettyAmount const& expectBalance) + verifyDefaultTrustline( + jtx::Env& env, + jtx::Account const& account, + jtx::PrettyAmount const& expectBalance) { auto const sleTrust = env.le(keylet::line(account.id(), expectBalance.value().issue())); BEAST_EXPECT(sleTrust); @@ -2350,7 +2437,8 @@ public: env(offer(bob, usdOffer, eurOffer)); env.close(); - env.require(balance(alice, eurOffer), balance(bob, usdOffer), offers(alice, 0), offers(bob, 0)); + env.require( + balance(alice, eurOffer), balance(bob, usdOffer), offers(alice, 0), offers(bob, 0)); // Alice's offer crossing created a default EUR trustline and // Bob's offer crossing created a default USD trustline: @@ -3835,9 +3923,12 @@ public: auto actorOffers = offersOnAccount(env, actor.acct); auto const offerCount = std::distance( actorOffers.begin(), - std::remove_if(actorOffers.begin(), actorOffers.end(), [](std::shared_ptr& offer) { - return (*offer)[sfTakerGets].signum() == 0; - })); + std::remove_if( + actorOffers.begin(), + actorOffers.end(), + [](std::shared_ptr& offer) { + return (*offer)[sfTakerGets].signum() == 0; + })); BEAST_EXPECT(offerCount == actor.offers); env.require(balance(actor.acct, actor.xrp)); @@ -3981,9 +4072,12 @@ public: auto actorOffers = offersOnAccount(env, actor.acct); auto const offerCount = std::distance( actorOffers.begin(), - std::remove_if(actorOffers.begin(), actorOffers.end(), [](std::shared_ptr& offer) { - return (*offer)[sfTakerGets].signum() == 0; - })); + std::remove_if( + actorOffers.begin(), + actorOffers.end(), + [](std::shared_ptr& offer) { + return (*offer)[sfTakerGets].signum() == 0; + })); BEAST_EXPECT(offerCount == actor.offers); env.require(balance(actor.acct, actor.xrp)); @@ -4248,7 +4342,8 @@ public: jvParams[jss::destination_amount][jss::value] = 10; jvParams[jss::source_account] = hotUS.human(); - Json::Value const jrr{env.rpc("json", "ripple_path_find", to_string(jvParams))[jss::result]}; + Json::Value const jrr{ + env.rpc("json", "ripple_path_find", to_string(jvParams))[jss::result]}; BEAST_EXPECT(jrr[jss::status] == "success"); BEAST_EXPECT(jrr[jss::alternatives].isArray() && jrr[jss::alternatives].size() > 0); @@ -4329,8 +4424,10 @@ public: testcase("Deleted offer issuer"); - auto trustLineExists = - [](jtx::Env const& env, jtx::Account const& src, jtx::Account const& dst, Currency const& cur) -> bool { + auto trustLineExists = [](jtx::Env const& env, + jtx::Account const& src, + jtx::Account const& dst, + Currency const& cur) -> bool { return bool(env.le(keylet::line(src, dst, cur))); }; @@ -4496,13 +4593,16 @@ public: std::map> offers; forEachItem(*env.current(), alice, [&](std::shared_ptr const& sle) { if (sle->getType() == ltOFFER) - offers.emplace((*sle)[sfSequence], std::make_pair((*sle)[sfTakerPays], (*sle)[sfTakerGets])); + offers.emplace( + (*sle)[sfSequence], std::make_pair((*sle)[sfTakerPays], (*sle)[sfTakerGets])); }); // first offer auto it = offers.begin(); BEAST_EXPECT(it != offers.end()); - BEAST_EXPECT(it->second.first == XTS(10) && it->second.second < XXX(30) && it->second.second > XXX(29.9994)); + BEAST_EXPECT( + it->second.first == XTS(10) && it->second.second < XXX(30) && + it->second.second > XXX(29.9994)); // second offer ++it; @@ -4951,9 +5051,12 @@ public: } BEAST_EXPECT( - env.balance(maker, USD) == makerUSDBalance && env.balance(taker, USD) == takerUSDBalance && - env.balance(maker, EUR) == makerEURBalance && env.balance(taker, EUR) == takerEURBalance && - env.balance(maker, XRP) == makerXRPBalance && env.balance(taker, XRP) == takerXRPBalance); + env.balance(maker, USD) == makerUSDBalance && + env.balance(taker, USD) == takerUSDBalance && + env.balance(maker, EUR) == makerEURBalance && + env.balance(taker, EUR) == takerEURBalance && + env.balance(maker, XRP) == makerXRPBalance && + env.balance(taker, XRP) == takerXRPBalance); } void diff --git a/src/test/app/Oracle_test.cpp b/src/test/app/Oracle_test.cpp index 66a8969164..9da0ee3a31 100644 --- a/src/test/app/Oracle_test.cpp +++ b/src/test/app/Oracle_test.cpp @@ -44,20 +44,23 @@ private: // Insufficient reserve if the data series extends to greater than 5 { Env env(*this); - env.fund(env.current()->fees().accountReserve(1) + env.current()->fees().base * 2, owner); - Oracle oracle(env, {.owner = owner, .fee = static_cast(env.current()->fees().base.drops())}); + env.fund( + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2, owner); + Oracle oracle( + env, {.owner = owner, .fee = static_cast(env.current()->fees().base.drops())}); BEAST_EXPECT(oracle.exists()); - oracle.set(UpdateArg{ - .series = - { - {"XRP", "EUR", 740, 1}, - {"XRP", "GBP", 740, 1}, - {"XRP", "CNY", 740, 1}, - {"XRP", "CAD", 740, 1}, - {"XRP", "AUD", 740, 1}, - }, - .fee = static_cast(env.current()->fees().base.drops()), - .err = ter(tecINSUFFICIENT_RESERVE)}); + oracle.set( + UpdateArg{ + .series = + { + {"XRP", "EUR", 740, 1}, + {"XRP", "GBP", 740, 1}, + {"XRP", "CNY", 740, 1}, + {"XRP", "CAD", 740, 1}, + {"XRP", "AUD", 740, 1}, + }, + .fee = static_cast(env.current()->fees().base.drops()), + .err = ter(tecINSUFFICIENT_RESERVE)}); } { @@ -67,45 +70,53 @@ private: Oracle oracle(env, {.owner = owner, .fee = baseFee}, false); // Invalid flag - oracle.set(CreateArg{.flags = tfSellNFToken, .fee = baseFee, .err = ter(temINVALID_FLAG)}); + oracle.set( + CreateArg{.flags = tfSellNFToken, .fee = baseFee, .err = ter(temINVALID_FLAG)}); // Duplicate token pair - oracle.set(CreateArg{ - .series = {{"XRP", "USD", 740, 1}, {"XRP", "USD", 750, 1}}, .fee = baseFee, .err = ter(temMALFORMED)}); + oracle.set( + CreateArg{ + .series = {{"XRP", "USD", 740, 1}, {"XRP", "USD", 750, 1}}, + .fee = baseFee, + .err = ter(temMALFORMED)}); // Price is not included - oracle.set(CreateArg{ - .series = {{"XRP", "USD", 740, 1}, {"XRP", "EUR", std::nullopt, 1}}, - .fee = baseFee, - .err = ter(temMALFORMED)}); + oracle.set( + CreateArg{ + .series = {{"XRP", "USD", 740, 1}, {"XRP", "EUR", std::nullopt, 1}}, + .fee = baseFee, + .err = ter(temMALFORMED)}); // Token pair is in update and delete - oracle.set(CreateArg{ - .series = {{"XRP", "USD", 740, 1}, {"XRP", "USD", std::nullopt, 1}}, - .fee = baseFee, - .err = ter(temMALFORMED)}); + oracle.set( + CreateArg{ + .series = {{"XRP", "USD", 740, 1}, {"XRP", "USD", std::nullopt, 1}}, + .fee = baseFee, + .err = ter(temMALFORMED)}); // Token pair is in add and delete - oracle.set(CreateArg{ - .series = {{"XRP", "EUR", 740, 1}, {"XRP", "EUR", std::nullopt, 1}}, - .fee = baseFee, - .err = ter(temMALFORMED)}); + oracle.set( + CreateArg{ + .series = {{"XRP", "EUR", 740, 1}, {"XRP", "EUR", std::nullopt, 1}}, + .fee = baseFee, + .err = ter(temMALFORMED)}); // Array of token pair is 0 or exceeds 10 - oracle.set(CreateArg{ - .series = - {{"XRP", "US1", 740, 1}, - {"XRP", "US2", 750, 1}, - {"XRP", "US3", 740, 1}, - {"XRP", "US4", 750, 1}, - {"XRP", "US5", 740, 1}, - {"XRP", "US6", 750, 1}, - {"XRP", "US7", 740, 1}, - {"XRP", "US8", 750, 1}, - {"XRP", "US9", 740, 1}, - {"XRP", "U10", 750, 1}, - {"XRP", "U11", 740, 1}}, - .fee = baseFee, - .err = ter(temARRAY_TOO_LARGE)}); + oracle.set( + CreateArg{ + .series = + {{"XRP", "US1", 740, 1}, + {"XRP", "US2", 750, 1}, + {"XRP", "US3", 740, 1}, + {"XRP", "US4", 750, 1}, + {"XRP", "US5", 740, 1}, + {"XRP", "US6", 750, 1}, + {"XRP", "US7", 740, 1}, + {"XRP", "US8", 750, 1}, + {"XRP", "US9", 740, 1}, + {"XRP", "U10", 750, 1}, + {"XRP", "U11", 740, 1}}, + .fee = baseFee, + .err = ter(temARRAY_TOO_LARGE)}); oracle.set(CreateArg{.series = {}, .fee = baseFee, .err = ter(temARRAY_EMPTY)}); } @@ -115,23 +126,26 @@ private: auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); - Oracle oracle(env, CreateArg{.owner = owner, .series = {{{"XRP", "USD", 740, 1}}}, .fee = baseFee}); - oracle.set(UpdateArg{ - .series = - { - {"XRP", "US1", 740, 1}, - {"XRP", "US2", 750, 1}, - {"XRP", "US3", 740, 1}, - {"XRP", "US4", 750, 1}, - {"XRP", "US5", 740, 1}, - {"XRP", "US6", 750, 1}, - {"XRP", "US7", 740, 1}, - {"XRP", "US8", 750, 1}, - {"XRP", "US9", 740, 1}, - {"XRP", "U10", 750, 1}, - }, - .fee = baseFee, - .err = ter(tecARRAY_TOO_LARGE)}); + Oracle oracle( + env, + CreateArg{.owner = owner, .series = {{{"XRP", "USD", 740, 1}}}, .fee = baseFee}); + oracle.set( + UpdateArg{ + .series = + { + {"XRP", "US1", 740, 1}, + {"XRP", "US2", 750, 1}, + {"XRP", "US3", 740, 1}, + {"XRP", "US4", 750, 1}, + {"XRP", "US5", 740, 1}, + {"XRP", "US6", 750, 1}, + {"XRP", "US7", 740, 1}, + {"XRP", "US8", 750, 1}, + {"XRP", "US9", 740, 1}, + {"XRP", "U10", 750, 1}, + }, + .fee = baseFee, + .err = ter(tecARRAY_TOO_LARGE)}); } { @@ -141,26 +155,36 @@ private: Oracle oracle(env, {.owner = owner, .fee = baseFee}, false); // Asset class or provider not included on create - oracle.set(CreateArg{ - .assetClass = std::nullopt, .provider = "provider", .fee = baseFee, .err = ter(temMALFORMED)}); - oracle.set(CreateArg{ - .assetClass = "currency", - .provider = std::nullopt, - .uri = "URI", - .fee = baseFee, - .err = ter(temMALFORMED)}); + oracle.set( + CreateArg{ + .assetClass = std::nullopt, + .provider = "provider", + .fee = baseFee, + .err = ter(temMALFORMED)}); + oracle.set( + CreateArg{ + .assetClass = "currency", + .provider = std::nullopt, + .uri = "URI", + .fee = baseFee, + .err = ter(temMALFORMED)}); // Asset class or provider are included on update // and don't match the current values oracle.set(CreateArg{.fee = static_cast(env.current()->fees().base.drops())}); BEAST_EXPECT(oracle.exists()); - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 740, 1}}, .provider = "provider1", .fee = baseFee, .err = ter(temMALFORMED)}); - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 740, 1}}, - .assetClass = "currency1", - .fee = baseFee, - .err = ter(temMALFORMED)}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "USD", 740, 1}}, + .provider = "provider1", + .fee = baseFee, + .err = ter(temMALFORMED)}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "USD", 740, 1}}, + .assetClass = "currency1", + .fee = baseFee, + .err = ter(temMALFORMED)}); } { @@ -172,7 +196,8 @@ private: // Fields too long // Asset class std::string assetClass(17, '0'); - oracle.set(CreateArg{.assetClass = assetClass, .fee = baseFee, .err = ter(temMALFORMED)}); + oracle.set( + CreateArg{.assetClass = assetClass, .fee = baseFee, .err = ter(temMALFORMED)}); // provider std::string const large(257, '0'); oracle.set(CreateArg{.provider = large, .fee = baseFee, .err = ter(temMALFORMED)}); @@ -198,7 +223,11 @@ private: Oracle oracle(env, {.owner = owner, .fee = baseFee}); BEAST_EXPECT(oracle.exists()); oracle.set( - UpdateArg{.owner = some, .series = {{"XRP", "USD", 740, 1}}, .fee = baseFee, .err = ter(temMALFORMED)}); + UpdateArg{ + .owner = some, + .series = {{"XRP", "USD", 740, 1}}, + .fee = baseFee, + .err = ter(temMALFORMED)}); } { @@ -207,38 +236,45 @@ private: Env env(*this); auto const baseFee = static_cast(env.current()->fees().base.drops()); auto closeTime = [&]() { - return duration_cast(env.current()->header().closeTime.time_since_epoch() - 10'000s).count(); + return duration_cast( + env.current()->header().closeTime.time_since_epoch() - 10'000s) + .count(); }; env.fund(XRP(1'000), owner); Oracle oracle(env, {.owner = owner, .fee = baseFee}); BEAST_EXPECT(oracle.exists()); env.close(seconds(400)); // Less than the last close time - 300s - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 740, 1}}, - .lastUpdateTime = static_cast(closeTime() - 301), - .fee = baseFee, - .err = ter(tecINVALID_UPDATE_TIME)}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "USD", 740, 1}}, + .lastUpdateTime = static_cast(closeTime() - 301), + .fee = baseFee, + .err = ter(tecINVALID_UPDATE_TIME)}); // Greater than last close time + 300s - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 740, 1}}, - .lastUpdateTime = static_cast(closeTime() + 311), - .fee = baseFee, - .err = ter(tecINVALID_UPDATE_TIME)}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "USD", 740, 1}}, + .lastUpdateTime = static_cast(closeTime() + 311), + .fee = baseFee, + .err = ter(tecINVALID_UPDATE_TIME)}); oracle.set(UpdateArg{.series = {{"XRP", "USD", 740, 1}}, .fee = baseFee}); - BEAST_EXPECT(oracle.expectLastUpdateTime(static_cast(testStartTime.count() + 450))); + BEAST_EXPECT(oracle.expectLastUpdateTime( + static_cast(testStartTime.count() + 450))); // Less than the previous lastUpdateTime - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 740, 1}}, - .lastUpdateTime = static_cast(449), - .fee = baseFee, - .err = ter(tecINVALID_UPDATE_TIME)}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "USD", 740, 1}}, + .lastUpdateTime = static_cast(449), + .fee = baseFee, + .err = ter(tecINVALID_UPDATE_TIME)}); // Less than the epoch time - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 740, 1}}, - .lastUpdateTime = static_cast(epoch_offset.count() - 1), - .fee = baseFee, - .err = ter(tecINVALID_UPDATE_TIME)}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "USD", 740, 1}}, + .lastUpdateTime = static_cast(epoch_offset.count() - 1), + .fee = baseFee, + .err = ter(tecINVALID_UPDATE_TIME)}); } { @@ -248,13 +284,17 @@ private: env.fund(XRP(1'000), owner); Oracle oracle(env, {.owner = owner, .fee = baseFee}); BEAST_EXPECT(oracle.exists()); - oracle.set(UpdateArg{ - .series = {{"XRP", "EUR", std::nullopt, std::nullopt}}, - .fee = baseFee, - .err = ter(tecTOKEN_PAIR_NOT_FOUND)}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "EUR", std::nullopt, std::nullopt}}, + .fee = baseFee, + .err = ter(tecTOKEN_PAIR_NOT_FOUND)}); // delete all token pairs - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", std::nullopt, std::nullopt}}, .fee = baseFee, .err = ter(tecARRAY_EMPTY)}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "USD", std::nullopt, std::nullopt}}, + .fee = baseFee, + .err = ter(tecARRAY_EMPTY)}); } { @@ -263,7 +303,11 @@ private: auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); Oracle oracle( - env, {.owner = owner, .series = {{"USD", "USD", 740, 1}}, .fee = baseFee, .err = ter(temMALFORMED)}); + env, + {.owner = owner, + .series = {{"USD", "USD", 740, 1}}, + .fee = baseFee, + .err = ter(temMALFORMED)}); } { @@ -285,21 +329,24 @@ private: auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); Oracle oracle(env, {.owner = owner, .fee = baseFee}); - oracle.set(UpdateArg{ - .series = {{"XRP", "EUR", std::nullopt, std::nullopt}, {"XRP", "EUR", 740, 1}}, - .fee = baseFee, - .err = ter(temMALFORMED)}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "EUR", std::nullopt, std::nullopt}, {"XRP", "EUR", 740, 1}}, + .fee = baseFee, + .err = ter(temMALFORMED)}); // Delete token pair that doesn't exist in this oracle - oracle.set(UpdateArg{ - .series = {{"XRP", "EUR", std::nullopt, std::nullopt}}, - .fee = baseFee, - .err = ter(tecTOKEN_PAIR_NOT_FOUND)}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "EUR", std::nullopt, std::nullopt}}, + .fee = baseFee, + .err = ter(tecTOKEN_PAIR_NOT_FOUND)}); // Delete token pair in oracle, which is not in the ledger - oracle.set(UpdateArg{ - .documentID = 10, - .series = {{"XRP", "EUR", std::nullopt, std::nullopt}}, - .fee = baseFee, - .err = ter(temMALFORMED)}); + oracle.set( + UpdateArg{ + .documentID = 10, + .series = {{"XRP", "EUR", std::nullopt, std::nullopt}}, + .fee = baseFee, + .err = ter(temMALFORMED)}); } { @@ -307,7 +354,8 @@ private: Env env(*this); env.fund(XRP(1'000), owner); Oracle oracle(env, {.owner = owner, .fee = -1, .err = ter(temBAD_FEE)}); - Oracle oracle1(env, {.owner = owner, .fee = static_cast(env.current()->fees().base.drops())}); + Oracle oracle1( + env, {.owner = owner, .fee = static_cast(env.current()->fees().base.drops())}); oracle.set(UpdateArg{.owner = owner, .fee = -1, .err = ter(temBAD_FEE)}); } } @@ -368,7 +416,8 @@ private: env.fund(XRP(1'000), some); Oracle oracle(env, {.owner = owner, .fee = baseFee}); BEAST_EXPECT(oracle.exists()); - oracle.set(CreateArg{.owner = some, .series = {{"912810RR9", "USD", 740, 1}}, .fee = baseFee}); + oracle.set( + CreateArg{.owner = some, .series = {{"912810RR9", "USD", 740, 1}}, .fee = baseFee}); BEAST_EXPECT(Oracle::exists(env, some, oracle.documentID())); } } @@ -457,8 +506,14 @@ private: auto const acctDelFee{drops(env.current()->fees().increment)}; env.fund(XRP(1'000), owner); env.fund(XRP(1'000), alice); - Oracle oracle(env, {.owner = owner, .series = {{"XRP", "USD", 740, 1}}, .fee = baseFee}); - Oracle oracle1(env, {.owner = owner, .documentID = 2, .series = {{"XRP", "EUR", 740, 1}}, .fee = baseFee}); + Oracle oracle( + env, {.owner = owner, .series = {{"XRP", "USD", 740, 1}}, .fee = baseFee}); + Oracle oracle1( + env, + {.owner = owner, + .documentID = 2, + .series = {{"XRP", "EUR", 740, 1}}, + .fee = baseFee}); BEAST_EXPECT(ownerCount(env, owner) == 2); BEAST_EXPECT(oracle.exists()); BEAST_EXPECT(oracle1.exists()); @@ -515,34 +570,39 @@ private: BEAST_EXPECT(ownerCount(env, owner) == count); // update both pairs - oracle.set(UpdateArg{.series = {{"XRP", "USD", 741, 2}, {"XRP", "EUR", 710, 2}}, .fee = baseFee}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "USD", 741, 2}, {"XRP", "EUR", 710, 2}}, .fee = baseFee}); BEAST_EXPECT(oracle.expectPrice({{"XRP", "USD", 741, 2}, {"XRP", "EUR", 710, 2}})); // owner count is not changed since the number of pairs is 2 BEAST_EXPECT(ownerCount(env, owner) == count); // owner count is increased by 1 since the number of pairs is 6 - oracle.set(UpdateArg{ - .series = - { - {"BTC", "USD", 741, 2}, - {"ETH", "EUR", 710, 2}, - {"YAN", "EUR", 710, 2}, - {"CAN", "EUR", 710, 2}, - }, - .fee = baseFee}); + oracle.set( + UpdateArg{ + .series = + { + {"BTC", "USD", 741, 2}, + {"ETH", "EUR", 710, 2}, + {"YAN", "EUR", 710, 2}, + {"CAN", "EUR", 710, 2}, + }, + .fee = baseFee}); count += 1; BEAST_EXPECT(ownerCount(env, owner) == count); // update two pairs and delete four - oracle.set(UpdateArg{.series = {{"BTC", "USD", std::nullopt, std::nullopt}}, .fee = baseFee}); - oracle.set(UpdateArg{ - .series = - {{"XRP", "USD", 742, 2}, - {"XRP", "EUR", 711, 2}, - {"ETH", "EUR", std::nullopt, std::nullopt}, - {"YAN", "EUR", std::nullopt, std::nullopt}, - {"CAN", "EUR", std::nullopt, std::nullopt}}, - .fee = baseFee}); + oracle.set( + UpdateArg{.series = {{"BTC", "USD", std::nullopt, std::nullopt}}, .fee = baseFee}); + oracle.set( + UpdateArg{ + .series = + {{"XRP", "USD", 742, 2}, + {"XRP", "EUR", 711, 2}, + {"ETH", "EUR", std::nullopt, std::nullopt}, + {"YAN", "EUR", std::nullopt, std::nullopt}, + {"CAN", "EUR", std::nullopt, std::nullopt}}, + .fee = baseFee}); BEAST_EXPECT(oracle.expectPrice({{"XRP", "USD", 742, 2}, {"XRP", "EUR", 711, 2}})); // owner count is decreased by 1 since the number of pairs is 2 count -= 1; @@ -553,7 +613,8 @@ private: { Env env(*this); auto const baseFee = static_cast(env.current()->fees().base.drops()); - env.fund(env.current()->fees().accountReserve(1) + env.current()->fees().base * 2, owner); + env.fund( + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2, owner); Oracle oracle(env, {.owner = owner, .fee = baseFee}); oracle.set(UpdateArg{.series = {{"XRP", "USD", 742, 2}}, .fee = baseFee}); } @@ -561,7 +622,9 @@ private: for (bool const withFixOrder : {false, true}) { // Should be same order as creation - Env env(*this, withFixOrder ? testable_amendments() : testable_amendments() - fixPriceOracleOrder); + Env env( + *this, + withFixOrder ? testable_amendments() : testable_amendments() - fixPriceOracleOrder); auto const baseFee = static_cast(env.current()->fees().base.drops()); auto test = [&](Env& env, DataSeries const& series) { @@ -571,18 +634,22 @@ private: auto sle = env.le(keylet::oracle(owner, oracle.documentID())); BEAST_EXPECT(sle->getFieldArray(sfPriceDataSeries).size() == series.size()); - auto const beforeQuoteAssetName1 = - sle->getFieldArray(sfPriceDataSeries)[0].getFieldCurrency(sfQuoteAsset).getText(); - auto const beforeQuoteAssetName2 = - sle->getFieldArray(sfPriceDataSeries)[1].getFieldCurrency(sfQuoteAsset).getText(); + auto const beforeQuoteAssetName1 = sle->getFieldArray(sfPriceDataSeries)[0] + .getFieldCurrency(sfQuoteAsset) + .getText(); + auto const beforeQuoteAssetName2 = sle->getFieldArray(sfPriceDataSeries)[1] + .getFieldCurrency(sfQuoteAsset) + .getText(); oracle.set(UpdateArg{.series = series, .fee = baseFee}); sle = env.le(keylet::oracle(owner, oracle.documentID())); - auto const afterQuoteAssetName1 = - sle->getFieldArray(sfPriceDataSeries)[0].getFieldCurrency(sfQuoteAsset).getText(); - auto const afterQuoteAssetName2 = - sle->getFieldArray(sfPriceDataSeries)[1].getFieldCurrency(sfQuoteAsset).getText(); + auto const afterQuoteAssetName1 = sle->getFieldArray(sfPriceDataSeries)[0] + .getFieldCurrency(sfQuoteAsset) + .getText(); + auto const afterQuoteAssetName2 = sle->getFieldArray(sfPriceDataSeries)[1] + .getFieldCurrency(sfQuoteAsset) + .getText(); if (env.current()->rules().enabled(fixPriceOracleOrder)) { @@ -638,11 +705,21 @@ private: BEAST_EXPECT(oracle.exists()); // Update - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 740, 1}}, .msig = msig(becky), .fee = baseFee, .err = ter(tefBAD_QUORUM)}); - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 740, 1}}, .msig = msig(zelda), .fee = baseFee, .err = ter(tefBAD_SIGNATURE)}); - oracle.set(UpdateArg{.series = {{"XRP", "USD", 741, 1}}, .msig = msig(becky, bogie), .fee = baseFee}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "USD", 740, 1}}, + .msig = msig(becky), + .fee = baseFee, + .err = ter(tefBAD_QUORUM)}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "USD", 740, 1}}, + .msig = msig(zelda), + .fee = baseFee, + .err = ter(tefBAD_SIGNATURE)}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "USD", 741, 1}}, .msig = msig(becky, bogie), .fee = baseFee}); BEAST_EXPECT(oracle.expectPrice({{"XRP", "USD", 741, 1}})); // remove the signer list env(signers(alice, jtx::none), sig(alie)); @@ -652,15 +729,19 @@ private: env(signers(alice, 2, {{zelda, 1}, {bob, 1}, {ed, 2}}), sig(alie)); env.close(); // old list fails - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 740, 1}}, - .msig = msig(becky, bogie), - .fee = baseFee, - .err = ter(tefBAD_SIGNATURE)}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "USD", 740, 1}}, + .msig = msig(becky, bogie), + .fee = baseFee, + .err = ter(tefBAD_SIGNATURE)}); // updated list succeeds - oracle.set(UpdateArg{.series = {{"XRP", "USD", 7412, 2}}, .msig = msig(zelda, bob), .fee = baseFee}); + oracle.set( + UpdateArg{ + .series = {{"XRP", "USD", 7412, 2}}, .msig = msig(zelda, bob), .fee = baseFee}); BEAST_EXPECT(oracle.expectPrice({{"XRP", "USD", 7412, 2}})); - oracle.set(UpdateArg{.series = {{"XRP", "USD", 74245, 3}}, .msig = msig(ed), .fee = baseFee}); + oracle.set( + UpdateArg{.series = {{"XRP", "USD", 74245, 3}}, .msig = msig(ed), .fee = baseFee}); BEAST_EXPECT(oracle.expectPrice({{"XRP", "USD", 74245, 3}})); // Remove diff --git a/src/test/app/Path_test.cpp b/src/test/app/Path_test.cpp index c019c2b8a3..c2de4f3f08 100644 --- a/src/test/app/Path_test.cpp +++ b/src/test/app/Path_test.cpp @@ -178,7 +178,8 @@ public: std::optional const& saSrcCurrency = std::nullopt, std::optional const& domain = std::nullopt) { - Json::Value result = find_paths_request(env, src, dst, saDstAmount, saSendMax, saSrcCurrency, domain); + Json::Value result = + find_paths_request(env, src, dst, saDstAmount, saSendMax, saSrcCurrency, domain); BEAST_EXPECT(!result.isMember(jss::error)); STAmount da; @@ -360,8 +361,8 @@ public: STPathSet st; STAmount sa; - std::tie(st, sa, std::ignore) = - find_paths(env, "alice", "bob", Account("bob")["USD"](5), std::nullopt, std::nullopt, domainID); + std::tie(st, sa, std::ignore) = find_paths( + env, "alice", "bob", Account("bob")["USD"](5), std::nullopt, std::nullopt, domainID); BEAST_EXPECT(same(st, stpath("gateway"))); BEAST_EXPECT(equal(sa, Account("alice")["USD"](5))); } @@ -379,14 +380,16 @@ public: if (domainEnabled) domainID = setupDomain(env, {"alice", "bob"}); - auto const result = find_paths(env, "alice", "bob", XRP(5), std::nullopt, std::nullopt, domainID); + auto const result = + find_paths(env, "alice", "bob", XRP(5), std::nullopt, std::nullopt, domainID); BEAST_EXPECT(std::get<0>(result).empty()); } void path_find_consume_all(bool const domainEnabled) { - testcase(std::string("path find consume all") + (domainEnabled ? " w/ " : " w/o ") + "domain"); + testcase( + std::string("path find consume all") + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; { @@ -406,8 +409,14 @@ public: STPathSet st; STAmount sa; STAmount da; - std::tie(st, sa, da) = - find_paths(env, "alice", "edward", Account("edward")["USD"](-1), std::nullopt, std::nullopt, domainID); + std::tie(st, sa, da) = find_paths( + env, + "alice", + "edward", + Account("edward")["USD"](-1), + std::nullopt, + std::nullopt, + domainID); BEAST_EXPECT(same(st, stpath("dan"), stpath("bob", "carol"))); BEAST_EXPECT(equal(sa, Account("alice")["USD"](110))); BEAST_EXPECT(equal(da, Account("edward")["USD"](110))); @@ -479,7 +488,9 @@ public: void alternative_path_consume_both(bool const domainEnabled) { - testcase(std::string("alternative path consume both") + (domainEnabled ? " w/ " : " w/o ") + "domain"); + testcase( + std::string("alternative path consume both") + (domainEnabled ? " w/ " : " w/o ") + + "domain"); using namespace jtx; Env env = pathTestEnv(); auto const gw = Account("gateway"); @@ -499,7 +510,9 @@ public: domainID = setupDomain(env, {"alice", "bob", "gateway", "gateway2"}); env(pay(gw, "alice", USD(70)), domain(*domainID)); env(pay(gw2, "alice", gw2_USD(70)), domain(*domainID)); - env(pay("alice", "bob", Account("bob")["USD"](140)), paths(Account("alice")["USD"]), domain(*domainID)); + env(pay("alice", "bob", Account("bob")["USD"](140)), + paths(Account("alice")["USD"]), + domain(*domainID)); } else { @@ -522,7 +535,8 @@ public: alternative_paths_consume_best_transfer(bool const domainEnabled) { testcase( - std::string("alternative paths consume best transfer") + (domainEnabled ? " w/ " : " w/o ") + "domain"); + std::string("alternative paths consume best transfer") + + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); auto const gw = Account("gateway"); @@ -630,16 +644,18 @@ public: STPathSet st; STAmount sa; - std::tie(st, sa, std::ignore) = - find_paths(env, "alice", "bob", Account("bob")["USD"](5), std::nullopt, std::nullopt, domainID); - BEAST_EXPECT(same(st, stpath("gateway"), stpath("gateway2"), stpath("dan"), stpath("carol"))); + std::tie(st, sa, std::ignore) = find_paths( + env, "alice", "bob", Account("bob")["USD"](5), std::nullopt, std::nullopt, domainID); + BEAST_EXPECT( + same(st, stpath("gateway"), stpath("gateway2"), stpath("dan"), stpath("carol"))); BEAST_EXPECT(equal(sa, Account("alice")["USD"](5))); } void issues_path_negative_issue(bool const domainEnabled) { - testcase(std::string("path negative: Issue #5") + (domainEnabled ? " w/ " : " w/o ") + "domain"); + testcase( + std::string("path negative: Issue #5") + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); env.fund(XRP(10000), "alice", "bob", "carol", "dan"); @@ -658,13 +674,15 @@ public: domainID = setupDomain(env, {"alice", "bob", "carol", "dan"}); } - auto result = find_paths(env, "alice", "bob", Account("bob")["USD"](25), std::nullopt, std::nullopt, domainID); + auto result = find_paths( + env, "alice", "bob", Account("bob")["USD"](25), std::nullopt, std::nullopt, domainID); BEAST_EXPECT(std::get<0>(result).empty()); env(pay("alice", "bob", Account("alice")["USD"](25)), ter(tecPATH_DRY)); env.close(); - result = find_paths(env, "alice", "bob", Account("alice")["USD"](25), std::nullopt, std::nullopt, domainID); + result = find_paths( + env, "alice", "bob", Account("alice")["USD"](25), std::nullopt, std::nullopt, domainID); BEAST_EXPECT(std::get<0>(result).empty()); env.require(balance("alice", Account("bob")["USD"](0))); @@ -765,8 +783,8 @@ public: env.require(balance("bob", AUD(10))); env.require(balance("carol", AUD(39))); - auto const result = - find_paths(env, "alice", "bob", Account("bob")["USD"](25), std::nullopt, std::nullopt, domainID); + auto const result = find_paths( + env, "alice", "bob", Account("bob")["USD"](25), std::nullopt, std::nullopt, domainID); BEAST_EXPECT(std::get<0>(result).empty()); } @@ -783,7 +801,8 @@ public: STPathSet st; STAmount sa; - std::tie(st, sa, std::ignore) = find_paths(env, "alice", "carol", Account("carol")["USD"](5)); + std::tie(st, sa, std::ignore) = + find_paths(env, "alice", "carol", Account("carol")["USD"](5)); BEAST_EXPECT(same(st, stpath("bob"))); BEAST_EXPECT(equal(sa, Account("alice")["USD"](5))); } @@ -827,8 +846,8 @@ public: })", jv); - auto const jv_l = - env.le(keylet::line(Account("bob").id(), Account("alice")["USD"].issue()))->getJson(JsonOptions::none); + auto const jv_l = env.le(keylet::line(Account("bob").id(), Account("alice")["USD"].issue())) + ->getJson(JsonOptions::none); for (auto it = jv.begin(); it != jv.end(); ++it) BEAST_EXPECT(*it == jv_l[it.memberName()]); } @@ -869,14 +888,15 @@ public: })", jv); - auto const jv_l = - env.le(keylet::line(Account("bob").id(), Account("alice")["USD"].issue()))->getJson(JsonOptions::none); + auto const jv_l = env.le(keylet::line(Account("bob").id(), Account("alice")["USD"].issue())) + ->getJson(JsonOptions::none); for (auto it = jv.begin(); it != jv.end(); ++it) BEAST_EXPECT(*it == jv_l[it.memberName()]); env.trust(Account("bob")["USD"](0), "alice"); env.trust(Account("alice")["USD"](0), "bob"); - BEAST_EXPECT(env.le(keylet::line(Account("bob").id(), Account("alice")["USD"].issue())) == nullptr); + BEAST_EXPECT( + env.le(keylet::line(Account("bob").id(), Account("alice")["USD"].issue())) == nullptr); } void @@ -919,19 +939,22 @@ public: })", jv); - auto const jv_l = - env.le(keylet::line(Account("alice").id(), Account("bob")["USD"].issue()))->getJson(JsonOptions::none); + auto const jv_l = env.le(keylet::line(Account("alice").id(), Account("bob")["USD"].issue())) + ->getJson(JsonOptions::none); for (auto it = jv.begin(); it != jv.end(); ++it) BEAST_EXPECT(*it == jv_l[it.memberName()]); env(pay("alice", "bob", Account("alice")["USD"](50))); - BEAST_EXPECT(env.le(keylet::line(Account("alice").id(), Account("bob")["USD"].issue())) == nullptr); + BEAST_EXPECT( + env.le(keylet::line(Account("alice").id(), Account("bob")["USD"].issue())) == nullptr); } void path_find_01(bool const domainEnabled) { - testcase(std::string("Path Find: XRP -> XRP and XRP -> IOU") + (domainEnabled ? " w/ " : " w/o ") + "domain"); + testcase( + std::string("Path Find: XRP -> XRP and XRP -> IOU") + + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); Account A1{"A1"}; @@ -983,7 +1006,8 @@ public: { auto const& send_amt = XRP(10); - std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, xrpCurrency(), domainID); + std::tie(st, sa, da) = + find_paths(env, A1, A2, send_amt, std::nullopt, xrpCurrency(), domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(st.empty()); } @@ -992,14 +1016,16 @@ public: // no path should exist for this since dest account // does not exist. auto const& send_amt = XRP(200); - std::tie(st, sa, da) = find_paths(env, A1, Account{"A0"}, send_amt, std::nullopt, xrpCurrency(), domainID); + std::tie(st, sa, da) = + find_paths(env, A1, Account{"A0"}, send_amt, std::nullopt, xrpCurrency(), domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(st.empty()); } { auto const& send_amt = G3["ABC"](10); - std::tie(st, sa, da) = find_paths(env, A2, G3, send_amt, std::nullopt, xrpCurrency(), domainID); + std::tie(st, sa, da) = + find_paths(env, A2, G3, send_amt, std::nullopt, xrpCurrency(), domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, XRP(100))); BEAST_EXPECT(same(st, stpath(IPE(G3["ABC"])))); @@ -1007,7 +1033,8 @@ public: { auto const& send_amt = A2["ABC"](1); - std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, xrpCurrency(), domainID); + std::tie(st, sa, da) = + find_paths(env, A1, A2, send_amt, std::nullopt, xrpCurrency(), domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, XRP(10))); BEAST_EXPECT(same(st, stpath(IPE(G3["ABC"]), G3))); @@ -1015,7 +1042,8 @@ public: { auto const& send_amt = A3["ABC"](1); - std::tie(st, sa, da) = find_paths(env, A1, A3, send_amt, std::nullopt, xrpCurrency(), domainID); + std::tie(st, sa, da) = + find_paths(env, A1, A3, send_amt, std::nullopt, xrpCurrency(), domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, XRP(10))); BEAST_EXPECT(same(st, stpath(IPE(G3["ABC"]), G3, A2))); @@ -1025,7 +1053,9 @@ public: void path_find_02(bool const domainEnabled) { - testcase(std::string("Path Find: non-XRP -> XRP") + (domainEnabled ? " w/ " : " w/o ") + "domain"); + testcase( + std::string("Path Find: non-XRP -> XRP") + (domainEnabled ? " w/ " : " w/o ") + + "domain"); using namespace jtx; Env env = pathTestEnv(); Account A1{"A1"}; @@ -1062,7 +1092,8 @@ public: auto const& send_amt = XRP(10); { - std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, A2["ABC"].currency, domainID); + std::tie(st, sa, da) = + find_paths(env, A1, A2, send_amt, std::nullopt, A2["ABC"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["ABC"](1))); BEAST_EXPECT(same(st, stpath(G3, IPE(xrpIssue())))); @@ -1072,7 +1103,8 @@ public: // paths if (domainEnabled) { - std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, A2["ABC"].currency); + std::tie(st, sa, da) = + find_paths(env, A1, A2, send_amt, std::nullopt, A2["ABC"].currency); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(st.empty()); } @@ -1120,7 +1152,8 @@ public: { auto const& send_amt = A2["HKD"](10); - std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, A2["HKD"].currency, domainID); + std::tie(st, sa, da) = + find_paths(env, A1, A2, send_amt, std::nullopt, A2["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same(st, stpath(G1BS, M1, G2SW))); @@ -1128,7 +1161,8 @@ public: { auto const& send_amt = A1["HKD"](10); - std::tie(st, sa, da) = find_paths(env, A2, A1, send_amt, std::nullopt, A1["HKD"].currency, domainID); + std::tie(st, sa, da) = + find_paths(env, A2, A1, send_amt, std::nullopt, A1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A2["HKD"](10))); BEAST_EXPECT(same(st, stpath(G2SW, M1, G1BS))); @@ -1136,7 +1170,8 @@ public: { auto const& send_amt = A2["HKD"](10); - std::tie(st, sa, da) = find_paths(env, G1BS, A2, send_amt, std::nullopt, A1["HKD"].currency, domainID); + std::tie(st, sa, da) = + find_paths(env, G1BS, A2, send_amt, std::nullopt, A1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, G1BS["HKD"](10))); BEAST_EXPECT(same(st, stpath(M1, G2SW))); @@ -1144,7 +1179,8 @@ public: { auto const& send_amt = M1["HKD"](10); - std::tie(st, sa, da) = find_paths(env, M1, G1BS, send_amt, std::nullopt, A1["HKD"].currency, domainID); + std::tie(st, sa, da) = + find_paths(env, M1, G1BS, send_amt, std::nullopt, A1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, M1["HKD"](10))); BEAST_EXPECT(st.empty()); @@ -1152,7 +1188,8 @@ public: { auto const& send_amt = A1["HKD"](10); - std::tie(st, sa, da) = find_paths(env, G2SW, A1, send_amt, std::nullopt, A1["HKD"].currency, domainID); + std::tie(st, sa, da) = + find_paths(env, G2SW, A1, send_amt, std::nullopt, A1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, G2SW["HKD"](10))); BEAST_EXPECT(same(st, stpath(M1, G1BS))); @@ -1163,8 +1200,8 @@ public: path_find_05(bool const domainEnabled) { testcase( - std::string("Path Find: non-XRP -> non-XRP, same currency") + (domainEnabled ? " w/ " : " w/o ") + - "domain"); + std::string("Path Find: non-XRP -> non-XRP, same currency") + + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); Account A1{"A1"}; @@ -1223,7 +1260,8 @@ public: // A) Borrow or repay -- // Source -> Destination (repay source issuer) auto const& send_amt = G1["HKD"](10); - std::tie(st, sa, da) = find_paths(env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency, domainID); + std::tie(st, sa, da) = + find_paths(env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency, domainID); BEAST_EXPECT(st.empty()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); @@ -1233,7 +1271,8 @@ public: // A2) Borrow or repay -- // Source -> Destination (repay destination issuer) auto const& send_amt = A1["HKD"](10); - std::tie(st, sa, da) = find_paths(env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency, domainID); + std::tie(st, sa, da) = + find_paths(env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency, domainID); BEAST_EXPECT(st.empty()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); @@ -1243,7 +1282,8 @@ public: // B) Common gateway -- // Source -> AC -> Destination auto const& send_amt = A3["HKD"](10); - std::tie(st, sa, da) = find_paths(env, A1, A3, send_amt, std::nullopt, G1["HKD"].currency, domainID); + std::tie(st, sa, da) = + find_paths(env, A1, A3, send_amt, std::nullopt, G1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same(st, stpath(G1))); @@ -1253,18 +1293,24 @@ public: // C) Gateway to gateway -- // Source -> OB -> Destination auto const& send_amt = G2["HKD"](10); - std::tie(st, sa, da) = find_paths(env, G1, G2, send_amt, std::nullopt, G1["HKD"].currency, domainID); + std::tie(st, sa, da) = + find_paths(env, G1, G2, send_amt, std::nullopt, G1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, G1["HKD"](10))); - BEAST_EXPECT( - same(st, stpath(IPE(G2["HKD"])), stpath(M1), stpath(M2), stpath(IPE(xrpIssue()), IPE(G2["HKD"])))); + BEAST_EXPECT(same( + st, + stpath(IPE(G2["HKD"])), + stpath(M1), + stpath(M2), + stpath(IPE(xrpIssue()), IPE(G2["HKD"])))); } { // D) User to unlinked gateway via order book -- // Source -> AC -> OB -> Destination auto const& send_amt = G2["HKD"](10); - std::tie(st, sa, da) = find_paths(env, A1, G2, send_amt, std::nullopt, G1["HKD"].currency, domainID); + std::tie(st, sa, da) = + find_paths(env, A1, G2, send_amt, std::nullopt, G1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same( @@ -1280,7 +1326,8 @@ public: // Source -> AC -> OB to XRP -> OB from XRP -> AC -> // Destination auto const& send_amt = A2["HKD"](10); - std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, G1["HKD"].currency, domainID); + std::tie(st, sa, da) = + find_paths(env, A1, A2, send_amt, std::nullopt, G1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same( @@ -1296,8 +1343,8 @@ public: path_find_06(bool const domainEnabled) { testcase( - std::string("Path Find: non-XRP -> non-XRP, same currency)") + (domainEnabled ? " w/ " : " w/o ") + - "domain"); + std::string("Path Find: non-XRP -> non-XRP, same currency)") + + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); Account A1{"A1"}; @@ -1340,7 +1387,8 @@ public: auto const& send_amt = A2["HKD"](10); STPathSet st; STAmount sa, da; - std::tie(st, sa, da) = find_paths(env, G1, A2, send_amt, std::nullopt, G1["HKD"].currency, domainID); + std::tie(st, sa, da) = + find_paths(env, G1, A2, send_amt, std::nullopt, G1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, G1["HKD"](10))); BEAST_EXPECT(same(st, stpath(M1, G2), stpath(IPE(G2["HKD"]), G2))); @@ -1380,14 +1428,16 @@ public: env.close(); } - auto [st, sa, da] = find_paths(env, alice, bob, USD(-1), XRP(100).value(), std::nullopt, domainID); + auto [st, sa, da] = + find_paths(env, alice, bob, USD(-1), XRP(100).value(), std::nullopt, domainID); BEAST_EXPECT(sa == XRP(10)); BEAST_EXPECT(equal(da, USD(10))); if (BEAST_EXPECT(st.size() == 1 && st[0].size() == 1)) { auto const& pathElem = st[0][0]; BEAST_EXPECT( - pathElem.isOffer() && pathElem.getIssuerID() == gw.id() && pathElem.getCurrency() == USD.currency); + pathElem.isOffer() && pathElem.getIssuerID() == gw.id() && + pathElem.getCurrency() == USD.currency); } } { @@ -1413,7 +1463,8 @@ public: env.close(); } - auto [st, sa, da] = find_paths(env, alice, bob, drops(-1), USD(100).value(), std::nullopt, domainID); + auto [st, sa, da] = + find_paths(env, alice, bob, drops(-1), USD(100).value(), std::nullopt, domainID); BEAST_EXPECT(sa == USD(10)); BEAST_EXPECT(equal(da, XRP(10))); if (BEAST_EXPECT(st.size() == 1 && st[0].size() == 1)) @@ -1520,7 +1571,8 @@ public: env(pay(G2, M2, G2["HKD"](5000))); env.close(); - std::optional domainID = setupDomain(env, {A1, A2, A3, A4, G1, G2, G3, G4, M1, M2}); + std::optional domainID = + setupDomain(env, {A1, A2, A3, A4, G1, G2, G3, G4, M1, M2}); BEAST_EXPECT(domainID); func(env, M1, M2, G1, G2, *domainID); @@ -1533,7 +1585,13 @@ public: // Source -> Destination (repay source issuer) auto const& send_amt = G1["HKD"](10); std::tie(st, sa, da) = find_paths( - env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency, domainEnabled ? domainID : std::nullopt); + env, + A1, + G1, + send_amt, + std::nullopt, + G1["HKD"].currency, + domainEnabled ? domainID : std::nullopt); BEAST_EXPECT(st.empty()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); @@ -1544,7 +1602,13 @@ public: // Source -> Destination (repay destination issuer) auto const& send_amt = A1["HKD"](10); std::tie(st, sa, da) = find_paths( - env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency, domainEnabled ? domainID : std::nullopt); + env, + A1, + G1, + send_amt, + std::nullopt, + G1["HKD"].currency, + domainEnabled ? domainID : std::nullopt); BEAST_EXPECT(st.empty()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); @@ -1555,7 +1619,13 @@ public: // Source -> AC -> Destination auto const& send_amt = A3["HKD"](10); std::tie(st, sa, da) = find_paths( - env, A1, A3, send_amt, std::nullopt, G1["HKD"].currency, domainEnabled ? domainID : std::nullopt); + env, + A1, + A3, + send_amt, + std::nullopt, + G1["HKD"].currency, + domainEnabled ? domainID : std::nullopt); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same(st, stpath(G1))); @@ -1566,11 +1636,21 @@ public: // Source -> OB -> Destination auto const& send_amt = G2["HKD"](10); std::tie(st, sa, da) = find_paths( - env, G1, G2, send_amt, std::nullopt, G1["HKD"].currency, domainEnabled ? domainID : std::nullopt); + env, + G1, + G2, + send_amt, + std::nullopt, + G1["HKD"].currency, + domainEnabled ? domainID : std::nullopt); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, G1["HKD"](10))); - BEAST_EXPECT( - same(st, stpath(IPE(G2["HKD"])), stpath(M1), stpath(M2), stpath(IPE(xrpIssue()), IPE(G2["HKD"])))); + BEAST_EXPECT(same( + st, + stpath(IPE(G2["HKD"])), + stpath(M1), + stpath(M2), + stpath(IPE(xrpIssue()), IPE(G2["HKD"])))); } { @@ -1578,7 +1658,13 @@ public: // Source -> AC -> OB -> Destination auto const& send_amt = G2["HKD"](10); std::tie(st, sa, da) = find_paths( - env, A1, G2, send_amt, std::nullopt, G1["HKD"].currency, domainEnabled ? domainID : std::nullopt); + env, + A1, + G2, + send_amt, + std::nullopt, + G1["HKD"].currency, + domainEnabled ? domainID : std::nullopt); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same( @@ -1595,7 +1681,13 @@ public: // Destination auto const& send_amt = A2["HKD"](10); std::tie(st, sa, da) = find_paths( - env, A1, A2, send_amt, std::nullopt, G1["HKD"].currency, domainEnabled ? domainID : std::nullopt); + env, + A1, + A2, + send_amt, + std::nullopt, + G1["HKD"].currency, + domainEnabled ? domainID : std::nullopt); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same( @@ -1611,35 +1703,58 @@ public: // offers to make sure that hybrid offers work in pathfinding for open // order book { - testPathfind([](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { - env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); - env(offer(M2, XRP(10000), G2["HKD"](1000))); - env(offer(M2, G1["HKD"](1000), XRP(10000))); - }); + testPathfind( + [](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { + env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), + domain(domainID), + txflags(tfHybrid)); + env(offer(M2, XRP(10000), G2["HKD"](1000))); + env(offer(M2, G1["HKD"](1000), XRP(10000))); + }); - testPathfind([](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { - env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); - env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); - env(offer(M2, G1["HKD"](1000), XRP(10000))); - }); + testPathfind( + [](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { + env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), + domain(domainID), + txflags(tfHybrid)); + env(offer(M2, XRP(10000), G2["HKD"](1000)), + domain(domainID), + txflags(tfHybrid)); + env(offer(M2, G1["HKD"](1000), XRP(10000))); + }); - testPathfind([](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { - env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); - env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); - env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(domainID), txflags(tfHybrid)); - }); + testPathfind( + [](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { + env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), + domain(domainID), + txflags(tfHybrid)); + env(offer(M2, XRP(10000), G2["HKD"](1000)), + domain(domainID), + txflags(tfHybrid)); + env(offer(M2, G1["HKD"](1000), XRP(10000)), + domain(domainID), + txflags(tfHybrid)); + }); - testPathfind([](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { - env(offer(M1, G1["HKD"](1000), G2["HKD"](1000))); - env(offer(M2, XRP(10000), G2["HKD"](1000))); - env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(domainID), txflags(tfHybrid)); - }); + testPathfind( + [](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { + env(offer(M1, G1["HKD"](1000), G2["HKD"](1000))); + env(offer(M2, XRP(10000), G2["HKD"](1000))); + env(offer(M2, G1["HKD"](1000), XRP(10000)), + domain(domainID), + txflags(tfHybrid)); + }); - testPathfind([](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { - env(offer(M1, G1["HKD"](1000), G2["HKD"](1000))); - env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); - env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(domainID), txflags(tfHybrid)); - }); + testPathfind( + [](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { + env(offer(M1, G1["HKD"](1000), G2["HKD"](1000))); + env(offer(M2, XRP(10000), G2["HKD"](1000)), + domain(domainID), + txflags(tfHybrid)); + env(offer(M2, G1["HKD"](1000), XRP(10000)), + domain(domainID), + txflags(tfHybrid)); + }); } // the following tests exercise different combinations of domain/hybrid @@ -1648,7 +1763,9 @@ public: { testPathfind( [](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { - env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); + env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), + domain(domainID), + txflags(tfHybrid)); env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(domainID)); env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(domainID)); }, @@ -1656,8 +1773,12 @@ public: testPathfind( [](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { - env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); - env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); + env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), + domain(domainID), + txflags(tfHybrid)); + env(offer(M2, XRP(10000), G2["HKD"](1000)), + domain(domainID), + txflags(tfHybrid)); env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(domainID)); }, true); @@ -1666,15 +1787,21 @@ public: [](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(domainID)); env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(domainID)); - env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(domainID), txflags(tfHybrid)); + env(offer(M2, G1["HKD"](1000), XRP(10000)), + domain(domainID), + txflags(tfHybrid)); }, true); testPathfind( [](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(domainID)); - env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); - env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(domainID), txflags(tfHybrid)); + env(offer(M2, XRP(10000), G2["HKD"](1000)), + domain(domainID), + txflags(tfHybrid)); + env(offer(M2, G1["HKD"](1000), XRP(10000)), + domain(domainID), + txflags(tfHybrid)); }, true); } @@ -1696,7 +1823,8 @@ public: auto const& send_amt = XRP(1); // doing pathfind with domain won't include amm - std::tie(st, sa, da) = find_paths(env, bob, carol, send_amt, std::nullopt, USD.currency, domainID); + std::tie(st, sa, da) = + find_paths(env, bob, carol, send_amt, std::nullopt, USD.currency, domainID); BEAST_EXPECT(st.empty()); // a non-domain pathfind returns amm in the path diff --git a/src/test/app/PayChan_test.cpp b/src/test/app/PayChan_test.cpp index 019dd42ca1..b217bb3687 100644 --- a/src/test/app/PayChan_test.cpp +++ b/src/test/app/PayChan_test.cpp @@ -25,7 +25,11 @@ struct PayChan_test : public beast::unit_test::suite } static Buffer - signClaimAuth(PublicKey const& pk, SecretKey const& sk, uint256 const& channel, STAmount const& authAmt) + signClaimAuth( + PublicKey const& pk, + SecretKey const& sk, + uint256 const& channel, + STAmount const& authAmt) { Serializer msg; serializePayChanAuthorization(msg, channel, authAmt.xrp()); @@ -96,7 +100,8 @@ struct PayChan_test : public beast::unit_test::suite env(create(alice, alice, XRP(1000), settleDelay, pk), ter(temDST_IS_SRC)); // invalid channel - env(fund(alice, channel(alice, "noAccount", env.seq(alice) - 1), XRP(1000)), ter(tecNO_ENTRY)); + env(fund(alice, channel(alice, "noAccount", env.seq(alice) - 1), XRP(1000)), + ter(tecNO_ENTRY)); // not enough funds env(create(alice, bob, XRP(10000), settleDelay, pk), ter(tecUNFUNDED)); @@ -150,7 +155,8 @@ struct PayChan_test : public beast::unit_test::suite // claim again preBob = env.balance(bob); - env(claim(bob, chan, reqBal, authAmt, Slice(sig), alice.pk()), ter(tecUNFUNDED_PAYMENT)); + env(claim(bob, chan, reqBal, authAmt, Slice(sig), alice.pk()), + ter(tecUNFUNDED_PAYMENT)); BEAST_EXPECT(channelBalance(*env.current(), chan) == chanBal); BEAST_EXPECT(channelAmount(*env.current(), chan) == chanAmt); BEAST_EXPECT(env.balance(bob) == preBob - feeDrops); @@ -176,14 +182,16 @@ struct PayChan_test : public beast::unit_test::suite { // Wrong signing key auto const sig = signClaimAuth(bob.pk(), bob.sk(), chan, XRP(1500)); - env(claim(bob, chan, XRP(1500).value(), XRP(1500).value(), Slice(sig), bob.pk()), ter(temBAD_SIGNER)); + env(claim(bob, chan, XRP(1500).value(), XRP(1500).value(), Slice(sig), bob.pk()), + ter(temBAD_SIGNER)); BEAST_EXPECT(channelBalance(*env.current(), chan) == chanBal); BEAST_EXPECT(channelAmount(*env.current(), chan) == chanAmt); } { // Bad signature auto const sig = signClaimAuth(bob.pk(), bob.sk(), chan, XRP(1500)); - env(claim(bob, chan, XRP(1500).value(), XRP(1500).value(), Slice(sig), alice.pk()), ter(temBAD_SIGNATURE)); + env(claim(bob, chan, XRP(1500).value(), XRP(1500).value(), Slice(sig), alice.pk()), + ter(temBAD_SIGNATURE)); BEAST_EXPECT(channelBalance(*env.current(), chan) == chanBal); BEAST_EXPECT(channelAmount(*env.current(), chan) == chanAmt); } @@ -283,7 +291,8 @@ struct PayChan_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob); auto const pk = alice.pk(); auto const settleDelay = 100s; - NetClock::time_point const cancelAfter = env.current()->header().parentCloseTime + 3600s; + NetClock::time_point const cancelAfter = + env.current()->header().parentCloseTime + 3600s; auto const channelFunds = XRP(1000); auto const chan = channel(alice, bob, env.seq(alice)); env(create(alice, bob, channelFunds, settleDelay, pk, cancelAfter)); @@ -313,7 +322,8 @@ struct PayChan_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob, carol); auto const pk = alice.pk(); auto const settleDelay = 100s; - NetClock::time_point const cancelAfter = env.current()->header().parentCloseTime + 3600s; + NetClock::time_point const cancelAfter = + env.current()->header().parentCloseTime + 3600s; auto const channelFunds = XRP(1000); auto const chan = channel(alice, bob, env.seq(alice)); env(create(alice, bob, channelFunds, settleDelay, pk, cancelAfter)); @@ -341,7 +351,8 @@ struct PayChan_test : public beast::unit_test::suite auto const pk = alice.pk(); auto const settleDelay = 100s; auto const channelFunds = XRP(1000); - NetClock::time_point const cancelAfter = env.current()->header().parentCloseTime - 1s; + NetClock::time_point const cancelAfter = + env.current()->header().parentCloseTime - 1s; auto const txResult = withFixPayChan ? ter(tecEXPIRED) : ter(tesSUCCESS); env(create(alice, bob, channelFunds, settleDelay, pk, cancelAfter), txResult); } @@ -360,7 +371,8 @@ struct PayChan_test : public beast::unit_test::suite auto const settleDelay = 100s; auto const channelFunds = XRP(1000); NetClock::time_point const cancelAfter = env.current()->header().parentCloseTime; - env(create(alice, bob, channelFunds, settleDelay, pk, cancelAfter), ter(tesSUCCESS)); + env(create(alice, bob, channelFunds, settleDelay, pk, cancelAfter), + ter(tesSUCCESS)); } } } @@ -397,14 +409,16 @@ struct PayChan_test : public beast::unit_test::suite env(fund(alice, chan, XRP(1), NetClock::time_point{minExpiration + 50s})); BEAST_EXPECT(*channelExpiration(*env.current(), chan) == counts(minExpiration) + 50); // decrease the expiration below minExpiration - env(fund(alice, chan, XRP(1), NetClock::time_point{minExpiration - 50s}), ter(temBAD_EXPIRATION)); + env(fund(alice, chan, XRP(1), NetClock::time_point{minExpiration - 50s}), + ter(temBAD_EXPIRATION)); BEAST_EXPECT(*channelExpiration(*env.current(), chan) == counts(minExpiration) + 50); env(claim(bob, chan), txflags(tfRenew), ter(tecNO_PERMISSION)); BEAST_EXPECT(*channelExpiration(*env.current(), chan) == counts(minExpiration) + 50); env(claim(alice, chan), txflags(tfRenew)); BEAST_EXPECT(!channelExpiration(*env.current(), chan)); // decrease the expiration below minExpiration - env(fund(alice, chan, XRP(1), NetClock::time_point{minExpiration - 50s}), ter(temBAD_EXPIRATION)); + env(fund(alice, chan, XRP(1), NetClock::time_point{minExpiration - 50s}), + ter(temBAD_EXPIRATION)); BEAST_EXPECT(!channelExpiration(*env.current(), chan)); env(fund(alice, chan, XRP(1), NetClock::time_point{minExpiration})); env.close(minExpiration); @@ -425,7 +439,8 @@ struct PayChan_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob); auto const pk = alice.pk(); auto const settleDelay = 3600s; - NetClock::time_point const settleTimepoint = env.current()->header().parentCloseTime + settleDelay; + NetClock::time_point const settleTimepoint = + env.current()->header().parentCloseTime + settleDelay; auto const channelFunds = XRP(1000); auto const chan = channel(alice, bob, env.seq(alice)); env(create(alice, bob, channelFunds, settleDelay, pk)); @@ -776,7 +791,8 @@ struct PayChan_test : public beast::unit_test::suite { // create credentials auto jv = credentials::create(alice, carol, credType); - uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count() + 100; + uint32_t const t = + env.current()->header().parentCloseTime.time_since_epoch().count() + 100; jv[sfExpiration.jsonName] = t; env(jv); env.close(); @@ -790,14 +806,18 @@ struct PayChan_test : public beast::unit_test::suite env.close(); // Fail, credentials not accepted - env(claim(alice, chan, delta, delta), credentials::ids({credIdx}), ter(tecBAD_CREDENTIALS)); + env(claim(alice, chan, delta, delta), + credentials::ids({credIdx}), + ter(tecBAD_CREDENTIALS)); env.close(); env(credentials::accept(alice, carol, credType)); env.close(); // Fail, no depositPreauth object - env(claim(alice, chan, delta, delta), credentials::ids({credIdx}), ter(tecNO_PERMISSION)); + env(claim(alice, chan, delta, delta), + credentials::ids({credIdx}), + ter(tecNO_PERMISSION)); env.close(); // Setup deposit authorization @@ -805,13 +825,17 @@ struct PayChan_test : public beast::unit_test::suite env.close(); // Fail, credentials doesn’t belong to root account - env(claim(dillon, chan, delta, delta), credentials::ids({credIdx}), ter(tecBAD_CREDENTIALS)); + env(claim(dillon, chan, delta, delta), + credentials::ids({credIdx}), + ter(tecBAD_CREDENTIALS)); // Fails because bob's lsfDepositAuth flag is set. env(claim(alice, chan, delta, delta), ter(tecNO_PERMISSION)); // Fail, bad credentials index. - env(claim(alice, chan, delta, delta), credentials::ids({credBadIdx}), ter(tecBAD_CREDENTIALS)); + env(claim(alice, chan, delta, delta), + credentials::ids({credBadIdx}), + ter(tecBAD_CREDENTIALS)); // Fail, empty credentials env(claim(alice, chan, delta, delta), credentials::ids({}), ter(temMALFORMED)); @@ -896,7 +920,9 @@ struct PayChan_test : public beast::unit_test::suite env(deposit::auth(bob, alice)); env.close(); - env(claim(alice, chan, XRP(500).value(), XRP(500).value()), credentials::ids({credIdx}), ter(temDISABLED)); + env(claim(alice, chan, XRP(500).value(), XRP(500).value()), + credentials::ids({credIdx}), + ter(temDISABLED)); } } @@ -1165,7 +1191,8 @@ struct PayChan_test : public beast::unit_test::suite forAllApiVersions([&, this](unsigned apiVersion) { testcase("PayChan Channel_Auth RPC Api " + std::to_string(apiVersion)); args[jss::api_version] = apiVersion; - auto const rs = env.rpc("json", "channel_authorize", args.toStyledString())[jss::result]; + auto const rs = + env.rpc("json", "channel_authorize", args.toStyledString())[jss::result]; auto const error = apiVersion < 2u ? "invalidParams" : "badKeyType"; BEAST_EXPECT(rs[jss::error] == error); }); @@ -1566,7 +1593,9 @@ struct PayChan_test : public beast::unit_test::suite auto const settleDelay = 100s; auto const pk = alice.pk(); - auto inOwnerDir = [](ReadView const& view, Account const& acc, std::shared_ptr const& chan) -> bool { + auto inOwnerDir = [](ReadView const& view, + Account const& acc, + std::shared_ptr const& chan) -> bool { xrpl::Dir const ownerDir(view, keylet::ownerDir(acc.id())); return std::find(ownerDir.begin(), ownerDir.end(), chan) != ownerDir.end(); }; @@ -1625,17 +1654,23 @@ struct PayChan_test : public beast::unit_test::suite testcase("Account Delete"); using namespace test::jtx; using namespace std::literals::chrono_literals; - auto rmAccount = [this](Env& env, Account const& toRm, Account const& dst, TER expectedTer = tesSUCCESS) { - // only allow an account to be deleted if the account's sequence - // number is at least 256 less than the current ledger sequence - for (auto minRmSeq = env.seq(toRm) + 257; env.current()->seq() < minRmSeq; env.close()) - { - } + auto rmAccount = + [this]( + Env& env, Account const& toRm, Account const& dst, TER expectedTer = tesSUCCESS) { + // only allow an account to be deleted if the account's sequence + // number is at least 256 less than the current ledger sequence + for (auto minRmSeq = env.seq(toRm) + 257; env.current()->seq() < minRmSeq; + env.close()) + { + } - env(acctdelete(toRm, dst), fee(drops(env.current()->fees().increment)), ter(expectedTer)); - env.close(); - this->BEAST_EXPECT(isTesSuccess(expectedTer) == !env.closed()->exists(keylet::account(toRm.id()))); - }; + env(acctdelete(toRm, dst), + fee(drops(env.current()->fees().increment)), + ter(expectedTer)); + env.close(); + this->BEAST_EXPECT( + isTesSuccess(expectedTer) == !env.closed()->exists(keylet::account(toRm.id()))); + }; auto const alice = Account("alice"); auto const bob = Account("bob"); @@ -1775,7 +1810,8 @@ struct PayChan_test : public beast::unit_test::suite auto const authAmt = reqBal + XRP(100); assert(reqBal <= chanAmt); auto const sig = signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); - env(claim(bob, chan, reqBal, authAmt, Slice(sig), alice.pk()), ticket::use(bobTicketSeq++)); + env(claim(bob, chan, reqBal, authAmt, Slice(sig), alice.pk()), + ticket::use(bobTicketSeq++)); env.require(tickets(bob, env.seq(bob) - bobTicketSeq)); BEAST_EXPECT(env.seq(bob) == bobSeq); diff --git a/src/test/app/PayStrand_test.cpp b/src/test/app/PayStrand_test.cpp index 9b534d9284..2cc2a188c3 100644 --- a/src/test/app/PayStrand_test.cpp +++ b/src/test/app/PayStrand_test.cpp @@ -1,9 +1,6 @@ #include #include -#include -#include -#include #include #include @@ -11,6 +8,9 @@ #include #include #include +#include +#include +#include #include @@ -53,7 +53,12 @@ trustFlag(TrustFlag f, bool useHigh) } bool -getTrustFlag(jtx::Env const& env, jtx::Account const& src, jtx::Account const& dst, Currency const& cur, TrustFlag flag) +getTrustFlag( + jtx::Env const& env, + jtx::Account const& src, + jtx::Account const& dst, + Currency const& cur, + TrustFlag flag) { if (auto sle = env.le(keylet::line(src, dst, cur))) { @@ -127,7 +132,10 @@ STPathElement ipe(Issue const& iss) { return STPathElement( - STPathElement::typeCurrency | STPathElement::typeIssuer, xrpAccount(), iss.currency, iss.account); + STPathElement::typeCurrency | STPathElement::typeIssuer, + xrpAccount(), + iss.currency, + iss.account); }; // Issuer path element @@ -201,8 +209,10 @@ public: { return (allowCompound_ || !(has(SB::acc) && hasAny({SB::cur, SB::iss}))) && (!hasAny({SB::prevAcc, SB::prevCur, SB::prevIss}) || prev_) && - (!hasAny({SB::rootAcc, SB::sameAccIss, SB::existingAcc, SB::prevAcc}) || has(SB::acc)) && - (!hasAny({SB::rootIss, SB::sameAccIss, SB::existingIss, SB::prevIss}) || has(SB::iss)) && + (!hasAny({SB::rootAcc, SB::sameAccIss, SB::existingAcc, SB::prevAcc}) || + has(SB::acc)) && + (!hasAny({SB::rootIss, SB::sameAccIss, SB::existingIss, SB::prevIss}) || + has(SB::iss)) && (!hasAny({SB::xrp, SB::existingCur, SB::prevCur}) || has(SB::cur)) && // These will be duplicates (count({SB::xrp, SB::existingCur, SB::prevCur}) <= 1) && @@ -535,14 +545,16 @@ struct ExistingElementPool { StateGuard og{*this}; outerResult = prefix; - outer.emplace_into(outerResult, accF, issF, currencyF, existingAcc, existingCur, existingIss); + outer.emplace_into( + outerResult, accF, issF, currencyF, existingAcc, existingCur, existingIss); STPathElement const* prevInner = &outerResult.back(); ElementComboIter inner(prevInner); while (inner.next()) { StateGuard ig{*this}; result = outerResult; - inner.emplace_into(result, accF, issF, currencyF, existingAcc, existingCur, existingIss); + inner.emplace_into( + result, accF, issF, currencyF, existingAcc, existingCur, existingIss); result.insert(result.end(), suffix.begin(), suffix.end()); f(sendMax, deliver, result); } @@ -659,7 +671,8 @@ struct PayStrand_test : public beast::unit_test::suite env(pay(gw, carol, USD(100))); // Insert implied account - test(env, USD, std::nullopt, STPath(), tesSUCCESS, D{alice, gw, usdC}, D{gw, bob, usdC}); + test( + env, USD, std::nullopt, STPath(), tesSUCCESS, D{alice, gw, usdC}, D{gw, bob, usdC}); env.trust(EUR(1000), alice, bob); // Insert implied offer @@ -712,7 +725,8 @@ struct PayStrand_test : public beast::unit_test::suite env, xrpIssue(), USD.issue(), - STPath({STPathElement{STPathElement::typeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()}}), + STPath({STPathElement{ + STPathElement::typeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()}}), tesSUCCESS, D{alice, gw, usdC}, B{USD, XRP, std::nullopt}, @@ -936,7 +950,8 @@ struct PayStrand_test : public beast::unit_test::suite std::nullopt, env.app().logs().journal("Flow")); BEAST_EXPECT(ter == tesSUCCESS); - BEAST_EXPECT(equal(strand, D{alice, gw, usdC}, B{USD.issue(), xrpIssue(), std::nullopt}, XRPS{bob})); + BEAST_EXPECT(equal( + strand, D{alice, gw, usdC}, B{USD.issue(), xrpIssue(), std::nullopt}, XRPS{bob})); } } @@ -996,7 +1011,10 @@ struct PayStrand_test : public beast::unit_test::suite env(offer(bob, USD(100), XRP(100)), txflags(tfPassive)); // payment path: XRP -> XRP/USD -> USD/XRP - env(pay(alice, carol, XRP(100)), path(~USD, ~XRP), txflags(tfNoRippleDirect), ter(temBAD_SEND_XRP_PATHS)); + env(pay(alice, carol, XRP(100)), + path(~USD, ~XRP), + txflags(tfNoRippleDirect), + ter(temBAD_SEND_XRP_PATHS)); } { @@ -1104,22 +1122,54 @@ struct PayStrand_test : public beast::unit_test::suite PaymentSandbox sb{env.current().get(), tapNONE}; { auto const r = ::xrpl::path::RippleCalc::rippleCalculate( - sb, sendMax, deliver, dstAcc, noAccount(), pathSet, std::nullopt, env.app().logs(), &inputs); + sb, + sendMax, + deliver, + dstAcc, + noAccount(), + pathSet, + std::nullopt, + env.app().logs(), + &inputs); BEAST_EXPECT(r.result() == temBAD_PATH); } { auto const r = ::xrpl::path::RippleCalc::rippleCalculate( - sb, sendMax, deliver, noAccount(), srcAcc, pathSet, std::nullopt, env.app().logs(), &inputs); + sb, + sendMax, + deliver, + noAccount(), + srcAcc, + pathSet, + std::nullopt, + env.app().logs(), + &inputs); BEAST_EXPECT(r.result() == temBAD_PATH); } { auto const r = ::xrpl::path::RippleCalc::rippleCalculate( - sb, noAccountAmount, deliver, dstAcc, srcAcc, pathSet, std::nullopt, env.app().logs(), &inputs); + sb, + noAccountAmount, + deliver, + dstAcc, + srcAcc, + pathSet, + std::nullopt, + env.app().logs(), + &inputs); BEAST_EXPECT(r.result() == temBAD_PATH); } { auto const r = ::xrpl::path::RippleCalc::rippleCalculate( - sb, sendMax, noAccountAmount, dstAcc, srcAcc, pathSet, std::nullopt, env.app().logs(), &inputs); + sb, + sendMax, + noAccountAmount, + dstAcc, + srcAcc, + pathSet, + std::nullopt, + env.app().logs(), + &inputs); BEAST_EXPECT(r.result() == temBAD_PATH); } } diff --git a/src/test/app/PermissionedDEX_test.cpp b/src/test/app/PermissionedDEX_test.cpp index 7a55866780..8ecc66911c 100644 --- a/src/test/app/PermissionedDEX_test.cpp +++ b/src/test/app/PermissionedDEX_test.cpp @@ -2,8 +2,6 @@ #include #include -#include - #include #include #include @@ -18,6 +16,7 @@ #include #include #include +#include #include #include @@ -84,7 +83,10 @@ class PermissionedDEX_test : public beast::unit_test::suite return false; if (!domainOffer && sle->isFieldPresent(sfDomainID)) return false; - if (!offerInDir(sle->getFieldH256(sfBookDirectory), sle->getFieldU64(sfBookNode), (*sle)[~sfDomainID])) + if (!offerInDir( + sle->getFieldH256(sfBookDirectory), + sle->getFieldU64(sfBookNode), + (*sle)[~sfDomainID])) return false; if (sle->isFlag(lsfHybrid)) @@ -161,7 +163,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // test preflight { Env env(*this, features - featurePermissionedDEX); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); env(offer(bob, XRP(10), USD(10)), domain(domainID), ter(temDISABLED)); env.close(); @@ -175,7 +178,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // preclaim - someone outside of the domain cannot create domain offer { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); // create devin account who is not part of the domain Account devin("devin"); @@ -207,7 +211,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // preclaim - someone with expired cred cannot create domain offer { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); // create devin account who is not part of the domain Account devin("devin"); @@ -241,7 +246,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // preclaim - cannot create an offer in a non existent domain { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); uint256 const badDomain{ "F10D0CC9A0F9A3CBF585B80BE09A186483668FDBDD39AA7E3370F3649CE134" "E5"}; @@ -254,7 +260,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // domain { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); env(credentials::deleteCred(domainOwner, gw, domainOwner, credType)); env.close(); @@ -270,7 +277,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // domain { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); env(credentials::deleteCred(domainOwner, gw, domainOwner, credType)); env.close(); @@ -285,7 +293,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // apply - two domain offers cross with each other { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); auto const bobOfferSeq{env.seq(bob)}; env(offer(bob, XRP(10), USD(10)), domain(domainID)); @@ -312,7 +321,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // apply - create lots of domain offers { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); std::vector offerSeqs; offerSeqs.reserve(100); @@ -344,9 +354,14 @@ class PermissionedDEX_test : public beast::unit_test::suite // test preflight - without enabling featurePermissionedDEX amendment { Env env(*this, features - featurePermissionedDEX); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); - env(pay(bob, alice, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID), ter(temDISABLED)); + env(pay(bob, alice, USD(10)), + path(~USD), + sendmax(XRP(10)), + domain(domainID), + ter(temDISABLED)); env.close(); env.enableFeature(featurePermissionedDEX); @@ -362,19 +377,25 @@ class PermissionedDEX_test : public beast::unit_test::suite // preclaim - cannot send payment with non existent domain { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); uint256 const badDomain{ "F10D0CC9A0F9A3CBF585B80BE09A186483668FDBDD39AA7E3370F3649CE134" "E5"}; - env(pay(bob, alice, USD(10)), path(~USD), sendmax(XRP(10)), domain(badDomain), ter(tecNO_PERMISSION)); + env(pay(bob, alice, USD(10)), + path(~USD), + sendmax(XRP(10)), + domain(badDomain), + ter(tecNO_PERMISSION)); env.close(); } // preclaim - payment with non-domain destination fails { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); @@ -389,7 +410,11 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // devin is not part of domain - env(pay(alice, devin, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID), ter(tecNO_PERMISSION)); + env(pay(alice, devin, USD(10)), + path(~USD), + sendmax(XRP(10)), + domain(domainID), + ter(tecNO_PERMISSION)); env.close(); // domain owner also issues a credential for devin @@ -397,7 +422,11 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // devin has not yet accepted cred - env(pay(alice, devin, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID), ter(tecNO_PERMISSION)); + env(pay(alice, devin, USD(10)), + path(~USD), + sendmax(XRP(10)), + domain(domainID), + ter(tecNO_PERMISSION)); env.close(); env(credentials::accept(devin, domainOwner, credType)); @@ -411,7 +440,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // preclaim - non-domain sender cannot send payment { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); @@ -426,7 +456,11 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // devin tries to send domain payment - env(pay(devin, alice, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID), ter(tecNO_PERMISSION)); + env(pay(devin, alice, USD(10)), + path(~USD), + sendmax(XRP(10)), + domain(domainID), + ter(tecNO_PERMISSION)); env.close(); // domain owner also issues a credential for devin @@ -434,7 +468,11 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // devin has not yet accepted cred - env(pay(devin, alice, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID), ter(tecNO_PERMISSION)); + env(pay(devin, alice, USD(10)), + path(~USD), + sendmax(XRP(10)), + domain(domainID), + ter(tecNO_PERMISSION)); env.close(); env(credentials::accept(devin, domainOwner, credType)); @@ -448,7 +486,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // apply - domain owner can always send and receive domain payment { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); @@ -474,7 +513,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // test domain cross currency payment consuming one offer { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); // create a regular offer without domain auto const regularOfferSeq{env.seq(bob)}; @@ -487,7 +527,11 @@ class PermissionedDEX_test : public beast::unit_test::suite BEAST_EXPECT(checkDirectorySize(env, *regularDirKey, 1)); // a domain payment cannot consume regular offers - env(pay(alice, carol, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID), ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(10)), + path(~USD), + sendmax(XRP(10)), + domain(domainID), + ter(tecPATH_PARTIAL)); env.close(); // create a domain offer @@ -516,7 +560,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // test domain payment consuming two offers in the path { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); auto const EUR = gw["EUR"]; env.trust(EUR(1000), alice); @@ -536,7 +581,11 @@ class PermissionedDEX_test : public beast::unit_test::suite BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); // payment fail because there isn't eur offer - env(pay(alice, carol, EUR(10)), path(~USD, ~EUR), sendmax(XRP(10)), domain(domainID), ter(tecPATH_PARTIAL)); + env(pay(alice, carol, EUR(10)), + path(~USD, ~EUR), + sendmax(XRP(10)), + domain(domainID), + ter(tecPATH_PARTIAL)); env.close(); BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); @@ -548,7 +597,11 @@ class PermissionedDEX_test : public beast::unit_test::suite // alice tries to pay again, but still fails because the regular // offer cannot be consumed - env(pay(alice, carol, EUR(10)), path(~USD, ~EUR), sendmax(XRP(10)), domain(domainID), ter(tecPATH_PARTIAL)); + env(pay(alice, carol, EUR(10)), + path(~USD, ~EUR), + sendmax(XRP(10)), + domain(domainID), + ter(tecPATH_PARTIAL)); env.close(); // bob creates a domain USD/EUR offer @@ -579,7 +632,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // domain payment cannot consume offer from another domain { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); // Fund devin and create USD trustline Account badDomainOwner("badDomainOwner"); @@ -607,7 +661,11 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // domain payment can't consume an offer from another domain - env(pay(alice, carol, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID), ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(10)), + path(~USD), + sendmax(XRP(10)), + domain(domainID), + ter(tecPATH_PARTIAL)); env.close(); // bob creates an offer under the right domain @@ -628,7 +686,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // offer { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); @@ -653,7 +712,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // offer becomes unfunded when offer owner's cred expires { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); // create devin account who is not part of the domain Account devin("devin"); @@ -686,7 +746,11 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(std::chrono::seconds(20)); // devin's offer is unfunded now due to expired cred - env(pay(alice, carol, USD(5)), path(~USD), sendmax(XRP(5)), domain(domainID), ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(5)), + path(~USD), + sendmax(XRP(5)), + domain(domainID), + ter(tecPATH_PARTIAL)); env.close(); BEAST_EXPECT(checkOffer(env, devin, offerSeq, XRP(5), USD(5), 0, true)); } @@ -694,7 +758,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // offer becomes unfunded when offer owner's cred is removed { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); auto const offerSeq{env.seq(bob)}; env(offer(bob, XRP(10), USD(10)), domain(domainID)); @@ -710,7 +775,11 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // bob's offer is unfunded now due to expired cred - env(pay(alice, carol, USD(5)), path(~USD), sendmax(XRP(5)), domain(domainID), ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(5)), + path(~USD), + sendmax(XRP(5)), + domain(domainID), + ter(tecPATH_PARTIAL)); env.close(); BEAST_EXPECT(checkOffer(env, bob, offerSeq, XRP(5), USD(5), 0, true)); } @@ -725,7 +794,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // payment. If the domain wishes to control who is allowed to ripple // through, they should set the rippling individually Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); auto const EURA = alice["EUR"]; auto const EURB = bob["EUR"]; @@ -762,7 +832,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // whether the issuer is in the domain should NOT affect whether an // offer can be consumed in domain payment Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); // create an xrp/usd offer with usd as takergets auto const bobOffer1Seq{env.seq(bob)}; @@ -802,7 +873,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // checking that an unfunded offer will be implicitly removed by a // successful payment tx Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); auto const aliceOfferSeq{env.seq(alice)}; env(offer(alice, XRP(100), USD(100)), domain(domainID)); @@ -839,11 +911,16 @@ class PermissionedDEX_test : public beast::unit_test::suite testcase("AMM not used"); Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); AMM amm(env, alice, XRP(10), USD(50)); // a domain payment isn't able to consume AMM - env(pay(bob, carol, USD(5)), path(~USD), sendmax(XRP(5)), domain(domainID), ter(tecPATH_PARTIAL)); + env(pay(bob, carol, USD(5)), + path(~USD), + sendmax(XRP(5)), + domain(domainID), + ter(tecPATH_PARTIAL)); env.close(); // a non domain payment can use AMM @@ -863,9 +940,13 @@ class PermissionedDEX_test : public beast::unit_test::suite // test preflight - invalid hybrid flag { Env env(*this, features - featurePermissionedDEX); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); - env(offer(bob, XRP(10), USD(10)), domain(domainID), txflags(tfHybrid), ter(temDISABLED)); + env(offer(bob, XRP(10), USD(10)), + domain(domainID), + txflags(tfHybrid), + ter(temDISABLED)); env.close(); env(offer(bob, XRP(10), USD(10)), txflags(tfHybrid), ter(temINVALID_FLAG)); @@ -888,7 +969,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // apply - domain offer can cross with hybrid { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); auto const bobOfferSeq{env.seq(bob)}; env(offer(bob, XRP(10), USD(10)), txflags(tfHybrid), domain(domainID)); @@ -910,7 +992,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // apply - open offer can cross with hybrid { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); auto const bobOfferSeq{env.seq(bob)}; env(offer(bob, XRP(10), USD(10)), txflags(tfHybrid), domain(domainID)); @@ -933,7 +1016,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // domain book { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); auto const bobOfferSeq{env.seq(bob)}; env(offer(bob, XRP(10), USD(10)), domain(domainID)); @@ -956,7 +1040,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // because by default, it only tries to cross domain offers { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); auto const bobOfferSeq{env.seq(bob)}; env(offer(bob, XRP(10), USD(10))); @@ -987,7 +1072,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // in this case, the hybrid offer will be considered as unfunded even in // a regular payment Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); auto const hybridOfferSeq{env.seq(bob)}; env(offer(bob, XRP(50), USD(50)), txflags(tfHybrid), domain(domainID)); @@ -999,7 +1085,11 @@ class PermissionedDEX_test : public beast::unit_test::suite // bob's hybrid offer is unfunded and can not be consumed in a domain // payment - env(pay(alice, carol, USD(5)), path(~USD), sendmax(XRP(5)), domain(domainID), ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(5)), + path(~USD), + sendmax(XRP(5)), + domain(domainID), + ter(tecPATH_PARTIAL)); env.close(); BEAST_EXPECT(checkOffer(env, bob, hybridOfferSeq, XRP(50), USD(50), lsfHybrid, true)); @@ -1018,7 +1108,8 @@ class PermissionedDEX_test : public beast::unit_test::suite auto const sleHybridOffer = env.le(keylet::offer(bob.id(), hybridOfferSeq)); BEAST_EXPECT(sleHybridOffer); - auto const openDir = sleHybridOffer->getFieldArray(sfAdditionalBooks)[0].getFieldH256(sfBookDirectory); + auto const openDir = + sleHybridOffer->getFieldArray(sfAdditionalBooks)[0].getFieldH256(sfBookDirectory); BEAST_EXPECT(checkDirectorySize(env, openDir, 2)); // this normal payment should consume the regular offer and remove the @@ -1039,7 +1130,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // both non domain and domain payments can consume hybrid offer { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); auto const hybridOfferSeq{env.seq(bob)}; env(offer(bob, XRP(10), USD(10)), txflags(tfHybrid), domain(domainID)); @@ -1060,7 +1152,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // wrong domainID { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); // Fund accounts Account badDomainOwner("badDomainOwner"); @@ -1085,7 +1178,11 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // other domains can't consume the offer - env(pay(devin, badDomainOwner, USD(5)), path(~USD), sendmax(XRP(5)), domain(badDomainID), ter(tecPATH_DRY)); + env(pay(devin, badDomainOwner, USD(5)), + path(~USD), + sendmax(XRP(5)), + domain(badDomainID), + ter(tecPATH_DRY)); env.close(); BEAST_EXPECT(checkOffer(env, bob, hybridOfferSeq, XRP(10), USD(10), lsfHybrid, true)); @@ -1103,7 +1200,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // test domain payment consuming two offers w/ hybrid offer { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); auto const EUR = gw["EUR"]; env.trust(EUR(1000), alice); @@ -1122,7 +1220,11 @@ class PermissionedDEX_test : public beast::unit_test::suite BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); // payment fail because there isn't eur offer - env(pay(alice, carol, EUR(5)), path(~USD, ~EUR), sendmax(XRP(5)), domain(domainID), ter(tecPATH_PARTIAL)); + env(pay(alice, carol, EUR(5)), + path(~USD, ~EUR), + sendmax(XRP(5)), + domain(domainID), + ter(tecPATH_PARTIAL)); env.close(); BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); @@ -1143,7 +1245,8 @@ class PermissionedDEX_test : public beast::unit_test::suite // test regular payment using a regular offer and a hybrid offer { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); auto const EUR = gw["EUR"]; env.trust(EUR(1000), alice); @@ -1181,7 +1284,8 @@ class PermissionedDEX_test : public beast::unit_test::suite testHybridOfferDirectories(FeatureBitset features) { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); std::vector offerSeqs; offerSeqs.reserve(100); @@ -1205,7 +1309,9 @@ class PermissionedDEX_test : public beast::unit_test::suite BEAST_EXPECT(sleOffer); BEAST_EXPECT(sleOffer->getFieldH256(sfBookDirectory) == domainDir); BEAST_EXPECT(sleOffer->getFieldArray(sfAdditionalBooks).size() == 1); - BEAST_EXPECT(sleOffer->getFieldArray(sfAdditionalBooks)[0].getFieldH256(sfBookDirectory) == openDir); + BEAST_EXPECT( + sleOffer->getFieldArray(sfAdditionalBooks)[0].getFieldH256(sfBookDirectory) == + openDir); BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), lsfHybrid, true)); BEAST_EXPECT(checkDirectorySize(env, domainDir, i)); @@ -1229,7 +1335,8 @@ class PermissionedDEX_test : public beast::unit_test::suite testcase("Auto bridge"); Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = + PermissionedDEX(env); auto const EUR = gw["EUR"]; for (auto const& account : {alice, bob, carol}) diff --git a/src/test/app/PermissionedDomains_test.cpp b/src/test/app/PermissionedDomains_test.cpp index 8485202144..39ce85d23d 100644 --- a/src/test/app/PermissionedDomains_test.cpp +++ b/src/test/app/PermissionedDomains_test.cpp @@ -1,9 +1,8 @@ #include -#include - #include #include +#include #include #include @@ -164,7 +163,8 @@ class PermissionedDomains_test : public beast::unit_test::suite "Cred0123456789012345678901234567890123456789012345678901234567890"; static_assert(longCredentialType.size() == maxCredentialTypeLength + 1); txJsonMutable["AcceptedCredentials"][2u] = credentialOrig; - txJsonMutable["AcceptedCredentials"][2u][jss::Credential]["CredentialType"] = std::string(longCredentialType); + txJsonMutable["AcceptedCredentials"][2u][jss::Credential]["CredentialType"] = + std::string(longCredentialType); BEAST_EXPECT(exceptionExpected(env, txJsonMutable).starts_with("invalidParams")); // Remove Credentialtype from a credential and apply. @@ -312,7 +312,8 @@ class PermissionedDomains_test : public beast::unit_test::suite BEAST_EXPECT(domain.isNonZero()); BEAST_EXPECT(object["LedgerEntryType"] == "PermissionedDomain"); BEAST_EXPECT(object["Owner"] == alice[0].human()); - BEAST_EXPECT(pdomain::credentialsFromJson(object, human2Acc) == longCredentials); + BEAST_EXPECT( + pdomain::credentialsFromJson(object, human2Acc) == longCredentials); break; } } @@ -342,13 +343,16 @@ class PermissionedDomains_test : public beast::unit_test::suite domain2 = pdomain::getNewDomain(env.meta()); auto objects = pdomain::getObjects(alice[0], env); auto object = objects[domain2]; - BEAST_EXPECT(pdomain::credentialsFromJson(object, human2Acc) == pdomain::sortCredentials(credentials10)); + BEAST_EXPECT( + pdomain::credentialsFromJson(object, human2Acc) == + pdomain::sortCredentials(credentials10)); } // Update with 1 credential. env(pdomain::setTx(alice[0], credentials1, domain2)); BEAST_EXPECT( - pdomain::credentialsFromJson(pdomain::getObjects(alice[0], env)[domain2], human2Acc) == credentials1); + pdomain::credentialsFromJson(pdomain::getObjects(alice[0], env)[domain2], human2Acc) == + credentials1); // Update with 10 credentials. env(pdomain::setTx(alice[0], credentials10, domain2)); diff --git a/src/test/app/PseudoTx_test.cpp b/src/test/app/PseudoTx_test.cpp index 29e13888c3..aa16df8e9c 100644 --- a/src/test/app/PseudoTx_test.cpp +++ b/src/test/app/PseudoTx_test.cpp @@ -1,8 +1,7 @@ #include -#include - #include +#include #include #include diff --git a/src/test/app/RCLValidations_test.cpp b/src/test/app/RCLValidations_test.cpp index 495176104b..140ba9f1d7 100644 --- a/src/test/app/RCLValidations_test.cpp +++ b/src/test/app/RCLValidations_test.cpp @@ -17,9 +17,11 @@ class RCLValidations_test : public beast::unit_test::suite testcase("Change validation trusted status"); auto keys = randomKeyPair(KeyType::secp256k1); auto v = std::make_shared( - xrpl::NetClock::time_point{}, keys.first, keys.second, calcNodeID(keys.first), [&](STValidation& v) { - v.setFieldU32(sfLedgerSequence, 123456); - }); + xrpl::NetClock::time_point{}, + keys.first, + keys.second, + calcNodeID(keys.first), + [&](STValidation& v) { v.setFieldU32(sfLedgerSequence, 123456); }); BEAST_EXPECT(v->isTrusted()); v->setUntrusted(); @@ -54,8 +56,8 @@ class RCLValidations_test : public beast::unit_test::suite jtx::Env env(*this); Config config; - auto prev = - std::make_shared(create_genesis, config, std::vector{}, env.app().getNodeFamily()); + auto prev = std::make_shared( + create_genesis, config, std::vector{}, env.app().getNodeFamily()); history.push_back(prev); for (auto i = 0; i < (2 * maxAncestors + 1); ++i) { @@ -67,7 +69,8 @@ class RCLValidations_test : public beast::unit_test::suite // altHistory agrees with first half of regular history Seq const diverge = history.size() / 2; - std::vector> altHistory(history.begin(), history.begin() + diverge); + std::vector> altHistory( + history.begin(), history.begin() + diverge); // advance clock to get new ledgers using namespace std::chrono_literals; env.timeKeeper().set(env.timeKeeper().now() + 1200s); @@ -211,8 +214,8 @@ class RCLValidations_test : public beast::unit_test::suite jtx::Env env(*this); auto& j = env.journal; Config config; - auto prev = - std::make_shared(create_genesis, config, std::vector{}, env.app().getNodeFamily()); + auto prev = std::make_shared( + create_genesis, config, std::vector{}, env.app().getNodeFamily()); history.push_back(prev); for (auto i = 0; i < (maxAncestors + 10); ++i) { diff --git a/src/test/app/ReducedOffer_test.cpp b/src/test/app/ReducedOffer_test.cpp index b967096eb8..737d73e462 100644 --- a/src/test/app/ReducedOffer_test.cpp +++ b/src/test/app/ReducedOffer_test.cpp @@ -24,12 +24,16 @@ class ReducedOffer_test : public beast::unit_test::suite offerInLedger(jtx::Env& env, jtx::Account const& acct, std::uint32_t offerSeq) { Json::Value ledgerOffer = ledgerEntryOffer(env, acct, offerSeq); - return !(ledgerOffer.isMember(jss::error) && ledgerOffer[jss::error].asString() == "entryNotFound"); + return !( + ledgerOffer.isMember(jss::error) && + ledgerOffer[jss::error].asString() == "entryNotFound"); } // Common code to clean up unneeded offers. static void - cleanupOldOffers(jtx::Env& env, std::initializer_list> list) + cleanupOldOffers( + jtx::Env& env, + std::initializer_list> list) { for (auto [acct, offerSeq] : list) env(offer_cancel(acct, offerSeq)); @@ -69,7 +73,8 @@ public: // 3. Cleans up for the next offer pair. // Returns 1 if the crossed offer has a bad rate for the book. auto exerciseOfferPair = [this, &env, &alice, &bob]( - Amounts const& inLedger, Amounts const& newOffer) -> unsigned int { + Amounts const& inLedger, + Amounts const& newOffer) -> unsigned int { // Put inLedger offer in the ledger so newOffer can cross it. std::uint32_t const aliceOfferSeq = env.seq(alice); env(offer(alice, inLedger.in, inLedger.out)); @@ -103,7 +108,8 @@ public: STAmount const bobGot = env.balance(bob) + bobFee - bobInitialBalance; BEAST_EXPECT(reducedTakerPays < newOffer.in); BEAST_EXPECT(reducedTakerGets < newOffer.out); - STAmount const inLedgerRate = Quality(Amounts{reducedTakerPays, reducedTakerGets}).rate(); + STAmount const inLedgerRate = + Quality(Amounts{reducedTakerPays, reducedTakerGets}).rate(); badRate = inLedgerRate > initialRate ? 1 : 0; @@ -115,7 +121,8 @@ public: if (badRate == 0) { STAmount const tweakedTakerPays = reducedTakerPays + drops(1); - STAmount const tweakedRate = Quality(Amounts{tweakedTakerPays, reducedTakerGets}).rate(); + STAmount const tweakedRate = + Quality(Amounts{tweakedTakerPays, reducedTakerGets}).rate(); BEAST_EXPECT(tweakedRate > initialRate); } #if 0 @@ -147,11 +154,14 @@ public: // iteration. This should mean that the size of the offer bob // places in the ledger should increase with each iteration. unsigned int blockedCount = 0; - for (std::uint64_t mantissaReduce = 1'000'000'000ull; mantissaReduce <= 5'000'000'000ull; + for (std::uint64_t mantissaReduce = 1'000'000'000ull; + mantissaReduce <= 5'000'000'000ull; mantissaReduce += 20'000'000ull) { STAmount aliceUSD{ - bobOffer.out.issue(), bobOffer.out.mantissa() - mantissaReduce, bobOffer.out.exponent()}; + bobOffer.out.issue(), + bobOffer.out.mantissa() - mantissaReduce, + bobOffer.out.exponent()}; STAmount aliceXRP{bobOffer.in.issue(), bobOffer.in.mantissa() - 1}; Amounts aliceOffer{aliceUSD, aliceXRP}; blockedCount += exerciseOfferPair(aliceOffer, bobOffer); @@ -193,7 +203,8 @@ public: // 2. Collects the results, and // 3. Cleans up for the next offer pair. auto exerciseOfferPair = [this, &env, &alice, &bob]( - Amounts const& inLedger, Amounts const& newOffer) -> unsigned int { + Amounts const& inLedger, + Amounts const& newOffer) -> unsigned int { // Get the inLedger offer into the ledger so newOffer can cross // it. STAmount const initialRate = Quality(inLedger).rate(); @@ -229,7 +240,8 @@ public: STAmount const aliceGot = env.balance(alice) - aliceInitialBalance; BEAST_EXPECT(reducedTakerPays < inLedger.in); BEAST_EXPECT(reducedTakerGets < inLedger.out); - STAmount const inLedgerRate = Quality(Amounts{reducedTakerPays, reducedTakerGets}).rate(); + STAmount const inLedgerRate = + Quality(Amounts{reducedTakerPays, reducedTakerGets}).rate(); badRate = inLedgerRate > initialRate ? 1 : 0; // If the inLedgerRate is less than initial rate, then @@ -240,7 +252,8 @@ public: if (badRate == 0) { STAmount const tweakedTakerPays = reducedTakerPays + drops(1); - STAmount const tweakedRate = Quality(Amounts{tweakedTakerPays, reducedTakerGets}).rate(); + STAmount const tweakedRate = + Quality(Amounts{tweakedTakerPays, reducedTakerGets}).rate(); BEAST_EXPECT(tweakedRate > initialRate); } #if 0 @@ -273,11 +286,14 @@ public: // This should mean that the size of the offer alice leaves in the // ledger should increase with each iteration. unsigned int blockedCount = 0; - for (std::uint64_t mantissaReduce = 1'000'000'000ull; mantissaReduce <= 4'000'000'000ull; + for (std::uint64_t mantissaReduce = 1'000'000'000ull; + mantissaReduce <= 4'000'000'000ull; mantissaReduce += 20'000'000ull) { STAmount bobUSD{ - aliceOffer.out.issue(), aliceOffer.out.mantissa() - mantissaReduce, aliceOffer.out.exponent()}; + aliceOffer.out.issue(), + aliceOffer.out.mantissa() - mantissaReduce, + aliceOffer.out.exponent()}; STAmount bobXRP{aliceOffer.in.issue(), aliceOffer.in.mantissa() - 1}; Amounts bobOffer{bobUSD, bobXRP}; @@ -311,7 +327,8 @@ public: env.trust(USD(1000), alice, bob); int blockedOrderBookCount = 0; - for (STAmount initialBobUSD = USD(0.45); initialBobUSD <= USD(1); initialBobUSD += USD(0.025)) + for (STAmount initialBobUSD = USD(0.45); initialBobUSD <= USD(1); + initialBobUSD += USD(0.025)) { // underfund bob's offer env(pay(gw, bob, initialBobUSD)); @@ -355,7 +372,8 @@ public: cleanupOldOffers(env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}}); // Zero out alice's and bob's USD balances. - if (STAmount const aliceBalance = env.balance(alice, USD); aliceBalance.signum() > 0) + if (STAmount const aliceBalance = env.balance(alice, USD); + aliceBalance.signum() > 0) env(pay(alice, gw, aliceBalance)); if (STAmount const bobBalance = env.balance(bob, USD); bobBalance.signum() > 0) @@ -403,7 +421,8 @@ public: STAmount const endLoop(USD.issue(), /*mantissa*/ 50, /*exponent*/ -81); int blockedOrderBookCount = 0; - for (STAmount initialBobUSD = tinyUSD; initialBobUSD <= endLoop; initialBobUSD += tinyUSD) + for (STAmount initialBobUSD = tinyUSD; initialBobUSD <= endLoop; + initialBobUSD += tinyUSD) { // underfund bob's offer env(pay(gw, bob, initialBobUSD)); @@ -497,7 +516,8 @@ public: // Make one test run without fixReducedOffersV2 and one with. for (FeatureBitset features : - {testable_amendments() - fixReducedOffersV2, testable_amendments() | fixReducedOffersV2}) + {testable_amendments() - fixReducedOffersV2, + testable_amendments() | fixReducedOffersV2}) { // Make sure none of the offers we generate are under funded. Env env{*this, features}; @@ -518,15 +538,16 @@ public: // 1. Exercises one offer trio, // 2. Collects the results, and // 3. Cleans up for the next offer trio. - auto exerciseOfferTrio = - [this, &env, &alice, &bob, &carol, &USD](Amounts const& carolOffer) -> unsigned int { + auto exerciseOfferTrio = [this, &env, &alice, &bob, &carol, &USD]( + Amounts const& carolOffer) -> unsigned int { // alice submits an offer that may become a blocker. std::uint32_t const aliceOfferSeq = env.seq(alice); static Amounts const aliceInitialOffer(USD(2), drops(3382562)); env(offer(alice, aliceInitialOffer.in, aliceInitialOffer.out)); env.close(); - STAmount const initialRate = - Quality(jsonOfferToAmounts(ledgerEntryOffer(env, alice, aliceOfferSeq)[jss::node])).rate(); + STAmount const initialRate = Quality(jsonOfferToAmounts(ledgerEntryOffer( + env, alice, aliceOfferSeq)[jss::node])) + .rate(); // bob submits an offer that is more desirable than alice's std::uint32_t const bobOfferSeq = env.seq(bob); @@ -541,11 +562,14 @@ public: // carol's offer should not have made it into the ledger and // bob's offer should be fully consumed. - if (!BEAST_EXPECT(!offerInLedger(env, carol, carolOfferSeq) && !offerInLedger(env, bob, bobOfferSeq))) + if (!BEAST_EXPECT( + !offerInLedger(env, carol, carolOfferSeq) && + !offerInLedger(env, bob, bobOfferSeq))) { // If carol's or bob's offers are still in the ledger then // further results are meaningless. - cleanupOldOffers(env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}, {carol, carolOfferSeq}}); + cleanupOldOffers( + env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}, {carol, carolOfferSeq}}); return 1; } // alice's offer should still be in the ledger, but reduced in @@ -573,7 +597,8 @@ public: aliceReducedOffer.in.mantissa() + 1, aliceReducedOffer.in.exponent(), aliceReducedOffer.in.negative()); - STAmount const tweakedRate = Quality(Amounts{aliceReducedOffer.in, tweakedTakerGets}).rate(); + STAmount const tweakedRate = + Quality(Amounts{aliceReducedOffer.in, tweakedTakerGets}).rate(); BEAST_EXPECT(tweakedRate > initialRate); } #if 0 @@ -593,7 +618,8 @@ public: // In preparation for the next iteration make sure all three // offers are gone from the ledger. - cleanupOldOffers(env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}, {carol, carolOfferSeq}}); + cleanupOldOffers( + env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}, {carol, carolOfferSeq}}); return badRate; }; @@ -604,7 +630,8 @@ public: STAmount const step(increaseGets.issue(), 1, -8); for (unsigned int i = 0; i < loopCount; ++i) { - blockedCount += exerciseOfferTrio(Amounts(drops(1642020), USD(1) + increaseGets)); + blockedCount += + exerciseOfferTrio(Amounts(drops(1642020), USD(1) + increaseGets)); increaseGets += step; } } diff --git a/src/test/app/Regression_test.cpp b/src/test/app/Regression_test.cpp index 052b334ef5..e323e61132 100644 --- a/src/test/app/Regression_test.cpp +++ b/src/test/app/Regression_test.cpp @@ -3,13 +3,13 @@ #include #include -#include #include #include #include #include #include +#include namespace xrpl { namespace test { @@ -278,10 +278,13 @@ struct Regression_test : public beast::unit_test::suite auto const afterCounts = mapCounts(CountedObjects::getInstance().getCounts(0)); using namespace std::string_literals; - BEAST_EXPECT(beforeCounts.at("CachedView::hit"s) == afterCounts.at("CachedView::hit"s)); BEAST_EXPECT( - beforeCounts.at("CachedView::hitExpired"s) + 1 == afterCounts.at("CachedView::hitExpired"s)); - BEAST_EXPECT(beforeCounts.at("CachedView::miss"s) == afterCounts.at("CachedView::miss"s)); + beforeCounts.at("CachedView::hit"s) == afterCounts.at("CachedView::hit"s)); + BEAST_EXPECT( + beforeCounts.at("CachedView::hitExpired"s) + 1 == + afterCounts.at("CachedView::hitExpired"s)); + BEAST_EXPECT( + beforeCounts.at("CachedView::miss"s) == afterCounts.at("CachedView::miss"s)); } } } diff --git a/src/test/app/SHAMapStore_test.cpp b/src/test/app/SHAMapStore_test.cpp index 9e0a971685..97a9a38e77 100644 --- a/src/test/app/SHAMapStore_test.cpp +++ b/src/test/app/SHAMapStore_test.cpp @@ -44,7 +44,8 @@ class SHAMapStore_test : public beast::unit_test::suite auto const seq = json[jss::result][jss::ledger_index].asUInt(); - std::optional outInfo = env.app().getRelationalDatabase().getLedgerInfoByIndex(seq); + std::optional outInfo = + env.app().getRelationalDatabase().getLedgerInfoByIndex(seq); if (!outInfo) return false; LedgerHeader const& info = outInfo.value(); @@ -62,7 +63,8 @@ class SHAMapStore_test : public beast::unit_test::suite auto const& ledger = json[jss::result][jss::ledger]; return outHash == ledger[jss::ledger_hash].asString() && outSeq == seq && - outParentHash == ledger[jss::parent_hash].asString() && outDrops == ledger[jss::total_coins].asString() && + outParentHash == ledger[jss::parent_hash].asString() && + outDrops == ledger[jss::total_coins].asString() && outCloseTime == ledger[jss::close_time].asUInt() && outParentCloseTime == ledger[jss::parent_close_time].asUInt() && outCloseTimeResolution == ledger[jss::close_time_resolution].asUInt() && @@ -91,7 +93,8 @@ class SHAMapStore_test : public beast::unit_test::suite void ledgerCheck(jtx::Env& env, int const rows, int const first) { - auto const [actualRows, actualFirst, actualLast] = env.app().getRelationalDatabase().getLedgerCountMinMax(); + auto const [actualRows, actualFirst, actualLast] = + env.app().getRelationalDatabase().getLedgerCountMinMax(); BEAST_EXPECT(actualRows == rows); BEAST_EXPECT(actualFirst == first); @@ -185,7 +188,9 @@ public: for (auto i = 3; i < deleteInterval + lastRotated; ++i) { ledgers.emplace(std::make_pair(i, env.rpc("ledger", std::to_string(i)))); - BEAST_EXPECT(goodLedger(env, ledgers[i], std::to_string(i), true) && getHash(ledgers[i]).length()); + BEAST_EXPECT( + goodLedger(env, ledgers[i], std::to_string(i), true) && + getHash(ledgers[i]).length()); } ledgerCheck(env, deleteInterval + 1, 2); @@ -220,8 +225,11 @@ public: BEAST_EXPECT(goodLedger(env, ledgerTmp, std::to_string(i + 3))); ledgers.emplace(std::make_pair(i, env.rpc("ledger", std::to_string(i)))); - BEAST_EXPECT(store.getLastRotated() == lastRotated || i == lastRotated + deleteInterval - 2); - BEAST_EXPECT(goodLedger(env, ledgers[i], std::to_string(i), true) && getHash(ledgers[i]).length()); + BEAST_EXPECT( + store.getLastRotated() == lastRotated || i == lastRotated + deleteInterval - 2); + BEAST_EXPECT( + goodLedger(env, ledgers[i], std::to_string(i), true) && + getHash(ledgers[i]).length()); } store.rendezvous(); @@ -393,7 +401,8 @@ public: // This does not kick off a cleanup canDelete = env.rpc("can_delete", "always"); BEAST_EXPECT(!RPC::contains_error(canDelete[jss::result])); - BEAST_EXPECT(canDelete[jss::result][jss::can_delete] == std::numeric_limits::max()); + BEAST_EXPECT( + canDelete[jss::result][jss::can_delete] == std::numeric_limits::max()); for (; ledgerSeq < lastRotated + deleteInterval; ++ledgerSeq) { @@ -538,7 +547,8 @@ public: // callback BEAST_EXPECT(dbr->getName() == "3"); }; - auto const cbReentrant = [&](std::string const& writableName, std::string const& archiveName) { + auto const cbReentrant = [&](std::string const& writableName, + std::string const& archiveName) { BEAST_EXPECT(writableName == "2"); BEAST_EXPECT(archiveName == "1"); auto newBackend = makeBackendRotating(env, scheduler, std::to_string(++threadNum)); diff --git a/src/test/app/SetAuth_test.cpp b/src/test/app/SetAuth_test.cpp index 400e2b0e29..a38cf7175a 100644 --- a/src/test/app/SetAuth_test.cpp +++ b/src/test/app/SetAuth_test.cpp @@ -17,7 +17,8 @@ struct SetAuth_test : public beast::unit_test::suite using namespace jtx; Json::Value jv; jv[jss::Account] = account.human(); - jv[jss::LimitAmount] = STAmount(Issue{to_currency(currency), dest}).getJson(JsonOptions::none); + jv[jss::LimitAmount] = + STAmount(Issue{to_currency(currency), dest}).getJson(JsonOptions::none); jv[jss::TransactionType] = jss::TrustSet; jv[jss::Flags] = tfSetfAuth; return jv; diff --git a/src/test/app/SetRegularKey_test.cpp b/src/test/app/SetRegularKey_test.cpp index aec8dddc7a..3cce01a112 100644 --- a/src/test/app/SetRegularKey_test.cpp +++ b/src/test/app/SetRegularKey_test.cpp @@ -65,13 +65,15 @@ public: env.fund(XRP(10000), alice, bob); auto ar = env.le(alice); - BEAST_EXPECT(ar->isFieldPresent(sfFlags) && ((ar->getFieldU32(sfFlags) & lsfPasswordSpent) == 0)); + BEAST_EXPECT( + ar->isFieldPresent(sfFlags) && ((ar->getFieldU32(sfFlags) & lsfPasswordSpent) == 0)); env(regkey(alice, bob), sig(alice), fee(0)); ar = env.le(alice); BEAST_EXPECT( - ar->isFieldPresent(sfFlags) && ((ar->getFieldU32(sfFlags) & lsfPasswordSpent) == lsfPasswordSpent)); + ar->isFieldPresent(sfFlags) && + ((ar->getFieldU32(sfFlags) & lsfPasswordSpent) == lsfPasswordSpent)); // The second SetRegularKey transaction with Fee=0 should fail. env(regkey(alice, bob), sig(alice), fee(0), ter(telINSUF_FEE_P)); @@ -79,7 +81,8 @@ public: env.trust(bob["USD"](1), alice); env(pay(bob, alice, bob["USD"](1))); ar = env.le(alice); - BEAST_EXPECT(ar->isFieldPresent(sfFlags) && ((ar->getFieldU32(sfFlags) & lsfPasswordSpent) == 0)); + BEAST_EXPECT( + ar->isFieldPresent(sfFlags) && ((ar->getFieldU32(sfFlags) & lsfPasswordSpent) == 0)); } void diff --git a/src/test/app/SetTrust_test.cpp b/src/test/app/SetTrust_test.cpp index 4704365550..06aebcd915 100644 --- a/src/test/app/SetTrust_test.cpp +++ b/src/test/app/SetTrust_test.cpp @@ -184,7 +184,9 @@ public: if (thirdLineCreatesLE) { // creator does not have enough for the third trust line - env(trust(creator, assistor["USD"](100)), ter(tecNO_LINE_INSUF_RESERVE), require(lines(creator, 2))); + env(trust(creator, assistor["USD"](100)), + ter(tecNO_LINE_INSUF_RESERVE), + require(lines(creator, 2))); } else { @@ -278,10 +280,12 @@ public: env.fund(XRP(10000), gw, alice); // Require valid tf flags - for (std::uint64_t badFlag = 1u; badFlag <= std::numeric_limits::max(); badFlag *= 2) + for (std::uint64_t badFlag = 1u; badFlag <= std::numeric_limits::max(); + badFlag *= 2) { if (badFlag & tfTrustSetMask) - env(trust(alice, gw["USD"](100), static_cast(badFlag)), ter(temINVALID_FLAG)); + env(trust(alice, gw["USD"](100), static_cast(badFlag)), + ter(temINVALID_FLAG)); } // trust amount can't be XRP @@ -294,7 +298,8 @@ public: env(trust(alice, gw["USD"](-1000)), ter(temBAD_LIMIT)); // trust amount can't be from invalid issuer - env(trust_explicit_amt(alice, STAmount{Issue{to_currency("USD"), noAccount()}, 100}), ter(temDST_NEEDED)); + env(trust_explicit_amt(alice, STAmount{Issue{to_currency("USD"), noAccount()}, 100}), + ter(temDST_NEEDED)); // trust cannot be to self env(trust(alice, alice["USD"](100)), ter(temDST_IS_SRC)); @@ -400,8 +405,9 @@ public: void testModifyQualityOfTrustline(FeatureBitset features, bool createQuality, bool createOnHighAcct) { - testcase << "SetTrust " << (createQuality ? "creates" : "removes") << " quality of trustline for " - << (createOnHighAcct ? "high" : "low") << " account"; + testcase << "SetTrust " << (createQuality ? "creates" : "removes") + << " quality of trustline for " << (createOnHighAcct ? "high" : "low") + << " account"; using namespace jtx; Env env{*this, features}; diff --git a/src/test/app/TheoreticalQuality_test.cpp b/src/test/app/TheoreticalQuality_test.cpp index 1f626ad477..9b6d86dd5f 100644 --- a/src/test/app/TheoreticalQuality_test.cpp +++ b/src/test/app/TheoreticalQuality_test.cpp @@ -1,16 +1,15 @@ #include #include -#include -#include -#include -#include - #include #include #include #include #include +#include +#include +#include +#include namespace xrpl { namespace test { @@ -46,7 +45,9 @@ struct RippleCalcTestParams { assert(!pe.isMember(jss::currency) && !pe.isMember(jss::issuer)); p.emplace_back( - *parseBase58(pe[jss::account].asString()), std::nullopt, std::nullopt); + *parseBase58(pe[jss::account].asString()), + std::nullopt, + std::nullopt); } else if (pe.isMember(jss::currency) && pe.isMember(jss::issuer)) { @@ -110,7 +111,11 @@ class RandomAccountParams // Setup the trust amounts and in/out qualities (but not the balances) void - setupTrustLine(jtx::Env& env, jtx::Account const& acc, jtx::Account const& peer, Currency const& currency) + setupTrustLine( + jtx::Env& env, + jtx::Account const& acc, + jtx::Account const& peer, + Currency const& currency) { using namespace jtx; IOU const iou{peer, currency}; @@ -135,19 +140,29 @@ public: // Set the initial balance, taking into account the qualities void - setInitialBalance(jtx::Env& env, jtx::Account const& acc, jtx::Account const& peer, Currency const& currency) + setInitialBalance( + jtx::Env& env, + jtx::Account const& acc, + jtx::Account const& peer, + Currency const& currency) { using namespace jtx; IOU const iou{acc, currency}; // This payment sets the acc's balance to `initialBalance`. // Since input qualities complicate this payment, use `sendMax` with // `initialBalance` to make sure the balance is set correctly. - env(pay(peer, acc, iou(trustAmount_)), sendmax(iou(initialBalance_)), txflags(tfPartialPayment)); + env(pay(peer, acc, iou(trustAmount_)), + sendmax(iou(initialBalance_)), + txflags(tfPartialPayment)); env.close(); } void - maybeSetInitialBalance(jtx::Env& env, jtx::Account const& acc, jtx::Account const& peer, Currency const& currency) + maybeSetInitialBalance( + jtx::Env& env, + jtx::Account const& acc, + jtx::Account const& peer, + Currency const& currency) { using namespace jtx; if (zeroOneDist_(engine_) > probRedeem_) @@ -158,7 +173,11 @@ public: // Setup the trust amounts and in/out qualities (but not the balances) on // both sides of the trust line void - setupTrustLines(jtx::Env& env, jtx::Account const& acc1, jtx::Account const& acc2, Currency const& currency) + setupTrustLines( + jtx::Env& env, + jtx::Account const& acc1, + jtx::Account const& acc2, + Currency const& currency) { setupTrustLine(env, acc1, acc2, currency); setupTrustLine(env, acc2, acc1, currency); @@ -237,7 +256,8 @@ class TheoreticalQuality_test : public beast::unit_test::suite for (auto const& strand : sr.second) { Quality const theoreticalQ = *qualityUpperBound(sb, strand); - auto const f = flow(sb, strand, IOUAmount(10, 0), IOUAmount(5, 0), dummyJ); + auto const f = + flow(sb, strand, IOUAmount(10, 0), IOUAmount(5, 0), dummyJ); BEAST_EXPECT(f.success); Quality const actualQ(f.out, f.in); if (actualQ != theoreticalQ && !compareClose(actualQ, theoreticalQ)) @@ -341,7 +361,9 @@ public: // Accounts are set up, make the payment IOU const iou{accounts.back(), currency}; RippleCalcTestParams rcp{env.json( - pay(accounts.front(), accounts.back(), iou(paymentAmount)), accountsPath, txflags(tfNoRippleDirect))}; + pay(accounts.front(), accounts.back(), iou(paymentAmount)), + accountsPath, + txflags(tfNoRippleDirect))}; testCase(rcp, env.closed()); } diff --git a/src/test/app/Ticket_test.cpp b/src/test/app/Ticket_test.cpp index 0835c02289..760cce88be 100644 --- a/src/test/app/Ticket_test.cpp +++ b/src/test/app/Ticket_test.cpp @@ -21,7 +21,8 @@ class Ticket_test : public beast::unit_test::suite { std::string const txType = tx[sfTransactionType.jsonName].asString(); - if (!BEAST_EXPECTS(txType == jss::TicketCreate, "Unexpected TransactionType: "s + txType)) + if (!BEAST_EXPECTS( + txType == jss::TicketCreate, "Unexpected TransactionType: "s + txType)) return; } @@ -96,9 +97,11 @@ class Ticket_test : public beast::unit_test::suite else { // Verify the OwnerCount did the right thing. - std::uint32_t const prevCount = {previousFields[sfOwnerCount.jsonName].asUInt()}; + std::uint32_t const prevCount = { + previousFields[sfOwnerCount.jsonName].asUInt()}; - std::uint32_t const finalCount = {finalFields[sfOwnerCount.jsonName].asUInt()}; + std::uint32_t const finalCount = { + finalFields[sfOwnerCount.jsonName].asUInt()}; BEAST_EXPECT(prevCount + count - consumedTickets == finalCount); } @@ -121,9 +124,12 @@ class Ticket_test : public beast::unit_test::suite ? previousFields[sfTicketCount.jsonName].asUInt() : 0u}; - BEAST_EXPECT((startCount == 0u) ^ previousFields.isMember(sfTicketCount.jsonName)); + BEAST_EXPECT( + (startCount == 0u) ^ previousFields.isMember(sfTicketCount.jsonName)); - BEAST_EXPECT(startCount + count - consumedTickets == finalFields[sfTicketCount.jsonName]); + BEAST_EXPECT( + startCount + count - consumedTickets == + finalFields[sfTicketCount.jsonName]); } } else if (entryType == jss::DirectoryNode) @@ -171,7 +177,8 @@ class Ticket_test : public beast::unit_test::suite // Verify the deleted ticket has the right TicketSequence. BEAST_EXPECT( - finalFields[sfTicketSequence.jsonName].asUInt() == tx[sfTicketSequence.jsonName].asUInt()); + finalFields[sfTicketSequence.jsonName].asUInt() == + tx[sfTicketSequence.jsonName].asUInt()); } } else @@ -222,19 +229,24 @@ class Ticket_test : public beast::unit_test::suite // was deleted. BEAST_EXPECT(tx[sfSequence.jsonName].asUInt() == 0); std::string const account{tx[sfAccount.jsonName].asString()}; - if (!BEAST_EXPECTS(tx.isMember(sfTicketSequence.jsonName), "Not metadata for a ticket consuming transaction.")) + if (!BEAST_EXPECTS( + tx.isMember(sfTicketSequence.jsonName), + "Not metadata for a ticket consuming transaction.")) return; std::uint32_t const ticketSeq{tx[sfTicketSequence.jsonName].asUInt()}; Json::Value const& metadata{env.meta()->getJson(JsonOptions::none)}; - if (!BEAST_EXPECTS(metadata.isMember(sfTransactionResult.jsonName), "Metadata is missing TransactionResult.")) + if (!BEAST_EXPECTS( + metadata.isMember(sfTransactionResult.jsonName), + "Metadata is missing TransactionResult.")) return; { std::string const transactionResult{metadata[sfTransactionResult.jsonName].asString()}; if (!BEAST_EXPECTS( - transactionResult == "tesSUCCESS" || transactionResult.compare(0, 3, "tec") == 0, + transactionResult == "tesSUCCESS" || + transactionResult.compare(0, 3, "tec") == 0, transactionResult + " neither tesSUCCESS nor tec")) return; } @@ -269,7 +281,8 @@ class Ticket_test : public beast::unit_test::suite "AccountRoot previous is missing TicketCount")) return; - std::uint32_t const prevTicketCount = previousFields[sfTicketCount.jsonName].asUInt(); + std::uint32_t const prevTicketCount = + previousFields[sfTicketCount.jsonName].asUInt(); BEAST_EXPECT(prevTicketCount > 0); if (prevTicketCount == 1) @@ -288,10 +301,13 @@ class Ticket_test : public beast::unit_test::suite if (entryType == jss::Ticket) { // Verify the account of the deleted ticket. - BEAST_EXPECT(deleted[sfFinalFields.jsonName][sfAccount.jsonName].asString() == account); + BEAST_EXPECT( + deleted[sfFinalFields.jsonName][sfAccount.jsonName].asString() == account); // Verify the deleted ticket has the right TicketSequence. - BEAST_EXPECT(deleted[sfFinalFields.jsonName][sfTicketSequence.jsonName].asUInt() == ticketSeq); + BEAST_EXPECT( + deleted[sfFinalFields.jsonName][sfTicketSequence.jsonName].asUInt() == + ticketSeq); ++ticketsRemoved; } @@ -463,7 +479,10 @@ class Ticket_test : public beast::unit_test::suite // Give alice not quite enough to make the reserve for a total of // 250 Tickets. - env(pay(env.master, alice, env.current()->fees().accountReserve(250) - drops(1) - env.balance(alice))); + env( + pay(env.master, + alice, + env.current()->fees().accountReserve(250) - drops(1) - env.balance(alice))); env.close(); // alice doesn't quite have the reserve for a total of 250 @@ -563,7 +582,10 @@ class Ticket_test : public beast::unit_test::suite checkTicketCreateMeta(env); env.close(); - env(noop(alice), ticket::use(ticketSeq_G), json(R"({"AccountTxnID": "0"})"), ter(temINVALID)); + env(noop(alice), + ticket::use(ticketSeq_G), + json(R"({"AccountTxnID": "0"})"), + ter(temINVALID)); env.close(); env.require(owners(alice, 2), tickets(alice, 1)); } @@ -657,7 +679,8 @@ class Ticket_test : public beast::unit_test::suite error_code_i txErrCode{rpcSUCCESS}; using TxPair = std::pair, std::shared_ptr>; - std::variant maybeTx = Transaction::load(txID, env.app(), txErrCode); + std::variant maybeTx = + Transaction::load(txID, env.app(), txErrCode); BEAST_EXPECT(txErrCode == rpcSUCCESS); if (auto txPtr = std::get_if(&maybeTx)) diff --git a/src/test/app/TrustAndBalance_test.cpp b/src/test/app/TrustAndBalance_test.cpp index aa06ccbdf1..413ef6dd78 100644 --- a/src/test/app/TrustAndBalance_test.cpp +++ b/src/test/app/TrustAndBalance_test.cpp @@ -215,7 +215,8 @@ class TrustAndBalance_test : public beast::unit_test::suite auto const& t = jval[jss::transaction]; return t[jss::TransactionType] == jss::Payment; })); - BEAST_EXPECT(wsc->findMsg(5s, [](auto const& jval) { return jval[jss::type] == "ledgerClosed"; })); + BEAST_EXPECT(wsc->findMsg( + 5s, [](auto const& jval) { return jval[jss::type] == "ledgerClosed"; })); BEAST_EXPECT(wsc->invoke("unsubscribe", jv)[jss::status] == "success"); } @@ -312,7 +313,9 @@ class TrustAndBalance_test : public beast::unit_test::suite void testIndirectMultiPath(bool with_rate, FeatureBitset features) { - testcase(std::string("Indirect Payment, Multi Path, ") + (with_rate ? "With " : "Without ") + " Xfer Fee, "); + testcase( + std::string("Indirect Payment, Multi Path, ") + (with_rate ? "With " : "Without ") + + " Xfer Fee, "); using namespace test::jtx; Env env{*this, features}; @@ -349,8 +352,10 @@ class TrustAndBalance_test : public beast::unit_test::suite if (with_rate) { - env.require( - balance(alice, STAmount(carol["USD"].issue(), 6500000000000000ull, -14, true, STAmount::unchecked{}))); + env.require(balance( + alice, + STAmount( + carol["USD"].issue(), 6500000000000000ull, -14, true, STAmount::unchecked{}))); env.require(balance(carol, gw["USD"](35))); } else @@ -386,7 +391,8 @@ class TrustAndBalance_test : public beast::unit_test::suite char const* invoiceId = "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"; Json::Value jv; - auto tx = env.jt(pay(env.master, alice, XRP(10000)), json(sfInvoiceID.fieldName, invoiceId)); + auto tx = + env.jt(pay(env.master, alice, XRP(10000)), json(sfInvoiceID.fieldName, invoiceId)); jv[jss::tx_blob] = strHex(tx.stx->getSerializer().slice()); auto jrr = wsc->invoke("submit", jv)[jss::result]; BEAST_EXPECT(jrr[jss::status] == "success"); diff --git a/src/test/app/TxQ_test.cpp b/src/test/app/TxQ_test.cpp index 13feceb74e..94db50842a 100644 --- a/src/test/app/TxQ_test.cpp +++ b/src/test/app/TxQ_test.cpp @@ -6,13 +6,13 @@ #include #include -#include #include -#include #include #include #include +#include +#include namespace xrpl { @@ -330,7 +330,13 @@ public: env(noop(env.master), fee(baseFee * 2), queued); ++metrics.txCount; - checkMetrics(*this, env, metrics.txCount, metrics.txQMaxSize, metrics.txPerLedger + 1, metrics.txPerLedger); + checkMetrics( + *this, + env, + metrics.txCount, + metrics.txQMaxSize, + metrics.txPerLedger + 1, + metrics.txPerLedger); } void @@ -543,11 +549,17 @@ public: // let's try replacing them. // The lowest fee ticket is baseFee * 2.1, trying to replace it - env(noop(alice), ticket::use(tkt1 + 18), fee(baseFee * 2.1 * 1.25 - 1), ter(telCAN_NOT_QUEUE_FEE)); + env(noop(alice), + ticket::use(tkt1 + 18), + fee(baseFee * 2.1 * 1.25 - 1), + ter(telCAN_NOT_QUEUE_FEE)); env(noop(alice), ticket::use(tkt1 + 18), fee(baseFee * 2.1 * 1.25 + 1), queued); // New lowest fee ticket is baseFee * 2.2 - env(noop(alice), ticket::use(tkt250 - 4), fee(baseFee * 2.2 * 1.25 - 1), ter(telCAN_NOT_QUEUE_FEE)); + env(noop(alice), + ticket::use(tkt250 - 4), + fee(baseFee * 2.2 * 1.25 - 1), + ter(telCAN_NOT_QUEUE_FEE)); env(noop(alice), ticket::use(tkt250 - 4), fee(baseFee * 2.2 * 1.25 + 1), queued); env.close(); @@ -715,7 +727,8 @@ public: auto bobStat = txQ.getAccountTxs(bob.id()); BEAST_EXPECT(bobStat.size() == 1); - BEAST_EXPECT(bobStat.begin()->feeLevel == FeeLevel64{baseFeeLevel.fee() * largeFeeMultiplier}); + BEAST_EXPECT( + bobStat.begin()->feeLevel == FeeLevel64{baseFeeLevel.fee() * largeFeeMultiplier}); BEAST_EXPECT(!bobStat.begin()->lastValid); BEAST_EXPECT(!bobStat.begin()->consequences.isBlocker()); @@ -960,7 +973,8 @@ public: Env env( *this, makeConfig( - {{"minimum_txn_in_ledger_standalone", "3"}}, {{"account_reserve", "200"}, {"owner_reserve", "50"}})); + {{"minimum_txn_in_ledger_standalone", "3"}}, + {{"account_reserve", "200"}, {"owner_reserve", "50"}})); auto alice = Account("alice"); auto bob = Account("bob"); @@ -1034,7 +1048,11 @@ public: auto lastLedgerSeq = env.current()->header().seq + 2; for (auto i = 0; i < 7; i++) { - env(noop(alice), seq(aliceSeq), json(jss::LastLedgerSequence, lastLedgerSeq + i), fee(--aliceFee), queued); + env(noop(alice), + seq(aliceSeq), + json(jss::LastLedgerSequence, lastLedgerSeq + i), + fee(--aliceFee), + queued); ++aliceSeq; } checkMetrics(*this, env, 8, 8, 5, 4, 513); @@ -1051,7 +1069,8 @@ public: BEAST_EXPECT(tx.feeLevel == toFeeLevel(XRPAmount(--aliceFee), baseFee)); BEAST_EXPECT(tx.lastValid); BEAST_EXPECT( - (tx.consequences.fee() == drops(aliceFee) && tx.consequences.potentialSpend() == drops(0) && + (tx.consequences.fee() == drops(aliceFee) && + tx.consequences.potentialSpend() == drops(0) && !tx.consequences.isBlocker()) || tx.seqProxy.value() == env.seq(alice) + 6); ++seq; @@ -1291,14 +1310,16 @@ public: // transaction ordering BEAST_EXPECT( aliceSeq + bobSeq + charlieSeq + dariaSeq + elmoSeq + fredSeq + gwenSeq + hankSeq + 6 == - env.seq(alice) + env.seq(bob) + env.seq(charlie) + env.seq(daria) + env.seq(elmo) + env.seq(fred) + - env.seq(gwen) + env.seq(hank)); + env.seq(alice) + env.seq(bob) + env.seq(charlie) + env.seq(daria) + env.seq(elmo) + + env.seq(fred) + env.seq(gwen) + env.seq(hank)); // These tests may change if TxQ ordering is changed using namespace std::string_literals; BEAST_EXPECTS( - aliceSeq == env.seq(alice), "alice: "s + std::to_string(aliceSeq) + ", " + std::to_string(env.seq(alice))); + aliceSeq == env.seq(alice), + "alice: "s + std::to_string(aliceSeq) + ", " + std::to_string(env.seq(alice))); BEAST_EXPECTS( - bobSeq + 1 == env.seq(bob), "bob: "s + std::to_string(bobSeq) + ", " + std::to_string(env.seq(bob))); + bobSeq + 1 == env.seq(bob), + "bob: "s + std::to_string(bobSeq) + ", " + std::to_string(env.seq(bob))); BEAST_EXPECTS( charlieSeq + 2 == env.seq(charlie), "charlie: "s + std::to_string(charlieSeq) + ", " + std::to_string(env.seq(charlie))); @@ -1306,13 +1327,17 @@ public: dariaSeq + 1 == env.seq(daria), "daria: "s + std::to_string(dariaSeq) + ", " + std::to_string(env.seq(daria))); BEAST_EXPECTS( - elmoSeq + 1 == env.seq(elmo), "elmo: "s + std::to_string(elmoSeq) + ", " + std::to_string(env.seq(elmo))); + elmoSeq + 1 == env.seq(elmo), + "elmo: "s + std::to_string(elmoSeq) + ", " + std::to_string(env.seq(elmo))); BEAST_EXPECTS( - fredSeq == env.seq(fred), "fred: "s + std::to_string(fredSeq) + ", " + std::to_string(env.seq(fred))); + fredSeq == env.seq(fred), + "fred: "s + std::to_string(fredSeq) + ", " + std::to_string(env.seq(fred))); BEAST_EXPECTS( - gwenSeq == env.seq(gwen), "gwen: "s + std::to_string(gwenSeq) + ", " + std::to_string(env.seq(gwen))); + gwenSeq == env.seq(gwen), + "gwen: "s + std::to_string(gwenSeq) + ", " + std::to_string(env.seq(gwen))); BEAST_EXPECTS( - hankSeq + 1 == env.seq(hank), "hank: "s + std::to_string(hankSeq) + ", " + std::to_string(env.seq(hank))); + hankSeq + 1 == env.seq(hank), + "hank: "s + std::to_string(hankSeq) + ", " + std::to_string(env.seq(hank))); // Which sequences get incremented may change if TxQ ordering is // changed @@ -1370,8 +1395,8 @@ public: // transaction ordering BEAST_EXPECT( aliceSeq + bobSeq + charlieSeq + dariaSeq + elmoSeq + fredSeq + gwenSeq + hankSeq + 7 == - env.seq(alice) + env.seq(bob) + env.seq(charlie) + env.seq(daria) + env.seq(elmo) + env.seq(fred) + - env.seq(gwen) + env.seq(hank)); + env.seq(alice) + env.seq(bob) + env.seq(charlie) + env.seq(daria) + env.seq(elmo) + + env.seq(fred) + env.seq(gwen) + env.seq(hank)); // These tests may change if TxQ ordering is changed BEAST_EXPECTS( aliceSeq + qTxCount1[alice.id()] - qTxCount2[alice.id()] == env.seq(alice), @@ -1468,7 +1493,8 @@ public: if (i == 4) { double const feeMultiplier = static_cast(cost.drops()) / baseFee; - medFeeLevel = FeeLevel64{static_cast(feeMultiplier * baseFeeLevel.fee())}; + medFeeLevel = + FeeLevel64{static_cast(feeMultiplier * baseFeeLevel.fee())}; } env(noop(alice), fee(cost)); @@ -1557,7 +1583,8 @@ public: Env env( *this, makeConfig( - {{"minimum_txn_in_ledger_standalone", "3"}}, {{"account_reserve", "200"}, {"owner_reserve", "50"}})); + {{"minimum_txn_in_ledger_standalone", "3"}}, + {{"account_reserve", "200"}, {"owner_reserve", "50"}})); auto alice = Account("alice"); auto bob = Account("bob"); @@ -1672,9 +1699,15 @@ public: env(noop(alice), seq(aliceSeq + 1), queued); // Can't replace either queued transaction with a blocker - env(fset(alice, asfAccountTxnID), seq(aliceSeq + 0), fee(baseFee * 2), ter(telCAN_NOT_QUEUE_BLOCKS)); + env(fset(alice, asfAccountTxnID), + seq(aliceSeq + 0), + fee(baseFee * 2), + ter(telCAN_NOT_QUEUE_BLOCKS)); - env(regkey(alice, bob), seq(aliceSeq + 1), fee(baseFee * 2), ter(telCAN_NOT_QUEUE_BLOCKS)); + env(regkey(alice, bob), + seq(aliceSeq + 1), + fee(baseFee * 2), + ter(telCAN_NOT_QUEUE_BLOCKS)); // Can't append a blocker to the queue. env(signers(alice, 2, {{bob}, {charlie}, {daria}}), @@ -1711,7 +1744,10 @@ public: env(noop(bob), queued); // We can replace the blocker with a different blocker. - env(signers(alice, 2, {{bob}, {charlie}, {daria}}), seq(aliceSeq + 0), fee(baseFee * 2.6), queued); + env(signers(alice, 2, {{bob}, {charlie}, {daria}}), + seq(aliceSeq + 0), + fee(baseFee * 2.6), + queued); // Prove that the queue is still blocked. env(noop(alice), seq(aliceSeq + 1), ter(telCAN_NOT_QUEUE_BLOCKED)); @@ -1795,12 +1831,20 @@ public: env(noop(alice), ticket::use(tkt + 1), queued); // Can't replace either queued transaction with a blocker - env(fset(alice, asfAccountTxnID), ticket::use(tkt + 1), fee(baseFee * 2), ter(telCAN_NOT_QUEUE_BLOCKS)); + env(fset(alice, asfAccountTxnID), + ticket::use(tkt + 1), + fee(baseFee * 2), + ter(telCAN_NOT_QUEUE_BLOCKS)); - env(regkey(alice, bob), ticket::use(tkt + 2), fee(baseFee * 2), ter(telCAN_NOT_QUEUE_BLOCKS)); + env(regkey(alice, bob), + ticket::use(tkt + 2), + fee(baseFee * 2), + ter(telCAN_NOT_QUEUE_BLOCKS)); // Can't append a blocker to the queue. - env(signers(alice, 2, {{bob}, {charlie}, {daria}}), fee(baseFee * 2), ter(telCAN_NOT_QUEUE_BLOCKS)); + env(signers(alice, 2, {{bob}, {charlie}, {daria}}), + fee(baseFee * 2), + ter(telCAN_NOT_QUEUE_BLOCKS)); env(signers(alice, 2, {{bob}, {charlie}, {daria}}), ticket::use(tkt + 0), @@ -1832,7 +1876,10 @@ public: // Since there's an entry in the queue we cannot append a // blocker to the account's queue. env(regkey(alice, bob), fee(baseFee * 2), ter(telCAN_NOT_QUEUE_BLOCKS)); - env(regkey(alice, bob), ticket::use(tkt + 1), fee(baseFee * 2), ter(telCAN_NOT_QUEUE_BLOCKS)); + env(regkey(alice, bob), + ticket::use(tkt + 1), + fee(baseFee * 2), + ter(telCAN_NOT_QUEUE_BLOCKS)); // However we can _replace_ that lone entry with a blocker. env(regkey(alice, bob), ticket::use(tkt + 0), fee(baseFee * 2), queued); @@ -1846,7 +1893,10 @@ public: env(noop(bob), queued); // We can replace the blocker with a different blocker. - env(signers(alice, 2, {{bob}, {charlie}, {daria}}), ticket::use(tkt + 0), fee(baseFee * 2.6), queued); + env(signers(alice, 2, {{bob}, {charlie}, {daria}}), + ticket::use(tkt + 0), + fee(baseFee * 2.6), + queued); // Prove that the queue is still blocked. env(noop(alice), ter(telCAN_NOT_QUEUE_BLOCKED)); @@ -1905,7 +1955,8 @@ public: Env env( *this, makeConfig( - {{"minimum_txn_in_ledger_standalone", "3"}}, {{"account_reserve", "200"}, {"owner_reserve", "50"}})); + {{"minimum_txn_in_ledger_standalone", "3"}}, + {{"account_reserve", "200"}, {"owner_reserve", "50"}})); auto alice = Account("alice"); auto charlie = Account("charlie"); @@ -2256,7 +2307,8 @@ public: env.memoize("carol"); { auto const jtx = env.jt(offer_cancel(alice, 3), seq(5), fee(10)); - auto const pf = preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); + auto const pf = + preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); BEAST_EXPECT(pf.ter == tesSUCCESS); BEAST_EXPECT(!pf.consequences.isBlocker()); BEAST_EXPECT(pf.consequences.fee() == drops(10)); @@ -2267,7 +2319,8 @@ public: auto USD = alice["USD"]; auto const jtx = env.jt(trust("carol", USD(50000000)), seq(1), fee(10)); - auto const pf = preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); + auto const pf = + preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); BEAST_EXPECT(pf.ter == tesSUCCESS); BEAST_EXPECT(!pf.consequences.isBlocker()); BEAST_EXPECT(pf.consequences.fee() == drops(10)); @@ -2276,7 +2329,8 @@ public: { auto const jtx = env.jt(ticket::create(alice, 1), seq(1), fee(10)); - auto const pf = preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); + auto const pf = + preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); BEAST_EXPECT(pf.ter == tesSUCCESS); BEAST_EXPECT(!pf.consequences.isBlocker()); BEAST_EXPECT(pf.consequences.fee() == drops(10)); @@ -2399,10 +2453,13 @@ public: auto fee = env.rpc("fee"); - if (BEAST_EXPECT(fee.isMember(jss::result)) && BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) + if (BEAST_EXPECT(fee.isMember(jss::result)) && + BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) { auto const& result = fee[jss::result]; - BEAST_EXPECT(result.isMember(jss::ledger_current_index) && result[jss::ledger_current_index] == 3); + BEAST_EXPECT( + result.isMember(jss::ledger_current_index) && + result[jss::ledger_current_index] == 3); BEAST_EXPECT(result.isMember(jss::current_ledger_size)); BEAST_EXPECT(result.isMember(jss::current_queue_size)); BEAST_EXPECT(result.isMember(jss::expected_ledger_size)); @@ -2425,10 +2482,13 @@ public: fee = env.rpc("fee"); - if (BEAST_EXPECT(fee.isMember(jss::result)) && BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) + if (BEAST_EXPECT(fee.isMember(jss::result)) && + BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) { auto const& result = fee[jss::result]; - BEAST_EXPECT(result.isMember(jss::ledger_current_index) && result[jss::ledger_current_index] == 4); + BEAST_EXPECT( + result.isMember(jss::ledger_current_index) && + result[jss::ledger_current_index] == 4); BEAST_EXPECT(result.isMember(jss::current_ledger_size)); BEAST_EXPECT(result.isMember(jss::current_queue_size)); BEAST_EXPECT(result.isMember(jss::expected_ledger_size)); @@ -2549,7 +2609,9 @@ public: testcase("full queue gap handling"); auto cfg = makeConfig( - {{"minimum_txn_in_ledger_standalone", "1"}, {"ledgers_in_queue", "10"}, {"maximum_txn_per_account", "11"}}); + {{"minimum_txn_in_ledger_standalone", "1"}, + {"ledgers_in_queue", "10"}, + {"maximum_txn_per_account", "11"}}); cfg->FEES.reference_fee = 10; Env env(*this, std::move(cfg)); @@ -2828,13 +2890,15 @@ public: { // account_info without the "queue" argument. auto const info = env.rpc("json", "account_info", to_string(withoutQueue)); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); BEAST_EXPECT(!info[jss::result].isMember(jss::queue_data)); } { // account_info with the "queue" argument. auto const info = env.rpc("json", "account_info", to_string(withQueue)); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& result = info[jss::result]; BEAST_EXPECT(result.isMember(jss::queue_data)); auto const& queue_data = result[jss::queue_data]; @@ -2854,7 +2918,8 @@ public: { auto const info = env.rpc("json", "account_info", to_string(withQueue)); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& result = info[jss::result]; BEAST_EXPECT(result.isMember(jss::queue_data)); auto const& queue_data = result[jss::queue_data]; @@ -2877,7 +2942,8 @@ public: { auto const info = env.rpc("json", "account_info", to_string(withQueue)); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& result = info[jss::result]; auto const& data = result[jss::account_data]; BEAST_EXPECT(result.isMember(jss::queue_data)); @@ -2931,7 +2997,8 @@ public: { auto const info = env.rpc("json", "account_info", to_string(withQueue)); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& result = info[jss::result]; auto const& data = result[jss::account_data]; BEAST_EXPECT(result.isMember(jss::queue_data)); @@ -2977,12 +3044,14 @@ public: } } - envs(noop(alice), fee(baseFee * 10), seq(none), ter(telCAN_NOT_QUEUE_BLOCKED))(submitParams); + envs( + noop(alice), fee(baseFee * 10), seq(none), ter(telCAN_NOT_QUEUE_BLOCKED))(submitParams); checkMetrics(*this, env, 1, 8, 5, 4); { auto const info = env.rpc("json", "account_info", to_string(withQueue)); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& result = info[jss::result]; auto const& data = result[jss::account_data]; BEAST_EXPECT(result.isMember(jss::queue_data)); @@ -3045,7 +3114,8 @@ public: { auto const info = env.rpc("json", "account_info", to_string(withQueue)); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& result = info[jss::result]; BEAST_EXPECT(result.isMember(jss::queue_data)); auto const& queue_data = result[jss::queue_data]; @@ -3076,7 +3146,8 @@ public: { auto const server_info = env.rpc("server_info"); - BEAST_EXPECT(server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); + BEAST_EXPECT( + server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); auto const& info = server_info[jss::result][jss::info]; BEAST_EXPECT(info.isMember(jss::load_factor) && info[jss::load_factor] == 1); BEAST_EXPECT(!info.isMember(jss::load_factor_server)); @@ -3089,12 +3160,17 @@ public: auto const& state = server_state[jss::result][jss::state]; BEAST_EXPECT(state.isMember(jss::load_factor) && state[jss::load_factor] == 256); BEAST_EXPECT(state.isMember(jss::load_base) && state[jss::load_base] == 256); - BEAST_EXPECT(state.isMember(jss::load_factor_server) && state[jss::load_factor_server] == 256); BEAST_EXPECT( - state.isMember(jss::load_factor_fee_escalation) && state[jss::load_factor_fee_escalation] == 256); - BEAST_EXPECT(state.isMember(jss::load_factor_fee_queue) && state[jss::load_factor_fee_queue] == 256); + state.isMember(jss::load_factor_server) && state[jss::load_factor_server] == 256); BEAST_EXPECT( - state.isMember(jss::load_factor_fee_reference) && state[jss::load_factor_fee_reference] == 256); + state.isMember(jss::load_factor_fee_escalation) && + state[jss::load_factor_fee_escalation] == 256); + BEAST_EXPECT( + state.isMember(jss::load_factor_fee_queue) && + state[jss::load_factor_fee_queue] == 256); + BEAST_EXPECT( + state.isMember(jss::load_factor_fee_reference) && + state[jss::load_factor_fee_reference] == 256); } checkMetrics(*this, env, 0, 6, 0, 3); @@ -3110,16 +3186,20 @@ public: { auto const server_info = env.rpc("server_info"); - BEAST_EXPECT(server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); + BEAST_EXPECT( + server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); auto const& info = server_info[jss::result][jss::info]; // Avoid double rounding issues by comparing to a range. BEAST_EXPECT( - info.isMember(jss::load_factor) && info[jss::load_factor] > 888.88 && info[jss::load_factor] < 888.89); - BEAST_EXPECT(info.isMember(jss::load_factor_server) && info[jss::load_factor_server] == 1); + info.isMember(jss::load_factor) && info[jss::load_factor] > 888.88 && + info[jss::load_factor] < 888.89); + BEAST_EXPECT( + info.isMember(jss::load_factor_server) && info[jss::load_factor_server] == 1); BEAST_EXPECT(!info.isMember(jss::load_factor_local)); BEAST_EXPECT(!info.isMember(jss::load_factor_net)); BEAST_EXPECT( - info.isMember(jss::load_factor_fee_escalation) && info[jss::load_factor_fee_escalation] > 888.88 && + info.isMember(jss::load_factor_fee_escalation) && + info[jss::load_factor_fee_escalation] > 888.88 && info[jss::load_factor_fee_escalation] < 888.89); } { @@ -3127,19 +3207,25 @@ public: auto const& state = server_state[jss::result][jss::state]; BEAST_EXPECT(state.isMember(jss::load_factor) && state[jss::load_factor] == 227555); BEAST_EXPECT(state.isMember(jss::load_base) && state[jss::load_base] == 256); - BEAST_EXPECT(state.isMember(jss::load_factor_server) && state[jss::load_factor_server] == 256); BEAST_EXPECT( - state.isMember(jss::load_factor_fee_escalation) && state[jss::load_factor_fee_escalation] == 227555); - BEAST_EXPECT(state.isMember(jss::load_factor_fee_queue) && state[jss::load_factor_fee_queue] == 256); + state.isMember(jss::load_factor_server) && state[jss::load_factor_server] == 256); BEAST_EXPECT( - state.isMember(jss::load_factor_fee_reference) && state[jss::load_factor_fee_reference] == 256); + state.isMember(jss::load_factor_fee_escalation) && + state[jss::load_factor_fee_escalation] == 227555); + BEAST_EXPECT( + state.isMember(jss::load_factor_fee_queue) && + state[jss::load_factor_fee_queue] == 256); + BEAST_EXPECT( + state.isMember(jss::load_factor_fee_reference) && + state[jss::load_factor_fee_reference] == 256); } env.app().getFeeTrack().setRemoteFee(256000); { auto const server_info = env.rpc("server_info"); - BEAST_EXPECT(server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); + BEAST_EXPECT( + server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); auto const& info = server_info[jss::result][jss::info]; // Avoid double rounding issues by comparing to a range. BEAST_EXPECT(info.isMember(jss::load_factor) && info[jss::load_factor] == 1000); @@ -3147,7 +3233,8 @@ public: BEAST_EXPECT(!info.isMember(jss::load_factor_local)); BEAST_EXPECT(info.isMember(jss::load_factor_net) && info[jss::load_factor_net] == 1000); BEAST_EXPECT( - info.isMember(jss::load_factor_fee_escalation) && info[jss::load_factor_fee_escalation] > 888.88 && + info.isMember(jss::load_factor_fee_escalation) && + info[jss::load_factor_fee_escalation] > 888.88 && info[jss::load_factor_fee_escalation] < 888.89); } { @@ -3155,12 +3242,18 @@ public: auto const& state = server_state[jss::result][jss::state]; BEAST_EXPECT(state.isMember(jss::load_factor) && state[jss::load_factor] == 256000); BEAST_EXPECT(state.isMember(jss::load_base) && state[jss::load_base] == 256); - BEAST_EXPECT(state.isMember(jss::load_factor_server) && state[jss::load_factor_server] == 256000); BEAST_EXPECT( - state.isMember(jss::load_factor_fee_escalation) && state[jss::load_factor_fee_escalation] == 227555); - BEAST_EXPECT(state.isMember(jss::load_factor_fee_queue) && state[jss::load_factor_fee_queue] == 256); + state.isMember(jss::load_factor_server) && + state[jss::load_factor_server] == 256000); BEAST_EXPECT( - state.isMember(jss::load_factor_fee_reference) && state[jss::load_factor_fee_reference] == 256); + state.isMember(jss::load_factor_fee_escalation) && + state[jss::load_factor_fee_escalation] == 227555); + BEAST_EXPECT( + state.isMember(jss::load_factor_fee_queue) && + state[jss::load_factor_fee_queue] == 256); + BEAST_EXPECT( + state.isMember(jss::load_factor_fee_reference) && + state[jss::load_factor_fee_reference] == 256); } env.app().getFeeTrack().setRemoteFee(256); @@ -3172,11 +3265,13 @@ public: { auto const server_info = env.rpc("server_info"); - BEAST_EXPECT(server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); + BEAST_EXPECT( + server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); auto const& info = server_info[jss::result][jss::info]; // Avoid double rounding issues by comparing to a range. BEAST_EXPECT( - info.isMember(jss::load_factor) && info[jss::load_factor] > 888.88 && info[jss::load_factor] < 888.89); + info.isMember(jss::load_factor) && info[jss::load_factor] > 888.88 && + info[jss::load_factor] < 888.89); // There can be a race between LoadManager lowering the fee, // and the call to server_info, so check a wide range. // The important thing is that it's not 1. @@ -3188,7 +3283,8 @@ public: info[jss::load_factor_local] < 2.4415); BEAST_EXPECT(!info.isMember(jss::load_factor_net)); BEAST_EXPECT( - info.isMember(jss::load_factor_fee_escalation) && info[jss::load_factor_fee_escalation] > 888.88 && + info.isMember(jss::load_factor_fee_escalation) && + info[jss::load_factor_fee_escalation] > 888.88 && info[jss::load_factor_fee_escalation] < 888.89); } { @@ -3203,17 +3299,22 @@ public: state.isMember(jss::load_factor_server) && state[jss::load_factor_server] >= 320 && state[jss::load_factor_server] <= 625); BEAST_EXPECT( - state.isMember(jss::load_factor_fee_escalation) && state[jss::load_factor_fee_escalation] == 227555); - BEAST_EXPECT(state.isMember(jss::load_factor_fee_queue) && state[jss::load_factor_fee_queue] == 256); + state.isMember(jss::load_factor_fee_escalation) && + state[jss::load_factor_fee_escalation] == 227555); BEAST_EXPECT( - state.isMember(jss::load_factor_fee_reference) && state[jss::load_factor_fee_reference] == 256); + state.isMember(jss::load_factor_fee_queue) && + state[jss::load_factor_fee_queue] == 256); + BEAST_EXPECT( + state.isMember(jss::load_factor_fee_reference) && + state[jss::load_factor_fee_reference] == 256); } env.close(); { auto const server_info = env.rpc("server_info"); - BEAST_EXPECT(server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); + BEAST_EXPECT( + server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); auto const& info = server_info[jss::result][jss::info]; // Avoid double rounding issues by comparing to a range. @@ -3221,7 +3322,8 @@ public: // and the call to server_info, so check a wide range. // The important thing is that it's not 1. BEAST_EXPECT( - info.isMember(jss::load_factor) && info[jss::load_factor] > 1.245 && info[jss::load_factor] < 2.4415); + info.isMember(jss::load_factor) && info[jss::load_factor] > 1.245 && + info[jss::load_factor] < 2.4415); BEAST_EXPECT(!info.isMember(jss::load_factor_server)); BEAST_EXPECT( info.isMember(jss::load_factor_local) && info[jss::load_factor_local] > 1.245 && @@ -3233,7 +3335,8 @@ public: auto const server_state = env.rpc("server_state"); auto const& state = server_state[jss::result][jss::state]; BEAST_EXPECT( - state.isMember(jss::load_factor) && state[jss::load_factor] >= 320 && state[jss::load_factor] <= 625); + state.isMember(jss::load_factor) && state[jss::load_factor] >= 320 && + state[jss::load_factor] <= 625); BEAST_EXPECT(state.isMember(jss::load_base) && state[jss::load_base] == 256); // There can be a race between LoadManager lowering the fee, // and the call to server_info, so check a wide range. @@ -3242,10 +3345,14 @@ public: state.isMember(jss::load_factor_server) && state[jss::load_factor_server] >= 320 && state[jss::load_factor_server] <= 625); BEAST_EXPECT( - state.isMember(jss::load_factor_fee_escalation) && state[jss::load_factor_fee_escalation] == 256); - BEAST_EXPECT(state.isMember(jss::load_factor_fee_queue) && state[jss::load_factor_fee_queue] == 256); + state.isMember(jss::load_factor_fee_escalation) && + state[jss::load_factor_fee_escalation] == 256); BEAST_EXPECT( - state.isMember(jss::load_factor_fee_reference) && state[jss::load_factor_fee_reference] == 256); + state.isMember(jss::load_factor_fee_queue) && + state[jss::load_factor_fee_queue] == 256); + BEAST_EXPECT( + state.isMember(jss::load_factor_fee_reference) && + state[jss::load_factor_fee_reference] == 256); } } @@ -3276,20 +3383,26 @@ public: // First transaction establishes the messaging using namespace std::chrono_literals; BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && jv[jss::load_factor] == 256 && - jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && - jv[jss::load_factor_server] == 256 && jv.isMember(jss::load_factor_fee_escalation) && - jv[jss::load_factor_fee_escalation] == 256 && jv.isMember(jss::load_factor_fee_queue) && - jv[jss::load_factor_fee_queue] == 256 && jv.isMember(jss::load_factor_fee_reference) && + return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && + jv[jss::load_factor] == 256 && jv.isMember(jss::load_base) && + jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && + jv[jss::load_factor_server] == 256 && + jv.isMember(jss::load_factor_fee_escalation) && + jv[jss::load_factor_fee_escalation] == 256 && + jv.isMember(jss::load_factor_fee_queue) && jv[jss::load_factor_fee_queue] == 256 && + jv.isMember(jss::load_factor_fee_reference) && jv[jss::load_factor_fee_reference] == 256; })); // Last transaction escalates the fee BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && jv[jss::load_factor] == 227555 && - jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && - jv[jss::load_factor_server] == 256 && jv.isMember(jss::load_factor_fee_escalation) && - jv[jss::load_factor_fee_escalation] == 227555 && jv.isMember(jss::load_factor_fee_queue) && - jv[jss::load_factor_fee_queue] == 256 && jv.isMember(jss::load_factor_fee_reference) && + return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && + jv[jss::load_factor] == 227555 && jv.isMember(jss::load_base) && + jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && + jv[jss::load_factor_server] == 256 && + jv.isMember(jss::load_factor_fee_escalation) && + jv[jss::load_factor_fee_escalation] == 227555 && + jv.isMember(jss::load_factor_fee_queue) && jv[jss::load_factor_fee_queue] == 256 && + jv.isMember(jss::load_factor_fee_reference) && jv[jss::load_factor_fee_reference] == 256; })); @@ -3297,11 +3410,14 @@ public: // Closing ledger should publish a status update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && jv[jss::load_factor] == 256 && - jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && - jv[jss::load_factor_server] == 256 && jv.isMember(jss::load_factor_fee_escalation) && - jv[jss::load_factor_fee_escalation] == 256 && jv.isMember(jss::load_factor_fee_queue) && - jv[jss::load_factor_fee_queue] == 256 && jv.isMember(jss::load_factor_fee_reference) && + return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && + jv[jss::load_factor] == 256 && jv.isMember(jss::load_base) && + jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && + jv[jss::load_factor_server] == 256 && + jv.isMember(jss::load_factor_fee_escalation) && + jv[jss::load_factor_fee_escalation] == 256 && + jv.isMember(jss::load_factor_fee_queue) && jv[jss::load_factor_fee_queue] == 256 && + jv.isMember(jss::load_factor_fee_reference) && jv[jss::load_factor_fee_reference] == 256; })); @@ -3323,37 +3439,47 @@ public: // Last transaction escalates the fee BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && jv[jss::load_factor] == 200000 && - jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && - jv[jss::load_factor_server] == 256 && jv.isMember(jss::load_factor_fee_escalation) && - jv[jss::load_factor_fee_escalation] == 200000 && jv.isMember(jss::load_factor_fee_queue) && - jv[jss::load_factor_fee_queue] == 256 && jv.isMember(jss::load_factor_fee_reference) && + return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && + jv[jss::load_factor] == 200000 && jv.isMember(jss::load_base) && + jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && + jv[jss::load_factor_server] == 256 && + jv.isMember(jss::load_factor_fee_escalation) && + jv[jss::load_factor_fee_escalation] == 200000 && + jv.isMember(jss::load_factor_fee_queue) && jv[jss::load_factor_fee_queue] == 256 && + jv.isMember(jss::load_factor_fee_reference) && jv[jss::load_factor_fee_reference] == 256; })); env.close(); // Ledger close publishes with escalated fees for queued transactions BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && jv[jss::load_factor] == 184320 && - jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && - jv[jss::load_factor_server] == 256 && jv.isMember(jss::load_factor_fee_escalation) && - jv[jss::load_factor_fee_escalation] == 184320 && jv.isMember(jss::load_factor_fee_queue) && - jv[jss::load_factor_fee_queue] == 256 && jv.isMember(jss::load_factor_fee_reference) && + return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && + jv[jss::load_factor] == 184320 && jv.isMember(jss::load_base) && + jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && + jv[jss::load_factor_server] == 256 && + jv.isMember(jss::load_factor_fee_escalation) && + jv[jss::load_factor_fee_escalation] == 184320 && + jv.isMember(jss::load_factor_fee_queue) && jv[jss::load_factor_fee_queue] == 256 && + jv.isMember(jss::load_factor_fee_reference) && jv[jss::load_factor_fee_reference] == 256; })); env.close(); // ledger close clears queue so fee is back to normal BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && jv[jss::load_factor] == 256 && - jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && - jv[jss::load_factor_server] == 256 && jv.isMember(jss::load_factor_fee_escalation) && - jv[jss::load_factor_fee_escalation] == 256 && jv.isMember(jss::load_factor_fee_queue) && - jv[jss::load_factor_fee_queue] == 256 && jv.isMember(jss::load_factor_fee_reference) && + return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && + jv[jss::load_factor] == 256 && jv.isMember(jss::load_base) && + jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && + jv[jss::load_factor_server] == 256 && + jv.isMember(jss::load_factor_fee_escalation) && + jv[jss::load_factor_fee_escalation] == 256 && + jv.isMember(jss::load_factor_fee_queue) && jv[jss::load_factor_fee_queue] == 256 && + jv.isMember(jss::load_factor_fee_reference) && jv[jss::load_factor_fee_reference] == 256; })); - BEAST_EXPECT(!wsc->findMsg(1s, [&](auto const& jv) { return jv[jss::type] == "serverStatus"; })); + BEAST_EXPECT( + !wsc->findMsg(1s, [&](auto const& jv) { return jv[jss::type] == "serverStatus"; })); auto jv = wsc->invoke("unsubscribe", stream); BEAST_EXPECT(jv[jss::status] == "success"); @@ -3376,7 +3502,8 @@ public: fillQueue(env, alice); auto calcTotalFee = [&](std::int64_t alreadyPaid, - std::optional numToClear = std::nullopt) -> std::uint64_t { + std::optional numToClear = + std::nullopt) -> std::uint64_t { auto totalFactor = 0; auto const metrics = env.app().getTxQ().getMetrics(*env.current()); if (!numToClear) @@ -3932,7 +4059,13 @@ public: auto const baseFee = env.current()->fees().base.drops(); // We're very close to the flag ledger. Fill the ledger. fillQueue(env, alice); - checkMetrics(*this, env, 0, ledgersInQueue * expectedPerLedger, expectedPerLedger + 1, expectedPerLedger); + checkMetrics( + *this, + env, + 0, + ledgersInQueue * expectedPerLedger, + expectedPerLedger + 1, + expectedPerLedger); // Fill everyone's queues. auto seqAlice = env.seq(alice); @@ -3944,7 +4077,9 @@ public: // Use fees to guarantee order int txFee{static_cast(baseFee * 9)}; - auto prepareFee = [&](uint64_t multiplier) { return fee(txFee - multiplier * baseFee / 10); }; + auto prepareFee = [&](uint64_t multiplier) { + return fee(txFee - multiplier * baseFee / 10); + }; uint64_t multiplier = 0; for (int i = 0; i < 10; ++i) @@ -3958,7 +4093,12 @@ public: } std::size_t expectedInQueue = multiplier; checkMetrics( - *this, env, expectedInQueue, ledgersInQueue * expectedPerLedger, expectedPerLedger + 1, expectedPerLedger); + *this, + env, + expectedInQueue, + ledgersInQueue * expectedPerLedger, + expectedPerLedger + 1, + expectedPerLedger); // The next close should cause the in-ledger amendments to change. // Alice's queued transactions have a cached PreflightResult @@ -3973,20 +4113,36 @@ public: { env.close(closeDuration); auto expectedInLedger = expectedInQueue; - expectedInQueue = (expectedInQueue > expectedPerLedger + 2 ? expectedInQueue - (expectedPerLedger + 2) : 0); + expectedInQueue = + (expectedInQueue > expectedPerLedger + 2 ? expectedInQueue - (expectedPerLedger + 2) + : 0); expectedInLedger -= expectedInQueue; ++expectedPerLedger; checkMetrics( - *this, env, expectedInQueue, ledgersInQueue * expectedPerLedger, expectedInLedger, expectedPerLedger); + *this, + env, + expectedInQueue, + ledgersInQueue * expectedPerLedger, + expectedInLedger, + expectedPerLedger); { auto const expectedPerAccount = expectedInQueue / 6; auto const expectedRemainder = expectedInQueue % 6; BEAST_EXPECT(env.seq(alice) == seqAlice - expectedPerAccount); - BEAST_EXPECT(env.seq(bob) == seqBob - expectedPerAccount - (expectedRemainder > 4 ? 1 : 0)); - BEAST_EXPECT(env.seq(carol) == seqCarol - expectedPerAccount - (expectedRemainder > 3 ? 1 : 0)); - BEAST_EXPECT(env.seq(daria) == seqDaria - expectedPerAccount - (expectedRemainder > 2 ? 1 : 0)); - BEAST_EXPECT(env.seq(ellie) == seqEllie - expectedPerAccount - (expectedRemainder > 1 ? 1 : 0)); - BEAST_EXPECT(env.seq(fiona) == seqFiona - expectedPerAccount - (expectedRemainder > 0 ? 1 : 0)); + BEAST_EXPECT( + env.seq(bob) == seqBob - expectedPerAccount - (expectedRemainder > 4 ? 1 : 0)); + BEAST_EXPECT( + env.seq(carol) == + seqCarol - expectedPerAccount - (expectedRemainder > 3 ? 1 : 0)); + BEAST_EXPECT( + env.seq(daria) == + seqDaria - expectedPerAccount - (expectedRemainder > 2 ? 1 : 0)); + BEAST_EXPECT( + env.seq(ellie) == + seqEllie - expectedPerAccount - (expectedRemainder > 1 ? 1 : 0)); + BEAST_EXPECT( + env.seq(fiona) == + seqFiona - expectedPerAccount - (expectedRemainder > 0 ? 1 : 0)); } } while (expectedInQueue > 0); } @@ -4338,22 +4494,29 @@ public: { auto const fee = env.rpc("fee"); - if (BEAST_EXPECT(fee.isMember(jss::result)) && BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) + if (BEAST_EXPECT(fee.isMember(jss::result)) && + BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) { auto const& result = fee[jss::result]; BEAST_EXPECT(result.isMember(jss::levels)); auto const& levels = result[jss::levels]; - BEAST_EXPECT(levels.isMember(jss::median_level) && levels[jss::median_level] == "128000"); - BEAST_EXPECT(levels.isMember(jss::minimum_level) && levels[jss::minimum_level] == "256"); - BEAST_EXPECT(levels.isMember(jss::open_ledger_level) && levels[jss::open_ledger_level] == "256"); - BEAST_EXPECT(levels.isMember(jss::reference_level) && levels[jss::reference_level] == "256"); + BEAST_EXPECT( + levels.isMember(jss::median_level) && levels[jss::median_level] == "128000"); + BEAST_EXPECT( + levels.isMember(jss::minimum_level) && levels[jss::minimum_level] == "256"); + BEAST_EXPECT( + levels.isMember(jss::open_ledger_level) && + levels[jss::open_ledger_level] == "256"); + BEAST_EXPECT( + levels.isMember(jss::reference_level) && levels[jss::reference_level] == "256"); auto const& drops = result[jss::drops]; BEAST_EXPECT(drops.isMember(jss::base_fee) && drops[jss::base_fee] == "0"); BEAST_EXPECT(drops.isMember(jss::median_fee) && drops[jss::median_fee] == "0"); BEAST_EXPECT(drops.isMember(jss::minimum_fee) && drops[jss::minimum_fee] == "0"); - BEAST_EXPECT(drops.isMember(jss::open_ledger_fee) && drops[jss::open_ledger_fee] == "0"); + BEAST_EXPECT( + drops.isMember(jss::open_ledger_fee) && drops[jss::open_ledger_fee] == "0"); } } @@ -4389,22 +4552,29 @@ public: { auto const fee = env.rpc("fee"); - if (BEAST_EXPECT(fee.isMember(jss::result)) && BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) + if (BEAST_EXPECT(fee.isMember(jss::result)) && + BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) { auto const& result = fee[jss::result]; BEAST_EXPECT(result.isMember(jss::levels)); auto const& levels = result[jss::levels]; - BEAST_EXPECT(levels.isMember(jss::median_level) && levels[jss::median_level] == "128000"); - BEAST_EXPECT(levels.isMember(jss::minimum_level) && levels[jss::minimum_level] == "256"); - BEAST_EXPECT(levels.isMember(jss::open_ledger_level) && levels[jss::open_ledger_level] == "355555"); - BEAST_EXPECT(levels.isMember(jss::reference_level) && levels[jss::reference_level] == "256"); + BEAST_EXPECT( + levels.isMember(jss::median_level) && levels[jss::median_level] == "128000"); + BEAST_EXPECT( + levels.isMember(jss::minimum_level) && levels[jss::minimum_level] == "256"); + BEAST_EXPECT( + levels.isMember(jss::open_ledger_level) && + levels[jss::open_ledger_level] == "355555"); + BEAST_EXPECT( + levels.isMember(jss::reference_level) && levels[jss::reference_level] == "256"); auto const& drops = result[jss::drops]; BEAST_EXPECT(drops.isMember(jss::base_fee) && drops[jss::base_fee] == "0"); BEAST_EXPECT(drops.isMember(jss::median_fee) && drops[jss::median_fee] == "0"); BEAST_EXPECT(drops.isMember(jss::minimum_fee) && drops[jss::minimum_fee] == "0"); - BEAST_EXPECT(drops.isMember(jss::open_ledger_fee) && drops[jss::open_ledger_fee] == "1389"); + BEAST_EXPECT( + drops.isMember(jss::open_ledger_fee) && drops[jss::open_ledger_fee] == "1389"); } } diff --git a/src/test/app/ValidatorKeys_test.cpp b/src/test/app/ValidatorKeys_test.cpp index c688b2661f..32f6305a37 100644 --- a/src/test/app/ValidatorKeys_test.cpp +++ b/src/test/app/ValidatorKeys_test.cpp @@ -64,7 +64,8 @@ public: beast::Journal journal{env.app().journal("ValidatorKeys_test")}; // Keys/ID when using [validation_seed] - SecretKey const seedSecretKey = generateSecretKey(KeyType::secp256k1, *parseBase58(seed)); + SecretKey const seedSecretKey = + generateSecretKey(KeyType::secp256k1, *parseBase58(seed)); PublicKey const seedPublicKey = derivePublicKey(KeyType::secp256k1, seedSecretKey); NodeID const seedNodeID = calcNodeID(seedPublicKey); diff --git a/src/test/app/ValidatorList_test.cpp b/src/test/app/ValidatorList_test.cpp index 4955686966..61d71b1883 100644 --- a/src/test/app/ValidatorList_test.cpp +++ b/src/test/app/ValidatorList_test.cpp @@ -42,7 +42,12 @@ private: } static std::string - makeManifestString(PublicKey const& pk, SecretKey const& sk, PublicKey const& spk, SecretKey const& ssk, int seq) + makeManifestString( + PublicKey const& pk, + SecretKey const& sk, + PublicKey const& spk, + SecretKey const& ssk, + int seq) { STObject st(sfGeneric); st[sfSequence] = seq; @@ -86,7 +91,8 @@ private: return { masterPublic, signingKeys.first, - base64_encode(makeManifestString(masterPublic, secret, signingKeys.first, signingKeys.second, 1))}; + base64_encode(makeManifestString( + masterPublic, secret, signingKeys.first, signingKeys.second, 1))}; } std::string @@ -96,16 +102,16 @@ private: std::size_t validUntil, std::optional validFrom = {}) { - std::string data = - "{\"sequence\":" + std::to_string(sequence) + ",\"expiration\":" + std::to_string(validUntil); + std::string data = "{\"sequence\":" + std::to_string(sequence) + + ",\"expiration\":" + std::to_string(validUntil); if (validFrom) data += ",\"effective\":" + std::to_string(*validFrom); data += ",\"validators\":["; for (auto const& val : validators) { - data += "{\"validation_public_key\":\"" + strHex(val.masterPublic) + "\",\"manifest\":\"" + val.manifest + - "\"},"; + data += "{\"validation_public_key\":\"" + strHex(val.masterPublic) + + "\",\"manifest\":\"" + val.manifest + "\"},"; } data.pop_back(); @@ -154,13 +160,22 @@ private: auto& app = env.app(); { auto trustedKeys = std::make_unique( - manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifests, + manifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); BEAST_EXPECT(trustedKeys->quorum() == 1); } { std::size_t minQuorum = 0; auto trustedKeys = std::make_unique( - manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal, minQuorum); + manifests, + manifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal, + minQuorum); BEAST_EXPECT(trustedKeys->quorum() == minQuorum); } } @@ -181,8 +196,8 @@ private: auto const localMasterSecret = randomSecretKey(); auto const localMasterPublic = derivePublicKey(KeyType::ed25519, localMasterSecret); - std::string const cfgManifest( - makeManifestString(localMasterPublic, localMasterSecret, localSigningPublicOuter, localSigningSecret, 1)); + std::string const cfgManifest(makeManifestString( + localMasterPublic, localMasterSecret, localSigningPublicOuter, localSigningSecret, 1)); auto format = [](PublicKey const& publicKey, char const* comment = nullptr) { auto ret = toBase58(TokenType::NodePublic, publicKey); @@ -213,17 +228,23 @@ private: { ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifests, + manifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); // Correct (empty) configuration BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, emptyCfgPublishers)); // load local validator key with or without manifest - BEAST_EXPECT(trustedKeys->load(localSigningPublicOuter, emptyCfgKeys, emptyCfgPublishers)); + BEAST_EXPECT( + trustedKeys->load(localSigningPublicOuter, emptyCfgKeys, emptyCfgPublishers)); BEAST_EXPECT(trustedKeys->listed(localSigningPublicOuter)); manifests.applyManifest(*deserializeManifest(cfgManifest)); - BEAST_EXPECT(trustedKeys->load(localSigningPublicOuter, emptyCfgKeys, emptyCfgPublishers)); + BEAST_EXPECT( + trustedKeys->load(localSigningPublicOuter, emptyCfgKeys, emptyCfgPublishers)); BEAST_EXPECT(trustedKeys->listed(localMasterPublic)); BEAST_EXPECT(trustedKeys->listed(localSigningPublicOuter)); @@ -232,7 +253,11 @@ private: // load should add validator keys from config ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifests, + manifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); BEAST_EXPECT(trustedKeys->load({}, cfgKeys, emptyCfgPublishers)); @@ -243,7 +268,8 @@ private: auto const masterNode1 = randomMasterKey(); auto const masterNode2 = randomMasterKey(); - std::vector cfgMasterKeys({format(masterNode1), format(masterNode2, " Comment")}); + std::vector cfgMasterKeys( + {format(masterNode1), format(masterNode2, " Comment")}); BEAST_EXPECT(trustedKeys->load({}, cfgMasterKeys, emptyCfgPublishers)); BEAST_EXPECT(trustedKeys->listed(masterNode1)); BEAST_EXPECT(trustedKeys->listed(masterNode2)); @@ -254,16 +280,22 @@ private: // load terminates when encountering an invalid entry auto const goodKey = randomNode(); - BEAST_EXPECT(!trustedKeys->load({}, {format(randomNode(), "!"), format(goodKey)}, emptyCfgPublishers)); + BEAST_EXPECT(!trustedKeys->load( + {}, {format(randomNode(), "!"), format(goodKey)}, emptyCfgPublishers)); BEAST_EXPECT(!trustedKeys->listed(goodKey)); } { // local validator key on config list ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifests, + manifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); - auto const localSigningPublic = parseBase58(TokenType::NodePublic, cfgKeys.front()); + auto const localSigningPublic = + parseBase58(TokenType::NodePublic, cfgKeys.front()); BEAST_EXPECT(trustedKeys->load(*localSigningPublic, cfgKeys, emptyCfgPublishers)); @@ -276,7 +308,11 @@ private: // local validator key not on config list ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifests, + manifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); auto const localSigningPublic = randomNode(); BEAST_EXPECT(trustedKeys->load(localSigningPublic, cfgKeys, emptyCfgPublishers)); @@ -290,7 +326,11 @@ private: // local validator key (with manifest) not on config list ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifests, + manifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); manifests.applyManifest(*deserializeManifest(cfgManifest)); @@ -305,7 +345,11 @@ private: { ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifests, + manifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); // load should reject invalid validator list signing keys std::vector badPublishers({"NotASigningKey"}); @@ -335,9 +379,14 @@ private: { ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifests, + manifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); - std::vector keys({randomMasterKey(), randomMasterKey(), randomMasterKey(), randomMasterKey()}); + std::vector keys( + {randomMasterKey(), randomMasterKey(), randomMasterKey(), randomMasterKey()}); std::vector cfgPublishers; for (auto const& key : keys) cfgPublishers.push_back(strHex(key)); @@ -354,7 +403,11 @@ private: ManifestCache valManifests; ManifestCache pubManifests; auto trustedKeys = std::make_unique( - valManifests, pubManifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + valManifests, + pubManifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); auto const pubRevokedSecret = randomSecretKey(); auto const pubRevokedPublic = derivePublicKey(KeyType::ed25519, pubRevokedSecret); @@ -372,7 +425,8 @@ private: auto legitKey1 = randomMasterKey(); auto legitKey2 = randomMasterKey(); - std::vector cfgPublishers = {strHex(pubRevokedPublic), strHex(legitKey1), strHex(legitKey2)}; + std::vector cfgPublishers = { + strHex(pubRevokedPublic), strHex(legitKey1), strHex(legitKey2)}; BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers)); BEAST_EXPECT(!trustedKeys->trustedPublisher(pubRevokedPublic)); @@ -387,7 +441,11 @@ private: ManifestCache valManifests; ManifestCache pubManifests; auto trustedKeys = std::make_unique( - valManifests, pubManifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + valManifests, + pubManifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); auto const pubRevokedSecret = randomSecretKey(); auto const pubRevokedPublic = derivePublicKey(KeyType::ed25519, pubRevokedSecret); @@ -422,51 +480,56 @@ private: std::string const siteUri = "testApplyList.test"; - auto checkAvailable = [this]( - auto const& trustedKeys, - auto const& hexPublic, - auto const& manifest, - auto const version, - std::vector> const& expected) { - auto const available = trustedKeys->getAvailable(hexPublic); + auto checkAvailable = + [this]( + auto const& trustedKeys, + auto const& hexPublic, + auto const& manifest, + auto const version, + std::vector> const& expected) { + auto const available = trustedKeys->getAvailable(hexPublic); - BEAST_EXPECT(!version || available); - if (available) - { - auto const& a = *available; - BEAST_EXPECT(a[jss::public_key] == hexPublic); - BEAST_EXPECT(a[jss::manifest] == manifest); - // Because multiple lists were processed, the version was - // overridden - BEAST_EXPECT(a[jss::version] == version); - if (version == 1) + BEAST_EXPECT(!version || available); + if (available) { - BEAST_EXPECT(expected.size() == 1); - BEAST_EXPECT(a[jss::blob] == expected[0].first); - BEAST_EXPECT(a[jss::signature] == expected[0].second); - BEAST_EXPECT(!a.isMember(jss::blobs_v2)); - } - else if (BEAST_EXPECT(a.isMember(jss::blobs_v2))) - { - BEAST_EXPECT(!a.isMember(jss::blob)); - BEAST_EXPECT(!a.isMember(jss::signature)); - auto const& blobs_v2 = a[jss::blobs_v2]; - BEAST_EXPECT(blobs_v2.isArray() && blobs_v2.size() == expected.size()); - - for (unsigned int i = 0; i < expected.size(); ++i) + auto const& a = *available; + BEAST_EXPECT(a[jss::public_key] == hexPublic); + BEAST_EXPECT(a[jss::manifest] == manifest); + // Because multiple lists were processed, the version was + // overridden + BEAST_EXPECT(a[jss::version] == version); + if (version == 1) { - BEAST_EXPECT(blobs_v2[i][jss::blob] == expected[i].first); - BEAST_EXPECT(blobs_v2[i][jss::signature] == expected[i].second); + BEAST_EXPECT(expected.size() == 1); + BEAST_EXPECT(a[jss::blob] == expected[0].first); + BEAST_EXPECT(a[jss::signature] == expected[0].second); + BEAST_EXPECT(!a.isMember(jss::blobs_v2)); + } + else if (BEAST_EXPECT(a.isMember(jss::blobs_v2))) + { + BEAST_EXPECT(!a.isMember(jss::blob)); + BEAST_EXPECT(!a.isMember(jss::signature)); + auto const& blobs_v2 = a[jss::blobs_v2]; + BEAST_EXPECT(blobs_v2.isArray() && blobs_v2.size() == expected.size()); + + for (unsigned int i = 0; i < expected.size(); ++i) + { + BEAST_EXPECT(blobs_v2[i][jss::blob] == expected[i].first); + BEAST_EXPECT(blobs_v2[i][jss::signature] == expected[i].second); + } } } - } - }; + }; ManifestCache manifests; jtx::Env env(*this); auto& app = env.app(); auto trustedKeys = std::make_unique( - manifests, manifests, env.app().timeKeeper(), app.config().legacy("database_path"), env.journal); + manifests, + manifests, + env.app().timeKeeper(), + app.config().legacy("database_path"), + env.journal); auto expectTrusted = [this, &trustedKeys](std::vector const& list) { for (auto const& val : list) @@ -488,8 +551,8 @@ private: auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); auto const hexPublic = strHex(publisherPublic.begin(), publisherPublic.end()); auto const pubSigningKeys1 = randomKeyPair(KeyType::secp256k1); - auto const manifest1 = base64_encode( - makeManifestString(publisherPublic, publisherSecret, pubSigningKeys1.first, pubSigningKeys1.second, 1)); + auto const manifest1 = base64_encode(makeManifestString( + publisherPublic, publisherSecret, pubSigningKeys1.first, pubSigningKeys1.second, 1)); std::vector cfgKeys1({strHex(publisherPublic)}); std::vector emptyCfgKeys; @@ -515,7 +578,8 @@ private: env.timeKeeper().set(env.timeKeeper().now() + 1s); auto const version = 1; auto const sequence1 = 1; - auto const expiredblob = makeList(lists.at(1), sequence1, env.timeKeeper().now().time_since_epoch().count()); + auto const expiredblob = + makeList(lists.at(1), sequence1, env.timeKeeper().now().time_since_epoch().count()); auto const expiredSig = signList(expiredblob, pubSigningKeys1); NetClock::time_point const validUntil = env.timeKeeper().now() + 3600s; @@ -524,7 +588,8 @@ private: auto const sig2 = signList(blob2, pubSigningKeys1); checkResult( - trustedKeys->applyLists(manifest1, version, {{expiredblob, expiredSig, {}}, {blob2, sig2, {}}}, siteUri), + trustedKeys->applyLists( + manifest1, version, {{expiredblob, expiredSig, {}}, {blob2, sig2, {}}}, siteUri), publisherPublic, ListDisposition::expired, ListDisposition::accepted); @@ -539,18 +604,25 @@ private: auto const effective7 = validUntil - 60s; auto const expiration7 = effective7 + 3600s; auto const blob7 = makeList( - lists.at(7), sequence7, expiration7.time_since_epoch().count(), effective7.time_since_epoch().count()); + lists.at(7), + sequence7, + expiration7.time_since_epoch().count(), + effective7.time_since_epoch().count()); auto const sig7 = signList(blob7, pubSigningKeys1); auto const sequence8 = 8; auto const effective8 = expiration7 - 60s; auto const expiration8 = effective8 + 3600s; auto const blob8 = makeList( - lists.at(8), sequence8, expiration8.time_since_epoch().count(), effective8.time_since_epoch().count()); + lists.at(8), + sequence8, + expiration8.time_since_epoch().count(), + effective8.time_since_epoch().count()); auto const sig8 = signList(blob8, pubSigningKeys1); checkResult( - trustedKeys->applyLists(manifest1, version2, {{blob7, sig7, {}}, {blob8, sig8, {}}}, siteUri), + trustedKeys->applyLists( + manifest1, version2, {{blob7, sig7, {}}, {blob8, sig8, {}}}, siteUri), publisherPublic, ListDisposition::pending, ListDisposition::pending); @@ -563,7 +635,10 @@ private: auto const effective6 = effective7 - 60s; auto const expiration6 = effective6 + 3600s; auto const blob6 = makeList( - lists.at(6), sequence6, expiration6.time_since_epoch().count(), effective6.time_since_epoch().count()); + lists.at(6), + sequence6, + expiration6.time_since_epoch().count(), + effective6.time_since_epoch().count()); auto const sig6 = signList(blob6, pubSigningKeys1); // Process future list that is overridden by a later list @@ -571,11 +646,15 @@ private: auto const effective6a = effective6 + 60s; auto const expiration6a = effective6a + 3600s; auto const blob6a = makeList( - lists.at(5), sequence6a, expiration6a.time_since_epoch().count(), effective6a.time_since_epoch().count()); + lists.at(5), + sequence6a, + expiration6a.time_since_epoch().count(), + effective6a.time_since_epoch().count()); auto const sig6a = signList(blob6a, pubSigningKeys1); checkResult( - trustedKeys->applyLists(manifest1, version, {{blob6a, sig6a, {}}, {blob6, sig6, {}}}, siteUri), + trustedKeys->applyLists( + manifest1, version, {{blob6a, sig6a, {}}, {blob6, sig6, {}}}, siteUri), publisherPublic, ListDisposition::pending, ListDisposition::pending); @@ -586,7 +665,8 @@ private: // Do not apply re-process lists known future sequence numbers checkResult( - trustedKeys->applyLists(manifest1, version, {{blob7, sig7, {}}, {blob6, sig6, {}}}, siteUri), + trustedKeys->applyLists( + manifest1, version, {{blob7, sig7, {}}, {blob6, sig6, {}}}, siteUri), publisherPublic, ListDisposition::known_sequence, ListDisposition::known_sequence); @@ -604,14 +684,17 @@ private: checkResult( trustedKeys->applyLists( - base64_encode("not a manifest"), version, {{blob7, sig7, {}}, {blob6, sig6, {}}}, siteUri), + base64_encode("not a manifest"), + version, + {{blob7, sig7, {}}, {blob6, sig6, {}}}, + siteUri), publisherPublic, ListDisposition::invalid, ListDisposition::invalid); // do not use list from untrusted publisher - auto const untrustedManifest = base64_encode( - makeManifestString(randomMasterKey(), publisherSecret, pubSigningKeys1.first, pubSigningKeys1.second, 1)); + auto const untrustedManifest = base64_encode(makeManifestString( + randomMasterKey(), publisherSecret, pubSigningKeys1.first, pubSigningKeys1.second, 1)); checkResult( trustedKeys->applyLists(untrustedManifest, version, {{blob2, sig2, {}}}, siteUri), @@ -645,11 +728,16 @@ private: // Note that blob6a is not present, because it was dropped during // processing checkAvailable( - trustedKeys, hexPublic, manifest1, 2, {{blob3, sig3}, {blob6, sig6}, {blob7, sig7}, {blob8, sig8}}); + trustedKeys, + hexPublic, + manifest1, + 2, + {{blob3, sig3}, {blob6, sig6}, {blob7, sig7}, {blob8, sig8}}); // do not re-apply lists with past or current sequence numbers checkResult( - trustedKeys->applyLists(manifest1, version, {{blob2, sig2, {}}, {blob3, sig3, {}}}, siteUri), + trustedKeys->applyLists( + manifest1, version, {{blob2, sig2, {}}, {blob3, sig3, {}}}, siteUri), publisherPublic, ListDisposition::stale, ListDisposition::same_sequence); @@ -657,8 +745,8 @@ private: // apply list with new publisher key updated by manifest. Also send some // old lists along with the old manifest auto const pubSigningKeys2 = randomKeyPair(KeyType::secp256k1); - auto manifest2 = base64_encode( - makeManifestString(publisherPublic, publisherSecret, pubSigningKeys2.first, pubSigningKeys2.second, 2)); + auto manifest2 = base64_encode(makeManifestString( + publisherPublic, publisherSecret, pubSigningKeys2.first, pubSigningKeys2.second, 2)); auto const sequence4 = 4; auto const blob4 = makeList(lists.at(4), sequence4, validUntil.time_since_epoch().count()); @@ -666,7 +754,10 @@ private: checkResult( trustedKeys->applyLists( - manifest2, version, {{blob2, sig2, manifest1}, {blob3, sig3, manifest1}, {blob4, sig4, {}}}, siteUri), + manifest2, + version, + {{blob2, sig2, manifest1}, {blob3, sig3, manifest1}, {blob4, sig4, {}}}, + siteUri), publisherPublic, ListDisposition::stale, ListDisposition::accepted); @@ -676,7 +767,11 @@ private: expectTrusted(lists.at(4)); checkAvailable( - trustedKeys, hexPublic, manifest2, 2, {{blob4, sig4}, {blob6, sig6}, {blob7, sig7}, {blob8, sig8}}); + trustedKeys, + hexPublic, + manifest2, + 2, + {{blob4, sig4}, {blob6, sig6}, {blob7, sig7}, {blob8, sig8}}); auto const sequence5 = 5; auto const blob5 = makeList(lists.at(5), sequence5, validUntil.time_since_epoch().count()); @@ -694,7 +789,8 @@ private: // Reprocess the pending list, but the signature is no longer valid checkResult( - trustedKeys->applyLists(manifest1, version, {{blob7, sig7, {}}, {blob8, sig8, {}}}, siteUri), + trustedKeys->applyLists( + manifest1, version, {{blob7, sig7, {}}, {blob8, sig8, {}}}, siteUri), publisherPublic, ListDisposition::invalid, ListDisposition::invalid); @@ -707,12 +803,17 @@ private: // updateTrusted. Note that the timekeeper is NOT moved, so the close // time will be ahead of the test's wall clock trustedKeys->updateTrusted( - {}, effective6 + 1s, env.app().getOPs(), env.app().overlay(), env.app().getHashRouter()); + {}, + effective6 + 1s, + env.app().getOPs(), + env.app().overlay(), + env.app().getHashRouter()); expectUntrusted(lists.at(3)); expectTrusted(lists.at(6)); - checkAvailable(trustedKeys, hexPublic, manifest2, 2, {{blob6, sig6}, {blob7, sig7}, {blob8, sig8}}); + checkAvailable( + trustedKeys, hexPublic, manifest2, 2, {{blob6, sig6}, {blob7, sig7}, {blob8, sig8}}); // Automatically rotate the LAST pending list using updateTrusted, // bypassing blob7. Note that the timekeeper IS moved, so the provided @@ -720,7 +821,11 @@ private: // clock is used. env.timeKeeper().set(effective8); trustedKeys->updateTrusted( - {}, effective8 + 1s, env.app().getOPs(), env.app().overlay(), env.app().getHashRouter()); + {}, + effective8 + 1s, + env.app().getOPs(), + env.app().overlay(), + env.app().getHashRouter()); expectUntrusted(lists.at(6)); expectUntrusted(lists.at(7)); @@ -735,7 +840,8 @@ private: auto const sig8_2 = signList(blob8, pubSigningKeys2); checkResult( - trustedKeys->applyLists(manifest2, version, {{blob8, sig8, manifest1}, {blob8, sig8_2, {}}}, siteUri), + trustedKeys->applyLists( + manifest2, version, {{blob8, sig8, manifest1}, {blob8, sig8_2, {}}}, siteUri), publisherPublic, ListDisposition::invalid, ListDisposition::same_sequence); @@ -781,14 +887,18 @@ private: jtx::Env env(*this); auto& app = env.app(); auto trustedKeys = std::make_unique( - manifests, manifests, env.app().timeKeeper(), app.config().legacy("database_path"), env.journal); + manifests, + manifests, + env.app().timeKeeper(), + app.config().legacy("database_path"), + env.journal); auto const publisherSecret = randomSecretKey(); auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); auto const hexPublic = strHex(publisherPublic.begin(), publisherPublic.end()); auto const pubSigningKeys1 = randomKeyPair(KeyType::secp256k1); - auto const manifest = base64_encode( - makeManifestString(publisherPublic, publisherSecret, pubSigningKeys1.first, pubSigningKeys1.second, 1)); + auto const manifest = base64_encode(makeManifestString( + publisherPublic, publisherSecret, pubSigningKeys1.first, pubSigningKeys1.second, 1)); std::vector cfgKeys1({strHex(publisherPublic)}); std::vector emptyCfgKeys; @@ -904,7 +1014,11 @@ private: jtx::Env env(*this); auto& app = env.app(); auto trustedKeysOuter = std::make_unique( - manifestsOuter, manifestsOuter, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifestsOuter, + manifestsOuter, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); std::vector cfgPublishersOuter; hash_set activeValidatorsOuter; @@ -992,10 +1106,11 @@ private: BEAST_EXPECT(!trustedKeysOuter->trusted(signingPublic1)); // Should trust the ephemeral signing key from the applied manifest - auto m1 = deserializeManifest( - makeManifestString(masterPublic, masterPrivate, signingPublic1, signingKeys1.second, 1)); + auto m1 = deserializeManifest(makeManifestString( + masterPublic, masterPrivate, signingPublic1, signingKeys1.second, 1)); - BEAST_EXPECT(manifestsOuter.applyManifest(std::move(*m1)) == ManifestDisposition::accepted); + BEAST_EXPECT( + manifestsOuter.applyManifest(std::move(*m1)) == ManifestDisposition::accepted); BEAST_EXPECT(trustedKeysOuter->listed(masterPublic)); BEAST_EXPECT(trustedKeysOuter->trusted(masterPublic)); BEAST_EXPECT(trustedKeysOuter->listed(signingPublic1)); @@ -1005,9 +1120,10 @@ private: // from the newest applied manifest auto const signingKeys2 = randomKeyPair(KeyType::secp256k1); auto const signingPublic2 = signingKeys2.first; - auto m2 = deserializeManifest( - makeManifestString(masterPublic, masterPrivate, signingPublic2, signingKeys2.second, 2)); - BEAST_EXPECT(manifestsOuter.applyManifest(std::move(*m2)) == ManifestDisposition::accepted); + auto m2 = deserializeManifest(makeManifestString( + masterPublic, masterPrivate, signingPublic2, signingKeys2.second, 2)); + BEAST_EXPECT( + manifestsOuter.applyManifest(std::move(*m2)) == ManifestDisposition::accepted); BEAST_EXPECT(trustedKeysOuter->listed(masterPublic)); BEAST_EXPECT(trustedKeysOuter->trusted(masterPublic)); BEAST_EXPECT(trustedKeysOuter->listed(signingPublic2)); @@ -1022,7 +1138,8 @@ private: auto mMax = deserializeManifest(makeRevocationString(masterPublic, masterPrivate)); BEAST_EXPECT(mMax->revoked()); - BEAST_EXPECT(manifestsOuter.applyManifest(std::move(*mMax)) == ManifestDisposition::accepted); + BEAST_EXPECT( + manifestsOuter.applyManifest(std::move(*mMax)) == ManifestDisposition::accepted); BEAST_EXPECT(manifestsOuter.getSigningKey(masterPublic) == masterPublic); BEAST_EXPECT(manifestsOuter.revoked(masterPublic)); @@ -1052,7 +1169,11 @@ private: // Make quorum unattainable if lists from any publishers are // unavailable auto trustedKeys = std::make_unique( - manifestsOuter, manifestsOuter, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifestsOuter, + manifestsOuter, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); auto const publisherSecret = randomSecretKey(); auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); @@ -1075,7 +1196,11 @@ private: // Trust explicitly listed validators also when list threshold is // higher than 1 auto trustedKeys = std::make_unique( - manifestsOuter, manifestsOuter, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifestsOuter, + manifestsOuter, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); auto const masterPrivate = randomSecretKey(); auto const masterPublic = derivePublicKey(KeyType::ed25519, masterPrivate); std::vector cfgKeys({toBase58(TokenType::NodePublic, masterPublic)}); @@ -1084,7 +1209,8 @@ private: auto const publisher1Public = derivePublicKey(KeyType::ed25519, publisher1Secret); auto const publisher2Secret = randomSecretKey(); auto const publisher2Public = derivePublicKey(KeyType::ed25519, publisher2Secret); - std::vector cfgPublishers({strHex(publisher1Public), strHex(publisher2Public)}); + std::vector cfgPublishers( + {strHex(publisher1Public), strHex(publisher2Public)}); BEAST_EXPECT(trustedKeys->load({}, cfgKeys, cfgPublishers, std::size_t(2))); @@ -1104,7 +1230,12 @@ private: std::size_t const minQuorum = 1; ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal, minQuorum); + manifests, + manifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal, + minQuorum); std::size_t n = 10; std::vector cfgKeys; @@ -1161,14 +1292,19 @@ private: auto const publisherKeys = randomKeyPair(KeyType::secp256k1); auto const pubSigningKeys = randomKeyPair(KeyType::secp256k1); auto const manifest = base64_encode(makeManifestString( - publisherKeys.first, publisherKeys.second, pubSigningKeys.first, pubSigningKeys.second, 1)); + publisherKeys.first, + publisherKeys.second, + pubSigningKeys.first, + pubSigningKeys.second, + 1)); std::vector cfgKeys({strHex(publisherKeys.first)}); BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgKeys)); std::vector list({randomValidator(), randomValidator()}); - hash_set activeValidators(asNodeIDs({list[0].masterPublic, list[1].masterPublic})); + hash_set activeValidators( + asNodeIDs({list[0].masterPublic, list[1].masterPublic})); // do not apply expired list auto const version = 1; @@ -1180,7 +1316,8 @@ private: BEAST_EXPECT( ListDisposition::accepted == - trustedKeys->applyLists(manifest, version, {{blob, sig, {}}}, siteUri).bestDisposition()); + trustedKeys->applyLists(manifest, version, {{blob, sig, {}}}, siteUri) + .bestDisposition()); TrustChanges changes = trustedKeys->updateTrusted( activeValidators, @@ -1220,7 +1357,8 @@ private: BEAST_EXPECT( ListDisposition::accepted == - trustedKeys->applyLists(manifest, version, {{blob2, sig2, {}}}, siteUri).bestDisposition()); + trustedKeys->applyLists(manifest, version, {{blob2, sig2, {}}}, siteUri) + .bestDisposition()); changes = trustedKeys->updateTrusted( activeValidators, @@ -1229,7 +1367,8 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(changes.removed.empty()); - BEAST_EXPECT(changes.added == asNodeIDs({list2[0].masterPublic, list2[1].masterPublic})); + BEAST_EXPECT( + changes.added == asNodeIDs({list2[0].masterPublic, list2[1].masterPublic})); for (Validator const& val : list2) { BEAST_EXPECT(trustedKeys->trusted(val.masterPublic)); @@ -1242,7 +1381,11 @@ private: { // Test 1-9 configured validators auto trustedKeys = std::make_unique( - manifestsOuter, manifestsOuter, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifestsOuter, + manifestsOuter, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); std::vector cfgPublishers; hash_set activeValidators; @@ -1274,7 +1417,11 @@ private: { // Test 2-9 configured validators as validator auto trustedKeys = std::make_unique( - manifestsOuter, manifestsOuter, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifestsOuter, + manifestsOuter, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); auto const localKey = randomNode(); std::vector cfgPublishers; @@ -1313,7 +1460,11 @@ private: // Trusted set should include all validators from multiple lists ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifests, + manifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); hash_set activeValidators; std::vector valKeys; @@ -1329,7 +1480,9 @@ private: // locals[1]: from 1 to maxKeys - 2 // locals[2]: from 2 to maxKeys constexpr static int publishers = 3; - std::array, publishers> + std::array< + std::pair, + publishers> locals = { std::make_pair(valKeys.cbegin(), valKeys.cend() - 4), std::make_pair(valKeys.cbegin() + 1, valKeys.cend() - 2), @@ -1341,7 +1494,11 @@ private: auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); auto const pubSigningKeys = randomKeyPair(KeyType::secp256k1); auto const manifest = base64_encode(makeManifestString( - publisherPublic, publisherSecret, pubSigningKeys.first, pubSigningKeys.second, 1)); + publisherPublic, + publisherSecret, + pubSigningKeys.first, + pubSigningKeys.second, + 1)); std::vector cfgPublishers({strHex(publisherPublic)}); std::vector emptyCfgKeys; @@ -1354,12 +1511,14 @@ private: using namespace std::chrono_literals; NetClock::time_point const validUntil = env.timeKeeper().now() + 3600s; std::vector localKeys{locals[i].first, locals[i].second}; - auto const blob = makeList(localKeys, sequence, validUntil.time_since_epoch().count()); + auto const blob = + makeList(localKeys, sequence, validUntil.time_since_epoch().count()); auto const sig = signList(blob, pubSigningKeys); BEAST_EXPECT( ListDisposition::accepted == - trustedKeys->applyLists(manifest, version, {{blob, sig, {}}}, siteUri).bestDisposition()); + trustedKeys->applyLists(manifest, version, {{blob, sig, {}}}, siteUri) + .bestDisposition()); }; // Apply multiple published lists @@ -1389,7 +1548,11 @@ private: // Trusted set should include validators from intersection of lists ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifests, + manifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); hash_set activeValidators; std::vector valKeys; @@ -1407,43 +1570,55 @@ private: // intersection of at least 2: same as locals[1] // intersection when 1 is dropped: from 2 to maxKeys - 4 constexpr static int publishers = 3; - std::array, publishers> + std::array< + std::pair, + publishers> locals = { std::make_pair(valKeys.cbegin(), valKeys.cend() - 4), std::make_pair(valKeys.cbegin() + 1, valKeys.cend() - 2), std::make_pair(valKeys.cbegin() + 2, valKeys.cend()), }; - auto addPublishedList = [&, this]( - int i, NetClock::time_point& validUntil1, NetClock::time_point& validUntil2) { - auto const publisherSecret = randomSecretKey(); - auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); - auto const pubSigningKeys = randomKeyPair(KeyType::secp256k1); - auto const manifest = base64_encode(makeManifestString( - publisherPublic, publisherSecret, pubSigningKeys.first, pubSigningKeys.second, 1)); + auto addPublishedList = + [&, this]( + int i, NetClock::time_point& validUntil1, NetClock::time_point& validUntil2) { + auto const publisherSecret = randomSecretKey(); + auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); + auto const pubSigningKeys = randomKeyPair(KeyType::secp256k1); + auto const manifest = base64_encode(makeManifestString( + publisherPublic, + publisherSecret, + pubSigningKeys.first, + pubSigningKeys.second, + 1)); - std::vector cfgPublishers({strHex(publisherPublic)}); - std::vector emptyCfgKeys; + std::vector cfgPublishers({strHex(publisherPublic)}); + std::vector emptyCfgKeys; - BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers)); + BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers)); - auto const version = 1; - auto const sequence = 1; - using namespace std::chrono_literals; - // Want to drop 1 sooner - NetClock::time_point const validUntil = env.timeKeeper().now() + (i == 2 ? 120s : i == 1 ? 60s : 3600s); - if (i == 1) - validUntil1 = validUntil; - else if (i == 2) - validUntil2 = validUntil; - std::vector localKeys{locals[i].first, locals[i].second}; - auto const blob = makeList(localKeys, sequence, validUntil.time_since_epoch().count()); - auto const sig = signList(blob, pubSigningKeys); + auto const version = 1; + auto const sequence = 1; + using namespace std::chrono_literals; + // Want to drop 1 sooner + NetClock::time_point const validUntil = env.timeKeeper().now() + + (i == 2 ? 120s + : i == 1 ? 60s + : 3600s); + if (i == 1) + validUntil1 = validUntil; + else if (i == 2) + validUntil2 = validUntil; + std::vector localKeys{locals[i].first, locals[i].second}; + auto const blob = + makeList(localKeys, sequence, validUntil.time_since_epoch().count()); + auto const sig = signList(blob, pubSigningKeys); - BEAST_EXPECT( - ListDisposition::accepted == - trustedKeys->applyLists(manifest, version, {{blob, sig, {}}}, siteUri).bestDisposition()); - }; + BEAST_EXPECT( + ListDisposition::accepted == + trustedKeys->applyLists(manifest, version, {{blob, sig, {}}}, siteUri) + .bestDisposition()); + }; // Apply multiple published lists // validUntil1 is expiration time for locals[1] @@ -1550,13 +1725,19 @@ private: jtx::Env env(*this); auto& app = env.app(); - auto toStr = [](PublicKey const& publicKey) { return toBase58(TokenType::NodePublic, publicKey); }; + auto toStr = [](PublicKey const& publicKey) { + return toBase58(TokenType::NodePublic, publicKey); + }; // Config listed keys { ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + manifests, + manifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); // Empty list has no expiration BEAST_EXPECT(trustedKeys->expires() == std::nullopt); @@ -1564,7 +1745,9 @@ private: // Config listed keys have maximum expiry PublicKey localCfgListed = randomNode(); trustedKeys->load({}, {toStr(localCfgListed)}, {}); - BEAST_EXPECT(trustedKeys->expires() && trustedKeys->expires().value() == NetClock::time_point::max()); + BEAST_EXPECT( + trustedKeys->expires() && + trustedKeys->expires().value() == NetClock::time_point::max()); BEAST_EXPECT(trustedKeys->listed(localCfgListed)); } @@ -1572,7 +1755,11 @@ private: { ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, manifests, env.app().timeKeeper(), app.config().legacy("database_path"), env.journal); + manifests, + manifests, + env.app().timeKeeper(), + app.config().legacy("database_path"), + env.journal); std::vector validators = {randomValidator()}; hash_set activeValidators; @@ -1594,7 +1781,11 @@ private: auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); auto const pubSigningKeys = randomKeyPair(KeyType::secp256k1); auto const manifest = base64_encode(makeManifestString( - publisherPublic, publisherSecret, pubSigningKeys.first, pubSigningKeys.second, 1)); + publisherPublic, + publisherSecret, + pubSigningKeys.first, + pubSigningKeys.second, + 1)); std::vector cfgPublishers({strHex(publisherPublic)}); std::vector emptyCfgKeys; @@ -1604,7 +1795,8 @@ private: auto const version = 2; auto const sequence1 = 1; NetClock::time_point const expiration1 = env.timeKeeper().now() + 1800s; - auto const blob1 = makeList(validators, sequence1, expiration1.time_since_epoch().count()); + auto const blob1 = + makeList(validators, sequence1, expiration1.time_since_epoch().count()); auto const sig1 = signList(blob1, pubSigningKeys); NetClock::time_point const effective2 = expiration1 - 300s; @@ -1651,7 +1843,9 @@ private: ListDisposition::pending, ListDisposition::accepted); // We now have loaded both lists, so expiration is known - BEAST_EXPECT(trustedKeys->expires() && trustedKeys->expires().value() == prep1.expirations.back()); + BEAST_EXPECT( + trustedKeys->expires() && + trustedKeys->expires().value() == prep1.expirations.back()); // Advance past the first list's LAST validFrom date. It remains // the earliest validUntil, while rotating in the second list @@ -1663,7 +1857,9 @@ private: env.app().getOPs(), env.app().overlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->expires() && trustedKeys->expires().value() == prep1.expirations.back()); + BEAST_EXPECT( + trustedKeys->expires() && + trustedKeys->expires().value() == prep1.expirations.back()); BEAST_EXPECT(!changes.added.empty()); BEAST_EXPECT(changes.removed.empty()); } @@ -1678,7 +1874,9 @@ private: env.app().getOPs(), env.app().overlay(), env.app().getHashRouter()); - BEAST_EXPECT(trustedKeys->expires() && trustedKeys->expires().value() == prep1.expirations.back()); + BEAST_EXPECT( + trustedKeys->expires() && + trustedKeys->expires().value() == prep1.expirations.back()); BEAST_EXPECT(changes.added.empty()); BEAST_EXPECT(changes.removed.empty()); } @@ -1693,7 +1891,8 @@ private: ManifestCache manifests; auto createValidatorList = - [&](std::uint32_t vlSize, std::optional minimumQuorum = {}) -> std::shared_ptr { + [&](std::uint32_t vlSize, + std::optional minimumQuorum = {}) -> std::shared_ptr { auto trustedKeys = std::make_shared( manifests, manifests, @@ -1720,7 +1919,8 @@ private: env.app().getOPs(), env.app().overlay(), env.app().getHashRouter()); - if (minimumQuorum == trustedKeys->quorum() || trustedKeys->quorum() == std::ceil(cfgKeys.size() * 0.8f)) + if (minimumQuorum == trustedKeys->quorum() || + trustedKeys->quorum() == std::ceil(cfgKeys.size() * 0.8f)) return trustedKeys; } return nullptr; @@ -1771,7 +1971,8 @@ private: env.app().getHashRouter()); BEAST_EXPECT( validators->quorum() == - static_cast(std::ceil(std::max((us - nUnlSize) * 0.8f, us * 0.6f)))); + static_cast( + std::ceil(std::max((us - nUnlSize) * 0.8f, us * 0.6f)))); } } } @@ -1956,7 +2157,9 @@ private: auto start = buffer.begin(); auto end = buffer.end(); std::vector slice(start, end); - buffers.commit(boost::asio::buffer_copy(buffers.prepare(slice.size()), boost::asio::buffer(slice))); + buffers.commit( + boost::asio::buffer_copy( + buffers.prepare(slice.size()), boost::asio::buffer(slice))); boost::system::error_code ec; auto header = detail::parseMessageHeader(ec, buffers.data(), buffers.size()); @@ -1965,9 +2168,11 @@ private: }; auto extractProtocolMessage1 = [this, &extractHeader](Message& message) { auto [header, buffers] = extractHeader(message); - if (BEAST_EXPECT(header) && BEAST_EXPECT(header->message_type == protocol::mtVALIDATOR_LIST)) + if (BEAST_EXPECT(header) && + BEAST_EXPECT(header->message_type == protocol::mtVALIDATOR_LIST)) { - auto const msg = detail::parseMessageContent(*header, buffers.data()); + auto const msg = + detail::parseMessageContent(*header, buffers.data()); BEAST_EXPECT(msg); return msg; } @@ -1975,91 +2180,102 @@ 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)) + if (BEAST_EXPECT(header) && + BEAST_EXPECT(header->message_type == protocol::mtVALIDATOR_LIST_COLLECTION)) { - auto const msg = - detail::parseMessageContent(*header, buffers.data()); + auto const msg = detail::parseMessageContent( + *header, buffers.data()); BEAST_EXPECT(msg); return msg; } return std::shared_ptr(); }; - auto verifyMessage = [this, manifestCutoff, &extractProtocolMessage1, &extractProtocolMessage2]( - auto const version, - auto const& manifest, - auto const& blobInfos, - auto const& messages, - std::vector>> expectedInfo) { - BEAST_EXPECT(messages.size() == expectedInfo.size()); - auto msgIter = expectedInfo.begin(); - for (auto const& messageWithHash : messages) - { - if (!BEAST_EXPECT(msgIter != expectedInfo.end())) - break; - if (!BEAST_EXPECT(messageWithHash.message)) - continue; - auto const& expectedSeqs = msgIter->second; - auto seqIter = expectedSeqs.begin(); - auto const size = messageWithHash.message->getBuffer(compression::Compressed::Off).size(); - // This size is arbitrary, but shouldn't change - BEAST_EXPECT(size == msgIter->first); - if (expectedSeqs.size() == 1) + auto verifyMessage = + [this, manifestCutoff, &extractProtocolMessage1, &extractProtocolMessage2]( + auto const version, + auto const& manifest, + auto const& blobInfos, + auto const& messages, + std::vector>> expectedInfo) { + BEAST_EXPECT(messages.size() == expectedInfo.size()); + auto msgIter = expectedInfo.begin(); + for (auto const& messageWithHash : messages) { - auto const msg = extractProtocolMessage1(*messageWithHash.message); - auto const expectedVersion = 1; - if (BEAST_EXPECT(msg)) + if (!BEAST_EXPECT(msgIter != expectedInfo.end())) + break; + if (!BEAST_EXPECT(messageWithHash.message)) + continue; + auto const& expectedSeqs = msgIter->second; + auto seqIter = expectedSeqs.begin(); + auto const size = + messageWithHash.message->getBuffer(compression::Compressed::Off).size(); + // This size is arbitrary, but shouldn't change + BEAST_EXPECT(size == msgIter->first); + if (expectedSeqs.size() == 1) { - BEAST_EXPECT(msg->version() == expectedVersion); - if (!BEAST_EXPECT(seqIter != expectedSeqs.end())) - continue; - auto const& expectedBlob = blobInfos.at(*seqIter); - BEAST_EXPECT((*seqIter < manifestCutoff) == !!expectedBlob.manifest); - auto const expectedManifest = - *seqIter < manifestCutoff && expectedBlob.manifest ? *expectedBlob.manifest : manifest; - BEAST_EXPECT(msg->manifest() == expectedManifest); - BEAST_EXPECT(msg->blob() == expectedBlob.blob); - BEAST_EXPECT(msg->signature() == expectedBlob.signature); - ++seqIter; - BEAST_EXPECT(seqIter == expectedSeqs.end()); - - BEAST_EXPECT( - messageWithHash.hash == - sha512Half(expectedManifest, expectedBlob.blob, expectedBlob.signature, expectedVersion)); - } - } - else - { - std::vector hashingBlobs; - hashingBlobs.reserve(msgIter->second.size()); - - auto const msg = extractProtocolMessage2(*messageWithHash.message); - if (BEAST_EXPECT(msg)) - { - BEAST_EXPECT(msg->version() == version); - BEAST_EXPECT(msg->manifest() == manifest); - for (auto const& blobInfo : msg->blobs()) + auto const msg = extractProtocolMessage1(*messageWithHash.message); + auto const expectedVersion = 1; + if (BEAST_EXPECT(msg)) { + BEAST_EXPECT(msg->version() == expectedVersion); if (!BEAST_EXPECT(seqIter != expectedSeqs.end())) - break; + continue; auto const& expectedBlob = blobInfos.at(*seqIter); - hashingBlobs.push_back(expectedBlob); - BEAST_EXPECT(blobInfo.has_manifest() == !!expectedBlob.manifest); - BEAST_EXPECT(blobInfo.has_manifest() == (*seqIter < manifestCutoff)); - - if (*seqIter < manifestCutoff) - BEAST_EXPECT(blobInfo.manifest() == *expectedBlob.manifest); - BEAST_EXPECT(blobInfo.blob() == expectedBlob.blob); - BEAST_EXPECT(blobInfo.signature() == expectedBlob.signature); + BEAST_EXPECT((*seqIter < manifestCutoff) == !!expectedBlob.manifest); + auto const expectedManifest = + *seqIter < manifestCutoff && expectedBlob.manifest + ? *expectedBlob.manifest + : manifest; + BEAST_EXPECT(msg->manifest() == expectedManifest); + BEAST_EXPECT(msg->blob() == expectedBlob.blob); + BEAST_EXPECT(msg->signature() == expectedBlob.signature); ++seqIter; + BEAST_EXPECT(seqIter == expectedSeqs.end()); + + BEAST_EXPECT( + messageWithHash.hash == + sha512Half( + expectedManifest, + expectedBlob.blob, + expectedBlob.signature, + expectedVersion)); } - BEAST_EXPECT(seqIter == expectedSeqs.end()); } - BEAST_EXPECT(messageWithHash.hash == sha512Half(manifest, hashingBlobs, version)); + else + { + std::vector hashingBlobs; + hashingBlobs.reserve(msgIter->second.size()); + + auto const msg = extractProtocolMessage2(*messageWithHash.message); + if (BEAST_EXPECT(msg)) + { + BEAST_EXPECT(msg->version() == version); + BEAST_EXPECT(msg->manifest() == manifest); + for (auto const& blobInfo : msg->blobs()) + { + if (!BEAST_EXPECT(seqIter != expectedSeqs.end())) + break; + auto const& expectedBlob = blobInfos.at(*seqIter); + hashingBlobs.push_back(expectedBlob); + BEAST_EXPECT(blobInfo.has_manifest() == !!expectedBlob.manifest); + BEAST_EXPECT( + blobInfo.has_manifest() == (*seqIter < manifestCutoff)); + + if (*seqIter < manifestCutoff) + BEAST_EXPECT(blobInfo.manifest() == *expectedBlob.manifest); + BEAST_EXPECT(blobInfo.blob() == expectedBlob.blob); + BEAST_EXPECT(blobInfo.signature() == expectedBlob.signature); + ++seqIter; + } + BEAST_EXPECT(seqIter == expectedSeqs.end()); + } + BEAST_EXPECT( + messageWithHash.hash == sha512Half(manifest, hashingBlobs, version)); + } + ++msgIter; } - ++msgIter; - } - BEAST_EXPECT(msgIter == expectedInfo.end()); - }; + BEAST_EXPECT(msgIter == expectedInfo.end()); + }; auto verifyBuildMessages = [this]( std::pair const& result, std::size_t expectedSequence, @@ -2102,7 +2318,10 @@ private: // This peer has a VL ahead of our "current" verifyBuildMessages( - ValidatorList::buildValidatorListMessages(1, 8, maxSequence, version, manifest, blobInfos, messages), 0, 0); + ValidatorList::buildValidatorListMessages( + 1, 8, maxSequence, version, manifest, blobInfos, messages), + 0, + 0); BEAST_EXPECT(messages.size() == 0); // Don't repeat the work if messages is populated, even though the @@ -2111,18 +2330,25 @@ private: // real code. messages.emplace_back(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages(1, 3, maxSequence, version, manifest, blobInfos, messages), 5, 0); + ValidatorList::buildValidatorListMessages( + 1, 3, maxSequence, version, manifest, blobInfos, messages), + 5, + 0); BEAST_EXPECT(messages.size() == 1 && !messages.front().message); // Generate a version 1 message messages.clear(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages(1, 3, maxSequence, version, manifest, blobInfos, messages), 5, 1); + ValidatorList::buildValidatorListMessages( + 1, 3, maxSequence, version, manifest, blobInfos, messages), + 5, + 1); if (BEAST_EXPECT(messages.size() == 1) && BEAST_EXPECT(messages.front().message)) { auto const& messageWithHash = messages.front(); auto const msg = extractProtocolMessage1(*messageWithHash.message); - auto const size = messageWithHash.message->getBuffer(compression::Compressed::Off).size(); + auto const size = + messageWithHash.message->getBuffer(compression::Compressed::Off).size(); // This size is arbitrary, but shouldn't change BEAST_EXPECT(size == 108); auto const& expected = blobInfos.at(5); @@ -2133,7 +2359,9 @@ private: BEAST_EXPECT(msg->blob() == expected.blob); BEAST_EXPECT(msg->signature() == expected.signature); } - BEAST_EXPECT(messageWithHash.hash == sha512Half(*expected.manifest, expected.blob, expected.signature, 1)); + BEAST_EXPECT( + messageWithHash.hash == + sha512Half(*expected.manifest, expected.blob, expected.signature, 1)); } // Version 2 @@ -2154,7 +2382,8 @@ private: // real code. messages.emplace_back(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages(2, 3, maxSequence, version, manifest, blobInfos, messages), + ValidatorList::buildValidatorListMessages( + 2, 3, maxSequence, version, manifest, blobInfos, messages), maxSequence, 0); BEAST_EXPECT(messages.size() == 1 && !messages.front().message); @@ -2162,7 +2391,8 @@ private: // Generate a version 2 message. Don't send the current messages.clear(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages(2, 5, maxSequence, version, manifest, blobInfos, messages), + ValidatorList::buildValidatorListMessages( + 2, 5, maxSequence, version, manifest, blobInfos, messages), maxSequence, 4); verifyMessage(version, manifest, blobInfos, messages, {{372, {6, 7, 10, 12}}}); @@ -2172,7 +2402,8 @@ private: // Set a limit that should give two messages messages.clear(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages(2, 5, maxSequence, version, manifest, blobInfos, messages, 300), + ValidatorList::buildValidatorListMessages( + 2, 5, maxSequence, version, manifest, blobInfos, messages, 300), maxSequence, 4); verifyMessage(version, manifest, blobInfos, messages, {{212, {6, 7}}, {192, {10, 12}}}); @@ -2181,27 +2412,41 @@ private: // will split and the other won't messages.clear(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages(2, 5, maxSequence, version, manifest, blobInfos, messages, 200), + ValidatorList::buildValidatorListMessages( + 2, 5, maxSequence, version, manifest, blobInfos, messages, 200), maxSequence, 4); - verifyMessage(version, manifest, blobInfos, messages, {{108, {6}}, {108, {7}}, {192, {10, 12}}}); + verifyMessage( + version, manifest, blobInfos, messages, {{108, {6}}, {108, {7}}, {192, {10, 12}}}); // Set a limit so that all the VLs are sent individually messages.clear(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages(2, 5, maxSequence, version, manifest, blobInfos, messages, 150), + ValidatorList::buildValidatorListMessages( + 2, 5, maxSequence, version, manifest, blobInfos, messages, 150), maxSequence, 4); - verifyMessage(version, manifest, blobInfos, messages, {{108, {6}}, {108, {7}}, {110, {10}}, {110, {12}}}); + verifyMessage( + version, + manifest, + blobInfos, + messages, + {{108, {6}}, {108, {7}}, {110, {10}}, {110, {12}}}); // Set a limit smaller than some of the messages. Because single // messages send regardless, they will all still be sent messages.clear(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages(2, 5, maxSequence, version, manifest, blobInfos, messages, 108), + ValidatorList::buildValidatorListMessages( + 2, 5, maxSequence, version, manifest, blobInfos, messages, 108), maxSequence, 4); - verifyMessage(version, manifest, blobInfos, messages, {{108, {6}}, {108, {7}}, {110, {10}}, {110, {12}}}); + verifyMessage( + version, + manifest, + blobInfos, + messages, + {{108, {6}}, {108, {7}}, {110, {10}}, {110, {12}}}); } void @@ -2243,7 +2488,11 @@ private: std::vector& publishers // out ) -> std::unique_ptr { auto result = std::make_unique( - valManifests, pubManifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + valManifests, + pubManifests, + env.timeKeeper(), + app.config().legacy("database_path"), + env.journal); std::vector cfgPublishers; for (std::size_t i = 0; i < countTotal; ++i) @@ -2260,7 +2509,8 @@ private: pubSigningKeys.first, pubSigningKeys.second, i < countRevoked ? revoked : 1)); - publishers.push_back(Publisher{i < countRevoked, publisherPublic, pubSigningKeys, manifest}); + publishers.push_back( + Publisher{i < countRevoked, publisherPublic, pubSigningKeys, manifest}); } std::vector const emptyCfgKeys; @@ -2268,7 +2518,8 @@ private: if (self) { valManifests.applyManifest(*deserializeManifest(base64_decode(self->manifest))); - BEAST_EXPECT(result->load(self->signingPublic, emptyCfgKeys, cfgPublishers, threshold)); + BEAST_EXPECT( + result->load(self->signingPublic, emptyCfgKeys, cfgPublishers, threshold)); } else { @@ -2279,12 +2530,15 @@ private: { using namespace std::chrono_literals; publishers[i].expiry = env.timeKeeper().now() + (i == countTotal - 1 ? 60s : 3600s); - auto const blob = makeList(valKeys, 1, publishers[i].expiry.time_since_epoch().count()); + auto const blob = + makeList(valKeys, 1, publishers[i].expiry.time_since_epoch().count()); auto const sig = signList(blob, publishers[i].signingKeys); BEAST_EXPECT( - result->applyLists(publishers[i].manifest, 1, {{blob, sig, {}}}, siteUri).bestDisposition() == - (publishers[i].revoked ? ListDisposition::untrusted : ListDisposition::accepted)); + result->applyLists(publishers[i].manifest, 1, {{blob, sig, {}}}, siteUri) + .bestDisposition() == + (publishers[i].revoked ? ListDisposition::untrusted + : ListDisposition::accepted)); } return result; diff --git a/src/test/app/ValidatorSite_test.cpp b/src/test/app/ValidatorSite_test.cpp index 3b616ad5c9..5fc290eda5 100644 --- a/src/test/app/ValidatorSite_test.cpp +++ b/src/test/app/ValidatorSite_test.cpp @@ -175,7 +175,12 @@ private: NetClock::time_point const effective2 = expires - cfg.effectiveOverlap; NetClock::time_point const expires2 = effective2 + cfg.expiresFromNow; item.server = make_TrustedPublisherServer( - env.app().getIOContext(), item.list, expires, {{effective2, expires2}}, cfg.ssl, cfg.serverVersion); + env.app().getIOContext(), + item.list, + expires, + {{effective2, expires2}}, + cfg.ssl, + cfg.serverVersion); std::string pubHex = strHex(item.server->publisherPublic()); cfgPublishers.push_back(pubHex); @@ -228,13 +233,16 @@ private: if (!u.cfg.msg.empty()) { - BEAST_EXPECTS(sink.messages().str().find(u.cfg.msg) != std::string::npos, sink.messages().str()); + BEAST_EXPECTS( + sink.messages().str().find(u.cfg.msg) != std::string::npos, + sink.messages().str()); } if (u.cfg.expectedRefreshMin) { BEAST_EXPECTS( - myStatus[jss::refresh_interval_min].asInt() == u.cfg.expectedRefreshMin, to_string(myStatus)); + myStatus[jss::refresh_interval_min].asInt() == u.cfg.expectedRefreshMin, + to_string(myStatus)); } if (u.cfg.failFetch) @@ -255,7 +263,8 @@ private: void testFileList(std::vector> const& paths) { - testcase << "File list - " << paths[0].first << (paths.size() > 1 ? ", " + paths[1].first : ""); + testcase << "File list - " << paths[0].first + << (paths.size() > 1 ? ", " + paths[1].first : ""); using namespace jtx; @@ -300,10 +309,14 @@ private: for (auto const& vs : jv[jss::validator_sites]) if (vs[jss::uri].asString().find(u.uri) != std::string::npos) myStatus = vs; - BEAST_EXPECTS(myStatus[jss::last_refresh_message].asString().empty() != u.shouldFail, to_string(myStatus)); + BEAST_EXPECTS( + myStatus[jss::last_refresh_message].asString().empty() != u.shouldFail, + to_string(myStatus)); if (u.shouldFail) { - BEAST_EXPECTS(sink.messages().str().find(u.expectMsg) != std::string::npos, sink.messages().str()); + BEAST_EXPECTS( + sink.messages().str().find(u.expectMsg) != std::string::npos, + sink.messages().str()); } } } @@ -323,7 +336,8 @@ private: // Create a file with arbitrary content detail::FileDirGuard hello(*this, "test_val", "helloworld.txt", "Hello, world!"); // Create a file with malformed Json - detail::FileDirGuard json(*this, "test_val", "json.txt", R"json({ "version": 2, "extra" : "value" })json"); + detail::FileDirGuard json( + *this, "test_val", "json.txt", R"json({ "version": 2, "extra" : "value" })json"); auto const goodPath = fullPath(good); auto const helloPath = fullPath(hello); auto const jsonPath = fullPath(json); @@ -365,9 +379,18 @@ public: // UNLs with a "gap" between validUntil of one and validFrom of the // next testFetchList( - good, {{"/validators2", "", ssl, false, false, 1, detail::default_expires, std::chrono::seconds{-90}}}); + good, + {{"/validators2", + "", + ssl, + false, + false, + 1, + detail::default_expires, + std::chrono::seconds{-90}}}); // fetch single site with unending redirect (fails to load) - testFetchList(good, {{"/redirect_forever/301", "Exceeded max redirects", ssl, true, true}}); + testFetchList( + good, {{"/redirect_forever/301", "Exceeded max redirects", ssl, true, true}}); // two that redirect forever testFetchList( good, @@ -375,25 +398,47 @@ public: {"/redirect_forever/308", "Exceeded max redirects", ssl, true, true}}); // one unending redirect, one not testFetchList( - good, {{"/validators", "", ssl}, {"/redirect_forever/302", "Exceeded max redirects", ssl, true, true}}); + good, + {{"/validators", "", ssl}, + {"/redirect_forever/302", "Exceeded max redirects", ssl, true, true}}); // one unending redirect, one not testFetchList( good, - {{"/validators2", "", ssl}, {"/redirect_forever/302", "Exceeded max redirects", ssl, true, true}}); + {{"/validators2", "", ssl}, + {"/redirect_forever/302", "Exceeded max redirects", ssl, true, true}}); // invalid redir Location - testFetchList(good, {{"/redirect_to/ftp://invalid-url/302", "Invalid redirect location", ssl, true, true}}); testFetchList( - good, {{"/redirect_to/file://invalid-url/302", "Invalid redirect location", ssl, true, true}}); + good, + {{"/redirect_to/ftp://invalid-url/302", + "Invalid redirect location", + ssl, + true, + true}}); + testFetchList( + good, + {{"/redirect_to/file://invalid-url/302", + "Invalid redirect location", + ssl, + true, + true}}); // invalid json - testFetchList(good, {{"/validators/bad", "Unable to parse JSON response", ssl, true, true}}); - testFetchList(good, {{"/validators2/bad", "Unable to parse JSON response", ssl, true, true}}); + testFetchList( + good, {{"/validators/bad", "Unable to parse JSON response", ssl, true, true}}); + testFetchList( + good, {{"/validators2/bad", "Unable to parse JSON response", ssl, true, true}}); // error status returned testFetchList(good, {{"/bad-resource", "returned bad status", ssl, true, true}}); // location field missing - testFetchList(good, {{"/redirect_nolo/308", "returned a redirect with no Location", ssl, true, true}}); + testFetchList( + good, + {{"/redirect_nolo/308", "returned a redirect with no Location", ssl, true, true}}); // json fields missing - testFetchList(good, {{"/validators/missing", "Missing fields in JSON response", ssl, true, true}}); - testFetchList(good, {{"/validators2/missing", "Missing fields in JSON response", ssl, true, true}}); + testFetchList( + good, + {{"/validators/missing", "Missing fields in JSON response", ssl, true, true}}); + testFetchList( + good, + {{"/validators2/missing", "Missing fields in JSON response", ssl, true, true}}); // timeout testFetchList(good, {{"/sleep/13", "took too long", ssl, true, true}}); // bad manifest format using known versions @@ -409,9 +454,19 @@ public: testFetchList(good, {{"/validators2", "1 unsupported version", ssl, false, true, 4}}); using namespace std::chrono_literals; // get expired validator list - testFetchList(good, {{"/validators", "Applied 1 expired validator list(s)", ssl, false, false, 1, 0s}}); testFetchList( - good, {{"/validators2", "Applied 1 expired validator list(s)", ssl, false, false, 1, 0s, -1s}}); + good, + {{"/validators", "Applied 1 expired validator list(s)", ssl, false, false, 1, 0s}}); + testFetchList( + good, + {{"/validators2", + "Applied 1 expired validator list(s)", + ssl, + false, + false, + 1, + 0s, + -1s}}); // force an out-of-range validUntil value testFetchList( good, @@ -427,13 +482,27 @@ public: // returns the "best" result, so this looks like a success. testFetchList( good, - {{"/validators2", "", ssl, false, false, 1, std::chrono::seconds{Json::Value::maxInt - 300}, 299s}}); + {{"/validators2", + "", + ssl, + false, + false, + 1, + std::chrono::seconds{Json::Value::maxInt - 300}, + 299s}}); // force an out-of-range validFrom value // The first list is accepted. The second fails. The parser // returns the "best" result, so this looks like a success. testFetchList( good, - {{"/validators2", "", ssl, false, false, 1, std::chrono::seconds{Json::Value::maxInt - 300}, 301s}}); + {{"/validators2", + "", + ssl, + false, + false, + 1, + std::chrono::seconds{Json::Value::maxInt - 300}, + 301s}}); // force an out-of-range validUntil value on _both_ lists testFetchList( good, diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index 5d31c674c0..93ac94d7ce 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -50,7 +50,10 @@ class Vault_test : public beast::unit_test::suite Account dave{"dave"}; auto const testSequence = [&, this]( - std::string const& prefix, Env& env, Vault& vault, PrettyAsset const& asset) { + std::string const& prefix, + Env& env, + Vault& vault, + PrettyAsset const& asset) { auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); tx[sfData] = "AFEED00E"; tx[sfAssetsMaximum] = asset(100).number(); @@ -87,14 +90,16 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " fail to deposit more than assets held"); - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(10000)}); + auto tx = vault.deposit( + {.depositor = depositor, .id = keylet.key, .amount = asset(10000)}); env(tx, ter(tecINSUFFICIENT_FUNDS)); env.close(); } { testcase(prefix + " deposit non-zero amount"); - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); + auto tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx); env.close(); BEAST_EXPECT(env.balance(depositor, shares) == share(50 * scale)); @@ -102,7 +107,8 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " deposit non-zero amount again"); - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); + auto tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx); env.close(); BEAST_EXPECT(env.balance(depositor, shares) == share(100 * scale)); @@ -165,7 +171,8 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " fail to deposit more than maximum"); - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); + auto tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx, ter(tecLIMIT_EXCEEDED)); env.close(); } @@ -180,14 +187,16 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " fail to withdraw more than assets held"); - auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); + auto tx = vault.withdraw( + {.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); env(tx, ter(tecINSUFFICIENT_FUNDS)); env.close(); } { testcase(prefix + " deposit some more"); - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); + auto tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx); env.close(); BEAST_EXPECT(env.balance(depositor, shares) == share(200 * scale)); @@ -196,8 +205,8 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " clawback some"); auto code = asset.raw().native() ? ter(temMALFORMED) : ter(tesSUCCESS); - auto tx = - vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(10)}); + auto tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(10)}); env(tx, code); env.close(); if (!asset.raw().native()) @@ -218,13 +227,17 @@ class Vault_test : public beast::unit_test::suite { auto tx = vault.clawback( - {.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(10)}); + {.issuer = issuer, + .id = keylet.key, + .holder = depositor, + .amount = asset(10)}); env(tx, ter{tecPRECISION_LOSS}); env.close(); } { - auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(10)}); + auto tx = vault.withdraw( + {.depositor = depositor, .id = keylet.key, .amount = asset(10)}); env(tx, ter{tecPRECISION_LOSS}); env.close(); } @@ -234,7 +247,8 @@ class Vault_test : public beast::unit_test::suite if (!asset.raw().native()) { testcase(prefix + " deposit again"); - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(200)}); + auto tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(200)}); env(tx); env.close(); BEAST_EXPECT(env.balance(depositor, shares) == share(200 * scale)); @@ -244,7 +258,8 @@ class Vault_test : public beast::unit_test::suite testcase(prefix + " deposit/withdrawal same or less than fee"); auto const amount = env.current()->fees().base; - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = amount}); + auto tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = amount}); env(tx); env.close(); @@ -262,18 +277,21 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = amount - 1}); + tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = amount - 1}); env(tx); env.close(); - tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = amount - 1}); + tx = vault.withdraw( + {.depositor = depositor, .id = keylet.key, .amount = amount - 1}); env(tx); env.close(); } { testcase(prefix + " fail to withdraw to 3rd party lsfDepositAuth"); - auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); + auto tx = vault.withdraw( + {.depositor = depositor, .id = keylet.key, .amount = asset(100)}); tx[sfDestination] = alice.human(); env(tx, ter{tecNO_PERMISSION}); env.close(); @@ -281,7 +299,8 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " fail to withdraw to zero destination"); - auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); + auto tx = vault.withdraw( + {.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); tx[sfDestination] = "0"; env(tx, ter(temMALFORMED)); env.close(); @@ -290,7 +309,8 @@ class Vault_test : public beast::unit_test::suite if (!asset.raw().native()) { testcase(prefix + " fail to withdraw to 3rd party no authorization"); - auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); + auto tx = vault.withdraw( + {.depositor = depositor, .id = keylet.key, .amount = asset(100)}); tx[sfDestination] = erin.human(); env(tx, ter{asset.raw().holds() ? tecNO_LINE : tecNO_AUTH}); env.close(); @@ -298,7 +318,8 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " fail to withdraw to 3rd party lsfRequireDestTag"); - auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); + auto tx = vault.withdraw( + {.depositor = depositor, .id = keylet.key, .amount = asset(100)}); tx[sfDestination] = dave.human(); env(tx, ter{tecDST_TAG_NEEDED}); env.close(); @@ -306,7 +327,8 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " withdraw to 3rd party lsfRequireDestTag"); - auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); + auto tx = + vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); tx[sfDestination] = dave.human(); tx[sfDestinationTag] = "0"; env(tx); @@ -322,14 +344,16 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " fail to withdraw lsfRequireDestTag"); - auto tx = vault.withdraw({.depositor = dave, .id = keylet.key, .amount = asset(50)}); + auto tx = + vault.withdraw({.depositor = dave, .id = keylet.key, .amount = asset(50)}); env(tx, ter{tecDST_TAG_NEEDED}); env.close(); } { testcase(prefix + " withdraw with tag"); - auto tx = vault.withdraw({.depositor = dave, .id = keylet.key, .amount = asset(50)}); + auto tx = + vault.withdraw({.depositor = dave, .id = keylet.key, .amount = asset(50)}); tx[sfDestinationTag] = "0"; env(tx); env.close(); @@ -337,7 +361,8 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " withdraw to authorized 3rd party"); - auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); + auto tx = + vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); tx[sfDestination] = charlie.human(); env(tx); env.close(); @@ -346,7 +371,8 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " withdraw to issuer"); - auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); + auto tx = + vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); tx[sfDestination] = issuer.human(); env(tx); env.close(); @@ -356,13 +382,15 @@ class Vault_test : public beast::unit_test::suite if (!asset.raw().native()) { testcase(prefix + " issuer deposits"); - auto tx = vault.deposit({.depositor = issuer, .id = keylet.key, .amount = asset(10)}); + auto tx = + vault.deposit({.depositor = issuer, .id = keylet.key, .amount = asset(10)}); env(tx); env.close(); BEAST_EXPECT(env.balance(issuer, shares) == share(10 * scale)); testcase(prefix + " issuer withdraws"); - tx = vault.withdraw({.depositor = issuer, .id = keylet.key, .amount = share(10 * scale)}); + tx = vault.withdraw( + {.depositor = issuer, .id = keylet.key, .amount = share(10 * scale)}); env(tx); env.close(); BEAST_EXPECT(env.balance(issuer, shares) == share(0 * scale)); @@ -370,21 +398,26 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " withdraw remaining assets"); - auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); + auto tx = + vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx); env.close(); BEAST_EXPECT(env.balance(depositor, shares) == share(0)); if (!asset.raw().native()) { - auto tx = - vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); + auto tx = vault.clawback( + {.issuer = issuer, + .id = keylet.key, + .holder = depositor, + .amount = asset(0)}); env(tx, ter{tecPRECISION_LOSS}); env.close(); } { - auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = share(10)}); + auto tx = vault.withdraw( + {.depositor = depositor, .id = keylet.key, .amount = share(10)}); env(tx, ter{tecINSUFFICIENT_FUNDS}); env.close(); } @@ -409,7 +442,8 @@ class Vault_test : public beast::unit_test::suite env.close(); // depositor will gain MPToken for shares again - env(vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(1)})); + env(vault.deposit( + {.depositor = depositor, .id = keylet.key, .amount = asset(1)})); env.close(); env(tx); @@ -418,7 +452,8 @@ class Vault_test : public beast::unit_test::suite testcase(prefix + " withdraw to authorized 3rd party"); // Depositor withdraws assets, destined to Erin - tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(10)}); + tx = + vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(10)}); tx[sfDestination] = erin.human(); env(tx); env.close(); @@ -457,7 +492,8 @@ class Vault_test : public beast::unit_test::suite } }; - auto testCases = [&, this](std::string prefix, std::function setup) { + auto testCases = [&, this]( + std::string prefix, std::function setup) { Env env{*this, testable_amendments() | featureSingleAssetVault}; Vault vault{env}; @@ -514,34 +550,41 @@ class Vault_test : public beast::unit_test::suite FeatureBitset features = testable_amendments() | featureSingleAssetVault; }; - auto testCase = - [&, this]( - std::function test, - CaseArgs args = {}) { - Env env{*this, args.features}; - Account issuer{"issuer"}; - Account owner{"owner"}; - Vault vault{env}; - env.fund(XRP(1000), issuer, owner); - env.close(); + auto testCase = [&, this]( + std::function test, + CaseArgs args = {}) { + Env env{*this, args.features}; + Account issuer{"issuer"}; + Account owner{"owner"}; + Vault vault{env}; + env.fund(XRP(1000), issuer, owner); + env.close(); - env(fset(issuer, asfAllowTrustLineClawback)); - env(fset(issuer, asfRequireAuth)); - env.close(); + env(fset(issuer, asfAllowTrustLineClawback)); + env(fset(issuer, asfRequireAuth)); + env.close(); - PrettyAsset asset = issuer["IOU"]; - env(trust(owner, asset(1000))); - env(trust(issuer, asset(0), owner, tfSetfAuth)); - env(pay(issuer, owner, asset(1000))); - env.close(); + PrettyAsset asset = issuer["IOU"]; + env(trust(owner, asset(1000))); + env(trust(issuer, asset(0), owner, tfSetfAuth)); + env(pay(issuer, owner, asset(1000))); + env.close(); - test(env, issuer, owner, asset, vault); - }; + test(env, issuer, owner, asset, vault); + }; auto testDisabled = [&](TER resultAfterCreate = temDISABLED) { return [&, resultAfterCreate]( - Env& env, Account const& issuer, Account const& owner, Asset const& asset, Vault& vault) { + Env& env, + Account const& issuer, + Account const& owner, + Asset const& asset, + Vault& vault) { testcase("disabled single asset vault"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); @@ -553,18 +596,20 @@ class Vault_test : public beast::unit_test::suite } { - auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(10)}); - env(tx, ter{resultAfterCreate}); - } - - { - auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto tx = + vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(10)}); env(tx, ter{resultAfterCreate}); } { auto tx = - vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(10)}); + vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + env(tx, ter{resultAfterCreate}); + } + + { + auto tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(10)}); env(tx, ter{resultAfterCreate}); } @@ -577,10 +622,15 @@ class Vault_test : public beast::unit_test::suite testCase(testDisabled(), {.features = testable_amendments() - featureSingleAssetVault}); - testCase(testDisabled(tecNO_ENTRY), {.features = testable_amendments() - featureMPTokensV1}); + testCase( + testDisabled(tecNO_ENTRY), {.features = testable_amendments() - featureMPTokensV1}); testCase( - [&](Env& env, Account const& issuer, Account const& owner, Asset const& asset, Vault& vault) { + [&](Env& env, + Account const& issuer, + Account const& owner, + Asset const& asset, + Vault& vault) { testcase("disabled permissioned domains"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); @@ -600,7 +650,11 @@ class Vault_test : public beast::unit_test::suite }, {.features = testable_amendments() - featurePermissionedDomains}); - testCase([&](Env& env, Account const& issuer, Account const& owner, Asset const& asset, Vault& vault) { + testCase([&](Env& env, + Account const& issuer, + Account const& owner, + Asset const& asset, + Vault& vault) { testcase("invalid flags"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); @@ -614,19 +668,22 @@ class Vault_test : public beast::unit_test::suite } { - auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto tx = + vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[sfFlags] = tfClearDeepFreeze; env(tx, ter{temINVALID_FLAG}); } { - auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto tx = + vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[sfFlags] = tfClearDeepFreeze; env(tx, ter{temINVALID_FLAG}); } { - auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(10)}); + auto tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(10)}); tx[sfFlags] = tfClearDeepFreeze; env(tx, ter{temINVALID_FLAG}); } @@ -638,7 +695,11 @@ class Vault_test : public beast::unit_test::suite } }); - testCase([&](Env& env, Account const& issuer, Account const& owner, Asset const& asset, Vault& vault) { + testCase([&](Env& env, + Account const& issuer, + Account const& owner, + Asset const& asset, + Vault& vault) { testcase("invalid fee"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); @@ -652,19 +713,22 @@ class Vault_test : public beast::unit_test::suite } { - auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto tx = + vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[jss::Fee] = "-1"; env(tx, ter{temBAD_FEE}); } { - auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto tx = + vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[jss::Fee] = "-1"; env(tx, ter{temBAD_FEE}); } { - auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(10)}); + auto tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(10)}); tx[jss::Fee] = "-1"; env(tx, ter{temBAD_FEE}); } @@ -696,9 +760,14 @@ class Vault_test : public beast::unit_test::suite env(tx, ter{temDISABLED}); } }, - {.features = (testable_amendments() | featureSingleAssetVault) - featurePermissionedDomains}); + {.features = + (testable_amendments() | featureSingleAssetVault) - featurePermissionedDomains}); - testCase([&](Env& env, Account const& issuer, Account const& owner, Asset const& asset, Vault& vault) { + testCase([&](Env& env, + Account const& issuer, + Account const& owner, + Asset const& asset, + Vault& vault) { testcase("use zero vault"); auto [tx, keylet] = vault.create({.owner = owner, .asset = xrpIssue()}); @@ -712,17 +781,20 @@ class Vault_test : public beast::unit_test::suite } { - auto tx = vault.deposit({.depositor = owner, .id = beast::zero, .amount = asset(10)}); + auto tx = + vault.deposit({.depositor = owner, .id = beast::zero, .amount = asset(10)}); env(tx, ter(temMALFORMED)); } { - auto tx = vault.withdraw({.depositor = owner, .id = beast::zero, .amount = asset(10)}); + auto tx = + vault.withdraw({.depositor = owner, .id = beast::zero, .amount = asset(10)}); env(tx, ter{temMALFORMED}); } { - auto tx = vault.clawback({.issuer = issuer, .id = beast::zero, .holder = owner, .amount = asset(10)}); + auto tx = vault.clawback( + {.issuer = issuer, .id = beast::zero, .holder = owner, .amount = asset(10)}); env(tx, ter{temMALFORMED}); } @@ -735,184 +807,202 @@ class Vault_test : public beast::unit_test::suite } }); - testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { - testcase("withdraw to bad destination"); + testCase( + [&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { + testcase("withdraw to bad destination"); - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - - { - auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); - tx[jss::Destination] = "0"; - env(tx, ter{temMALFORMED}); - } - }); - - testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { - testcase("create with Scale"); - - { auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - tx[sfScale] = 255; - env(tx, ter(temMALFORMED)); - } - { + { + auto tx = + vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + tx[jss::Destination] = "0"; + env(tx, ter{temMALFORMED}); + } + }); + + testCase( + [&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { + testcase("create with Scale"); + + { + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + tx[sfScale] = 255; + env(tx, ter(temMALFORMED)); + } + + { + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + tx[sfScale] = 19; + env(tx, ter(temMALFORMED)); + } + + // accepted range from 0 to 18 + { + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + tx[sfScale] = 18; + env(tx); + env.close(); + auto const sleVault = env.le(keylet); + BEAST_EXPECT(sleVault); + BEAST_EXPECT((*sleVault)[sfScale] == 18); + } + + { + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + tx[sfScale] = 0; + env(tx); + env.close(); + auto const sleVault = env.le(keylet); + BEAST_EXPECT(sleVault); + BEAST_EXPECT((*sleVault)[sfScale] == 0); + } + + { + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + env(tx); + env.close(); + auto const sleVault = env.le(keylet); + BEAST_EXPECT(sleVault); + BEAST_EXPECT((*sleVault)[sfScale] == 6); + } + }); + + testCase( + [&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { + testcase("create or set invalid data"); + + auto [tx1, keylet] = vault.create({.owner = owner, .asset = asset}); + + { + auto tx = tx1; + tx[sfData] = ""; + env(tx, ter(temMALFORMED)); + } + + { + auto tx = tx1; + // A hexadecimal string of 257 bytes. + tx[sfData] = std::string(514, 'A'); + env(tx, ter(temMALFORMED)); + } + + { + auto tx = vault.set({.owner = owner, .id = keylet.key}); + tx[sfData] = ""; + env(tx, ter{temMALFORMED}); + } + + { + auto tx = vault.set({.owner = owner, .id = keylet.key}); + // A hexadecimal string of 257 bytes. + tx[sfData] = std::string(514, 'A'); + env(tx, ter{temMALFORMED}); + } + }); + + testCase( + [&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { + testcase("set nothing updated"); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - tx[sfScale] = 19; - env(tx, ter(temMALFORMED)); - } - // accepted range from 0 to 18 - { + { + auto tx = vault.set({.owner = owner, .id = keylet.key}); + env(tx, ter{temMALFORMED}); + } + }); + + testCase( + [&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { + testcase("create with invalid metadata"); + + auto [tx1, keylet] = vault.create({.owner = owner, .asset = asset}); + + { + auto tx = tx1; + tx[sfMPTokenMetadata] = ""; + env(tx, ter(temMALFORMED)); + } + + { + auto tx = tx1; + // This metadata is for the share token. + // A hexadecimal string of 1025 bytes. + tx[sfMPTokenMetadata] = std::string(2050, 'B'); + env(tx, ter(temMALFORMED)); + } + }); + + testCase( + [&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { + testcase("set negative maximum"); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - tx[sfScale] = 18; - env(tx); - env.close(); - auto const sleVault = env.le(keylet); - BEAST_EXPECT(sleVault); - BEAST_EXPECT((*sleVault)[sfScale] == 18); - } - { + { + auto tx = vault.set({.owner = owner, .id = keylet.key}); + tx[sfAssetsMaximum] = negativeAmount(asset).number(); + env(tx, ter{temMALFORMED}); + } + }); + + testCase( + [&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { + testcase("invalid deposit amount"); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - tx[sfScale] = 0; - env(tx); - env.close(); - auto const sleVault = env.le(keylet); - BEAST_EXPECT(sleVault); - BEAST_EXPECT((*sleVault)[sfScale] == 0); - } - { + { + auto tx = vault.deposit( + {.depositor = owner, .id = keylet.key, .amount = negativeAmount(asset)}); + env(tx, ter(temBAD_AMOUNT)); + } + + { + auto tx = + vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(0)}); + env(tx, ter(temBAD_AMOUNT)); + } + }); + + testCase( + [&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { + testcase("invalid set immutable flag"); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - env(tx); - env.close(); - auto const sleVault = env.le(keylet); - BEAST_EXPECT(sleVault); - BEAST_EXPECT((*sleVault)[sfScale] == 6); - } - }); - testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { - testcase("create or set invalid data"); + { + auto tx = vault.set({.owner = owner, .id = keylet.key}); + tx[sfFlags] = tfVaultPrivate; + env(tx, ter(temINVALID_FLAG)); + } + }); - auto [tx1, keylet] = vault.create({.owner = owner, .asset = asset}); + testCase( + [&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { + testcase("invalid withdraw amount"); - { - auto tx = tx1; - tx[sfData] = ""; - env(tx, ter(temMALFORMED)); - } + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - { - auto tx = tx1; - // A hexadecimal string of 257 bytes. - tx[sfData] = std::string(514, 'A'); - env(tx, ter(temMALFORMED)); - } + { + auto tx = vault.withdraw( + {.depositor = owner, .id = keylet.key, .amount = negativeAmount(asset)}); + env(tx, ter(temBAD_AMOUNT)); + } - { - auto tx = vault.set({.owner = owner, .id = keylet.key}); - tx[sfData] = ""; - env(tx, ter{temMALFORMED}); - } + { + auto tx = + vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(0)}); + env(tx, ter(temBAD_AMOUNT)); + } + }); - { - auto tx = vault.set({.owner = owner, .id = keylet.key}); - // A hexadecimal string of 257 bytes. - tx[sfData] = std::string(514, 'A'); - env(tx, ter{temMALFORMED}); - } - }); - - testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { - testcase("set nothing updated"); - - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - - { - auto tx = vault.set({.owner = owner, .id = keylet.key}); - env(tx, ter{temMALFORMED}); - } - }); - - testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { - testcase("create with invalid metadata"); - - auto [tx1, keylet] = vault.create({.owner = owner, .asset = asset}); - - { - auto tx = tx1; - tx[sfMPTokenMetadata] = ""; - env(tx, ter(temMALFORMED)); - } - - { - auto tx = tx1; - // This metadata is for the share token. - // A hexadecimal string of 1025 bytes. - tx[sfMPTokenMetadata] = std::string(2050, 'B'); - env(tx, ter(temMALFORMED)); - } - }); - - testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { - testcase("set negative maximum"); - - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - - { - auto tx = vault.set({.owner = owner, .id = keylet.key}); - tx[sfAssetsMaximum] = negativeAmount(asset).number(); - env(tx, ter{temMALFORMED}); - } - }); - - testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { - testcase("invalid deposit amount"); - - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - - { - auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = negativeAmount(asset)}); - env(tx, ter(temBAD_AMOUNT)); - } - - { - auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(0)}); - env(tx, ter(temBAD_AMOUNT)); - } - }); - - testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { - testcase("invalid set immutable flag"); - - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - - { - auto tx = vault.set({.owner = owner, .id = keylet.key}); - tx[sfFlags] = tfVaultPrivate; - env(tx, ter(temINVALID_FLAG)); - } - }); - - testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { - testcase("invalid withdraw amount"); - - auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); - - { - auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = negativeAmount(asset)}); - env(tx, ter(temBAD_AMOUNT)); - } - - { - auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(0)}); - env(tx, ter(temBAD_AMOUNT)); - } - }); - - testCase([&](Env& env, Account const& issuer, Account const& owner, Asset const& asset, Vault& vault) { + testCase([&](Env& env, + Account const& issuer, + Account const& owner, + Asset const& asset, + Vault& vault) { testcase("invalid clawback"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); @@ -920,47 +1010,52 @@ class Vault_test : public beast::unit_test::suite // Preclaim only checks for native assets. if (asset.native()) { - auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(50)}); + auto tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(50)}); env(tx, ter(temMALFORMED)); } { auto tx = vault.clawback( - {.issuer = issuer, .id = keylet.key, .holder = owner, .amount = negativeAmount(asset)}); + {.issuer = issuer, + .id = keylet.key, + .holder = owner, + .amount = negativeAmount(asset)}); env(tx, ter(temBAD_AMOUNT)); } }); - testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { - testcase("invalid create"); + testCase( + [&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { + testcase("invalid create"); - auto [tx1, keylet] = vault.create({.owner = owner, .asset = asset}); + auto [tx1, keylet] = vault.create({.owner = owner, .asset = asset}); - { - auto tx = tx1; - tx[sfWithdrawalPolicy] = 0; - env(tx, ter(temMALFORMED)); - } + { + auto tx = tx1; + tx[sfWithdrawalPolicy] = 0; + env(tx, ter(temMALFORMED)); + } - { - auto tx = tx1; - tx[sfDomainID] = to_string(base_uint<256>(42ul)); - env(tx, ter{temMALFORMED}); - } + { + auto tx = tx1; + tx[sfDomainID] = to_string(base_uint<256>(42ul)); + env(tx, ter{temMALFORMED}); + } - { - auto tx = tx1; - tx[sfAssetsMaximum] = negativeAmount(asset).number(); - env(tx, ter{temMALFORMED}); - } + { + auto tx = tx1; + tx[sfAssetsMaximum] = negativeAmount(asset).number(); + env(tx, ter{temMALFORMED}); + } - { - auto tx = tx1; - tx[sfFlags] = tfVaultPrivate; - tx[sfDomainID] = "0"; - env(tx, ter{temMALFORMED}); - } - }); + { + auto tx = tx1; + tx[sfFlags] = tfVaultPrivate; + tx[sfDomainID] = "0"; + env(tx, ter{temMALFORMED}); + } + }); } // Test for non-asset specific behaviors. @@ -969,13 +1064,14 @@ class Vault_test : public beast::unit_test::suite { using namespace test::jtx; - auto testCase = [this](std::function test) { + auto testCase = [this]( + std::function test) { Env env{*this, testable_amendments() | featureSingleAssetVault}; Account issuer{"issuer"}; Account owner{"owner"}; @@ -1009,7 +1105,8 @@ class Vault_test : public beast::unit_test::suite PrettyAsset const& asset, Vault& vault) { testcase("nothing to deposit to"); - auto tx = vault.deposit({.depositor = depositor, .id = keylet::skip().key, .amount = asset(10)}); + auto tx = vault.deposit( + {.depositor = depositor, .id = keylet::skip().key, .amount = asset(10)}); env(tx, ter(tecNO_ENTRY)); }); @@ -1021,7 +1118,8 @@ class Vault_test : public beast::unit_test::suite PrettyAsset const& asset, Vault& vault) { testcase("nothing to withdraw from"); - auto tx = vault.withdraw({.depositor = depositor, .id = keylet::skip().key, .amount = asset(10)}); + auto tx = vault.withdraw( + {.depositor = depositor, .id = keylet::skip().key, .amount = asset(10)}); env(tx, ter(tecNO_ENTRY)); }); @@ -1138,7 +1236,8 @@ class Vault_test : public beast::unit_test::suite { { testcase("IOU fail because MPT is disabled"); - Env env{*this, (testable_amendments() - featureMPTokensV1) | featureSingleAssetVault}; + Env env{ + *this, (testable_amendments() - featureMPTokensV1) | featureSingleAssetVault}; Account issuer{"issuer"}; Account owner{"owner"}; env.fund(XRP(1000), issuer, owner); @@ -1255,13 +1354,14 @@ class Vault_test : public beast::unit_test::suite { using namespace test::jtx; - auto testCase = [this](std::function test) { + auto testCase = [this]( + std::function test) { Env env{*this, testable_amendments() | featureSingleAssetVault}; Account issuer{"issuer"}; Account owner{"owner"}; @@ -1343,7 +1443,8 @@ class Vault_test : public beast::unit_test::suite { testcase("nontransferable deposits"); - auto tx1 = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(40)}); + auto tx1 = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(40)}); env(tx1); auto tx2 = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(60)}); @@ -1356,10 +1457,12 @@ class Vault_test : public beast::unit_test::suite auto jvVault = env.rpc("vault_info", strHex(key)); BEAST_EXPECT(jvVault[jss::result][jss::vault][sfAssetsTotal] == "100"); - BEAST_EXPECT(jvVault[jss::result][jss::vault][jss::shares][sfOutstandingAmount] == "100000000"); + BEAST_EXPECT( + jvVault[jss::result][jss::vault][jss::shares][sfOutstandingAmount] == "100000000"); // Vault pseudo-account - return parseBase58(jvVault[jss::result][jss::vault][jss::Account].asString()).value(); + return parseBase58(jvVault[jss::result][jss::vault][jss::Account].asString()) + .value(); }(); auto const MptID = makeMptID(1, vaultAccount); @@ -1373,7 +1476,8 @@ class Vault_test : public beast::unit_test::suite { testcase("nontransferable shares can be used to withdraw"); - auto tx1 = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(20)}); + auto tx1 = + vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(20)}); env(tx1); auto tx2 = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(30)}); @@ -1385,12 +1489,14 @@ class Vault_test : public beast::unit_test::suite testcase("nontransferable shares balance check"); auto jvVault = env.rpc("vault_info", strHex(keylet.key)); BEAST_EXPECT(jvVault[jss::result][jss::vault][sfAssetsTotal] == "50"); - BEAST_EXPECT(jvVault[jss::result][jss::vault][jss::shares][sfOutstandingAmount] == "50000000"); + BEAST_EXPECT( + jvVault[jss::result][jss::vault][jss::shares][sfOutstandingAmount] == "50000000"); } { testcase("nontransferable shares withdraw rest"); - auto tx1 = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(20)}); + auto tx1 = + vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(20)}); env(tx1); auto tx2 = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(30)}); @@ -1439,7 +1545,8 @@ class Vault_test : public beast::unit_test::suite MPTTester mptt{env, issuer, mptInitNoFund}; auto const none = LedgerSpecificFlags(0); mptt.create( - {.flags = tfMPTCanTransfer | tfMPTCanLock | (args.enableClawback ? tfMPTCanClawback : none) | + {.flags = tfMPTCanTransfer | tfMPTCanLock | + (args.enableClawback ? tfMPTCanClawback : none) | (args.requireAuth ? tfMPTRequireAuth : none), .mutableFlags = tmfMPTCanMutateCanTransfer}); PrettyAsset asset = mptt.issuanceID(); @@ -1466,8 +1573,11 @@ class Vault_test : public beast::unit_test::suite Vault& vault, MPTTester& mptt) { testcase("MPT nothing to clawback from"); - auto tx = - vault.clawback({.issuer = issuer, .id = keylet::skip().key, .holder = depositor, .amount = asset(10)}); + auto tx = vault.clawback( + {.issuer = issuer, + .id = keylet::skip().key, + .holder = depositor, + .amount = asset(10)}); env(tx, ter(tecNO_ENTRY)); }); @@ -1546,7 +1656,8 @@ class Vault_test : public beast::unit_test::suite env(tx, ter(tecLOCKED)); // Clawback is still permitted, even with global lock - tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); + tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); env(tx); env.close(); @@ -1611,7 +1722,8 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); + tx = vault.deposit( + {.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); env(tx); env.close(); @@ -1624,7 +1736,8 @@ class Vault_test : public beast::unit_test::suite auto const sleMPT1 = env.le(mptoken); BEAST_EXPECT(sleMPT1 == nullptr); - tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); + tx = vault.withdraw( + {.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx, ter{tecNO_AUTH}); env.close(); @@ -1638,7 +1751,8 @@ class Vault_test : public beast::unit_test::suite env.fund(XRP(1000), charlie); env.close(); - tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); + tx = vault.withdraw( + {.depositor = depositor, .id = keylet.key, .amount = asset(100)}); tx[sfDestination] = charlie.human(); env(tx, ter(tecNO_AUTH)); } @@ -1663,7 +1777,9 @@ class Vault_test : public beast::unit_test::suite BEAST_EXPECT(v); tx = vault.deposit( - {.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); // all assets held by depositor + {.depositor = depositor, + .id = keylet.key, + .amount = asset(1000)}); // all assets held by depositor env(tx); env.close(); @@ -1676,7 +1792,8 @@ class Vault_test : public beast::unit_test::suite auto const sleMPT1 = env.le(mptoken); BEAST_EXPECT(sleMPT1 == nullptr); - tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); + tx = vault.withdraw( + {.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx); env.close(); @@ -1694,7 +1811,8 @@ class Vault_test : public beast::unit_test::suite auto const sleMPT1 = env.le(mptoken); BEAST_EXPECT(sleMPT1 == nullptr); - tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); + tx = vault.withdraw( + {.depositor = depositor, .id = keylet.key, .amount = asset(100)}); tx[sfDestination] = owner.human(); env(tx, ter(tecNO_AUTH)); env.close(); @@ -1733,7 +1851,9 @@ class Vault_test : public beast::unit_test::suite env.close(); tx = vault.deposit( - {.depositor = owner, .id = keylet.key, .amount = asset(1000)}); // all assets held by owner + {.depositor = owner, + .id = keylet.key, + .amount = asset(1000)}); // all assets held by owner env(tx); env.close(); @@ -1751,7 +1871,8 @@ class Vault_test : public beast::unit_test::suite env.close(); // No reserve to create MPToken for asset in VaultWithdraw - tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(100)}); + tx = vault.withdraw( + {.depositor = owner, .id = keylet.key, .amount = asset(100)}); env(tx, ter{tecINSUFFICIENT_RESERVE}); env.close(); @@ -1784,7 +1905,8 @@ class Vault_test : public beast::unit_test::suite env.close(); { - auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); + auto tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); env(tx); } @@ -1797,17 +1919,20 @@ class Vault_test : public beast::unit_test::suite } { - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(10)}); + auto tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(10)}); env(tx, ter{tecOBJECT_NOT_FOUND}); } { - auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(10)}); + auto tx = + vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(10)}); env(tx, ter{tecOBJECT_NOT_FOUND}); } { - auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); + auto tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); env(tx, ter{tecOBJECT_NOT_FOUND}); } @@ -1851,7 +1976,8 @@ class Vault_test : public beast::unit_test::suite env(pay(depositor, owner, shares(1))); env.close(); - tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)}); + tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)}); env(tx); env.close(); @@ -1880,7 +2006,8 @@ class Vault_test : public beast::unit_test::suite env.close(); // destroy all remaining shares, so we can delete vault - tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); + tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); env(tx); env.close(); @@ -1905,13 +2032,17 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); + tx = vault.deposit( + {.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); env(tx); env.close(); { - auto tx = - vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); + auto tx = vault.clawback( + {.issuer = issuer, + .id = keylet.key, + .holder = depositor, + .amount = asset(0)}); env(tx, ter{tecNO_PERMISSION}); } }, @@ -1937,7 +2068,8 @@ class Vault_test : public beast::unit_test::suite env.close(); { - auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); + auto tx = vault.withdraw( + {.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx, ter(tecNO_AUTH)); // Withdrawal to other (authorized) accounts works @@ -1952,17 +2084,20 @@ class Vault_test : public beast::unit_test::suite { // Cannot deposit some more - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); + auto tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx, ter(tecNO_AUTH)); } { // Cannot clawback if issuer is the holder - tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = issuer, .amount = asset(800)}); + tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = issuer, .amount = asset(800)}); env(tx, ter(tecNO_PERMISSION)); } // Clawback works - tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(800)}); + tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(800)}); env(tx); env.close(); @@ -2011,7 +2146,8 @@ class Vault_test : public beast::unit_test::suite env(tx, ter(tecLOCKED)); // Clawback works, even when locked - tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(100)}); + tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(100)}); env(tx); // Can delete an empty vault even when asset is locked. @@ -2030,7 +2166,8 @@ class Vault_test : public beast::unit_test::suite Vault vault{env}; MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock | lsfMPTCanClawback | tfMPTRequireAuth}); + mptt.create( + {.flags = tfMPTCanTransfer | tfMPTCanLock | lsfMPTCanClawback | tfMPTRequireAuth}); mptt.authorize({.account = owner}); mptt.authorize({.account = issuer, .holder = owner}); PrettyAsset asset = mptt.issuanceID(); @@ -2148,7 +2285,9 @@ class Vault_test : public beast::unit_test::suite auto const vaultAccount = [&env](xrpl::Keylet keylet) -> Account { return Account("vault", env.le(keylet)->at(sfAccount)); }; - auto const issuanceId = [&env](xrpl::Keylet keylet) -> MPTID { return env.le(keylet)->at(sfShareMPTID); }; + auto const issuanceId = [&env](xrpl::Keylet keylet) -> MPTID { + return env.le(keylet)->at(sfShareMPTID); + }; test(env, owner, issuer, charlie, vaultAccount, vault, asset, issuanceId); }; @@ -2193,7 +2332,8 @@ class Vault_test : public beast::unit_test::suite } { - auto tx = vault.withdraw({.depositor = issuer, .id = keylet.key, .amount = foo(20)}); + auto tx = + vault.withdraw({.depositor = issuer, .id = keylet.key, .amount = foo(20)}); env(tx, ter{tecWRONG_ASSET}); env.close(); } @@ -2242,12 +2382,14 @@ class Vault_test : public beast::unit_test::suite // is reported as "locked" state of the vault shares, because // this state is attached to shares by means of the transitive // isFrozen. - auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(80)}); + auto tx = + vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(80)}); env(tx, ter{tecLOCKED}); } { - auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(100)}); + auto tx = + vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(100)}); env(tx, ter{tecLOCKED}); // also when trying to withdraw to a 3rd party @@ -2258,7 +2400,8 @@ class Vault_test : public beast::unit_test::suite { // Clawback works, even when locked - auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(50)}); + auto tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(50)}); env(tx); env.close(); } @@ -2268,7 +2411,8 @@ class Vault_test : public beast::unit_test::suite env(trustSet); env.close(); - env(vault.withdraw({.depositor = owner, .id = keylet.key, .amount = share(50'000'000)})); + env(vault.withdraw( + {.depositor = owner, .id = keylet.key, .amount = share(50'000'000)})); env(vault.del({.owner = owner, .id = keylet.key})); env.close(); @@ -2301,8 +2445,8 @@ class Vault_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(vaultAccount(keylet), issue) == asset(100)); { - auto tx = - vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(50)}); + auto tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(50)}); env(tx); env.close(); } @@ -2311,14 +2455,16 @@ class Vault_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(owner, issue) == asset(100)); BEAST_EXPECT(env.balance(vaultAccount(keylet), issue) == asset(50)); - env(vault.withdraw({.depositor = owner, .id = keylet.key, .amount = share(20'000'000)})); + env(vault.withdraw( + {.depositor = owner, .id = keylet.key, .amount = share(20'000'000)})); // transfer fees ignored on withdraw BEAST_EXPECT(env.balance(owner, issue) == asset(120)); BEAST_EXPECT(env.balance(vaultAccount(keylet), issue) == asset(30)); { - auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = share(30'000'000)}); + auto tx = vault.withdraw( + {.depositor = owner, .id = keylet.key, .amount = share(30'000'000)}); tx[sfDestination] = charlie.human(); env(tx); } @@ -2353,7 +2499,8 @@ class Vault_test : public beast::unit_test::suite // Withdraw to 3rd party works auto const withdrawToCharlie = [&](xrpl::Keylet keylet) { - auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto tx = + vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[sfDestination] = charlie.human(); return tx; }(keylet); @@ -2364,7 +2511,8 @@ class Vault_test : public beast::unit_test::suite env.close(); // Cannot withdraw - auto const withdraw = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto const withdraw = + vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); env(withdraw, ter{tecFROZEN}); // Cannot withdraw to 3rd party @@ -2373,13 +2521,15 @@ class Vault_test : public beast::unit_test::suite { // Cannot deposit some more - auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto tx = + vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(10)}); env(tx, ter{tecFROZEN}); } { // Clawback still works - auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)}); + auto tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)}); env(tx); env.close(); } @@ -2412,7 +2562,8 @@ class Vault_test : public beast::unit_test::suite // Withdraw to 3rd party without trust line auto const tx1 = [&](xrpl::Keylet keylet) { - auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto tx = + vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[sfDestination] = erin.human(); return tx; }(keylet); @@ -2446,7 +2597,8 @@ class Vault_test : public beast::unit_test::suite // Withdraw without trust line, will succeed auto const tx1 = [&](xrpl::Keylet keylet) { - auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto tx = + vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); return tx; }(keylet); env(tx1); @@ -2475,19 +2627,22 @@ class Vault_test : public beast::unit_test::suite { // Charlie cannot deposit - auto tx = vault.deposit({.depositor = charlie, .id = keylet.key, .amount = asset(100)}); + auto tx = vault.deposit( + {.depositor = charlie, .id = keylet.key, .amount = asset(100)}); env(tx, ter{terNO_RIPPLE}, THISLINE); env.close(); } { PrettyAsset shares = issuanceId(keylet); - auto tx1 = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(100)}); + auto tx1 = + vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(100)}); env(tx1, THISLINE); env.close(); // Charlie cannot receive funds - auto tx2 = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = shares(100)}); + auto tx2 = vault.withdraw( + {.depositor = owner, .id = keylet.key, .amount = shares(100)}); tx2[sfDestination] = charlie.human(); env(tx2, ter{terNO_RIPPLE}, THISLINE); env.close(); @@ -2496,7 +2651,8 @@ class Vault_test : public beast::unit_test::suite // Create MPToken for shares held by Charlie Json::Value tx{Json::objectValue}; tx[sfAccount] = charlie.human(); - tx[sfMPTokenIssuanceID] = to_string(shares.raw().get().getMptID()); + tx[sfMPTokenIssuanceID] = + to_string(shares.raw().get().getMptID()); tx[sfTransactionType] = jss::MPTokenAuthorize; env(tx); env.close(); @@ -2505,7 +2661,8 @@ class Vault_test : public beast::unit_test::suite env.close(); // Charlie cannot withdraw - auto tx3 = vault.withdraw({.depositor = charlie, .id = keylet.key, .amount = shares(100)}); + auto tx3 = vault.withdraw( + {.depositor = charlie, .id = keylet.key, .amount = shares(100)}); env(tx3, ter{terNO_RIPPLE}); env.close(); @@ -2548,8 +2705,8 @@ class Vault_test : public beast::unit_test::suite // blocked by Vault invariants. env(vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(100)})); - auto const tx1 = - vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(Number(375, -2))}); + auto const tx1 = vault.deposit( + {.depositor = owner, .id = keylet.key, .amount = asset(Number(375, -2))}); for (auto i = 0; i < 5; ++i) { env(tx1); @@ -2569,7 +2726,10 @@ class Vault_test : public beast::unit_test::suite // Total vault balance should be 118.5 IOU. Withdraw and delete // the vault to verify this exact amount was deposited and the // owner has matching shares - env(vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(Number(1000 + 37 * 5, -1))})); + env(vault.withdraw( + {.depositor = owner, + .id = keylet.key, + .amount = asset(Number(1000 + 37 * 5, -1))})); { BEAST_EXPECT(env.balance(owner, asset) == startingOwnerBalance.value()); @@ -2689,7 +2849,8 @@ class Vault_test : public beast::unit_test::suite // Withdraw to 3rd party works auto const withdrawToCharlie = [&](xrpl::Keylet keylet) { - auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto tx = + vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[sfDestination] = charlie.human(); return tx; }(keylet); @@ -2700,7 +2861,8 @@ class Vault_test : public beast::unit_test::suite env.close(); // Can withdraw - auto const withdraw = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto const withdraw = + vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); env(withdraw); env.close(); @@ -2708,7 +2870,8 @@ class Vault_test : public beast::unit_test::suite env(withdrawToCharlie, ter{tecFROZEN}); env.close(); - env(vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)})); + env(vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)})); env.close(); env(vault.del({.owner = owner, .id = keylet.key})); @@ -2738,7 +2901,8 @@ class Vault_test : public beast::unit_test::suite { // Cannot withdraw - auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto tx = + vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); env(tx, ter{tecFROZEN}); // Cannot withdraw to 3rd party @@ -2753,7 +2917,8 @@ class Vault_test : public beast::unit_test::suite } // Clawback is permitted - env(vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)})); + env(vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)})); env.close(); env(vault.del({.owner = owner, .id = keylet.key})); @@ -2806,7 +2971,8 @@ class Vault_test : public beast::unit_test::suite { testcase("private vault depositor not authorized yet"); - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); + auto tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx, ter{tecNO_AUTH}); } @@ -2821,7 +2987,8 @@ class Vault_test : public beast::unit_test::suite testcase("private vault set domainId"); { - pdomain::Credentials const credentials1{{.issuer = credIssuer1, .credType = credType}}; + pdomain::Credentials const credentials1{ + {.issuer = credIssuer1, .credType = credType}}; env(pdomain::setTx(pdOwner, credentials1)); auto const domainId1 = [&]() { @@ -2841,7 +3008,8 @@ class Vault_test : public beast::unit_test::suite { pdomain::Credentials const credentials{ - {.issuer = credIssuer1, .credType = credType}, {.issuer = credIssuer2, .credType = credType}}; + {.issuer = credIssuer1, .credType = credType}, + {.issuer = credIssuer2, .credType = credType}}; env(pdomain::setTx(pdOwner, credentials)); auto const domainId = [&]() { @@ -2864,7 +3032,8 @@ class Vault_test : public beast::unit_test::suite { testcase("private vault depositor still not authorized"); - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); + auto tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx, ter{tecNO_AUTH}); env.close(); } @@ -2880,7 +3049,8 @@ class Vault_test : public beast::unit_test::suite auto credSle = env.le(credKeylet); BEAST_EXPECT(credSle != nullptr); - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); + auto tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx); env.close(); @@ -2897,7 +3067,8 @@ class Vault_test : public beast::unit_test::suite auto credSle = env.le(credKeylet); BEAST_EXPECT(credSle == nullptr); - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); + auto tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx, ter{tecNO_AUTH}); env.close(); } @@ -2910,7 +3081,8 @@ class Vault_test : public beast::unit_test::suite { testcase("private vault expired authorization"); - uint32_t const closeTime = env.current()->header().parentCloseTime.time_since_epoch().count(); + uint32_t const closeTime = + env.current()->header().parentCloseTime.time_since_epoch().count(); { auto tx0 = credentials::create(depositor, credIssuer2, credType); tx0[sfExpiration] = closeTime + 20; @@ -2926,11 +3098,13 @@ class Vault_test : public beast::unit_test::suite } { - auto tx1 = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); + auto tx1 = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx1); env.close(); - auto const tokenKeylet = keylet::mptoken(shares.get().getMptID(), depositor.id()); + auto const tokenKeylet = + keylet::mptoken(shares.get().getMptID(), depositor.id()); BEAST_EXPECT(env.le(tokenKeylet) != nullptr); } @@ -2943,7 +3117,8 @@ class Vault_test : public beast::unit_test::suite auto const credsKeylet = credentials::keylet(depositor, credIssuer2, credType); BEAST_EXPECT(env.le(credsKeylet) != nullptr); - auto tx2 = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(1)}); + auto tx2 = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(1)}); env(tx2, ter{tecEXPIRED}); env.close(); @@ -2953,10 +3128,12 @@ class Vault_test : public beast::unit_test::suite { auto const credsKeylet = credentials::keylet(charlie, credIssuer2, credType); BEAST_EXPECT(env.le(credsKeylet) != nullptr); - auto const tokenKeylet = keylet::mptoken(shares.get().getMptID(), charlie.id()); + auto const tokenKeylet = + keylet::mptoken(shares.get().getMptID(), charlie.id()); BEAST_EXPECT(env.le(tokenKeylet) == nullptr); - auto tx3 = vault.deposit({.depositor = charlie, .id = keylet.key, .amount = asset(2)}); + auto tx3 = + vault.deposit({.depositor = charlie, .id = keylet.key, .amount = asset(2)}); env(tx3, ter{tecEXPIRED}); env.close(); @@ -2980,10 +3157,12 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); + tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); env(tx); - tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)}); + tx = vault.clawback( + {.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)}); env(tx); env.close(); @@ -3016,7 +3195,8 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - auto const [vaultAccount, issuanceId] = [&env, keylet = keylet, this]() -> std::tuple { + auto const [vaultAccount, issuanceId] = + [&env, keylet = keylet, this]() -> std::tuple { auto const vault = env.le(keylet); BEAST_EXPECT(vault != nullptr); return {vault->at(sfAccount), vault->at(sfShareMPTID)}; @@ -3039,7 +3219,8 @@ class Vault_test : public beast::unit_test::suite { testcase("private XRP vault depositor not authorized yet"); - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); + auto tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx, ter{tecNO_AUTH}); } @@ -3067,7 +3248,8 @@ class Vault_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(env.le(credKeylet)); - auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); + auto tx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx); env.close(); } @@ -3106,7 +3288,10 @@ class Vault_test : public beast::unit_test::suite { AccountID const accountId = xrpl::pseudoAccountAddress(*env.current(), keylet.key); - env(pay(env.master.id(), accountId, XRP(1000)), seq(autofill), fee(autofill), sig(autofill)); + env(pay(env.master.id(), accountId, XRP(1000)), + seq(autofill), + fee(autofill), + sig(autofill)); } auto [tx, keylet1] = vault.create({.owner = owner, .asset = xrpIssue()}); @@ -3134,7 +3319,8 @@ class Vault_test : public beast::unit_test::suite std::function)> peek; }; - auto testCase = [&, this](std::uint8_t scale, std::function test) { + auto testCase = [&, this]( + std::uint8_t scale, std::function test) { Env env{*this, testable_amendments() | featureSingleAssetVault}; Account const owner{"owner"}; Account const issuer{"issuer"}; @@ -3155,7 +3341,8 @@ class Vault_test : public beast::unit_test::suite tx[sfScale] = scale; env(tx); - auto const [vaultAccount, issuanceId] = [&env](xrpl::Keylet keylet) -> std::tuple { + auto const [vaultAccount, issuanceId] = + [&env](xrpl::Keylet keylet) -> std::tuple { auto const vault = env.le(keylet); return {Account("vault", vault->at(sfAccount)), vault->at(sfShareMPTID)}; }(keylet); @@ -3199,7 +3386,8 @@ class Vault_test : public beast::unit_test::suite testCase(18, [&, this](Env& env, Data d) { testcase("Scale deposit overflow on first deposit"); - auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(10)}); + auto tx = d.vault.deposit( + {.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(10)}); env(tx, ter{tecPATH_DRY}); env.close(); }); @@ -3208,13 +3396,15 @@ class Vault_test : public beast::unit_test::suite testcase("Scale deposit overflow on second deposit"); { - auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); + auto tx = d.vault.deposit( + {.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); env(tx); env.close(); } { - auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(10)}); + auto tx = d.vault.deposit( + {.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(10)}); env(tx, ter{tecPATH_DRY}); env.close(); } @@ -3224,13 +3414,15 @@ class Vault_test : public beast::unit_test::suite testcase("Scale deposit overflow on total shares"); { - auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); + auto tx = d.vault.deposit( + {.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); env(tx); env.close(); } { - auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); + auto tx = d.vault.deposit( + {.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); env(tx, ter{tecPATH_DRY}); env.close(); } @@ -3240,7 +3432,8 @@ class Vault_test : public beast::unit_test::suite testcase("Scale deposit exact"); auto const start = env.balance(d.depositor, d.assets).number(); - auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(1)}); + auto tx = d.vault.deposit( + {.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(1)}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(10)); @@ -3251,7 +3444,9 @@ class Vault_test : public beast::unit_test::suite testcase("Scale deposit insignificant amount"); auto tx = d.vault.deposit( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(9, -2))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(9, -2))}); env(tx, ter{tecPRECISION_LOSS}); }); @@ -3260,11 +3455,14 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.deposit( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(15, -1))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(15, -1))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(15)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(15, -1))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(15, -1))); }); testCase(1, [&, this](Env& env, Data d) { @@ -3275,29 +3473,41 @@ class Vault_test : public beast::unit_test::suite // vault and receive 12 shares in exchange { auto tx = d.vault.deposit( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(125, -2))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(125, -2))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(12)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(12, -1))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == + STAmount(d.asset, start - Number(12, -1))); } { auto tx = d.vault.deposit( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(1201, -3))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(1201, -3))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(24)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(24, -1))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == + STAmount(d.asset, start - Number(24, -1))); } { auto tx = d.vault.deposit( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(1299, -3))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(1299, -3))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(36)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(36, -1))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == + STAmount(d.asset, start - Number(36, -1))); } }); @@ -3307,20 +3517,27 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); // round to 12 auto tx = d.vault.deposit( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(1201, -3))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(1201, -3))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(12)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(12, -1))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(12, -1))); { // round to 6 auto tx = d.vault.deposit( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(69, -2))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(69, -2))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(18)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(18, -1))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == + STAmount(d.asset, start - Number(18, -1))); } }); @@ -3330,20 +3547,27 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); // round to 12 auto tx = d.vault.deposit( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(1299, -3))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(1299, -3))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(12)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(12, -1))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(12, -1))); { // round to 6 auto tx = d.vault.deposit( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(62, -2))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(62, -2))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(18)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(18, -1))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == + STAmount(d.asset, start - Number(18, -1))); } }); @@ -3351,13 +3575,18 @@ class Vault_test : public beast::unit_test::suite // initial setup: deposit 100 IOU, receive 1000 shares auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.deposit( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(100, 0))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(100, 0))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(1000)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(100, 0))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(100, 0))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, Number(-1000, 0))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(100, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(100, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == STAmount(d.share, Number(-1000, 0))); { testcase("Scale redeem exact"); @@ -3367,13 +3596,18 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.withdraw( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.share, Number(100, 0))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.share, Number(100, 0))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(900)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(10, 0))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(90, 0))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, Number(-900, 0))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(10, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(90, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == STAmount(d.share, Number(-900, 0))); } { @@ -3393,13 +3627,21 @@ class Vault_test : public beast::unit_test::suite // closed (because a modification like above is not persistent), // which is why the checks below are expected to pass. auto tx = d.vault.withdraw( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.share, Number(25, 0))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.share, Number(25, 0))}); env(tx, ter{tecINSUFFICIENT_FUNDS}); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(900 - 25)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(25, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(900 - 25, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(900 - 25, 0))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == + STAmount(d.asset, start + Number(25, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == + STAmount(d.asset, Number(900 - 25, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == + STAmount(d.share, -Number(900 - 25, 0))); } { @@ -3411,21 +3653,31 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); tx = d.vault.withdraw( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.share, Number(21, 0))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.share, Number(21, 0))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(875 - 21)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(21, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(875 - 21, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(875 - 21, 0))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == + STAmount(d.asset, start + Number(21, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == + STAmount(d.asset, Number(875 - 21, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == + STAmount(d.share, -Number(875 - 21, 0))); } { testcase("Scale redeem rest"); auto const rest = env.balance(d.depositor, d.shares).number(); - tx = - d.vault.withdraw({.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.share, rest)}); + tx = d.vault.withdraw( + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.share, rest)}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares).number() == 0); @@ -3438,14 +3690,17 @@ class Vault_test : public beast::unit_test::suite testcase("Scale withdraw overflow"); { - auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); + auto tx = d.vault.deposit( + {.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); env(tx); env.close(); } { auto tx = d.vault.withdraw( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(10, 0))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(10, 0))}); env(tx, ter{tecPATH_DRY}); env.close(); } @@ -3455,13 +3710,18 @@ class Vault_test : public beast::unit_test::suite // initial setup: deposit 100 IOU, receive 1000 shares auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.deposit( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(100, 0))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(100, 0))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(1000)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(100, 0))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(100, 0))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, Number(-1000, 0))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(100, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(100, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == STAmount(d.share, Number(-1000, 0))); { testcase("Scale withdraw exact"); @@ -3474,19 +3734,26 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.withdraw( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(10, 0))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(10, 0))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(900)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(10, 0))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(90, 0))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, Number(-900, 0))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(10, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(90, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == STAmount(d.share, Number(-900, 0))); } { testcase("Scale withdraw insignificant amount"); auto tx = d.vault.withdraw( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(4, -2))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(4, -2))}); env(tx, ter{tecPRECISION_LOSS}); } @@ -3510,13 +3777,21 @@ class Vault_test : public beast::unit_test::suite // closed (because a modification like above is not persistent), // which is why the checks below are expected to pass. auto tx = d.vault.withdraw( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(25, -1))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(25, -1))}); env(tx, ter{tecINSUFFICIENT_FUNDS}); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(900 - 25)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(25, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(900 - 25, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(900 - 25, 0))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == + STAmount(d.asset, start + Number(25, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == + STAmount(d.asset, Number(900 - 25, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == + STAmount(d.share, -Number(900 - 25, 0))); } { @@ -3530,13 +3805,21 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.withdraw( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(375, -2))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(375, -2))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(875 - 38)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(38, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(875 - 38, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(875 - 38, 0))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == + STAmount(d.asset, start + Number(38, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == + STAmount(d.asset, Number(875 - 38, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == + STAmount(d.share, -Number(875 - 38, 0))); } { @@ -3550,13 +3833,21 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.withdraw( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(372, -2))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(372, -2))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(837 - 37)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(37, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(837 - 37, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(837 - 37, 0))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == + STAmount(d.asset, start + Number(37, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == + STAmount(d.asset, Number(837 - 37, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == + STAmount(d.share, -Number(837 - 37, 0))); } { @@ -3564,21 +3855,30 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.withdraw( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(9, -2))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(9, -2))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(800 - 1)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(1, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(800 - 1, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(800 - 1, 0))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(1, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == + STAmount(d.asset, Number(800 - 1, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == + STAmount(d.share, -Number(800 - 1, 0))); } { testcase("Scale withdraw rest"); auto const rest = env.balance(d.vaultAccount, d.assets).number(); - tx = - d.vault.withdraw({.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, rest)}); + tx = d.vault.withdraw( + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, rest)}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares).number() == 0); @@ -3591,7 +3891,8 @@ class Vault_test : public beast::unit_test::suite testcase("Scale clawback overflow"); { - auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); + auto tx = d.vault.deposit( + {.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); env(tx); env.close(); } @@ -3611,13 +3912,18 @@ class Vault_test : public beast::unit_test::suite // initial setup: deposit 100 IOU, receive 1000 shares auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.deposit( - {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(100, 0))}); + {.depositor = d.depositor, + .id = d.keylet.key, + .amount = STAmount(d.asset, Number(100, 0))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(1000)); - BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(100, 0))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(100, 0))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(1000, 0))); + BEAST_EXPECT( + env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(100, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(100, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(1000, 0))); { testcase("Scale clawback exact"); // assetsToSharesWithdraw: @@ -3637,8 +3943,10 @@ class Vault_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(900)); BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start)); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(90, 0))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(900, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(90, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(900, 0))); } { @@ -3670,8 +3978,12 @@ class Vault_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(900 - 25)); BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start)); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(900 - 25, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(900 - 25, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == + STAmount(d.asset, Number(900 - 25, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == + STAmount(d.share, -Number(900 - 25, 0))); } { @@ -3693,8 +4005,12 @@ class Vault_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(875 - 38)); BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start)); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(875 - 38, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(875 - 38, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == + STAmount(d.asset, Number(875 - 38, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == + STAmount(d.share, -Number(875 - 38, 0))); } { @@ -3716,8 +4032,12 @@ class Vault_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(837 - 37)); BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start)); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(837 - 37, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(837 - 37, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == + STAmount(d.asset, Number(837 - 37, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == + STAmount(d.share, -Number(837 - 37, 0))); } { @@ -3733,8 +4053,12 @@ class Vault_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(800 - 1)); BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start)); - BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(800 - 1, -1))); - BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(800 - 1, 0))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.assets) == + STAmount(d.asset, Number(800 - 1, -1))); + BEAST_EXPECT( + env.balance(d.vaultAccount, d.shares) == + STAmount(d.share, -Number(800 - 1, 0))); } { @@ -3750,7 +4074,10 @@ class Vault_test : public beast::unit_test::suite // * when the ledger is closed with unmodified AssetsAvailable // because a modification like above is not persistent. tx = d.vault.clawback( - {.issuer = d.issuer, .id = d.keylet.key, .holder = d.depositor, .amount = STAmount(d.asset, rest)}); + {.issuer = d.issuer, + .id = d.keylet.key, + .holder = d.depositor, + .amount = STAmount(d.asset, rest)}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares).number() == 0); @@ -3801,14 +4128,19 @@ class Vault_test : public beast::unit_test::suite }(); auto const check = [&, keylet = keylet, sle = sleVault, this]( - Json::Value const& vault, Json::Value const& issuance = Json::nullValue) { + Json::Value const& vault, + Json::Value const& issuance = Json::nullValue) { BEAST_EXPECT(vault.isObject()); - constexpr auto checkString = [](auto& node, SField const& field, std::string v) -> bool { - return node.isMember(field.fieldName) && node[field.fieldName].isString() && node[field.fieldName] == v; + constexpr auto checkString = + [](auto& node, SField const& field, std::string v) -> bool { + return node.isMember(field.fieldName) && node[field.fieldName].isString() && + node[field.fieldName] == v; }; - constexpr auto checkObject = [](auto& node, SField const& field, Json::Value v) -> bool { - return node.isMember(field.fieldName) && node[field.fieldName].isObject() && node[field.fieldName] == v; + constexpr auto checkObject = + [](auto& node, SField const& field, Json::Value v) -> bool { + return node.isMember(field.fieldName) && node[field.fieldName].isObject() && + node[field.fieldName] == v; }; constexpr auto checkInt = [](auto& node, SField const& field, int v) -> bool { return node.isMember(field.fieldName) && @@ -3839,7 +4171,8 @@ class Vault_test : public beast::unit_test::suite BEAST_EXPECT(issuance["LedgerEntryType"].asString() == "MPTokenIssuance"); BEAST_EXPECT(issuance[jss::mpt_issuance_id].asString() == strShareID); BEAST_EXPECT(checkInt(issuance, sfSequence, 1)); - BEAST_EXPECT(checkInt(issuance, sfFlags, int(lsfMPTCanEscrow | lsfMPTCanTrade | lsfMPTCanTransfer))); + BEAST_EXPECT(checkInt( + issuance, sfFlags, int(lsfMPTCanEscrow | lsfMPTCanTrade | lsfMPTCanTransfer))); BEAST_EXPECT(checkString(issuance, sfOutstandingAmount, "50000000")); } }; @@ -4182,7 +4515,8 @@ class Vault_test : public beast::unit_test::suite PrettyAsset asset = xrpIssue(); }; - auto const xrpBalance = [this](Env const& env, Account const& account) -> std::optional { + auto const xrpBalance = [this]( + Env const& env, Account const& account) -> std::optional { auto sle = env.le(keylet::account(account.id())); if (BEAST_EXPECT(sle != nullptr)) return sle->getFieldAmount(sfBalance).xrp().drops(); @@ -4244,7 +4578,8 @@ class Vault_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(xrpBalance(env, carol) == *startBalance - amount); - tx = vault.withdraw({.depositor = carol, .id = keylet.key, .amount = asset(amount - 1)}); + tx = + vault.withdraw({.depositor = carol, .id = keylet.key, .amount = asset(amount - 1)}); env(tx, delegate::as(alice)); env.close(); BEAST_EXPECT(xrpBalance(env, carol) == *startBalance - 1); @@ -4278,7 +4613,8 @@ class Vault_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(xrpBalance(env, carol) == *startBalance - amount); - tx = vault.withdraw({.depositor = carol, .id = keylet.key, .amount = asset(amount - baseFee)}); + tx = vault.withdraw( + {.depositor = carol, .id = keylet.key, .amount = asset(amount - baseFee)}); env(tx, delegate::as(alice)); env.close(); BEAST_EXPECT(xrpBalance(env, carol) == *startBalance - baseFee); @@ -4314,8 +4650,9 @@ class Vault_test : public beast::unit_test::suite return sleIssuance->at(sfOutstandingAmount); }; - auto const setupVault = - [&](PrettyAsset const& asset, Account const& owner, Account const& depositor) -> std::pair { + auto const setupVault = [&](PrettyAsset const& asset, + Account const& owner, + Account const& depositor) -> std::pair { Vault vault{env}; auto const& [tx, vaultKeylet] = vault.create({.owner = owner, .asset = asset}); @@ -4327,7 +4664,8 @@ class Vault_test : public beast::unit_test::suite Asset share = vaultSle->at(sfShareMPTID); - env(vault.deposit({.depositor = depositor, .id = vaultKeylet.key, .amount = asset(100)}), + env(vault.deposit( + {.depositor = depositor, .id = vaultKeylet.key, .amount = asset(100)}), ter(tesSUCCESS), THISLINE); env.close(); @@ -4338,7 +4676,10 @@ class Vault_test : public beast::unit_test::suite // attempt to clawback shares while there are assets fails env(vault.clawback( - {.issuer = owner, .id = vaultKeylet.key, .holder = depositor, .amount = share(0).value()}), + {.issuer = owner, + .id = vaultKeylet.key, + .holder = depositor, + .amount = share(0).value()}), ter(tecNO_PERMISSION), THISLINE); env.close(); @@ -4366,7 +4707,10 @@ class Vault_test : public beast::unit_test::suite // attempt to clawback shares while there assetsAvailable == 0 and // assetsTotal > 0 fails env(vault.clawback( - {.issuer = owner, .id = vaultKeylet.key, .holder = depositor, .amount = share(0).value()}), + {.issuer = owner, + .id = vaultKeylet.key, + .holder = depositor, + .amount = share(0).value()}), ter(tecNO_PERMISSION), THISLINE); env.close(); @@ -4384,124 +4728,132 @@ class Vault_test : public beast::unit_test::suite return std::make_pair(vault, vaultKeylet); }; - auto const testCase = - [&](PrettyAsset const& asset, std::string const& prefix, Account const& owner, Account const& depositor) { - { - testcase("VaultClawback (share) - " + prefix + " owner asset clawback fails"); - auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); - env(vault.clawback({ - .issuer = owner, - .id = vaultKeylet.key, - .holder = depositor, - .amount = asset(100).value(), - }), - // when asset is XRP or owner is not issuer clawback fail - // when owner is issuer precision loss occurs as vault is - // empty - asset.native() ? ter(temMALFORMED) - : asset.raw().getIssuer() != owner.id() ? ter(tecNO_PERMISSION) - : ter(tecPRECISION_LOSS), - THISLINE); - env.close(); - } + auto const testCase = [&](PrettyAsset const& asset, + std::string const& prefix, + Account const& owner, + Account const& depositor) { + { + testcase("VaultClawback (share) - " + prefix + " owner asset clawback fails"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); + env(vault.clawback({ + .issuer = owner, + .id = vaultKeylet.key, + .holder = depositor, + .amount = asset(100).value(), + }), + // when asset is XRP or owner is not issuer clawback fail + // when owner is issuer precision loss occurs as vault is + // empty + asset.native() ? ter(temMALFORMED) + : asset.raw().getIssuer() != owner.id() ? ter(tecNO_PERMISSION) + : ter(tecPRECISION_LOSS), + THISLINE); + env.close(); + } - { - testcase("VaultClawback (share) - " + prefix + " owner incomplete share clawback fails"); - auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); - auto const& vaultSle = env.le(vaultKeylet); - BEAST_EXPECT(vaultSle != nullptr); - if (!vaultSle) - return; - Asset share = vaultSle->at(sfShareMPTID); - env(vault.clawback({ - .issuer = owner, - .id = vaultKeylet.key, - .holder = depositor, - .amount = share(1).value(), - }), - ter(tecLIMIT_EXCEEDED), - THISLINE); - env.close(); - } + { + testcase( + "VaultClawback (share) - " + prefix + " owner incomplete share clawback fails"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); + auto const& vaultSle = env.le(vaultKeylet); + BEAST_EXPECT(vaultSle != nullptr); + if (!vaultSle) + return; + Asset share = vaultSle->at(sfShareMPTID); + env(vault.clawback({ + .issuer = owner, + .id = vaultKeylet.key, + .holder = depositor, + .amount = share(1).value(), + }), + ter(tecLIMIT_EXCEEDED), + THISLINE); + env.close(); + } - { - testcase("VaultClawback (share) - " + prefix + " owner implicit complete share clawback"); - auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); - env(vault.clawback({ - .issuer = owner, - .id = vaultKeylet.key, - .holder = depositor, - }), - // when owner is issuer implicit clawback fails - asset.native() || asset.raw().getIssuer() != owner.id() ? ter(tesSUCCESS) : ter(tecWRONG_ASSET), - THISLINE); - env.close(); - } + { + testcase( + "VaultClawback (share) - " + prefix + + " owner implicit complete share clawback"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); + env(vault.clawback({ + .issuer = owner, + .id = vaultKeylet.key, + .holder = depositor, + }), + // when owner is issuer implicit clawback fails + asset.native() || asset.raw().getIssuer() != owner.id() ? ter(tesSUCCESS) + : ter(tecWRONG_ASSET), + THISLINE); + env.close(); + } - { - testcase("VaultClawback (share) - " + prefix + " owner explicit complete share clawback succeeds"); - auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); - auto const& vaultSle = env.le(vaultKeylet); - BEAST_EXPECT(vaultSle != nullptr); - if (!vaultSle) - return; - Asset share = vaultSle->at(sfShareMPTID); - env(vault.clawback({ - .issuer = owner, - .id = vaultKeylet.key, - .holder = depositor, - .amount = share(vaultShareBalance(vaultKeylet)).value(), - }), - ter(tesSUCCESS), - THISLINE); - env.close(); - } - { - testcase("VaultClawback (share) - " + prefix + " owner can clawback own shares"); - auto [vault, vaultKeylet] = setupVault(asset, owner, owner); - auto const& vaultSle = env.le(vaultKeylet); - BEAST_EXPECT(vaultSle != nullptr); - if (!vaultSle) - return; - Asset share = vaultSle->at(sfShareMPTID); - env(vault.clawback({ - .issuer = owner, - .id = vaultKeylet.key, - .holder = owner, - .amount = share(vaultShareBalance(vaultKeylet)).value(), - }), - ter(tesSUCCESS), - THISLINE); - env.close(); - } + { + testcase( + "VaultClawback (share) - " + prefix + + " owner explicit complete share clawback succeeds"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); + auto const& vaultSle = env.le(vaultKeylet); + BEAST_EXPECT(vaultSle != nullptr); + if (!vaultSle) + return; + Asset share = vaultSle->at(sfShareMPTID); + env(vault.clawback({ + .issuer = owner, + .id = vaultKeylet.key, + .holder = depositor, + .amount = share(vaultShareBalance(vaultKeylet)).value(), + }), + ter(tesSUCCESS), + THISLINE); + env.close(); + } + { + testcase("VaultClawback (share) - " + prefix + " owner can clawback own shares"); + auto [vault, vaultKeylet] = setupVault(asset, owner, owner); + auto const& vaultSle = env.le(vaultKeylet); + BEAST_EXPECT(vaultSle != nullptr); + if (!vaultSle) + return; + Asset share = vaultSle->at(sfShareMPTID); + env(vault.clawback({ + .issuer = owner, + .id = vaultKeylet.key, + .holder = owner, + .amount = share(vaultShareBalance(vaultKeylet)).value(), + }), + ter(tesSUCCESS), + THISLINE); + env.close(); + } - { - testcase("VaultClawback (share) - " + prefix + " empty vault share clawback fails"); - auto [vault, vaultKeylet] = setupVault(asset, owner, owner); - auto const& vaultSle = env.le(vaultKeylet); - if (BEAST_EXPECT(vaultSle != nullptr)) - return; - Asset share = vaultSle->at(sfShareMPTID); - env(vault.clawback({ - .issuer = owner, - .id = vaultKeylet.key, - .holder = owner, - .amount = share(vaultShareBalance(vaultKeylet)).value(), - }), - ter(tesSUCCESS), - THISLINE); + { + testcase("VaultClawback (share) - " + prefix + " empty vault share clawback fails"); + auto [vault, vaultKeylet] = setupVault(asset, owner, owner); + auto const& vaultSle = env.le(vaultKeylet); + if (BEAST_EXPECT(vaultSle != nullptr)) + return; + Asset share = vaultSle->at(sfShareMPTID); + env(vault.clawback({ + .issuer = owner, + .id = vaultKeylet.key, + .holder = owner, + .amount = share(vaultShareBalance(vaultKeylet)).value(), + }), + ter(tesSUCCESS), + THISLINE); - // Now the vault is empty, clawback again fails - env(vault.clawback({ - .issuer = owner, - .id = vaultKeylet.key, - .holder = owner, - }), - ter(tecNO_PERMISSION), - THISLINE); - env.close(); - } - }; + // Now the vault is empty, clawback again fails + env(vault.clawback({ + .issuer = owner, + .id = vaultKeylet.key, + .holder = owner, + }), + ter(tecNO_PERMISSION), + THISLINE); + env.close(); + } + }; Account owner{"alice"}; Account depositor{"bob"}; @@ -4561,7 +4913,8 @@ class Vault_test : public beast::unit_test::suite auto const& vaultSle = env.le(vaultKeylet); BEAST_EXPECT(vaultSle != nullptr); - env(vault.deposit({.depositor = depositor, .id = vaultKeylet.key, .amount = asset(100)}), + env(vault.deposit( + {.depositor = depositor, .id = vaultKeylet.key, .amount = asset(100)}), ter(tesSUCCESS), THISLINE); env.close(); @@ -4600,7 +4953,8 @@ class Vault_test : public beast::unit_test::suite } { - testcase("VaultClawback (asset) - " + prefix + " clawback for different asset fails"); + testcase( + "VaultClawback (asset) - " + prefix + " clawback for different asset fails"); auto [vault, vaultKeylet] = setupVault(asset, owner, depositor, issuer); Account issuer2{"issuer2"}; @@ -4616,7 +4970,9 @@ class Vault_test : public beast::unit_test::suite } { - testcase("VaultClawback (asset) - " + prefix + " ambiguous owner/issuer asset clawback fails"); + testcase( + "VaultClawback (asset) - " + prefix + + " ambiguous owner/issuer asset clawback fails"); auto [vault, vaultKeylet] = setupVault(asset, issuer, depositor, issuer); env(vault.clawback({ .issuer = issuer, @@ -4681,7 +5037,9 @@ class Vault_test : public beast::unit_test::suite } { - testcase("VaultClawback (asset) - " + prefix + " partial issuer asset clawback succeeds"); + testcase( + "VaultClawback (asset) - " + prefix + + " partial issuer asset clawback succeeds"); auto [vault, vaultKeylet] = setupVault(asset, owner, depositor, issuer); env(vault.clawback({ @@ -4695,7 +5053,8 @@ class Vault_test : public beast::unit_test::suite } { - testcase("VaultClawback (asset) - " + prefix + " full issuer asset clawback succeeds"); + testcase( + "VaultClawback (asset) - " + prefix + " full issuer asset clawback succeeds"); auto [vault, vaultKeylet] = setupVault(asset, owner, depositor, issuer); env(vault.clawback({ @@ -4709,7 +5068,9 @@ class Vault_test : public beast::unit_test::suite } { - testcase("VaultClawback (asset) - " + prefix + " implicit full issuer asset clawback succeeds"); + testcase( + "VaultClawback (asset) - " + prefix + + " implicit full issuer asset clawback succeeds"); auto [vault, vaultKeylet] = setupVault(asset, owner, depositor, issuer); env(vault.clawback({ @@ -4774,8 +5135,8 @@ class Vault_test : public beast::unit_test::suite BEAST_EXPECT(maxInt64 == "9223372036854775807"); // Naming things is hard - auto const maxInt64Plus1 = - std::to_string(static_cast(std::numeric_limits::max()) + 1); + auto const maxInt64Plus1 = std::to_string( + static_cast(std::numeric_limits::max()) + 1); BEAST_EXPECT(maxInt64Plus1 == "9223372036854775808"); auto const initialXRP = to_string(INITIAL_XRP); @@ -4810,8 +5171,8 @@ class Vault_test : public beast::unit_test::suite // This value will be rounded auto const insertAt = maxInt64Plus1.size() - 3; - auto const decimalTest = - maxInt64Plus1.substr(0, insertAt) + "." + maxInt64Plus1.substr(insertAt); // (max int64+1) / 1000 + auto const decimalTest = maxInt64Plus1.substr(0, insertAt) + "." + + maxInt64Plus1.substr(insertAt); // (max int64+1) / 1000 BEAST_EXPECT(decimalTest == "9223372036854775.808"); tx[sfAssetsMaximum] = decimalTest; auto const newKeylet = keylet::vault(owner.id(), env.seq(owner)); @@ -4862,8 +5223,8 @@ class Vault_test : public beast::unit_test::suite // This value will be rounded auto const insertAt = maxInt64Plus1.size() - 1; - auto const decimalTest = - maxInt64Plus1.substr(0, insertAt) + "." + maxInt64Plus1.substr(insertAt); // (max int64+1) / 10 + auto const decimalTest = maxInt64Plus1.substr(0, insertAt) + "." + + maxInt64Plus1.substr(insertAt); // (max int64+1) / 10 BEAST_EXPECT(decimalTest == "922337203685477580.8"); tx[sfAssetsMaximum] = decimalTest; auto const newKeylet = keylet::vault(owner.id(), env.seq(owner)); @@ -4914,8 +5275,8 @@ class Vault_test : public beast::unit_test::suite // These values will be rounded to 15 significant digits { auto const insertAt = maxInt64Plus1.size() - 1; - auto const decimalTest = - maxInt64Plus1.substr(0, insertAt) + "." + maxInt64Plus1.substr(insertAt); // (max int64+1) / 10 + auto const decimalTest = maxInt64Plus1.substr(0, insertAt) + "." + + maxInt64Plus1.substr(insertAt); // (max int64+1) / 10 BEAST_EXPECT(decimalTest == "922337203685477580.8"); tx[sfAssetsMaximum] = decimalTest; auto const newKeylet = keylet::vault(owner.id(), env.seq(owner)); @@ -4926,7 +5287,9 @@ class Vault_test : public beast::unit_test::suite if (!BEAST_EXPECT(vaultSle)) return; - BEAST_EXPECT((vaultSle->at(sfAssetsMaximum) == Number{9223372036854776, 2, Number::normalized{}})); + BEAST_EXPECT( + (vaultSle->at(sfAssetsMaximum) == + Number{9223372036854776, 2, Number::normalized{}})); } { tx[sfAssetsMaximum] = "9223372036854775807e40"; // max int64 * 10^40 @@ -4938,7 +5301,9 @@ class Vault_test : public beast::unit_test::suite if (!BEAST_EXPECT(vaultSle)) return; - BEAST_EXPECT((vaultSle->at(sfAssetsMaximum) == Number{9223372036854776, 43, Number::normalized{}})); + BEAST_EXPECT( + (vaultSle->at(sfAssetsMaximum) == + Number{9223372036854776, 43, Number::normalized{}})); } { tx[sfAssetsMaximum] = "9223372036854775807e-40"; // max int64 * 10^-40 @@ -4950,7 +5315,9 @@ class Vault_test : public beast::unit_test::suite if (!BEAST_EXPECT(vaultSle)) return; - BEAST_EXPECT((vaultSle->at(sfAssetsMaximum) == Number{9223372036854776, -37, Number::normalized{}})); + BEAST_EXPECT( + (vaultSle->at(sfAssetsMaximum) == + Number{9223372036854776, -37, Number::normalized{}})); } { tx[sfAssetsMaximum] = "9223372036854775807e-100"; // max int64 * 10^-100 diff --git a/src/test/app/XChain_test.cpp b/src/test/app/XChain_test.cpp index 2921e10ae4..c74857fa86 100644 --- a/src/test/app/XChain_test.cpp +++ b/src/test/app/XChain_test.cpp @@ -277,8 +277,9 @@ struct BalanceTransfer bool payees_received(STAmount const& reward) const { - return std::all_of( - reward_accounts.begin(), reward_accounts.end(), [&](balance const& b) { return b.diff() == reward; }); + return std::all_of(reward_accounts.begin(), reward_accounts.end(), [&](balance const& b) { + return b.diff() == reward; + }); } bool @@ -291,7 +292,8 @@ struct BalanceTransfer has_happened(STAmount const& amt, STAmount const& reward, bool check_payer = true) { auto reward_cost = multiply(reward, STAmount(reward_accounts.size()), reward.issue()); - return check_most_balances(amt, reward) && (!check_payer || payer_.diff() == -(reward_cost + txFees_)); + return check_most_balances(amt, reward) && + (!check_payer || payer_.diff() == -(reward_cost + txFees_)); } bool @@ -325,9 +327,13 @@ struct BridgeDef return {}; return minAccountCreate; }(); - mcEnv.tx(bridge_create(doorA, jvb, reward, optAccountCreate)).tx(jtx::signers(doorA, quorum, signers)).close(); + mcEnv.tx(bridge_create(doorA, jvb, reward, optAccountCreate)) + .tx(jtx::signers(doorA, quorum, signers)) + .close(); - scEnv.tx(bridge_create(doorB, jvb, reward, optAccountCreate)).tx(jtx::signers(doorB, quorum, signers)).close(); + scEnv.tx(bridge_create(doorB, jvb, reward, optAccountCreate)) + .tx(jtx::signers(doorB, quorum, signers)) + .close(); } }; @@ -394,7 +400,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj XEnv(*this).tx(create_bridge(mcDoor)).close().tx(create_bridge(mcDoor), ter(tecDUPLICATE)); // Create USD bridge Alice -> Bob ... should succeed - XEnv(*this).tx(create_bridge(mcAlice, bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"])), ter(tesSUCCESS)); + XEnv(*this).tx( + create_bridge(mcAlice, bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"])), + ter(tesSUCCESS)); // Create USD bridge, Alice is both the locking door and locking issue, // ... should fail. @@ -404,7 +412,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // Bridge where the two door accounts are equal. XEnv(*this).tx( - create_bridge(mcBob, bridge(mcBob, mcGw["USD"], mcBob, mcGw["USD"])), ter(temXCHAIN_EQUAL_DOOR_ACCOUNTS)); + create_bridge(mcBob, bridge(mcBob, mcGw["USD"], mcBob, mcGw["USD"])), + ter(temXCHAIN_EQUAL_DOOR_ACCOUNTS)); // Both door accounts are on the same chain. This is not allowed. // Although it doesn't violate any invariants, it's not a useful thing @@ -412,7 +421,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj XEnv(*this) .tx(create_bridge(mcAlice, bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"]))) .close() - .tx(create_bridge(mcBob, bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"])), ter(tecDUPLICATE)) + .tx(create_bridge(mcBob, bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"])), + ter(tecDUPLICATE)) .close(); // Create a bridge on an account with exactly enough balance to @@ -430,10 +440,12 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .tx(create_bridge(mcuDoor, jvub), ter(tecINSUFFICIENT_RESERVE)); // Reward amount is non-xrp - XEnv(*this).tx(create_bridge(mcDoor, jvb, mcUSD(1)), ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); + XEnv(*this).tx( + create_bridge(mcDoor, jvb, mcUSD(1)), ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); // Reward amount is XRP and negative - XEnv(*this).tx(create_bridge(mcDoor, jvb, XRP(-1)), ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); + XEnv(*this).tx( + create_bridge(mcDoor, jvb, XRP(-1)), ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); // Reward amount is 1 xrp => should succeed XEnv(*this).tx(create_bridge(mcDoor, jvb, XRP(1)), ter(tesSUCCESS)); @@ -443,14 +455,18 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // Min create amount is non-xrp XEnv(*this).tx( - create_bridge(mcDoor, jvb, XRP(1), mcUSD(100)), ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); + create_bridge(mcDoor, jvb, XRP(1), mcUSD(100)), + ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); // Min create amount is zero (should fail, currently succeeds) - XEnv(*this).tx(create_bridge(mcDoor, jvb, XRP(1), XRP(0)), ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); + XEnv(*this).tx( + create_bridge(mcDoor, jvb, XRP(1), XRP(0)), + ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); // Min create amount is negative XEnv(*this).tx( - create_bridge(mcDoor, jvb, XRP(1), XRP(-1)), ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); + create_bridge(mcDoor, jvb, XRP(1), XRP(-1)), + ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); // coverage test: BridgeCreate::preflight() - create bridge when feature // disabled. @@ -461,13 +477,16 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // coverage test: BridgeCreate::preclaim() returns tecNO_ISSUER. XEnv(*this).tx( - create_bridge(mcAlice, bridge(mcAlice, mcuAlice["USD"], mcBob, mcBob["USD"])), ter(tecNO_ISSUER)); + create_bridge(mcAlice, bridge(mcAlice, mcuAlice["USD"], mcBob, mcBob["USD"])), + ter(tecNO_ISSUER)); // coverage test: create_bridge transaction with incorrect flag XEnv(*this).tx(create_bridge(mcAlice, jvb), txflags(tfFillOrKill), ter(temINVALID_FLAG)); // coverage test: create_bridge transaction with xchain feature disabled - XEnv(*this).disableFeature(featureXChainBridge).tx(create_bridge(mcAlice, jvb), ter(temDISABLED)); + XEnv(*this) + .disableFeature(featureXChainBridge) + .tx(create_bridge(mcAlice, jvb), ter(temDISABLED)); } void @@ -573,7 +592,11 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj env.tx(create_bridge(A, bridge(A, CUSD, B, BEUR)), ter(tecDUPLICATE)).close(); // Test case 6 and 7, commits - env.tx(trust(C, BUSD(1000))).tx(trust(A, BUSD(1000))).close().tx(pay(B, C, BUSD(1000))).close(); + env.tx(trust(C, BUSD(1000))) + .tx(trust(A, BUSD(1000))) + .close() + .tx(pay(B, C, BUSD(1000))) + .close(); auto const aBalanceStart = env.balance(A, BUSD); auto const cBalanceStart = env.balance(C, BUSD); env.tx(xchain_commit(C, goodBridge1, 1, BUSD(50))).close(); @@ -808,7 +831,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj std::cout << "Markdown output for matrix test: " << fname << "\n"; auto print_res = [](auto tup) -> std::string { - std::string status = std::string(transToken(std::get<0>(tup))) + " / " + transToken(std::get<1>(tup)); + std::string status = + std::string(transToken(std::get<0>(tup))) + " / " + transToken(std::get<1>(tup)); if (std::get<2>(tup)) return status; @@ -830,7 +854,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj res += "\n"; res += "| :--- | "; - std::apply([&](auto const&... ic) { (((void)ic.first, res += ":---: | "), ...); }, ics); + std::apply( + [&](auto const&... ic) { (((void)ic.first, res += ":---: | "), ...); }, ics); res += "\n"; auto output = [&](auto const& lc, auto const& ic) { @@ -860,8 +885,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj std::ofstream ofs(ter_fname); for (auto& t : test_result) { - ofs << "{ " << std::string(transToken(std::get<0>(t))) << ", " << std::string(transToken(std::get<1>(t))) - << "}\n,"; + ofs << "{ " << std::string(transToken(std::get<0>(t))) << ", " + << std::string(transToken(std::get<1>(t))) << "}\n,"; } #endif } @@ -874,7 +899,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // Changing a non-existent bridge should fail XEnv(*this).tx( - bridge_modify(mcAlice, bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"]), XRP(2), std::nullopt), + bridge_modify( + mcAlice, bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"]), XRP(2), std::nullopt), ter(tecNO_ENTRY)); // must change something @@ -890,21 +916,27 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .tx(bridge_modify(mcDoor, jvb, {}, {}), ter(temMALFORMED)); // Reward amount is non-xrp - XEnv(*this).tx(bridge_modify(mcDoor, jvb, mcUSD(2), XRP(10)), ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); + XEnv(*this).tx( + bridge_modify(mcDoor, jvb, mcUSD(2), XRP(10)), ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); // Reward amount is XRP and negative - XEnv(*this).tx(bridge_modify(mcDoor, jvb, XRP(-2), XRP(10)), ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); + XEnv(*this).tx( + bridge_modify(mcDoor, jvb, XRP(-2), XRP(10)), ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); // Min create amount is non-xrp XEnv(*this).tx( - bridge_modify(mcDoor, jvb, XRP(2), mcUSD(10)), ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); + bridge_modify(mcDoor, jvb, XRP(2), mcUSD(10)), + ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); // Min create amount is zero - XEnv(*this).tx(bridge_modify(mcDoor, jvb, XRP(2), XRP(0)), ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); + XEnv(*this).tx( + bridge_modify(mcDoor, jvb, XRP(2), XRP(0)), + ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); // Min create amount is negative XEnv(*this).tx( - bridge_modify(mcDoor, jvb, XRP(2), XRP(-10)), ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); + bridge_modify(mcDoor, jvb, XRP(2), XRP(-10)), + ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); // First check the regular claim process (without bridge_modify) for (auto withClaim : {false, true}) @@ -926,9 +958,17 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM, + withClaim); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) + scEnv + .multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) .close(); if (withClaim) @@ -968,9 +1008,17 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj scEnv.tx(bridge_modify(Account::master, jvb, XRP(2), XRP(10))).close(); BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM, + withClaim); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) + scEnv + .multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) .close(); if (withClaim) @@ -1013,18 +1061,28 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj scEnv.tx(jtx::signers(Account::master, quorum, alt_signers)).close(); BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM, + withClaim); // submit claim using outdated signers - should fail scEnv .multiTx( - claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers), + claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers), ter(tecNO_PERMISSION)) .close(); if (withClaim) { // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecXCHAIN_CLAIM_NO_QUORUM)).close(); + scEnv + .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), + ter(tecXCHAIN_CLAIM_NO_QUORUM)) + .close(); } // make sure transfer has not happened as we sent attestations @@ -1032,7 +1090,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BEAST_EXPECT(transfer.has_not_happened()); // submit claim using current signers - should succeed - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, alt_signers)) + scEnv + .multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, alt_signers)) .close(); if (withClaim) { @@ -1051,7 +1111,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj XEnv(*this) .tx(create_bridge(mcDoor, jvb)) .close() - .tx(bridge_modify(mcDoor, jvb, XRP(1), XRP(2)), txflags(tfFillOrKill), ter(temINVALID_FLAG)); + .tx(bridge_modify(mcDoor, jvb, XRP(1), XRP(2)), + txflags(tfFillOrKill), + ter(temINVALID_FLAG)); // coverage test: bridge_modify transaction with xchain feature // disabled @@ -1078,7 +1140,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .close() .tx(sidechain_xchain_account_create(mcAlice, jvb, scuAlice, XRP(100), reward)) .close() - .tx(bridge_modify(mcDoor, jvb, {}, XRP(2)), txflags(tfClearAccountCreateAmount), ter(temMALFORMED)) + .tx(bridge_modify(mcDoor, jvb, {}, XRP(2)), + txflags(tfClearAccountCreateAmount), + ter(temMALFORMED)) .close() .tx(bridge_modify(mcDoor, jvb, XRP(3), {}), txflags(tfClearAccountCreateAmount)) .close() @@ -1120,7 +1184,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // Non-existent bridge XEnv(*this, true) - .tx(xchain_create_claim_id(scAlice, bridge(mcAlice, mcAlice["USD"], scBob, scBob["USD"]), reward, mcAlice), + .tx(xchain_create_claim_id( + scAlice, bridge(mcAlice, mcAlice["USD"], scBob, scBob["USD"]), reward, mcAlice), ter(tecNO_ENTRY)) .close(); @@ -1129,7 +1194,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .tx(create_bridge(Account::master, jvb)) .fund(res1 - xrp_dust, scuAlice) // barely not enough .close() - .tx(xchain_create_claim_id(scuAlice, jvb, reward, mcAlice), ter(tecINSUFFICIENT_RESERVE)) + .tx(xchain_create_claim_id(scuAlice, jvb, reward, mcAlice), + ter(tecINSUFFICIENT_RESERVE)) .close(); // The specified reward doesn't match the reward on the bridge (test @@ -1138,14 +1204,16 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj XEnv(*this, true) .tx(create_bridge(Account::master, jvb)) .close() - .tx(xchain_create_claim_id(scAlice, jvb, split_reward_quorum, mcAlice), ter(tecXCHAIN_REWARD_MISMATCH)) + .tx(xchain_create_claim_id(scAlice, jvb, split_reward_quorum, mcAlice), + ter(tecXCHAIN_REWARD_MISMATCH)) .close(); // A reward amount that isn't XRP XEnv(*this, true) .tx(create_bridge(Account::master, jvb)) .close() - .tx(xchain_create_claim_id(scAlice, jvb, mcUSD(1), mcAlice), ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)) + .tx(xchain_create_claim_id(scAlice, jvb, mcUSD(1), mcAlice), + ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)) .close(); // coverage test: xchain_create_claim_id transaction with incorrect @@ -1153,7 +1221,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj XEnv(*this, true) .tx(create_bridge(Account::master, jvb)) .close() - .tx(xchain_create_claim_id(scAlice, jvb, reward, mcAlice), txflags(tfFillOrKill), ter(temINVALID_FLAG)) + .tx(xchain_create_claim_id(scAlice, jvb, reward, mcAlice), + txflags(tfFillOrKill), + ter(temINVALID_FLAG)) .close(); // coverage test: xchain_create_claim_id transaction with xchain @@ -1185,7 +1255,10 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj Balance alice_bal(xenv, mcAlice); auto const amt = XRP(1000); - xenv.tx(create_bridge(mcDoor, jvb)).close().tx(xchain_commit(mcAlice, jvb, 1, amt, scBob)).close(); + xenv.tx(create_bridge(mcDoor, jvb)) + .close() + .tx(xchain_commit(mcAlice, jvb, 1, amt, scBob)) + .close(); STAmount claim_cost = amt; BEAST_EXPECT(alice_bal.diff() == -(claim_cost + tx_fee)); @@ -1277,7 +1350,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj XEnv(*this) .tx(create_bridge(mcDoor)) .close() - .tx(xchain_commit(mcAlice, jvb, 1, one_xrp, scBob), txflags(tfFillOrKill), ter(temINVALID_FLAG)); + .tx(xchain_commit(mcAlice, jvb, 1, one_xrp, scBob), + txflags(tfFillOrKill), + ter(temINVALID_FLAG)); // coverage test: xchain_commit transaction with xchain feature // disabled @@ -1297,7 +1372,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj XRPAmount res0 = reserve(0); XRPAmount tx_fee = txFee(); - auto multiTtxFee = [&](std::uint32_t m) -> STAmount { return multiply(tx_fee, STAmount(m), xrpIssue()); }; + auto multiTtxFee = [&](std::uint32_t m) -> STAmount { + return multiply(tx_fee, STAmount(m), xrpIssue()); + }; // Add an attestation to a claim id that has already reached quorum. // This should succeed and share in the reward. @@ -1329,7 +1406,16 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj scEnv .multiTx(claim_attestations( - scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers, UT_XCHAIN_DEFAULT_QUORUM)) + scAttester, + jvb, + mcAlice, + amt, + payees, + true, + claimID, + dst, + signers, + UT_XCHAIN_DEFAULT_QUORUM)) .close(); scEnv .tx(claim_attestation( @@ -1399,9 +1485,12 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, &payees[0], 3, withClaim); + BalanceTransfer transfer( + scEnv, Account::master, scBob, scAlice, &payees[0], 3, withClaim); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers_, 3)) + scEnv + .multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers_, 3)) .close(); if (withClaim) @@ -1438,7 +1527,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj } return result; }(); - STAmount const split_reward_ = divide(reward, STAmount(signers_.size()), reward.issue()); + STAmount const split_reward_ = + divide(reward, STAmount(signers_.size()), reward.issue()); mcEnv.tx(create_bridge(mcDoor, jvb)).close(); @@ -1455,9 +1545,12 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, &payees[2], 2, withClaim); + BalanceTransfer transfer( + scEnv, Account::master, scBob, scAlice, &payees[2], 2, withClaim); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers_, 2, 2)) + scEnv + .multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers_, 2, 2)) .close(); if (withClaim) @@ -1510,16 +1603,22 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj auto const amt = XRP(1000); mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, &payees[0], 2, withClaim); + BalanceTransfer transfer( + scEnv, Account::master, scBob, scAlice, &payees[0], 2, withClaim); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers_, 2)) + scEnv + .multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers_, 2)) .close(); if (withClaim) { BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecXCHAIN_CLAIM_NO_QUORUM)).close(); + scEnv + .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), + ter(tecXCHAIN_CLAIM_NO_QUORUM)) + .close(); } BEAST_EXPECT(!!scEnv.claimID(jvb, claimID)); // claim id still present @@ -1564,9 +1663,12 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, &payees[1], 2, withClaim); + BalanceTransfer transfer( + scEnv, Account::master, scBob, scAlice, &payees[1], 2, withClaim); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers_, 2, 1)) + scEnv + .multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers_, 2, 1)) .close(); if (withClaim) @@ -1574,7 +1676,10 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecXCHAIN_CLAIM_NO_QUORUM)).close(); + scEnv + .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), + ter(tecXCHAIN_CLAIM_NO_QUORUM)) + .close(); } BEAST_EXPECT(!!scEnv.claimID(jvb, claimID)); // claim id still present @@ -1602,7 +1707,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .tx(sidechain_xchain_account_create(mcCarol, jvb, scuCarol, amt, reward)) .close(); - BEAST_EXPECT(door.diff() == (multiply(amt_plus_reward, STAmount(3), xrpIssue()) - tx_fee)); + BEAST_EXPECT( + door.diff() == (multiply(amt_plus_reward, STAmount(3), xrpIssue()) - tx_fee)); BEAST_EXPECT(carol.diff() == -(amt + reward + tx_fee)); } @@ -1747,7 +1853,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj Balance door(mcEnv, mcDoor); Balance carol(mcEnv, mcCarol); - mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, amt, reward)).close(); + mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, amt, reward)) + .close(); BEAST_EXPECT(door.diff() == amt_plus_reward); BEAST_EXPECT(carol.diff() == -(amt_plus_reward + tx_fee)); @@ -1788,7 +1895,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj Balance door(mcEnv, mcDoor); Balance carol(mcEnv, mcCarol); - mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scAlice, amt, reward)).close(); + mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scAlice, amt, reward)) + .close(); BEAST_EXPECT(door.diff() == amt_plus_reward); BEAST_EXPECT(carol.diff() == -(amt_plus_reward + tx_fee)); @@ -1830,7 +1938,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj Balance door(mcEnv, mcDoor); Balance carol(mcEnv, mcCarol); - mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scAlice, amt, reward)).close(); + mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scAlice, amt, reward)) + .close(); BEAST_EXPECT(door.diff() == amt_plus_reward); BEAST_EXPECT(carol.diff() == -(amt_plus_reward + tx_fee)); @@ -1882,7 +1991,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .tx(sidechain_xchain_account_create(mcCarol, jvb, scuCarol, amt, reward)) .close(); // and Carol will get claim #3 - BEAST_EXPECT(door.diff() == (multiply(amt_plus_reward, STAmount(3), xrpIssue()) - tx_fee)); + BEAST_EXPECT( + door.diff() == (multiply(amt_plus_reward, STAmount(3), xrpIssue()) - tx_fee)); BEAST_EXPECT(carol.diff() == -(amt + reward + tx_fee)); } @@ -1937,7 +2047,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BEAST_EXPECTS(scEnv.claimCount(jvb) == 1, "scuAlice created"); scEnv.multiTx(att_create_acct_vec(2, amt, scuBob, 1, 3)) - .multiTx(att_create_acct_vec(1, amt, scuAlice, 1, 3), ter(tecXCHAIN_ACCOUNT_CREATE_PAST)) + .multiTx( + att_create_acct_vec(1, amt, scuAlice, 1, 3), + ter(tecXCHAIN_ACCOUNT_CREATE_PAST)) .close(); txCount += 2; @@ -1954,7 +2066,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // because of the division of the rewards among attesters, // sometimes a couple drops are left over unspent in the // door account (here 2 drops) - BEAST_EXPECT(multiply(amt_plus_reward, STAmount(3), xrpIssue()) + door.diff() < drops(3)); + BEAST_EXPECT( + multiply(amt_plus_reward, STAmount(3), xrpIssue()) + door.diff() < drops(3)); BEAST_EXPECT(attester.diff() == -multiTtxFee(txCount)); BEAST_EXPECT(scEnv.balance(scuAlice) == amt); BEAST_EXPECT(scEnv.balance(scuBob) == amt); @@ -1972,7 +2085,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj scEnv.tx(create_bridge(Account::master, jvb)) .tx(jtx::signers(Account::master, quorum, signers)) .close() - .tx(claim_attestation(scAttester, jvb, mcAlice, XRP(1000), payees[0], true, 1, {}, signers[0]), + .tx(claim_attestation( + scAttester, jvb, mcAlice, XRP(1000), payees[0], true, 1, {}, signers[0]), txflags(tfFillOrKill), ter(temINVALID_FLAG)) .close(); @@ -1986,7 +2100,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .tx(jtx::signers(Account::master, quorum, signers)) .disableFeature(featureXChainBridge) .close() - .tx(claim_attestation(scAttester, jvb, mcAlice, XRP(1000), payees[0], true, 1, {}, signers[0]), + .tx(claim_attestation( + scAttester, jvb, mcAlice, XRP(1000), payees[0], true, 1, {}, signers[0]), ter(temDISABLED)) .close(); } @@ -2022,8 +2137,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj for (int i = 0; i < signers.size(); ++i) { - auto const att = - claim_attestation(scAttester, jvb, mcAlice, amt, payees[i], true, claimID, dst, signers[i]); + auto const att = claim_attestation( + scAttester, jvb, mcAlice, amt, payees[i], true, claimID, dst, signers[i]); TER const expectedTER = i < quorum ? tesSUCCESS : TER{tecXCHAIN_NO_CLAIM_ID}; if (i + 1 == quorum) @@ -2078,8 +2193,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj { // G1: master key - auto att = - claim_attestation(scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, alt_signers[0]); + auto att = claim_attestation( + scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, alt_signers[0]); scEnv.tx(att).close(); } { @@ -2087,8 +2202,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // 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(); - auto att = - claim_attestation(scAttester, jvb, mcAlice, amt, payees[1], true, claimID, dst, alt_signers[0]); + auto att = claim_attestation( + scAttester, jvb, mcAlice, amt, payees[1], true, claimID, dst, alt_signers[0]); att[sfAttestationSignerAccount.getJsonName()] = alt_signers[1].account.human(); scEnv.tx(att).close(); } @@ -2117,27 +2232,36 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj std::vector tempSignerList = {signers[0]}; scEnv.tx(jtx::signers(alt_signers[2].account, 1, tempSignerList)); auto att = claim_attestation( - scAttester, jvb, mcAlice, amt, payees[2], true, claimID, dst, tempSignerList.front()); + scAttester, + jvb, + mcAlice, + amt, + payees[2], + true, + claimID, + dst, + tempSignerList.front()); att[sfAttestationSignerAccount.getJsonName()] = alt_signers[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(); - auto att = - claim_attestation(scAttester, jvb, mcAlice, amt, payees[2], true, claimID, dst, alt_signers[2]); + auto att = claim_attestation( + scAttester, jvb, mcAlice, amt, payees[2], true, claimID, dst, alt_signers[2]); scEnv.tx(att, ter(tecXCHAIN_BAD_PUBLIC_KEY_ACCOUNT_PAIR)).close(); } { // --B4: not on signer list - auto att = claim_attestation(scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, signers[0]); + auto att = claim_attestation( + scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, signers[0]); scEnv.tx(att, ter(tecNO_PERMISSION)).close(); } { // --B5: missing sfAttestationSignerAccount field // Then submit the one with the field. Should reach quorum. - auto att = - claim_attestation(scAttester, jvb, mcAlice, amt, payees[3], true, claimID, dst, alt_signers[3]); + auto att = claim_attestation( + scAttester, jvb, mcAlice, amt, payees[3], true, claimID, dst, alt_signers[3]); att.removeMember(sfAttestationSignerAccount.getJsonName()); scEnv.tx(att, ter(temMALFORMED)).close(); BEAST_EXPECT(dstStartBalance == scEnv.env_.balance(dst)); @@ -2197,8 +2321,18 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj for (int i = 0; i < signers.size(); ++i) { auto const att = create_account_attestation( - signers[0].account, xrp_b.jvb, a, amt, xrp_b.reward, signers[i].account, true, 1, ua, signers[i]); - TER const expectedTER = i < xrp_b.quorum ? tesSUCCESS : TER{tecXCHAIN_ACCOUNT_CREATE_PAST}; + signers[0].account, + xrp_b.jvb, + a, + amt, + xrp_b.reward, + signers[i].account, + true, + 1, + ua, + signers[i]); + TER const expectedTER = + i < xrp_b.quorum ? tesSUCCESS : TER{tecXCHAIN_ACCOUNT_CREATE_PAST}; scEnv.tx(att, ter(expectedTER)).close(); if (i + 1 < xrp_b.quorum) @@ -2242,9 +2376,17 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM, + withClaim); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) + scEnv + .multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) .close(); if (withClaim) { @@ -2279,11 +2421,21 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj std::uint32_t const claimID = 1; mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, &payees[0], 1, withClaim); + BalanceTransfer transfer( + scEnv, Account::master, scBob, scAlice, &payees[0], 1, withClaim); jtx::signer master_signer(Account::master); scEnv - .tx(claim_attestation(scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, master_signer), + .tx(claim_attestation( + scAttester, + jvb, + mcAlice, + amt, + payees[0], + true, + claimID, + dst, + master_signer), ter(tecXCHAIN_NO_SIGNERS_LIST)) .close(); @@ -2314,11 +2466,21 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj std::uint32_t const claimID = 1; mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, &payees[0], 1, withClaim); + BalanceTransfer transfer( + scEnv, Account::master, scBob, scAlice, &payees[0], 1, withClaim); jtx::signer master_signer(payees[0]); scEnv - .tx(claim_attestation(scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, master_signer), + .tx(claim_attestation( + scAttester, + jvb, + mcAlice, + amt, + payees[0], + true, + claimID, + dst, + master_signer), ter(tecXCHAIN_NO_SIGNERS_LIST)) .close(); @@ -2345,11 +2507,21 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj auto dst(withClaim ? std::nullopt : std::optional{scBob}); auto const amt = XRP(1000); std::uint32_t const claimID = 1; - mcEnv.tx(xchain_commit(mcAlice, jvb_unknown, claimID, amt, dst), ter(tecNO_ENTRY)).close(); + mcEnv.tx(xchain_commit(mcAlice, jvb_unknown, claimID, amt, dst), ter(tecNO_ENTRY)) + .close(); BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, payees, withClaim); scEnv - .tx(claim_attestation(scAttester, jvb_unknown, mcAlice, amt, payees[0], true, claimID, dst, signers[0]), + .tx(claim_attestation( + scAttester, + jvb_unknown, + mcAlice, + amt, + payees[0], + true, + claimID, + dst, + signers[0]), ter(tecNO_ENTRY)) .close(); @@ -2358,7 +2530,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb_unknown, claimID, amt, scBob), ter(tecNO_ENTRY)).close(); + scEnv.tx(xchain_claim(scAlice, jvb_unknown, claimID, amt, scBob), ter(tecNO_ENTRY)) + .close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -2388,7 +2561,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // attest using non-existent claim id scEnv - .tx(claim_attestation(scAttester, jvb, mcAlice, amt, payees[0], true, 999, dst, signers[0]), + .tx(claim_attestation( + scAttester, jvb, mcAlice, amt, payees[0], true, 999, dst, signers[0]), ter(tecXCHAIN_NO_CLAIM_ID)) .close(); if (withClaim) @@ -2396,7 +2570,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BEAST_EXPECT(transfer.has_not_happened()); // claim using non-existent claim id - scEnv.tx(xchain_claim(scAlice, jvb, 999, amt, scBob), ter(tecXCHAIN_NO_CLAIM_ID)).close(); + scEnv.tx(xchain_claim(scAlice, jvb, 999, amt, scBob), ter(tecXCHAIN_NO_CLAIM_ID)) + .close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -2423,9 +2598,17 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM, + withClaim); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) + scEnv + .multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) .close(); if (withClaim) { @@ -2433,7 +2616,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // submit a claim transaction with the wrong account (scGw // instead of scAlice) - scEnv.tx(xchain_claim(scGw, jvb, claimID, amt, scBob), ter(tecXCHAIN_BAD_CLAIM_ID)).close(); + scEnv.tx(xchain_claim(scGw, jvb, claimID, amt, scBob), ter(tecXCHAIN_BAD_CLAIM_ID)) + .close(); BEAST_EXPECT(transfer.has_not_happened()); } else @@ -2471,7 +2655,10 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecXCHAIN_CLAIM_NO_QUORUM)).close(); + scEnv + .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), + ter(tecXCHAIN_CLAIM_NO_QUORUM)) + .close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -2502,14 +2689,18 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj auto tooFew = quorum - 1; scEnv - .multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers, tooFew)) + .multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers, tooFew)) .close(); if (withClaim) { BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecXCHAIN_CLAIM_NO_QUORUM)).close(); + scEnv + .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), + ter(tecXCHAIN_CLAIM_NO_QUORUM)) + .close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -2539,7 +2730,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj scEnv .multiTx( - claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, 0, dst, signers), + claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, 0, dst, signers), ter(tecXCHAIN_NO_CLAIM_ID)) .close(); if (withClaim) @@ -2547,7 +2739,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, 0, amt, scBob), ter(tecXCHAIN_NO_CLAIM_ID)).close(); + scEnv.tx(xchain_claim(scAlice, jvb, 0, amt, scBob), ter(tecXCHAIN_NO_CLAIM_ID)) + .close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -2577,9 +2770,17 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM, + withClaim); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) + scEnv + .multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) .close(); if (withClaim) @@ -2587,7 +2788,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, scUSD(1000), scBob), ter(temBAD_AMOUNT)).close(); + scEnv + .tx(xchain_claim(scAlice, jvb, claimID, scUSD(1000), scBob), ter(temBAD_AMOUNT)) + .close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -2614,9 +2817,17 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM, + withClaim); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) + scEnv + .multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) .close(); if (withClaim) { @@ -2653,20 +2864,30 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM, + withClaim); if (withClaim) { - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) + scEnv + .multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) .close(); BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecUNFUNDED_PAYMENT)).close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecUNFUNDED_PAYMENT)) + .close(); } else { - auto txns = claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers); + auto txns = claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers); for (int i = 0; i < UT_XCHAIN_DEFAULT_QUORUM - 1; ++i) { scEnv.tx(txns[i]).close(); @@ -2676,7 +2897,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // The attestation should succeed, because it adds an // attestation, but the claim should fail with insufficient // funds - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecUNFUNDED_PAYMENT)).close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecUNFUNDED_PAYMENT)) + .close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -2698,7 +2920,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj res0 + reward, scuAlice) // just not enough because of fees .close() - .tx(xchain_create_claim_id(scuAlice, jvb, reward, mcAlice), ter(tecINSUFFICIENT_RESERVE)) + .tx(xchain_create_claim_id(scuAlice, jvb, reward, mcAlice), + ter(tecINSUFFICIENT_RESERVE)) .close(); auto dst(withClaim ? std::nullopt : std::optional{scBob}); @@ -2709,7 +2932,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BalanceTransfer transfer(scEnv, Account::master, scBob, scuAlice, payees, withClaim); scEnv - .tx(claim_attestation(scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, signers[0]), + .tx(claim_attestation( + scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, signers[0]), ter(tecXCHAIN_NO_CLAIM_ID)) .close(); if (withClaim) @@ -2717,7 +2941,10 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scuAlice, jvb, claimID, amt, scBob), ter(tecXCHAIN_NO_CLAIM_ID)).close(); + scEnv + .tx(xchain_claim(scuAlice, jvb, claimID, amt, scBob), + ter(tecXCHAIN_NO_CLAIM_ID)) + .close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -2745,8 +2972,15 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); - auto txns = claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM, + withClaim); + auto txns = claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers); for (int i = 0; i < UT_XCHAIN_DEFAULT_QUORUM - 1; ++i) { scEnv.tx(txns[i]).close(); @@ -2758,7 +2992,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecNO_PERMISSION)).close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecNO_PERMISSION)) + .close(); // the transfer failed, but check that we can still use the // claimID with a different account @@ -2770,7 +3005,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj else { scEnv.tx(txns.back()).close(); - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecNO_PERMISSION)).close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecNO_PERMISSION)) + .close(); // A way would be to remove deposit auth and resubmit the // attestations (even though the witness servers won't do // it) @@ -2806,8 +3042,15 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); - auto txns = claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM, + withClaim); + auto txns = claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers); for (int i = 0; i < UT_XCHAIN_DEFAULT_QUORUM - 1; ++i) { scEnv.tx(txns[i]).close(); @@ -2818,7 +3061,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecDST_TAG_NEEDED)).close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecDST_TAG_NEEDED)) + .close(); // the transfer failed, but check that we can still use the // claimID with a different account @@ -2830,7 +3074,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj else { scEnv.tx(txns.back()).close(); - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecDST_TAG_NEEDED)).close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecDST_TAG_NEEDED)) + .close(); // A way would be to remove the destination tag requirement // and resubmit the attestations (even though the witness // servers won't do it) @@ -2871,7 +3116,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // should not occur because dest account has deposit auth set Balance scBob_bal(scEnv, scBob); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); + scEnv.multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); BEAST_EXPECT(scBob_bal.diff() == STAmount(0)); // Check that check that we still can use the claimID to transfer @@ -2903,14 +3149,24 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM, + withClaim); + scEnv.multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); if (withClaim) { BEAST_EXPECT(transfer.has_not_happened()); // claim wrong amount - scEnv.tx(xchain_claim(scAlice, jvb, claimID, one_xrp, scBob), ter(tecXCHAIN_CLAIM_NO_QUORUM)).close(); + scEnv + .tx(xchain_claim(scAlice, jvb, claimID, one_xrp, scBob), + ter(tecXCHAIN_CLAIM_NO_QUORUM)) + .close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -2938,9 +3194,16 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM, + withClaim); Balance scAlice_bal(scEnv, scAlice); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); + scEnv.multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); STAmount claim_cost = reward; @@ -2979,9 +3242,16 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM, + withClaim); Balance scAlice_bal(scEnv, scAlice); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); + scEnv.multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); STAmount claim_cost = tiny_reward; if (withClaim) @@ -3024,8 +3294,15 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM - 1, withClaim); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, alt_payees, true, claimID, dst, signers)); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM - 1, + withClaim); + scEnv.multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, alt_payees, true, claimID, dst, signers)); if (withClaim) { @@ -3067,8 +3344,15 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // split_reward BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM - 1, withClaim); - scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); + scEnv, + Account::master, + scBob, + scAlice, + &payees[0], + UT_XCHAIN_DEFAULT_QUORUM - 1, + withClaim); + scEnv.multiTx(claim_attestations( + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); if (withClaim) { @@ -3091,7 +3375,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj XEnv(*this, true) .tx(create_bridge(Account::master, jvb)) .close() - .tx(xchain_claim(scAlice, jvb, 1, XRP(1000), scBob), txflags(tfFillOrKill), ter(temINVALID_FLAG)) + .tx(xchain_claim(scAlice, jvb, 1, XRP(1000), scBob), + txflags(tfFillOrKill), + ter(temINVALID_FLAG)) .close(); // coverage test: xchain_claim transaction with xchain feature @@ -3125,7 +3411,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj auto const amt = XRP(111); auto const amt_plus_reward = amt + reward; - scEnv.tx(create_bridge(Account::master, jvb)).tx(jtx::signers(Account::master, quorum, signers)).close(); + scEnv.tx(create_bridge(Account::master, jvb)) + .tx(jtx::signers(Account::master, quorum, signers)) + .close(); Balance door(scEnv, Account::master); @@ -3190,7 +3478,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj Balance door(mcEnv, mcDoor); mcEnv.disableFeature(featureXChainBridge) - .tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(20), reward), ter(temDISABLED)) + .tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(20), reward), + ter(temDISABLED)) .close(); BEAST_EXPECT(door.diff() == STAmount(0)); @@ -3204,7 +3493,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj Balance door(mcEnv, mcDoor); - mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(-20), reward), ter(temBAD_AMOUNT)) + mcEnv + .tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(-20), reward), + ter(temBAD_AMOUNT)) .close(); BEAST_EXPECT(door.diff() == STAmount(0)); @@ -3218,7 +3509,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj Balance door(mcEnv, mcDoor); - mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(20), XRP(-1)), ter(temBAD_AMOUNT)) + mcEnv + .tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(20), XRP(-1)), + ter(temBAD_AMOUNT)) .close(); BEAST_EXPECT(door.diff() == STAmount(0)); @@ -3233,7 +3526,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj Balance door(mcEnv, mcDoor); mcEnv - .tx(sidechain_xchain_account_create(mcDoor, jvb, scuAlice, XRP(20), XRP(1)), ter(tecXCHAIN_SELF_COMMIT)) + .tx(sidechain_xchain_account_create(mcDoor, jvb, scuAlice, XRP(20), XRP(1)), + ter(tecXCHAIN_SELF_COMMIT)) .close(); BEAST_EXPECT(door.diff() == -tx_fee); @@ -3288,7 +3582,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .tx(create_bridge(mcDoor, jvb, reward, minAccountCreate)) .fund(res0 + tx_fee + minAccountCreate + reward - drops(1), mcuAlice) .close() - .tx(sidechain_xchain_account_create(mcuAlice, jvb, scuAlice, minAccountCreate, reward), ter(tesSUCCESS)); + .tx(sidechain_xchain_account_create(mcuAlice, jvb, scuAlice, minAccountCreate, reward), + ter(tesSUCCESS)); // account create commit where the commit dips into the reserve, // this should fail @@ -3355,7 +3650,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj std::uint32_t const claimID = 1; std::optional dst{scBob}; auto const amt = XRP(1000); - scEnv.tx(create_bridge(Account::master, jvb)).tx(jtx::signers(Account::master, quorum, signers)).close(); + scEnv.tx(create_bridge(Account::master, jvb)) + .tx(jtx::signers(Account::master, quorum, signers)) + .close(); scEnv.tx(xchain_create_claim_id(scAlice, jvb, reward, mcAlice)).close(); auto jvAtt = claim_attestation( scAttester, @@ -3383,7 +3680,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj Account dst{scBob}; auto const amt = XRP(1000); auto const rewardAmt = XRP(1); - scEnv.tx(create_bridge(Account::master, jvb)).tx(jtx::signers(Account::master, quorum, signers)).close(); + scEnv.tx(create_bridge(Account::master, jvb)) + .tx(jtx::signers(Account::master, quorum, signers)) + .close(); auto jvAtt = create_account_attestation( scAttester, jvb, @@ -3547,7 +3846,8 @@ private: auto num_attns = create_claims.size(); if (num_attns) { - c.num_create_attn_sent += sendCreateAttestations(i, bridge, create_claims); + c.num_create_attn_sent += + sendCreateAttestations(i, bridge, create_claims); } assert(claims.create_claims[c.claim_count].empty()); } @@ -3595,7 +3895,9 @@ private: { if (amt.issue() != xrpIssue()) return; - receive(acct, times == 1 ? -amt : -multiply(amt, STAmount(amt.issue(), times), amt.issue())); + receive( + acct, + times == 1 ? -amt : -multiply(amt, STAmount(amt.issue(), times), amt.issue())); } void @@ -3756,7 +4058,8 @@ private: ChainStateTrack& st = srcState(); jtx::Account const& srcdoor = srcDoor(); - st.env.tx(sidechain_xchain_account_create(cr.from, bridge_.jvb, cr.to, cr.amt, cr.reward)) + st.env + .tx(sidechain_xchain_account_create(cr.from, bridge_.jvb, cr.to, cr.amt, cr.reward)) .close(); // needed for claim_id sequence to be correct' st.spendFee(cr.from); st.transfer(cr.from, srcdoor, cr.amt); @@ -3781,8 +4084,9 @@ private: // enqueue one attestation for this signer cr.attested[signer_idx] = true; - st.signers_attns[signer_idx][&bridge_].create_claims[cr.claim_id - 1].emplace_back( - create_account_attestation( + st.signers_attns[signer_idx][&bridge_] + .create_claims[cr.claim_id - 1] + .emplace_back(create_account_attestation( bridge_.signers[signer_idx].account, bridge_.jvb, cr.from, @@ -3861,7 +4165,10 @@ private: public: using Base = SmBase; - SmTransfer(std::shared_ptr const& chainstate, BridgeDef const& bridge, Transfer xfer) + SmTransfer( + std::shared_ptr const& chainstate, + BridgeDef const& bridge, + Transfer xfer) : Base(chainstate, bridge), xfer(std::move(xfer)), sm_state(st_initial) { } @@ -3900,7 +4207,8 @@ private: bridge_.jvb, xfer.claim_id, xfer.amt, - xfer.with_claim == WithClaim::yes ? std::nullopt : std::optional(xfer.finaldest))); + xfer.with_claim == WithClaim::yes ? std::nullopt + : std::optional(xfer.finaldest))); st.spendFee(xfer.from); st.transfer(xfer.from, srcdoor, xfer.amt); } @@ -3933,22 +4241,26 @@ private: // enqueue one attestation for this signer xfer.attested[signer_idx] = true; - st.signers_attns[signer_idx][&bridge_].xfer_claims.emplace_back(claim_attestation( - bridge_.signers[signer_idx].account, - bridge_.jvb, - xfer.from, - xfer.amt, - bridge_.signers[signer_idx].account, - xfer.a2b, - xfer.claim_id, - xfer.with_claim == WithClaim::yes ? std::nullopt : std::optional(xfer.finaldest), - bridge_.signers[signer_idx])); + st.signers_attns[signer_idx][&bridge_].xfer_claims.emplace_back( + claim_attestation( + bridge_.signers[signer_idx].account, + bridge_.jvb, + xfer.from, + xfer.amt, + bridge_.signers[signer_idx].account, + xfer.a2b, + xfer.claim_id, + xfer.with_claim == WithClaim::yes + ? std::nullopt + : std::optional(xfer.finaldest), + bridge_.signers[signer_idx])); break; } } // return true if quorum was reached, false otherwise - bool quorum = std::count(xfer.attested.begin(), xfer.attested.end(), true) >= bridge_.quorum; + bool quorum = + std::count(xfer.attested.begin(), xfer.attested.end(), true) >= bridge_.quorum; if (quorum && xfer.with_claim == WithClaim::no) { distribute_reward(st); @@ -3983,8 +4295,9 @@ private: break; case st_attesting: - sm_state = attest(time, rnd) ? (xfer.with_claim == WithClaim::yes ? st_attested : st_completed) - : st_attesting; + sm_state = attest(time, rnd) + ? (xfer.with_claim == WithClaim::yes ? st_attested : st_completed) + : st_attesting; break; case st_attested: @@ -4023,7 +4336,10 @@ private: } void - ac(uint64_t time, std::shared_ptr const& chainstate, BridgeDef const& bridge, AccountCreate ac) + ac(uint64_t time, + std::shared_ptr const& chainstate, + BridgeDef const& bridge, + AccountCreate ac) { sm_.emplace_back(time, SmCreateAccount(chainstate, bridge, std::move(ac))); } @@ -4081,7 +4397,8 @@ public: // create 10 accounts + door funded on both chains, and store // in ChainStateTracker the initial amount of these accounts - Account doorXRPLocking("doorXRPLocking"), doorUSDLocking("doorUSDLocking"), doorUSDIssuing("doorUSDIssuing"); + Account doorXRPLocking("doorXRPLocking"), doorUSDLocking("doorUSDLocking"), + doorUSDIssuing("doorUSDIssuing"); constexpr size_t num_acct = 10; auto a = [&doorXRPLocking, &doorUSDLocking, &doorUSDIssuing]() { @@ -4089,7 +4406,8 @@ public: std::vector result; result.reserve(num_acct); for (int i = 0; i < num_acct; ++i) - result.emplace_back("a"s + std::to_string(i), (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); + result.emplace_back( + "a"s + std::to_string(i), (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); result.emplace_back("doorXRPLocking"); doorXRPLocking = result.back(); result.emplace_back("doorUSDLocking"); @@ -4138,7 +4456,8 @@ public: std::vector result; result.reserve(num_ua); for (int i = 0; i < num_ua; ++i) - result.emplace_back("ua"s + std::to_string(i), (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); + result.emplace_back( + "ua"s + std::to_string(i), (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); return result; }(); @@ -4152,14 +4471,30 @@ public: // create XRP -> XRP bridge // ------------------------ BridgeDef xrp_b{ - doorXRPLocking, xrpIssue(), Account::master, xrpIssue(), XRP(1), XRP(20), quorum, signers, Json::nullValue}; + doorXRPLocking, + xrpIssue(), + Account::master, + xrpIssue(), + XRP(1), + XRP(20), + quorum, + signers, + Json::nullValue}; initBridge(xrp_b); // create USD -> USD bridge // ------------------------ BridgeDef usd_b{ - doorUSDLocking, usdLocking, doorUSDIssuing, usdIssuing, XRP(1), XRP(20), quorum, signers, Json::nullValue}; + doorUSDLocking, + usdLocking, + doorUSDIssuing, + usdIssuing, + XRP(1), + XRP(20), + quorum, + signers, + Json::nullValue}; initBridge(usd_b); diff --git a/src/test/app/tx/apply_test.cpp b/src/test/app/tx/apply_test.cpp index fada168112..f21af50817 100644 --- a/src/test/app/tx/apply_test.cpp +++ b/src/test/app/tx/apply_test.cpp @@ -2,10 +2,9 @@ #include -#include - #include #include +#include namespace xrpl { @@ -38,12 +37,10 @@ public: { test::jtx::Env fully_canonical(*this, test::jtx::testable_amendments()); - Validity valid = checkValidity( - fully_canonical.app().getHashRouter(), - tx, - fully_canonical.current()->rules(), - fully_canonical.app().config()) - .first; + Validity valid = + checkValidity( + fully_canonical.app().getHashRouter(), tx, fully_canonical.current()->rules()) + .first; if (valid == Validity::Valid) fail("Non-Fully canonical signature was permitted"); } diff --git a/src/test/basics/Buffer_test.cpp b/src/test/basics/Buffer_test.cpp index 908650982c..56f440b993 100644 --- a/src/test/basics/Buffer_test.cpp +++ b/src/test/basics/Buffer_test.cpp @@ -21,9 +21,10 @@ struct Buffer_test : beast::unit_test::suite void run() override { - std::uint8_t const data[] = {0xa8, 0xa1, 0x38, 0x45, 0x23, 0xec, 0xe4, 0x23, 0x71, 0x6d, 0x2a, - 0x18, 0xb4, 0x70, 0xcb, 0xf5, 0xac, 0x2d, 0x89, 0x4d, 0x19, 0x9c, - 0xf0, 0x2c, 0x15, 0xd1, 0xf9, 0x9b, 0x66, 0xd2, 0x30, 0xd3}; + std::uint8_t const data[] = {0xa8, 0xa1, 0x38, 0x45, 0x23, 0xec, 0xe4, 0x23, + 0x71, 0x6d, 0x2a, 0x18, 0xb4, 0x70, 0xcb, 0xf5, + 0xac, 0x2d, 0x89, 0x4d, 0x19, 0x9c, 0xf0, 0x2c, + 0x15, 0xd1, 0xf9, 0x9b, 0x66, 0xd2, 0x30, 0xd3}; Buffer b0; BEAST_EXPECT(sane(b0)); diff --git a/src/test/basics/Expected_test.cpp b/src/test/basics/Expected_test.cpp index 186e34d2e0..2caa15816f 100644 --- a/src/test/basics/Expected_test.cpp +++ b/src/test/basics/Expected_test.cpp @@ -85,7 +85,9 @@ struct Expected_test : beast::unit_test::suite } // Test error construction from rvalue. { - auto const expected = []() -> Expected { return Unexpected(telLOCAL_ERROR); }(); + auto const expected = []() -> Expected { + return Unexpected(telLOCAL_ERROR); + }(); BEAST_EXPECT(!expected); BEAST_EXPECT(!expected.has_value()); BEAST_EXPECT(expected.error() == telLOCAL_ERROR); @@ -126,14 +128,18 @@ struct Expected_test : beast::unit_test::suite } // Test error construction from const char*. { - auto const expected = []() -> Expected { return Unexpected("Not what is expected!"); }(); + auto const expected = []() -> Expected { + return Unexpected("Not what is expected!"); + }(); BEAST_EXPECT(!expected); BEAST_EXPECT(!expected.has_value()); BEAST_EXPECT(expected.error() == std::string("Not what is expected!")); } // Test error construction of string from const char*. { - auto expected = []() -> Expected { return Unexpected("Not what is expected!"); }(); + auto expected = []() -> Expected { + return Unexpected("Not what is expected!"); + }(); BEAST_EXPECT(!expected); BEAST_EXPECT(!expected.has_value()); BEAST_EXPECT(expected.error() == "Not what is expected!"); @@ -176,13 +182,17 @@ struct Expected_test : beast::unit_test::suite } // Test error const construction of Expected. { - auto const expected = []() -> Expected { return Unexpected("Not what is expected!"); }(); + auto const expected = []() -> Expected { + return Unexpected("Not what is expected!"); + }(); BEAST_EXPECT(!expected); BEAST_EXPECT(expected.error() == "Not what is expected!"); } // Test error non-const construction of Expected. { - auto expected = []() -> Expected { return Unexpected("Not what is expected!"); }(); + auto expected = []() -> Expected { + return Unexpected("Not what is expected!"); + }(); BEAST_EXPECT(!expected); BEAST_EXPECT(expected.error() == "Not what is expected!"); std::string const s(std::move(expected.error())); diff --git a/src/test/basics/FileUtilities_test.cpp b/src/test/basics/FileUtilities_test.cpp index d8664448d6..3d6f9b754b 100644 --- a/src/test/basics/FileUtilities_test.cpp +++ b/src/test/basics/FileUtilities_test.cpp @@ -17,7 +17,8 @@ public: constexpr char const* expectedContents = "This file is very short. That's all we need."; - FileDirGuard file(*this, "test_file", "test.txt", "This is temporary text that should get overwritten"); + FileDirGuard file( + *this, "test_file", "test.txt", "This is temporary text that should get overwritten"); error_code ec; auto const path = file.file(); diff --git a/src/test/basics/IntrusiveShared_test.cpp b/src/test/basics/IntrusiveShared_test.cpp index d0aa4c75e9..817cbb8c1d 100644 --- a/src/test/basics/IntrusiveShared_test.cpp +++ b/src/test/basics/IntrusiveShared_test.cpp @@ -494,8 +494,12 @@ public: int s = destructionState.load(std::memory_order_relaxed); return {(s & 1) != 0, (s & 2) != 0}; }; - auto setDestructorRan = [&]() -> void { destructionState.fetch_or(1, std::memory_order_acq_rel); }; - auto setPartialDeleteRan = [&]() -> void { destructionState.fetch_or(2, std::memory_order_acq_rel); }; + auto setDestructorRan = [&]() -> void { + destructionState.fetch_or(1, std::memory_order_acq_rel); + }; + auto setPartialDeleteRan = [&]() -> void { + destructionState.fetch_or(2, std::memory_order_acq_rel); + }; auto tracingCallback = [&](TrackedState cur, std::optional next) { using enum TrackedState; auto [destructorRan, partialDeleteRan] = getDestructorState(); @@ -623,8 +627,12 @@ public: int s = destructionState.load(std::memory_order_relaxed); return {(s & 1) != 0, (s & 2) != 0}; }; - auto setDestructorRan = [&]() -> void { destructionState.fetch_or(1, std::memory_order_acq_rel); }; - auto setPartialDeleteRan = [&]() -> void { destructionState.fetch_or(2, std::memory_order_acq_rel); }; + auto setDestructorRan = [&]() -> void { + destructionState.fetch_or(1, std::memory_order_acq_rel); + }; + auto setPartialDeleteRan = [&]() -> void { + destructionState.fetch_or(2, std::memory_order_acq_rel); + }; auto tracingCallback = [&](TrackedState cur, std::optional next) { using enum TrackedState; auto [destructorRan, partialDeleteRan] = getDestructorState(); @@ -639,8 +647,9 @@ public: setDestructorRan(); } }; - auto createVecOfPointers = [&](auto const& toClone, - std::default_random_engine& eng) -> std::vector> { + auto createVecOfPointers = + [&](auto const& toClone, + std::default_random_engine& eng) -> std::vector> { std::vector> result; std::uniform_int_distribution<> toCreateDist(4, 64); auto numToCreate = toCreateDist(eng); @@ -758,8 +767,12 @@ public: int s = destructionState.load(std::memory_order_relaxed); return {(s & 1) != 0, (s & 2) != 0}; }; - auto setDestructorRan = [&]() -> void { destructionState.fetch_or(1, std::memory_order_acq_rel); }; - auto setPartialDeleteRan = [&]() -> void { destructionState.fetch_or(2, std::memory_order_acq_rel); }; + auto setDestructorRan = [&]() -> void { + destructionState.fetch_or(1, std::memory_order_acq_rel); + }; + auto setPartialDeleteRan = [&]() -> void { + destructionState.fetch_or(2, std::memory_order_acq_rel); + }; auto tracingCallback = [&](TrackedState cur, std::optional next) { using enum TrackedState; auto [destructorRan, partialDeleteRan] = getDestructorState(); diff --git a/src/test/basics/Number_test.cpp b/src/test/basics/Number_test.cpp index 13b2d72412..eaf184ffe4 100644 --- a/src/test/basics/Number_test.cpp +++ b/src/test/basics/Number_test.cpp @@ -66,17 +66,20 @@ public: test( Number{std::numeric_limits::min()}, - scale == MantissaRange::small ? Number{-9'223'372'036'854'776, 3} - : Number{true, 9'223'372'036'854'775'808ULL, 0, Number::normalized{}}, + scale == MantissaRange::small + ? Number{-9'223'372'036'854'776, 3} + : Number{true, 9'223'372'036'854'775'808ULL, 0, Number::normalized{}}, __LINE__); test( Number{std::numeric_limits::min() + 1}, - scale == MantissaRange::small ? Number{-9'223'372'036'854'776, 3} : Number{-9'223'372'036'854'775'807}, + scale == MantissaRange::small ? Number{-9'223'372'036'854'776, 3} + : Number{-9'223'372'036'854'775'807}, __LINE__); test( Number{std::numeric_limits::max()}, Number{ - scale == MantissaRange::small ? 9'223'372'036'854'776 : std::numeric_limits::max(), + scale == MantissaRange::small ? 9'223'372'036'854'776 + : std::numeric_limits::max(), 18 - Number::mantissaLog()}, __LINE__); caught = false; @@ -114,7 +117,9 @@ public: Number{9'999'999'999'999'344, -16}}, {Number{}, Number{5}, Number{5}}, {Number{5}, Number{}, Number{5}}, - {Number{5'555'555'555'555'555, -32768}, Number{-5'555'555'555'555'554, -32768}, Number{0}}, + {Number{5'555'555'555'555'555, -32768}, + Number{-5'555'555'555'555'554, -32768}, + Number{0}}, {Number{-9'999'999'999'999'999, -31}, Number{1'000'000'000'000'000, -15}, Number{9'999'999'999'999'990, -16}}}); @@ -137,7 +142,9 @@ public: Number{false, 9'999'999'999'999'344'444ULL, -19, Number::normalized{}}}, {Number{}, Number{5}, Number{5}}, {Number{5}, Number{}, Number{5}}, - {Number{5'555'555'555'555'555'000, -32768}, Number{-5'555'555'555'555'554'000, -32768}, Number{0}}, + {Number{5'555'555'555'555'555'000, -32768}, + Number{-5'555'555'555'555'554'000, -32768}, + Number{0}}, {Number{-9'999'999'999'999'999, -31}, Number{1'000'000'000'000'000, -15}, Number{9'999'999'999'999'990, -16}}, @@ -155,7 +162,9 @@ public: Number{1'000'000'000'000'000'000, -18}, Number{false, 9'999'999'999'999'999'344ULL, -19, Number::normalized{}}}, {Number{}, Number{5}, Number{5}}, - {Number{5'555'555'555'555'555'555, -32768}, Number{-5'555'555'555'555'555'554, -32768}, Number{0}}, + {Number{5'555'555'555'555'555'555, -32768}, + Number{-5'555'555'555'555'555'554, -32768}, + Number{0}}, {Number{true, 9'999'999'999'999'999'999ULL, -37, Number::normalized{}}, Number{1'000'000'000'000'000'000, -18}, Number{false, 9'999'999'999'999'999'990ULL, -19, Number::normalized{}}}, @@ -254,7 +263,9 @@ public: {Number{6'555'555'555'555'555'555, -32}, Number{1'000'000'000'000'000'000, -18}, Number{true, 9'999'999'999'999'344'444ULL, -19, Number::normalized{}}}, - {Number{1'000'000'000'000'000'000, -18}, Number{1'000'000'000'000'000'000, -18}, Number{0}}, + {Number{1'000'000'000'000'000'000, -18}, + Number{1'000'000'000'000'000'000, -18}, + Number{0}}, {Number{1'000'000'000'000'000'000, -18}, Number{1'000'000'000'000'000'001, -18}, Number{-1'000'000'000'000'000'000, -36}}, @@ -265,7 +276,9 @@ public: {Number{false, Number::maxRep + 1, 0, Number::normalized{}}, Number{1, 0}, Number{Number::maxRep / 10 + 1, 1}}, - {Number{false, Number::maxRep + 1, 0, Number::normalized{}}, Number{3, 0}, Number{Number::maxRep}}, + {Number{false, Number::maxRep + 1, 0, Number::normalized{}}, + Number{3, 0}, + Number{Number::maxRep}}, {power(2, 63), Number{3, 0}, Number{Number::maxRep}}, }); auto test = [this](auto const& c) { @@ -311,30 +324,50 @@ public: { auto const cSmall = std::to_array({ {Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{2000000000000000, -15}}, - {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-2000000000000000, -15}}, - {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{2000000000000000, -15}}, - {Number{3214285714285706, -15}, Number{3111111111111119, -15}, Number{1000000000000000, -14}}, + {Number{1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{2000000000000000, -15}}, + {Number{-1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{-2000000000000000, -15}}, + {Number{-1414213562373095, -15}, + Number{-1414213562373095, -15}, + Number{2000000000000000, -15}}, + {Number{3214285714285706, -15}, + Number{3111111111111119, -15}, + Number{1000000000000000, -14}}, {Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}}, // Maximum mantissa range - {Number{9'999'999'999'999'999, 0}, Number{9'999'999'999'999'999, 0}, Number{9'999'999'999'999'998, 16}}, + {Number{9'999'999'999'999'999, 0}, + Number{9'999'999'999'999'999, 0}, + Number{9'999'999'999'999'998, 16}}, }); auto const cLarge = std::to_array({ // Note that items with extremely large mantissas need to be // calculated, because otherwise they overflow uint64. Items // from C with larger mantissa {Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{1999999999999999862, -18}}, - {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-1999999999999999862, -18}}, - {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{1999999999999999862, -18}}, + {Number{1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{1999999999999999862, -18}}, + {Number{-1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{-1999999999999999862, -18}}, + {Number{-1414213562373095, -15}, + Number{-1414213562373095, -15}, + Number{1999999999999999862, -18}}, {Number{3214285714285706, -15}, Number{3111111111111119, -15}, Number{false, 9'999'999'999'999'999'579ULL, -18, Number::normalized{}}}, - {Number{1000000000000000000, -32768}, Number{1000000000000000000, -32768}, Number{0}}, + {Number{1000000000000000000, -32768}, + Number{1000000000000000000, -32768}, + Number{0}}, // Items from cSmall expanded for the larger mantissa, // except duplicates. Sadly, it looks like sqrt(2)^2 != 2 // with higher precision - {Number{1414213562373095049, -18}, Number{1414213562373095049, -18}, Number{2000000000000000001, -18}}, + {Number{1414213562373095049, -18}, + Number{1414213562373095049, -18}, + Number{2000000000000000001, -18}}, {Number{-1414213562373095048, -18}, Number{1414213562373095048, -18}, Number{-1999999999999999998, -18}}, @@ -347,7 +380,9 @@ public: Number{false, maxMantissa, 0, Number::normalized{}}, Number{1, 38}}, // Maximum int64 range - {Number{Number::maxRep, 0}, Number{Number::maxRep, 0}, Number{85'070'591'730'234'615'85, 19}}, + {Number{Number::maxRep, 0}, + Number{Number::maxRep, 0}, + Number{85'070'591'730'234'615'85, 19}}, }); tests(cSmall, cLarge); } @@ -356,10 +391,18 @@ public: { auto const cSmall = std::to_array( {{Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{1999999999999999, -15}}, - {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-1999999999999999, -15}}, - {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{1999999999999999, -15}}, - {Number{3214285714285706, -15}, Number{3111111111111119, -15}, Number{9999999999999999, -15}}, + {Number{1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{1999999999999999, -15}}, + {Number{-1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{-1999999999999999, -15}}, + {Number{-1414213562373095, -15}, + Number{-1414213562373095, -15}, + Number{1999999999999999, -15}}, + {Number{3214285714285706, -15}, + Number{3111111111111119, -15}, + Number{9999999999999999, -15}}, {Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}}}); auto const cLarge = std::to_array( // Note that items with extremely large mantissas need to be @@ -367,24 +410,36 @@ public: // from C with larger mantissa { {Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{1999999999999999861, -18}}, - {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-1999999999999999861, -18}}, - {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{1999999999999999861, -18}}, + {Number{1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{1999999999999999861, -18}}, + {Number{-1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{-1999999999999999861, -18}}, + {Number{-1414213562373095, -15}, + Number{-1414213562373095, -15}, + Number{1999999999999999861, -18}}, {Number{3214285714285706, -15}, Number{3111111111111119, -15}, Number{false, 9999999999999999579ULL, -18, Number::normalized{}}}, - {Number{1000000000000000000, -32768}, Number{1000000000000000000, -32768}, Number{0}}, + {Number{1000000000000000000, -32768}, + Number{1000000000000000000, -32768}, + Number{0}}, // Items from cSmall expanded for the larger mantissa, // except duplicates. Sadly, it looks like sqrt(2)^2 != 2 // with higher precision - {Number{1414213562373095049, -18}, Number{1414213562373095049, -18}, Number{2, 0}}, + {Number{1414213562373095049, -18}, + Number{1414213562373095049, -18}, + Number{2, 0}}, {Number{-1414213562373095048, -18}, Number{1414213562373095048, -18}, Number{-1999999999999999997, -18}}, {Number{-1414213562373095048, -18}, Number{-1414213562373095049, -18}, Number{1999999999999999999, -18}}, - {Number{3214285714285714278, -18}, Number{3111111111111111119, -18}, Number{10, 0}}, + {Number{3214285714285714278, -18}, + Number{3111111111111111119, -18}, + Number{10, 0}}, // Maximum mantissa range - rounds down to maxMantissa/10e1 // 99'999'999'999'999'999'800'000'000'000'000'000'100 {Number{false, maxMantissa, 0, Number::normalized{}}, @@ -392,7 +447,9 @@ public: Number{false, maxMantissa / 10 - 1, 20, Number::normalized{}}}, // Maximum int64 range // 85'070'591'730'234'615'847'396'907'784'232'501'249 - {Number{Number::maxRep, 0}, Number{Number::maxRep, 0}, Number{85'070'591'730'234'615'84, 19}}, + {Number{Number::maxRep, 0}, + Number{Number::maxRep, 0}, + Number{85'070'591'730'234'615'84, 19}}, }); tests(cSmall, cLarge); } @@ -401,10 +458,18 @@ public: { auto const cSmall = std::to_array( {{Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{1999999999999999, -15}}, - {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-2000000000000000, -15}}, - {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{1999999999999999, -15}}, - {Number{3214285714285706, -15}, Number{3111111111111119, -15}, Number{9999999999999999, -15}}, + {Number{1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{1999999999999999, -15}}, + {Number{-1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{-2000000000000000, -15}}, + {Number{-1414213562373095, -15}, + Number{-1414213562373095, -15}, + Number{1999999999999999, -15}}, + {Number{3214285714285706, -15}, + Number{3111111111111119, -15}, + Number{9999999999999999, -15}}, {Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}}}); auto const cLarge = std::to_array( // Note that items with extremely large mantissas need to be @@ -412,24 +477,36 @@ public: // from C with larger mantissa { {Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{1999999999999999861, -18}}, - {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-1999999999999999862, -18}}, - {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{1999999999999999861, -18}}, + {Number{1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{1999999999999999861, -18}}, + {Number{-1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{-1999999999999999862, -18}}, + {Number{-1414213562373095, -15}, + Number{-1414213562373095, -15}, + Number{1999999999999999861, -18}}, {Number{3214285714285706, -15}, Number{3111111111111119, -15}, Number{false, 9'999'999'999'999'999'579ULL, -18, Number::normalized{}}}, - {Number{1000000000000000000, -32768}, Number{1000000000000000000, -32768}, Number{0}}, + {Number{1000000000000000000, -32768}, + Number{1000000000000000000, -32768}, + Number{0}}, // Items from cSmall expanded for the larger mantissa, // except duplicates. Sadly, it looks like sqrt(2)^2 != 2 // with higher precision - {Number{1414213562373095049, -18}, Number{1414213562373095049, -18}, Number{2, 0}}, + {Number{1414213562373095049, -18}, + Number{1414213562373095049, -18}, + Number{2, 0}}, {Number{-1414213562373095048, -18}, Number{1414213562373095048, -18}, Number{-1999999999999999998, -18}}, {Number{-1414213562373095048, -18}, Number{-1414213562373095049, -18}, Number{1999999999999999999, -18}}, - {Number{3214285714285714278, -18}, Number{3111111111111111119, -18}, Number{10, 0}}, + {Number{3214285714285714278, -18}, + Number{3111111111111111119, -18}, + Number{10, 0}}, // Maximum mantissa range - rounds down to maxMantissa/10e1 // 99'999'999'999'999'999'800'000'000'000'000'000'100 {Number{false, maxMantissa, 0, Number::normalized{}}, @@ -437,7 +514,9 @@ public: Number{false, maxMantissa / 10 - 1, 20, Number::normalized{}}}, // Maximum int64 range // 85'070'591'730'234'615'847'396'907'784'232'501'249 - {Number{Number::maxRep, 0}, Number{Number::maxRep, 0}, Number{85'070'591'730'234'615'84, 19}}, + {Number{Number::maxRep, 0}, + Number{Number::maxRep, 0}, + Number{85'070'591'730'234'615'84, 19}}, }); tests(cSmall, cLarge); } @@ -446,10 +525,18 @@ public: { auto const cSmall = std::to_array( {{Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{2000000000000000, -15}}, - {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-1999999999999999, -15}}, - {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{2000000000000000, -15}}, - {Number{3214285714285706, -15}, Number{3111111111111119, -15}, Number{1000000000000000, -14}}, + {Number{1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{2000000000000000, -15}}, + {Number{-1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{-1999999999999999, -15}}, + {Number{-1414213562373095, -15}, + Number{-1414213562373095, -15}, + Number{2000000000000000, -15}}, + {Number{3214285714285706, -15}, + Number{3111111111111119, -15}, + Number{1000000000000000, -14}}, {Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}}}); auto const cLarge = std::to_array( // Note that items with extremely large mantissas need to be @@ -457,11 +544,21 @@ public: // from C with larger mantissa { {Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{1999999999999999862, -18}}, - {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-1999999999999999861, -18}}, - {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{1999999999999999862, -18}}, - {Number{3214285714285706, -15}, Number{3111111111111119, -15}, Number{999999999999999958, -17}}, - {Number{1000000000000000000, -32768}, Number{1000000000000000000, -32768}, Number{0}}, + {Number{1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{1999999999999999862, -18}}, + {Number{-1414213562373095, -15}, + Number{1414213562373095, -15}, + Number{-1999999999999999861, -18}}, + {Number{-1414213562373095, -15}, + Number{-1414213562373095, -15}, + Number{1999999999999999862, -18}}, + {Number{3214285714285706, -15}, + Number{3111111111111119, -15}, + Number{999999999999999958, -17}}, + {Number{1000000000000000000, -32768}, + Number{1000000000000000000, -32768}, + Number{0}}, // Items from cSmall expanded for the larger mantissa, // except duplicates. Sadly, it looks like sqrt(2)^2 != 2 // with higher precision @@ -471,7 +568,9 @@ public: {Number{-1414213562373095048, -18}, Number{1414213562373095048, -18}, Number{-1999999999999999997, -18}}, - {Number{-1414213562373095048, -18}, Number{-1414213562373095049, -18}, Number{2, 0}}, + {Number{-1414213562373095048, -18}, + Number{-1414213562373095049, -18}, + Number{2, 0}}, {Number{3214285714285714278, -18}, Number{3111111111111111119, -18}, Number{1000000000000000001, -17}}, @@ -482,7 +581,9 @@ public: Number{1, 38}}, // Maximum int64 range // 85'070'591'730'234'615'847'396'907'784'232'501'249 - {Number{Number::maxRep, 0}, Number{Number::maxRep, 0}, Number{85'070'591'730'234'615'85, 19}}, + {Number{Number::maxRep, 0}, + Number{Number::maxRep, 0}, + Number{85'070'591'730'234'615'85, 19}}, }); tests(cSmall, cLarge); } @@ -533,7 +634,9 @@ public: {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, - {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, + {Number{9'999'999'999'999'999}, + Number{1'000'000'000'000'000}, + Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'667, -16}}, {Number{-2}, Number{3}, Number{-6'666'666'666'666'667, -16}}, {Number{1}, Number{7}, Number{1'428'571'428'571'428, -16}}}); @@ -546,7 +649,9 @@ public: {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, - {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, + {Number{9'999'999'999'999'999}, + Number{1'000'000'000'000'000}, + Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'666'667, -19}}, {Number{-2}, Number{3}, Number{-6'666'666'666'666'666'667, -19}}, {Number{1}, Number{7}, Number{1'428'571'428'571'428'571, -19}}, @@ -567,7 +672,9 @@ public: {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, - {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, + {Number{9'999'999'999'999'999}, + Number{1'000'000'000'000'000}, + Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'666, -16}}, {Number{-2}, Number{3}, Number{-6'666'666'666'666'666, -16}}, {Number{1}, Number{7}, Number{1'428'571'428'571'428, -16}}}); @@ -580,7 +687,9 @@ public: {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, - {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, + {Number{9'999'999'999'999'999}, + Number{1'000'000'000'000'000}, + Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'666'666, -19}}, {Number{-2}, Number{3}, Number{-6'666'666'666'666'666'666, -19}}, {Number{1}, Number{7}, Number{1'428'571'428'571'428'571, -19}}, @@ -601,7 +710,9 @@ public: {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, - {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, + {Number{9'999'999'999'999'999}, + Number{1'000'000'000'000'000}, + Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'666, -16}}, {Number{-2}, Number{3}, Number{-6'666'666'666'666'667, -16}}, {Number{1}, Number{7}, Number{1'428'571'428'571'428, -16}}}); @@ -614,7 +725,9 @@ public: {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, - {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, + {Number{9'999'999'999'999'999}, + Number{1'000'000'000'000'000}, + Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'666'666, -19}}, {Number{-2}, Number{3}, Number{-6'666'666'666'666'666'667, -19}}, {Number{1}, Number{7}, Number{1'428'571'428'571'428'571, -19}}, @@ -635,7 +748,9 @@ public: {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, - {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, + {Number{9'999'999'999'999'999}, + Number{1'000'000'000'000'000}, + Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'667, -16}}, {Number{-2}, Number{3}, Number{-6'666'666'666'666'666, -16}}, {Number{1}, Number{7}, Number{1'428'571'428'571'429, -16}}}); @@ -648,7 +763,9 @@ public: {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, - {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, + {Number{9'999'999'999'999'999}, + Number{1'000'000'000'000'000}, + Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'666'667, -19}}, {Number{-2}, Number{3}, Number{-6'666'666'666'666'666'666, -19}}, {Number{1}, Number{7}, Number{1'428'571'428'571'428'572, -19}}, @@ -714,8 +831,12 @@ public: {Number{false, Number::maxMantissa() - 9, 0, Number::normalized{}}, 2, Number{false, 3'162'277'660'168'379'330, -9, Number::normalized{}}}, - {Number{Number::maxRep}, 2, Number{false, 3'037'000'499'976049692, -9, Number::normalized{}}}, - {Number{Number::maxRep}, 4, Number{false, 55'108'98747006743627, -14, Number::normalized{}}}, + {Number{Number::maxRep}, + 2, + Number{false, 3'037'000'499'976049692, -9, Number::normalized{}}}, + {Number{Number::maxRep}, + 4, + Number{false, 55'108'98747006743627, -14, Number::normalized{}}}, }); test(cSmall); if (Number::getMantissaScale() != MantissaRange::small) @@ -1100,14 +1221,23 @@ public: auto const maxMantissa = Number::maxMantissa(); BEAST_EXPECT(maxMantissa == 9'999'999'999'999'999); - test(Number{false, maxMantissa * 1000 + 999, -3, Number::normalized()}, "9999999999999999"); - test(Number{true, maxMantissa * 1000 + 999, -3, Number::normalized()}, "-9999999999999999"); + test( + Number{false, maxMantissa * 1000 + 999, -3, Number::normalized()}, + "9999999999999999"); + test( + Number{true, maxMantissa * 1000 + 999, -3, Number::normalized()}, + "-9999999999999999"); test(Number{std::numeric_limits::max(), -3}, "9223372036854775"); - test(-(Number{std::numeric_limits::max(), -3}), "-9223372036854775"); + test( + -(Number{std::numeric_limits::max(), -3}), + "-9223372036854775"); - test(Number{std::numeric_limits::min(), 0}, "-9223372036854775e3"); - test(-(Number{std::numeric_limits::min(), 0}), "9223372036854775e3"); + test( + Number{std::numeric_limits::min(), 0}, "-9223372036854775e3"); + test( + -(Number{std::numeric_limits::min(), 0}), + "9223372036854775e3"); } break; case MantissaRange::large: @@ -1121,21 +1251,33 @@ public: auto const maxMantissa = Number::maxMantissa(); BEAST_EXPECT(maxMantissa == 9'999'999'999'999'999'999ULL); - test(Number{false, maxMantissa, 0, Number::normalized{}}, "9999999999999999990"); - test(Number{true, maxMantissa, 0, Number::normalized{}}, "-9999999999999999990"); + test( + Number{false, maxMantissa, 0, Number::normalized{}}, "9999999999999999990"); + test( + Number{true, maxMantissa, 0, Number::normalized{}}, "-9999999999999999990"); - test(Number{std::numeric_limits::max(), 0}, "9223372036854775807"); - test(-(Number{std::numeric_limits::max(), 0}), "-9223372036854775807"); + test( + Number{std::numeric_limits::max(), 0}, "9223372036854775807"); + test( + -(Number{std::numeric_limits::max(), 0}), + "-9223372036854775807"); // Because the absolute value of min is larger than max, it // will be scaled down to fit under max. Since we're // rounding towards zero, the 8 at the end is dropped. - test(Number{std::numeric_limits::min(), 0}, "-9223372036854775800"); - test(-(Number{std::numeric_limits::min(), 0}), "9223372036854775800"); + test( + Number{std::numeric_limits::min(), 0}, + "-9223372036854775800"); + test( + -(Number{std::numeric_limits::min(), 0}), + "9223372036854775800"); } - test(Number{std::numeric_limits::max(), 0} + 1, "9223372036854775810"); - test(-(Number{std::numeric_limits::max(), 0} + 1), "-9223372036854775810"); + test( + Number{std::numeric_limits::max(), 0} + 1, "9223372036854775810"); + test( + -(Number{std::numeric_limits::max(), 0} + 1), + "-9223372036854775810"); break; default: BEAST_EXPECT(false); @@ -1233,39 +1375,87 @@ public: std::map const expected{ // Positive numbers {Number{13, -1}, - {{Number::to_nearest, 1}, {Number::towards_zero, 1}, {Number::downward, 1}, {Number::upward, 2}}}, + {{Number::to_nearest, 1}, + {Number::towards_zero, 1}, + {Number::downward, 1}, + {Number::upward, 2}}}, {Number{23, -1}, - {{Number::to_nearest, 2}, {Number::towards_zero, 2}, {Number::downward, 2}, {Number::upward, 3}}}, + {{Number::to_nearest, 2}, + {Number::towards_zero, 2}, + {Number::downward, 2}, + {Number::upward, 3}}}, {Number{15, -1}, - {{Number::to_nearest, 2}, {Number::towards_zero, 1}, {Number::downward, 1}, {Number::upward, 2}}}, + {{Number::to_nearest, 2}, + {Number::towards_zero, 1}, + {Number::downward, 1}, + {Number::upward, 2}}}, {Number{25, -1}, - {{Number::to_nearest, 2}, {Number::towards_zero, 2}, {Number::downward, 2}, {Number::upward, 3}}}, + {{Number::to_nearest, 2}, + {Number::towards_zero, 2}, + {Number::downward, 2}, + {Number::upward, 3}}}, {Number{152, -2}, - {{Number::to_nearest, 2}, {Number::towards_zero, 1}, {Number::downward, 1}, {Number::upward, 2}}}, + {{Number::to_nearest, 2}, + {Number::towards_zero, 1}, + {Number::downward, 1}, + {Number::upward, 2}}}, {Number{252, -2}, - {{Number::to_nearest, 3}, {Number::towards_zero, 2}, {Number::downward, 2}, {Number::upward, 3}}}, + {{Number::to_nearest, 3}, + {Number::towards_zero, 2}, + {Number::downward, 2}, + {Number::upward, 3}}}, {Number{17, -1}, - {{Number::to_nearest, 2}, {Number::towards_zero, 1}, {Number::downward, 1}, {Number::upward, 2}}}, + {{Number::to_nearest, 2}, + {Number::towards_zero, 1}, + {Number::downward, 1}, + {Number::upward, 2}}}, {Number{27, -1}, - {{Number::to_nearest, 3}, {Number::towards_zero, 2}, {Number::downward, 2}, {Number::upward, 3}}}, + {{Number::to_nearest, 3}, + {Number::towards_zero, 2}, + {Number::downward, 2}, + {Number::upward, 3}}}, // Negative numbers {Number{-13, -1}, - {{Number::to_nearest, -1}, {Number::towards_zero, -1}, {Number::downward, -2}, {Number::upward, -1}}}, + {{Number::to_nearest, -1}, + {Number::towards_zero, -1}, + {Number::downward, -2}, + {Number::upward, -1}}}, {Number{-23, -1}, - {{Number::to_nearest, -2}, {Number::towards_zero, -2}, {Number::downward, -3}, {Number::upward, -2}}}, + {{Number::to_nearest, -2}, + {Number::towards_zero, -2}, + {Number::downward, -3}, + {Number::upward, -2}}}, {Number{-15, -1}, - {{Number::to_nearest, -2}, {Number::towards_zero, -1}, {Number::downward, -2}, {Number::upward, -1}}}, + {{Number::to_nearest, -2}, + {Number::towards_zero, -1}, + {Number::downward, -2}, + {Number::upward, -1}}}, {Number{-25, -1}, - {{Number::to_nearest, -2}, {Number::towards_zero, -2}, {Number::downward, -3}, {Number::upward, -2}}}, + {{Number::to_nearest, -2}, + {Number::towards_zero, -2}, + {Number::downward, -3}, + {Number::upward, -2}}}, {Number{-152, -2}, - {{Number::to_nearest, -2}, {Number::towards_zero, -1}, {Number::downward, -2}, {Number::upward, -1}}}, + {{Number::to_nearest, -2}, + {Number::towards_zero, -1}, + {Number::downward, -2}, + {Number::upward, -1}}}, {Number{-252, -2}, - {{Number::to_nearest, -3}, {Number::towards_zero, -2}, {Number::downward, -3}, {Number::upward, -2}}}, + {{Number::to_nearest, -3}, + {Number::towards_zero, -2}, + {Number::downward, -3}, + {Number::upward, -2}}}, {Number{-17, -1}, - {{Number::to_nearest, -2}, {Number::towards_zero, -1}, {Number::downward, -2}, {Number::upward, -1}}}, + {{Number::to_nearest, -2}, + {Number::towards_zero, -1}, + {Number::downward, -2}, + {Number::upward, -1}}}, {Number{-27, -1}, - {{Number::to_nearest, -3}, {Number::towards_zero, -2}, {Number::downward, -3}, {Number::upward, -2}}}, + {{Number::to_nearest, -3}, + {Number::towards_zero, -2}, + {Number::downward, -3}, + {Number::upward, -2}}}, }; for (auto const& [num, roundings] : expected) @@ -1276,8 +1466,8 @@ public: auto const res = static_cast(num); BEAST_EXPECTS( res == val, - to_string(num) + " with mode " + std::to_string(mode) + " expected " + std::to_string(val) + - " got " + std::to_string(res)); + to_string(num) + " with mode " + std::to_string(mode) + " expected " + + std::to_string(val) + " got " + std::to_string(res)); } } } @@ -1330,7 +1520,8 @@ public: BEAST_EXPECT(max.exponent() == 1); // 99'999'999'999'999'999'800'000'000'000'000'000'100 - also 38 // digits - BEAST_EXPECT((power(max, 2) == Number{false, maxMantissa / 10 - 1, 20, Number::normalized{}})); + BEAST_EXPECT( + (power(max, 2) == Number{false, maxMantissa / 10 - 1, 20, Number::normalized{}})); } } diff --git a/src/test/basics/PerfLog_test.cpp b/src/test/basics/PerfLog_test.cpp index 57eed2aed9..a2976301ef 100644 --- a/src/test/basics/PerfLog_test.cpp +++ b/src/test/basics/PerfLog_test.cpp @@ -85,7 +85,8 @@ class PerfLog_test : public beast::unit_test::suite std::unique_ptr perfLog(WithFile withFile) { - perf::PerfLog::Setup const setup{withFile == WithFile::no ? "" : logFile(), logInterval()}; + perf::PerfLog::Setup const setup{ + withFile == WithFile::no ? "" : logFile(), logInterval()}; return perf::make_PerfLog(setup, app_, j_, [this]() { return signalStop(); }); } @@ -235,7 +236,9 @@ public: return; boost::filesystem::permissions( - fixture.logFile(), perms::remove_perms | perms::owner_write | perms::others_write | perms::group_write); + fixture.logFile(), + perms::remove_perms | perms::owner_write | perms::others_write | + perms::group_write); // If the test is running as root, then the write protect may have // no effect. Make sure write protect worked before proceeding. @@ -260,7 +263,8 @@ public: // Fix file permissions so the file can be cleaned up. boost::filesystem::permissions( - fixture.logFile(), perms::add_perms | perms::owner_write | perms::others_write | perms::group_write); + fixture.logFile(), + perms::add_perms | perms::owner_write | perms::others_write | perms::group_write); } } @@ -284,13 +288,13 @@ public: std::vector ids; ids.reserve(labels.size() * 2); std::generate_n( - std::back_inserter(ids), labels.size(), [i = std::numeric_limits::min()]() mutable { - return i++; - }); + std::back_inserter(ids), + labels.size(), + [i = std::numeric_limits::min()]() mutable { return i++; }); std::generate_n( - std::back_inserter(ids), labels.size(), [i = std::numeric_limits::max()]() mutable { - return i--; - }); + std::back_inserter(ids), + labels.size(), + [i = std::numeric_limits::max()]() mutable { return i--; }); std::shuffle(ids.begin(), ids.end(), default_prng()); // Start all of the RPC commands twice to show they can all be tracked @@ -579,7 +583,8 @@ public: BEAST_EXPECT(total[jss::finished] == "0"); // Total queued duration is triangle number of (i + 1). - BEAST_EXPECT(jsonToUint64(total[jss::queued_duration_us]) == (((i * i) + 3 * i + 2) / 2)); + BEAST_EXPECT( + jsonToUint64(total[jss::queued_duration_us]) == (((i * i) + 3 * i + 2) / 2)); BEAST_EXPECT(total[jss::running_duration_us] == "0"); } @@ -805,31 +810,34 @@ public: perfLog->resizeJobs(1); // Lambda to validate countersJson for this test. - auto verifyCounters = - [this, jobTypeName]( - Json::Value const& countersJson, int started, int finished, int queued_us, int running_us) { - BEAST_EXPECT(countersJson.isObject()); - BEAST_EXPECT(countersJson.size() == 2); + auto verifyCounters = [this, jobTypeName]( + Json::Value const& countersJson, + int started, + int finished, + int queued_us, + int running_us) { + BEAST_EXPECT(countersJson.isObject()); + BEAST_EXPECT(countersJson.size() == 2); - BEAST_EXPECT(countersJson.isMember(jss::rpc)); - BEAST_EXPECT(countersJson[jss::rpc].isObject()); - BEAST_EXPECT(countersJson[jss::rpc].size() == 0); + BEAST_EXPECT(countersJson.isMember(jss::rpc)); + BEAST_EXPECT(countersJson[jss::rpc].isObject()); + BEAST_EXPECT(countersJson[jss::rpc].size() == 0); - BEAST_EXPECT(countersJson.isMember(jss::job_queue)); - BEAST_EXPECT(countersJson[jss::job_queue].isObject()); - BEAST_EXPECT(countersJson[jss::job_queue].size() == 1); - { - Json::Value const& job{countersJson[jss::job_queue][jobTypeName]}; + BEAST_EXPECT(countersJson.isMember(jss::job_queue)); + BEAST_EXPECT(countersJson[jss::job_queue].isObject()); + BEAST_EXPECT(countersJson[jss::job_queue].size() == 1); + { + Json::Value const& job{countersJson[jss::job_queue][jobTypeName]}; - BEAST_EXPECT(job.isObject()); - BEAST_EXPECT(jsonToUint64(job[jss::queued]) == 0); - BEAST_EXPECT(jsonToUint64(job[jss::started]) == started); - BEAST_EXPECT(jsonToUint64(job[jss::finished]) == finished); + BEAST_EXPECT(job.isObject()); + BEAST_EXPECT(jsonToUint64(job[jss::queued]) == 0); + BEAST_EXPECT(jsonToUint64(job[jss::started]) == started); + BEAST_EXPECT(jsonToUint64(job[jss::finished]) == finished); - BEAST_EXPECT(jsonToUint64(job[jss::queued_duration_us]) == queued_us); - BEAST_EXPECT(jsonToUint64(job[jss::running_duration_us]) == running_us); - } - }; + BEAST_EXPECT(jsonToUint64(job[jss::queued_duration_us]) == queued_us); + BEAST_EXPECT(jsonToUint64(job[jss::running_duration_us]) == running_us); + } + }; // Lambda to validate currentJson (always empty) for this test. auto verifyEmptyCurrent = [this](Json::Value const& currentJson) { diff --git a/src/test/basics/Units_test.cpp b/src/test/basics/Units_test.cpp index 9094730870..9712ec91c0 100644 --- a/src/test/basics/Units_test.cpp +++ b/src/test/basics/Units_test.cpp @@ -32,7 +32,9 @@ private: BEAST_EXPECT(drops); BEAST_EXPECT(drops.value() == 1000); - BEAST_EXPECT((std::is_same_v::unit_type, unit::dropTag>)); + BEAST_EXPECT((std::is_same_v< + std::remove_reference_t::unit_type, + unit::dropTag>)); BEAST_EXPECT((std::is_same_v, XRPAmount>)); } @@ -51,7 +53,9 @@ private: BEAST_EXPECT(drops); BEAST_EXPECT(drops.value() == 1000); - BEAST_EXPECT((std::is_same_v::unit_type, unit::dropTag>)); + BEAST_EXPECT((std::is_same_v< + std::remove_reference_t::unit_type, + unit::dropTag>)); BEAST_EXPECT((std::is_same_v, XRPAmount>)); } { @@ -70,7 +74,9 @@ private: BEAST_EXPECT(drops); BEAST_EXPECT(drops.value() == 40); - BEAST_EXPECT((std::is_same_v::unit_type, unit::dropTag>)); + BEAST_EXPECT((std::is_same_v< + std::remove_reference_t::unit_type, + unit::dropTag>)); BEAST_EXPECT((std::is_same_v, XRPAmount>)); } } diff --git a/src/test/basics/base58_test.cpp b/src/test/basics/base58_test.cpp index 5da22d533e..46e0c7615e 100644 --- a/src/test/basics/base58_test.cpp +++ b/src/test/basics/base58_test.cpp @@ -73,7 +73,8 @@ randomTokenTypeAndSize() -> std::tuple // Return the token type and subspan of `d` to use as test data. [[nodiscard]] inline auto -randomB256TestData(std::span d) -> std::tuple> +randomB256TestData(std::span d) + -> std::tuple> { auto& rng = randEngine(); std::uniform_int_distribution dist(0, 255); @@ -164,14 +165,14 @@ class base58_test : public beast::unit_test::suite if (!d) continue; auto bigInt = multiprecision_utils::randomBigInt(); - auto const boostBigInt = - multiprecision_utils::toBoostMP(std::span(bigInt.data(), bigInt.size())); + auto const boostBigInt = multiprecision_utils::toBoostMP( + std::span(bigInt.data(), bigInt.size())); auto const refDiv = boostBigInt / d; auto const refMod = boostBigInt % d; - auto const mod = - b58_fast::detail::inplace_bigint_div_rem(std::span(bigInt.data(), bigInt.size()), d); + auto const mod = b58_fast::detail::inplace_bigint_div_rem( + std::span(bigInt.data(), bigInt.size()), d); auto const foundDiv = multiprecision_utils::toBoostMP(bigInt); BEAST_EXPECT(refMod.convert_to() == mod); BEAST_EXPECT(foundDiv == refDiv); @@ -184,13 +185,13 @@ class base58_test : public beast::unit_test::suite { bigInt[bigInt.size() - 1] -= 1; // Prevent overflow } - auto const boostBigInt = - multiprecision_utils::toBoostMP(std::span(bigInt.data(), bigInt.size())); + auto const boostBigInt = multiprecision_utils::toBoostMP( + std::span(bigInt.data(), bigInt.size())); auto const refAdd = boostBigInt + d; - auto const result = - b58_fast::detail::inplace_bigint_add(std::span(bigInt.data(), bigInt.size()), d); + auto const result = b58_fast::detail::inplace_bigint_add( + std::span(bigInt.data(), bigInt.size()), d); BEAST_EXPECT(result == TokenCodecErrc::success); auto const foundAdd = multiprecision_utils::toBoostMP(bigInt); BEAST_EXPECT(refAdd == foundAdd); @@ -201,13 +202,13 @@ class base58_test : public beast::unit_test::suite // Force overflow std::vector bigInt(5, std::numeric_limits::max()); - auto const boostBigInt = - multiprecision_utils::toBoostMP(std::span(bigInt.data(), bigInt.size())); + auto const boostBigInt = multiprecision_utils::toBoostMP( + std::span(bigInt.data(), bigInt.size())); auto const refAdd = boostBigInt + d; - auto const result = - b58_fast::detail::inplace_bigint_add(std::span(bigInt.data(), bigInt.size()), d); + auto const result = b58_fast::detail::inplace_bigint_add( + std::span(bigInt.data(), bigInt.size()), d); BEAST_EXPECT(result == TokenCodecErrc::overflowAdd); auto const foundAdd = multiprecision_utils::toBoostMP(bigInt); BEAST_EXPECT(refAdd != foundAdd); @@ -219,13 +220,13 @@ class base58_test : public beast::unit_test::suite // inplace mul requires the most significant coeff to be zero to // hold the result. bigInt[bigInt.size() - 1] = 0; - auto const boostBigInt = - multiprecision_utils::toBoostMP(std::span(bigInt.data(), bigInt.size())); + auto const boostBigInt = multiprecision_utils::toBoostMP( + std::span(bigInt.data(), bigInt.size())); auto const refMul = boostBigInt * d; - auto const result = - b58_fast::detail::inplace_bigint_mul(std::span(bigInt.data(), bigInt.size()), d); + auto const result = b58_fast::detail::inplace_bigint_mul( + std::span(bigInt.data(), bigInt.size()), d); BEAST_EXPECT(result == TokenCodecErrc::success); auto const foundMul = multiprecision_utils::toBoostMP(bigInt); BEAST_EXPECT(refMul == foundMul); @@ -235,13 +236,13 @@ class base58_test : public beast::unit_test::suite std::uint64_t const d = dist1(eng); // Force overflow std::vector bigInt(5, std::numeric_limits::max()); - auto const boostBigInt = - multiprecision_utils::toBoostMP(std::span(bigInt.data(), bigInt.size())); + auto const boostBigInt = multiprecision_utils::toBoostMP( + std::span(bigInt.data(), bigInt.size())); auto const refMul = boostBigInt * d; - auto const result = - b58_fast::detail::inplace_bigint_mul(std::span(bigInt.data(), bigInt.size()), d); + auto const result = b58_fast::detail::inplace_bigint_mul( + std::span(bigInt.data(), bigInt.size()), d); BEAST_EXPECT(result == TokenCodecErrc::inputTooLarge); auto const foundMul = multiprecision_utils::toBoostMP(bigInt); BEAST_EXPECT(refMul != foundMul); @@ -279,7 +280,8 @@ class base58_test : public beast::unit_test::suite } if (BEAST_EXPECT(b58Result[0].size() == b58Result[1].size())) { - if (!BEAST_EXPECT(memcmp(b58Result[0].data(), b58Result[1].data(), b58Result[0].size()) == 0)) + if (!BEAST_EXPECT( + memcmp(b58Result[0].data(), b58Result[1].data(), b58Result[0].size()) == 0)) { printAsChar(b58Result[0], b58Result[1]); } @@ -290,7 +292,8 @@ class base58_test : public beast::unit_test::suite std::span const outBuf{b256ResultBuf[i].data(), b256ResultBuf[i].size()}; if (i == 0) { - std::string const in(b58Result[i].data(), b58Result[i].data() + b58Result[i].size()); + std::string const in( + b58Result[i].data(), b58Result[i].data() + b58Result[i].size()); auto const r = xrpl::b58_fast::detail::b58_to_b256_be(in, outBuf); BEAST_EXPECT(r); b256Result[i] = r.value(); @@ -307,14 +310,17 @@ class base58_test : public beast::unit_test::suite if (BEAST_EXPECT(b256Result[0].size() == b256Result[1].size())) { - if (!BEAST_EXPECT(memcmp(b256Result[0].data(), b256Result[1].data(), b256Result[0].size()) == 0)) + if (!BEAST_EXPECT( + memcmp(b256Result[0].data(), b256Result[1].data(), b256Result[0].size()) == + 0)) { printAsInt(b256Result[0], b256Result[1]); } } }; - auto testTokenEncode = [&](xrpl::TokenType const tokType, std::span const& b256Data) { + auto testTokenEncode = [&](xrpl::TokenType const tokType, + std::span const& b256Data) { std::array b58ResultBuf[2]; std::array, 2> b58Result; @@ -331,7 +337,8 @@ class base58_test : public beast::unit_test::suite } else { - std::string const s = xrpl::b58_ref::encodeBase58Token(tokType, b256Data.data(), b256Data.size()); + std::string const s = + xrpl::b58_ref::encodeBase58Token(tokType, b256Data.data(), b256Data.size()); BEAST_EXPECT(s.size()); b58Result[i] = outBuf.subspan(0, s.size()); std::copy(s.begin(), s.end(), b58Result[i].begin()); @@ -339,7 +346,8 @@ class base58_test : public beast::unit_test::suite } if (BEAST_EXPECT(b58Result[0].size() == b58Result[1].size())) { - if (!BEAST_EXPECT(memcmp(b58Result[0].data(), b58Result[1].data(), b58Result[0].size()) == 0)) + if (!BEAST_EXPECT( + memcmp(b58Result[0].data(), b58Result[1].data(), b58Result[0].size()) == 0)) { printAsChar(b58Result[0], b58Result[1]); } @@ -350,7 +358,8 @@ class base58_test : public beast::unit_test::suite std::span const outBuf{b256ResultBuf[i].data(), b256ResultBuf[i].size()}; if (i == 0) { - std::string const in(b58Result[i].data(), b58Result[i].data() + b58Result[i].size()); + std::string const in( + b58Result[i].data(), b58Result[i].data() + b58Result[i].size()); auto const r = xrpl::b58_fast::decodeBase58Token(tokType, in, outBuf); BEAST_EXPECT(r); b256Result[i] = r.value(); @@ -367,7 +376,9 @@ class base58_test : public beast::unit_test::suite if (BEAST_EXPECT(b256Result[0].size() == b256Result[1].size())) { - if (!BEAST_EXPECT(memcmp(b256Result[0].data(), b256Result[1].data(), b256Result[0].size()) == 0)) + if (!BEAST_EXPECT( + memcmp(b256Result[0].data(), b256Result[1].data(), b256Result[0].size()) == + 0)) { printAsInt(b256Result[0], b256Result[1]); } diff --git a/src/test/basics/base_uint_test.cpp b/src/test/basics/base_uint_test.cpp index 9fdc2c7f29..0aa89bcecc 100644 --- a/src/test/basics/base_uint_test.cpp +++ b/src/test/basics/base_uint_test.cpp @@ -76,14 +76,15 @@ struct base_uint_test : beast::unit_test::suite } { - static constexpr std::array, 6> test_args{{ - {"000000000000000000000000", "000000000000000000000001"}, - {"000000000000000000000000", "ffffffffffffffffffffffff"}, - {"0123456789ab0123456789ab", "123456789abc123456789abc"}, - {"555555555555555555555555", "55555555555a555555555555"}, - {"aaaaaaaaaaaaaaa9aaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaa"}, - {"fffffffffffffffffffffffe", "ffffffffffffffffffffffff"}, - }}; + static constexpr std::array, 6> test_args{ + { + {"000000000000000000000000", "000000000000000000000001"}, + {"000000000000000000000000", "ffffffffffffffffffffffff"}, + {"0123456789ab0123456789ab", "123456789abc123456789abc"}, + {"555555555555555555555555", "55555555555a555555555555"}, + {"aaaaaaaaaaaaaaa9aaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaa"}, + {"fffffffffffffffffffffffe", "ffffffffffffffffffffffff"}, + }}; for (auto const& arg : test_args) { diff --git a/src/test/basics/join_test.cpp b/src/test/basics/join_test.cpp index 9739624c63..36d34eee04 100644 --- a/src/test/basics/join_test.cpp +++ b/src/test/basics/join_test.cpp @@ -50,7 +50,9 @@ struct join_test : beast::unit_test::suite { // vector with one item edge case using namespace jtx; - test(CollectionAndDelimiter(std::vector{Account::master}, "xxx"), Account::master.human()); + test( + CollectionAndDelimiter(std::vector{Account::master}, "xxx"), + Account::master.human()); } // empty vector edge case test(CollectionAndDelimiter(std::vector{}, ","), ""); diff --git a/src/test/beast/IPEndpointCommon.h b/src/test/beast/IPEndpointCommon.h index 3ca023188e..73cbe7d95b 100644 --- a/src/test/beast/IPEndpointCommon.h +++ b/src/test/beast/IPEndpointCommon.h @@ -34,7 +34,9 @@ randomEP(bool v4 = true) static_cast(rand_int(1, UINT8_MAX)), static_cast(rand_int(1, UINT8_MAX))}}; }; - return Endpoint{v4 ? Address{AddressV4{dv4()}} : Address{AddressV6{dv6()}}, rand_int(1, UINT16_MAX)}; + return Endpoint{ + v4 ? Address{AddressV4{dv4()}} : Address{AddressV6{dv6()}}, + rand_int(1, UINT16_MAX)}; } } // namespace IP diff --git a/src/test/beast/IPEndpoint_test.cpp b/src/test/beast/IPEndpoint_test.cpp index 67e3f8ed7d..e0eedd4c24 100644 --- a/src/test/beast/IPEndpoint_test.cpp +++ b/src/test/beast/IPEndpoint_test.cpp @@ -209,8 +209,14 @@ public: shouldParseEPV4("1.2.3.4:5 ", {{1, 2, 3, 4}}, 5, "1.2.3.4:5"); shouldParseEPV4("1.2.3.4 ", {{1, 2, 3, 4}}, 0, "1.2.3.4"); shouldParseEPV4(" 1.2.3.4", {{1, 2, 3, 4}}, 0, "1.2.3.4"); - shouldParseEPV6("2001:db8:a0b:12f0::1", {{32, 01, 13, 184, 10, 11, 18, 240, 0, 0, 0, 0, 0, 0, 0, 1}}, 0); - shouldParseEPV6("[2001:db8:a0b:12f0::1]:8", {{32, 01, 13, 184, 10, 11, 18, 240, 0, 0, 0, 0, 0, 0, 0, 1}}, 8); + shouldParseEPV6( + "2001:db8:a0b:12f0::1", + {{32, 01, 13, 184, 10, 11, 18, 240, 0, 0, 0, 0, 0, 0, 0, 1}}, + 0); + shouldParseEPV6( + "[2001:db8:a0b:12f0::1]:8", + {{32, 01, 13, 184, 10, 11, 18, 240, 0, 0, 0, 0, 0, 0, 0, 1}}, + 8); shouldParseEPV6( "[2001:2002:2003:2004:2005:2006:2007:2008]:65535", {{32, 1, 32, 2, 32, 3, 32, 4, 32, 5, 32, 6, 32, 7, 32, 8}}, @@ -232,7 +238,8 @@ public: BEAST_EXPECT(is_loopback(ep)); BEAST_EXPECT(to_string(ep) == "127.0.0.1:80"); // same address as v4 mapped in ipv6 - ep = Endpoint(boost::asio::ip::make_address_v6(boost::asio::ip::v4_mapped, AddressV4{d}), 80); + ep = Endpoint( + boost::asio::ip::make_address_v6(boost::asio::ip::v4_mapped, AddressV4{d}), 80); BEAST_EXPECT(!is_unspecified(ep)); BEAST_EXPECT(!is_public(ep)); BEAST_EXPECT(is_private(ep)); @@ -251,7 +258,9 @@ public: BEAST_EXPECT(to_string(ep) == "10.0.0.1"); // same address as v4 mapped in ipv6 ep = Endpoint(boost::asio::ip::make_address_v6(boost::asio::ip::v4_mapped, AddressV4{d})); - BEAST_EXPECT(get_class(boost::asio::ip::make_address_v4(boost::asio::ip::v4_mapped, ep.to_v6())) == 'A'); + BEAST_EXPECT( + get_class(boost::asio::ip::make_address_v4(boost::asio::ip::v4_mapped, ep.to_v6())) == + 'A'); BEAST_EXPECT(!is_unspecified(ep)); BEAST_EXPECT(!is_public(ep)); BEAST_EXPECT(is_private(ep)); @@ -334,9 +343,9 @@ public: #if BOOST_OS_WINDOWS // windows asio bugs...false positives - shouldParseEPV4("255", {{ 0, 0, 0, 255 }}, 0, "0.0.0.255"); - shouldParseEPV4("512", {{ 0, 0, 2, 0 }}, 0, "0.0.2.0"); - shouldParseEPV4("1.2.3:80", {{ 1, 2, 0, 3 }}, 80, "1.2.0.3:80"); + shouldParseEPV4("255", {{0, 0, 0, 255}}, 0, "0.0.0.255"); + shouldParseEPV4("512", {{0, 0, 2, 0}}, 0, "0.0.2.0"); + shouldParseEPV4("1.2.3:80", {{1, 2, 0, 3}}, 80, "1.2.0.3:80"); #else failParseEP("255"); failParseEP("512"); @@ -385,7 +394,8 @@ public: using namespace std::literals; T t; BEAST_EXPECT(parse(text, t)); - BEAST_EXPECTS(to_string(t) == (normal.empty() ? text : normal), "string mismatch for "s + text); + BEAST_EXPECTS( + to_string(t) == (normal.empty() ? text : normal), "string mismatch for "s + text); } template diff --git a/src/test/beast/SemanticVersion_test.cpp b/src/test/beast/SemanticVersion_test.cpp index b3394235d1..cae10497af 100644 --- a/src/test/beast/SemanticVersion_test.cpp +++ b/src/test/beast/SemanticVersion_test.cpp @@ -198,7 +198,12 @@ public: checkValues("1.2.3+full.prod", 1, 2, 3, ids(), ids("full", "prod")); checkValues("1.2.3+full.prod.x86", 1, 2, 3, ids(), ids("full", "prod", "x86")); checkValues( - "1.2.3-rc1.debug.asm+full.prod.x86", 1, 2, 3, ids("rc1", "debug", "asm"), ids("full", "prod", "x86")); + "1.2.3-rc1.debug.asm+full.prod.x86", + 1, + 2, + 3, + ids("rc1", "debug", "asm"), + ids("full", "prod", "x86")); } // makes sure the left version is less than the right diff --git a/src/test/beast/aged_associative_container_test.cpp b/src/test/beast/aged_associative_container_test.cpp index 3af559c1cb..19927c2d35 100644 --- a/src/test/beast/aged_associative_container_test.cpp +++ b/src/test/beast/aged_associative_container_test.cpp @@ -292,7 +292,9 @@ public: template struct ContType { - template , class Allocator = std::allocator> + template < + class Compare = std::less, + class Allocator = std::allocator> using Cont = detail::aged_ordered_container< Base::is_multi::value, Base::is_map::value, @@ -332,10 +334,12 @@ public: }; template - struct TestTraitsHelper : MaybeUnordered, IsMulti>, IsUnordered> + struct TestTraitsHelper + : MaybeUnordered, IsMulti>, IsUnordered> { private: - using Base = MaybeUnordered, IsMulti>, IsUnordered>; + using Base = + MaybeUnordered, IsMulti>, IsUnordered>; public: using typename Base::Key; @@ -350,7 +354,8 @@ public: static std::string name() { - return std::string("aged_") + Base::name_ordered_part() + Base::name_multi_part() + Base::name_map_part(); + return std::string("aged_") + Base::name_ordered_part() + Base::name_multi_part() + + Base::name_map_part(); } }; @@ -629,7 +634,8 @@ typename std::enable_if::type::is_unordered::value>::ty aged_associative_container_test_base::checkUnorderedContentsRefRef(C&& c, Values const& v) { using Cont = typename std::remove_reference::type; - using Traits = TestTraits; + using Traits = + TestTraits; using size_type = typename Cont::size_type; auto const hash(c.hash_function()); auto const key_eq(c.key_eq()); @@ -638,9 +644,10 @@ aged_associative_container_test_base::checkUnorderedContentsRefRef(C&& c, Values auto const last(c.end(i)); for (auto iter(c.begin(i)); iter != last; ++iter) { - auto const match(std::find_if(v.begin(), v.end(), [iter](typename Values::value_type const& e) { - return Traits::extract(*iter) == Traits::extract(e); - })); + auto const match( + std::find_if(v.begin(), v.end(), [iter](typename Values::value_type const& e) { + return Traits::extract(*iter) == Traits::extract(e); + })); BEAST_EXPECT(match != v.end()); BEAST_EXPECT(key_eq(Traits::extract(*iter), Traits::extract(*match))); BEAST_EXPECT(hash(Traits::extract(*iter)) == hash(Traits::extract(*match))); @@ -658,10 +665,14 @@ aged_associative_container_test_base::checkContentsRefRef(C&& c, Values const& v BEAST_EXPECT(c.size() == v.size()); BEAST_EXPECT(size_type(std::distance(c.begin(), c.end())) == v.size()); BEAST_EXPECT(size_type(std::distance(c.cbegin(), c.cend())) == v.size()); - BEAST_EXPECT(size_type(std::distance(c.chronological.begin(), c.chronological.end())) == v.size()); - BEAST_EXPECT(size_type(std::distance(c.chronological.cbegin(), c.chronological.cend())) == v.size()); - BEAST_EXPECT(size_type(std::distance(c.chronological.rbegin(), c.chronological.rend())) == v.size()); - BEAST_EXPECT(size_type(std::distance(c.chronological.crbegin(), c.chronological.crend())) == v.size()); + BEAST_EXPECT( + size_type(std::distance(c.chronological.begin(), c.chronological.end())) == v.size()); + BEAST_EXPECT( + size_type(std::distance(c.chronological.cbegin(), c.chronological.cend())) == v.size()); + BEAST_EXPECT( + size_type(std::distance(c.chronological.rbegin(), c.chronological.rend())) == v.size()); + BEAST_EXPECT( + size_type(std::distance(c.chronological.crbegin(), c.chronological.crend())) == v.size()); checkUnorderedContentsRefRef(c, v); } @@ -679,7 +690,8 @@ template void aged_associative_container_test_base::checkContents(Cont& c) { - using Traits = TestTraits; + using Traits = + TestTraits; using Values = typename Traits::Values; checkContents(c, Values()); } @@ -778,7 +790,8 @@ aged_associative_container_test_base::testConstructEmpty() } { - typename Traits::template Cont c(clock, MyHash(1), MyEqual(1), MyAlloc(1)); + typename Traits::template Cont c( + clock, MyHash(1), MyEqual(1), MyAlloc(1)); checkContents(c); } } @@ -815,7 +828,8 @@ aged_associative_container_test_base::testConstructRange() } { - typename Traits::template Cont c(v.begin(), v.end(), clock, MyComp(1), MyAlloc(1)); + typename Traits::template Cont c( + v.begin(), v.end(), clock, MyComp(1), MyAlloc(1)); checkContents(c, v); } @@ -853,32 +867,38 @@ aged_associative_container_test_base::testConstructRange() } { - typename Traits::template Cont c(v.begin(), v.end(), clock, MyHash(1)); + typename Traits::template Cont c( + v.begin(), v.end(), clock, MyHash(1)); checkContents(c, v); } { - typename Traits::template Cont c(v.begin(), v.end(), clock, MyEqual(1)); + typename Traits::template Cont c( + v.begin(), v.end(), clock, MyEqual(1)); checkContents(c, v); } { - typename Traits::template Cont c(v.begin(), v.end(), clock, MyAlloc(1)); + typename Traits::template Cont c( + v.begin(), v.end(), clock, MyAlloc(1)); checkContents(c, v); } { - typename Traits::template Cont c(v.begin(), v.end(), clock, MyHash(1), MyEqual(1)); + typename Traits::template Cont c( + v.begin(), v.end(), clock, MyHash(1), MyEqual(1)); checkContents(c, v); } { - typename Traits::template Cont c(v.begin(), v.end(), clock, MyHash(1), MyAlloc(1)); + typename Traits::template Cont c( + v.begin(), v.end(), clock, MyHash(1), MyAlloc(1)); checkContents(c, v); } { - typename Traits::template Cont c(v.begin(), v.end(), clock, MyEqual(1), MyAlloc(1)); + typename Traits::template Cont c( + v.begin(), v.end(), clock, MyEqual(1), MyAlloc(1)); checkContents(c, v); } @@ -1266,7 +1286,12 @@ aged_associative_container_test_base::testChronological() typename Traits::template Cont<> c(v.begin(), v.end(), clock); BEAST_EXPECT( - std::equal(c.chronological.cbegin(), c.chronological.cend(), v.begin(), v.end(), equal_value())); + std::equal( + c.chronological.cbegin(), + c.chronological.cend(), + v.begin(), + v.end(), + equal_value())); // Test touch() with a non-const iterator. for (auto iter(v.crbegin()); iter != v.crend(); ++iter) @@ -1281,7 +1306,12 @@ aged_associative_container_test_base::testChronological() } BEAST_EXPECT( - std::equal(c.chronological.cbegin(), c.chronological.cend(), v.crbegin(), v.crend(), equal_value())); + std::equal( + c.chronological.cbegin(), + c.chronological.cend(), + v.crbegin(), + v.crend(), + equal_value())); // Test touch() with a const_iterator for (auto iter(v.cbegin()); iter != v.cend(); ++iter) @@ -1296,7 +1326,12 @@ aged_associative_container_test_base::testChronological() } BEAST_EXPECT( - std::equal(c.chronological.cbegin(), c.chronological.cend(), v.cbegin(), v.cend(), equal_value())); + std::equal( + c.chronological.cbegin(), + c.chronological.cend(), + v.cbegin(), + v.cend(), + equal_value())); { // Because touch (reverse_iterator pos) is not allowed, the following @@ -1407,7 +1442,10 @@ aged_associative_container_test_base::nextToEndIter(Iter beginIter, Iter const e // the whole test. template bool -aged_associative_container_test_base::doElementErase(Container& c, Iter const beginItr, Iter const endItr) +aged_associative_container_test_base::doElementErase( + Container& c, + Iter const beginItr, + Iter const endItr) { auto it(beginItr); size_t count = c.size(); @@ -1486,7 +1524,9 @@ aged_associative_container_test_base::testElementErase() auto tempContainer(c); BEAST_EXPECT(tempContainer.size() > 2); if (!doElementErase( - tempContainer, ++tempContainer.begin(), nextToEndIter(tempContainer.begin(), tempContainer.end()))) + tempContainer, + ++tempContainer.begin(), + nextToEndIter(tempContainer.begin(), tempContainer.end()))) return; // Test failed BEAST_EXPECT(tempContainer.size() == 2); @@ -1497,7 +1537,8 @@ aged_associative_container_test_base::testElementErase() auto tempContainer(c); BEAST_EXPECT(tempContainer.size() > 2); auto& chron(tempContainer.chronological); - if (!doElementErase(tempContainer, ++chron.begin(), nextToEndIter(chron.begin(), chron.end()))) + if (!doElementErase( + tempContainer, ++chron.begin(), nextToEndIter(chron.begin(), chron.end()))) return; // Test failed BEAST_EXPECT(tempContainer.size() == 2); @@ -1696,7 +1737,8 @@ public: "bad alias: aged_set"); static_assert( - std::is_same, detail::aged_ordered_container>::value, + std::is_same, detail::aged_ordered_container>:: + value, "bad alias: aged_multiset"); static_assert( @@ -1704,23 +1746,32 @@ public: "bad alias: aged_map"); static_assert( - std::is_same, detail::aged_ordered_container>::value, + std::is_same, detail::aged_ordered_container>:: + value, "bad alias: aged_multimap"); static_assert( - std::is_same, detail::aged_unordered_container>::value, + std::is_same< + aged_unordered_set, + detail::aged_unordered_container>::value, "bad alias: aged_unordered_set"); static_assert( - std::is_same, detail::aged_unordered_container>::value, + std::is_same< + aged_unordered_multiset, + detail::aged_unordered_container>::value, "bad alias: aged_unordered_multiset"); static_assert( - std::is_same, detail::aged_unordered_container>::value, + std::is_same< + aged_unordered_map, + detail::aged_unordered_container>::value, "bad alias: aged_unordered_map"); static_assert( - std::is_same, detail::aged_unordered_container>::value, + std::is_same< + aged_unordered_multimap, + detail::aged_unordered_container>::value, "bad alias: aged_unordered_multimap"); void diff --git a/src/test/beast/beast_PropertyStream_test.cpp b/src/test/beast/beast_PropertyStream_test.cpp index c2e6ddc22b..35aa91d18e 100644 --- a/src/test/beast/beast_PropertyStream_test.cpp +++ b/src/test/beast/beast_PropertyStream_test.cpp @@ -9,7 +9,10 @@ public: using Source = PropertyStream::Source; void - test_peel_name(std::string s, std::string const& expected, std::string const& expected_remainder) + test_peel_name( + std::string s, + std::string const& expected, + std::string const& expected_remainder) { try { @@ -41,7 +44,10 @@ public: } void - test_peel_trailing_slashstar(std::string s, std::string const& expected_remainder, bool should_be_found) + test_peel_trailing_slashstar( + std::string s, + std::string const& expected_remainder, + bool should_be_found) { try { diff --git a/src/test/beast/beast_io_latency_probe_test.cpp b/src/test/beast/beast_io_latency_probe_test.cpp index 4a78eb77fe..f2423550d3 100644 --- a/src/test/beast/beast_io_latency_probe_test.cpp +++ b/src/test/beast/beast_io_latency_probe_test.cpp @@ -39,8 +39,8 @@ class io_latency_probe_test : public beast::unit_test::suite, public beast::test { using namespace std::chrono; boost::asio::io_context ios; - std::optional> work{ - boost::asio::make_work_guard(ios)}; + std::optional> + work{boost::asio::make_work_guard(ios)}; std::thread worker{[&] { ios.run(); }}; boost::asio::basic_waitable_timer timer{ios}; elapsed_times_.reserve(num_samples); @@ -88,7 +88,8 @@ class io_latency_probe_test : public beast::unit_test::suite, public beast::test auto getMax() { - return std::chrono::duration_cast(*std::max_element(elapsed_times_.begin(), elapsed_times_.end())) + return std::chrono::duration_cast( + *std::max_element(elapsed_times_.begin(), elapsed_times_.end())) .count(); } @@ -96,7 +97,8 @@ class io_latency_probe_test : public beast::unit_test::suite, public beast::test auto getMin() { - return std::chrono::duration_cast(*std::min_element(elapsed_times_.begin(), elapsed_times_.end())) + return std::chrono::duration_cast( + *std::min_element(elapsed_times_.begin(), elapsed_times_.end())) .count(); } }; @@ -107,7 +109,8 @@ class io_latency_probe_test : public beast::unit_test::suite, public beast::test beast::io_latency_probe probe_; std::vector durations_; - test_sampler(std::chrono::milliseconds interval, boost::asio::io_context& ios) : probe_(interval, ios) + test_sampler(std::chrono::milliseconds interval, boost::asio::io_context& ios) + : probe_(interval, ios) { } @@ -162,7 +165,8 @@ class io_latency_probe_test : public beast::unit_test::suite, public beast::test measure_asio_timers tt{interval}; log << "measured mean for timers: " << tt.getMean() << "ms\n"; log << "measured max for timers: " << tt.getMax() << "ms\n"; - expected_probe_count_min = static_cast(duration_cast(probe_duration).count()) / + expected_probe_count_min = + static_cast(duration_cast(probe_duration).count()) / static_cast(tt.getMean()); #endif test_sampler io_probe{interval, get_io_context()}; @@ -173,7 +177,8 @@ class io_latency_probe_test : public beast::unit_test::suite, public beast::test return; auto probes_seen = io_probe.durations_.size(); BEAST_EXPECTS( - probes_seen >= (expected_probe_count_min - 1) && probes_seen <= (expected_probe_count_max + 1), + probes_seen >= (expected_probe_count_min - 1) && + probes_seen <= (expected_probe_count_max + 1), std::string("probe count is ") + std::to_string(probes_seen)); io_probe.probe_.cancel_async(); // wait again in order to flush the remaining diff --git a/src/test/conditions/PreimageSha256_test.cpp b/src/test/conditions/PreimageSha256_test.cpp index 71ba526be3..c3508758a7 100644 --- a/src/test/conditions/PreimageSha256_test.cpp +++ b/src/test/conditions/PreimageSha256_test.cpp @@ -1,12 +1,11 @@ -#include -#include -#include - #include #include #include #include #include +#include +#include +#include #include #include diff --git a/src/test/consensus/ByzantineFailureSim_test.cpp b/src/test/consensus/ByzantineFailureSim_test.cpp index 62899730c2..245c52d9e3 100644 --- a/src/test/consensus/ByzantineFailureSim_test.cpp +++ b/src/test/consensus/ByzantineFailureSim_test.cpp @@ -48,7 +48,8 @@ class ByzantineFailureSim_test : public beast::unit_test::suite for (TrustGraph::ForkInfo const& fi : sim.trustGraph.forkablePairs(0.8)) { std::cout << "Can fork " << PeerGroup{fi.unlA} << " " - << " " << PeerGroup{fi.unlB} << " overlap " << fi.overlap << " required " << fi.required << "\n"; + << " " << PeerGroup{fi.unlB} << " overlap " << fi.overlap << " required " + << fi.required << "\n"; }; // set prior state diff --git a/src/test/consensus/Consensus_test.cpp b/src/test/consensus/Consensus_test.cpp index 3227ad4d1c..0d023f270d 100644 --- a/src/test/consensus/Consensus_test.cpp +++ b/src/test/consensus/Consensus_test.cpp @@ -61,61 +61,79 @@ public: // Disputes still in doubt // // Not enough time has elapsed - BEAST_EXPECT(ConsensusState::No == checkConsensus(10, 2, 2, 0, 3s, 2s, false, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::No == checkConsensus(10, 2, 2, 0, 3s, 2s, false, p, true, journal_)); // If not enough peers have proposed, ensure // more time for proposals - BEAST_EXPECT(ConsensusState::No == checkConsensus(10, 2, 2, 0, 3s, 4s, false, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::No == checkConsensus(10, 2, 2, 0, 3s, 4s, false, p, true, journal_)); // Enough time has elapsed and we all agree - BEAST_EXPECT(ConsensusState::Yes == checkConsensus(10, 2, 2, 0, 3s, 10s, false, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::Yes == checkConsensus(10, 2, 2, 0, 3s, 10s, false, p, true, journal_)); // Enough time has elapsed and we don't yet agree - BEAST_EXPECT(ConsensusState::No == checkConsensus(10, 2, 1, 0, 3s, 10s, false, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::No == checkConsensus(10, 2, 1, 0, 3s, 10s, false, p, true, journal_)); // Our peers have moved on // Enough time has elapsed and we all agree - BEAST_EXPECT(ConsensusState::MovedOn == checkConsensus(10, 2, 1, 8, 3s, 10s, false, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::MovedOn == + checkConsensus(10, 2, 1, 8, 3s, 10s, false, p, true, journal_)); // If no peers, don't agree until time has passed. - BEAST_EXPECT(ConsensusState::No == checkConsensus(0, 0, 0, 0, 3s, 10s, false, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::No == checkConsensus(0, 0, 0, 0, 3s, 10s, false, p, true, journal_)); // Agree if no peers and enough time has passed. - BEAST_EXPECT(ConsensusState::Yes == checkConsensus(0, 0, 0, 0, 3s, 16s, false, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::Yes == checkConsensus(0, 0, 0, 0, 3s, 16s, false, p, true, journal_)); // Expire if too much time has passed without agreement - BEAST_EXPECT(ConsensusState::Expired == checkConsensus(10, 8, 1, 0, 1s, 19s, false, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::Expired == + checkConsensus(10, 8, 1, 0, 1s, 19s, false, p, true, journal_)); /////////////// // Stalled // // Not enough time has elapsed - BEAST_EXPECT(ConsensusState::No == checkConsensus(10, 2, 2, 0, 3s, 2s, true, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::No == checkConsensus(10, 2, 2, 0, 3s, 2s, true, p, true, journal_)); // If not enough peers have proposed, ensure // more time for proposals - BEAST_EXPECT(ConsensusState::No == checkConsensus(10, 2, 2, 0, 3s, 4s, true, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::No == checkConsensus(10, 2, 2, 0, 3s, 4s, true, p, true, journal_)); // Enough time has elapsed and we all agree - BEAST_EXPECT(ConsensusState::Yes == checkConsensus(10, 2, 2, 0, 3s, 10s, true, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::Yes == checkConsensus(10, 2, 2, 0, 3s, 10s, true, p, true, journal_)); // Enough time has elapsed and we don't yet agree, but there's nothing // left to dispute - BEAST_EXPECT(ConsensusState::Yes == checkConsensus(10, 2, 1, 0, 3s, 10s, true, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::Yes == checkConsensus(10, 2, 1, 0, 3s, 10s, true, p, true, journal_)); // Our peers have moved on // Enough time has elapsed and we all agree, nothing left to dispute - BEAST_EXPECT(ConsensusState::Yes == checkConsensus(10, 2, 1, 8, 3s, 10s, true, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::Yes == checkConsensus(10, 2, 1, 8, 3s, 10s, true, p, true, journal_)); // If no peers, don't agree until time has passed. - BEAST_EXPECT(ConsensusState::No == checkConsensus(0, 0, 0, 0, 3s, 10s, true, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::No == checkConsensus(0, 0, 0, 0, 3s, 10s, true, p, true, journal_)); // Agree if no peers and enough time has passed. - BEAST_EXPECT(ConsensusState::Yes == checkConsensus(0, 0, 0, 0, 3s, 16s, true, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::Yes == checkConsensus(0, 0, 0, 0, 3s, 16s, true, p, true, journal_)); // We are done if there's nothing left to dispute, no matter how much // time has passed - BEAST_EXPECT(ConsensusState::Yes == checkConsensus(10, 8, 1, 0, 1s, 19s, true, p, true, journal_)); + BEAST_EXPECT( + ConsensusState::Yes == checkConsensus(10, 8, 1, 0, 1s, 19s, true, p, true, journal_)); } void @@ -1005,8 +1023,8 @@ public: // Simulate clients submitting 1 tx every 5 seconds to a random // validator Rate const rate{1, 5s}; - auto peerSelector = - makeSelector(network.begin(), network.end(), std::vector(network.size(), 1.), sim.rng); + auto peerSelector = makeSelector( + network.begin(), network.end(), std::vector(network.size(), 1.), sim.rng); auto txSubmitter = makeSubmitter( ConstantDistribution{rate.inv()}, sim.scheduler.now(), @@ -1238,19 +1256,36 @@ public: BEAST_EXPECT(clog->str() == ""); } - auto expectStalled = - [this, &clog](int txid, bool ourVote, int ourTime, int peerTime, int support, std::uint32_t line) { - using namespace std::string_literals; + auto expectStalled = [this, &clog]( + int txid, + bool ourVote, + int ourTime, + int peerTime, + int support, + std::uint32_t line) { + using namespace std::string_literals; - auto const s = clog->str(); - expect(s.find("stalled"), s, __FILE__, line); - expect(s.starts_with("Transaction "s + std::to_string(txid)), s, __FILE__, line); - expect(s.find("voting "s + (ourVote ? "YES" : "NO")) != s.npos, s, __FILE__, line); - expect(s.find("for "s + std::to_string(ourTime) + " rounds."s) != s.npos, s, __FILE__, line); - expect(s.find("votes in "s + std::to_string(peerTime) + " rounds.") != s.npos, s, __FILE__, line); - expect(s.ends_with("has "s + std::to_string(support) + "% support. "s), s, __FILE__, line); - clog = std::make_unique(); - }; + auto const s = clog->str(); + expect(s.find("stalled"), s, __FILE__, line); + expect(s.starts_with("Transaction "s + std::to_string(txid)), s, __FILE__, line); + expect(s.find("voting "s + (ourVote ? "YES" : "NO")) != s.npos, s, __FILE__, line); + expect( + s.find("for "s + std::to_string(ourTime) + " rounds."s) != s.npos, + s, + __FILE__, + line); + expect( + s.find("votes in "s + std::to_string(peerTime) + " rounds.") != s.npos, + s, + __FILE__, + line); + expect( + s.ends_with("has "s + std::to_string(support) + "% support. "s), + s, + __FILE__, + line); + clog = std::make_unique(); + }; for (int i = 0; i < 1; ++i) { diff --git a/src/test/consensus/DistributedValidatorsSim_test.cpp b/src/test/consensus/DistributedValidatorsSim_test.cpp index 49d2c6e7e2..b430a63880 100644 --- a/src/test/consensus/DistributedValidatorsSim_test.cpp +++ b/src/test/consensus/DistributedValidatorsSim_test.cpp @@ -67,7 +67,8 @@ class DistributedValidators_test : public beast::unit_test::suite HeartbeatTimer heart(sim.scheduler); // txs, start/stop/step, target - auto peerSelector = makeSelector(peers.begin(), peers.end(), std::vector(numPeers, 1.), sim.rng); + auto peerSelector = + makeSelector(peers.begin(), peers.end(), std::vector(numPeers, 1.), sim.rng); auto txSubmitter = makeSubmitter( ConstantDistribution{rate.inv()}, sim.scheduler.now() + quiet, @@ -85,7 +86,8 @@ class DistributedValidators_test : public beast::unit_test::suite log << std::right; log << "| Peers: " << std::setw(2) << peers.size(); - log << " | Duration: " << std::setw(6) << duration_cast(simDuration).count() << " ms"; + log << " | Duration: " << std::setw(6) << duration_cast(simDuration).count() + << " ms"; log << " | Branches: " << std::setw(1) << sim.branches(); log << " | Synchronized: " << std::setw(1) << (sim.synchronized() ? "Y" : "N"); log << " |" << std::endl; @@ -136,7 +138,12 @@ class DistributedValidators_test : public beast::unit_test::suite // scale-free connect graph with fixed delay std::vector const ranks = sample(peers.size(), PowerLawDistribution{1, 3}, sim.rng); randomRankedConnect( - peers, ranks, numCNLs, std::uniform_int_distribution<>{minCNLSize, maxCNLSize}, sim.rng, delay); + peers, + ranks, + numCNLs, + std::uniform_int_distribution<>{minCNLSize, maxCNLSize}, + sim.rng, + delay); // Initialize collectors to track statistics to report TxCollector txCollector; @@ -156,7 +163,8 @@ class DistributedValidators_test : public beast::unit_test::suite HeartbeatTimer heart(sim.scheduler); // txs, start/stop/step, target - auto peerSelector = makeSelector(peers.begin(), peers.end(), std::vector(numPeers, 1.), sim.rng); + auto peerSelector = + makeSelector(peers.begin(), peers.end(), std::vector(numPeers, 1.), sim.rng); auto txSubmitter = makeSubmitter( ConstantDistribution{rate.inv()}, sim.scheduler.now() + quiet, @@ -174,7 +182,8 @@ class DistributedValidators_test : public beast::unit_test::suite log << std::right; log << "| Peers: " << std::setw(2) << peers.size(); - log << " | Duration: " << std::setw(6) << duration_cast(simDuration).count() << " ms"; + log << " | Duration: " << std::setw(6) << duration_cast(simDuration).count() + << " ms"; log << " | Branches: " << std::setw(1) << sim.branches(); log << " | Synchronized: " << std::setw(1) << (sim.synchronized() ? "Y" : "N"); log << " |" << std::endl; diff --git a/src/test/consensus/LedgerTiming_test.cpp b/src/test/consensus/LedgerTiming_test.cpp index ac00cd1f3a..62902d6a28 100644 --- a/src/test/consensus/LedgerTiming_test.cpp +++ b/src/test/consensus/LedgerTiming_test.cpp @@ -26,7 +26,8 @@ class LedgerTiming_test : public beast::unit_test::suite std::uint32_t round = 0; do { - nextCloseResolution = getNextLedgerTimeResolution(closeResolution, previousAgree, ++round); + nextCloseResolution = + getNextLedgerTimeResolution(closeResolution, previousAgree, ++round); if (nextCloseResolution < closeResolution) ++res.decrease; else if (nextCloseResolution > closeResolution) diff --git a/src/test/consensus/NegativeUNL_test.cpp b/src/test/consensus/NegativeUNL_test.cpp index 9e77f158a3..d03ee3950d 100644 --- a/src/test/consensus/NegativeUNL_test.cpp +++ b/src/test/consensus/NegativeUNL_test.cpp @@ -4,10 +4,10 @@ #include #include #include -#include #include #include +#include namespace xrpl { namespace test { @@ -34,7 +34,11 @@ namespace test { * @return true if meet all three expectation */ bool -negUnlSizeTest(std::shared_ptr const& l, size_t size, bool hasToDisable, bool hasToReEnable); +negUnlSizeTest( + std::shared_ptr const& l, + size_t size, + bool hasToDisable, + bool hasToReEnable); /** * Try to apply a ttUNL_MODIFY Tx, and test the apply result @@ -58,7 +62,9 @@ applyAndTestResult(jtx::Env& env, OpenView& view, STTx const& tx, bool pass); * @return true if meet the expectation */ bool -VerifyPubKeyAndSeq(std::shared_ptr const& l, hash_map nUnlLedgerSeq); +VerifyPubKeyAndSeq( + std::shared_ptr const& l, + hash_map nUnlLedgerSeq); /** * Count the number of Tx in a TxSet @@ -536,7 +542,10 @@ struct NetworkHistory { static uint256 fake_amendment; // So we have different genesis ledgers auto l = std::make_shared( - create_genesis, env.app().config(), std::vector{fake_amendment++}, env.app().getNodeFamily()); + create_genesis, + env.app().config(), + std::vector{fake_amendment++}, + env.app().getNodeFamily()); history.push_back(l); // When putting validators into the negative UNL, we start with @@ -660,11 +669,16 @@ auto defaultPreVote = [](NegativeUNLVote& vote) {}; */ template bool -voteAndCheck(NetworkHistory& history, NodeID const& myId, std::size_t expect, PreVote const& pre = defaultPreVote) +voteAndCheck( + NetworkHistory& history, + NodeID const& myId, + std::size_t expect, + PreVote const& pre = defaultPreVote) { NegativeUNLVote vote(myId, history.env.journal); pre(vote); - auto txSet = std::make_shared(SHAMapType::TRANSACTION, history.env.app().getNodeFamily()); + auto txSet = + std::make_shared(SHAMapType::TRANSACTION, history.env.app().getNodeFamily()); vote.doVoting(history.lastLedger(), history.UNLKeySet, history.validations, txSet); return countTx(txSet) == expect; } @@ -741,7 +755,8 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite if (history.goodHistory) { NegativeUNLVote vote(history.UNLNodeIDs[3], history.env.journal); - BEAST_EXPECT(!vote.buildScoreTable(history.lastLedger(), history.UNLNodeIDSet, history.validations)); + BEAST_EXPECT(!vote.buildScoreTable( + history.lastLedger(), history.UNLNodeIDSet, history.validations)); } } @@ -752,7 +767,8 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite if (history.goodHistory) { NegativeUNLVote vote(history.UNLNodeIDs[3], history.env.journal); - BEAST_EXPECT(!vote.buildScoreTable(history.lastLedger(), history.UNLNodeIDSet, history.validations)); + BEAST_EXPECT(!vote.buildScoreTable( + history.lastLedger(), history.UNLNodeIDSet, history.validations)); } } @@ -769,7 +785,8 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite 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)); + BEAST_EXPECT(!vote.buildScoreTable( + history.lastLedger(), history.UNLNodeIDSet, history.validations)); } } @@ -810,7 +827,8 @@ 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); + auto scoreTable = vote.buildScoreTable( + wrongChain.back(), history.UNLNodeIDSet, history.validations); BEAST_EXPECT(scoreTable); if (scoreTable) { @@ -825,7 +843,8 @@ 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)); + BEAST_EXPECT(!vote.buildScoreTable( + history.lastLedger(), history.UNLNodeIDSet, history.validations)); } } @@ -836,9 +855,12 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { + return true; + }); NegativeUNLVote vote(history.UNLNodeIDs[3], history.env.journal); - auto scoreTable = vote.buildScoreTable(history.lastLedger(), history.UNLNodeIDSet, history.validations); + auto scoreTable = vote.buildScoreTable( + history.lastLedger(), history.UNLNodeIDSet, history.validations); BEAST_EXPECT(scoreTable); if (scoreTable) { @@ -873,7 +895,8 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite std::size_t numDisable, std::size_t numReEnable) { - auto [disableCandidates, reEnableCandidates] = vote.findAllCandidates(unl, negUnl, scoreTable); + auto [disableCandidates, reEnableCandidates] = + vote.findAllCandidates(unl, negUnl, scoreTable); bool rightDisable = disableCandidates.size() == numDisable; bool rightReEnable = reEnableCandidates.size() == numReEnable; return rightDisable && rightReEnable; @@ -914,28 +937,32 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite { // all good scores - BEAST_EXPECT(checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, goodScoreTable, 0, 3)); + BEAST_EXPECT( + checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, goodScoreTable, 0, 3)); } { // all bad scores hash_map scoreTable; for (auto& n : history.UNLNodeIDs) scoreTable[n] = NegativeUNLVote::negativeUNLLowWaterMark - 1; - BEAST_EXPECT(checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 35 - 3, 0)); + BEAST_EXPECT( + checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 35 - 3, 0)); } { // all between watermarks hash_map scoreTable; for (auto& n : history.UNLNodeIDs) scoreTable[n] = NegativeUNLVote::negativeUNLLowWaterMark + 1; - BEAST_EXPECT(checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 0, 0)); + BEAST_EXPECT( + checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 0, 0)); } { // 2 good scorers in negUnl auto scoreTable = goodScoreTable; scoreTable[*negUnl_012.begin()] = NegativeUNLVote::negativeUNLLowWaterMark + 1; - BEAST_EXPECT(checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 0, 2)); + BEAST_EXPECT( + checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 0, 2)); } { @@ -943,7 +970,8 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite auto scoreTable = goodScoreTable; scoreTable[history.UNLNodeIDs[11]] = NegativeUNLVote::negativeUNLLowWaterMark - 1; scoreTable[history.UNLNodeIDs[12]] = NegativeUNLVote::negativeUNLLowWaterMark - 1; - BEAST_EXPECT(checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 2, 3)); + BEAST_EXPECT( + checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 2, 3)); } { @@ -984,7 +1012,8 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite hash_set negUnl_temp = negUnl_012; negUnl_temp.insert(new_1); negUnl_temp.insert(new_2); - BEAST_EXPECT(checkCandidateSizes(vote, UNL_temp, negUnl_temp, scoreTable, 0, 3 + 2)); + BEAST_EXPECT( + checkCandidateSizes(vote, UNL_temp, negUnl_temp, scoreTable, 0, 3 + 2)); } { // 2 new validators have bad scores, not in negUnl @@ -1098,8 +1127,8 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite toReEnable_expect = us; } } - BEAST_EXPECT( - checkCandidateSizes(vote, unl, negUnl, scoreTable, toDisable_expect, toReEnable_expect)); + BEAST_EXPECT(checkCandidateSizes( + vote, unl, negUnl, scoreTable, toDisable_expect, toReEnable_expect)); } } } @@ -1168,8 +1197,8 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite { toReEnable_expect = negUnl.size() - 12; } - BEAST_EXPECT( - checkCandidateSizes(vote, unl, negUnl, scoreTable, toDisable_expect, toReEnable_expect)); + BEAST_EXPECT(checkCandidateSizes( + vote, unl, negUnl, scoreTable, toDisable_expect, toReEnable_expect)); } } } @@ -1227,7 +1256,8 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite vote.purgeNewValidators(NegativeUNLVote::newValidatorDisableSkip + 4); BEAST_EXPECT(vote.newValidators_.size() == 1); BEAST_EXPECT(vote.newValidators_.begin()->first == n3); - BEAST_EXPECT(vote.newValidators_.begin()->second == NegativeUNLVote::newValidatorDisableSkip); + BEAST_EXPECT( + vote.newValidators_.begin()->second == NegativeUNLVote::newValidatorDisableSkip); } void @@ -1289,8 +1319,8 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::suite }); NegativeUNLVote vote(myId, history.env.journal); - auto scoreTable = - vote.buildScoreTable(history.lastLedger(), history.UNLNodeIDSet, history.validations); + auto scoreTable = vote.buildScoreTable( + history.lastLedger(), history.UNLNodeIDSet, history.validations); BEAST_EXPECT(scoreTable); if (scoreTable) { @@ -1379,7 +1409,9 @@ class NegativeUNLVoteGoodScore_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { + return true; + }); BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 0)); } } @@ -1392,7 +1424,9 @@ class NegativeUNLVoteGoodScore_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { + return true; + }); BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 1)); } } @@ -1500,7 +1534,9 @@ class NegativeUNLVoteRetiredValidator_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, std::size_t idx) -> bool { return idx > 1; }); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { + return idx > 1; + }); BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 0)); } } @@ -1513,7 +1549,9 @@ class NegativeUNLVoteRetiredValidator_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, std::size_t idx) -> bool { return idx > 1; }); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { + return idx > 1; + }); BEAST_EXPECT(voteAndCheck(history, NodeID(0xdeadbeef), 0)); } } @@ -1526,11 +1564,14 @@ class NegativeUNLVoteRetiredValidator_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, std::size_t idx) -> bool { 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]); - })); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { + 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]); + })); } } } @@ -1557,39 +1598,46 @@ class NegativeUNLVoteNewValidator_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); - BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 0, [&](NegativeUNLVote& vote) { - auto extra_key_1 = randomKeyPair(KeyType::ed25519).first; - auto extra_key_2 = randomKeyPair(KeyType::ed25519).first; - history.UNLKeySet.insert(extra_key_1); - history.UNLKeySet.insert(extra_key_2); - hash_set nowTrusted; - nowTrusted.insert(calcNodeID(extra_key_1)); - nowTrusted.insert(calcNodeID(extra_key_2)); - vote.newValidators(history.lastLedger()->seq(), nowTrusted); - })); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { + return true; + }); + BEAST_EXPECT( + voteAndCheck(history, history.UNLNodeIDs[0], 0, [&](NegativeUNLVote& vote) { + auto extra_key_1 = randomKeyPair(KeyType::ed25519).first; + auto extra_key_2 = randomKeyPair(KeyType::ed25519).first; + history.UNLKeySet.insert(extra_key_1); + history.UNLKeySet.insert(extra_key_2); + hash_set nowTrusted; + nowTrusted.insert(calcNodeID(extra_key_1)); + nowTrusted.insert(calcNodeID(extra_key_2)); + vote.newValidators(history.lastLedger()->seq(), nowTrusted); + })); } } { //== 2 expired new validators have bad scores //-- txSet.size = 1 - NetworkHistory history = {*this, {21, 0, false, false, NegativeUNLVote::newValidatorDisableSkip * 2}}; + NetworkHistory history = { + *this, {21, 0, false, false, NegativeUNLVote::newValidatorDisableSkip * 2}}; BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); - BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 1, [&](NegativeUNLVote& vote) { - auto extra_key_1 = randomKeyPair(KeyType::ed25519).first; - auto extra_key_2 = randomKeyPair(KeyType::ed25519).first; - history.UNLKeySet.insert(extra_key_1); - history.UNLKeySet.insert(extra_key_2); - hash_set nowTrusted; - nowTrusted.insert(calcNodeID(extra_key_1)); - nowTrusted.insert(calcNodeID(extra_key_2)); - vote.newValidators(256, nowTrusted); - })); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { + return true; + }); + BEAST_EXPECT( + voteAndCheck(history, history.UNLNodeIDs[0], 1, [&](NegativeUNLVote& vote) { + auto extra_key_1 = randomKeyPair(KeyType::ed25519).first; + auto extra_key_2 = randomKeyPair(KeyType::ed25519).first; + history.UNLKeySet.insert(extra_key_1); + history.UNLKeySet.insert(extra_key_2); + hash_set nowTrusted; + nowTrusted.insert(calcNodeID(extra_key_1)); + nowTrusted.insert(calcNodeID(extra_key_2)); + vote.newValidators(256, nowTrusted); + })); } } } @@ -1613,7 +1661,11 @@ class NegativeUNLVoteFilterValidations_test : public beast::unit_test::suite auto createSTVal = [&](std::pair const& keys) { return std::make_shared( - env.app().timeKeeper().now(), keys.first, keys.second, calcNodeID(keys.first), [&](STValidation& v) { + env.app().timeKeeper().now(), + keys.first, + keys.second, + calcNodeID(keys.first), + [&](STValidation& v) { v.setFieldH256(sfLedgerHash, l->header().hash); v.setFieldU32(sfLedgerSequence, l->seq()); v.setFlag(vfFullValidation); @@ -1682,7 +1734,11 @@ BEAST_DEFINE_TESTSUITE(NegativeUNLVoteFilterValidations, consensus, xrpl); /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// bool -negUnlSizeTest(std::shared_ptr const& l, size_t size, bool hasToDisable, bool hasToReEnable) +negUnlSizeTest( + std::shared_ptr const& l, + size_t size, + bool hasToDisable, + bool hasToReEnable) { bool sameSize = l->negativeUNL().size() == size; bool sameToDisable = (l->validatorToDisable() != std::nullopt) == hasToDisable; @@ -1702,7 +1758,9 @@ applyAndTestResult(jtx::Env& env, OpenView& view, STTx const& tx, bool pass) } bool -VerifyPubKeyAndSeq(std::shared_ptr const& l, hash_map nUnlLedgerSeq) +VerifyPubKeyAndSeq( + std::shared_ptr const& l, + hash_map nUnlLedgerSeq) { auto sle = l->read(keylet::negativeUNL()); if (!sle) diff --git a/src/test/consensus/ScaleFreeSim_test.cpp b/src/test/consensus/ScaleFreeSim_test.cpp index ae70ee9174..2c8014d8e8 100644 --- a/src/test/consensus/ScaleFreeSim_test.cpp +++ b/src/test/consensus/ScaleFreeSim_test.cpp @@ -29,10 +29,16 @@ class ScaleFreeSim_test : public beast::unit_test::suite PeerGroup network = sim.createGroup(N); // generate trust ranks - std::vector const ranks = sample(network.size(), PowerLawDistribution{1, 3}, sim.rng); + std::vector const ranks = + sample(network.size(), PowerLawDistribution{1, 3}, sim.rng); // generate scale-free trust graph - randomRankedTrust(network, ranks, numUNLs, std::uniform_int_distribution<>{minUNLSize, maxUNLSize}, sim.rng); + randomRankedTrust( + network, + ranks, + numUNLs, + std::uniform_int_distribution<>{minUNLSize, maxUNLSize}, + sim.rng); // nodes with a trust line in either direction are network-connected network.connectFromTrust(round(0.2 * parms.ledgerGRANULARITY)); @@ -74,7 +80,8 @@ class ScaleFreeSim_test : public beast::unit_test::suite // TODO: Clean up this formatting mess!! log << "Peers: " << network.size() << std::endl; - log << "Simulated Duration: " << duration_cast(simDuration).count() << " ms" << std::endl; + log << "Simulated Duration: " << duration_cast(simDuration).count() << " ms" + << std::endl; log << "Branches: " << sim.branches() << std::endl; log << "Synchronized: " << (sim.synchronized() ? "Y" : "N") << std::endl; log << std::endl; diff --git a/src/test/consensus/Validations_test.cpp b/src/test/consensus/Validations_test.cpp index 34e0c23bad..f8458e090c 100644 --- a/src/test/consensus/Validations_test.cpp +++ b/src/test/consensus/Validations_test.cpp @@ -25,7 +25,8 @@ class Validations_test : public beast::unit_test::suite // generated NetClock time to be well past its epoch to ensure // any subtractions are positive using namespace std::chrono; - return NetClock::time_point(duration_cast(c.now().time_since_epoch() + 86400s)); + return NetClock::time_point( + duration_cast(c.now().time_since_epoch() + 86400s)); } // Represents a node that can issue validations @@ -99,7 +100,15 @@ class Validations_test : public beast::unit_test::suite NetClock::duration seenOffset, bool full) const { - Validation v{id, seq, now() + signOffset, now() + seenOffset, currKey(), nodeID_, full, loadFee_}; + Validation v{ + id, + seq, + now() + signOffset, + now() + seenOffset, + currKey(), + nodeID_, + full, + loadFee_}; if (trusted_) v.setTrusted(); return v; @@ -114,13 +123,15 @@ class Validations_test : public beast::unit_test::suite Validation validate(Ledger ledger) const { - return validate(ledger.id(), ledger.seq(), NetClock::duration{0}, NetClock::duration{0}, true); + return validate( + ledger.id(), ledger.seq(), NetClock::duration{0}, NetClock::duration{0}, true); } Validation partial(Ledger ledger) const { - return validate(ledger.id(), ledger.seq(), NetClock::duration{0}, NetClock::duration{0}, false); + return validate( + ledger.id(), ledger.seq(), NetClock::duration{0}, NetClock::duration{0}, false); } }; @@ -304,13 +315,16 @@ class Validations_test : public beast::unit_test::suite Node n = harness.makeNode(); BEAST_EXPECT( - ValStatus::stale == harness.add(n.validate(ledgerA, -harness.parms().validationCURRENT_EARLY, 0s))); + ValStatus::stale == + harness.add(n.validate(ledgerA, -harness.parms().validationCURRENT_EARLY, 0s))); BEAST_EXPECT( - ValStatus::stale == harness.add(n.validate(ledgerA, harness.parms().validationCURRENT_WALL, 0s))); + ValStatus::stale == + harness.add(n.validate(ledgerA, harness.parms().validationCURRENT_WALL, 0s))); BEAST_EXPECT( - ValStatus::stale == harness.add(n.validate(ledgerA, 0s, harness.parms().validationCURRENT_LOCAL))); + ValStatus::stale == + harness.add(n.validate(ledgerA, 0s, harness.parms().validationCURRENT_LOCAL))); } { @@ -367,7 +381,9 @@ class Validations_test : public beast::unit_test::suite BEAST_EXPECT(ValStatus::current == harness.add(n.validate(ledgerAB))); trigger(harness.vals()); BEAST_EXPECT(harness.vals().getNodesAfter(ledgerA, ledgerA.id()) == 1); - BEAST_EXPECT(harness.vals().getPreferred(genesisLedger) == std::make_pair(ledgerAB.seq(), ledgerAB.id())); + BEAST_EXPECT( + harness.vals().getPreferred(genesisLedger) == + std::make_pair(ledgerAB.seq(), ledgerAB.id())); harness.clock().advance(harness.parms().validationCURRENT_LOCAL); // trigger check for stale @@ -395,7 +411,8 @@ class Validations_test : public beast::unit_test::suite Ledger ledgerAD = h["ad"]; TestHarness harness(h.oracle); - Node a = harness.makeNode(), b = harness.makeNode(), c = harness.makeNode(), d = harness.makeNode(); + Node a = harness.makeNode(), b = harness.makeNode(), c = harness.makeNode(), + d = harness.makeNode(); c.untrust(); // first round a,b,c agree, d has is partial @@ -520,8 +537,8 @@ class Validations_test : public beast::unit_test::suite LedgerHistoryHelper h; TestHarness harness(h.oracle); - Node a = harness.makeNode(), b = harness.makeNode(), c = harness.makeNode(), d = harness.makeNode(), - e = harness.makeNode(); + Node a = harness.makeNode(), b = harness.makeNode(), c = harness.makeNode(), + d = harness.makeNode(), e = harness.makeNode(); c.untrust(); // Mix of load fees @@ -546,7 +563,9 @@ class Validations_test : public beast::unit_test::suite auto const& expectedValidations = it.second; BEAST_EXPECT(harness.vals().numTrustedForLedger(id) == expectedValidations.size()); - BEAST_EXPECT(sorted(harness.vals().getTrustedForLedger(id, seq)) == sorted(expectedValidations)); + BEAST_EXPECT( + sorted(harness.vals().getTrustedForLedger(id, seq)) == + sorted(expectedValidations)); std::uint32_t baseFee = 0; std::vector expectedFees; @@ -641,7 +660,8 @@ class Validations_test : public beast::unit_test::suite // change toKeep harness.vals().setSeqToKeep(ledgerB.seq() + one, ledgerB.seq() + two); // advance clock slowly - int const loops = harness.parms().validationSET_EXPIRES / harness.parms().validationFRESHNESS + 1; + int const loops = + harness.parms().validationSET_EXPIRES / harness.parms().validationFRESHNESS + 1; for (int i = 0; i < loops; ++i) { harness.clock().advance(harness.parms().validationFRESHNESS); @@ -698,7 +718,8 @@ class Validations_test : public beast::unit_test::suite LedgerHistoryHelper h; TestHarness harness(h.oracle); - Node a = harness.makeNode(), b = harness.makeNode(), c = harness.makeNode(), d = harness.makeNode(); + Node a = harness.makeNode(), b = harness.makeNode(), c = harness.makeNode(), + d = harness.makeNode(); c.untrust(); Ledger ledgerA = h["a"]; @@ -841,20 +862,26 @@ class Validations_test : public beast::unit_test::suite Validation val2 = a.validate(ID{4}, Seq{4}, 0s, 0s, true); BEAST_EXPECT(ValStatus::current == harness.add(val2)); BEAST_EXPECT(harness.vals().numTrustedForLedger(ID{4}) == 1); - BEAST_EXPECT(harness.vals().getPreferred(genesisLedger) == std::make_pair(ledgerAB.seq(), ledgerAB.id())); + BEAST_EXPECT( + harness.vals().getPreferred(genesisLedger) == + std::make_pair(ledgerAB.seq(), ledgerAB.id())); // Another node requesting that ledger still doesn't change things Validation val3 = b.validate(ID{4}, Seq{4}, 0s, 0s, true); BEAST_EXPECT(ValStatus::current == harness.add(val3)); BEAST_EXPECT(harness.vals().numTrustedForLedger(ID{4}) == 2); - BEAST_EXPECT(harness.vals().getPreferred(genesisLedger) == std::make_pair(ledgerAB.seq(), ledgerAB.id())); + BEAST_EXPECT( + harness.vals().getPreferred(genesisLedger) == + std::make_pair(ledgerAB.seq(), ledgerAB.id())); // Switch to validation that is available harness.clock().advance(5s); Ledger ledgerABCDE = h["abcde"]; BEAST_EXPECT(ValStatus::current == harness.add(a.partial(ledgerABCDE))); BEAST_EXPECT(ValStatus::current == harness.add(b.partial(ledgerABCDE))); - BEAST_EXPECT(harness.vals().getPreferred(genesisLedger) == std::make_pair(ledgerABCDE.seq(), ledgerABCDE.id())); + BEAST_EXPECT( + harness.vals().getPreferred(genesisLedger) == + std::make_pair(ledgerABCDE.seq(), ledgerABCDE.id())); } void @@ -902,20 +929,25 @@ class Validations_test : public beast::unit_test::suite testcase("TrustChanged"); using namespace std::chrono; - auto checker = - [this](TestValidations& vals, hash_set const& listed, std::vector const& trustedVals) { - Ledger::ID testID = trustedVals.empty() ? this->genesisLedger.id() : trustedVals[0].ledgerID(); - Ledger::Seq testSeq = trustedVals.empty() ? this->genesisLedger.seq() : trustedVals[0].seq(); - BEAST_EXPECT(vals.currentTrusted() == trustedVals); - BEAST_EXPECT(vals.getCurrentNodeIDs() == listed); - BEAST_EXPECT(vals.getNodesAfter(this->genesisLedger, genesisLedger.id()) == trustedVals.size()); - if (trustedVals.empty()) - BEAST_EXPECT(vals.getPreferred(this->genesisLedger) == std::nullopt); - else - BEAST_EXPECT(vals.getPreferred(this->genesisLedger)->second == testID); - BEAST_EXPECT(vals.getTrustedForLedger(testID, testSeq) == trustedVals); - BEAST_EXPECT(vals.numTrustedForLedger(testID) == trustedVals.size()); - }; + auto checker = [this]( + TestValidations& vals, + hash_set const& listed, + std::vector const& trustedVals) { + Ledger::ID testID = + trustedVals.empty() ? this->genesisLedger.id() : trustedVals[0].ledgerID(); + Ledger::Seq testSeq = + trustedVals.empty() ? this->genesisLedger.seq() : trustedVals[0].seq(); + BEAST_EXPECT(vals.currentTrusted() == trustedVals); + BEAST_EXPECT(vals.getCurrentNodeIDs() == listed); + BEAST_EXPECT( + vals.getNodesAfter(this->genesisLedger, genesisLedger.id()) == trustedVals.size()); + if (trustedVals.empty()) + BEAST_EXPECT(vals.getPreferred(this->genesisLedger) == std::nullopt); + else + BEAST_EXPECT(vals.getPreferred(this->genesisLedger)->second == testID); + BEAST_EXPECT(vals.getTrustedForLedger(testID, testSeq) == trustedVals); + BEAST_EXPECT(vals.numTrustedForLedger(testID) == trustedVals.size()); + }; { // Trusted to untrusted diff --git a/src/test/core/ClosureCounter_test.cpp b/src/test/core/ClosureCounter_test.cpp index f5e9dc7880..5cce837fb0 100644 --- a/src/test/core/ClosureCounter_test.cpp +++ b/src/test/core/ClosureCounter_test.cpp @@ -106,12 +106,14 @@ class ClosureCounter_test : public beast::unit_test::suite } // Copy constructor - TrackedString(TrackedString const& rhs) : copies(rhs.copies + 1), moves(rhs.moves), str(rhs.str) + TrackedString(TrackedString const& rhs) + : copies(rhs.copies + 1), moves(rhs.moves), str(rhs.str) { } // Move constructor - TrackedString(TrackedString&& rhs) noexcept : copies(rhs.copies), moves(rhs.moves + 1), str(std::move(rhs.str)) + TrackedString(TrackedString&& rhs) noexcept + : copies(rhs.copies), moves(rhs.moves + 1), str(std::move(rhs.str)) { } diff --git a/src/test/core/Config_test.cpp b/src/test/core/Config_test.cpp index d5f3bb556c..0ce457ec89 100644 --- a/src/test/core/Config_test.cpp +++ b/src/test/core/Config_test.cpp @@ -101,7 +101,8 @@ backend=sqlite )xrpldConfig"); std::string dbPathSection = dbPath.empty() ? "" : "[database_path]\n" + dbPath; - std::string valFileSection = validatorsFile.empty() ? "" : "[validators_file]\n" + validatorsFile; + std::string valFileSection = + validatorsFile.empty() ? "" : "[validators_file]\n" + validatorsFile; return boost::str(configContentsTemplate % dbPathSection % valFileSection); } @@ -130,7 +131,8 @@ public: test, std::move(subDir), configFile, - confContents.empty() ? configContents(dbPath.string(), validatorsFile.string()) : confContents, + confContents.empty() ? configContents(dbPath.string(), validatorsFile.string()) + : confContents, useCounter) , dataDir_(dbPath) { @@ -312,7 +314,9 @@ port_wss_admin Config c; c.setup("", true, false, true); BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values().size() == 1); - BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values()[0] == "/Users/dummy/xrpld/config/log/debug.log"); + BEAST_EXPECT( + c.section(SECTION_DEBUG_LOGFILE).values()[0] == + "/Users/dummy/xrpld/config/log/debug.log"); } // Config file in HOME or XDG_CONFIG_HOME directory. @@ -349,7 +353,9 @@ port_wss_admin Config c; c.setup("", true, false, true); BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values().size() == 1); - BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values()[0] == "/Users/dummy/xrpld/config/log/debug.log"); + BEAST_EXPECT( + c.section(SECTION_DEBUG_LOGFILE).values()[0] == + "/Users/dummy/xrpld/config/log/debug.log"); // Restore the environment variables. h ? setenv("HOME", h, 1) : unsetenv("HOME"); @@ -383,7 +389,9 @@ port_wss_admin Config c; c.setup("", true, false, true); BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values().size() == 1); - BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values()[0] == "/Users/dummy/xrpld/config/log/debug.log"); + BEAST_EXPECT( + c.section(SECTION_DEBUG_LOGFILE).values()[0] == + "/Users/dummy/xrpld/config/log/debug.log"); // Restore the environment variables. h ? setenv("HOME", h, 1) : unsetenv("HOME"); @@ -435,7 +443,8 @@ port_wss_admin detail::DirGuard const g0(*this, "test_db"); path const dataDirRel("test_data_dir"); path const dataDirAbs(cwd / g0.subdir() / dataDirRel); - detail::FileCfgGuard const g(*this, g0.subdir(), dataDirAbs, Config::configFileName, "", false); + detail::FileCfgGuard const g( + *this, g0.subdir(), dataDirAbs, Config::configFileName, "", false); auto const& c(g.config()); BEAST_EXPECT(g.dataDirExists()); BEAST_EXPECT(g.configFileExists()); @@ -455,7 +464,8 @@ port_wss_admin // read from file no path detail::FileCfgGuard const g(*this, "test_db", "", Config::configFileName, ""); auto const& c(g.config()); - std::string const nativeDbPath = absolute(g.subdir() / path(Config::databaseDirName)).string(); + std::string const nativeDbPath = + absolute(g.subdir() / path(Config::databaseDirName)).string(); BEAST_EXPECT(g.dataDirExists()); BEAST_EXPECT(g.configFileExists()); BEAST_EXPECT(c.legacy("database_path") == nativeDbPath); @@ -581,7 +591,8 @@ main boost::format cc("[validators_file]\n%1%\n"); std::string error; std::string const missingPath = "/no/way/this/path/exists"; - auto const expectedError = "The file specified in [validators_file] does not exist: " + missingPath; + auto const expectedError = + "The file specified in [validators_file] does not exist: " + missingPath; try { Config c; @@ -599,7 +610,8 @@ main path const invalidFile = current_path() / vtg.subdir(); boost::format cc("[validators_file]\n%1%\n"); std::string error; - auto const expectedError = "Invalid file specified in [validators_file]: " + invalidFile.string(); + auto const expectedError = + "Invalid file specified in [validators_file]: " + invalidFile.string(); try { Config c; @@ -645,8 +657,11 @@ trust-these-validators.gov )xrpldConfig"); c.loadFromString(toLoad); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values()[0] == "xrpl-validators.com"); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values()[1] == "trust-these-validators.gov"); + BEAST_EXPECT( + c.section(SECTION_VALIDATOR_LIST_SITES).values()[0] == "xrpl-validators.com"); + BEAST_EXPECT( + c.section(SECTION_VALIDATOR_LIST_SITES).values()[1] == + "trust-these-validators.gov"); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 1); BEAST_EXPECT( c.section(SECTION_VALIDATOR_LIST_KEYS).values()[0] == @@ -672,8 +687,11 @@ trust-these-validators.gov )xrpldConfig"); c.loadFromString(toLoad); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values()[0] == "xrpl-validators.com"); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values()[1] == "trust-these-validators.gov"); + BEAST_EXPECT( + c.section(SECTION_VALIDATOR_LIST_SITES).values()[0] == "xrpl-validators.com"); + BEAST_EXPECT( + c.section(SECTION_VALIDATOR_LIST_SITES).values()[1] == + "trust-these-validators.gov"); BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 1); BEAST_EXPECT( c.section(SECTION_VALIDATOR_LIST_KEYS).values()[0] == @@ -809,7 +827,8 @@ trust-these-validators.gov // in config directory std::string const valFileName = "validators.txt"; detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", valFileName); - detail::FileCfgGuard const rcg(*this, vtg.subdir(), "", Config::configFileName, valFileName, false); + detail::FileCfgGuard const rcg( + *this, vtg.subdir(), "", Config::configFileName, valFileName, false); BEAST_EXPECT(vtg.validatorsFileExists()); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); @@ -825,7 +844,8 @@ trust-these-validators.gov // to config directory detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.txt"); auto const valFilePath = ".." / vtg.subdir() / "validators.txt"; - detail::FileCfgGuard const rcg(*this, vtg.subdir(), "", Config::configFileName, valFilePath, false); + detail::FileCfgGuard const rcg( + *this, vtg.subdir(), "", Config::configFileName, valFilePath, false); BEAST_EXPECT(vtg.validatorsFileExists()); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); @@ -839,7 +859,8 @@ trust-these-validators.gov { // load from validators file in default location detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.txt"); - detail::FileCfgGuard const rcg(*this, vtg.subdir(), "", Config::configFileName, "", false); + detail::FileCfgGuard const rcg( + *this, vtg.subdir(), "", Config::configFileName, "", false); BEAST_EXPECT(vtg.validatorsFileExists()); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); @@ -855,7 +876,8 @@ trust-these-validators.gov // of default location detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.cfg"); BEAST_EXPECT(vtg.validatorsFileExists()); - detail::ValidatorsTxtGuard const vtgDefault(*this, vtg.subdir(), "validators.txt", false); + detail::ValidatorsTxtGuard const vtgDefault( + *this, vtg.subdir(), "validators.txt", false); BEAST_EXPECT(vtgDefault.validatorsFileExists()); detail::FileCfgGuard const rcg( *this, vtg.subdir(), "", Config::configFileName, vtg.validatorsFile(), false); @@ -963,7 +985,8 @@ trust-these-validators.gov void testSetup(bool explicitPath) { - detail::FileCfgGuard const cfg(*this, "testSetup", explicitPath ? "test_db" : "", Config::configFileName, ""); + detail::FileCfgGuard const cfg( + *this, "testSetup", explicitPath ? "test_db" : "", Config::configFileName, ""); /* FileCfgGuard has a Config object that gets loaded on construction, but Config::setup is not reentrant, so we need a fresh config for every test case, so ignore it. @@ -1096,17 +1119,19 @@ trust-these-validators.gov void testZeroPort() { - auto const contents = - std::regex_replace(detail::configContents("", ""), std::regex("port\\s*=\\s*\\d+"), "port = 0"); + auto const contents = std::regex_replace( + detail::configContents("", ""), std::regex("port\\s*=\\s*\\d+"), "port = 0"); try { - detail::FileCfgGuard const cfg(*this, "testPort", "", Config::configFileName, "", true, contents); + detail::FileCfgGuard const cfg( + *this, "testPort", "", Config::configFileName, "", true, contents); BEAST_EXPECT(false); } catch (std::exception const& ex) { - BEAST_EXPECT(std::string_view(ex.what()).starts_with("Invalid value '0' for key 'port'")); + BEAST_EXPECT( + std::string_view(ex.what()).starts_with("Invalid value '0' for key 'port'")); } } @@ -1116,23 +1141,24 @@ trust-these-validators.gov Config cfg; /* NOTE: this string includes some explicit * space chars in order to verify proper trimming */ - std::string toLoad(R"( + std::string toLoad( + R"( [port_rpc])" - "\x20" - R"( + "\x20" + R"( # comment # indented comment )" - "\x20\x20" - R"( + "\x20\x20" + R"( [ips])" - "\x20" - R"( + "\x20" + R"( r.ripple.com 51235 [ips_fixed])" - "\x20\x20" - R"( + "\x20\x20" + R"( # COMMENT s1.ripple.com 51235 s2.ripple.com 51235 @@ -1156,23 +1182,24 @@ r.ripple.com 51235 Config cfg; /* NOTE: this string includes some explicit * space chars in order to verify proper trimming */ - std::string toLoad(R"( + std::string toLoad( + R"( [port_rpc])" - "\x20" - R"( + "\x20" + R"( # comment # indented comment )" - "\x20\x20" - R"( + "\x20\x20" + R"( [ips])" - "\x20" - R"( + "\x20" + R"( r.ripple.com:51235 [ips_fixed])" - "\x20\x20" - R"( + "\x20\x20" + R"( # COMMENT s1.ripple.com:51235 s2.ripple.com 51235 diff --git a/src/test/core/JobQueue_test.cpp b/src/test/core/JobQueue_test.cpp index 0eee9ce6f2..8289e305a0 100644 --- a/src/test/core/JobQueue_test.cpp +++ b/src/test/core/JobQueue_test.cpp @@ -19,7 +19,8 @@ class JobQueue_test : public beast::unit_test::suite { // addJob() should run the Job (and return true). std::atomic jobRan{false}; - BEAST_EXPECT(jQueue.addJob(jtCLIENT, "JobAddTest1", [&jobRan]() { jobRan = true; }) == true); + BEAST_EXPECT( + jQueue.addJob(jtCLIENT, "JobAddTest1", [&jobRan]() { jobRan = true; }) == true); // Wait for the Job to run. while (jobRan == false) @@ -36,7 +37,9 @@ class JobQueue_test : public beast::unit_test::suite // unprotected variable on the stack should be completely safe. // Not recommended for the faint of heart... bool unprotected; - BEAST_EXPECT(jQueue.addJob(jtCLIENT, "JobAddTest2", [&unprotected]() { unprotected = false; }) == false); + BEAST_EXPECT(jQueue.addJob(jtCLIENT, "JobAddTest2", [&unprotected]() { + unprotected = false; + }) == false); } } @@ -50,7 +53,9 @@ class JobQueue_test : public beast::unit_test::suite // Test repeated post()s until the Coro completes. std::atomic yieldCount{0}; auto const coro = jQueue.postCoro( - jtCLIENT, "PostCoroTest1", [&yieldCount](std::shared_ptr const& coroCopy) { + jtCLIENT, + "PostCoroTest1", + [&yieldCount](std::shared_ptr const& coroCopy) { while (++yieldCount < 4) coroCopy->yield(); }); @@ -77,7 +82,9 @@ class JobQueue_test : public beast::unit_test::suite // Test repeated resume()s until the Coro completes. int yieldCount{0}; auto const coro = jQueue.postCoro( - jtCLIENT, "PostCoroTest2", [&yieldCount](std::shared_ptr const& coroCopy) { + jtCLIENT, + "PostCoroTest2", + [&yieldCount](std::shared_ptr const& coroCopy) { while (++yieldCount < 4) coroCopy->yield(); }); @@ -112,8 +119,8 @@ class JobQueue_test : public beast::unit_test::suite // unprotected variable on the stack should be completely safe. // Not recommended for the faint of heart... bool unprotected; - auto const coro = - jQueue.postCoro(jtCLIENT, "PostCoroTest3", [&unprotected](std::shared_ptr const&) { + auto const coro = jQueue.postCoro( + jtCLIENT, "PostCoroTest3", [&unprotected](std::shared_ptr const&) { unprotected = false; }); BEAST_EXPECT(coro == nullptr); diff --git a/src/test/core/SociDB_test.cpp b/src/test/core/SociDB_test.cpp index fe73d42b0a..a06193ae86 100644 --- a/src/test/core/SociDB_test.cpp +++ b/src/test/core/SociDB_test.cpp @@ -80,7 +80,10 @@ public: BasicConfig c; setupSQLiteConfig(c, getDatabasePath()); std::vector> const d( - {{"peerfinder", ".sqlite"}, {"state", ".db"}, {"random", ".db"}, {"validators", ".sqlite"}}); + {{"peerfinder", ".sqlite"}, + {"state", ".db"}, + {"random", ".db"}, + {"validators", ".sqlite"}}); for (auto const& i : d) { @@ -101,13 +104,17 @@ public: // Check values in db std::vector stringResult(20 * stringData.size()); std::vector intResult(20 * intData.size()); - s << "SELECT StringData, IntData FROM SociTestTable;", soci::into(stringResult), soci::into(intResult); - BEAST_EXPECT(stringResult.size() == stringData.size() && intResult.size() == intData.size()); + s << "SELECT StringData, IntData FROM SociTestTable;", soci::into(stringResult), + soci::into(intResult); + BEAST_EXPECT( + stringResult.size() == stringData.size() && intResult.size() == intData.size()); for (int i = 0; i < stringResult.size(); ++i) { - auto si = - std::distance(stringData.begin(), std::find(stringData.begin(), stringData.end(), stringResult[i])); - auto ii = std::distance(intData.begin(), std::find(intData.begin(), intData.end(), intResult[i])); + auto si = std::distance( + stringData.begin(), + std::find(stringData.begin(), stringData.end(), stringResult[i])); + auto ii = std::distance( + intData.begin(), std::find(intData.begin(), intData.end(), intResult[i])); BEAST_EXPECT(si == ii && si < stringResult.size()); } }; @@ -148,7 +155,8 @@ public: BasicConfig c; setupSQLiteConfig(c, getDatabasePath()); DBConfig sc(c, "SociTestDB"); - std::vector const ubid({(std::uint64_t)std::numeric_limits::max(), 20, 30}); + std::vector const ubid( + {(std::uint64_t)std::numeric_limits::max(), 20, 30}); std::vector const bid({-10, -20, -30}); std::vector const uid({std::numeric_limits::max(), 2, 3}); std::vector const id({-1, -2, -3}); @@ -176,8 +184,8 @@ public: std::uint32_t uig = 0; std::int64_t big = 0; std::uint64_t ubig = 0; - s << "SELECT I, UI, BI, UBI from STT;", soci::into(ig), soci::into(uig), soci::into(big), - soci::into(ubig); + s << "SELECT I, UI, BI, UBI from STT;", soci::into(ig), soci::into(uig), + soci::into(big), soci::into(ubig); BEAST_EXPECT(ig == id[0] && uig == uid[0] && big == bid[0] && ubig == ubid[0]); } catch (std::exception&) @@ -194,8 +202,8 @@ public: uint32_t uig = 0; boost::optional big; boost::optional ubig; - s << "SELECT I, UI, BI, UBI from STT;", soci::into(ig), soci::into(uig), soci::into(big), - soci::into(ubig); + s << "SELECT I, UI, BI, UBI from STT;", soci::into(ig), soci::into(uig), + soci::into(big), soci::into(ubig); BEAST_EXPECT(*ig == id[0] && uig == uid[0] && *big == bid[0] && *ubig == ubid[0]); } catch (std::exception&) diff --git a/src/test/core/Workers_test.cpp b/src/test/core/Workers_test.cpp index 1f1c16b12b..65245b8c94 100644 --- a/src/test/core/Workers_test.cpp +++ b/src/test/core/Workers_test.cpp @@ -101,7 +101,9 @@ public: void testThreads(int const tc1, int const tc2, int const tc3) { - testcase("threadCounts: " + std::to_string(tc1) + " -> " + std::to_string(tc2) + " -> " + std::to_string(tc3)); + testcase( + "threadCounts: " + std::to_string(tc1) + " -> " + std::to_string(tc2) + " -> " + + std::to_string(tc3)); TestCallback cb; std::unique_ptr perfLog = std::make_unique(); diff --git a/src/test/csf/BasicNetwork_test.cpp b/src/test/csf/BasicNetwork_test.cpp index d66f5c9891..eaef805f33 100644 --- a/src/test/csf/BasicNetwork_test.cpp +++ b/src/test/csf/BasicNetwork_test.cpp @@ -33,7 +33,8 @@ public: if (id == 0) { for (auto const link : net.links(this)) - net.send(this, link.target, [&, to = link.target] { to->receive(net, this, 1); }); + net.send( + this, link.target, [&, to = link.target] { to->receive(net, this, 1); }); } else { @@ -50,7 +51,9 @@ public: if (m < 5) { for (auto const link : net.links(this)) - net.send(this, link.target, [&, mm = m, to = link.target] { to->receive(net, this, mm); }); + net.send(this, link.target, [&, mm = m, to = link.target] { + to->receive(net, this, mm); + }); } } }; diff --git a/src/test/csf/Digraph.h b/src/test/csf/Digraph.h index 672445ca95..66ef73390a 100644 --- a/src/test/csf/Digraph.h +++ b/src/test/csf/Digraph.h @@ -128,7 +128,8 @@ public: auto outVertices() const { - return boost::adaptors::transform(graph_, [](typename Graph::value_type const& v) { return v.first; }); + return boost::adaptors::transform( + graph_, [](typename Graph::value_type const& v) { return v.first; }); } /** Range over target vertices diff --git a/src/test/csf/Peer.h b/src/test/csf/Peer.h index 7b19c977d6..c36d600e6c 100644 --- a/src/test/csf/Peer.h +++ b/src/test/csf/Peer.h @@ -489,7 +489,9 @@ struct Peer issue(CloseLedger{prevLedger, openTxs}); return Result( - TxSet{openTxs}, Proposal(prevLedger.id(), Proposal::seqJoin, TxSet::calcID(openTxs), closeTime, now(), id)); + TxSet{openTxs}, + Proposal( + prevLedger.id(), Proposal::seqJoin, TxSet::calcID(openTxs), closeTime, now(), id)); } void @@ -501,7 +503,14 @@ struct Peer ConsensusMode const& mode, Json::Value&& consensusJson) { - onAccept(result, prevLedger, closeResolution, rawCloseTimes, mode, std::move(consensusJson), validating()); + onAccept( + result, + prevLedger, + closeResolution, + rawCloseTimes, + mode, + std::move(consensusJson), + validating()); } void @@ -519,8 +528,8 @@ struct Peer bool const consensusFail = result.state == ConsensusState::MovedOn; TxSet const acceptedTxs = injectTxs(prevLedger, result.txns); - Ledger const newLedger = - oracle.accept(prevLedger, acceptedTxs.txs(), closeResolution, result.position.closeTime()); + Ledger const newLedger = oracle.accept( + prevLedger, acceptedTxs.txs(), closeResolution, result.position.closeTime()); ledgers[newLedger.id()] = newLedger; issue(AcceptLedger{newLedger, lastClosedLedger}); @@ -528,8 +537,9 @@ struct Peer prevRoundTime = result.roundTime.read(); lastClosedLedger = newLedger; - auto const it = std::remove_if( - openTxs.begin(), openTxs.end(), [&](Tx const& tx) { return acceptedTxs.exists(tx.id()); }); + auto const it = std::remove_if(openTxs.begin(), openTxs.end(), [&](Tx const& tx) { + return acceptedTxs.exists(tx.id()); + }); openTxs.erase(it, openTxs.end()); // Only send validation if the new ledger is compatible with our @@ -537,7 +547,8 @@ struct Peer bool const isCompatible = newLedger.isAncestor(fullyValidatedLedger); // Can only send one validated ledger per seq - if (runAsValidator && isCompatible && !consensusFail && validations.canValidateSeq(newLedger.seq())) + if (runAsValidator && isCompatible && !consensusFail && + validations.canValidateSeq(newLedger.seq())) { bool isFull = proposing; @@ -709,7 +720,9 @@ struct Peer if (link.target->router.lastObservedSeq[bm.origin] < bm.seq) { issue(Relay{link.target->id, bm.msg}); - net.send(this, link.target, [to = link.target, bm, id = this->id] { to->receive(bm, id); }); + net.send(this, link.target, [to = link.target, bm, id = this->id] { + to->receive(bm, id); + }); } } } @@ -892,7 +905,8 @@ struct Peer using namespace std::chrono; using namespace std::chrono_literals; return NetClock::time_point( - duration_cast(scheduler.now().time_since_epoch() + 86400s + clockSkew)); + duration_cast( + scheduler.now().time_since_epoch() + 86400s + clockSkew)); } Ledger::ID diff --git a/src/test/csf/PeerGroup.h b/src/test/csf/PeerGroup.h index ce7325f659..e900ab9934 100644 --- a/src/test/csf/PeerGroup.h +++ b/src/test/csf/PeerGroup.h @@ -85,7 +85,9 @@ public: bool contains(PeerID id) { - return std::find_if(peers_.begin(), peers_.end(), [id](Peer const* p) { return p->id == id; }) != peers_.end(); + return std::find_if(peers_.begin(), peers_.end(), [id](Peer const* p) { + return p->id == id; + }) != peers_.end(); } std::size_t @@ -214,7 +216,11 @@ public: { PeerGroup res; std::set_union( - a.peers_.begin(), a.peers_.end(), b.peers_.begin(), b.peers_.end(), std::back_inserter(res.peers_)); + a.peers_.begin(), + a.peers_.end(), + b.peers_.begin(), + b.peers_.end(), + std::back_inserter(res.peers_)); return res; } @@ -225,7 +231,11 @@ public: PeerGroup res; std::set_difference( - a.peers_.begin(), a.peers_.end(), b.peers_.begin(), b.peers_.end(), std::back_inserter(res.peers_)); + a.peers_.begin(), + a.peers_.end(), + b.peers_.begin(), + b.peers_.end(), + std::back_inserter(res.peers_)); return res; } diff --git a/src/test/csf/Scheduler.h b/src/test/csf/Scheduler.h index 2f7535ef16..61ec8f62ff 100644 --- a/src/test/csf/Scheduler.h +++ b/src/test/csf/Scheduler.h @@ -34,7 +34,8 @@ public: using time_point = typename clock_type::time_point; private: - using by_when_hook = boost::intrusive::set_base_hook>; + using by_when_hook = + boost::intrusive::set_base_hook>; struct event : by_when_hook { @@ -73,7 +74,8 @@ private: operator=(event_impl const&) = delete; template - event_impl(time_point when_, DeducedHandler&& h) : event(when_), h_(std::forward(h)) + event_impl(time_point when_, DeducedHandler&& h) + : event(when_), h_(std::forward(h)) { } @@ -87,8 +89,8 @@ private: class queue_type { private: - using by_when_set = - typename boost::intrusive::make_multiset>::type; + using by_when_set = typename boost::intrusive:: + make_multiset>::type; // alloc_ is owned by the scheduler boost::container::pmr::monotonic_buffer_resource* alloc_; by_when_set by_when_; @@ -251,7 +253,8 @@ public: //------------------------------------------------------------------------------ -inline Scheduler::queue_type::queue_type(boost::container::pmr::monotonic_buffer_resource* alloc) : alloc_(alloc) +inline Scheduler::queue_type::queue_type(boost::container::pmr::monotonic_buffer_resource* alloc) + : alloc_(alloc) { } diff --git a/src/test/csf/Sim.h b/src/test/csf/Sim.h index 709226b216..3525258c59 100644 --- a/src/test/csf/Sim.h +++ b/src/test/csf/Sim.h @@ -23,7 +23,8 @@ class BasicSink : public beast::Journal::Sink Scheduler::clock_type const& clock_; public: - BasicSink(Scheduler::clock_type const& clock) : Sink(beast::severities::kDisabled, false), clock_{clock} + BasicSink(Scheduler::clock_type const& clock) + : Sink(beast::severities::kDisabled, false), clock_{clock} { } @@ -89,7 +90,13 @@ public: for (std::size_t i = 0; i < numPeers; ++i) { peers.emplace_back( - PeerID{static_cast(peers.size())}, scheduler, oracle, net, trustGraph, collectors, j); + PeerID{static_cast(peers.size())}, + scheduler, + oracle, + net, + trustGraph, + collectors, + j); newPeers.emplace_back(&peers.back()); } PeerGroup res{newPeers}; diff --git a/src/test/csf/TrustGraph.h b/src/test/csf/TrustGraph.h index d25925ad38..bae0be4af7 100644 --- a/src/test/csf/TrustGraph.h +++ b/src/test/csf/TrustGraph.h @@ -124,8 +124,8 @@ public: auto const& unlB = uniqueUNLs[j]; double rhs = 2.0 * (1. - quorum) * std::max(unlA.size(), unlB.size()); - int intersectionSize = - std::count_if(unlA.begin(), unlA.end(), [&](Peer p) { return unlB.find(p) != unlB.end(); }); + int intersectionSize = std::count_if( + unlA.begin(), unlA.end(), [&](Peer p) { return unlB.find(p) != unlB.end(); }); if (intersectionSize < rhs) { diff --git a/src/test/csf/Tx.h b/src/test/csf/Tx.h index 20c90cbac5..f919b650db 100644 --- a/src/test/csf/Tx.h +++ b/src/test/csf/Tx.h @@ -144,7 +144,11 @@ public: auto populate_diffs = [&res](auto const& a, auto const& b, bool s) { auto populator = [&](auto const& tx) { res[tx.id()] = s; }; std::set_difference( - a.begin(), a.end(), b.begin(), b.end(), boost::make_function_output_iterator(std::ref(populator))); + a.begin(), + a.end(), + b.begin(), + b.end(), + boost::make_function_output_iterator(std::ref(populator))); }; populate_diffs(txs_, other.txs_, true); diff --git a/src/test/csf/collectors.h b/src/test/csf/collectors.h index 20fc31a01f..cfe40330ff 100644 --- a/src/test/csf/collectors.h +++ b/src/test/csf/collectors.h @@ -229,14 +229,16 @@ struct TxCollector std::size_t orphaned() const { - return std::count_if(txs.begin(), txs.end(), [](auto const& it) { return !it.second.accepted; }); + return std::count_if( + txs.begin(), txs.end(), [](auto const& it) { return !it.second.accepted; }); } // Returns the number of txs which were never validated std::size_t unvalidated() const { - return std::count_if(txs.begin(), txs.end(), [](auto const& it) { return !it.second.validated; }); + return std::count_if( + txs.begin(), txs.end(), [](auto const& it) { return !it.second.validated; }); } template @@ -252,47 +254,49 @@ struct TxCollector if (printBreakline) { - log << std::setw(11) << std::setfill('-') << "-" << "-" << std::setw(7) << std::setfill('-') << "-" << "-" - << std::setw(7) << std::setfill('-') << "-" << "-" << std::setw(36) << std::setfill('-') << "-" - << std::endl; + log << std::setw(11) << std::setfill('-') << "-" << "-" << std::setw(7) + << std::setfill('-') << "-" << "-" << std::setw(7) << std::setfill('-') << "-" + << "-" << std::setw(36) << std::setfill('-') << "-" << std::endl; log << std::setfill(' '); } - log << std::left << std::setw(11) << "TxStats" << "|" << std::setw(7) << "Count" << "|" << std::setw(7) - << "Per Sec" << "|" << std::setw(15) << "Latency (sec)" << std::right << std::setw(7) << "10-ile" - << std::setw(7) << "50-ile" << std::setw(7) << "90-ile" << std::left << std::endl; + log << std::left << std::setw(11) << "TxStats" << "|" << std::setw(7) << "Count" << "|" + << std::setw(7) << "Per Sec" << "|" << std::setw(15) << "Latency (sec)" << std::right + << std::setw(7) << "10-ile" << std::setw(7) << "50-ile" << std::setw(7) << "90-ile" + << std::left << std::endl; - log << std::setw(11) << std::setfill('-') << "-" << "|" << std::setw(7) << std::setfill('-') << "-" << "|" - << std::setw(7) << std::setfill('-') << "-" << "|" << std::setw(36) << std::setfill('-') << "-" - << std::endl; + log << std::setw(11) << std::setfill('-') << "-" << "|" << std::setw(7) << std::setfill('-') + << "-" << "|" << std::setw(7) << std::setfill('-') << "-" << "|" << std::setw(36) + << std::setfill('-') << "-" << std::endl; log << std::setfill(' '); - log << std::left << std::setw(11) << "Submit " << "|" << std::right << std::setw(7) << submitted << "|" - << std::setw(7) << std::setprecision(2) << perSec(submitted) << "|" << std::setw(36) << "" << std::endl; + log << std::left << std::setw(11) << "Submit " << "|" << std::right << std::setw(7) + << submitted << "|" << std::setw(7) << std::setprecision(2) << perSec(submitted) << "|" + << std::setw(36) << "" << std::endl; - log << std::left << std::setw(11) << "Accept " << "|" << std::right << std::setw(7) << accepted << "|" - << std::setw(7) << std::setprecision(2) << perSec(accepted) << "|" << std::setw(15) << std::left - << "From Submit" << std::right << std::setw(7) << std::setprecision(2) - << fmtS(submitToAccept.percentile(0.1f)) << std::setw(7) << std::setprecision(2) - << fmtS(submitToAccept.percentile(0.5f)) << std::setw(7) << std::setprecision(2) - << fmtS(submitToAccept.percentile(0.9f)) << std::endl; + log << std::left << std::setw(11) << "Accept " << "|" << std::right << std::setw(7) + << accepted << "|" << std::setw(7) << std::setprecision(2) << perSec(accepted) << "|" + << std::setw(15) << std::left << "From Submit" << std::right << std::setw(7) + << std::setprecision(2) << fmtS(submitToAccept.percentile(0.1f)) << std::setw(7) + << std::setprecision(2) << fmtS(submitToAccept.percentile(0.5f)) << std::setw(7) + << std::setprecision(2) << fmtS(submitToAccept.percentile(0.9f)) << std::endl; - log << std::left << std::setw(11) << "Validate " << "|" << std::right << std::setw(7) << validated << "|" - << std::setw(7) << std::setprecision(2) << perSec(validated) << "|" << std::setw(15) << std::left - << "From Submit" << std::right << std::setw(7) << std::setprecision(2) - << fmtS(submitToValidate.percentile(0.1f)) << std::setw(7) << std::setprecision(2) - << fmtS(submitToValidate.percentile(0.5f)) << std::setw(7) << std::setprecision(2) - << fmtS(submitToValidate.percentile(0.9f)) << std::endl; + log << std::left << std::setw(11) << "Validate " << "|" << std::right << std::setw(7) + << validated << "|" << std::setw(7) << std::setprecision(2) << perSec(validated) << "|" + << std::setw(15) << std::left << "From Submit" << std::right << std::setw(7) + << std::setprecision(2) << fmtS(submitToValidate.percentile(0.1f)) << std::setw(7) + << std::setprecision(2) << fmtS(submitToValidate.percentile(0.5f)) << std::setw(7) + << std::setprecision(2) << fmtS(submitToValidate.percentile(0.9f)) << std::endl; - log << std::left << std::setw(11) << "Orphan" << "|" << std::right << std::setw(7) << orphaned() << "|" - << std::setw(7) << "" << "|" << std::setw(36) << std::endl; + log << std::left << std::setw(11) << "Orphan" << "|" << std::right << std::setw(7) + << orphaned() << "|" << std::setw(7) << "" << "|" << std::setw(36) << std::endl; - log << std::left << std::setw(11) << "Unvalidated" << "|" << std::right << std::setw(7) << unvalidated() << "|" - << std::setw(7) << "" << "|" << std::setw(43) << std::endl; + log << std::left << std::setw(11) << "Unvalidated" << "|" << std::right << std::setw(7) + << unvalidated() << "|" << std::setw(7) << "" << "|" << std::setw(43) << std::endl; - log << std::setw(11) << std::setfill('-') << "-" << "-" << std::setw(7) << std::setfill('-') << "-" << "-" - << std::setw(7) << std::setfill('-') << "-" << "-" << std::setw(36) << std::setfill('-') << "-" - << std::endl; + log << std::setw(11) << std::setfill('-') << "-" << "-" << std::setw(7) << std::setfill('-') + << "-" << "-" << std::setw(7) << std::setfill('-') << "-" << "-" << std::setw(36) + << std::setfill('-') << "-" << std::endl; log << std::setfill(' '); } @@ -453,8 +457,9 @@ struct LedgerCollector std::size_t unvalidated() const { - return std::count_if( - ledgers_.begin(), ledgers_.end(), [](auto const& it) { return !it.second.fullyValidated; }); + return std::count_if(ledgers_.begin(), ledgers_.end(), [](auto const& it) { + return !it.second.fullyValidated; + }); } template @@ -470,39 +475,40 @@ struct LedgerCollector if (printBreakline) { - log << std::setw(11) << std::setfill('-') << "-" << "-" << std::setw(7) << std::setfill('-') << "-" << "-" - << std::setw(7) << std::setfill('-') << "-" << "-" << std::setw(36) << std::setfill('-') << "-" - << std::endl; + log << std::setw(11) << std::setfill('-') << "-" << "-" << std::setw(7) + << std::setfill('-') << "-" << "-" << std::setw(7) << std::setfill('-') << "-" + << "-" << std::setw(36) << std::setfill('-') << "-" << std::endl; log << std::setfill(' '); } - log << std::left << std::setw(11) << "LedgerStats" << "|" << std::setw(7) << "Count" << "|" << std::setw(7) - << "Per Sec" - << "|" << std::setw(15) << "Latency (sec)" << std::right << std::setw(7) << "10-ile" << std::setw(7) - << "50-ile" << std::setw(7) << "90-ile" << std::left << std::endl; + log << std::left << std::setw(11) << "LedgerStats" << "|" << std::setw(7) << "Count" << "|" + << std::setw(7) << "Per Sec" + << "|" << std::setw(15) << "Latency (sec)" << std::right << std::setw(7) << "10-ile" + << std::setw(7) << "50-ile" << std::setw(7) << "90-ile" << std::left << std::endl; - log << std::setw(11) << std::setfill('-') << "-" << "|" << std::setw(7) << std::setfill('-') << "-" << "|" - << std::setw(7) << std::setfill('-') << "-" << "|" << std::setw(36) << std::setfill('-') << "-" - << std::endl; + log << std::setw(11) << std::setfill('-') << "-" << "|" << std::setw(7) << std::setfill('-') + << "-" << "|" << std::setw(7) << std::setfill('-') << "-" << "|" << std::setw(36) + << std::setfill('-') << "-" << std::endl; log << std::setfill(' '); - log << std::left << std::setw(11) << "Accept " << "|" << std::right << std::setw(7) << accepted << "|" - << std::setw(7) << std::setprecision(2) << perSec(accepted) << "|" << std::setw(15) << std::left - << "From Accept" << std::right << std::setw(7) << std::setprecision(2) - << fmtS(acceptToAccept.percentile(0.1f)) << std::setw(7) << std::setprecision(2) - << fmtS(acceptToAccept.percentile(0.5f)) << std::setw(7) << std::setprecision(2) - << fmtS(acceptToAccept.percentile(0.9f)) << std::endl; + log << std::left << std::setw(11) << "Accept " << "|" << std::right << std::setw(7) + << accepted << "|" << std::setw(7) << std::setprecision(2) << perSec(accepted) << "|" + << std::setw(15) << std::left << "From Accept" << std::right << std::setw(7) + << std::setprecision(2) << fmtS(acceptToAccept.percentile(0.1f)) << std::setw(7) + << std::setprecision(2) << fmtS(acceptToAccept.percentile(0.5f)) << std::setw(7) + << std::setprecision(2) << fmtS(acceptToAccept.percentile(0.9f)) << std::endl; - log << std::left << std::setw(11) << "Validate " << "|" << std::right << std::setw(7) << fullyValidated << "|" - << std::setw(7) << std::setprecision(2) << perSec(fullyValidated) << "|" << std::setw(15) << std::left - << "From Validate " << std::right << std::setw(7) << std::setprecision(2) + log << std::left << std::setw(11) << "Validate " << "|" << std::right << std::setw(7) + << fullyValidated << "|" << std::setw(7) << std::setprecision(2) + << perSec(fullyValidated) << "|" << std::setw(15) << std::left << "From Validate " + << std::right << std::setw(7) << std::setprecision(2) << fmtS(fullyValidToFullyValid.percentile(0.1f)) << std::setw(7) << std::setprecision(2) << fmtS(fullyValidToFullyValid.percentile(0.5f)) << std::setw(7) << std::setprecision(2) << fmtS(fullyValidToFullyValid.percentile(0.9f)) << std::endl; - log << std::setw(11) << std::setfill('-') << "-" << "-" << std::setw(7) << std::setfill('-') << "-" << "-" - << std::setw(7) << std::setfill('-') << "-" << "-" << std::setw(36) << std::setfill('-') << "-" - << std::endl; + log << std::setw(11) << std::setfill('-') << "-" << "-" << std::setw(7) << std::setfill('-') + << "-" << "-" << std::setw(7) << std::setfill('-') << "-" << "-" << std::setw(36) + << std::setfill('-') << "-" << std::endl; log << std::setfill(' '); } @@ -583,15 +589,15 @@ struct StreamCollector void on(PeerID who, SimTime when, AcceptLedger const& e) { - out << when.time_since_epoch().count() << ": Node " << who << " accepted " << "L" << e.ledger.id() << " " - << e.ledger.txs() << "\n"; + out << when.time_since_epoch().count() << ": Node " << who << " accepted " << "L" + << e.ledger.id() << " " << e.ledger.txs() << "\n"; } void on(PeerID who, SimTime when, FullyValidateLedger const& e) { - out << when.time_since_epoch().count() << ": Node " << who << " fully-validated " << "L" << e.ledger.id() << " " - << e.ledger.txs() << "\n"; + out << when.time_since_epoch().count() << ": Node " << who << " fully-validated " << "L" + << e.ledger.id() << " " << e.ledger.txs() << "\n"; } }; diff --git a/src/test/csf/ledgers.h b/src/test/csf/ledgers.h index d78c7c29fa..9da1c2182a 100644 --- a/src/test/csf/ledgers.h +++ b/src/test/csf/ledgers.h @@ -93,7 +93,14 @@ private: auto asTie() const { - return std::tie(seq, txs, closeTimeResolution, closeTime, closeTimeAgree, parentID, parentCloseTime); + return std::tie( + seq, + txs, + closeTimeResolution, + closeTime, + closeTimeAgree, + parentID, + parentCloseTime); } friend bool diff --git a/src/test/csf/submitters.h b/src/test/csf/submitters.h index 2300b91388..ae81b3e89c 100644 --- a/src/test/csf/submitters.h +++ b/src/test/csf/submitters.h @@ -79,7 +79,13 @@ class Submitter } public: - Submitter(Distribution dist, SimTime start, SimTime end, Selector& selector, Scheduler& s, Generator& g) + Submitter( + Distribution dist, + SimTime start, + SimTime end, + Selector& selector, + Scheduler& s, + Generator& g) : dist_{dist}, stop_{end}, selector_{selector}, scheduler_{s}, g_{g} { scheduler_.at(start, [&]() { submit(); }); @@ -88,7 +94,13 @@ public: template Submitter -makeSubmitter(Distribution dist, SimTime start, SimTime end, Selector& sel, Scheduler& s, Generator& g) +makeSubmitter( + Distribution dist, + SimTime start, + SimTime end, + Selector& sel, + Scheduler& s, + Generator& g) { return Submitter(dist, start, end, sel, s, g); } diff --git a/src/test/csf/timers.h b/src/test/csf/timers.h index a071844a41..c8d71d5b7a 100644 --- a/src/test/csf/timers.h +++ b/src/test/csf/timers.h @@ -25,7 +25,10 @@ class HeartbeatTimer SimTime startSimTime_; public: - HeartbeatTimer(Scheduler& sched, SimDuration interval = std::chrono::seconds{60}, std::ostream& out = std::cerr) + HeartbeatTimer( + Scheduler& sched, + SimDuration interval = std::chrono::seconds{60}, + std::ostream& out = std::cerr) : scheduler_{sched} , interval_{interval} , out_{out} diff --git a/src/test/jtx/AMM.h b/src/test/jtx/AMM.h index 4d8059d172..210138f290 100644 --- a/src/test/jtx/AMM.h +++ b/src/test/jtx/AMM.h @@ -141,7 +141,11 @@ public: ter const& ter, bool log = false, bool close = true); - AMM(Env& env, Account const& account, STAmount const& asset1, STAmount const& asset2, CreateArg const& arg); + AMM(Env& env, + Account const& account, + STAmount const& asset1, + STAmount const& asset2, + CreateArg const& arg); /** Send amm_info RPC command */ @@ -167,7 +171,10 @@ public: /** Get AMM balances for the token pair. */ std::tuple - balances(Issue const& issue1, Issue const& issue2, std::optional const& account = std::nullopt) const; + balances( + Issue const& issue1, + Issue const& issue2, + std::optional const& account = std::nullopt) const; std::tuple balances(std::optional const& account = std::nullopt) const @@ -184,7 +191,10 @@ public: * @param expectedPrice expected slot price */ [[nodiscard]] bool - expectAuctionSlot(std::uint32_t fee, std::optional timeSlot, IOUAmount expectedPrice) const; + expectAuctionSlot( + std::uint32_t fee, + std::optional timeSlot, + IOUAmount expectedPrice) const; [[nodiscard]] bool expectAuctionSlot(std::vector const& authAccount) const; @@ -252,7 +262,11 @@ public: std::optional const& ter = std::nullopt) { return withdraw( - account, std::nullopt, asset1OutDetails, asset1OutDetails ? tfOneAssetWithdrawAll : tfWithdrawAll, ter); + account, + std::nullopt, + asset1OutDetails, + asset1OutDetails ? tfOneAssetWithdrawAll : tfWithdrawAll, + ter); } IOUAmount @@ -383,11 +397,17 @@ private: } [[nodiscard]] bool - expectAmmInfo(STAmount const& asset1, STAmount const& asset2, IOUAmount const& balance, Json::Value const& jv) - const; + expectAmmInfo( + STAmount const& asset1, + STAmount const& asset2, + IOUAmount const& balance, + Json::Value const& jv) const; void - submit(Json::Value const& jv, std::optional const& seq, std::optional const& ter); + submit( + Json::Value const& jv, + std::optional const& seq, + std::optional const& ter); [[nodiscard]] bool expectAuctionSlot(auto&& cb) const; diff --git a/src/test/jtx/CaptureLogs.h b/src/test/jtx/CaptureLogs.h index f8d0449977..8419c4dc70 100644 --- a/src/test/jtx/CaptureLogs.h +++ b/src/test/jtx/CaptureLogs.h @@ -26,7 +26,10 @@ class CaptureLogs : public Logs std::stringstream& strm_; public: - CaptureSink(beast::severities::Severity threshold, std::mutex& mutex, std::stringstream& strm) + CaptureSink( + beast::severities::Severity threshold, + std::mutex& mutex, + std::stringstream& strm) : beast::Journal::Sink(threshold, false), strmMutex_(mutex), strm_(strm) { } diff --git a/src/test/jtx/Env.h b/src/test/jtx/Env.h index 7d7dcd2cb8..9caf257aa1 100644 --- a/src/test/jtx/Env.h +++ b/src/test/jtx/Env.h @@ -59,7 +59,8 @@ struct WithSourceLocation // Non-explicit constructor allows implicit conversion. // The default argument for loc is evaluated at the call site. - WithSourceLocation(T v, std::source_location l = std::source_location::current()) : value(std::move(v)), loc(l) + WithSourceLocation(T v, std::source_location l = std::source_location::current()) + : value(std::move(v)), loc(l) { } }; @@ -99,7 +100,8 @@ class SuiteLogs : public Logs beast::unit_test::suite& suite_; public: - explicit SuiteLogs(beast::unit_test::suite& suite) : Logs(beast::severities::kError), suite_(suite) + explicit SuiteLogs(beast::unit_test::suite& suite) + : Logs(beast::severities::kError), suite_(suite) { } @@ -190,7 +192,9 @@ public: { memoize(Account::master); Pathfinder::initPathTable(); - foreachFeature(features, [&appFeats = app().config().features](uint256 const& f) { appFeats.insert(f); }); + foreachFeature(features, [&appFeats = app().config().features](uint256 const& f) { + appFeats.insert(f); + }); } /** @@ -206,7 +210,9 @@ public: * @param args collection of features * */ - Env(beast::unit_test::suite& suite_, FeatureBitset features, std::unique_ptr logs = nullptr) + Env(beast::unit_test::suite& suite_, + FeatureBitset features, + std::unique_ptr logs = nullptr) : Env(suite_, envconfig(), features, std::move(logs)) { } @@ -240,7 +246,8 @@ public: * * @param suite_ the current unit_test::suite */ - Env(beast::unit_test::suite& suite_, beast::severities::Severity thresh = beast::severities::kError) + Env(beast::unit_test::suite& suite_, + beast::severities::Severity thresh = beast::severities::kError) : Env(suite_, envconfig(), nullptr, thresh) { } @@ -301,7 +308,9 @@ public: template Json::Value - rpc(std::unordered_map const& headers, std::string const& cmd, Args&&... args); + rpc(std::unordered_map const& headers, + std::string const& cmd, + Args&&... args); template Json::Value @@ -351,7 +360,9 @@ public: @return true if no error, false if error */ bool - close(NetClock::time_point closeTime, std::optional consensusDelay = std::nullopt); + close( + NetClock::time_point closeTime, + std::optional consensusDelay = std::nullopt); /** Close and advance the ledger. @@ -802,14 +813,24 @@ template Json::Value Env::rpc(unsigned apiVersion, std::string const& cmd, Args&&... args) { - return rpc(apiVersion, std::unordered_map(), cmd, std::forward(args)...); + return rpc( + apiVersion, + std::unordered_map(), + cmd, + std::forward(args)...); } template Json::Value -Env::rpc(std::unordered_map const& headers, std::string const& cmd, Args&&... args) +Env::rpc( + std::unordered_map const& headers, + std::string const& cmd, + Args&&... args) { - return do_rpc(RPC::apiCommandLineVersion, std::vector{cmd, std::forward(args)...}, headers); + return do_rpc( + RPC::apiCommandLineVersion, + std::vector{cmd, std::forward(args)...}, + headers); } template diff --git a/src/test/jtx/Env_ss.h b/src/test/jtx/Env_ss.h index 9c178a1c13..9db96d5907 100644 --- a/src/test/jtx/Env_ss.h +++ b/src/test/jtx/Env_ss.h @@ -23,7 +23,8 @@ private: SignSubmitRunner& operator=(SignSubmitRunner&&) = delete; - SignSubmitRunner(Env& env, JTx&& jt, std::source_location loc) : env_(env), jt_(jt), loc_(loc) + SignSubmitRunner(Env& env, JTx&& jt, std::source_location loc) + : env_(env), jt_(jt), loc_(loc) { } diff --git a/src/test/jtx/Env_test.cpp b/src/test/jtx/Env_test.cpp index 0f43691b86..6d151c27ce 100644 --- a/src/test/jtx/Env_test.cpp +++ b/src/test/jtx/Env_test.cpp @@ -1,6 +1,5 @@ #include -#include #include #include @@ -8,6 +7,7 @@ #include #include #include +#include #include @@ -415,7 +415,10 @@ public: env(noop("alice"), msig("bob"), fee(2 * baseFee)); env(noop("alice"), msig("carol"), fee(2 * baseFee)); env(noop("alice"), msig("bob", "carol"), fee(3 * baseFee)); - env(noop("alice"), msig("bob", "carol", "dilbert"), fee(4 * baseFee), ter(tefBAD_SIGNATURE)); + env(noop("alice"), + msig("bob", "carol", "dilbert"), + fee(4 * baseFee), + ter(tefBAD_SIGNATURE)); env(signers("alice", none)); } @@ -725,7 +728,8 @@ public: // default Env has all supported features Env env{*this}; BEAST_EXPECT(supported.count() == env.app().config().features.size()); - foreachFeature(supported, [&](uint256 const& f) { this->BEAST_EXPECT(hasFeature(env, f)); }); + foreachFeature( + supported, [&](uint256 const& f) { this->BEAST_EXPECT(hasFeature(env, f)); }); } { @@ -738,7 +742,8 @@ public: }); } - auto const missingSomeFeatures = testable_amendments() - featureDynamicMPT - featureTokenEscrow; + auto const missingSomeFeatures = + testable_amendments() - featureDynamicMPT - featureTokenEscrow; BEAST_EXPECT(missingSomeFeatures.count() == (supported.count() - 2)); { // a Env supported_features_except is missing *only* those features @@ -755,7 +760,8 @@ public: // along with a list of explicit amendments // the unsupported feature should be enabled along with // the two supported ones - Env env{*this, FeatureBitset{featureDynamicMPT, featureTokenEscrow, *neverSupportedFeat}}; + Env env{ + *this, FeatureBitset{featureDynamicMPT, featureTokenEscrow, *neverSupportedFeat}}; // this app will have just 2 supported amendments and // one additional never supported feature flag @@ -794,7 +800,8 @@ public: // one additional never supported feature flag BEAST_EXPECT(env.app().config().features.size() == (supported.count() + 1)); BEAST_EXPECT(hasFeature(env, *neverSupportedFeat)); - foreachFeature(supported, [&](uint256 const& f) { this->BEAST_EXPECT(hasFeature(env, f)); }); + foreachFeature( + supported, [&](uint256 const& f) { this->BEAST_EXPECT(hasFeature(env, f)); }); } } diff --git a/src/test/jtx/Oracle.h b/src/test/jtx/Oracle.h index da241c0ce8..8efd17802c 100644 --- a/src/test/jtx/Oracle.h +++ b/src/test/jtx/Oracle.h @@ -31,8 +31,9 @@ void toJsonHex(Json::Value& jv, AnyValue const& v); // base asset, quote asset, price, scale -using DataSeries = - std::vector, std::optional>>; +using DataSeries = std::vector< + std:: + tuple, std::optional>>; // Typical defaults for Create struct CreateArg diff --git a/src/test/jtx/PathSet.h b/src/test/jtx/PathSet.h index 3f30d7193f..a363f9dff9 100644 --- a/src/test/jtx/PathSet.h +++ b/src/test/jtx/PathSet.h @@ -11,7 +11,11 @@ namespace test { /** Count offer */ inline std::size_t -countOffers(jtx::Env& env, jtx::Account const& account, Issue const& takerPays, Issue const& takerGets) +countOffers( + jtx::Env& env, + jtx::Account const& account, + Issue const& takerPays, + Issue const& takerGets) { size_t count = 0; forEachItem(*env.current(), account, [&](std::shared_ptr const& sle) { @@ -23,7 +27,11 @@ countOffers(jtx::Env& env, jtx::Account const& account, Issue const& takerPays, } inline std::size_t -countOffers(jtx::Env& env, jtx::Account const& account, STAmount const& takerPays, STAmount const& takerGets) +countOffers( + jtx::Env& env, + jtx::Account const& account, + STAmount const& takerPays, + STAmount const& takerGets) { size_t count = 0; forEachItem(*env.current(), account, [&](std::shared_ptr const& sle) { @@ -37,7 +45,11 @@ countOffers(jtx::Env& env, jtx::Account const& account, STAmount const& takerPay /** An offer exists */ inline bool -isOffer(jtx::Env& env, jtx::Account const& account, STAmount const& takerPays, STAmount const& takerGets) +isOffer( + jtx::Env& env, + jtx::Account const& account, + STAmount const& takerPays, + STAmount const& takerGets) { return countOffers(env, account, takerPays, takerGets) > 0; } @@ -93,7 +105,11 @@ Path::push_back(STPathElement const& pe) inline Path& Path::push_back(Issue const& iss) { - path.emplace_back(STPathElement::typeCurrency | STPathElement::typeIssuer, beast::zero, iss.currency, iss.account); + path.emplace_back( + STPathElement::typeCurrency | STPathElement::typeIssuer, + beast::zero, + iss.currency, + iss.account); return *this; } diff --git a/src/test/jtx/SignerUtils.h b/src/test/jtx/SignerUtils.h index 37b1d85ec7..994868e4a2 100644 --- a/src/test/jtx/SignerUtils.h +++ b/src/test/jtx/SignerUtils.h @@ -40,7 +40,9 @@ struct Reg inline void sortSigners(std::vector& signers) { - std::sort(signers.begin(), signers.end(), [](Reg const& lhs, Reg const& rhs) { return lhs.acct < rhs.acct; }); + std::sort(signers.begin(), signers.end(), [](Reg const& lhs, Reg const& rhs) { + return lhs.acct < rhs.acct; + }); } } // namespace jtx diff --git a/src/test/jtx/TestHelpers.h b/src/test/jtx/TestHelpers.h index c0e54900f6..2836748ec3 100644 --- a/src/test/jtx/TestHelpers.h +++ b/src/test/jtx/TestHelpers.h @@ -26,7 +26,10 @@ namespace jtx { Not every helper will be able to use this because of conversions and other issues, but for classes where it's straightforward, this can simplify things. */ -template +template < + class SField, + class StoredValue = typename SField::type::value_type, + class OutputValue = StoredValue> struct JTxField { using SF = SField; @@ -178,7 +181,8 @@ struct blobField : public JTxField } template - explicit blobField(SF const& sfield, std::array const& c) : blobField(sfield, makeSlice(c)) + explicit blobField(SF const& sfield, std::array const& c) + : blobField(sfield, makeSlice(c)) { } }; @@ -433,7 +437,11 @@ PrettyAmount xrpMinusFee(Env const& env, std::int64_t xrpAmount); bool -expectHolding(Env& env, AccountID const& account, STAmount const& value, bool defaultLimits = false); +expectHolding( + Env& env, + AccountID const& account, + STAmount const& value, + bool defaultLimits = false); template bool @@ -446,13 +454,21 @@ bool expectHolding(Env& env, AccountID const& account, None const& value); bool -expectOffers(Env& env, AccountID const& account, std::uint16_t size, std::vector const& toMatch = {}); +expectOffers( + Env& env, + AccountID const& account, + std::uint16_t size, + std::vector const& toMatch = {}); Json::Value ledgerEntryRoot(Env& env, Account const& acct); Json::Value -ledgerEntryState(Env& env, Account const& acct_a, Account const& acct_b, std::string const& currency); +ledgerEntryState( + Env& env, + Account const& acct_a, + Account const& acct_b, + std::string const& currency); Json::Value accountBalance(Env& env, Account const& acct); @@ -589,55 +605,64 @@ checkMetrics( auto const metrics = env.app().getTxQ().getMetrics(*env.current()); using namespace std::string_literals; - metrics.referenceFeeLevel == baseFeeLevel ? test.pass() - : test.fail( - "reference: "s + std::to_string(metrics.referenceFeeLevel.value()) + - "/" + std::to_string(baseFeeLevel.value()), - file, - line); + metrics.referenceFeeLevel == baseFeeLevel + ? test.pass() + : test.fail( + "reference: "s + std::to_string(metrics.referenceFeeLevel.value()) + "/" + + std::to_string(baseFeeLevel.value()), + file, + line); metrics.txCount == expectedCount ? test.pass() - : test.fail("txCount: "s + std::to_string(metrics.txCount) + "/" + std::to_string(expectedCount), file, line); + : test.fail( + "txCount: "s + std::to_string(metrics.txCount) + "/" + std::to_string(expectedCount), + file, + line); - metrics.txQMaxSize == expectedMaxCount ? test.pass() - : test.fail( - "txQMaxSize: "s + std::to_string(metrics.txQMaxSize.value_or(0)) + - "/" + std::to_string(expectedMaxCount.value_or(0)), - file, - line); + metrics.txQMaxSize == expectedMaxCount + ? test.pass() + : test.fail( + "txQMaxSize: "s + std::to_string(metrics.txQMaxSize.value_or(0)) + "/" + + std::to_string(expectedMaxCount.value_or(0)), + file, + line); metrics.txInLedger == expectedInLedger ? test.pass() : test.fail( - "txInLedger: "s + std::to_string(metrics.txInLedger) + "/" + std::to_string(expectedInLedger), + "txInLedger: "s + std::to_string(metrics.txInLedger) + "/" + + std::to_string(expectedInLedger), file, line); metrics.txPerLedger == expectedPerLedger ? test.pass() : test.fail( - "txPerLedger: "s + std::to_string(metrics.txPerLedger) + "/" + std::to_string(expectedPerLedger), + "txPerLedger: "s + std::to_string(metrics.txPerLedger) + "/" + + std::to_string(expectedPerLedger), file, line); metrics.minProcessingFeeLevel == expectedMin ? test.pass() : test.fail( - "minProcessingFeeLevel: "s + std::to_string(metrics.minProcessingFeeLevel.value()) + "/" + - std::to_string(expectedMin.value()), + "minProcessingFeeLevel: "s + std::to_string(metrics.minProcessingFeeLevel.value()) + + "/" + std::to_string(expectedMin.value()), file, line); - metrics.medFeeLevel == expectedMed ? test.pass() - : test.fail( - "medFeeLevel: "s + std::to_string(metrics.medFeeLevel.value()) + "/" + - std::to_string(expectedMed.value()), - file, - line); + metrics.medFeeLevel == expectedMed + ? test.pass() + : test.fail( + "medFeeLevel: "s + std::to_string(metrics.medFeeLevel.value()) + "/" + + std::to_string(expectedMed.value()), + file, + line); auto const expectedCurFeeLevel = expectedInLedger > expectedPerLedger - ? expectedMed * expectedInLedger * expectedInLedger / (expectedPerLedger * expectedPerLedger) + ? expectedMed * expectedInLedger * expectedInLedger / + (expectedPerLedger * expectedPerLedger) : metrics.referenceFeeLevel; metrics.openLedgerFeeLevel == expectedCurFeeLevel @@ -662,10 +687,18 @@ Json::Value del(AccountID const& account, uint256 const& brokerID, std::uint32_t flags = 0); Json::Value -coverDeposit(AccountID const& account, uint256 const& brokerID, STAmount const& amount, std::uint32_t flags = 0); +coverDeposit( + AccountID const& account, + uint256 const& brokerID, + STAmount const& amount, + std::uint32_t flags = 0); Json::Value -coverWithdraw(AccountID const& account, uint256 const& brokerID, STAmount const& amount, std::uint32_t flags = 0); +coverWithdraw( + AccountID const& account, + uint256 const& brokerID, + STAmount const& amount, + std::uint32_t flags = 0); // Must specify at least one of loanBrokerID or amount. Json::Value @@ -679,7 +712,8 @@ auto const debtMaximum = simpleField(sfDebtMaximum); auto const coverRateMinimum = valueUnitWrapper(sfCoverRateMinimum); -auto const coverRateLiquidation = valueUnitWrapper(sfCoverRateLiquidation); +auto const coverRateLiquidation = + valueUnitWrapper(sfCoverRateLiquidation); auto const destination = JTxFieldWrapper(sfDestination); @@ -690,7 +724,10 @@ auto const destination = JTxFieldWrapper(sfDestination); namespace loan { Json::Value -set(AccountID const& account, uint256 const& loanBrokerID, Number principalRequested, std::uint32_t flags = 0); +set(AccountID const& account, + uint256 const& loanBrokerID, + Number principalRequested, + std::uint32_t flags = 0); auto const counterparty = JTxFieldWrapper(sfCounterparty); @@ -712,7 +749,8 @@ auto const lateInterestRate = valueUnitWrapper(sf auto const closeInterestRate = valueUnitWrapper(sfCloseInterestRate); -auto const overpaymentInterestRate = valueUnitWrapper(sfOverpaymentInterestRate); +auto const overpaymentInterestRate = + valueUnitWrapper(sfOverpaymentInterestRate); auto const paymentTotal = simpleField(sfPaymentTotal); @@ -727,7 +765,10 @@ Json::Value del(AccountID const& account, uint256 const& loanID, std::uint32_t flags = 0); Json::Value -pay(AccountID const& account, uint256 const& loanID, STAmount const& amount, std::uint32_t flags = 0); +pay(AccountID const& account, + uint256 const& loanID, + STAmount const& amount, + std::uint32_t flags = 0); } // namespace loan diff --git a/src/test/jtx/TestSuite.h b/src/test/jtx/TestSuite.h index 1558f68d39..604557c155 100644 --- a/src/test/jtx/TestSuite.h +++ b/src/test/jtx/TestSuite.h @@ -47,7 +47,10 @@ public: template bool - expectCollectionEquals(Collection const& actual, Collection const& expected, std::string const& message = "") + expectCollectionEquals( + Collection const& actual, + Collection const& expected, + std::string const& message = "") { auto msg = addPrefix(message); bool success = expectEquals(actual.size(), expected.size(), msg + "Sizes are different"); diff --git a/src/test/jtx/TrustedPublisherServer.h b/src/test/jtx/TrustedPublisherServer.h index a46e98ad50..529383c622 100644 --- a/src/test/jtx/TrustedPublisherServer.h +++ b/src/test/jtx/TrustedPublisherServer.h @@ -67,7 +67,8 @@ class TrustedPublisherServer : public std::enable_shared_from_this blobInfo; blobInfo.reserve(futures.size() + 1); auto const [data, blob] = [&]() -> std::pair { // Builds the validator list, then encodes it into a blob. std::string data = "{\"sequence\":" + std::to_string(sequence) + - ",\"expiration\":" + std::to_string(validUntil.time_since_epoch().count()) + ",\"validators\":["; + ",\"expiration\":" + std::to_string(validUntil.time_since_epoch().count()) + + ",\"validators\":["; for (auto const& val : validators) { - data += "{\"validation_public_key\":\"" + strHex(val.masterPublic) + "\",\"manifest\":\"" + - val.manifest + "\"},"; + data += "{\"validation_public_key\":\"" + strHex(val.masterPublic) + + "\",\"manifest\":\"" + val.manifest + "\"},"; } data.pop_back(); data += "]}"; @@ -170,8 +178,8 @@ public: getList_ = [blob = blob, sig, manifest, version](int interval) { // Build the contents of a version 1 format UNL file std::stringstream l; - l << "{\"blob\":\"" << blob << "\"" << ",\"signature\":\"" << sig << "\"" << ",\"manifest\":\"" << manifest - << "\"" + l << "{\"blob\":\"" << blob << "\"" << ",\"signature\":\"" << sig << "\"" + << ",\"manifest\":\"" << manifest << "\"" << ",\"refresh_interval\": " << interval << ",\"version\":" << version << '}'; return l.str(); }; @@ -179,13 +187,14 @@ public: { std::string data = "{\"sequence\":" + std::to_string(++sequence) + ",\"effective\":" + std::to_string(future.first.time_since_epoch().count()) + - ",\"expiration\":" + std::to_string(future.second.time_since_epoch().count()) + ",\"validators\":["; + ",\"expiration\":" + std::to_string(future.second.time_since_epoch().count()) + + ",\"validators\":["; // Use the same set of validators for simplicity for (auto const& val : validators) { - data += "{\"validation_public_key\":\"" + strHex(val.masterPublic) + "\",\"manifest\":\"" + - val.manifest + "\"},"; + data += "{\"validation_public_key\":\"" + strHex(val.masterPublic) + + "\",\"manifest\":\"" + val.manifest + "\"},"; } data.pop_back(); data += "]}"; @@ -200,7 +209,8 @@ public: std::stringstream l; for (auto const& info : blobInfo) { - l << "{\"blob\":\"" << info.blob << "\"" << ",\"signature\":\"" << info.signature << "\"},"; + l << "{\"blob\":\"" << info.blob << "\"" << ",\"signature\":\"" << info.signature + << "\"},"; } std::string blobs = l.str(); blobs.pop_back(); @@ -225,12 +235,13 @@ public: acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true), ec); acceptor_.bind(ep_); acceptor_.listen(boost::asio::socket_base::max_listen_connections); - acceptor_.async_accept(sock_, [wp = std::weak_ptr{shared_from_this()}](error_code ec) { - if (auto p = wp.lock()) - { - p->on_accept(ec); - } - }); + acceptor_.async_accept( + sock_, [wp = std::weak_ptr{shared_from_this()}](error_code ec) { + if (auto p = wp.lock()) + { + p->on_accept(ec); + } + }); } void @@ -460,12 +471,13 @@ private: static int id_ = 0; std::thread{lambda{++id_, *this, std::move(sock_), useSSL_}}.detach(); - acceptor_.async_accept(sock_, [wp = std::weak_ptr{shared_from_this()}](error_code ec) { - if (auto p = wp.lock()) - { - p->on_accept(ec); - } - }); + acceptor_.async_accept( + sock_, [wp = std::weak_ptr{shared_from_this()}](error_code ec) { + if (auto p = wp.lock()) + { + p->on_accept(ec); + } + }); } void @@ -521,7 +533,8 @@ private: int refresh = 5; constexpr char const* refreshPrefix = "/validators2/refresh/"; if (boost::starts_with(path, refreshPrefix)) - refresh = boost::lexical_cast(path.substr(strlen(refreshPrefix))); + refresh = boost::lexical_cast( + path.substr(strlen(refreshPrefix))); res.body() = getList2_(refresh); } } @@ -538,7 +551,8 @@ private: int refresh = 5; constexpr char const* refreshPrefix = "/validators/refresh/"; if (boost::starts_with(path, refreshPrefix)) - refresh = boost::lexical_cast(path.substr(strlen(refreshPrefix))); + refresh = boost::lexical_cast( + path.substr(strlen(refreshPrefix))); res.body() = getList_(refresh); } } @@ -548,14 +562,16 @@ private: res.result(http::status::ok); res.insert("Content-Type", "text/example"); // if huge was requested, lie about content length - std::uint64_t cl = - boost::starts_with(path, "/textfile/huge") ? std::numeric_limits::max() : 1024; + std::uint64_t cl = boost::starts_with(path, "/textfile/huge") + ? std::numeric_limits::max() + : 1024; res.content_length(cl); if (req.method() == http::verb::get) { std::stringstream body; for (auto i = 0; i < 1024; ++i) - body << static_cast(rand_int(32, 126)), res.body() = body.str(); + body << static_cast(rand_int(32, 126)), + res.body() = body.str(); } } else if (boost::starts_with(path, "/sleep/")) @@ -582,7 +598,9 @@ private: else if (!boost::starts_with(path, "/redirect_nolo")) { location << (ssl ? "https://" : "http://") << local_endpoint() - << (boost::starts_with(path, "/redirect_forever/") ? path : "/validators"); + << (boost::starts_with(path, "/redirect_forever/") + ? path + : "/validators"); } if (!location.str().empty()) res.insert("Location", location.str()); @@ -637,8 +655,8 @@ make_TrustedPublisherServer( bool immediateStart = true, int sequence = 1) { - auto const r = - std::make_shared(ioc, validators, validUntil, futures, useSSL, version, sequence); + auto const r = std::make_shared( + ioc, validators, validUntil, futures, useSSL, version, sequence); if (immediateStart) r->start(); return r; diff --git a/src/test/jtx/WSClient.h b/src/test/jtx/WSClient.h index 86b81ac0ac..d1801cb4a9 100644 --- a/src/test/jtx/WSClient.h +++ b/src/test/jtx/WSClient.h @@ -20,7 +20,9 @@ public: /** Retrieve a message that meets the predicate criteria. */ virtual std::optional - findMsg(std::chrono::milliseconds const& timeout, std::function pred) = 0; + findMsg( + std::chrono::milliseconds const& timeout, + std::function pred) = 0; }; /** Returns a client operating through WebSockets/S. */ diff --git a/src/test/jtx/amount.h b/src/test/jtx/amount.h index c7b66504d3..c4e97502db 100644 --- a/src/test/jtx/amount.h +++ b/src/test/jtx/amount.h @@ -81,14 +81,18 @@ public: template PrettyAmount( T v, - std::enable_if_t= sizeof(int) && std::is_integral_v && std::is_signed_v>* = nullptr) + std::enable_if_t< + sizeof(T) >= sizeof(int) && std::is_integral_v && std::is_signed_v>* = nullptr) : amount_((v > 0) ? v : -v, v < 0) { } /** drops */ template - PrettyAmount(T v, std::enable_if_t= sizeof(int) && std::is_unsigned_v>* = nullptr) : amount_(v) + PrettyAmount( + T v, + std::enable_if_t= sizeof(int) && std::is_unsigned_v>* = nullptr) + : amount_(v) { } @@ -230,7 +234,8 @@ struct BookSpec AccountID account; xrpl::Currency currency; - BookSpec(AccountID const& account_, xrpl::Currency const& currency_) : account(account_), currency(currency_) + BookSpec(AccountID const& account_, xrpl::Currency const& currency_) + : account(account_), currency(currency_) { } }; @@ -378,7 +383,8 @@ public: Account account; xrpl::Currency currency; - IOU(Account const& account_, xrpl::Currency const& currency_) : account(account_), currency(currency_) + IOU(Account const& account_, xrpl::Currency const& currency_) + : account(account_), currency(currency_) { } @@ -412,7 +418,9 @@ public: return asset(); } - template = sizeof(int) && std::is_arithmetic::value>> + template < + class T, + class = std::enable_if_t= sizeof(int) && std::is_arithmetic::value>> PrettyAmount operator()(T v) const { diff --git a/src/test/jtx/balance.h b/src/test/jtx/balance.h index 83e2e3ea03..2181429908 100644 --- a/src/test/jtx/balance.h +++ b/src/test/jtx/balance.h @@ -27,11 +27,13 @@ public: { } - balance(Account const& account, None const& value) : none_(true), account_(account), value_(value.asset) + balance(Account const& account, None const& value) + : none_(true), account_(account), value_(value.asset) { } - balance(Account const& account, STAmount const& value) : none_(false), account_(account), value_(value) + balance(Account const& account, STAmount const& value) + : none_(false), account_(account), value_(value) { } diff --git a/src/test/jtx/batch.h b/src/test/jtx/batch.h index c11a9fe17e..f81bed3c6e 100644 --- a/src/test/jtx/batch.h +++ b/src/test/jtx/batch.h @@ -109,7 +109,8 @@ public: Account master; std::vector signers; - msig(Account const& masterAccount, std::vector signers_) : master(masterAccount), signers(std::move(signers_)) + msig(Account const& masterAccount, std::vector signers_) + : master(masterAccount), signers(std::move(signers_)) { sortSigners(signers); } @@ -117,7 +118,8 @@ public: template requires std::convertible_to explicit msig(Account const& masterAccount, AccountType&& a0, Accounts&&... aN) - : master(masterAccount), signers{std::forward(a0), std::forward(aN)...} + : master(masterAccount) + , signers{std::forward(a0), std::forward(aN)...} { sortSigners(signers); } diff --git a/src/test/jtx/credentials.h b/src/test/jtx/credentials.h index 29ecacb11b..56d127fca9 100644 --- a/src/test/jtx/credentials.h +++ b/src/test/jtx/credentials.h @@ -11,7 +11,10 @@ namespace jtx { namespace credentials { inline Keylet -keylet(test::jtx::Account const& subject, test::jtx::Account const& issuer, std::string_view credType) +keylet( + test::jtx::Account const& subject, + test::jtx::Account const& issuer, + std::string_view credType) { return keylet::credential(subject.id(), issuer.id(), Slice(credType.data(), credType.size())); } @@ -61,10 +64,18 @@ Json::Value accept(jtx::Account const& subject, jtx::Account const& issuer, std::string_view credType); Json::Value -deleteCred(jtx::Account const& acc, jtx::Account const& subject, jtx::Account const& issuer, std::string_view credType); +deleteCred( + jtx::Account const& acc, + jtx::Account const& subject, + jtx::Account const& issuer, + std::string_view credType); Json::Value -ledgerEntry(jtx::Env& env, jtx::Account const& subject, jtx::Account const& issuer, std::string_view credType); +ledgerEntry( + jtx::Env& env, + jtx::Account const& subject, + jtx::Account const& issuer, + std::string_view credType); Json::Value ledgerEntry(jtx::Env& env, std::string const& credIdx); diff --git a/src/test/jtx/delegate.h b/src/test/jtx/delegate.h index d965ab580a..7aecb54922 100644 --- a/src/test/jtx/delegate.h +++ b/src/test/jtx/delegate.h @@ -10,7 +10,9 @@ namespace jtx { namespace delegate { Json::Value -set(jtx::Account const& account, jtx::Account const& authorize, std::vector const& permissions); +set(jtx::Account const& account, + jtx::Account const& authorize, + std::vector const& permissions); Json::Value entry(jtx::Env& env, jtx::Account const& account, jtx::Account const& authorize); diff --git a/src/test/jtx/envconfig.h b/src/test/jtx/envconfig.h index dc0c48e064..f2f67f935b 100644 --- a/src/test/jtx/envconfig.h +++ b/src/test/jtx/envconfig.h @@ -106,7 +106,9 @@ std::unique_ptr addGrpcConfigWithSecureGateway(std::unique_ptr, std::string const& secureGateway); std::unique_ptr -makeConfig(std::map extraTxQ = {}, std::map extraVoting = {}); +makeConfig( + std::map extraTxQ = {}, + std::map extraVoting = {}); } // namespace jtx } // namespace test diff --git a/src/test/jtx/escrow.h b/src/test/jtx/escrow.h index c3f535e29f..8fe9d9f5f9 100644 --- a/src/test/jtx/escrow.h +++ b/src/test/jtx/escrow.h @@ -48,26 +48,26 @@ rate(Env& env, Account const& account, std::uint32_t const& seq); // A PreimageSha256 fulfillments and its associated condition. std::array const fb1 = {{0xA0, 0x02, 0x80, 0x00}}; -std::array const cb1 = {{0xA0, 0x25, 0x80, 0x20, 0xE3, 0xB0, 0xC4, 0x42, 0x98, 0xFC, - 0x1C, 0x14, 0x9A, 0xFB, 0xF4, 0xC8, 0x99, 0x6F, 0xB9, 0x24, - 0x27, 0xAE, 0x41, 0xE4, 0x64, 0x9B, 0x93, 0x4C, 0xA4, 0x95, - 0x99, 0x1B, 0x78, 0x52, 0xB8, 0x55, 0x81, 0x01, 0x00}}; +std::array const cb1 = { + {0xA0, 0x25, 0x80, 0x20, 0xE3, 0xB0, 0xC4, 0x42, 0x98, 0xFC, 0x1C, 0x14, 0x9A, + 0xFB, 0xF4, 0xC8, 0x99, 0x6F, 0xB9, 0x24, 0x27, 0xAE, 0x41, 0xE4, 0x64, 0x9B, + 0x93, 0x4C, 0xA4, 0x95, 0x99, 0x1B, 0x78, 0x52, 0xB8, 0x55, 0x81, 0x01, 0x00}}; // Another PreimageSha256 fulfillments and its associated condition. std::array const fb2 = {{0xA0, 0x05, 0x80, 0x03, 0x61, 0x61, 0x61}}; -std::array const cb2 = {{0xA0, 0x25, 0x80, 0x20, 0x98, 0x34, 0x87, 0x6D, 0xCF, 0xB0, - 0x5C, 0xB1, 0x67, 0xA5, 0xC2, 0x49, 0x53, 0xEB, 0xA5, 0x8C, - 0x4A, 0xC8, 0x9B, 0x1A, 0xDF, 0x57, 0xF2, 0x8F, 0x2F, 0x9D, - 0x09, 0xAF, 0x10, 0x7E, 0xE8, 0xF0, 0x81, 0x01, 0x03}}; +std::array const cb2 = { + {0xA0, 0x25, 0x80, 0x20, 0x98, 0x34, 0x87, 0x6D, 0xCF, 0xB0, 0x5C, 0xB1, 0x67, + 0xA5, 0xC2, 0x49, 0x53, 0xEB, 0xA5, 0x8C, 0x4A, 0xC8, 0x9B, 0x1A, 0xDF, 0x57, + 0xF2, 0x8F, 0x2F, 0x9D, 0x09, 0xAF, 0x10, 0x7E, 0xE8, 0xF0, 0x81, 0x01, 0x03}}; // Another PreimageSha256 fulfillment and its associated condition. std::array const fb3 = {{0xA0, 0x06, 0x80, 0x04, 0x6E, 0x69, 0x6B, 0x62}}; -std::array const cb3 = {{0xA0, 0x25, 0x80, 0x20, 0x6E, 0x4C, 0x71, 0x45, 0x30, 0xC0, - 0xA4, 0x26, 0x8B, 0x3F, 0xA6, 0x3B, 0x1B, 0x60, 0x6F, 0x2D, - 0x26, 0x4A, 0x2D, 0x85, 0x7B, 0xE8, 0xA0, 0x9C, 0x1D, 0xFD, - 0x57, 0x0D, 0x15, 0x85, 0x8B, 0xD4, 0x81, 0x01, 0x04}}; +std::array const cb3 = { + {0xA0, 0x25, 0x80, 0x20, 0x6E, 0x4C, 0x71, 0x45, 0x30, 0xC0, 0xA4, 0x26, 0x8B, + 0x3F, 0xA6, 0x3B, 0x1B, 0x60, 0x6F, 0x2D, 0x26, 0x4A, 0x2D, 0x85, 0x7B, 0xE8, + 0xA0, 0x9C, 0x1D, 0xFD, 0x57, 0x0D, 0x15, 0x85, 0x8B, 0xD4, 0x81, 0x01, 0x04}}; /** Set the "FinishAfter" time tag on a JTx */ auto const finish_time = JTxFieldWrapper(sfFinishAfter); diff --git a/src/test/jtx/impl/AMM.cpp b/src/test/jtx/impl/AMM.cpp index f920858ea5..faf47259dc 100644 --- a/src/test/jtx/impl/AMM.cpp +++ b/src/test/jtx/impl/AMM.cpp @@ -1,13 +1,12 @@ #include #include -#include -#include - #include #include #include #include +#include +#include namespace xrpl { namespace test { @@ -71,12 +70,39 @@ AMM::AMM( ter const& ter, bool log, bool close) - : AMM(env, account, asset1, asset2, log, 0, 0, std::nullopt, std::nullopt, std::nullopt, ter, close) + : AMM(env, + account, + asset1, + asset2, + log, + 0, + 0, + std::nullopt, + std::nullopt, + std::nullopt, + ter, + close) { } -AMM::AMM(Env& env, Account const& account, STAmount const& asset1, STAmount const& asset2, CreateArg const& arg) - : AMM(env, account, asset1, asset2, arg.log, arg.tfee, arg.fee, arg.flags, arg.seq, arg.ms, arg.err, arg.close) +AMM::AMM( + Env& env, + Account const& account, + STAmount const& asset1, + STAmount const& asset2, + CreateArg const& arg) + : AMM(env, + account, + asset1, + asset2, + arg.log, + arg.tfee, + arg.fee, + arg.flags, + arg.seq, + arg.ms, + arg.err, + arg.close) { } @@ -144,23 +170,31 @@ AMM::ammRpcInfo( jv[jss::amm_account] = to_string(*ammAccount); } auto jr = - (apiVersion == RPC::apiInvalidVersion ? env_.rpc("json", "amm_info", to_string(jv)) - : env_.rpc(apiVersion, "json", "amm_info", to_string(jv))); + (apiVersion == RPC::apiInvalidVersion + ? env_.rpc("json", "amm_info", to_string(jv)) + : env_.rpc(apiVersion, "json", "amm_info", to_string(jv))); if (jr.isObject() && jr.isMember(jss::result) && jr[jss::result].isMember(jss::status)) return jr[jss::result]; return Json::nullValue; } std::tuple -AMM::balances(Issue const& issue1, Issue const& issue2, std::optional const& account) const +AMM::balances(Issue const& issue1, Issue const& issue2, std::optional const& account) + const { if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) { auto const ammAccountID = amm->getAccountID(sfAccount); - auto const [asset1Balance, asset2Balance] = - ammPoolHolds(*env_.current(), ammAccountID, issue1, issue2, FreezeHandling::fhIGNORE_FREEZE, env_.journal); - auto const lptAMMBalance = - account ? ammLPHolds(*env_.current(), *amm, *account, env_.journal) : amm->getFieldAmount(sfLPTokenBalance); + auto const [asset1Balance, asset2Balance] = ammPoolHolds( + *env_.current(), + ammAccountID, + issue1, + issue2, + FreezeHandling::fhIGNORE_FREEZE, + env_.journal); + auto const lptAMMBalance = account + ? ammLPHolds(*env_.current(), *amm, *account, env_.journal) + : amm->getFieldAmount(sfLPTokenBalance); return {asset1Balance, asset2Balance, lptAMMBalance}; } return {STAmount{}, STAmount{}, STAmount{}}; @@ -173,15 +207,23 @@ AMM::expectBalances( IOUAmount const& lpt, std::optional const& account) const { - auto const [asset1Balance, asset2Balance, lptAMMBalance] = balances(asset1.issue(), asset2.issue(), account); - return asset1 == asset1Balance && asset2 == asset2Balance && lptAMMBalance == STAmount{lpt, lptIssue_}; + auto const [asset1Balance, asset2Balance, lptAMMBalance] = + balances(asset1.issue(), asset2.issue(), account); + return asset1 == asset1Balance && asset2 == asset2Balance && + lptAMMBalance == STAmount{lpt, lptIssue_}; } IOUAmount AMM::getLPTokensBalance(std::optional const& account) const { if (account) - return accountHolds(*env_.current(), *account, lptIssue_, FreezeHandling::fhZERO_IF_FROZEN, env_.journal).iou(); + return accountHolds( + *env_.current(), + *account, + lptIssue_, + FreezeHandling::fhZERO_IF_FROZEN, + env_.journal) + .iou(); if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) return amm->getFieldAmount(sfLPTokenBalance).iou(); return IOUAmount{0}; @@ -199,15 +241,21 @@ AMM::expectLPTokens(AccountID const& account, IOUAmount const& expTokens) const } bool -AMM::expectAuctionSlot(std::uint32_t fee, std::optional timeSlot, IOUAmount expectedPrice) const +AMM::expectAuctionSlot( + std::uint32_t fee, + std::optional timeSlot, + IOUAmount expectedPrice) const { - return expectAuctionSlot( - [&](std::uint32_t slotFee, std::optional slotInterval, IOUAmount const& slotPrice, auto const&) { - return slotFee == fee && - // Auction slot might be expired, in which case slotInterval is - // 0 - ((!timeSlot && slotInterval == 0) || slotInterval == timeSlot) && slotPrice == expectedPrice; - }); + return expectAuctionSlot([&](std::uint32_t slotFee, + std::optional slotInterval, + IOUAmount const& slotPrice, + auto const&) { + return slotFee == fee && + // Auction slot might be expired, in which case slotInterval is + // 0 + ((!timeSlot && slotInterval == 0) || slotInterval == timeSlot) && + slotPrice == expectedPrice; + }); } bool @@ -217,8 +265,10 @@ AMM::expectAuctionSlot(std::vector const& authAccounts) const [&](std::uint32_t, std::optional, IOUAmount const&, STArray const& accounts) { for (auto const& account : accounts) { - if (std::find(authAccounts.cbegin(), authAccounts.cend(), account.getAccountID(sfAccount)) == - authAccounts.end()) + if (std::find( + authAccounts.cbegin(), + authAccounts.cend(), + account.getAccountID(sfAccount)) == authAccounts.end()) return false; } return true; @@ -253,8 +303,11 @@ AMM::expectAmmRpcInfo( } bool -AMM::expectAmmInfo(STAmount const& asset1, STAmount const& asset2, IOUAmount const& balance, Json::Value const& jvRes) - const +AMM::expectAmmInfo( + STAmount const& asset1, + STAmount const& asset2, + IOUAmount const& balance, + Json::Value const& jvRes) const { if (!jvRes.isMember(jss::amm)) return false; @@ -273,7 +326,8 @@ AMM::expectAmmInfo(STAmount const& asset1, STAmount const& asset2, IOUAmount con // ammRpcInfo returns unordered assets if (asset1Info.issue() != asset1.issue()) std::swap(asset1Info, asset2Info); - return asset1 == asset1Info && asset2 == asset2Info && lptBalance == STAmount{balance, lptIssue_}; + return asset1 == asset1Info && asset2 == asset2Info && + lptBalance == STAmount{balance, lptIssue_}; } void @@ -319,7 +373,16 @@ AMM::deposit( std::optional const& ter) { return deposit( - account, tokens, asset1In, std::nullopt, std::nullopt, flags, std::nullopt, std::nullopt, std::nullopt, ter); + account, + tokens, + asset1In, + std::nullopt, + std::nullopt, + flags, + std::nullopt, + std::nullopt, + std::nullopt, + ter); } IOUAmount @@ -333,7 +396,16 @@ AMM::deposit( { assert(!(asset2In && maxEP)); return deposit( - account, std::nullopt, asset1In, asset2In, maxEP, flags, std::nullopt, std::nullopt, std::nullopt, ter); + account, + std::nullopt, + asset1In, + asset2In, + maxEP, + flags, + std::nullopt, + std::nullopt, + std::nullopt, + ter); } IOUAmount @@ -426,7 +498,16 @@ AMM::withdraw( std::optional const& flags, std::optional const& ter) { - return withdraw(account, tokens, asset1Out, std::nullopt, std::nullopt, flags, std::nullopt, std::nullopt, ter); + return withdraw( + account, + tokens, + asset1Out, + std::nullopt, + std::nullopt, + flags, + std::nullopt, + std::nullopt, + ter); } IOUAmount @@ -438,7 +519,16 @@ AMM::withdraw( std::optional const& ter) { assert(!(asset2Out && maxEP)); - return withdraw(account, std::nullopt, asset1Out, asset2Out, maxEP, std::nullopt, std::nullopt, std::nullopt, ter); + return withdraw( + account, + std::nullopt, + asset1Out, + asset2Out, + maxEP, + std::nullopt, + std::nullopt, + std::nullopt, + ter); } IOUAmount @@ -489,7 +579,15 @@ IOUAmount AMM::withdraw(WithdrawArg const& arg) { return withdraw( - arg.account, arg.tokens, arg.asset1Out, arg.asset2Out, arg.maxEP, arg.flags, arg.assets, arg.seq, arg.err); + arg.account, + arg.tokens, + arg.asset1Out, + arg.asset2Out, + arg.maxEP, + arg.flags, + arg.assets, + arg.seq, + arg.err); } void @@ -524,7 +622,9 @@ AMM::bid(BidArg const& arg) { if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) { - assert(!env_.current()->rules().enabled(fixInnerObjTemplate) || amm->isFieldPresent(sfAuctionSlot)); + assert( + !env_.current()->rules().enabled(fixInnerObjTemplate) || + amm->isFieldPresent(sfAuctionSlot)); if (amm->isFieldPresent(sfAuctionSlot)) { auto const& auctionSlot = static_cast(amm->peekAtField(sfAuctionSlot)); @@ -579,7 +679,10 @@ AMM::bid(BidArg const& arg) } void -AMM::submit(Json::Value const& jv, std::optional const& seq, std::optional const& ter) +AMM::submit( + Json::Value const& jv, + std::optional const& seq, + std::optional const& ter) { if (log_) std::cout << jv.toStyledString(); @@ -611,7 +714,9 @@ AMM::expectAuctionSlot(auto&& cb) const { if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) { - assert(!env_.current()->rules().enabled(fixInnerObjTemplate) || amm->isFieldPresent(sfAuctionSlot)); + assert( + !env_.current()->rules().enabled(fixInnerObjTemplate) || + amm->isFieldPresent(sfAuctionSlot)); if (amm->isFieldPresent(sfAuctionSlot)) { auto const& auctionSlot = static_cast(amm->peekAtField(sfAuctionSlot)); @@ -622,8 +727,8 @@ AMM::expectAuctionSlot(auto&& cb) const // the failure scenarios. Access as optional // to avoid the failure. auto const slotFee = auctionSlot[~sfDiscountedFee].value_or(0); - auto const slotInterval = - ammAuctionTimeSlot(env_.app().timeKeeper().now().time_since_epoch().count(), auctionSlot); + auto const slotInterval = ammAuctionTimeSlot( + env_.app().timeKeeper().now().time_since_epoch().count(), auctionSlot); auto const slotPrice = auctionSlot[sfPrice].iou(); auto const authAccounts = auctionSlot.getFieldArray(sfAuthAccounts); return cb(slotFee, slotInterval, slotPrice, authAccounts); diff --git a/src/test/jtx/impl/AMMTest.cpp b/src/test/jtx/impl/AMMTest.cpp index 18359ad201..01ba5069bf 100644 --- a/src/test/jtx/impl/AMMTest.cpp +++ b/src/test/jtx/impl/AMMTest.cpp @@ -88,7 +88,8 @@ AMMTestBase::testAMM( std::optional const& ter, std::vector const& vfeatures) { - testAMM(std::move(cb), TestAMMArg{.pool = pool, .tfee = tfee, .ter = ter, .features = vfeatures}); + testAMM( + std::move(cb), TestAMMArg{.pool = pool, .tfee = tfee, .ter = ter, .features = vfeatures}); } void @@ -135,7 +136,8 @@ AMMTestBase::testAMM(std::function&& cb, TestAMMArg else if (asset2.native()) fund(env, gw, {alice, carol}, toFund2, {toFund1}, Fund::All); - AMM ammAlice(env, alice, asset1, asset2, CreateArg{.log = false, .tfee = arg.tfee, .err = arg.ter}); + AMM ammAlice( + env, alice, asset1, asset2, CreateArg{.log = false, .tfee = arg.tfee, .err = arg.ter}); if (BEAST_EXPECT(ammAlice.expectBalances(asset1, asset2, ammAlice.tokens()))) cb(ammAlice, env); } diff --git a/src/test/jtx/impl/Account.cpp b/src/test/jtx/impl/Account.cpp index 31798abdc7..a7b71ea6eb 100644 --- a/src/test/jtx/impl/Account.cpp +++ b/src/test/jtx/impl/Account.cpp @@ -14,8 +14,15 @@ Account const Account::master( generateKeyPair(KeyType::secp256k1, generateSeed("masterpassphrase")), Account::privateCtorTag{}); -Account::Account(std::string name, std::pair const& keys, Account::privateCtorTag) - : name_(std::move(name)), pk_(keys.first), sk_(keys.second), id_(calcAccountID(pk_)), human_(toBase58(id_)) +Account::Account( + std::string name, + std::pair const& keys, + Account::privateCtorTag) + : name_(std::move(name)) + , pk_(keys.first) + , sk_(keys.second) + , id_(calcAccountID(pk_)) + , human_(toBase58(id_)) { } @@ -46,7 +53,8 @@ Account::fromCache(AcctStringType stringType, std::string name, KeyType type) return r.first->second; } -Account::Account(std::string name, KeyType type) : Account(fromCache(Account::other, std::move(name), type)) +Account::Account(std::string name, KeyType type) + : Account(fromCache(Account::other, std::move(name), type)) { } diff --git a/src/test/jtx/impl/Env.cpp b/src/test/jtx/impl/Env.cpp index d8bcec84ee..df86aaa2e4 100644 --- a/src/test/jtx/impl/Env.cpp +++ b/src/test/jtx/impl/Env.cpp @@ -10,12 +10,12 @@ #include #include -#include #include #include #include #include +#include #include #include #include @@ -25,6 +25,7 @@ #include #include #include +#include #include #include @@ -56,7 +57,8 @@ Env::AppBundle::AppBundle( auto timeKeeper_ = std::make_unique(); timeKeeper = timeKeeper_.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()); + HTTPClient::initializeSSLContext( + config->SSL_VERIFY_DIR, config->SSL_VERIFY_FILE, config->SSL_VERIFY, debugLog()); owned = make_Application(std::move(config), std::move(logs), std::move(timeKeeper_)); app = owned.get(); app->logs().threshold(thresh); @@ -269,12 +271,20 @@ Env::fund(bool setDefaultRipple, STAmount const& amount, Account const& account) jtx::seq(jtx::autofill), fee(jtx::autofill), sig(jtx::autofill)); - apply(fset(account, asfDefaultRipple), jtx::seq(jtx::autofill), fee(jtx::autofill), sig(jtx::autofill)); + apply( + fset(account, asfDefaultRipple), + jtx::seq(jtx::autofill), + fee(jtx::autofill), + sig(jtx::autofill)); require(flags(account, asfDefaultRipple)); } else { - apply(pay(master, account, amount), jtx::seq(jtx::autofill), fee(jtx::autofill), sig(jtx::autofill)); + apply( + pay(master, account, amount), + jtx::seq(jtx::autofill), + fee(jtx::autofill), + sig(jtx::autofill)); require(nflags(account, asfDefaultRipple)); } require(jtx::balance(account, amount)); @@ -284,7 +294,11 @@ void Env::trust(STAmount const& amount, Account const& account) { auto const start = balance(account); - apply(jtx::trust(account, amount), jtx::seq(jtx::autofill), fee(jtx::autofill), sig(jtx::autofill)); + apply( + jtx::trust(account, amount), + jtx::seq(jtx::autofill), + fee(jtx::autofill), + sig(jtx::autofill)); apply( pay(master, account, drops(current()->fees().base)), jtx::seq(jtx::autofill), @@ -378,8 +392,9 @@ Env::sign_and_submit(JTx const& jt, Json::Value params, std::source_location con // Use the provided parameters, and go straight // to the (RPC) client. assert(params.isObject()); - if (!params.isMember(jss::secret) && !params.isMember(jss::key_type) && !params.isMember(jss::seed) && - !params.isMember(jss::seed_hex) && !params.isMember(jss::passphrase)) + if (!params.isMember(jss::secret) && !params.isMember(jss::key_type) && + !params.isMember(jss::seed) && !params.isMember(jss::seed_hex) && + !params.isMember(jss::passphrase)) { params[jss::secret] = passphrase; } @@ -398,7 +413,11 @@ Env::sign_and_submit(JTx const& jt, Json::Value params, std::source_location con } void -Env::postconditions(JTx const& jt, ParsedResult const& parsed, Json::Value const& jr, std::source_location const& loc) +Env::postconditions( + JTx const& jt, + ParsedResult const& parsed, + Json::Value const& jr, + std::source_location const& loc) { auto const line = jt.testLine ? " (" + to_string(*jt.testLine) + ")" : ""; auto const locStr = std::string("(") + loc.file_name() + ":" + to_string(loc.line()) + ")"; @@ -407,28 +426,31 @@ Env::postconditions(JTx const& jt, ParsedResult const& parsed, Json::Value const (jt.ter && parsed.ter && !test.expect( *parsed.ter == *jt.ter, - "apply " + locStr + ": Got " + transToken(*parsed.ter) + " (" + transHuman(*parsed.ter) + "); Expected " + - transToken(*jt.ter) + " (" + transHuman(*jt.ter) + ")" + line)); + "apply " + locStr + ": Got " + transToken(*parsed.ter) + " (" + + transHuman(*parsed.ter) + "); Expected " + transToken(*jt.ter) + " (" + + transHuman(*jt.ter) + ")" + line)); using namespace std::string_literals; bad = (jt.rpcCode && !test.expect( parsed.rpcCode == jt.rpcCode->first && parsed.rpcMessage == jt.rpcCode->second, "apply " + locStr + ": Got RPC result "s + - (parsed.rpcCode ? RPC::get_error_info(*parsed.rpcCode).token.c_str() : "NO RESULT") + " (" + - parsed.rpcMessage + "); Expected " + RPC::get_error_info(jt.rpcCode->first).token.c_str() + " (" + + (parsed.rpcCode ? RPC::get_error_info(*parsed.rpcCode).token.c_str() + : "NO RESULT") + + " (" + parsed.rpcMessage + "); Expected " + + RPC::get_error_info(jt.rpcCode->first).token.c_str() + " (" + jt.rpcCode->second + ")" + line)) || bad; // If we have an rpcCode (just checked), then the rpcException check is // optional - the 'error' field may not be defined, but if it is, it must // match rpcError. - bad = - (jt.rpcException && - !test.expect( - (jt.rpcCode && parsed.rpcError.empty()) || - (parsed.rpcError == jt.rpcException->first && - (!jt.rpcException->second || parsed.rpcException == *jt.rpcException->second)), - "apply " + locStr + ": Got RPC result "s + parsed.rpcError + " (" + parsed.rpcException + "); Expected " + - jt.rpcException->first + " (" + jt.rpcException->second.value_or("n/a") + ")" + line)) || + bad = (jt.rpcException && + !test.expect( + (jt.rpcCode && parsed.rpcError.empty()) || + (parsed.rpcError == jt.rpcException->first && + (!jt.rpcException->second || parsed.rpcException == *jt.rpcException->second)), + "apply " + locStr + ": Got RPC result "s + parsed.rpcError + " (" + + parsed.rpcException + "); Expected " + jt.rpcException->first + " (" + + jt.rpcException->second.value_or("n/a") + ")" + line)) || bad; if (bad) { @@ -499,8 +521,9 @@ Env::autofill_sig(JTx& jt) // If the sig is still needed, get it here. if (!jt.fill_sig) return; - auto const account = jv.isMember(sfDelegate.jsonName) ? lookup(jv[sfDelegate.jsonName].asString()) - : lookup(jv[jss::Account].asString()); + auto const account = jv.isMember(sfDelegate.jsonName) + ? lookup(jv[sfDelegate.jsonName].asString()) + : lookup(jv[jss::Account].asString()); if (!app().checkSigs()) { jv[jss::SigningPubKey] = strHex(account.pk().slice()); @@ -526,7 +549,7 @@ Env::autofill(JTx& jt) if (jt.fill_netid) { - uint32_t networkID = app().config().NETWORK_ID; + uint32_t networkID = app().getNetworkIDService().getNetworkID(); if (!jv.isMember(jss::NetworkID) && networkID > 1024) jv[jss::NetworkID] = std::to_string(networkID); } diff --git a/src/test/jtx/impl/JSONRPCClient.cpp b/src/test/jtx/impl/JSONRPCClient.cpp index 34d0ea2f68..df41ed39be 100644 --- a/src/test/jtx/impl/JSONRPCClient.cpp +++ b/src/test/jtx/impl/JSONRPCClient.cpp @@ -35,7 +35,8 @@ class JSONRPCClient : public AbstractClient continue; using namespace boost::asio::ip; if (pp.ip && pp.ip->is_unspecified()) - *pp.ip = pp.ip->is_v6() ? address{address_v6::loopback()} : address{address_v4::loopback()}; + *pp.ip = pp.ip->is_v6() ? address{address_v6::loopback()} + : address{address_v4::loopback()}; if (!pp.port) Throw("Use fixConfigPorts with auto ports"); diff --git a/src/test/jtx/impl/Oracle.cpp b/src/test/jtx/impl/Oracle.cpp index c696011da5..c9d8c0ce27 100644 --- a/src/test/jtx/impl/Oracle.cpp +++ b/src/test/jtx/impl/Oracle.cpp @@ -99,8 +99,9 @@ Oracle::expectPrice(DataSeries const& series) const auto const& quoteAsset = o.getFieldCurrency(sfQuoteAsset); auto const& price = o.getFieldU64(sfAssetPrice); auto const& scale = o.getFieldU8(sfScale); - return baseAsset.getText() == std::get<0>(data) && quoteAsset.getText() == std::get<1>(data) && - price == std::get<2>(data) && scale == std::get<3>(data); + return baseAsset.getText() == std::get<0>(data) && + quoteAsset.getText() == std::get<1>(data) && price == std::get<2>(data) && + scale == std::get<3>(data); }) == leSeries.end()) return false; } @@ -199,7 +200,8 @@ Oracle::set(UpdateArg const& arg) if (arg.lastUpdateTime) { if (std::holds_alternative(*arg.lastUpdateTime)) - jv[jss::LastUpdateTime] = to_string(testStartTime.count() + std::get(*arg.lastUpdateTime)); + jv[jss::LastUpdateTime] = + to_string(testStartTime.count() + std::get(*arg.lastUpdateTime)); else toJson(jv[jss::LastUpdateTime], *arg.lastUpdateTime); } diff --git a/src/test/jtx/impl/TestHelpers.cpp b/src/test/jtx/impl/TestHelpers.cpp index d89dec456b..5e7a31adcd 100644 --- a/src/test/jtx/impl/TestHelpers.cpp +++ b/src/test/jtx/impl/TestHelpers.cpp @@ -62,7 +62,10 @@ STPathElement IPE(Issue const& iss) { return STPathElement( - STPathElement::typeCurrency | STPathElement::typeIssuer, xrpAccount(), iss.currency, iss.account); + STPathElement::typeCurrency | STPathElement::typeIssuer, + xrpAccount(), + iss.currency, + iss.account); } /******************************************************************************/ @@ -97,7 +100,8 @@ expectHolding(Env& env, AccountID const& account, STAmount const& value, bool de low.setIssuer(accountLow ? account : issue.account); high.setIssuer(accountLow ? issue.account : account); - expectDefaultTrustLine = sle->getFieldAmount(sfLowLimit) == low && sle->getFieldAmount(sfHighLimit) == high; + expectDefaultTrustLine = + sle->getFieldAmount(sfLowLimit) == low && sle->getFieldAmount(sfHighLimit) == high; } auto amount = sle->getFieldAmount(sfBalance); @@ -125,11 +129,16 @@ expectHolding(Env& env, AccountID const& account, None const&, MPTIssue const& m expectHolding(Env& env, AccountID const& account, None const& value) { return std::visit( - [&](auto const& issue) { return expectHolding(env, account, value, issue); }, value.asset.value()); + [&](auto const& issue) { return expectHolding(env, account, value, issue); }, + value.asset.value()); } [[nodiscard]] bool -expectOffers(Env& env, AccountID const& account, std::uint16_t size, std::vector const& toMatch) +expectOffers( + Env& env, + AccountID const& account, + std::uint16_t size, + std::vector const& toMatch) { std::uint16_t cnt = 0; std::uint16_t matched = 0; @@ -140,7 +149,8 @@ expectOffers(Env& env, AccountID const& account, std::uint16_t size, std::vector { ++cnt; if (std::find_if(toMatch.begin(), toMatch.end(), [&](auto const& a) { - return a.in == sle->getFieldAmount(sfTakerPays) && a.out == sle->getFieldAmount(sfTakerGets); + return a.in == sle->getFieldAmount(sfTakerPays) && + a.out == sle->getFieldAmount(sfTakerGets); }) != toMatch.end()) ++matched; } @@ -159,7 +169,11 @@ ledgerEntryRoot(Env& env, Account const& acct) } Json::Value -ledgerEntryState(Env& env, Account const& acct_a, Account const& acct_b, std::string const& currency) +ledgerEntryState( + Env& env, + Account const& acct_a, + Account const& acct_b, + std::string const& currency) { Json::Value jvParams; jvParams[jss::ledger_index] = "current"; @@ -341,7 +355,11 @@ del(AccountID const& account, uint256 const& brokerID, uint32_t flags) } Json::Value -coverDeposit(AccountID const& account, uint256 const& brokerID, STAmount const& amount, uint32_t flags) +coverDeposit( + AccountID const& account, + uint256 const& brokerID, + STAmount const& amount, + uint32_t flags) { Json::Value jv; jv[sfTransactionType] = jss::LoanBrokerCoverDeposit; @@ -353,7 +371,11 @@ coverDeposit(AccountID const& account, uint256 const& brokerID, STAmount const& } Json::Value -coverWithdraw(AccountID const& account, uint256 const& brokerID, STAmount const& amount, uint32_t flags) +coverWithdraw( + AccountID const& account, + uint256 const& brokerID, + STAmount const& amount, + uint32_t flags) { Json::Value jv; jv[sfTransactionType] = jss::LoanBrokerCoverWithdraw; @@ -381,7 +403,10 @@ coverClawback(AccountID const& account, std::uint32_t flags) namespace loan { Json::Value -set(AccountID const& account, uint256 const& loanBrokerID, Number principalRequested, std::uint32_t flags) +set(AccountID const& account, + uint256 const& loanBrokerID, + Number principalRequested, + std::uint32_t flags) { Json::Value jv; jv[sfTransactionType] = jss::LoanSet; diff --git a/src/test/jtx/impl/WSClient.cpp b/src/test/jtx/impl/WSClient.cpp index c1012b57a4..2b92eb5ec3 100644 --- a/src/test/jtx/impl/WSClient.cpp +++ b/src/test/jtx/impl/WSClient.cpp @@ -49,7 +49,8 @@ class WSClientImpl : public WSClient continue; using namespace boost::asio::ip; if (pp.ip && pp.ip->is_unspecified()) - *pp.ip = pp.ip->is_v6() ? address{address_v6::loopback()} : address{address_v4::loopback()}; + *pp.ip = pp.ip->is_v6() ? address{address_v6::loopback()} + : address{address_v4::loopback()}; if (!pp.port) Throw("Use fixConfigPorts with auto ports"); @@ -100,16 +101,17 @@ class WSClientImpl : public WSClient boost::asio::post(ios_, boost::asio::bind_executor(strand_, [this] { if (!peerClosed_) { - ws_.async_close({}, boost::asio::bind_executor(strand_, [&](error_code) { - try - { - stream_.cancel(); - } - catch (boost::system::system_error const&) - { - // ignored - } - })); + ws_.async_close( + {}, boost::asio::bind_executor(strand_, [&](error_code) { + try + { + stream_.cancel(); + } + catch (boost::system::system_error const&) + { + // ignored + } + })); } })); work_ = std::nullopt; @@ -134,10 +136,11 @@ public: auto const ep = getEndpoint(cfg, v2); stream_.connect(ep); ws_.set_option( - boost::beast::websocket::stream_base::decorator([&](boost::beast::websocket::request_type& req) { - for (auto const& h : headers) - req.set(h.first, h.second); - })); + boost::beast::websocket::stream_base::decorator( + [&](boost::beast::websocket::request_type& req) { + for (auto const& h : headers) + req.set(h.first, h.second); + })); ws_.handshake(ep.address().to_string() + ":" + std::to_string(ep.port()), "/"); ws_.async_read( rb_, @@ -179,7 +182,8 @@ public: ws_.write_some(true, buffer(s)); } - auto jv = findMsg(5s, [&](Json::Value const& jval) { return jval[jss::type] == jss::response; }); + auto jv = + findMsg(5s, [&](Json::Value const& jval) { return jval[jss::type] == jss::response; }); if (jv) { // Normalize JSON output @@ -215,7 +219,8 @@ public: } std::optional - findMsg(std::chrono::milliseconds const& timeout, std::function pred) override + findMsg(std::chrono::milliseconds const& timeout, std::function pred) + override { std::shared_ptr m; { @@ -268,7 +273,8 @@ private: } ws_.async_read( rb_, - boost::asio::bind_executor(strand_, std::bind(&WSClientImpl::on_read_msg, this, std::placeholders::_1))); + boost::asio::bind_executor( + strand_, std::bind(&WSClientImpl::on_read_msg, this, std::placeholders::_1))); } // Called when the read op terminates diff --git a/src/test/jtx/impl/amount.cpp b/src/test/jtx/impl/amount.cpp index 73dad7f48e..4952334fe8 100644 --- a/src/test/jtx/impl/amount.cpp +++ b/src/test/jtx/impl/amount.cpp @@ -28,7 +28,8 @@ operator<<(std::ostream&& os, } #endif -PrettyAmount::operator AnyAmount() const +PrettyAmount:: +operator AnyAmount() const { return {amount_}; } @@ -74,8 +75,8 @@ operator<<(std::ostream& os, PrettyAmount const& amount) } else if (amount.value().holds()) { - os << amount.value().getText() << "/" << to_string(amount.value().issue().currency) << "(" << amount.name() - << ")"; + os << amount.value().getText() << "/" << to_string(amount.value().issue().currency) << "(" + << amount.name() << ")"; } else { diff --git a/src/test/jtx/impl/attester.cpp b/src/test/jtx/impl/attester.cpp index 04b2a037c6..d4693e69fb 100644 --- a/src/test/jtx/impl/attester.cpp +++ b/src/test/jtx/impl/attester.cpp @@ -40,7 +40,14 @@ sign_create_account_attestation( AccountID const& dst) { auto const toSign = Attestations::AttestationCreateAccount::message( - bridge, sendingAccount, sendingAmount, rewardAmount, rewardAccount, wasLockingChainSend, createCount, dst); + bridge, + sendingAccount, + sendingAmount, + rewardAmount, + rewardAccount, + wasLockingChainSend, + createCount, + dst); return sign(pk, sk, makeSlice(toSign)); } diff --git a/src/test/jtx/impl/balance.cpp b/src/test/jtx/impl/balance.cpp index 1ebeeed437..a136b19bdb 100644 --- a/src/test/jtx/impl/balance.cpp +++ b/src/test/jtx/impl/balance.cpp @@ -44,7 +44,12 @@ doBalance(Env& env, AccountID const& account, bool none, STAmount const& value, } void -doBalance(Env& env, AccountID const& account, bool none, STAmount const& value, MPTIssue const& mptIssue) +doBalance( + Env& env, + AccountID const& account, + bool none, + STAmount const& value, + MPTIssue const& mptIssue) { auto const sle = env.le(keylet::mptoken(mptIssue.getMptID(), account)); if (none) @@ -62,7 +67,8 @@ void balance::operator()(Env& env) const { return std::visit( - [&](auto const& issue) { doBalance(env, account_.id(), none_, value_, issue); }, value_.asset().value()); + [&](auto const& issue) { doBalance(env, account_.id(), none_, value_, issue); }, + value_.asset().value()); } } // namespace jtx diff --git a/src/test/jtx/impl/creds.cpp b/src/test/jtx/impl/creds.cpp index 5a9ecfec59..e1018cc0e5 100644 --- a/src/test/jtx/impl/creds.cpp +++ b/src/test/jtx/impl/creds.cpp @@ -34,7 +34,11 @@ accept(jtx::Account const& subject, jtx::Account const& issuer, std::string_view } Json::Value -deleteCred(jtx::Account const& acc, jtx::Account const& subject, jtx::Account const& issuer, std::string_view credType) +deleteCred( + jtx::Account const& acc, + jtx::Account const& subject, + jtx::Account const& issuer, + std::string_view credType) { Json::Value jv; jv[jss::TransactionType] = jss::CredentialDelete; @@ -46,7 +50,11 @@ deleteCred(jtx::Account const& acc, jtx::Account const& subject, jtx::Account co } Json::Value -ledgerEntry(jtx::Env& env, jtx::Account const& subject, jtx::Account const& issuer, std::string_view credType) +ledgerEntry( + jtx::Env& env, + jtx::Account const& subject, + jtx::Account const& issuer, + std::string_view credType) { Json::Value jvParams; jvParams[jss::ledger_index] = jss::validated; diff --git a/src/test/jtx/impl/delegate.cpp b/src/test/jtx/impl/delegate.cpp index 312a3f2403..7cca9aa738 100644 --- a/src/test/jtx/impl/delegate.cpp +++ b/src/test/jtx/impl/delegate.cpp @@ -9,7 +9,9 @@ namespace jtx { namespace delegate { Json::Value -set(jtx::Account const& account, jtx::Account const& authorize, std::vector const& permissions) +set(jtx::Account const& account, + jtx::Account const& authorize, + std::vector const& permissions) { Json::Value jv; jv[jss::TransactionType] = jss::DelegateSet; diff --git a/src/test/jtx/impl/envconfig.cpp b/src/test/jtx/impl/envconfig.cpp index 1def778c69..31034f3b63 100644 --- a/src/test/jtx/impl/envconfig.cpp +++ b/src/test/jtx/impl/envconfig.cpp @@ -94,7 +94,8 @@ std::unique_ptr validator(std::unique_ptr cfg, std::string const& seed) { // If the config has valid validation keys then we run as a validator. - cfg->section(SECTION_VALIDATION_SEED).append(std::vector{seed.empty() ? defaultseed : seed}); + cfg->section(SECTION_VALIDATION_SEED) + .append(std::vector{seed.empty() ? defaultseed : seed}); return cfg; } @@ -119,7 +120,9 @@ addGrpcConfigWithSecureGateway(std::unique_ptr cfg, std::string const& s } std::unique_ptr -makeConfig(std::map extraTxQ, std::map extraVoting) +makeConfig( + std::map extraTxQ, + std::map extraVoting) { auto p = test::jtx::envconfig(); auto& section = p->section("transaction_queue"); diff --git a/src/test/jtx/impl/ledgerStateFixes.cpp b/src/test/jtx/impl/ledgerStateFixes.cpp index f1e6b6eda1..04860a5e3a 100644 --- a/src/test/jtx/impl/ledgerStateFixes.cpp +++ b/src/test/jtx/impl/ledgerStateFixes.cpp @@ -1,9 +1,8 @@ #include -#include - #include #include +#include namespace xrpl { namespace test { diff --git a/src/test/jtx/impl/mpt.cpp b/src/test/jtx/impl/mpt.cpp index f505bff740..4745b1a7a7 100644 --- a/src/test/jtx/impl/mpt.cpp +++ b/src/test/jtx/impl/mpt.cpp @@ -63,7 +63,12 @@ MPTTester::MPTTester(Env& env, Account const& issuer, MPTInit const& arg) create(*arg.create); } -MPTTester::MPTTester(Env& env, Account const& issuer, MPTID const& id, std::vector const& holders, bool close) +MPTTester::MPTTester( + Env& env, + Account const& issuer, + MPTID const& id, + std::vector const& holders, + bool close) : env_(env), issuer_(issuer), holders_(makeHolders(holders)), id_(id), close_(close) { } @@ -87,11 +92,15 @@ makeMPTCreate(MPTInitDef const& arg) } MPTTester::MPTTester(MPTInitDef const& arg) - : MPTTester{arg.env, arg.issuer, MPTInit{.fund = arg.fund, .close = arg.close, .create = makeMPTCreate(arg)}} + : MPTTester{ + arg.env, + arg.issuer, + MPTInit{.fund = arg.fund, .close = arg.close, .create = makeMPTCreate(arg)}} { } -MPTTester::operator MPT() const +MPTTester:: +operator MPT() const { if (!id_) Throw("MPT has not been created"); @@ -139,7 +148,8 @@ MPTTester::create(MPTCreate const& arg) if (submit(arg, jv) != tesSUCCESS) { // Verify issuance doesn't exist - env_.require(requireAny([&]() -> bool { return env_.le(keylet::mptIssuance(*id_)) == nullptr; })); + env_.require( + requireAny([&]() -> bool { return env_.le(keylet::mptIssuance(*id_)) == nullptr; })); id_.reset(); } @@ -196,7 +206,8 @@ MPTTester::destroy(MPTDestroy const& arg) { if (!arg.id && !id_) Throw("MPT has not been created"); - Json::Value jv = destroyJV({.issuer = arg.issuer ? arg.issuer : issuer_, .id = arg.id ? arg.id : id_}); + Json::Value jv = + destroyJV({.issuer = arg.issuer ? arg.issuer : issuer_, .id = arg.id ? arg.id : id_}); submit(arg, jv); } @@ -261,20 +272,23 @@ MPTTester::authorize(MPTAuthorize const& arg) forObject([&](SLEP const& sle) { return env_.test.BEAST_EXPECT(!sle); }, arg.account); } } - else if (arg.account && *arg.account != issuer_ && arg.flags.value_or(0) != tfMPTUnauthorize && id_) + else if ( + arg.account && *arg.account != issuer_ && arg.flags.value_or(0) != tfMPTUnauthorize && id_) { if (result == tecDUPLICATE) { // Verify that MPToken already exists - env_.require( - requireAny([&]() -> bool { return env_.le(keylet::mptoken(*id_, arg.account->id())) != nullptr; })); + env_.require(requireAny([&]() -> bool { + return env_.le(keylet::mptoken(*id_, arg.account->id())) != nullptr; + })); } else { // Verify MPToken doesn't exist if holder failed authorizing(unless // it already exists) - env_.require( - requireAny([&]() -> bool { return env_.le(keylet::mptoken(*id_, arg.account->id())) == nullptr; })); + env_.require(requireAny([&]() -> bool { + return env_.le(keylet::mptoken(*id_, arg.account->id())) == nullptr; + })); } } } @@ -394,7 +408,9 @@ MPTTester::set(MPTSet const& arg) } bool -MPTTester::forObject(std::function const& cb, std::optional const& holder_) const +MPTTester::forObject( + std::function const& cb, + std::optional const& holder_) const { if (!id_) Throw("MPT has not been created"); @@ -417,13 +433,15 @@ MPTTester::checkDomainID(std::optional expected) const [[nodiscard]] bool MPTTester::checkMPTokenAmount(Account const& holder_, std::int64_t expectedAmount) const { - return forObject([&](SLEP const& sle) { return expectedAmount == (*sle)[sfMPTAmount]; }, holder_); + return forObject( + [&](SLEP const& sle) { return expectedAmount == (*sle)[sfMPTAmount]; }, holder_); } [[nodiscard]] bool MPTTester::checkMPTokenOutstandingAmount(std::int64_t expectedAmount) const { - return forObject([&](SLEP const& sle) { return expectedAmount == (*sle)[sfOutstandingAmount]; }); + return forObject( + [&](SLEP const& sle) { return expectedAmount == (*sle)[sfOutstandingAmount]; }); } [[nodiscard]] bool @@ -445,7 +463,8 @@ MPTTester::checkMetadata(std::string const& metadata) const [[nodiscard]] bool MPTTester::isMetadataPresent() const { - return forObject([&](SLEP const& sle) -> bool { return sle->isFieldPresent(sfMPTokenMetadata); }); + return forObject( + [&](SLEP const& sle) -> bool { return sle->isFieldPresent(sfMPTokenMetadata); }); } [[nodiscard]] bool @@ -479,7 +498,10 @@ MPTTester::pay( auto const outstandingAmt = getBalance(issuer_); if (credentials) - env_(jtx::pay(src, dest, mpt(amount)), ter(err.value_or(tesSUCCESS)), credentials::ids(*credentials)); + env_( + jtx::pay(src, dest, mpt(amount)), + ter(err.value_or(tesSUCCESS)), + credentials::ids(*credentials)); else env_(jtx::pay(src, dest, mpt(amount)), ter(err.value_or(tesSUCCESS))); @@ -510,7 +532,11 @@ MPTTester::pay( } void -MPTTester::claw(Account const& issuer, Account const& holder, std::int64_t amount, std::optional err) +MPTTester::claw( + Account const& issuer, + Account const& holder, + std::int64_t amount, + std::optional err) { if (!id_) Throw("MPT has not been created"); @@ -534,7 +560,8 @@ MPTTester::mpt(std::int64_t amount) const return xrpl::test::jtx::MPT(issuer_.name(), *id_)(amount); } -MPTTester::operator Asset() const +MPTTester:: +operator Asset() const { if (!id_) Throw("MPT has not been created"); diff --git a/src/test/jtx/impl/offer.cpp b/src/test/jtx/impl/offer.cpp index bbcfbf07c1..251b659f3b 100644 --- a/src/test/jtx/impl/offer.cpp +++ b/src/test/jtx/impl/offer.cpp @@ -7,7 +7,11 @@ namespace test { namespace jtx { Json::Value -offer(Account const& account, STAmount const& takerPays, STAmount const& takerGets, std::uint32_t flags) +offer( + Account const& account, + STAmount const& takerPays, + STAmount const& takerGets, + std::uint32_t flags) { Json::Value jv; jv[jss::Account] = account.human(); diff --git a/src/test/jtx/impl/owners.cpp b/src/test/jtx/impl/owners.cpp index ee6efc171c..53f2302143 100644 --- a/src/test/jtx/impl/owners.cpp +++ b/src/test/jtx/impl/owners.cpp @@ -15,7 +15,11 @@ owned_count_of(ReadView const& view, AccountID const& id, LedgerEntryType type) } void -owned_count_helper(test::jtx::Env& env, AccountID const& id, LedgerEntryType type, std::uint32_t value) +owned_count_helper( + test::jtx::Env& env, + AccountID const& id, + LedgerEntryType type, + std::uint32_t value) { env.test.expect(owned_count_of(*env.current(), id, type) == value); } diff --git a/src/test/jtx/impl/permissioned_domains.cpp b/src/test/jtx/impl/permissioned_domains.cpp index fb802cf084..fffcaa91a1 100644 --- a/src/test/jtx/impl/permissioned_domains.cpp +++ b/src/test/jtx/impl/permissioned_domains.cpp @@ -59,7 +59,8 @@ getObjects(Account const& account, Env& env, bool withType) if (withType) { // impossible to get there Throw( - "Invalid object type: " + object["LedgerEntryType"].asString()); // LCOV_EXCL_LINE + "Invalid object type: " + + object["LedgerEntryType"].asString()); // LCOV_EXCL_LINE } continue; } @@ -95,7 +96,9 @@ objectExists(uint256 const& objID, Env& env) // Extract credentials from account_object object Credentials -credentialsFromJson(Json::Value const& object, std::unordered_map const& human2Acc) +credentialsFromJson( + Json::Value const& object, + std::unordered_map const& human2Acc) { Credentials ret; Json::Value credentials(Json::arrayValue); @@ -133,7 +136,8 @@ getNewDomain(std::shared_ptr const& meta) for (auto const& node : a) { - if (!node.isMember("CreatedNode") || node["CreatedNode"]["LedgerEntryType"] != "PermissionedDomain") + if (!node.isMember("CreatedNode") || + node["CreatedNode"]["LedgerEntryType"] != "PermissionedDomain") { continue; } diff --git a/src/test/jtx/impl/quality2.cpp b/src/test/jtx/impl/quality2.cpp index bbd0cff319..c202592b9d 100644 --- a/src/test/jtx/impl/quality2.cpp +++ b/src/test/jtx/impl/quality2.cpp @@ -7,12 +7,14 @@ namespace xrpl { namespace test { namespace jtx { -qualityInPercent::qualityInPercent(double percent) : qIn_(static_cast((percent / 100) * QUALITY_ONE)) +qualityInPercent::qualityInPercent(double percent) + : qIn_(static_cast((percent / 100) * QUALITY_ONE)) { assert(percent <= 400 && percent >= 0); } -qualityOutPercent::qualityOutPercent(double percent) : qOut_(static_cast((percent / 100) * QUALITY_ONE)) +qualityOutPercent::qualityOutPercent(double percent) + : qOut_(static_cast((percent / 100) * QUALITY_ONE)) { assert(percent <= 400 && percent >= 0); } diff --git a/src/test/jtx/impl/token.cpp b/src/test/jtx/impl/token.cpp index 172bd75bc7..59f8c822fb 100644 --- a/src/test/jtx/impl/token.cpp +++ b/src/test/jtx/impl/token.cpp @@ -1,10 +1,9 @@ #include #include -#include - #include #include +#include namespace xrpl { namespace test { @@ -70,7 +69,8 @@ getID( // We must add issuer's FirstNFTokenSequence to offset the starting NFT // sequence number. nftSeq += env.le(issuer)->at(~sfFirstNFTokenSequence).value_or(env.seq(issuer)); - return xrpl::NFTokenMint::createNFTokenID(flags, xferFee, issuer, nft::toTaxon(nfTokenTaxon), nftSeq); + return xrpl::NFTokenMint::createNFTokenID( + flags, xferFee, issuer, nft::toTaxon(nfTokenTaxon), nftSeq); } Json::Value @@ -167,7 +167,10 @@ acceptSellOffer(jtx::Account const& account, uint256 const& offerIndex) } Json::Value -brokerOffers(jtx::Account const& account, uint256 const& buyOfferIndex, uint256 const& sellOfferIndex) +brokerOffers( + jtx::Account const& account, + uint256 const& buyOfferIndex, + uint256 const& sellOfferIndex) { Json::Value jv; jv[sfAccount.jsonName] = account.human(); diff --git a/src/test/jtx/impl/xchain_bridge.cpp b/src/test/jtx/impl/xchain_bridge.cpp index 0f78ed3029..dfd7f0ba96 100644 --- a/src/test/jtx/impl/xchain_bridge.cpp +++ b/src/test/jtx/impl/xchain_bridge.cpp @@ -183,7 +183,15 @@ claim_attestation( auto const& pk = signer.account.pk(); auto const& sk = signer.account.sk(); auto const sig = sign_claim_attestation( - pk, sk, stBridge, sendingAccount, sendingAmount.value, rewardAccount, wasLockingChainSend, claimID, dst); + pk, + sk, + stBridge, + sendingAccount, + sendingAmount.value, + rewardAccount, + wasLockingChainSend, + claimID, + dst); Json::Value result; @@ -249,7 +257,8 @@ create_account_attestation( result[sfAttestationRewardAccount.getJsonName()] = toBase58(rewardAccount); result[sfWasLockingChainSend.getJsonName()] = wasLockingChainSend ? 1 : 0; - result[sfXChainAccountCreateCount.getJsonName()] = STUInt64{createCount}.getJson(JsonOptions::none); + result[sfXChainAccountCreateCount.getJsonName()] = + STUInt64{createCount}.getJson(JsonOptions::none); result[sfDestination.getJsonName()] = toBase58(dst); result[sfSignatureReward.getJsonName()] = rewardAmount.value.getJson(JsonOptions::none); @@ -360,7 +369,8 @@ XChainBridgeObjects::XChainBridgeObjects() for (int i = 0; i < numSigners; ++i) { using namespace std::literals; - auto const a = Account("signer_"s + std::to_string(i), (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); + auto const a = Account( + "signer_"s + std::to_string(i), (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); result.emplace_back(a); } return result; @@ -372,7 +382,9 @@ XChainBridgeObjects::XChainBridgeObjects() for (int i = 0; i < numSigners; ++i) { using namespace std::literals; - auto const a = Account("alt_signer_"s + std::to_string(i), (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); + auto const a = Account( + "alt_signer_"s + std::to_string(i), + (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); result.emplace_back(a); } return result; @@ -402,9 +414,11 @@ XChainBridgeObjects::XChainBridgeObjects() , split_reward_quorum(divide(reward, STAmount(UT_XCHAIN_DEFAULT_QUORUM), reward.issue())) , split_reward_everyone(divide(reward, STAmount(UT_XCHAIN_DEFAULT_NUM_SIGNERS), reward.issue())) , tiny_reward(drops(37)) - , tiny_reward_split((divide(tiny_reward, STAmount(UT_XCHAIN_DEFAULT_QUORUM), tiny_reward.issue()))) + , tiny_reward_split( + (divide(tiny_reward, STAmount(UT_XCHAIN_DEFAULT_QUORUM), tiny_reward.issue()))) , tiny_reward_remainder( - tiny_reward - multiply(tiny_reward_split, STAmount(UT_XCHAIN_DEFAULT_QUORUM), tiny_reward.issue())) + tiny_reward - + multiply(tiny_reward_split, STAmount(UT_XCHAIN_DEFAULT_QUORUM), tiny_reward.issue())) , one_xrp(XRP(1)) , xrp_dust(divide(one_xrp, STAmount(10000), one_xrp.issue())) { diff --git a/src/test/jtx/mpt.h b/src/test/jtx/mpt.h index 510248240d..3368d129c1 100644 --- a/src/test/jtx/mpt.h +++ b/src/test/jtx/mpt.h @@ -24,7 +24,10 @@ private: std::optional holder_; public: - mptflags(MPTTester& tester, std::uint32_t flags, std::optional const& holder = std::nullopt) + mptflags( + MPTTester& tester, + std::uint32_t flags, + std::optional const& holder = std::nullopt) : tester_(tester), flags_(flags), holder_(holder) { } @@ -210,7 +213,8 @@ public: checkMPTokenOutstandingAmount(std::int64_t expectedAmount) const; [[nodiscard]] bool - checkFlags(uint32_t const expectedFlags, std::optional const& holder = std::nullopt) const; + checkFlags(uint32_t const expectedFlags, std::optional const& holder = std::nullopt) + const; [[nodiscard]] bool checkMetadata(std::string const& metadata) const; @@ -240,7 +244,11 @@ public: std::optional> credentials = std::nullopt); void - claw(Account const& issuer, Account const& holder, std::int64_t amount, std::optional err = std::nullopt); + claw( + Account const& issuer, + Account const& holder, + std::int64_t amount, + std::optional err = std::nullopt); PrettyAmount mpt(std::int64_t amount) const; @@ -267,8 +275,9 @@ public: private: using SLEP = SLE::const_pointer; bool - forObject(std::function const& cb, std::optional const& holder = std::nullopt) - const; + forObject( + std::function const& cb, + std::optional const& holder = std::nullopt) const; template TER diff --git a/src/test/jtx/multisign.h b/src/test/jtx/multisign.h index 3bbf43bb05..56d0b10906 100644 --- a/src/test/jtx/multisign.h +++ b/src/test/jtx/multisign.h @@ -50,7 +50,8 @@ public: /// a subfield. static constexpr SField* const topLevel = nullptr; - msig(SField const* subField_, std::vector signers_) : signers(std::move(signers_)), subField(subField_) + msig(SField const* subField_, std::vector signers_) + : signers(std::move(signers_)), subField(subField_) { sortSigners(signers); } @@ -66,21 +67,27 @@ public: template requires std::convertible_to explicit msig(SField const* subField_, AccountType&& a0, Accounts&&... aN) - : msig{subField_, std::vector{std::forward(a0), std::forward(aN)...}} + : msig{ + subField_, + std::vector{std::forward(a0), std::forward(aN)...}} { } template requires std::convertible_to explicit msig(SField const& subField_, AccountType&& a0, Accounts&&... aN) - : msig{&subField_, std::vector{std::forward(a0), std::forward(aN)...}} + : msig{ + &subField_, + std::vector{std::forward(a0), std::forward(aN)...}} { } template requires(std::convertible_to && !std::is_same_v) explicit msig(AccountType&& a0, Accounts&&... aN) - : msig{topLevel, std::vector{std::forward(a0), std::forward(aN)...}} + : msig{ + topLevel, + std::vector{std::forward(a0), std::forward(aN)...}} { } diff --git a/src/test/jtx/offer.h b/src/test/jtx/offer.h index dab15a4c8c..0fad9ec6dc 100644 --- a/src/test/jtx/offer.h +++ b/src/test/jtx/offer.h @@ -11,7 +11,11 @@ namespace jtx { /** Create an offer. */ Json::Value -offer(Account const& account, STAmount const& takerPays, STAmount const& takerGets, std::uint32_t flags = 0); +offer( + Account const& account, + STAmount const& takerPays, + STAmount const& takerGets, + std::uint32_t flags = 0); /** Cancel an offer. */ Json::Value diff --git a/src/test/jtx/owners.h b/src/test/jtx/owners.h index 87fa26417a..785a9347dd 100644 --- a/src/test/jtx/owners.h +++ b/src/test/jtx/owners.h @@ -16,7 +16,11 @@ std::uint32_t owned_count_of(ReadView const& view, AccountID const& id, LedgerEntryType type); void -owned_count_helper(test::jtx::Env& env, AccountID const& id, LedgerEntryType type, std::uint32_t value); +owned_count_helper( + test::jtx::Env& env, + AccountID const& id, + LedgerEntryType type, + std::uint32_t value); } // namespace detail diff --git a/src/test/jtx/paths.h b/src/test/jtx/paths.h index c4e69fe3f3..6522364e14 100644 --- a/src/test/jtx/paths.h +++ b/src/test/jtx/paths.h @@ -19,7 +19,8 @@ private: unsigned int limit_; public: - paths(Issue const& in, int depth = 7, unsigned int limit = 4) : in_(in), depth_(depth), limit_(limit) + paths(Issue const& in, int depth = 7, unsigned int limit = 4) + : in_(in), depth_(depth), limit_(limit) { } diff --git a/src/test/jtx/permissioned_domains.h b/src/test/jtx/permissioned_domains.h index ff8ab129ae..bf67722c9c 100644 --- a/src/test/jtx/permissioned_domains.h +++ b/src/test/jtx/permissioned_domains.h @@ -16,7 +16,10 @@ using Credentials = std::vector; // helpers // Make json for PermissionedDomainSet transaction Json::Value -setTx(AccountID const& account, Credentials const& credentials, std::optional domain = std::nullopt); +setTx( + AccountID const& account, + Credentials const& credentials, + std::optional domain = std::nullopt); // Make json for PermissionedDomainDelete transaction Json::Value @@ -32,7 +35,9 @@ objectExists(uint256 const& objID, Env& env); // Extract credentials from account_object object Credentials -credentialsFromJson(Json::Value const& object, std::unordered_map const& human2Acc); +credentialsFromJson( + Json::Value const& object, + std::unordered_map const& human2Acc); // Sort credentials the same way as PermissionedDomainSet Credentials diff --git a/src/test/jtx/rpc.h b/src/test/jtx/rpc.h index 6946cbc4e1..bbdecf1519 100644 --- a/src/test/jtx/rpc.h +++ b/src/test/jtx/rpc.h @@ -21,7 +21,8 @@ private: public: /// If there's an error code, we expect an error message - explicit rpc(error_code_i code, std::optional m = {}) : code_(code), errorMessage_(m) + explicit rpc(error_code_i code, std::optional m = {}) + : code_(code), errorMessage_(m) { } diff --git a/src/test/jtx/sig.h b/src/test/jtx/sig.h index ab22a46c69..0ed59de50e 100644 --- a/src/test/jtx/sig.h +++ b/src/test/jtx/sig.h @@ -39,7 +39,8 @@ public: { } - explicit sig(SField const* subField, Account const& account) : subField_(subField), account_(account) + explicit sig(SField const* subField, Account const& account) + : subField_(subField), account_(account) { } diff --git a/src/test/jtx/token.h b/src/test/jtx/token.h index f6d562587a..3f4a3f75a3 100644 --- a/src/test/jtx/token.h +++ b/src/test/jtx/token.h @@ -182,7 +182,10 @@ acceptSellOffer(jtx::Account const& account, uint256 const& offerIndex); /** Broker two NFToken offers. */ Json::Value -brokerOffers(jtx::Account const& account, uint256 const& buyOfferIndex, uint256 const& sellOfferIndex); +brokerOffers( + jtx::Account const& account, + uint256 const& buyOfferIndex, + uint256 const& sellOfferIndex); /** Sets the optional NFTokenBrokerFee field in a brokerOffer transaction. */ class brokerFee diff --git a/src/test/jtx/trust.h b/src/test/jtx/trust.h index 462538854b..afea256382 100644 --- a/src/test/jtx/trust.h +++ b/src/test/jtx/trust.h @@ -18,7 +18,10 @@ Json::Value trust(Account const& account, STAmount const& amount, Account const& peer, std::uint32_t flags); Json::Value -claw(Account const& account, STAmount const& amount, std::optional const& mptHolder = std::nullopt); +claw( + Account const& account, + STAmount const& amount, + std::optional const& mptHolder = std::nullopt); } // namespace jtx } // namespace test diff --git a/src/test/jtx/xchain_bridge.h b/src/test/jtx/xchain_bridge.h index cdacede234..698426c59c 100644 --- a/src/test/jtx/xchain_bridge.h +++ b/src/test/jtx/xchain_bridge.h @@ -70,7 +70,11 @@ sidechain_xchain_account_create( AnyAmount const& xChainFee); Json::Value -sidechain_xchain_account_claim(Account const& acc, Json::Value const& bridge, Account const& dst, AnyAmount const& amt); +sidechain_xchain_account_claim( + Account const& acc, + Json::Value const& bridge, + Account const& dst, + AnyAmount const& amt); Json::Value claim_attestation( @@ -201,7 +205,18 @@ struct XChainBridgeObjects std::size_t const fromIdx = 0) { return create_account_attestations( - scAttester, jvb, mcCarol, amt, reward, payees, true, createCount, dst, signers, numAtts, fromIdx); + scAttester, + jvb, + mcCarol, + amt, + reward, + payees, + true, + createCount, + dst, + signers, + numAtts, + fromIdx); } Json::Value @@ -211,7 +226,8 @@ struct XChainBridgeObjects STAmount const& _reward = XRP(1), std::optional const& minAccountCreate = std::nullopt) { - return bridge_create(acc, bridge == Json::nullValue ? jvb : bridge, _reward, minAccountCreate); + return bridge_create( + acc, bridge == Json::nullValue ? jvb : bridge, _reward, minAccountCreate); } }; diff --git a/src/test/ledger/BookDirs_test.cpp b/src/test/ledger/BookDirs_test.cpp index 45e585d68d..50f1bb46ba 100644 --- a/src/test/ledger/BookDirs_test.cpp +++ b/src/test/ledger/BookDirs_test.cpp @@ -33,7 +33,8 @@ struct BookDirs_test : public beast::unit_test::suite { env(offer("alice", Account("alice")["USD"](50), XRP(10))); - auto d = BookDirs(*env.current(), Book(Account("alice")["USD"].issue(), xrpIssue(), std::nullopt)); + auto d = BookDirs( + *env.current(), Book(Account("alice")["USD"].issue(), xrpIssue(), std::nullopt)); BEAST_EXPECT(std::distance(d.begin(), d.end()) == 1); } @@ -47,7 +48,8 @@ struct BookDirs_test : public beast::unit_test::suite env.trust(Account("bob")["CNY"](10), "alice"); env(pay("bob", "alice", Account("bob")["CNY"](10))); env(offer("alice", USD(50), Account("bob")["CNY"](10))); - auto d = BookDirs(*env.current(), Book(USD.issue(), Account("bob")["CNY"].issue(), std::nullopt)); + auto d = BookDirs( + *env.current(), Book(USD.issue(), Account("bob")["CNY"].issue(), std::nullopt)); BEAST_EXPECT(std::distance(d.begin(), d.end()) == 1); } diff --git a/src/test/ledger/Directory_test.cpp b/src/test/ledger/Directory_test.cpp index 0774390490..8e7ba38c53 100644 --- a/src/test/ledger/Directory_test.cpp +++ b/src/test/ledger/Directory_test.cpp @@ -449,7 +449,9 @@ struct Directory_test : public beast::unit_test::suite // All of the other directories, including the order // book, did get touched, so they should have those // fields - BEAST_EXPECT(directory.isMember("PreviousTxnID") && directory["PreviousTxnID"].asString() == txID); + BEAST_EXPECT( + directory.isMember("PreviousTxnID") && + directory["PreviousTxnID"].asString() == txID); BEAST_EXPECT( directory.isMember("PreviousTxnLgrSeq") && directory["PreviousTxnLgrSeq"].asUInt() == ledgerSeq); @@ -521,10 +523,12 @@ struct Directory_test : public beast::unit_test::suite env.close(); }; - testCase(testable_amendments() - fixDirectoryLimit, [this](Env&) -> std::tuple { - testcase("directory full without fixDirectoryLimit"); - return {dirNodeMaxPages - 1, true}; - }); + testCase( + testable_amendments() - fixDirectoryLimit, + [this](Env&) -> std::tuple { + testcase("directory full without fixDirectoryLimit"); + return {dirNodeMaxPages - 1, true}; + }); testCase( testable_amendments(), // [this](Env&) -> std::tuple { diff --git a/src/test/ledger/PaymentSandbox_test.cpp b/src/test/ledger/PaymentSandbox_test.cpp index cd5b1d1c19..4be5827630 100644 --- a/src/test/ledger/PaymentSandbox_test.cpp +++ b/src/test/ledger/PaymentSandbox_test.cpp @@ -66,7 +66,9 @@ class PaymentSandbox_test : public beast::unit_test::suite PathSet paths(Path(gw1, USD_gw2, gw2), Path(gw2, USD_gw1, gw1)); - env(pay(snd, rcv, any(USD_gw1(4))), json(paths.json()), txflags(tfNoRippleDirect | tfPartialPayment)); + env(pay(snd, rcv, any(USD_gw1(4))), + json(paths.json()), + txflags(tfNoRippleDirect | tfPartialPayment)); env.require(balance("rcv", USD_gw1(0))); env.require(balance("rcv", USD_gw2(2))); @@ -103,13 +105,15 @@ class PaymentSandbox_test : public beast::unit_test::suite ApplyViewImpl av(&*env.current(), tapNONE); auto const iss = USD_gw1.issue(); - auto const startingAmount = accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); + auto const startingAmount = + accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); { auto r = accountSend(av, gw1, alice, toCredit, j); BEAST_EXPECT(r == tesSUCCESS); } BEAST_EXPECT( - accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount + toCredit); + accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == + startingAmount + toCredit); { auto r = accountSend(av, alice, gw1, toDebit, j); BEAST_EXPECT(r == tesSUCCESS); @@ -124,11 +128,13 @@ class PaymentSandbox_test : public beast::unit_test::suite ApplyViewImpl av(&*env.current(), tapNONE); auto const iss = USD_gw1.issue(); - auto const startingAmount = accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); + auto const startingAmount = + accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); rippleCredit(av, gw1, alice, toCredit, true, j); BEAST_EXPECT( - accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount + toCredit); + accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == + startingAmount + toCredit); rippleCredit(av, alice, gw1, toDebit, true, j); BEAST_EXPECT( @@ -142,20 +148,24 @@ class PaymentSandbox_test : public beast::unit_test::suite PaymentSandbox pv(&av); auto const iss = USD_gw1.issue(); - auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); + auto const startingAmount = + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); { auto r = accountSend(pv, gw1, alice, toCredit, j); BEAST_EXPECT(r == tesSUCCESS); } - BEAST_EXPECT(accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount); + BEAST_EXPECT( + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == + startingAmount); { auto r = accountSend(pv, alice, gw1, toDebit, j); BEAST_EXPECT(r == tesSUCCESS); } BEAST_EXPECT( - accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount - toDebit); + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == + startingAmount - toDebit); } { @@ -164,10 +174,13 @@ class PaymentSandbox_test : public beast::unit_test::suite PaymentSandbox pv(&av); auto const iss = USD_gw1.issue(); - auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); + auto const startingAmount = + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); rippleCredit(pv, gw1, alice, toCredit, true, j); - BEAST_EXPECT(accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount); + BEAST_EXPECT( + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == + startingAmount); } { @@ -176,11 +189,13 @@ class PaymentSandbox_test : public beast::unit_test::suite PaymentSandbox pv(&av); auto const iss = USD_gw1.issue(); - auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); + auto const startingAmount = + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); BEAST_EXPECT(redeemIOU(pv, alice, toDebit, iss, j) == tesSUCCESS); BEAST_EXPECT( - accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount - toDebit); + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == + startingAmount - toDebit); } { @@ -189,10 +204,13 @@ class PaymentSandbox_test : public beast::unit_test::suite PaymentSandbox pv(&av); auto const iss = USD_gw1.issue(); - auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); + auto const startingAmount = + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); BEAST_EXPECT(issueIOU(pv, alice, toCredit, iss, j) == tesSUCCESS); - BEAST_EXPECT(accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount); + BEAST_EXPECT( + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == + startingAmount); } { @@ -201,22 +219,29 @@ class PaymentSandbox_test : public beast::unit_test::suite PaymentSandbox pv(&av); auto const iss = USD_gw1.issue(); - auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); + auto const startingAmount = + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); { auto r = accountSend(pv, gw1, alice, toCredit, j); BEAST_EXPECT(r == tesSUCCESS); } - BEAST_EXPECT(accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount); + BEAST_EXPECT( + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == + startingAmount); { PaymentSandbox pv2(&pv); - BEAST_EXPECT(accountHolds(pv2, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount); + BEAST_EXPECT( + accountHolds(pv2, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == + startingAmount); { auto r = accountSend(pv2, gw1, alice, toCredit, j); BEAST_EXPECT(r == tesSUCCESS); } - BEAST_EXPECT(accountHolds(pv2, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount); + BEAST_EXPECT( + accountHolds(pv2, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == + startingAmount); } { @@ -224,7 +249,8 @@ class PaymentSandbox_test : public beast::unit_test::suite BEAST_EXPECT(r == tesSUCCESS); } BEAST_EXPECT( - accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount - toDebit); + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == + startingAmount - toDebit); } } @@ -246,8 +272,10 @@ class PaymentSandbox_test : public beast::unit_test::suite auto const USD = gw["USD"]; auto const issue = USD.issue(); - STAmount tinyAmt(issue, STAmount::cMinValue, STAmount::cMinOffset + 1, false, STAmount::unchecked{}); - STAmount hugeAmt(issue, STAmount::cMaxValue, STAmount::cMaxOffset - 1, false, STAmount::unchecked{}); + STAmount tinyAmt( + issue, STAmount::cMinValue, STAmount::cMinOffset + 1, false, STAmount::unchecked{}); + STAmount hugeAmt( + issue, STAmount::cMaxValue, STAmount::cMaxOffset - 1, false, STAmount::unchecked{}); ApplyViewImpl av(&*env.current(), tapNONE); PaymentSandbox pv(&av); @@ -261,8 +289,10 @@ class PaymentSandbox_test : public beast::unit_test::suite testcase("Reserve"); using namespace jtx; - auto accountFundsXRP = [](ReadView const& view, AccountID const& id, beast::Journal j) -> XRPAmount { - return toAmount(accountHolds(view, id, xrpCurrency(), xrpAccount(), fhZERO_IF_FROZEN, j)); + auto accountFundsXRP = + [](ReadView const& view, AccountID const& id, beast::Journal j) -> XRPAmount { + return toAmount( + accountHolds(view, id, xrpCurrency(), xrpAccount(), fhZERO_IF_FROZEN, j)); }; auto reserve = [](jtx::Env& env, std::uint32_t count) -> XRPAmount { diff --git a/src/test/ledger/SkipList_test.cpp b/src/test/ledger/SkipList_test.cpp index 2f4a231c14..8430db3904 100644 --- a/src/test/ledger/SkipList_test.cpp +++ b/src/test/ledger/SkipList_test.cpp @@ -17,8 +17,8 @@ class SkipList_test : public beast::unit_test::suite std::vector> history; { Config config; - auto prev = - std::make_shared(create_genesis, config, std::vector{}, env.app().getNodeFamily()); + auto prev = std::make_shared( + create_genesis, config, std::vector{}, env.app().getNodeFamily()); history.push_back(prev); for (auto i = 0; i < 1023; ++i) { @@ -43,7 +43,8 @@ class SkipList_test : public beast::unit_test::suite { for (auto n = i; n != std::next(i, (*i)->header().seq - 256 > 1 ? 257 : 256); ++n) { - BEAST_EXPECT(hashOfSeq(**i, (*n)->header().seq, env.journal) == (*n)->header().hash); + BEAST_EXPECT( + hashOfSeq(**i, (*n)->header().seq, env.journal) == (*n)->header().hash); } // edge case accessing beyond 256 @@ -55,7 +56,8 @@ class SkipList_test : public beast::unit_test::suite { for (auto n = std::next(i, 512); n != history.crend(); n += 256) { - BEAST_EXPECT(hashOfSeq(**i, (*n)->header().seq, env.journal) == (*n)->header().hash); + BEAST_EXPECT( + hashOfSeq(**i, (*n)->header().seq, env.journal) == (*n)->header().hash); } } } diff --git a/src/test/ledger/View_test.cpp b/src/test/ledger/View_test.cpp index 33813e135e..80ecdba2d5 100644 --- a/src/test/ledger/View_test.cpp +++ b/src/test/ledger/View_test.cpp @@ -113,8 +113,8 @@ class View_test : public beast::unit_test::suite using namespace jtx; Env env(*this); Config config; - std::shared_ptr const genesis = - std::make_shared(create_genesis, config, std::vector{}, env.app().getNodeFamily()); + std::shared_ptr const genesis = std::make_shared( + create_genesis, config, std::vector{}, env.app().getNodeFamily()); auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); wipe(*ledger); ReadView& v = *ledger; @@ -376,8 +376,8 @@ class View_test : public beast::unit_test::suite using namespace jtx; Env env(*this); Config config; - std::shared_ptr const genesis = - std::make_shared(create_genesis, config, std::vector{}, env.app().getNodeFamily()); + std::shared_ptr const genesis = std::make_shared( + create_genesis, config, std::vector{}, env.app().getNodeFamily()); auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); auto setup = [&ledger](std::vector const& vec) { @@ -580,8 +580,8 @@ class View_test : public beast::unit_test::suite using namespace jtx; Env env(*this); Config config; - std::shared_ptr const genesis = - std::make_shared(create_genesis, config, std::vector{}, env.app().getNodeFamily()); + std::shared_ptr const genesis = std::make_shared( + create_genesis, config, std::vector{}, env.app().getNodeFamily()); auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); auto setup123 = [&ledger, this]() { // erase middle element @@ -732,7 +732,10 @@ class View_test : public beast::unit_test::suite env.close(); // Alice's USD balance should be zero if frozen. - BEAST_EXPECT(USD(0) == accountHolds(*env.closed(), alice, USD.currency, gw, fhZERO_IF_FROZEN, env.journal)); + BEAST_EXPECT( + USD(0) == + accountHolds( + *env.closed(), alice, USD.currency, gw, fhZERO_IF_FROZEN, env.journal)); // Thaw gw and try again. env(fclear(gw, asfGlobalFreeze)); @@ -749,12 +752,16 @@ class View_test : public beast::unit_test::suite env.close(); // Bob's balance should be zero if frozen. - BEAST_EXPECT(USD(0) == accountHolds(*env.closed(), bob, USD.currency, gw, fhZERO_IF_FROZEN, env.journal)); + BEAST_EXPECT( + USD(0) == + accountHolds(*env.closed(), bob, USD.currency, gw, fhZERO_IF_FROZEN, env.journal)); // gw thaws bob's trust line. bob gets his money back. env(trust(gw, USD(100), bob, tfClearFreeze)); env.close(); - BEAST_EXPECT(USD(50) == accountHolds(*env.closed(), bob, USD.currency, gw, fhZERO_IF_FROZEN, env.journal)); + BEAST_EXPECT( + USD(50) == + accountHolds(*env.closed(), bob, USD.currency, gw, fhZERO_IF_FROZEN, env.journal)); } { // accountHolds(). @@ -762,15 +769,20 @@ class View_test : public beast::unit_test::suite env.close(); // carol has no EUR. - BEAST_EXPECT(EUR(0) == accountHolds(*env.closed(), carol, EUR.currency, gw, fhZERO_IF_FROZEN, env.journal)); + BEAST_EXPECT( + EUR(0) == + accountHolds( + *env.closed(), carol, EUR.currency, gw, fhZERO_IF_FROZEN, env.journal)); // But carol does have USD. BEAST_EXPECT( - USD(50) == accountHolds(*env.closed(), carol, USD.currency, gw, fhZERO_IF_FROZEN, env.journal)); + USD(50) == + accountHolds( + *env.closed(), carol, USD.currency, gw, fhZERO_IF_FROZEN, env.journal)); // carol's XRP balance should be her holdings minus her reserve. - auto const carolsXRP = - accountHolds(*env.closed(), carol, xrpCurrency(), xrpAccount(), fhZERO_IF_FROZEN, env.journal); + auto const carolsXRP = accountHolds( + *env.closed(), carol, xrpCurrency(), xrpAccount(), fhZERO_IF_FROZEN, env.journal); // carol's XRP balance: 10000 // base reserve: -200 // 1 trust line times its reserve: 1 * -50 @@ -785,16 +797,20 @@ class View_test : public beast::unit_test::suite // carol's XRP balance should now show as zero. BEAST_EXPECT( - XRP(0) == accountHolds(*env.closed(), carol, xrpCurrency(), gw, fhZERO_IF_FROZEN, env.journal)); + XRP(0) == + accountHolds( + *env.closed(), carol, xrpCurrency(), gw, fhZERO_IF_FROZEN, env.journal)); } { // accountFunds(). // Gateways have whatever funds they claim to have. - auto const gwUSD = accountFunds(*env.closed(), gw, USD(314159), fhZERO_IF_FROZEN, env.journal); + auto const gwUSD = + accountFunds(*env.closed(), gw, USD(314159), fhZERO_IF_FROZEN, env.journal); BEAST_EXPECT(gwUSD == USD(314159)); // carol has funds from the gateway. - auto carolsUSD = accountFunds(*env.closed(), carol, USD(0), fhZERO_IF_FROZEN, env.journal); + auto carolsUSD = + accountFunds(*env.closed(), carol, USD(0), fhZERO_IF_FROZEN, env.journal); BEAST_EXPECT(carolsUSD == USD(50)); // If carol's funds are frozen she has no funds... @@ -910,9 +926,10 @@ class View_test : public beast::unit_test::suite { Env env(*this); Config config; - std::shared_ptr const genesis = - std::make_shared(create_genesis, config, std::vector{}, env.app().getNodeFamily()); - auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); + std::shared_ptr const genesis = std::make_shared( + create_genesis, config, std::vector{}, env.app().getNodeFamily()); + auto const ledger = + std::make_shared(*genesis, env.app().timeKeeper().closeTime()); wipe(*ledger); ledger->rawInsert(sle(1)); ReadView& v0 = *ledger; diff --git a/src/test/nodestore/Database_test.cpp b/src/test/nodestore/Database_test.cpp index 1229923e7d..6943f0733e 100644 --- a/src/test/nodestore/Database_test.cpp +++ b/src/test/nodestore/Database_test.cpp @@ -508,7 +508,10 @@ public: //-------------------------------------------------------------------------- void - testImport(std::string const& destBackendType, std::string const& srcBackendType, std::int64_t seedValue) + testImport( + std::string const& destBackendType, + std::string const& srcBackendType, + std::int64_t seedValue) { DummyScheduler scheduler; @@ -627,8 +630,8 @@ public: { // Verify default earliest ledger sequence { - std::unique_ptr db = - Manager::instance().make_Database(megabytes(4), scheduler, 2, nodeParams, journal_); + std::unique_ptr db = Manager::instance().make_Database( + megabytes(4), scheduler, 2, nodeParams, journal_); BEAST_EXPECT(db->earliestLedgerSeq() == XRP_LEDGER_EARLIEST_SEQ); } @@ -636,8 +639,8 @@ public: try { nodeParams.set("earliest_seq", "0"); - std::unique_ptr db = - Manager::instance().make_Database(megabytes(4), scheduler, 2, nodeParams, journal_); + std::unique_ptr db = Manager::instance().make_Database( + megabytes(4), scheduler, 2, nodeParams, journal_); } catch (std::runtime_error const& e) { @@ -647,8 +650,8 @@ public: { // Set a valid earliest ledger sequence nodeParams.set("earliest_seq", "1"); - std::unique_ptr db = - Manager::instance().make_Database(megabytes(4), scheduler, 2, nodeParams, journal_); + std::unique_ptr db = Manager::instance().make_Database( + megabytes(4), scheduler, 2, nodeParams, journal_); // Verify database uses the earliest ledger sequence setting BEAST_EXPECT(db->earliestLedgerSeq() == 1); @@ -659,8 +662,8 @@ public: { // Set to default earliest ledger sequence nodeParams.set("earliest_seq", std::to_string(XRP_LEDGER_EARLIEST_SEQ)); - std::unique_ptr db2 = - Manager::instance().make_Database(megabytes(4), scheduler, 2, nodeParams, journal_); + std::unique_ptr db2 = Manager::instance().make_Database( + megabytes(4), scheduler, 2, nodeParams, journal_); } catch (std::runtime_error const& e) { diff --git a/src/test/nodestore/NuDBFactory_test.cpp b/src/test/nodestore/NuDBFactory_test.cpp index 7d8f1df45d..9a9b7d83bd 100644 --- a/src/test/nodestore/NuDBFactory_test.cpp +++ b/src/test/nodestore/NuDBFactory_test.cpp @@ -37,7 +37,8 @@ private: DummyScheduler scheduler; test::SuiteJournal journal("NuDBFactory_test", *this); - auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); + auto backend = + Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); if (!BEAST_EXPECT(backend)) return false; @@ -69,7 +70,10 @@ private: // Helper function to test log messages void - testLogMessage(Section const& params, beast::severities::Severity level, std::string const& expectedMessage) + testLogMessage( + Section const& params, + beast::severities::Severity level, + std::string const& expectedMessage) { test::StreamSink sink(level); beast::Journal journal(sink); @@ -204,14 +208,17 @@ public: DummyScheduler scheduler; try { - auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); + auto backend = + Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); fail(); } catch (std::exception const& e) { std::string logOutput{e.what()}; BEAST_EXPECT(logOutput.find("Invalid nudb_block_size: 5000") != std::string::npos); - BEAST_EXPECT(logOutput.find("Must be power of 2 between 4096 and 32768") != std::string::npos); + BEAST_EXPECT( + logOutput.find("Must be power of 2 between 4096 and 32768") != + std::string::npos); } } @@ -226,14 +233,16 @@ public: DummyScheduler scheduler; try { - auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); + auto backend = + Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); fail(); } catch (std::exception const& e) { std::string logOutput{e.what()}; - BEAST_EXPECT(logOutput.find("Invalid nudb_block_size value: invalid") != std::string::npos); + BEAST_EXPECT( + logOutput.find("Invalid nudb_block_size value: invalid") != std::string::npos); } } } @@ -269,7 +278,8 @@ public: DummyScheduler scheduler; try { - auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); + auto backend = + Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); BEAST_EXPECT(shouldWork); } catch (std::exception const& e) @@ -293,7 +303,8 @@ public: // Test first constructor (without nudb::context) { - auto backend1 = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); + auto backend1 = + Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); BEAST_EXPECT(backend1 != nullptr); BEAST_EXPECT(testBackendFunctionality(params, 16384)); } @@ -333,11 +344,13 @@ public: beast::Journal journal(sink); DummyScheduler scheduler; - auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); + auto backend = + Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); // Should log success message for valid values std::string logOutput = sink.messages().str(); - bool hasSuccessMessage = logOutput.find("Using custom NuDB block size") != std::string::npos; + bool hasSuccessMessage = + logOutput.find("Using custom NuDB block size") != std::string::npos; BEAST_EXPECT(hasSuccessMessage); } @@ -355,7 +368,8 @@ public: DummyScheduler scheduler; try { - auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); + auto backend = + Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); fail(); } catch (...) @@ -386,7 +400,8 @@ public: // Store data { - auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); + auto backend = + Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); backend->open(); storeBatch(*backend, batch); backend->close(); @@ -394,7 +409,8 @@ public: // Retrieve data in new backend instance { - auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); + auto backend = + Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); backend->open(); Batch copy; diff --git a/src/test/nodestore/TestBase.h b/src/test/nodestore/TestBase.h index dfa2b05642..4a4d21002e 100644 --- a/src/test/nodestore/TestBase.h +++ b/src/test/nodestore/TestBase.h @@ -26,7 +26,8 @@ namespace NodeStore { struct LessThan { bool - operator()(std::shared_ptr const& lhs, std::shared_ptr const& rhs) const noexcept + operator()(std::shared_ptr const& lhs, std::shared_ptr const& rhs) + const noexcept { return lhs->getHash() < rhs->getHash(); } diff --git a/src/test/nodestore/Timing_test.cpp b/src/test/nodestore/Timing_test.cpp index 09e39028e8..dae131e5e7 100644 --- a/src/test/nodestore/Timing_test.cpp +++ b/src/test/nodestore/Timing_test.cpp @@ -100,7 +100,8 @@ public: rngcpy(data + 1, key.size() - 1, gen_); Blob value(d_size_(gen_)); rngcpy(&value[0], value.size(), gen_); - return NodeObject::createObject(safe_cast(d_type_(gen_)), std::move(value), key); + return NodeObject::createObject( + safe_cast(d_type_(gen_)), std::move(value), key); } // returns a batch of NodeObjects starting at n @@ -324,7 +325,12 @@ public: }; try { - parallel_for_id(params.items, params.threads, std::ref(*this), std::ref(params), std::ref(*backend)); + parallel_for_id( + params.items, + params.threads, + std::ref(*this), + std::ref(params), + std::ref(*backend)); } catch (std::exception const&) { @@ -385,7 +391,12 @@ public: try { - parallel_for_id(params.items, params.threads, std::ref(*this), std::ref(params), std::ref(*backend)); + parallel_for_id( + params.items, + params.threads, + std::ref(*this), + std::ref(params), + std::ref(*backend)); } catch (std::exception const&) { @@ -461,7 +472,12 @@ public: try { - parallel_for_id(params.items, params.threads, std::ref(*this), std::ref(params), std::ref(*backend)); + parallel_for_id( + params.items, + params.threads, + std::ref(*this), + std::ref(params), + std::ref(*backend)); } catch (std::exception const&) { @@ -566,7 +582,12 @@ public: try { - parallel_for_id(params.items, params.threads, std::ref(*this), std::ref(params), std::ref(*backend)); + parallel_for_id( + params.items, + params.threads, + std::ref(*this), + std::ref(params), + std::ref(*backend)); } catch (std::exception const&) { @@ -592,14 +613,18 @@ public: } void - do_tests(std::size_t threads, test_list const& tests, std::vector const& config_strings) + do_tests( + std::size_t threads, + test_list const& tests, + std::vector const& config_strings) { using std::setw; int w = 8; for (auto const& test : tests) if (w < test.first.size()) w = test.first.size(); - log << threads << " Thread" << (threads > 1 ? "s" : "") << ", " << default_items << " Objects" << std::endl; + log << threads << " Thread" << (threads > 1 ? "s" : "") << ", " << default_items + << " Objects" << std::endl; { std::stringstream ss; ss << std::left << setw(10) << "Backend" << std::right; @@ -624,7 +649,8 @@ public: std::stringstream ss; ss << std::left << setw(10) << get(config, "type", std::string()) << std::right; for (auto const& test : tests) - ss << " " << setw(w) << to_string(do_test(test.second, config, params, journal)); + ss << " " << setw(w) + << to_string(do_test(test.second, config, params, journal)); ss << " " << to_string(config); log << ss.str() << std::endl; } diff --git a/src/test/nodestore/import_test.cpp b/src/test/nodestore/import_test.cpp index 896f9558da..578dd3670e 100644 --- a/src/test/nodestore/import_test.cpp +++ b/src/test/nodestore/import_test.cpp @@ -209,9 +209,11 @@ public: return; } auto const rate = elapsed.count() / double(work); - clock_type::duration const remain(static_cast((work_ - work) * rate)); + clock_type::duration const remain( + static_cast((work_ - work) * rate)); log << "Remaining: " << detail::fmtdur(remain) << " (" << work << " of " << work_ << " in " - << detail::fmtdur(elapsed) << ", " << (work - prev_) << " in " << detail::fmtdur(now - report_) << ")"; + << detail::fmtdur(elapsed) << ", " << (work - prev_) << " in " + << detail::fmtdur(now - report_) << ")"; report_ = now; prev_ = work; } @@ -365,7 +367,8 @@ public: for (it->SeekToFirst(); it->Valid(); it->Next()) { if (it->key().size() != 32) - Throw("Unexpected key size " + std::to_string(it->key().size())); + Throw( + "Unexpected key size " + std::to_string(it->key().size())); void const* const key = it->key().data(); void const* const data = it->value().data(); auto const size = it->value().size(); diff --git a/src/test/overlay/ProtocolVersion_test.cpp b/src/test/overlay/ProtocolVersion_test.cpp index 02cbaba909..f0d02edbca 100644 --- a/src/test/overlay/ProtocolVersion_test.cpp +++ b/src/test/overlay/ProtocolVersion_test.cpp @@ -62,9 +62,12 @@ public: testcase("Protocol version negotiation"); BEAST_EXPECT(negotiateProtocolVersion("RTXP/1.2") == std::nullopt); - BEAST_EXPECT(negotiateProtocolVersion("RTXP/1.2, XRPL/2.0, XRPL/2.1") == make_protocol(2, 1)); + BEAST_EXPECT( + negotiateProtocolVersion("RTXP/1.2, XRPL/2.0, XRPL/2.1") == make_protocol(2, 1)); BEAST_EXPECT(negotiateProtocolVersion("XRPL/2.2") == make_protocol(2, 2)); - BEAST_EXPECT(negotiateProtocolVersion("RTXP/1.2, XRPL/2.2, XRPL/2.3, XRPL/999.999") == make_protocol(2, 2)); + BEAST_EXPECT( + negotiateProtocolVersion("RTXP/1.2, XRPL/2.2, XRPL/2.3, XRPL/999.999") == + make_protocol(2, 2)); BEAST_EXPECT(negotiateProtocolVersion("XRPL/999.999, WebSocket/1.0") == std::nullopt); BEAST_EXPECT(negotiateProtocolVersion("") == std::nullopt); } diff --git a/src/test/overlay/TMGetObjectByHash_test.cpp b/src/test/overlay/TMGetObjectByHash_test.cpp index c4e70ba305..0624c7b088 100644 --- a/src/test/overlay/TMGetObjectByHash_test.cpp +++ b/src/test/overlay/TMGetObjectByHash_test.cpp @@ -97,7 +97,8 @@ class TMGetObjectByHash_test : public beast::unit_test::suite { auto& overlay = dynamic_cast(env.app().overlay()); boost::beast::http::request request; - auto stream_ptr = std::make_unique(socket_type(env.app().getIOContext()), *context_); + auto stream_ptr = + std::make_unique(socket_type(env.app().getIOContext()), *context_); beast::IP::Endpoint local(boost::asio::ip::make_address("172.1.1.1"), 51235); beast::IP::Endpoint remote(boost::asio::ip::make_address("172.1.1.2"), 51235); @@ -107,7 +108,14 @@ class TMGetObjectByHash_test : public beast::unit_test::suite auto [slot, _] = overlay.peerFinder().new_inbound_slot(local, remote); auto peer = std::make_shared( - env.app(), slot, std::move(request), key, protocolVersion_, consumer, std::move(stream_ptr), overlay); + env.app(), + slot, + std::move(request), + key, + protocolVersion_, + consumer, + std::move(stream_ptr), + overlay); overlay.add_active(peer); return peer; diff --git a/src/test/overlay/compression_test.cpp b/src/test/overlay/compression_test.cpp index 19876809d2..3c787a4c72 100644 --- a/src/test/overlay/compression_test.cpp +++ b/src/test/overlay/compression_test.cpp @@ -82,7 +82,9 @@ public: auto start = buffer.begin() + sz * i; auto end = i < nbuffers - 1 ? (buffer.begin() + sz * (i + 1)) : buffer.end(); std::vector slice(start, end); - buffers.commit(boost::asio::buffer_copy(buffers.prepare(slice.size()), boost::asio::buffer(slice))); + buffers.commit( + boost::asio::buffer_copy( + buffers.prepare(slice.size()), boost::asio::buffer(slice))); } boost::system::error_code ec; @@ -108,8 +110,11 @@ public: BEAST_EXPECT(proto1->ParseFromArray(decompressed.data(), decompressedSize)); auto uncompressed = m.getBuffer(Compressed::Off); - BEAST_EXPECT(std::equal( - uncompressed.begin() + xrpl::compression::headerBytes, uncompressed.end(), decompressed.begin())); + BEAST_EXPECT( + std::equal( + uncompressed.begin() + xrpl::compression::headerBytes, + uncompressed.end(), + decompressed.begin())); } std::shared_ptr @@ -125,8 +130,10 @@ public: st[sfSequence] = i; st[sfPublicKey] = std::get<0>(master); st[sfSigningPubKey] = std::get<0>(signing); - st[sfDomain] = makeSlice(std::string("example") + std::to_string(i) + std::string(".com")); - sign(st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(master), sfMasterSignature); + st[sfDomain] = + makeSlice(std::string("example") + std::to_string(i) + std::string(".com")); + sign( + st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(master), sfMasterSignature); sign(st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(signing)); Serializer s; st.add(s); @@ -249,7 +256,8 @@ public: { auto getObject = std::make_shared(); - getObject->set_type(protocol::TMGetObjectByHash_ObjectType::TMGetObjectByHash_ObjectType_otTRANSACTION); + getObject->set_type( + protocol::TMGetObjectByHash_ObjectType::TMGetObjectByHash_ObjectType_otTRANSACTION); getObject->set_query(true); getObject->set_seq(123456789); uint256 hash(xrpl::sha512Half(123456789)); @@ -365,7 +373,11 @@ public: doTest(buildGetObjectByHash(), protocol::mtGET_OBJECTS, 4, "TMGetObjectByHash"); // 895B doTest(buildValidatorList(), protocol::mtVALIDATOR_LIST, 4, "TMValidatorList"); - doTest(buildValidatorListCollection(), protocol::mtVALIDATOR_LIST_COLLECTION, 4, "TMValidatorListCollection"); + doTest( + buildValidatorListCollection(), + protocol::mtVALIDATOR_LIST_COLLECTION, + 4, + "TMValidatorListCollection"); } void @@ -382,7 +394,8 @@ public: 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().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = + c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE; return env; }; auto handshake = [&](int outboundEnable, int inboundEnable) { @@ -403,15 +416,18 @@ public: auto const peerEnabled = inboundEnable && outboundEnable; // inbound is enabled if the request's header has the feature // enabled and the peer's configuration is enabled - auto const inboundEnabled = peerFeatureEnabled(http_request, FEATURE_COMPR, "lz4", inboundEnable); + auto const inboundEnabled = + peerFeatureEnabled(http_request, FEATURE_COMPR, "lz4", inboundEnable); BEAST_EXPECT(!(peerEnabled ^ inboundEnabled)); env.reset(); env = getEnv(inboundEnable); - auto http_resp = xrpl::makeResponse(true, http_request, addr, addr, uint256{1}, 1, {1, 0}, env->app()); + auto http_resp = xrpl::makeResponse( + true, http_request, addr, addr, uint256{1}, 1, {1, 0}, env->app()); // outbound is enabled if the response's header has the feature // enabled and the peer's configuration is enabled - auto const outboundEnabled = peerFeatureEnabled(http_resp, FEATURE_COMPR, "lz4", outboundEnable); + auto const outboundEnabled = + peerFeatureEnabled(http_resp, FEATURE_COMPR, "lz4", outboundEnable); BEAST_EXPECT(!(peerEnabled ^ outboundEnabled)); }; handshake(1, 1); diff --git a/src/test/overlay/reduce_relay_test.cpp b/src/test/overlay/reduce_relay_test.cpp index 9d9aef7a36..bf6d8aac1c 100644 --- a/src/test/overlay/reduce_relay_test.cpp +++ b/src/test/overlay/reduce_relay_test.cpp @@ -245,7 +245,10 @@ class Link using Latency = std::pair; public: - Link(Validator& validator, PeerSPtr peer, Latency const& latency = {milliseconds(5), milliseconds(15)}) + Link( + Validator& validator, + PeerSPtr peer, + Latency const& latency = {milliseconds(5), milliseconds(15)}) : validator_(validator), peer_(peer), latency_(latency), up_(true) { auto sp = peer_.lock(); @@ -367,7 +370,9 @@ public: for_links(LinkIterCB f, bool simulateSlow = false) { std::vector v; - std::transform(links_.begin(), links_.end(), std::back_inserter(v), [](auto& kv) { return kv.second; }); + std::transform(links_.begin(), links_.end(), std::back_inserter(v), [](auto& kv) { + return kv.second; + }); std::random_device d; std::mt19937 g(d()); std::shuffle(v.begin(), v.end(), g); @@ -631,7 +636,9 @@ public: return *selected.begin(); } - std::unordered_map> + std::unordered_map< + id_t, + std::tuple> getPeers(PublicKey const& validator) { return slots_.getPeers(validator); @@ -740,7 +747,8 @@ public: void enableLink(std::uint16_t validatorId, Peer::id_t peer, bool enable) { - auto it = std::find_if(validators_.begin(), validators_.end(), [&](auto& v) { return v.id() == validatorId; }); + auto it = std::find_if( + validators_.begin(), validators_.end(), [&](auto& v) { return v.id() == validatorId; }); assert(it != validators_.end()); if (enable) it->linkUp(peer); @@ -762,8 +770,9 @@ public: PublicKey key = v; squelch.clear_validatorpubkey(); squelch.set_validatorpubkey(key.data(), key.size()); - v.for_links( - {peer}, [&](Link& l, MessageSPtr) { std::dynamic_pointer_cast(l.getPeer())->send(squelch); }); + v.for_links({peer}, [&](Link& l, MessageSPtr) { + std::dynamic_pointer_cast(l.getPeer())->send(squelch); + }); } } @@ -862,7 +871,10 @@ protected: /** Send squelch (if duration is set) or unsquelch (if duration not set) */ Peer::id_t - sendSquelch(PublicKey const& validator, PeerWPtr const& peerPtr, std::optional duration) + sendSquelch( + PublicKey const& validator, + PeerWPtr const& peerPtr, + std::optional duration) { protocol::TMSquelch squelch; bool res = duration ? true : false; @@ -912,12 +924,13 @@ protected: bool squelched = false; std::stringstream str; - link.send(m, [&](PublicKey const& key, PeerWPtr const& peerPtr, std::uint32_t duration) { - assert(key == validator); - auto p = sendSquelch(key, peerPtr, duration); - squelched = true; - str << p << " "; - }); + link.send( + m, [&](PublicKey const& key, PeerWPtr const& peerPtr, std::uint32_t duration) { + assert(key == validator); + auto p = sendSquelch(key, peerPtr, duration); + squelched = true; + str << p << " "; + }); if (squelched) { @@ -927,12 +940,13 @@ protected: str << s << " "; if (log) std::cout << (double)reduce_relay::epoch(now).count() / 1000. - << " random, squelched, validator: " << validator.id() << " peers: " << str.str() - << std::endl; + << " random, squelched, validator: " << validator.id() + << " peers: " << str.str() << std::endl; 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().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); } // Trigger Link Down or Peer Disconnect event @@ -949,7 +963,8 @@ protected: if (event == EventType::LinkDown) { network_.enableLink(validator.id(), link.peerId(), false); - events[event].isSelected_ = network_.overlay().isSelected(validator, link.peerId()); + events[event].isSelected_ = + network_.overlay().isSelected(validator, link.peerId()); } else events[event].isSelected_ = network_.isSelected(link.peerId()); @@ -965,11 +980,12 @@ protected: { auto& event = events[EventType::PeerDisconnected]; bool allCounting = network_.allCounting(event.peer_); - network_.overlay().deletePeer(event.peer_, [&](PublicKey const& v, PeerWPtr const& peerPtr) { - if (event.isSelected_) - sendSquelch(v, peerPtr, {}); - event.handled_ = true; - }); + network_.overlay().deletePeer( + event.peer_, [&](PublicKey const& v, PeerWPtr const& peerPtr) { + if (event.isSelected_) + sendSquelch(v, peerPtr, {}); + event.handled_ = true; + }); // Should only be unsquelched if the peer is in Selected state // If in Selected state it's possible unsquelching didn't // take place because there is no peers in Squelched state in @@ -1002,9 +1018,12 @@ protected: { event.isSelected_ = network_.overlay().isSelected(*event.key_, event.peer_); auto peers = network_.overlay().getPeers(*event.key_); - auto d = reduce_relay::epoch(now).count() - std::get<3>(peers[event.peer_]); - mustHandle = event.isSelected_ && d > milliseconds(reduce_relay::IDLED).count() && - network_.overlay().inState(*event.key_, reduce_relay::PeerState::Squelched) > 0 && + auto d = reduce_relay::epoch(now).count() - + std::get<3>(peers[event.peer_]); + mustHandle = event.isSelected_ && + d > milliseconds(reduce_relay::IDLED).count() && + network_.overlay().inState( + *event.key_, reduce_relay::PeerState::Squelched) > 0 && peers.find(event.peer_) != peers.end(); } network_.overlay().deleteIdlePeers([&](PublicKey const& v, PeerWPtr const& ptr) { @@ -1015,11 +1034,13 @@ protected: sendSquelch(validator, ptr, {}); } }); - bool handled = (event.handled_ && event.state_ == State::WaitReset) || (!event.handled_ && !mustHandle); + bool handled = (event.handled_ && event.state_ == State::WaitReset) || + (!event.handled_ && !mustHandle); BEAST_EXPECT(handled); } if (event.state_ == State::WaitReset || - (event.state_ == State::On && (now - event.time_ > (reduce_relay::IDLED + seconds(2))))) + (event.state_ == State::On && + (now - event.time_ > (reduce_relay::IDLED + seconds(2))))) { bool handled = event.state_ == State::WaitReset || !event.handled_; BEAST_EXPECT(handled); @@ -1039,7 +1060,8 @@ protected: BEAST_EXPECT(disconnected.cnt_ == disconnected.handledCnt_); if (log) std::cout << "link down count: " << down.cnt_ << "/" << down.handledCnt_ - << " peer disconnect count: " << disconnected.cnt_ << "/" << disconnected.handledCnt_; + << " peer disconnect count: " << disconnected.cnt_ << "/" + << disconnected.handledCnt_; } bool @@ -1086,8 +1108,9 @@ protected: testPeerUnsquelched(bool log) { ManualClock::advance(seconds(601)); - doTest( - "Peer Unsquelched", log, [this](bool log) { BEAST_EXPECT(propagateNoSquelch(log, 2, true, true, false)); }); + doTest("Peer Unsquelched", log, [this](bool log) { + BEAST_EXPECT(propagateNoSquelch(log, 2, true, true, false)); + }); } /** Propagate enough messages to generate one squelch event */ @@ -1098,14 +1121,17 @@ protected: network_.propagate( [&](Link& link, MessageSPtr message) { std::uint16_t squelched = 0; - link.send(message, [&](PublicKey const& key, PeerWPtr const& peerPtr, std::uint32_t duration) { - squelched++; - sendSquelch(key, peerPtr, duration); - }); + link.send( + message, + [&](PublicKey const& key, PeerWPtr const& peerPtr, std::uint32_t duration) { + squelched++; + sendSquelch(key, peerPtr, duration); + }); if (squelched) { BEAST_EXPECT( - squelched == MAX_PEERS - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); + squelched == + MAX_PEERS - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); n++; } }, @@ -1114,7 +1140,8 @@ 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().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); BEAST_EXPECT(n == 1); // only one selection round auto res = checkCounting(network_.validator(0), false); BEAST_EXPECT(res); @@ -1123,15 +1150,22 @@ protected: /** Send fewer message so that squelch event is not generated */ bool - propagateNoSquelch(bool log, std::uint16_t nMessages, bool countingState, bool purge = true, bool resetClock = true) + propagateNoSquelch( + bool log, + std::uint16_t nMessages, + bool countingState, + bool purge = true, + bool resetClock = true) { bool squelched = false; network_.propagate( [&](Link& link, MessageSPtr message) { - link.send(message, [&](PublicKey const& key, PeerWPtr const& peerPtr, std::uint32_t duration) { - squelched = true; - BEAST_EXPECT(false); - }); + link.send( + message, + [&](PublicKey const& key, PeerWPtr const& peerPtr, std::uint32_t duration) { + squelched = true; + BEAST_EXPECT(false); + }); }, 1, nMessages, @@ -1164,8 +1198,11 @@ protected: BEAST_EXPECT(propagateAndSquelch(log, true, false)); auto id = network_.overlay().getSelectedPeer(network_.validator(0)); std::uint16_t unsquelched = 0; - network_.overlay().deletePeer(id, [&](PublicKey const& key, PeerWPtr const& peer) { unsquelched++; }); - BEAST_EXPECT(unsquelched == MAX_PEERS - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); + network_.overlay().deletePeer( + id, [&](PublicKey const& key, PeerWPtr const& peer) { unsquelched++; }); + BEAST_EXPECT( + unsquelched == + MAX_PEERS - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); BEAST_EXPECT(checkCounting(network_.validator(0), true)); }); } @@ -1180,9 +1217,12 @@ protected: BEAST_EXPECT(propagateAndSquelch(log, true, false)); ManualClock::advance(reduce_relay::IDLED + seconds(1)); std::uint16_t unsquelched = 0; - network_.overlay().deleteIdlePeers([&](PublicKey const& key, PeerWPtr const& peer) { unsquelched++; }); + network_.overlay().deleteIdlePeers( + [&](PublicKey const& key, PeerWPtr const& peer) { unsquelched++; }); auto peers = network_.overlay().getPeers(network_.validator(0)); - BEAST_EXPECT(unsquelched == MAX_PEERS - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); + BEAST_EXPECT( + unsquelched == + MAX_PEERS - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); BEAST_EXPECT(checkCounting(network_.validator(0), true)); }); } @@ -1197,7 +1237,8 @@ protected: BEAST_EXPECT(propagateAndSquelch(log, true, false)); auto peers = network_.overlay().getPeers(network_.validator(0)); auto it = std::find_if(peers.begin(), peers.end(), [&](auto it) { - return std::get(it.second) == reduce_relay::PeerState::Squelched; + return std::get(it.second) == + reduce_relay::PeerState::Squelched; }); assert(it != peers.end()); std::uint16_t unsquelched = 0; @@ -1349,7 +1390,8 @@ vp_base_squelch_max_selected_peers=2 ManualClock::reset(); auto createSlots = [&](bool baseSquelchEnabled) -> reduce_relay::Slots { env_.app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = baseSquelchEnabled; - return reduce_relay::Slots(env_.app().logs(), network_.overlay(), env_.app().config()); + return reduce_relay::Slots( + env_.app().logs(), network_.overlay(), env_.app().config()); }; // base squelching must not be ready if squelching is disabled BEAST_EXPECT(!createSlots(false).baseSquelchReady()); @@ -1380,7 +1422,8 @@ vp_base_squelch_max_selected_peers=2 { uint256 key(i); network_.overlay().updateSlotAndSquelch( - key, network_.validator(0), 0, [&](PublicKey const&, PeerWPtr, std::uint32_t) {}); + key, network_.validator(0), 0, [&](PublicKey const&, PeerWPtr, std::uint32_t) { + }); } auto peers = network_.overlay().getPeers(network_.validator(0)); // first message changes Slot state to Counting and is not counted, @@ -1430,7 +1473,8 @@ vp_base_squelch_max_selected_peers=2 auto run = [&](int npeers) { handler.maxDuration_ = 0; - reduce_relay::Slots slots(env_.app().logs(), handler, env_.app().config()); + reduce_relay::Slots slots( + env_.app().logs(), handler, env_.app().config()); // 1st message from a new peer switches the slot // to counting state and resets the counts of all peers + // MAX_MESSAGE_THRESHOLD + 1 messages to reach the threshold @@ -1443,7 +1487,8 @@ vp_base_squelch_max_selected_peers=2 // slot's internal hash router accept the message std::uint64_t mid = m * 1000 + peer; uint256 const message{mid}; - slots.updateSlotAndSquelch(message, validator, peer, protocol::MessageType::mtVALIDATION); + slots.updateSlotAndSquelch( + message, validator, peer, protocol::MessageType::mtVALIDATION); } } // make Slot's internal hash router expire all messages @@ -1473,14 +1518,18 @@ vp_base_squelch_max_selected_peers=2 handler.maxDuration_ <= MAX_UNSQUELCH_EXPIRE_PEERS.count()); using namespace beast::unit_test::detail; if (handler.maxDuration_ <= MAX_UNSQUELCH_EXPIRE_DEFAULT.count()) - log << make_reason("warning: squelch duration is low", __FILE__, __LINE__) << std::endl << std::flush; + log << make_reason("warning: squelch duration is low", __FILE__, __LINE__) + << std::endl + << std::flush; // more than 400 is still less than MAX_UNSQUELCH_EXPIRE_PEERS run(400); BEAST_EXPECT( handler.maxDuration_ >= MIN_UNSQUELCH_EXPIRE.count() && handler.maxDuration_ <= MAX_UNSQUELCH_EXPIRE_PEERS.count()); if (handler.maxDuration_ <= MAX_UNSQUELCH_EXPIRE_DEFAULT.count()) - log << make_reason("warning: squelch duration is low", __FILE__, __LINE__) << std::endl << std::flush; + log << make_reason("warning: squelch duration is low", __FILE__, __LINE__) + << std::endl + << std::flush; }); } @@ -1496,7 +1545,8 @@ 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().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = + c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE; env_.app().config().COMPRESSION = c.COMPRESSION; }; @@ -1518,14 +1568,17 @@ vp_base_squelch_max_selected_peers=2 auto const peerEnabled = inboundEnable && outboundEnable; // inbound is enabled if the request's header has the feature // enabled and the peer's configuration is enabled - auto const inboundEnabled = peerFeatureEnabled(http_request, FEATURE_VPRR, inboundEnable); + auto const inboundEnabled = + peerFeatureEnabled(http_request, FEATURE_VPRR, inboundEnable); BEAST_EXPECT(!(peerEnabled ^ inboundEnabled)); setEnv(inboundEnable); - auto http_resp = xrpl::makeResponse(true, http_request, addr, addr, uint256{1}, 1, {1, 0}, env_.app()); + auto http_resp = xrpl::makeResponse( + true, http_request, addr, addr, uint256{1}, 1, {1, 0}, env_.app()); // outbound is enabled if the response's header has the feature // enabled and the peer's configuration is enabled - auto const outboundEnabled = peerFeatureEnabled(http_resp, FEATURE_VPRR, outboundEnable); + auto const outboundEnabled = + peerFeatureEnabled(http_resp, FEATURE_VPRR, outboundEnable); BEAST_EXPECT(!(peerEnabled ^ outboundEnabled)); }; handshake(1, 1); diff --git a/src/test/overlay/short_read_test.cpp b/src/test/overlay/short_read_test.cpp index 498ecb6a27..bff0bd82cb 100644 --- a/src/test/overlay/short_read_test.cpp +++ b/src/test/overlay/short_read_test.cpp @@ -189,7 +189,10 @@ private: { acceptor_.async_accept( socket_, - bind_executor(strand_, std::bind(&Acceptor::on_accept, shared_from_this(), std::placeholders::_1))); + bind_executor( + strand_, + std::bind( + &Acceptor::on_accept, shared_from_this(), std::placeholders::_1))); } void @@ -213,7 +216,10 @@ private: p->run(); acceptor_.async_accept( socket_, - bind_executor(strand_, std::bind(&Acceptor::on_accept, shared_from_this(), std::placeholders::_1))); + bind_executor( + strand_, + std::bind( + &Acceptor::on_accept, shared_from_this(), std::placeholders::_1))); } }; @@ -255,11 +261,14 @@ private: { timer_.expires_after(std::chrono::seconds(3)); timer_.async_wait(bind_executor( - strand_, std::bind(&Connection::on_timer, shared_from_this(), std::placeholders::_1))); + strand_, + std::bind(&Connection::on_timer, shared_from_this(), std::placeholders::_1))); stream_.async_handshake( stream_type::server, bind_executor( - strand_, std::bind(&Connection::on_handshake, shared_from_this(), std::placeholders::_1))); + strand_, + std::bind( + &Connection::on_handshake, shared_from_this(), std::placeholders::_1))); } void @@ -298,7 +307,10 @@ private: bind_executor( strand_, std::bind( - &Connection::on_read, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); + &Connection::on_read, + shared_from_this(), + std::placeholders::_1, + std::placeholders::_2))); #else close(); #endif @@ -311,7 +323,9 @@ private: { server_.test_.log << "[server] read: EOF" << std::endl; return stream_.async_shutdown(bind_executor( - strand_, std::bind(&Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); + strand_, + std::bind( + &Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); } if (ec) return fail("read", ec); @@ -325,7 +339,10 @@ private: bind_executor( strand_, std::bind( - &Connection::on_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); + &Connection::on_write, + shared_from_this(), + std::placeholders::_1, + std::placeholders::_2))); } void @@ -335,7 +352,9 @@ private: if (ec) return fail("write", ec); stream_.async_shutdown(bind_executor( - strand_, std::bind(&Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); + strand_, + std::bind( + &Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); } void @@ -416,11 +435,14 @@ private: { timer_.expires_after(std::chrono::seconds(3)); timer_.async_wait(bind_executor( - strand_, std::bind(&Connection::on_timer, shared_from_this(), std::placeholders::_1))); + strand_, + std::bind(&Connection::on_timer, shared_from_this(), std::placeholders::_1))); socket_.async_connect( ep, bind_executor( - strand_, std::bind(&Connection::on_connect, shared_from_this(), std::placeholders::_1))); + strand_, + std::bind( + &Connection::on_connect, shared_from_this(), std::placeholders::_1))); } void @@ -454,7 +476,9 @@ private: stream_.async_handshake( stream_type::client, bind_executor( - strand_, std::bind(&Connection::on_handshake, shared_from_this(), std::placeholders::_1))); + strand_, + std::bind( + &Connection::on_handshake, shared_from_this(), std::placeholders::_1))); } void @@ -471,10 +495,15 @@ private: bind_executor( strand_, std::bind( - &Connection::on_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); + &Connection::on_write, + shared_from_this(), + std::placeholders::_1, + std::placeholders::_2))); #else stream_.async_shutdown(bind_executor( - strand_, std::bind(&Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); + strand_, + std::bind( + &Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); #endif } @@ -492,10 +521,15 @@ private: bind_executor( strand_, std::bind( - &Connection::on_read, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); + &Connection::on_read, + shared_from_this(), + std::placeholders::_1, + std::placeholders::_2))); #else stream_.async_shutdown(bind_executor( - strand_, std::bind(&Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); + strand_, + std::bind( + &Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); #endif } @@ -506,7 +540,9 @@ private: return fail("read", ec); buf_.commit(bytes_transferred); stream_.async_shutdown(bind_executor( - strand_, std::bind(&Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); + strand_, + std::bind( + &Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); } void diff --git a/src/test/overlay/traffic_count_test.cpp b/src/test/overlay/traffic_count_test.cpp index 6516fe3843..5e6e4e685c 100644 --- a/src/test/overlay/traffic_count_test.cpp +++ b/src/test/overlay/traffic_count_test.cpp @@ -25,7 +25,8 @@ public: BEAST_EXPECT(known == TrafficCount::category::base); // an unknown message type is categorized as unknown - auto const unknown = TrafficCount::categorize(message, static_cast(99), false); + auto const unknown = + TrafficCount::categorize(message, static_cast(99), false); BEAST_EXPECT(unknown == TrafficCount::category::unknown); } @@ -109,7 +110,8 @@ public: BEAST_EXPECT(TrafficCount::to_string(TrafficCount::category::total) == "total"); // return "unknown" for unknown categories - BEAST_EXPECT(TrafficCount::to_string(static_cast(1000)) == "unknown"); + BEAST_EXPECT( + TrafficCount::to_string(static_cast(1000)) == "unknown"); } void diff --git a/src/test/overlay/tx_reduce_relay_test.cpp b/src/test/overlay/tx_reduce_relay_test.cpp index b8e3300c03..e3facb2f76 100644 --- a/src/test/overlay/tx_reduce_relay_test.cpp +++ b/src/test/overlay/tx_reduce_relay_test.cpp @@ -32,7 +32,11 @@ private: testConfig(bool log) { doTest("Config Test", log, [&](bool log) { - auto test = [&](bool enable, bool metrics, std::uint16_t min, std::uint16_t pct, bool success = true) { + auto test = [&](bool enable, + bool metrics, + std::uint16_t min, + std::uint16_t pct, + bool success = true) { std::stringstream str("[reduce_relay]"); str << "[reduce_relay]\n" << "tx_enable=" << static_cast(enable) << "\n" @@ -141,17 +145,28 @@ private: { auto& overlay = dynamic_cast(env.app().overlay()); boost::beast::http::request request; - (nDisabled == 0) ? (void)request.insert("X-Protocol-Ctl", makeFeaturesRequestHeader(false, false, true, false)) - : (void)nDisabled--; + (nDisabled == 0) + ? (void)request.insert( + "X-Protocol-Ctl", makeFeaturesRequestHeader(false, false, true, false)) + : (void)nDisabled--; auto stream_ptr = std::make_unique( - socket_type(std::forward(env.app().getIOContext())), *context_); + socket_type(std::forward(env.app().getIOContext())), + *context_); beast::IP::Endpoint local(boost::asio::ip::make_address("172.1.1." + std::to_string(lid_))); - beast::IP::Endpoint remote(boost::asio::ip::make_address("172.1.1." + std::to_string(rid_))); + beast::IP::Endpoint remote( + boost::asio::ip::make_address("172.1.1." + std::to_string(rid_))); PublicKey key(std::get<0>(randomKeyPair(KeyType::ed25519))); auto consumer = overlay.resourceManager().newInboundEndpoint(remote); auto [slot, _] = overlay.peerFinder().new_inbound_slot(local, remote); auto const peer = std::make_shared( - env.app(), slot, std::move(request), key, protocolVersion_, consumer, std::move(stream_ptr), overlay); + env.app(), + slot, + std::move(request), + key, + protocolVersion_, + consumer, + std::move(stream_ptr), + overlay); BEAST_EXPECT(overlay.findPeerByPublicKey(key) == std::shared_ptr{}); overlay.add_active(peer); BEAST_EXPECT(overlay.findPeerByPublicKey(key) == peer); diff --git a/src/test/peerfinder/Livecache_test.cpp b/src/test/peerfinder/Livecache_test.cpp index 2c2ac01111..a69a300686 100644 --- a/src/test/peerfinder/Livecache_test.cpp +++ b/src/test/peerfinder/Livecache_test.cpp @@ -152,10 +152,12 @@ public: }; all_hops before; all_hops before_sorted; - for (auto i = std::make_pair(0, c.hops.begin()); i.second != c.hops.end(); ++i.first, ++i.second) + for (auto i = std::make_pair(0, c.hops.begin()); i.second != c.hops.end(); + ++i.first, ++i.second) { std::copy((*i.second).begin(), (*i.second).end(), std::back_inserter(before[i.first])); - std::copy((*i.second).begin(), (*i.second).end(), std::back_inserter(before_sorted[i.first])); + std::copy( + (*i.second).begin(), (*i.second).end(), std::back_inserter(before_sorted[i.first])); std::sort(before_sorted[i.first].begin(), before_sorted[i.first].end(), cmp_EP); } @@ -163,10 +165,12 @@ public: all_hops after; all_hops after_sorted; - for (auto i = std::make_pair(0, c.hops.begin()); i.second != c.hops.end(); ++i.first, ++i.second) + for (auto i = std::make_pair(0, c.hops.begin()); i.second != c.hops.end(); + ++i.first, ++i.second) { std::copy((*i.second).begin(), (*i.second).end(), std::back_inserter(after[i.first])); - std::copy((*i.second).begin(), (*i.second).end(), std::back_inserter(after_sorted[i.first])); + std::copy( + (*i.second).begin(), (*i.second).end(), std::back_inserter(after_sorted[i.first])); std::sort(after_sorted[i.first].begin(), after_sorted[i.first].end(), cmp_EP); } diff --git a/src/test/peerfinder/PeerFinder_test.cpp b/src/test/peerfinder/PeerFinder_test.cpp index 49ddc52c9d..2a9290ac3e 100644 --- a/src/test/peerfinder/PeerFinder_test.cpp +++ b/src/test/peerfinder/PeerFinder_test.cpp @@ -80,7 +80,8 @@ public: { BEAST_EXPECT(list.size() == 1); auto const [slot, _] = logic.new_outbound_slot(list.front()); - BEAST_EXPECT(logic.onConnected(slot, beast::IP::Endpoint::from_string("65.0.0.2:5"))); + BEAST_EXPECT( + logic.onConnected(slot, beast::IP::Endpoint::from_string("65.0.0.2:5"))); logic.on_closed(slot); ++n; } @@ -119,7 +120,8 @@ public: { BEAST_EXPECT(list.size() == 1); auto const [slot, _] = logic.new_outbound_slot(list.front()); - if (!BEAST_EXPECT(logic.onConnected(slot, beast::IP::Endpoint::from_string("65.0.0.2:5")))) + if (!BEAST_EXPECT( + logic.onConnected(slot, beast::IP::Endpoint::from_string("65.0.0.2:5")))) return; std::string s = "."; if (!BEAST_EXPECT(logic.activate(slot, pk, false) == PeerFinder::Result::success)) @@ -218,15 +220,18 @@ public: } auto const local = beast::IP::Endpoint::from_string("65.0.0.2:1024"); - auto const [slot, r] = logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1025")); + auto const [slot, r] = + logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1025")); BEAST_EXPECT(slot != nullptr); BEAST_EXPECT(r == Result::success); - auto const [slot1, r1] = logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1026")); + auto const [slot1, r1] = + logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1026")); BEAST_EXPECT(slot1 != nullptr); BEAST_EXPECT(r1 == Result::success); - auto const [slot2, r2] = logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1027")); + auto const [slot2, r2] = + logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1027")); BEAST_EXPECT(r2 == Result::ipLimitExceeded); if (!BEAST_EXPECT(slot2 == nullptr)) @@ -255,11 +260,13 @@ public: PublicKey const pk1(randomKeyPair(KeyType::secp256k1).first); - auto const [slot, rSlot] = logic.new_outbound_slot(beast::IP::Endpoint::from_string("55.104.0.2:1025")); + auto const [slot, rSlot] = + logic.new_outbound_slot(beast::IP::Endpoint::from_string("55.104.0.2:1025")); BEAST_EXPECT(slot != nullptr); BEAST_EXPECT(rSlot == Result::success); - auto const [slot2, r2Slot] = logic.new_outbound_slot(beast::IP::Endpoint::from_string("55.104.0.2:1026")); + auto const [slot2, r2Slot] = + logic.new_outbound_slot(beast::IP::Endpoint::from_string("55.104.0.2:1026")); BEAST_EXPECT(slot2 != nullptr); BEAST_EXPECT(r2Slot == Result::success); @@ -297,7 +304,8 @@ public: PublicKey const pk1(randomKeyPair(KeyType::secp256k1).first); auto const local = beast::IP::Endpoint::from_string("65.0.0.2:1024"); - auto const [slot, rSlot] = logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1025")); + auto const [slot, rSlot] = + logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1025")); BEAST_EXPECT(slot != nullptr); BEAST_EXPECT(rSlot == Result::success); @@ -315,7 +323,8 @@ public: BEAST_EXPECT(logic.activate(slot, pk1, false) == Result::success); // creating a new inbound slot must succeed as IP Limit is not exceeded - auto const [slot2, r2Slot] = logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1026")); + auto const [slot2, r2Slot] = + logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1026")); BEAST_EXPECT(slot2 != nullptr); BEAST_EXPECT(r2Slot == Result::success); @@ -408,7 +417,8 @@ public: Counts counts; counts.onConfig(config); BEAST_EXPECT( - counts.out_max() == expectOut && counts.in_max() == expectIn && config.ipLimit == expectIpLimit); + counts.out_max() == expectOut && counts.in_max() == expectIn && + config.ipLimit == expectIpLimit); TestStore store; TestChecker checker; diff --git a/src/test/protocol/InnerObjectFormats_test.cpp b/src/test/protocol/InnerObjectFormats_test.cpp index 7d69bb7afb..c06524b90e 100644 --- a/src/test/protocol/InnerObjectFormats_test.cpp +++ b/src/test/protocol/InnerObjectFormats_test.cpp @@ -163,7 +163,8 @@ public: Json::Reader().parse(test.txt, req); if (RPC::contains_error(req)) { - Throw("Internal InnerObjectFormatsParsedJSON error. Bad JSON."); + Throw( + "Internal InnerObjectFormatsParsedJSON error. Bad JSON."); } STParsedJSONObject parsed("request", req); bool const noObj = !parsed.object.has_value(); diff --git a/src/test/protocol/Memo_test.cpp b/src/test/protocol/Memo_test.cpp index 3c5d3f5a38..9a0fd7d94c 100644 --- a/src/test/protocol/Memo_test.cpp +++ b/src/test/protocol/Memo_test.cpp @@ -35,14 +35,16 @@ public: { // Make sure that too big a memo is flagged as invalid. JTx memoSize = makeJtxWithMemo(); - memoSize.jv[sfMemos.jsonName][0u][sfMemo.jsonName][sfMemoData.jsonName] = std::string(2020, '0'); + memoSize.jv[sfMemos.jsonName][0u][sfMemo.jsonName][sfMemoData.jsonName] = + std::string(2020, '0'); env(memoSize, rpc("invalidTransaction", "fails local checks: The memo exceeds the maximum allowed " "size.")); // This memo is just barely small enough. - memoSize.jv[sfMemos.jsonName][0u][sfMemo.jsonName][sfMemoData.jsonName] = std::string(2018, '1'); + memoSize.jv[sfMemos.jsonName][0u][sfMemo.jsonName][sfMemoData.jsonName] = + std::string(2018, '1'); env(memoSize); } { diff --git a/src/test/protocol/MultiApiJson_test.cpp b/src/test/protocol/MultiApiJson_test.cpp index 66eea9888f..ccf719e349 100644 --- a/src/test/protocol/MultiApiJson_test.cpp +++ b/src/test/protocol/MultiApiJson_test.cpp @@ -63,10 +63,12 @@ struct MultiApiJson_test : beast::unit_test::suite static_assert(std::size(primes) > RPC::apiMaximumValidVersion); MultiApiJson<1, 3> s1{}; - static_assert(s1.size == RPC::apiMaximumValidVersion + 1 - RPC::apiMinimumSupportedVersion); + static_assert( + s1.size == RPC::apiMaximumValidVersion + 1 - RPC::apiMinimumSupportedVersion); int productAllVersions = 1; - for (unsigned i = RPC::apiMinimumSupportedVersion; i <= RPC::apiMaximumValidVersion; ++i) + for (unsigned i = RPC::apiMinimumSupportedVersion; i <= RPC::apiMaximumValidVersion; + ++i) { auto const index = i - RPC::apiMinimumSupportedVersion; BEAST_EXPECT(index == s1.index(i)); @@ -76,7 +78,8 @@ struct MultiApiJson_test : beast::unit_test::suite } BEAST_EXPECT(!s1.valid(0)); BEAST_EXPECT(!s1.valid(RPC::apiMaximumValidVersion + 1)); - BEAST_EXPECT(!s1.valid(std::numeric_limits::max())); + BEAST_EXPECT( + !s1.valid(std::numeric_limits::max())); int result = 1; static_assert(RPC::apiMinimumSupportedVersion + 1 <= RPC::apiMaximumValidVersion); @@ -84,7 +87,8 @@ struct MultiApiJson_test : beast::unit_test::suite std::as_const(s1).visit(), [this](Json::Value const& json, unsigned int version, int* result) { BEAST_EXPECT( - version >= RPC::apiMinimumSupportedVersion && version <= RPC::apiMinimumSupportedVersion + 1); + version >= RPC::apiMinimumSupportedVersion && + version <= RPC::apiMinimumSupportedVersion + 1); if (BEAST_EXPECT(json.isMember("value"))) { *result *= json["value"].asInt(); @@ -92,7 +96,9 @@ struct MultiApiJson_test : beast::unit_test::suite }, &result); BEAST_EXPECT( - result == primes[RPC::apiMinimumSupportedVersion] * primes[RPC::apiMinimumSupportedVersion + 1]); + result == + primes[RPC::apiMinimumSupportedVersion] * + primes[RPC::apiMinimumSupportedVersion + 1]); // Check all the values with mutable data forAllApiVersions(s1.visit(), [&s1, this](Json::Value& json, auto version) { @@ -107,7 +113,9 @@ struct MultiApiJson_test : beast::unit_test::suite forAllApiVersions( std::as_const(s1).visit(), [this](Json::Value const& json, unsigned int version, int* result) { - BEAST_EXPECT(version >= RPC::apiMinimumSupportedVersion && version <= RPC::apiMaximumValidVersion); + BEAST_EXPECT( + version >= RPC::apiMinimumSupportedVersion && + version <= RPC::apiMaximumValidVersion); if (BEAST_EXPECT(json.isMember("value"))) { *result *= json["value"].asInt(); @@ -207,7 +215,10 @@ struct MultiApiJson_test : beast::unit_test::suite forAllApiVersions( std::forward(v).visit(), // []( - Json::Value const&, std::integral_constant, int, char const*) {}, + Json::Value const&, + std::integral_constant, + int, + char const*) {}, 0, ""); }; @@ -355,12 +366,16 @@ struct MultiApiJson_test : beast::unit_test::suite s1, std::integral_constant{}, Overload{ - [](Json::Value& v, std::integral_constant) { return v["value"].asInt(); }, + [](Json::Value& v, std::integral_constant) { + return v["value"].asInt(); + }, [](Json::Value const&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 2); static_assert([](auto&& v) { - return requires { v.visitor(v, std::integral_constant{}, [](Json::Value&) {}); }; + return requires { + v.visitor(v, std::integral_constant{}, [](Json::Value&) {}); + }; }(s1)); BEAST_EXPECT( s1.visitor( @@ -384,12 +399,16 @@ struct MultiApiJson_test : beast::unit_test::suite std::as_const(s1), std::integral_constant{}, Overload{ - [](Json::Value const& v, std::integral_constant) { return v["value"].asInt(); }, + [](Json::Value const& v, std::integral_constant) { + return v["value"].asInt(); + }, [](Json::Value&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 3); static_assert([](auto&& v) { - return requires { v.visitor(v, std::integral_constant{}, [](Json::Value const&) {}); }; + return requires { + v.visitor(v, std::integral_constant{}, [](Json::Value const&) {}); + }; }(std::as_const(s1))); BEAST_EXPECT( s1.visitor( @@ -400,7 +419,9 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value&) { return 0; }, [](auto...) { return 0; }}) == 3); - static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value&, unsigned) {}); }; }(s1)); + static_assert([](auto&& v) { + return requires { v.visitor(v, 1, [](Json::Value&, unsigned) {}); }; + }(s1)); BEAST_EXPECT( s1.visitor( s1, // @@ -410,7 +431,8 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value const&, unsigned) { return 0; }, [](auto, auto) { return 0; }}) == 5); - static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value&) {}); }; }(s1)); + static_assert( + [](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value&) {}); }; }(s1)); BEAST_EXPECT( s1.visitor( s1, // @@ -432,8 +454,9 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value const&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 3); - static_assert( - [](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value const&) {}); }; }(std::as_const(s1))); + static_assert([](auto&& v) { + return requires { v.visitor(v, 1, [](Json::Value const&) {}); }; + }(std::as_const(s1))); BEAST_EXPECT( s1.visitor( std::as_const(s1), // @@ -505,14 +528,18 @@ struct MultiApiJson_test : beast::unit_test::suite s1.visitor( s1, std::integral_constant{}, - [](Json::Value& v, auto ver, auto a1, auto a2) { return ver * a1 * a2 * v["value"].asInt(); }, + [](Json::Value& v, auto ver, auto a1, auto a2) { + return ver * a1 * a2 * v["value"].asInt(); + }, 5, 7) == 2 * 5 * 7 * 3); BEAST_EXPECT( s1.visitor( s1, std::integral_constant{}, - [](Json::Value& v, auto ver, auto... args) { return ver * (1 * ... * args) * v["value"].asInt(); }, + [](Json::Value& v, auto ver, auto... args) { + return ver * (1 * ... * args) * v["value"].asInt(); + }, 5, 7) == 2 * 5 * 7 * 3); @@ -556,25 +583,38 @@ struct MultiApiJson_test : beast::unit_test::suite // Want these to be unambiguous static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](auto) {}); }; }(s1)); - static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value&) {}); }; }(s1)); + static_assert( + [](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value&) {}); }; }(s1)); - static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value&, auto...) {}); }; }(s1)); + static_assert([](auto&& v) { + return requires { v.visitor(v, 1, [](Json::Value&, auto...) {}); }; + }(s1)); - static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value const&) {}); }; }(s1)); + static_assert([](auto&& v) { + return requires { v.visitor(v, 1, [](Json::Value const&) {}); }; + }(s1)); + + static_assert([](auto&& v) { + return requires { v.visitor(v, 1, [](Json::Value const&, auto...) {}); }; + }(s1)); static_assert( - [](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value const&, auto...) {}); }; }(s1)); - - static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](auto...) {}); }; }(s1)); - - static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](auto, auto...) {}); }; }(s1)); - - static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](auto, auto, auto...) {}); }; }(s1)); - - static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](auto, auto, auto...) {}, ""); }; }(s1)); + [](auto&& v) { return requires { v.visitor(v, 1, [](auto...) {}); }; }(s1)); static_assert( - [](auto&& v) { return requires { v.visitor(v, 1, [](auto, auto, auto, auto...) {}, ""); }; }(s1)); + [](auto&& v) { return requires { v.visitor(v, 1, [](auto, auto...) {}); }; }(s1)); + + static_assert([](auto&& v) { + return requires { v.visitor(v, 1, [](auto, auto, auto...) {}); }; + }(s1)); + + static_assert([](auto&& v) { + return requires { v.visitor(v, 1, [](auto, auto, auto...) {}, ""); }; + }(s1)); + + static_assert([](auto&& v) { + return requires { v.visitor(v, 1, [](auto, auto, auto, auto...) {}, ""); }; + }(s1)); } { @@ -597,7 +637,9 @@ struct MultiApiJson_test : beast::unit_test::suite s1.visit( std::integral_constant{}, Overload{ - [](Json::Value& v, std::integral_constant) { return v["value"].asInt(); }, + [](Json::Value& v, std::integral_constant) { + return v["value"].asInt(); + }, [](Json::Value const&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 2); static_assert([](auto&& v) { @@ -611,12 +653,16 @@ struct MultiApiJson_test : beast::unit_test::suite s1.visit()( std::integral_constant{}, Overload{ - [](Json::Value& v, std::integral_constant) { return v["value"].asInt(); }, + [](Json::Value& v, std::integral_constant) { + return v["value"].asInt(); + }, [](Json::Value const&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 2); static_assert([](auto&& v) { - return requires { v.visit(std::integral_constant{}, [](Json::Value&) {}); }; + return requires { + v.visit(std::integral_constant{}, [](Json::Value&) {}); + }; }(s1)); BEAST_EXPECT( s1.visit( @@ -626,7 +672,9 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value const&) { return 0; }, [](auto...) { return 0; }}) == 2); static_assert([](auto&& v) { - return requires { v.visit()(std::integral_constant{}, [](Json::Value&) {}); }; + return requires { + v.visit()(std::integral_constant{}, [](Json::Value&) {}); + }; }(s1)); BEAST_EXPECT( s1.visit()( @@ -647,7 +695,9 @@ struct MultiApiJson_test : beast::unit_test::suite std::as_const(s1).visit( std::integral_constant{}, Overload{ - [](Json::Value const& v, std::integral_constant) { return v["value"].asInt(); }, + [](Json::Value const& v, std::integral_constant) { + return v["value"].asInt(); + }, [](Json::Value&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 3); static_assert([](auto&& v) { @@ -661,12 +711,16 @@ struct MultiApiJson_test : beast::unit_test::suite std::as_const(s1).visit()( std::integral_constant{}, Overload{ - [](Json::Value const& v, std::integral_constant) { return v["value"].asInt(); }, + [](Json::Value const& v, std::integral_constant) { + return v["value"].asInt(); + }, [](Json::Value&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 3); static_assert([](auto&& v) { - return requires { v.visit(std::integral_constant{}, [](Json::Value const&) {}); }; + return requires { + v.visit(std::integral_constant{}, [](Json::Value const&) {}); + }; }(std::as_const(s1))); BEAST_EXPECT( std::as_const(s1).visit( @@ -676,7 +730,9 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value&) { return 0; }, [](auto...) { return 0; }}) == 3); static_assert([](auto&& v) { - return requires { v.visit()(std::integral_constant{}, [](Json::Value const&) {}); }; + return requires { + v.visit()(std::integral_constant{}, [](Json::Value const&) {}); + }; }(std::as_const(s1))); BEAST_EXPECT( std::as_const(s1).visit()( @@ -686,7 +742,9 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value&) { return 0; }, [](auto...) { return 0; }}) == 3); - static_assert([](auto&& v) { return requires { v.visit(1, [](Json::Value&, unsigned) {}); }; }(s1)); + static_assert([](auto&& v) { + return requires { v.visit(1, [](Json::Value&, unsigned) {}); }; + }(s1)); BEAST_EXPECT( s1.visit( 3u, @@ -695,7 +753,9 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value const&, unsigned) { return 0; }, [](Json::Value&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 5); - static_assert([](auto&& v) { return requires { v.visit()(1, [](Json::Value&, unsigned) {}); }; }(s1)); + static_assert([](auto&& v) { + return requires { v.visit()(1, [](Json::Value&, unsigned) {}); }; + }(s1)); BEAST_EXPECT( s1.visit()( 3u, @@ -705,7 +765,8 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 5); - static_assert([](auto&& v) { return requires { v.visit(1, [](Json::Value&) {}); }; }(s1)); + static_assert( + [](auto&& v) { return requires { v.visit(1, [](Json::Value&) {}); }; }(s1)); BEAST_EXPECT( s1.visit( 3, @@ -713,7 +774,8 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value& v) { return v["value"].asInt(); }, [](Json::Value const&) { return 0; }, [](auto...) { return 0; }}) == 5); - static_assert([](auto&& v) { return requires { v.visit()(1, [](Json::Value&) {}); }; }(s1)); + static_assert( + [](auto&& v) { return requires { v.visit()(1, [](Json::Value&) {}); }; }(s1)); BEAST_EXPECT( s1.visit()( 3, @@ -745,8 +807,9 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value&, unsigned) { return 0; }, [](auto, auto) { return 0; }}) == 3); - static_assert( - [](auto&& v) { return requires { v.visit(1, [](Json::Value const&) {}); }; }(std::as_const(s1))); + static_assert([](auto&& v) { + return requires { v.visit(1, [](Json::Value const&) {}); }; + }(std::as_const(s1))); BEAST_EXPECT( std::as_const(s1).visit( 2, @@ -754,8 +817,9 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value const& v) { return v["value"].asInt(); }, [](Json::Value&) { return 0; }, [](auto...) { return 0; }}) == 3); - static_assert( - [](auto&& v) { return requires { v.visit()(1, [](Json::Value const&) {}); }; }(std::as_const(s1))); + static_assert([](auto&& v) { + return requires { v.visit()(1, [](Json::Value const&) {}); }; + }(std::as_const(s1))); BEAST_EXPECT( std::as_const(s1).visit()( 2, @@ -769,50 +833,74 @@ struct MultiApiJson_test : beast::unit_test::suite return !requires { std::forward(v).visit(1, [](Json::Value&&) {}); }; }(std::move(s1))); static_assert([](auto&& v) { - return !requires { std::forward(v).visit(1, [](Json::Value const&&) {}); }; + return !requires { + std::forward(v).visit(1, [](Json::Value const&&) {}); + }; }(std::move(s1))); static_assert([](auto&& v) { return requires { std::forward(v).visit(1, [](Json::Value&) {}); }; }(std::move(s1))); static_assert([](auto&& v) { - return requires { std::forward(v).visit(1, [](Json::Value const&) {}); }; + return requires { + std::forward(v).visit(1, [](Json::Value const&) {}); + }; }(std::move(s1))); static_assert([](auto&& v) { return !requires { std::forward(v).visit()(1, [](Json::Value&&) {}); }; }(std::move(s1))); static_assert([](auto&& v) { - return !requires { std::forward(v).visit()(1, [](Json::Value const&&) {}); }; + return !requires { + std::forward(v).visit()(1, [](Json::Value const&&) {}); + }; }(std::move(s1))); static_assert([](auto&& v) { return requires { std::forward(v).visit()(1, [](Json::Value&) {}); }; }(std::move(s1))); static_assert([](auto&& v) { - return requires { std::forward(v).visit()(1, [](Json::Value const&) {}); }; + return requires { + std::forward(v).visit()(1, [](Json::Value const&) {}); + }; }(std::move(s1))); static_assert([](auto&& v) { - return !requires { std::forward(v).visit(1, [](Json::Value const&&) {}); }; + return !requires { + std::forward(v).visit(1, [](Json::Value const&&) {}); + }; }(std::move(std::as_const(s1)))); static_assert([](auto&& v) { - return requires { std::forward(v).visit(1, [](Json::Value const&) {}); }; + return requires { + std::forward(v).visit(1, [](Json::Value const&) {}); + }; }(std::move(std::as_const(s1)))); static_assert([](auto&& v) { - return !requires { std::forward(v).visit()(1, [](Json::Value const&&) {}); }; + return !requires { + std::forward(v).visit()(1, [](Json::Value const&&) {}); + }; }(std::move(std::as_const(s1)))); static_assert([](auto&& v) { - return requires { std::forward(v).visit()(1, [](Json::Value const&) {}); }; + return requires { + std::forward(v).visit()(1, [](Json::Value const&) {}); + }; }(std::move(std::as_const(s1)))); // Missing const static_assert([](auto&& v) { - return !requires { std::forward(v).visit(1, [](Json::Value&, auto) {}); }; + return !requires { + std::forward(v).visit(1, [](Json::Value&, auto) {}); + }; }(std::as_const(s1))); static_assert([](auto&& v) { - return !requires { std::forward(v).visit()(1, [](Json::Value&, auto) {}); }; + return !requires { + std::forward(v).visit()(1, [](Json::Value&, auto) {}); + }; }(std::as_const(s1))); // Missing parameter - static_assert([](auto&& v) { return !requires { std::forward(v).visit(1, []() {}); }; }(s1)); - static_assert([](auto&& v) { return !requires { std::forward(v).visit()(1, []() {}); }; }(s1)); + static_assert([](auto&& v) { + return !requires { std::forward(v).visit(1, []() {}); }; + }(s1)); + static_assert([](auto&& v) { + return !requires { std::forward(v).visit()(1, []() {}); }; + }(s1)); // Sanity checks static_assert([](auto&& v) { diff --git a/src/test/protocol/PublicKey_test.cpp b/src/test/protocol/PublicKey_test.cpp index cad1e87198..9a7808db7e 100644 --- a/src/test/protocol/PublicKey_test.cpp +++ b/src/test/protocol/PublicKey_test.cpp @@ -296,7 +296,8 @@ public: BEAST_EXPECT(!parseBase58(TokenType::NodePublic, " ")); BEAST_EXPECT(!parseBase58(TokenType::NodePublic, "!ty89234gh45")); - auto const good = toBase58(TokenType::NodePublic, derivePublicKey(keyType, randomSecretKey())); + auto const good = + toBase58(TokenType::NodePublic, derivePublicKey(keyType, randomSecretKey())); // Short (non-empty) strings { @@ -381,10 +382,11 @@ public: { auto const pk1 = derivePublicKey( - KeyType::secp256k1, generateSecretKey(KeyType::secp256k1, generateSeed("masterpassphrase"))); + KeyType::secp256k1, + generateSecretKey(KeyType::secp256k1, generateSeed("masterpassphrase"))); - auto const pk2 = - parseBase58(TokenType::NodePublic, "n94a1u4jAz288pZLtw6yFWVbi89YamiC6JBXPVUj5zmExe5fTVg9"); + auto const pk2 = parseBase58( + TokenType::NodePublic, "n94a1u4jAz288pZLtw6yFWVbi89YamiC6JBXPVUj5zmExe5fTVg9"); BEAST_EXPECT(pk2); BEAST_EXPECT(pk1 == *pk2); @@ -396,10 +398,11 @@ public: { auto const pk1 = derivePublicKey( - KeyType::ed25519, generateSecretKey(KeyType::ed25519, generateSeed("masterpassphrase"))); + KeyType::ed25519, + generateSecretKey(KeyType::ed25519, generateSeed("masterpassphrase"))); - auto const pk2 = - parseBase58(TokenType::NodePublic, "nHUeeJCSY2dM71oxM8Cgjouf5ekTuev2mwDpc374aLMxzDLXNmjf"); + auto const pk2 = parseBase58( + TokenType::NodePublic, "nHUeeJCSY2dM71oxM8Cgjouf5ekTuev2mwDpc374aLMxzDLXNmjf"); BEAST_EXPECT(pk2); BEAST_EXPECT(pk1 == *pk2); @@ -414,14 +417,16 @@ public: testcase("Miscellaneous operations"); auto const pk1 = derivePublicKey( - KeyType::secp256k1, generateSecretKey(KeyType::secp256k1, generateSeed("masterpassphrase"))); + KeyType::secp256k1, + generateSecretKey(KeyType::secp256k1, generateSeed("masterpassphrase"))); PublicKey pk2(pk1); BEAST_EXPECT(pk1 == pk2); BEAST_EXPECT(pk2 == pk1); PublicKey pk3 = derivePublicKey( - KeyType::secp256k1, generateSecretKey(KeyType::secp256k1, generateSeed("arbitraryPassPhrase"))); + KeyType::secp256k1, + generateSecretKey(KeyType::secp256k1, generateSeed("arbitraryPassPhrase"))); // Testing the copy assignment operation of PublicKey class pk3 = pk2; BEAST_EXPECT(pk3 == pk2); diff --git a/src/test/protocol/STAmount_test.cpp b/src/test/protocol/STAmount_test.cpp index 98bcc7b1bc..c9382d508a 100644 --- a/src/test/protocol/STAmount_test.cpp +++ b/src/test/protocol/STAmount_test.cpp @@ -37,7 +37,12 @@ public: if (mantissa < STAmount::cMinValue) return {amount.issue(), mantissa, amount.exponent(), amount.negative()}; - return {amount.issue(), mantissa, amount.exponent(), amount.negative(), STAmount::unchecked{}}; + return { + amount.issue(), + mantissa, + amount.exponent(), + amount.negative(), + STAmount::unchecked{}}; } if (valueDigits == 999999999) @@ -47,7 +52,12 @@ public: if (mantissa > STAmount::cMaxValue) return {amount.issue(), mantissa, amount.exponent(), amount.negative()}; - return {amount.issue(), mantissa, amount.exponent(), amount.negative(), STAmount::unchecked{}}; + return { + amount.issue(), + mantissa, + amount.exponent(), + amount.negative(), + STAmount::unchecked{}}; } return amount; @@ -73,8 +83,8 @@ public: if (res != cmp) { - log << "(" << num.getText() << "/" << den.getText() << ") X " << mul.getText() << " = " << res.getText() - << " not " << cmp.getText(); + log << "(" << num.getText() << "/" << den.getText() << ") X " << mul.getText() << " = " + << res.getText() << " not " << cmp.getText(); fail("Rounding"); return; } @@ -93,8 +103,8 @@ public: if (prod1 != prod2) { - log << "nn(" << aa.getFullText() << " * " << bb.getFullText() << ") = " << prod1.getFullText() << " not " - << prod2.getFullText(); + log << "nn(" << aa.getFullText() << " * " << bb.getFullText() + << ") = " << prod1.getFullText() << " not " << prod2.getFullText(); fail("Multiplication result is not exact"); } } @@ -338,11 +348,17 @@ public: unexpected(STAmount(noIssue(), 31, -1).getText() != "3.1", "STAmount fail"); unexpected(STAmount(noIssue(), 31, -2).getText() != "0.31", "STAmount fail"); unexpected( - multiply(STAmount(noIssue(), 20), STAmount(3), noIssue()).getText() != "60", "STAmount multiply fail 1"); + multiply(STAmount(noIssue(), 20), STAmount(3), noIssue()).getText() != "60", + "STAmount multiply fail 1"); unexpected( - multiply(STAmount(noIssue(), 20), STAmount(3), xrpIssue()).getText() != "60", "STAmount multiply fail 2"); - unexpected(multiply(STAmount(20), STAmount(3), noIssue()).getText() != "60", "STAmount multiply fail 3"); - unexpected(multiply(STAmount(20), STAmount(3), xrpIssue()).getText() != "60", "STAmount multiply fail 4"); + multiply(STAmount(noIssue(), 20), STAmount(3), xrpIssue()).getText() != "60", + "STAmount multiply fail 2"); + unexpected( + multiply(STAmount(20), STAmount(3), noIssue()).getText() != "60", + "STAmount multiply fail 3"); + unexpected( + multiply(STAmount(20), STAmount(3), xrpIssue()).getText() != "60", + "STAmount multiply fail 4"); if (divide(STAmount(noIssue(), 60), STAmount(3), noIssue()).getText() != "20") { @@ -354,7 +370,9 @@ public: pass(); } - unexpected(divide(STAmount(noIssue(), 60), STAmount(3), xrpIssue()).getText() != "20", "STAmount divide fail"); + unexpected( + divide(STAmount(noIssue(), 60), STAmount(3), xrpIssue()).getText() != "20", + "STAmount divide fail"); unexpected( divide(STAmount(noIssue(), 60), STAmount(noIssue(), 3), noIssue()).getText() != "20", @@ -366,9 +384,13 @@ public: STAmount a1(noIssue(), 60), a2(noIssue(), 10, -1); - unexpected(divide(a2, a1, noIssue()) != amountFromQuality(getRate(a1, a2)), "STAmount setRate(getRate) fail"); + unexpected( + divide(a2, a1, noIssue()) != amountFromQuality(getRate(a1, a2)), + "STAmount setRate(getRate) fail"); - unexpected(divide(a1, a2, noIssue()) != amountFromQuality(getRate(a2, a1)), "STAmount setRate(getRate) fail"); + unexpected( + divide(a1, a2, noIssue()) != amountFromQuality(getRate(a2, a1)), + "STAmount setRate(getRate) fail"); } //-------------------------------------------------------------------------- @@ -383,11 +405,13 @@ public: // and getNeeded unexpected( - getRate(STAmount(1), STAmount(10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull), + getRate(STAmount(1), STAmount(10)) != + (((100ull - 14) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 1"); unexpected( - getRate(STAmount(10), STAmount(1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull), + getRate(STAmount(10), STAmount(1)) != + (((100ull - 16) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 2"); unexpected( @@ -401,19 +425,23 @@ public: "STAmount getRate fail 4"); unexpected( - getRate(STAmount(noIssue(), 1), STAmount(10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull), + getRate(STAmount(noIssue(), 1), STAmount(10)) != + (((100ull - 14) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 5"); unexpected( - getRate(STAmount(noIssue(), 10), STAmount(1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull), + getRate(STAmount(noIssue(), 10), STAmount(1)) != + (((100ull - 16) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 6"); unexpected( - getRate(STAmount(1), STAmount(noIssue(), 10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull), + getRate(STAmount(1), STAmount(noIssue(), 10)) != + (((100ull - 14) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 7"); unexpected( - getRate(STAmount(10), STAmount(noIssue(), 1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull), + getRate(STAmount(10), STAmount(noIssue(), 1)) != + (((100ull - 16) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 8"); roundTest(1, 3, 3); @@ -437,8 +465,10 @@ public: testcase("underflow"); STAmount bigNative(STAmount::cMaxNative / 2); - STAmount bigValue(noIssue(), (STAmount::cMinValue + STAmount::cMaxValue) / 2, STAmount::cMaxOffset - 1); - STAmount smallValue(noIssue(), (STAmount::cMinValue + STAmount::cMaxValue) / 2, STAmount::cMinOffset + 1); + STAmount bigValue( + noIssue(), (STAmount::cMinValue + STAmount::cMaxValue) / 2, STAmount::cMaxOffset - 1); + STAmount smallValue( + noIssue(), (STAmount::cMinValue + STAmount::cMaxValue) / 2, STAmount::cMinOffset + 1); STAmount zeroSt(noIssue(), 0); STAmount smallXSmall = multiply(smallValue, smallValue, noIssue()); diff --git a/src/test/protocol/STInteger_test.cpp b/src/test/protocol/STInteger_test.cpp index 74340d53ea..937dbd1a7f 100644 --- a/src/test/protocol/STInteger_test.cpp +++ b/src/test/protocol/STInteger_test.cpp @@ -21,7 +21,8 @@ struct STInteger_test : public beast::unit_test::suite // there is some special handling for sfTransactionResult STUInt8 tr(sfTransactionResult, 0); BEAST_EXPECT(tr.value() == 0); - BEAST_EXPECT(tr.getText() == "The transaction was applied. Only final in a validated ledger."); + BEAST_EXPECT( + tr.getText() == "The transaction was applied. Only final in a validated ledger."); BEAST_EXPECT(tr.getSType() == STI_UINT8); BEAST_EXPECT(tr.getJson(JsonOptions::none) == "tesSUCCESS"); diff --git a/src/test/protocol/STIssue_test.cpp b/src/test/protocol/STIssue_test.cpp index cfd047e752..7e6fe5487c 100644 --- a/src/test/protocol/STIssue_test.cpp +++ b/src/test/protocol/STIssue_test.cpp @@ -123,8 +123,11 @@ public: BEAST_EXPECT(STIssue(sfAsset, asset1) != asset3); BEAST_EXPECT(STIssue(sfAsset, asset1) == asset1); BEAST_EXPECT(STIssue(sfAsset, asset1).getText() == "XRP"); - BEAST_EXPECT(STIssue(sfAsset, asset2).getText() == "USD/rG1QQv2nh2gr7RCZ1P8YYcBUKCCN633jCn"); - BEAST_EXPECT(STIssue(sfAsset, asset3).getText() == "000000000000000000000000000000000000000000000002"); + BEAST_EXPECT( + STIssue(sfAsset, asset2).getText() == "USD/rG1QQv2nh2gr7RCZ1P8YYcBUKCCN633jCn"); + BEAST_EXPECT( + STIssue(sfAsset, asset3).getText() == + "000000000000000000000000000000000000000000000002"); } void diff --git a/src/test/protocol/STNumber_test.cpp b/src/test/protocol/STNumber_test.cpp index a1a94accaa..9d43ace638 100644 --- a/src/test/protocol/STNumber_test.cpp +++ b/src/test/protocol/STNumber_test.cpp @@ -40,11 +40,16 @@ struct STNumber_test : public beast::unit_test::suite } std::initializer_list const mantissas = { - std::numeric_limits::min(), -1, 0, 1, std::numeric_limits::max()}; + std::numeric_limits::min(), + -1, + 0, + 1, + std::numeric_limits::max()}; for (std::int64_t mantissa : mantissas) testCombo(Number{mantissa}); - std::initializer_list const exponents = {Number::minExponent, -1, 0, 1, Number::maxExponent - 1}; + std::initializer_list const exponents = { + Number::minExponent, -1, 0, 1, Number::maxExponent - 1}; for (std::int32_t exponent : exponents) testCombo(Number{123, exponent}); @@ -98,31 +103,42 @@ struct STNumber_test : public beast::unit_test::suite if (Number::getMantissaScale() == MantissaRange::small) { BEAST_EXPECT( - numberFromJson(sfNumber, maxInt) == STNumber(sfNumber, Number{9'223'372'036'854'775, 3})); + numberFromJson(sfNumber, maxInt) == + STNumber(sfNumber, Number{9'223'372'036'854'775, 3})); BEAST_EXPECT( - numberFromJson(sfNumber, minInt) == STNumber(sfNumber, Number{-9'223'372'036'854'775, 3})); + numberFromJson(sfNumber, minInt) == + STNumber(sfNumber, Number{-9'223'372'036'854'775, 3})); } else { BEAST_EXPECT( - numberFromJson(sfNumber, maxInt) == STNumber(sfNumber, Number{9'223'372'036'854'775'807, 0})); + numberFromJson(sfNumber, maxInt) == + STNumber(sfNumber, Number{9'223'372'036'854'775'807, 0})); BEAST_EXPECT( numberFromJson(sfNumber, minInt) == - STNumber(sfNumber, Number{true, 9'223'372'036'854'775'808ULL, 0, Number::normalized{}})); + STNumber( + sfNumber, + Number{true, 9'223'372'036'854'775'808ULL, 0, Number::normalized{}})); } } constexpr auto imin = std::numeric_limits::min(); BEAST_EXPECT(numberFromJson(sfNumber, imin) == STNumber(sfNumber, Number(imin, 0))); - BEAST_EXPECT(numberFromJson(sfNumber, std::to_string(imin)) == STNumber(sfNumber, Number(imin, 0))); + BEAST_EXPECT( + numberFromJson(sfNumber, std::to_string(imin)) == + STNumber(sfNumber, Number(imin, 0))); constexpr auto imax = std::numeric_limits::max(); BEAST_EXPECT(numberFromJson(sfNumber, imax) == STNumber(sfNumber, Number(imax, 0))); - BEAST_EXPECT(numberFromJson(sfNumber, std::to_string(imax)) == STNumber(sfNumber, Number(imax, 0))); + BEAST_EXPECT( + numberFromJson(sfNumber, std::to_string(imax)) == + STNumber(sfNumber, Number(imax, 0))); constexpr auto umax = std::numeric_limits::max(); BEAST_EXPECT(numberFromJson(sfNumber, umax) == STNumber(sfNumber, Number(umax, 0))); - BEAST_EXPECT(numberFromJson(sfNumber, std::to_string(umax)) == STNumber(sfNumber, Number(umax, 0))); + BEAST_EXPECT( + numberFromJson(sfNumber, std::to_string(umax)) == + STNumber(sfNumber, Number(umax, 0))); // Obvious non-numbers tested here try diff --git a/src/test/protocol/STObject_test.cpp b/src/test/protocol/STObject_test.cpp index 861a1ab967..058df3ba82 100644 --- a/src/test/protocol/STObject_test.cpp +++ b/src/test/protocol/STObject_test.cpp @@ -63,7 +63,9 @@ public: unexpected(object1.getSerializer() != object2.getSerializer(), "STObject error 1"); - unexpected(object1.isFieldPresent(sfTestH256) || !object1.isFieldPresent(sfTestVL), "STObject error"); + unexpected( + object1.isFieldPresent(sfTestH256) || !object1.isFieldPresent(sfTestVL), + "STObject error"); object1.makeFieldPresent(sfTestH256); @@ -325,7 +327,8 @@ public: { STObject st(sfGeneric); auto const v = ~st[~sf1Outer]; - static_assert(std::is_same, std::optional>::value, ""); + static_assert( + std::is_same, std::optional>::value, ""); } // UDT scalar fields @@ -399,7 +402,8 @@ public: BEAST_EXPECT(cst[~sf]->size() == 2); BEAST_EXPECT(cst[sf][0] == 1); BEAST_EXPECT(cst[sf][1] == 2); - static_assert(std::is_same const&>::value, ""); + static_assert( + std::is_same const&>::value, ""); } // Default by reference field diff --git a/src/test/protocol/STParsedJSON_test.cpp b/src/test/protocol/STParsedJSON_test.cpp index 0ef7878cdc..6838f557a9 100644 --- a/src/test/protocol/STParsedJSON_test.cpp +++ b/src/test/protocol/STParsedJSON_test.cpp @@ -336,7 +336,22 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object->isFieldPresent(sfEmailHash)); BEAST_EXPECT(obj.object->getFieldH128(sfEmailHash).size() == 16); std::array expected = { - 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; + 0x01, + 0x23, + 0x45, + 0x67, + 0x89, + 0xAB, + 0xCD, + 0xEF, + 0x01, + 0x23, + 0x45, + 0x67, + 0x89, + 0xAB, + 0xCD, + 0xEF}; BEAST_EXPECT(obj.object->getFieldH128(sfEmailHash) == uint128{expected}); } @@ -423,8 +438,9 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfTakerPaysCurrency)); BEAST_EXPECT(obj.object->getFieldH160(sfTakerPaysCurrency).size() == 20); - std::array expected = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, - 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67}; + std::array expected = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, + 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, + 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67}; BEAST_EXPECT(obj.object->getFieldH160(sfTakerPaysCurrency) == uint160{expected}); } // Valid lowercase hex string for UInt160 @@ -502,8 +518,9 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfMPTokenIssuanceID)); BEAST_EXPECT(obj.object->getFieldH192(sfMPTokenIssuanceID).size() == 24); - std::array expected = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; + std::array expected = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; BEAST_EXPECT(obj.object->getFieldH192(sfMPTokenIssuanceID) == uint192{expected}); } @@ -593,9 +610,10 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfLedgerHash)); BEAST_EXPECT(obj.object->getFieldH256(sfLedgerHash).size() == 32); - std::array expected = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, - 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, - 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; + std::array expected = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, + 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, + 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, + 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; BEAST_EXPECT(obj.object->getFieldH256(sfLedgerHash) == uint256{expected}); } // Valid lowercase hex string for UInt256 @@ -709,7 +727,8 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); if (BEAST_EXPECT(obj.object->isFieldPresent(sfLoanScale))) - BEAST_EXPECT(obj.object->getFieldI32(sfLoanScale) == static_cast(maxUInt32)); + BEAST_EXPECT( + obj.object->getFieldI32(sfLoanScale) == static_cast(maxUInt32)); } // Test with string value @@ -1197,9 +1216,13 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!ps.empty()); BEAST_EXPECT(ps.size() == 1); BEAST_EXPECT(ps[0].size() == 1); - BEAST_EXPECT(ps[0][0].getAccountID() == parseBase58("rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")); + BEAST_EXPECT( + ps[0][0].getAccountID() == + parseBase58("rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")); BEAST_EXPECT(to_string(ps[0][0].getCurrency()) == "USD"); - BEAST_EXPECT(ps[0][0].getIssuerID() == parseBase58("rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe")); + BEAST_EXPECT( + ps[0][0].getIssuerID() == + parseBase58("rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe")); } } @@ -1374,7 +1397,8 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(issue.currency.size() == 20); BEAST_EXPECT(to_string(issue.currency) == "USD"); BEAST_EXPECT(issue.account.size() == 20); - BEAST_EXPECT(issue.account == parseBase58("rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")); + BEAST_EXPECT( + issue.account == parseBase58("rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")); } } @@ -2003,8 +2027,9 @@ class STParsedJSON_test : public beast::unit_test::suite } { - std::string const goodJson(R"({"CloseResolution":19,"Method":250,)" - R"("TransactionResult":"tecFROZEN"})"); + std::string const goodJson( + R"({"CloseResolution":19,"Method":250,)" + R"("TransactionResult":"tecFROZEN"})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(goodJson, jv))) @@ -2012,17 +2037,20 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject parsed("test", jv); if (BEAST_EXPECT(parsed.object)) { - std::string const& serialized(to_string(parsed.object->getJson(JsonOptions::none))); + std::string const& serialized( + to_string(parsed.object->getJson(JsonOptions::none))); BEAST_EXPECT(serialized == goodJson); } } } { - std::string const goodJson(R"({"CloseResolution":19,"Method":"250",)" - R"("TransactionResult":"tecFROZEN"})"); - std::string const expectedJson(R"({"CloseResolution":19,"Method":250,)" - R"("TransactionResult":"tecFROZEN"})"); + std::string const goodJson( + R"({"CloseResolution":19,"Method":"250",)" + R"("TransactionResult":"tecFROZEN"})"); + std::string const expectedJson( + R"({"CloseResolution":19,"Method":250,)" + R"("TransactionResult":"tecFROZEN"})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(goodJson, jv))) @@ -2033,17 +2061,20 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject parsed("test", jv); if (BEAST_EXPECT(parsed.object)) { - std::string const& serialized(to_string(parsed.object->getJson(JsonOptions::none))); + std::string const& serialized( + to_string(parsed.object->getJson(JsonOptions::none))); BEAST_EXPECT(serialized == expectedJson); } } } { - std::string const goodJson(R"({"CloseResolution":"19","Method":"250",)" - R"("TransactionResult":"tecFROZEN"})"); - std::string const expectedJson(R"({"CloseResolution":19,"Method":250,)" - R"("TransactionResult":"tecFROZEN"})"); + std::string const goodJson( + R"({"CloseResolution":"19","Method":"250",)" + R"("TransactionResult":"tecFROZEN"})"); + std::string const expectedJson( + R"({"CloseResolution":19,"Method":250,)" + R"("TransactionResult":"tecFROZEN"})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(goodJson, jv))) @@ -2054,15 +2085,17 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject parsed("test", jv); if (BEAST_EXPECT(parsed.object)) { - std::string const& serialized(to_string(parsed.object->getJson(JsonOptions::none))); + std::string const& serialized( + to_string(parsed.object->getJson(JsonOptions::none))); BEAST_EXPECT(serialized == expectedJson); } } } { - std::string const json(R"({"CloseResolution":19,"Method":250,)" - R"("TransactionResult":"terQUEUED"})"); + std::string const json( + R"({"CloseResolution":19,"Method":250,)" + R"("TransactionResult":"terQUEUED"})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(json, jv))) @@ -2071,13 +2104,16 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.TransactionResult' is out of range."); + BEAST_EXPECT( + parsed.error[jss::error_message] == + "Field 'test.TransactionResult' is out of range."); } } { - std::string const json(R"({"CloseResolution":19,"Method":"pony",)" - R"("TransactionResult":"tesSUCCESS"})"); + std::string const json( + R"({"CloseResolution":19,"Method":"pony",)" + R"("TransactionResult":"tesSUCCESS"})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(json, jv))) @@ -2086,13 +2122,15 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.Method' has bad type."); + BEAST_EXPECT( + parsed.error[jss::error_message] == "Field 'test.Method' has bad type."); } } { - std::string const json(R"({"CloseResolution":19,"Method":3294967296,)" - R"("TransactionResult":"tesSUCCESS"})"); + std::string const json( + R"({"CloseResolution":19,"Method":3294967296,)" + R"("TransactionResult":"tesSUCCESS"})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(json, jv))) @@ -2101,13 +2139,15 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.Method' is out of range."); + BEAST_EXPECT( + parsed.error[jss::error_message] == "Field 'test.Method' is out of range."); } } { - std::string const json(R"({"CloseResolution":-10,"Method":42,)" - R"("TransactionResult":"tesSUCCESS"})"); + std::string const json( + R"({"CloseResolution":-10,"Method":42,)" + R"("TransactionResult":"tesSUCCESS"})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(json, jv))) @@ -2116,13 +2156,16 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.CloseResolution' is out of range."); + BEAST_EXPECT( + parsed.error[jss::error_message] == + "Field 'test.CloseResolution' is out of range."); } } { - std::string const json(R"({"CloseResolution":19,"Method":3.141592653,)" - R"("TransactionResult":"tesSUCCESS"})"); + std::string const json( + R"({"CloseResolution":19,"Method":3.141592653,)" + R"("TransactionResult":"tesSUCCESS"})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(json, jv))) @@ -2131,15 +2174,18 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.Method' has bad type."); + BEAST_EXPECT( + parsed.error[jss::error_message] == "Field 'test.Method' has bad type."); } } { - std::string const goodJson(R"({"CloseResolution":19,"Method":250,)" - R"("TransferFee":"65535"})"); - std::string const expectedJson(R"({"CloseResolution":19,"Method":250,)" - R"("TransferFee":65535})"); + std::string const goodJson( + R"({"CloseResolution":19,"Method":250,)" + R"("TransferFee":"65535"})"); + std::string const expectedJson( + R"({"CloseResolution":19,"Method":250,)" + R"("TransferFee":65535})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(goodJson, jv))) @@ -2147,15 +2193,17 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject parsed("test", jv); if (BEAST_EXPECT(parsed.object)) { - std::string const& serialized(to_string(parsed.object->getJson(JsonOptions::none))); + std::string const& serialized( + to_string(parsed.object->getJson(JsonOptions::none))); BEAST_EXPECT(serialized == expectedJson); } } } { - std::string const json(R"({"CloseResolution":19,"Method":250,)" - R"("TransferFee":"65536"})"); + std::string const json( + R"({"CloseResolution":19,"Method":250,)" + R"("TransferFee":"65536"})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(json, jv))) @@ -2164,13 +2212,16 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.TransferFee' has invalid data."); + BEAST_EXPECT( + parsed.error[jss::error_message] == + "Field 'test.TransferFee' has invalid data."); } } { - std::string const json(R"({"CloseResolution":19,"Method":250,)" - R"("TransferFee":"Payment"})"); + std::string const json( + R"({"CloseResolution":19,"Method":250,)" + R"("TransferFee":"Payment"})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(json, jv))) @@ -2179,13 +2230,16 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.TransferFee' has invalid data."); + BEAST_EXPECT( + parsed.error[jss::error_message] == + "Field 'test.TransferFee' has invalid data."); } } { - std::string const json(R"({"CloseResolution":19,"Method":250,)" - R"("TransferFee":true})"); + std::string const json( + R"({"CloseResolution":19,"Method":250,)" + R"("TransferFee":true})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(json, jv))) @@ -2194,7 +2248,8 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.TransferFee' has bad type."); + BEAST_EXPECT( + parsed.error[jss::error_message] == "Field 'test.TransferFee' has bad type."); } } } diff --git a/src/test/protocol/STTx_test.cpp b/src/test/protocol/STTx_test.cpp index 853ff35635..86e5e88d0a 100644 --- a/src/test/protocol/STTx_test.cpp +++ b/src/test/protocol/STTx_test.cpp @@ -47,814 +47,1042 @@ public: { testcase("Malformed serialized form"); - constexpr unsigned char payload1[] = {0x0a, 0xff, 0xff, 0xff, 0xff, 0x63, 0x63, 0x63, 0x63, 0x63, - 0x63, 0x63, 0x63, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, - 0x1b, 0x1b, 0x29, 0x1b, 0x1b, 0x1b, 0x1b, 0xef, 0xef, 0xef, - 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef}; + constexpr unsigned char payload1[] = { + 0x0a, 0xff, 0xff, 0xff, 0xff, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, + 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x29, 0x1b, 0x1b, 0x1b, + 0x1b, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef}; constexpr unsigned char payload2[] = { - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, - 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, - 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, - 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, - 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, - 0x26, 0xdf, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, - 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, - 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, - 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, - 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, - 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, - 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, - 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, - 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, - 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, - 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, - 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, - 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, - 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, - 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, - 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, - 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, - 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, - 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xe7, 0x27, 0xdf, 0xff, 0xff, - 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, - 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, - 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, - 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, - 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, - 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, - 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, - 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, - 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, - 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, - 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, - 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, - 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, - 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, - 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, - 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, - 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, - 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, - 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, - 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, - 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x14, 0x14, 0x14, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, - 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, - 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, - 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, - 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, - 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, - 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, - 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, - 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, - 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xda, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, - 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, - 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, - 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, - 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, - 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, - 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, - 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, - 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0x29, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xef, - 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, - 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, - 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, - 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, - 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, - 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, - 0xe7, 0x3b, 0x3b, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, - 0x3b, 0x7f, 0x3b, 0x3b, 0xef, 0xfd, 0xf1, 0xff, 0xf1, 0xff, 0xf1, 0xfb, 0xef, 0xfd, 0xf1, 0xff, 0xf1, 0xfd, - 0xf1, 0xfb, 0xf1, 0xfd, 0xf1, 0xef, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0x01, 0x00, 0xfd, 0xf1, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0x3b, 0x3b, 0x43, - 0x3b, 0x3b, 0xff, 0x3b, 0x12, 0xf1, 0x12, 0x12, 0x12, 0xff}; + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, + 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, + 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, + 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, + 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, + 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, + 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, + 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, + 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, + 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, + 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, + 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, + 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, + 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, + 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, + 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, + 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, + 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, + 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, + 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, + 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, + 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, + 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, + 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, + 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, + 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, + 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, + 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, + 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, + 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, + 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, + 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, + 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, + 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, + 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xe7, 0x27, 0xdf, 0xff, 0xff, + 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, + 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, + 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, + 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, + 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, + 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, + 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, + 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, + 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, + 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, + 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, + 0x26, 0xdf, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, + 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, + 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, + 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, + 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, + 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, + 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, + 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, + 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, + 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, + 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, 0x29, 0xe7, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, + 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, + 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, + 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, + 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, + 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, + 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, + 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, + 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x14, 0x14, 0x14, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, + 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, + 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, + 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, + 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, + 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, + 0x67, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, + 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, + 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, + 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, + 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, + 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, + 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, + 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xda, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, + 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, + 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, + 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, + 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, + 0x3b, 0x3b, 0x3b, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, + 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, + 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, + 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, + 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, + 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0x29, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xef, + 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, + 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, + 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xef, 0xff, 0xef, 0xf4, + 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, + 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, + 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, + 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, + 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, + 0xe7, 0x3b, 0x3b, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0x3b, 0x3b, 0x3b, + 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x7f, 0x3b, 0x3b, 0xef, 0xfd, + 0xf1, 0xff, 0xf1, 0xff, 0xf1, 0xfb, 0xef, 0xfd, 0xf1, 0xff, 0xf1, 0xfd, 0xf1, 0xfb, + 0xf1, 0xfd, 0xf1, 0xef, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0x01, 0x00, 0xfd, 0xf1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0x3b, 0x3b, 0x43, 0x3b, 0x3b, 0xff, 0x3b, + 0x12, 0xf1, 0x12, 0x12, 0x12, 0xff}; constexpr unsigned char payload3[] = { - 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x4f, 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, - 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, - 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe, 0xf3, 0xe7, 0xe5, 0x65, - 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, 0x20, - 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x02, 0x00, 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x4f, 0x00, - 0x00, 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x24, 0x59, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x54, 0x72, 0x61, 0x6e, 0x00, - 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, - 0xfe, 0xf3, 0xe7, 0xe5, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, 0x20, 0xf6, - 0x00, 0x00, 0x03, 0x1f, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x73, - 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe}; + 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x4f, 0x00, 0x00, + 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, + 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe, 0xf3, 0xe7, + 0xe5, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, 0x20, + 0x1f, 0x03, 0xf6, 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, + 0x00, 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x4f, 0x00, + 0x00, 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, + 0x24, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x54, 0x72, 0x61, 0x6e, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe, 0xf3, + 0xe7, 0xe5, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, + 0x20, 0xf6, 0x00, 0x00, 0x03, 0x1f, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, + 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, + 0x10, 0x00, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe}; constexpr unsigned char payload4[] = { - 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x4f, 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, - 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, - 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe, 0xf3, 0xe7, 0xe5, 0x65, - 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, - 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x4f, - 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x24, 0x59, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x54, 0x72, 0x61, 0x6e, - 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xe5, 0xfe, 0xf3, 0xe7, 0xe5, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, 0x20, - 0xf6, 0x00, 0x00, 0x03, 0x1f, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, - 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe}; + 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x4f, 0x00, 0x00, + 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, + 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe, 0xf3, 0xe7, + 0xe5, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, 0x00, + 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, + 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x4f, + 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, + 0x35, 0x24, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x02, 0x00, 0x54, 0x72, 0x61, 0x6e, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe, + 0xf3, 0xe7, 0xe5, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x6f, 0x00, + 0x00, 0x20, 0xf6, 0x00, 0x00, 0x03, 0x1f, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, + 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x73, 0x00, 0x81, 0x14, + 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe}; // Construct an STObject with 11 levels of object nesting so the // maximum nesting level exception is thrown. @@ -910,7 +1138,8 @@ public: } catch (std::runtime_error const& ex) { - BEAST_EXPECT(std::strcmp(ex.what(), "Maximum nesting depth of STVar exceeded") == 0); + BEAST_EXPECT( + std::strcmp(ex.what(), "Maximum nesting depth of STVar exceeded") == 0); } } { @@ -973,7 +1202,8 @@ public: } catch (std::runtime_error const& ex) { - BEAST_EXPECT(std::strcmp(ex.what(), "Maximum nesting depth of STVar exceeded") == 0); + BEAST_EXPECT( + std::strcmp(ex.what(), "Maximum nesting depth of STVar exceeded") == 0); } } diff --git a/src/test/protocol/STValidation_test.cpp b/src/test/protocol/STValidation_test.cpp index 0c0951fde2..e426af3e44 100644 --- a/src/test/protocol/STValidation_test.cpp +++ b/src/test/protocol/STValidation_test.cpp @@ -14,109 +14,123 @@ class STValidation_test : public beast::unit_test::suite { // No public key: static constexpr std::uint8_t payload1[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x3A, 0x4E, - 0x69, 0x6B, 0x2B, 0x54, 0x69, 0x66, 0x66, 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, - 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, - 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, - 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, 0xD9, - 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x76, 0x47, 0x30, 0x45, 0x02, 0x21, 0x00, 0xAF, 0x1D, 0x17, 0xA2, - 0x12, 0x7B, 0xA4, 0x6B, 0x40, 0xBD, 0x58, 0x76, 0x39, 0x3F, 0xF4, 0x49, 0x6B, 0x25, 0xA1, 0xAD, 0xB7, - 0x36, 0xFB, 0x64, 0x4C, 0x05, 0x21, 0x0C, 0x43, 0x02, 0xE5, 0xEE, 0x02, 0x20, 0x26, 0x01, 0x7C, 0x5F, - 0x69, 0xDA, 0xD1, 0xC3, 0x28, 0xED, 0x80, 0x05, 0x36, 0x86, 0x8B, 0x1B, 0x22, 0xE4, 0x8E, 0x09, 0x11, - 0x52, 0x28, 0x5A, 0x48, 0x8F, 0x98, 0x7A, 0x5A, 0x10, 0x74, 0xCC}; + 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, + 0x3A, 0x4E, 0x69, 0x6B, 0x2B, 0x54, 0x69, 0x66, 0x66, 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, + 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, + 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, + 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, + 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, + 0xE0, 0x76, 0x47, 0x30, 0x45, 0x02, 0x21, 0x00, 0xAF, 0x1D, 0x17, 0xA2, 0x12, 0x7B, 0xA4, + 0x6B, 0x40, 0xBD, 0x58, 0x76, 0x39, 0x3F, 0xF4, 0x49, 0x6B, 0x25, 0xA1, 0xAD, 0xB7, 0x36, + 0xFB, 0x64, 0x4C, 0x05, 0x21, 0x0C, 0x43, 0x02, 0xE5, 0xEE, 0x02, 0x20, 0x26, 0x01, 0x7C, + 0x5F, 0x69, 0xDA, 0xD1, 0xC3, 0x28, 0xED, 0x80, 0x05, 0x36, 0x86, 0x8B, 0x1B, 0x22, 0xE4, + 0x8E, 0x09, 0x11, 0x52, 0x28, 0x5A, 0x48, 0x8F, 0x98, 0x7A, 0x5A, 0x10, 0x74, 0xCC}; // Short public key: static constexpr std::uint8_t payload2[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x51, 0x53, 0x1F, - 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, - 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, - 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, - 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x20, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, - 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, - 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x76, 0x46, 0x30, 0x44, 0x02, 0x20, 0x34, 0x89, 0xA3, 0xBF, - 0xA9, 0x97, 0x13, 0xBC, 0x87, 0x61, 0xC5, 0x2B, 0x7F, 0xAA, 0xE9, 0x31, 0x4C, 0xCD, 0x6F, 0x57, 0x68, 0x70, - 0xC8, 0xDC, 0x58, 0x76, 0x91, 0x2F, 0x70, 0x2F, 0xD0, 0x78, 0x02, 0x20, 0x7E, 0x57, 0x9D, 0xCA, 0x11, 0xF1, - 0x3B, 0xA0, 0x39, 0x38, 0x37, 0x40, 0xC5, 0xC8, 0xFE, 0xC1, 0xFC, 0xE9, 0xE7, 0x84, 0x6C, 0x2D, 0x47, 0x6E, + 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, + 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, + 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, + 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, + 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, + 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x20, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, + 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, + 0xA5, 0xC3, 0x3E, 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x76, 0x46, 0x30, 0x44, + 0x02, 0x20, 0x34, 0x89, 0xA3, 0xBF, 0xA9, 0x97, 0x13, 0xBC, 0x87, 0x61, 0xC5, 0x2B, 0x7F, + 0xAA, 0xE9, 0x31, 0x4C, 0xCD, 0x6F, 0x57, 0x68, 0x70, 0xC8, 0xDC, 0x58, 0x76, 0x91, 0x2F, + 0x70, 0x2F, 0xD0, 0x78, 0x02, 0x20, 0x7E, 0x57, 0x9D, 0xCA, 0x11, 0xF1, 0x3B, 0xA0, 0x39, + 0x38, 0x37, 0x40, 0xC5, 0xC8, 0xFE, 0xC1, 0xFC, 0xE9, 0xE7, 0x84, 0x6C, 0x2D, 0x47, 0x6E, 0xD7, 0xFF, 0x83, 0x9D, 0xEF, 0x7D, 0xF7, 0x6A}; // Long public key: static constexpr std::uint8_t payload3[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x51, 0x53, 0x1F, - 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, - 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, - 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, - 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x22, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, - 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, - 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32, 0x78, 0x76, 0x46, 0x30, 0x44, 0x02, 0x20, 0x3C, 0xAB, - 0xEE, 0x36, 0xD8, 0xF3, 0x74, 0x5F, 0x50, 0x28, 0x66, 0x17, 0x57, 0x26, 0x6A, 0xBD, 0x9A, 0x19, 0x08, 0xAA, - 0x65, 0x94, 0x0B, 0xDF, 0x24, 0x20, 0x44, 0x99, 0x05, 0x8C, 0xB7, 0x3D, 0x02, 0x20, 0x79, 0x66, 0xE6, 0xCC, - 0xA2, 0x5E, 0x15, 0xFE, 0x18, 0x4B, 0xB2, 0xA8, 0x01, 0x3A, 0xD6, 0x63, 0x54, 0x08, 0x1B, 0xDA, 0xD0, 0x04, + 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, + 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, + 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, + 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, + 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, + 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x22, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, + 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, + 0xA5, 0xC3, 0x3E, 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32, 0x78, 0x76, 0x46, + 0x30, 0x44, 0x02, 0x20, 0x3C, 0xAB, 0xEE, 0x36, 0xD8, 0xF3, 0x74, 0x5F, 0x50, 0x28, 0x66, + 0x17, 0x57, 0x26, 0x6A, 0xBD, 0x9A, 0x19, 0x08, 0xAA, 0x65, 0x94, 0x0B, 0xDF, 0x24, 0x20, + 0x44, 0x99, 0x05, 0x8C, 0xB7, 0x3D, 0x02, 0x20, 0x79, 0x66, 0xE6, 0xCC, 0xA2, 0x5E, 0x15, + 0xFE, 0x18, 0x4B, 0xB2, 0xA8, 0x01, 0x3A, 0xD6, 0x63, 0x54, 0x08, 0x1B, 0xDA, 0xD0, 0x04, 0xEF, 0x4C, 0x73, 0xB3, 0xFF, 0xFE, 0xA9, 0x8E, 0x92, 0xE8}; // Ed25519 public key: static constexpr std::uint8_t payload4[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x51, 0x53, - 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, - 0x4B, 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, - 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, - 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0xED, - 0x04, 0x8B, 0x9A, 0x31, 0x5E, 0xC7, 0x33, 0xC0, 0x15, 0x3B, 0x67, 0x04, 0x73, 0x7A, 0x91, 0x3D, 0xEF, - 0x57, 0x1D, 0xAD, 0xEC, 0x57, 0xE5, 0x91, 0x5D, 0x55, 0xD9, 0x32, 0x9D, 0x45, 0x12, 0x85, 0x76, 0x40, - 0x52, 0x07, 0xF9, 0x0D, 0x18, 0x2B, 0xB7, 0xAF, 0x5D, 0x43, 0xF8, 0xF9, 0xC5, 0xAD, 0xF9, 0xBA, 0x33, - 0x23, 0xC0, 0x2F, 0x95, 0xFF, 0x36, 0x94, 0xD8, 0x99, 0x99, 0xE0, 0x66, 0xF8, 0xB6, 0x27, 0x22, 0xFD, - 0x29, 0x39, 0x30, 0x39, 0xAB, 0x93, 0xDB, 0x9D, 0x2C, 0xE5, 0xF0, 0x4C, 0xB7, 0x30, 0xFD, 0xC7, 0xD3, - 0x21, 0xC9, 0x4E, 0x0D, 0x8A, 0x1B, 0xB2, 0x89, 0x97, 0x10, 0x7E, 0x84, 0x09}; + 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, + 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, + 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, + 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, + 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, + 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0xED, 0x04, 0x8B, 0x9A, 0x31, 0x5E, + 0xC7, 0x33, 0xC0, 0x15, 0x3B, 0x67, 0x04, 0x73, 0x7A, 0x91, 0x3D, 0xEF, 0x57, 0x1D, 0xAD, + 0xEC, 0x57, 0xE5, 0x91, 0x5D, 0x55, 0xD9, 0x32, 0x9D, 0x45, 0x12, 0x85, 0x76, 0x40, 0x52, + 0x07, 0xF9, 0x0D, 0x18, 0x2B, 0xB7, 0xAF, 0x5D, 0x43, 0xF8, 0xF9, 0xC5, 0xAD, 0xF9, 0xBA, + 0x33, 0x23, 0xC0, 0x2F, 0x95, 0xFF, 0x36, 0x94, 0xD8, 0x99, 0x99, 0xE0, 0x66, 0xF8, 0xB6, + 0x27, 0x22, 0xFD, 0x29, 0x39, 0x30, 0x39, 0xAB, 0x93, 0xDB, 0x9D, 0x2C, 0xE5, 0xF0, 0x4C, + 0xB7, 0x30, 0xFD, 0xC7, 0xD3, 0x21, 0xC9, 0x4E, 0x0D, 0x8A, 0x1B, 0xB2, 0x89, 0x97, 0x10, + 0x7E, 0x84, 0x09}; // No ledger sequence: static constexpr std::uint8_t payload5[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, - 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, 0x8C, 0xDE, 0xB8, - 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, - 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, - 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, - 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, - 0x3E, 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32, 0x76, 0x47, 0x30, 0x45, 0x02, 0x21, 0x00, - 0x83, 0xB3, 0x1B, 0xE9, 0x03, 0x8F, 0x4A, 0x92, 0x8B, 0x9B, 0x51, 0xEF, 0x79, 0xED, 0xA1, 0x4A, 0x58, - 0x9B, 0x20, 0xCF, 0x89, 0xC4, 0x75, 0x99, 0x5F, 0x6D, 0x79, 0x51, 0x79, 0x07, 0xF9, 0x93, 0x02, 0x20, - 0x39, 0xA6, 0x0C, 0x77, 0x68, 0x84, 0x50, 0xDB, 0xDA, 0x64, 0x32, 0x74, 0xEC, 0x63, 0x48, 0x48, 0x96, - 0xB5, 0x94, 0x57, 0x55, 0x8D, 0x7D, 0xD8, 0x25, 0x78, 0xD1, 0xEA, 0x5F, 0xD9, 0xC7, 0xAA}; + 0x22, 0x80, 0x00, 0x00, 0x01, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x51, 0x53, 0x1F, 0x1A, 0x4E, + 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, + 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, + 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, + 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, + 0xC2, 0xE0, 0x73, 0x21, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, 0xE5, 0xC0, 0xD8, 0x58, 0x73, + 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, 0x92, 0x8C, + 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32, 0x76, 0x47, 0x30, 0x45, 0x02, 0x21, 0x00, 0x83, + 0xB3, 0x1B, 0xE9, 0x03, 0x8F, 0x4A, 0x92, 0x8B, 0x9B, 0x51, 0xEF, 0x79, 0xED, 0xA1, 0x4A, + 0x58, 0x9B, 0x20, 0xCF, 0x89, 0xC4, 0x75, 0x99, 0x5F, 0x6D, 0x79, 0x51, 0x79, 0x07, 0xF9, + 0x93, 0x02, 0x20, 0x39, 0xA6, 0x0C, 0x77, 0x68, 0x84, 0x50, 0xDB, 0xDA, 0x64, 0x32, 0x74, + 0xEC, 0x63, 0x48, 0x48, 0x96, 0xB5, 0x94, 0x57, 0x55, 0x8D, 0x7D, 0xD8, 0x25, 0x78, 0xD1, + 0xEA, 0x5F, 0xD9, 0xC7, 0xAA}; // No sign time: static constexpr std::uint8_t payload6[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, - 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, 0x8C, 0xDE, 0xB8, - 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, - 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, - 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, - 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, - 0x3E, 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32, 0x76, 0x47, 0x30, 0x45, 0x02, 0x21, 0x00, - 0xDD, 0xB0, 0x59, 0x9A, 0x02, 0x3E, 0xF2, 0x44, 0xCE, 0x1D, 0xA8, 0x99, 0x06, 0xF3, 0x8A, 0x4B, 0xEB, - 0x95, 0x42, 0x63, 0x6A, 0x6C, 0x04, 0x30, 0x7F, 0x62, 0x78, 0x3A, 0x89, 0xB0, 0x3F, 0x22, 0x02, 0x20, - 0x4E, 0x6A, 0x55, 0x63, 0x8A, 0x19, 0xED, 0xFE, 0x70, 0x34, 0xD1, 0x30, 0xED, 0x7C, 0xAF, 0xB2, 0x78, - 0xBB, 0x15, 0x6C, 0x42, 0x3E, 0x19, 0x5D, 0xEA, 0xC5, 0x5E, 0x23, 0xE2, 0x14, 0x80, 0x54}; + 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x51, 0x53, 0x1F, 0x1A, 0x4E, + 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, + 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, + 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, + 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, + 0xC2, 0xE0, 0x73, 0x21, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, 0xE5, 0xC0, 0xD8, 0x58, 0x73, + 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, 0x92, 0x8C, + 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32, 0x76, 0x47, 0x30, 0x45, 0x02, 0x21, 0x00, 0xDD, + 0xB0, 0x59, 0x9A, 0x02, 0x3E, 0xF2, 0x44, 0xCE, 0x1D, 0xA8, 0x99, 0x06, 0xF3, 0x8A, 0x4B, + 0xEB, 0x95, 0x42, 0x63, 0x6A, 0x6C, 0x04, 0x30, 0x7F, 0x62, 0x78, 0x3A, 0x89, 0xB0, 0x3F, + 0x22, 0x02, 0x20, 0x4E, 0x6A, 0x55, 0x63, 0x8A, 0x19, 0xED, 0xFE, 0x70, 0x34, 0xD1, 0x30, + 0xED, 0x7C, 0xAF, 0xB2, 0x78, 0xBB, 0x15, 0x6C, 0x42, 0x3E, 0x19, 0x5D, 0xEA, 0xC5, 0x5E, + 0x23, 0xE2, 0x14, 0x80, 0x54}; // No signature field: static constexpr std::uint8_t payload7[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x51, 0x53, - 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, - 0x4B, 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, - 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, - 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0x02, - 0x9D, 0x19, 0xFB, 0x09, 0x40, 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, - 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32}; + 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, + 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, + 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, + 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, + 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, + 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, + 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, + 0xA5, 0xC3, 0x3E, 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32}; // Good: static constexpr std::uint8_t payload8[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x51, 0x53, 0x1F, - 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, - 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, - 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, - 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, - 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, - 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32, 0x76, 0x47, 0x30, 0x45, 0x02, 0x21, 0x00, 0xDD, 0x29, - 0xDC, 0xAC, 0x82, 0x5E, 0xF9, 0xE2, 0x2D, 0x26, 0x03, 0x95, 0xC2, 0x11, 0x3A, 0x2A, 0x83, 0xEE, 0xA0, 0x2B, - 0x9F, 0x2A, 0x51, 0xBD, 0x6B, 0xF7, 0x83, 0xCE, 0x4A, 0x7C, 0x52, 0x29, 0x02, 0x20, 0x52, 0x45, 0xB9, 0x07, - 0x57, 0xEF, 0xB2, 0x6C, 0x69, 0xC5, 0x47, 0xCA, 0xE2, 0x76, 0x00, 0xFC, 0x35, 0x46, 0x5D, 0x19, 0x64, 0xCE, + 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, + 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, + 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, + 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, + 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, + 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, + 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, + 0xA5, 0xC3, 0x3E, 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32, 0x76, 0x47, 0x30, + 0x45, 0x02, 0x21, 0x00, 0xDD, 0x29, 0xDC, 0xAC, 0x82, 0x5E, 0xF9, 0xE2, 0x2D, 0x26, 0x03, + 0x95, 0xC2, 0x11, 0x3A, 0x2A, 0x83, 0xEE, 0xA0, 0x2B, 0x9F, 0x2A, 0x51, 0xBD, 0x6B, 0xF7, + 0x83, 0xCE, 0x4A, 0x7C, 0x52, 0x29, 0x02, 0x20, 0x52, 0x45, 0xB9, 0x07, 0x57, 0xEF, 0xB2, + 0x6C, 0x69, 0xC5, 0x47, 0xCA, 0xE2, 0x76, 0x00, 0xFC, 0x35, 0x46, 0x5D, 0x19, 0x64, 0xCE, 0xCA, 0x88, 0xA1, 0x2A, 0x20, 0xCF, 0x3C, 0xF9, 0xCE, 0xCF}; public: @@ -129,7 +143,8 @@ public: { SerialIter sit{payload8}; - auto val = std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, true); + auto val = std::make_shared( + sit, [](PublicKey const& pk) { return calcNodeID(pk); }, true); BEAST_EXPECT(val); BEAST_EXPECT(val->isFieldPresent(sfLedgerSequence)); @@ -149,8 +164,8 @@ public: try { SerialIter sit{payload1}; - auto val = - std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); + auto val = std::make_shared( + sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("An exception should have been thrown"); } catch (std::exception const& ex) @@ -161,8 +176,8 @@ public: try { SerialIter sit{payload2}; - auto val = - std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); + auto val = std::make_shared( + sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("An exception should have been thrown"); } catch (std::exception const& ex) @@ -173,8 +188,8 @@ public: try { SerialIter sit{payload3}; - auto val = - std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); + auto val = std::make_shared( + sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("An exception should have been thrown"); } catch (std::exception const& ex) @@ -185,8 +200,8 @@ public: try { SerialIter sit{payload4}; - auto val = - std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); + auto val = std::make_shared( + sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("An exception should have been thrown"); } catch (std::exception const& ex) @@ -199,7 +214,8 @@ public: try { SerialIter sit{payload5}; - auto val = std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); + auto val = std::make_shared( + sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("Expected exception not thrown from validation"); } catch (std::exception const& ex) @@ -210,7 +226,8 @@ public: try { SerialIter sit{payload6}; - auto val = std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); + auto val = std::make_shared( + sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("Expected exception not thrown from validation"); } catch (std::exception const& ex) @@ -222,7 +239,8 @@ public: { SerialIter sit{payload7}; - auto val = std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); + auto val = std::make_shared( + sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("Expected exception not thrown from validation"); } @@ -251,8 +269,8 @@ public: { SerialIter sit{makeSlice(v2)}; - auto val = - std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, true); + auto val = std::make_shared( + sit, [](PublicKey const& pk) { return calcNodeID(pk); }, true); fail("Mutated validation signature checked out: offset=" + std::to_string(i)); } diff --git a/src/test/protocol/SecretKey_test.cpp b/src/test/protocol/SecretKey_test.cpp index 60081c8251..de21c7d88b 100644 --- a/src/test/protocol/SecretKey_test.cpp +++ b/src/test/protocol/SecretKey_test.cpp @@ -31,29 +31,36 @@ public: { testcase("secp256k1: canonicality"); - std::array const digestData{0x34, 0xC1, 0x90, 0x28, 0xC8, 0x0D, 0x21, 0xF3, 0xF4, 0x8C, 0x93, - 0x54, 0x89, 0x5F, 0x8D, 0x5B, 0xF0, 0xD5, 0xEE, 0x7F, 0xF4, 0x57, - 0x64, 0x7C, 0xF6, 0x55, 0xF5, 0x53, 0x0A, 0x30, 0x22, 0xA7}; + std::array const digestData{ + 0x34, 0xC1, 0x90, 0x28, 0xC8, 0x0D, 0x21, 0xF3, 0xF4, 0x8C, 0x93, + 0x54, 0x89, 0x5F, 0x8D, 0x5B, 0xF0, 0xD5, 0xEE, 0x7F, 0xF4, 0x57, + 0x64, 0x7C, 0xF6, 0x55, 0xF5, 0x53, 0x0A, 0x30, 0x22, 0xA7}; - std::array const pkData{0x02, 0x50, 0x96, 0xEB, 0x12, 0xD3, 0xE9, 0x24, 0x23, 0x4E, 0x71, - 0x62, 0x36, 0x9C, 0x11, 0xD8, 0xBF, 0x87, 0x7E, 0xDA, 0x23, 0x87, - 0x78, 0xE7, 0xA3, 0x1F, 0xF0, 0xAA, 0xC5, 0xD0, 0xDB, 0xCF, 0x37}; + std::array const pkData{ + 0x02, 0x50, 0x96, 0xEB, 0x12, 0xD3, 0xE9, 0x24, 0x23, 0x4E, 0x71, + 0x62, 0x36, 0x9C, 0x11, 0xD8, 0xBF, 0x87, 0x7E, 0xDA, 0x23, 0x87, + 0x78, 0xE7, 0xA3, 0x1F, 0xF0, 0xAA, 0xC5, 0xD0, 0xDB, 0xCF, 0x37}; - std::array const skData{0xAA, 0x92, 0x14, 0x17, 0xE7, 0xE5, 0xC2, 0x99, 0xDA, 0x4E, 0xEC, - 0x16, 0xD1, 0xCA, 0xA9, 0x2F, 0x19, 0xB1, 0x9F, 0x2A, 0x68, 0x51, - 0x1F, 0x68, 0xEC, 0x73, 0xBB, 0xB2, 0xF5, 0x23, 0x6F, 0x3D}; + std::array const skData{0xAA, 0x92, 0x14, 0x17, 0xE7, 0xE5, 0xC2, 0x99, + 0xDA, 0x4E, 0xEC, 0x16, 0xD1, 0xCA, 0xA9, 0x2F, + 0x19, 0xB1, 0x9F, 0x2A, 0x68, 0x51, 0x1F, 0x68, + 0xEC, 0x73, 0xBB, 0xB2, 0xF5, 0x23, 0x6F, 0x3D}; std::array const sig{ - 0x30, 0x45, 0x02, 0x21, 0x00, 0xB4, 0x9D, 0x07, 0xF0, 0xE9, 0x34, 0xBA, 0x46, 0x8C, 0x0E, 0xFC, 0x78, 0x11, - 0x77, 0x91, 0x40, 0x8D, 0x1F, 0xB8, 0xB6, 0x3A, 0x64, 0x92, 0xAD, 0x39, 0x5A, 0xC2, 0xF3, 0x60, 0xF2, 0x46, - 0x60, 0x02, 0x20, 0x50, 0x87, 0x39, 0xDB, 0x0A, 0x2E, 0xF8, 0x16, 0x76, 0xE3, 0x9F, 0x45, 0x9C, 0x8B, 0xBB, - 0x07, 0xA0, 0x9C, 0x3E, 0x9F, 0x9B, 0xEB, 0x69, 0x62, 0x94, 0xD5, 0x24, 0xD4, 0x79, 0xD6, 0x27, 0x40}; + 0x30, 0x45, 0x02, 0x21, 0x00, 0xB4, 0x9D, 0x07, 0xF0, 0xE9, 0x34, 0xBA, + 0x46, 0x8C, 0x0E, 0xFC, 0x78, 0x11, 0x77, 0x91, 0x40, 0x8D, 0x1F, 0xB8, + 0xB6, 0x3A, 0x64, 0x92, 0xAD, 0x39, 0x5A, 0xC2, 0xF3, 0x60, 0xF2, 0x46, + 0x60, 0x02, 0x20, 0x50, 0x87, 0x39, 0xDB, 0x0A, 0x2E, 0xF8, 0x16, 0x76, + 0xE3, 0x9F, 0x45, 0x9C, 0x8B, 0xBB, 0x07, 0xA0, 0x9C, 0x3E, 0x9F, 0x9B, + 0xEB, 0x69, 0x62, 0x94, 0xD5, 0x24, 0xD4, 0x79, 0xD6, 0x27, 0x40}; std::array const non{ - 0x30, 0x46, 0x02, 0x21, 0x00, 0xB4, 0x9D, 0x07, 0xF0, 0xE9, 0x34, 0xBA, 0x46, 0x8C, 0x0E, 0xFC, 0x78, 0x11, - 0x77, 0x91, 0x40, 0x8D, 0x1F, 0xB8, 0xB6, 0x3A, 0x64, 0x92, 0xAD, 0x39, 0x5A, 0xC2, 0xF3, 0x60, 0xF2, 0x46, - 0x60, 0x02, 0x21, 0x00, 0xAF, 0x78, 0xC6, 0x24, 0xF5, 0xD1, 0x07, 0xE9, 0x89, 0x1C, 0x60, 0xBA, 0x63, 0x74, - 0x44, 0xF7, 0x1A, 0x12, 0x9E, 0x47, 0x13, 0x5D, 0x36, 0xD9, 0x2A, 0xFD, 0x39, 0xB8, 0x56, 0x60, 0x1A, 0x01}; + 0x30, 0x46, 0x02, 0x21, 0x00, 0xB4, 0x9D, 0x07, 0xF0, 0xE9, 0x34, 0xBA, + 0x46, 0x8C, 0x0E, 0xFC, 0x78, 0x11, 0x77, 0x91, 0x40, 0x8D, 0x1F, 0xB8, + 0xB6, 0x3A, 0x64, 0x92, 0xAD, 0x39, 0x5A, 0xC2, 0xF3, 0x60, 0xF2, 0x46, + 0x60, 0x02, 0x21, 0x00, 0xAF, 0x78, 0xC6, 0x24, 0xF5, 0xD1, 0x07, 0xE9, + 0x89, 0x1C, 0x60, 0xBA, 0x63, 0x74, 0x44, 0xF7, 0x1A, 0x12, 0x9E, 0x47, + 0x13, 0x5D, 0x36, 0xD9, 0x2A, 0xFD, 0x39, 0xB8, 0x56, 0x60, 0x1A, 0x01}; auto const digest = uint256::fromVoid(digestData.data()); @@ -143,7 +150,8 @@ public: // swaps the smallest and largest elements in buffer std::iter_swap( - std::min_element(badData.begin(), badData.end()), std::max_element(badData.begin(), badData.end())); + std::min_element(badData.begin(), badData.end()), + std::max_element(badData.begin(), badData.end())); // Wrong data: should fail BEAST_EXPECT(!verify(pk, makeSlice(badData), sig)); @@ -168,10 +176,11 @@ public: // Ensure that parsing some well-known secret keys works { - auto const sk1 = generateSecretKey(KeyType::secp256k1, generateSeed("masterpassphrase")); + auto const sk1 = + generateSecretKey(KeyType::secp256k1, generateSeed("masterpassphrase")); - auto const sk2 = - parseBase58(TokenType::NodePrivate, "pnen77YEeUd4fFKG7iycBWcwKpTaeFRkW2WFostaATy1DSupwXe"); + auto const sk2 = parseBase58( + TokenType::NodePrivate, "pnen77YEeUd4fFKG7iycBWcwKpTaeFRkW2WFostaATy1DSupwXe"); BEAST_EXPECT(sk2); BEAST_EXPECT(sk1 == *sk2); @@ -180,8 +189,8 @@ public: { auto const sk1 = generateSecretKey(KeyType::ed25519, generateSeed("masterpassphrase")); - auto const sk2 = - parseBase58(TokenType::NodePrivate, "paKv46LztLqK3GaKz1rG2nQGN6M4JLyRtxFBYFTw4wAVHtGys36"); + auto const sk2 = parseBase58( + TokenType::NodePrivate, "paKv46LztLqK3GaKz1rG2nQGN6M4JLyRtxFBYFTw4wAVHtGys36"); BEAST_EXPECT(sk2); BEAST_EXPECT(sk1 == *sk2); diff --git a/src/test/protocol/Seed_test.cpp b/src/test/protocol/Seed_test.cpp index d6b200cca8..9f0ce68c46 100644 --- a/src/test/protocol/Seed_test.cpp +++ b/src/test/protocol/Seed_test.cpp @@ -60,7 +60,8 @@ public: testcase("generation from passphrase"); BEAST_EXPECT(testPassphrase("masterpassphrase") == "snoPBrXtMeMyMHUVTgbuqAfg1SUTb"); BEAST_EXPECT(testPassphrase("Non-Random Passphrase") == "snMKnVku798EnBwUfxeSD8953sLYA"); - BEAST_EXPECT(testPassphrase("cookies excitement hand public") == "sspUXGrmjQhq6mgc24jiRuevZiwKT"); + BEAST_EXPECT( + testPassphrase("cookies excitement hand public") == "sspUXGrmjQhq6mgc24jiRuevZiwKT"); } void @@ -105,14 +106,18 @@ public: { testcase("Node keypair generation & signing (secp256k1)"); - auto const secretKey = generateSecretKey(KeyType::secp256k1, generateSeed("masterpassphrase")); + auto const secretKey = + generateSecretKey(KeyType::secp256k1, generateSeed("masterpassphrase")); auto const publicKey = derivePublicKey(KeyType::secp256k1, secretKey); BEAST_EXPECT( - toBase58(TokenType::NodePublic, publicKey) == "n94a1u4jAz288pZLtw6yFWVbi89YamiC6JBXPVUj5zmExe5fTVg9"); + toBase58(TokenType::NodePublic, publicKey) == + "n94a1u4jAz288pZLtw6yFWVbi89YamiC6JBXPVUj5zmExe5fTVg9"); BEAST_EXPECT( - toBase58(TokenType::NodePrivate, secretKey) == "pnen77YEeUd4fFKG7iycBWcwKpTaeFRkW2WFostaATy1DSupwXe"); - BEAST_EXPECT(to_string(calcNodeID(publicKey)) == "7E59C17D50F5959C7B158FEC95C8F815BF653DC8"); + toBase58(TokenType::NodePrivate, secretKey) == + "pnen77YEeUd4fFKG7iycBWcwKpTaeFRkW2WFostaATy1DSupwXe"); + BEAST_EXPECT( + to_string(calcNodeID(publicKey)) == "7E59C17D50F5959C7B158FEC95C8F815BF653DC8"); auto sig = sign(publicKey, secretKey, makeSlice(message1)); BEAST_EXPECT(sig.size() != 0); @@ -124,7 +129,8 @@ public: // Verify with incorrect public key { auto const otherPublicKey = derivePublicKey( - KeyType::secp256k1, generateSecretKey(KeyType::secp256k1, generateSeed("otherpassphrase"))); + KeyType::secp256k1, + generateSecretKey(KeyType::secp256k1, generateSeed("otherpassphrase"))); BEAST_EXPECT(!verify(otherPublicKey, makeSlice(message1), sig)); } @@ -142,14 +148,18 @@ public: { testcase("Node keypair generation & signing (ed25519)"); - auto const secretKey = generateSecretKey(KeyType::ed25519, generateSeed("masterpassphrase")); + auto const secretKey = + generateSecretKey(KeyType::ed25519, generateSeed("masterpassphrase")); auto const publicKey = derivePublicKey(KeyType::ed25519, secretKey); BEAST_EXPECT( - toBase58(TokenType::NodePublic, publicKey) == "nHUeeJCSY2dM71oxM8Cgjouf5ekTuev2mwDpc374aLMxzDLXNmjf"); + toBase58(TokenType::NodePublic, publicKey) == + "nHUeeJCSY2dM71oxM8Cgjouf5ekTuev2mwDpc374aLMxzDLXNmjf"); BEAST_EXPECT( - toBase58(TokenType::NodePrivate, secretKey) == "paKv46LztLqK3GaKz1rG2nQGN6M4JLyRtxFBYFTw4wAVHtGys36"); - BEAST_EXPECT(to_string(calcNodeID(publicKey)) == "AA066C988C712815CC37AF71472B7CBBBD4E2A0A"); + toBase58(TokenType::NodePrivate, secretKey) == + "paKv46LztLqK3GaKz1rG2nQGN6M4JLyRtxFBYFTw4wAVHtGys36"); + BEAST_EXPECT( + to_string(calcNodeID(publicKey)) == "AA066C988C712815CC37AF71472B7CBBBD4E2A0A"); auto sig = sign(publicKey, secretKey, makeSlice(message1)); BEAST_EXPECT(sig.size() != 0); @@ -161,7 +171,8 @@ public: // Verify with incorrect public key { auto const otherPublicKey = derivePublicKey( - KeyType::ed25519, generateSecretKey(KeyType::ed25519, generateSeed("otherpassphrase"))); + KeyType::ed25519, + generateSecretKey(KeyType::ed25519, generateSeed("otherpassphrase"))); BEAST_EXPECT(!verify(otherPublicKey, makeSlice(message1), sig)); } @@ -179,13 +190,16 @@ public: { testcase("Account keypair generation & signing (secp256k1)"); - auto const [pk, sk] = generateKeyPair(KeyType::secp256k1, generateSeed("masterpassphrase")); + auto const [pk, sk] = + generateKeyPair(KeyType::secp256k1, generateSeed("masterpassphrase")); BEAST_EXPECT(toBase58(calcAccountID(pk)) == "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"); BEAST_EXPECT( - toBase58(TokenType::AccountPublic, pk) == "aBQG8RQAzjs1eTKFEAQXr2gS4utcDiEC9wmi7pfUPTi27VCahwgw"); + toBase58(TokenType::AccountPublic, pk) == + "aBQG8RQAzjs1eTKFEAQXr2gS4utcDiEC9wmi7pfUPTi27VCahwgw"); BEAST_EXPECT( - toBase58(TokenType::AccountSecret, sk) == "p9JfM6HHi64m6mvB6v5k7G2b1cXzGmYiCNJf6GHPKvFTWdeRVjh"); + toBase58(TokenType::AccountSecret, sk) == + "p9JfM6HHi64m6mvB6v5k7G2b1cXzGmYiCNJf6GHPKvFTWdeRVjh"); auto sig = sign(pk, sk, makeSlice(message1)); BEAST_EXPECT(sig.size() != 0); @@ -196,7 +210,8 @@ public: // Verify with incorrect public key { - auto const otherKeyPair = generateKeyPair(KeyType::secp256k1, generateSeed("otherpassphrase")); + auto const otherKeyPair = + generateKeyPair(KeyType::secp256k1, generateSeed("otherpassphrase")); BEAST_EXPECT(!verify(otherKeyPair.first, makeSlice(message1), sig)); } @@ -214,13 +229,16 @@ public: { testcase("Account keypair generation & signing (ed25519)"); - auto const [pk, sk] = generateKeyPair(KeyType::ed25519, generateSeed("masterpassphrase")); + auto const [pk, sk] = + generateKeyPair(KeyType::ed25519, generateSeed("masterpassphrase")); BEAST_EXPECT(to_string(calcAccountID(pk)) == "rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf"); BEAST_EXPECT( - toBase58(TokenType::AccountPublic, pk) == "aKGheSBjmCsKJVuLNKRAKpZXT6wpk2FCuEZAXJupXgdAxX5THCqR"); + toBase58(TokenType::AccountPublic, pk) == + "aKGheSBjmCsKJVuLNKRAKpZXT6wpk2FCuEZAXJupXgdAxX5THCqR"); BEAST_EXPECT( - toBase58(TokenType::AccountSecret, sk) == "pwDQjwEhbUBmPuEjFpEG75bFhv2obkCB7NxQsfFxM7xGHBMVPu9"); + toBase58(TokenType::AccountSecret, sk) == + "pwDQjwEhbUBmPuEjFpEG75bFhv2obkCB7NxQsfFxM7xGHBMVPu9"); auto sig = sign(pk, sk, makeSlice(message1)); BEAST_EXPECT(sig.size() != 0); @@ -231,7 +249,8 @@ public: // Verify with incorrect public key { - auto const otherKeyPair = generateKeyPair(KeyType::ed25519, generateSeed("otherpassphrase")); + auto const otherKeyPair = + generateKeyPair(KeyType::ed25519, generateSeed("otherpassphrase")); BEAST_EXPECT(!verify(otherKeyPair.first, makeSlice(message1), sig)); } diff --git a/src/test/protocol/SeqProxy_test.cpp b/src/test/protocol/SeqProxy_test.cpp index 0e91680c8c..9096fe7daf 100644 --- a/src/test/protocol/SeqProxy_test.cpp +++ b/src/test/protocol/SeqProxy_test.cpp @@ -13,28 +13,32 @@ struct SeqProxy_test : public beast::unit_test::suite expectValues(SeqProxy seqProx, std::uint32_t value, SeqProxy::Type type) { bool const expectSeq{type == SeqProxy::seq}; - return (seqProx.value() == value) && (seqProx.isSeq() == expectSeq) && (seqProx.isTicket() == !expectSeq); + return (seqProx.value() == value) && (seqProx.isSeq() == expectSeq) && + (seqProx.isTicket() == !expectSeq); } // Exercise all SeqProxy comparison operators expecting lhs < rhs. static constexpr bool expectLt(SeqProxy lhs, SeqProxy rhs) { - return (lhs < rhs) && (lhs <= rhs) && (!(lhs == rhs)) && (lhs != rhs) && (!(lhs >= rhs)) && (!(lhs > rhs)); + return (lhs < rhs) && (lhs <= rhs) && (!(lhs == rhs)) && (lhs != rhs) && (!(lhs >= rhs)) && + (!(lhs > rhs)); } // Exercise all SeqProxy comparison operators expecting lhs == rhs. static constexpr bool expectEq(SeqProxy lhs, SeqProxy rhs) { - return (!(lhs < rhs)) && (lhs <= rhs) && (lhs == rhs) && (!(lhs != rhs)) && (lhs >= rhs) && (!(lhs > rhs)); + return (!(lhs < rhs)) && (lhs <= rhs) && (lhs == rhs) && (!(lhs != rhs)) && (lhs >= rhs) && + (!(lhs > rhs)); } // Exercise all SeqProxy comparison operators expecting lhs > rhs. static constexpr bool expectGt(SeqProxy lhs, SeqProxy rhs) { - return (!(lhs < rhs)) && (!(lhs <= rhs)) && (!(lhs == rhs)) && (lhs != rhs) && (lhs >= rhs) && (lhs > rhs); + return (!(lhs < rhs)) && (!(lhs <= rhs)) && (!(lhs == rhs)) && (lhs != rhs) && + (lhs >= rhs) && (lhs > rhs); } // Verify streaming. @@ -48,7 +52,8 @@ struct SeqProxy_test : public beast::unit_test::suite ss << seqProx; std::string str{ss.str()}; - return str.find(type) == 0 && str[type.size()] == ' ' && str.find(value) == (type.size() + 1); + return str.find(type) == 0 && str[type.size()] == ' ' && + str.find(value) == (type.size() + 1); } void diff --git a/src/test/protocol/Serializer_test.cpp b/src/test/protocol/Serializer_test.cpp index cd34446fa8..c5b56c3029 100644 --- a/src/test/protocol/Serializer_test.cpp +++ b/src/test/protocol/Serializer_test.cpp @@ -12,7 +12,11 @@ struct Serializer_test : public beast::unit_test::suite { { std::initializer_list const values = { - std::numeric_limits::min(), -1, 0, 1, std::numeric_limits::max()}; + std::numeric_limits::min(), + -1, + 0, + 1, + std::numeric_limits::max()}; for (std::int32_t value : values) { Serializer s; @@ -24,7 +28,11 @@ struct Serializer_test : public beast::unit_test::suite } { std::initializer_list const values = { - std::numeric_limits::min(), -1, 0, 1, std::numeric_limits::max()}; + std::numeric_limits::min(), + -1, + 0, + 1, + std::numeric_limits::max()}; for (std::int64_t value : values) { Serializer s; diff --git a/src/test/protocol/TER_test.cpp b/src/test/protocol/TER_test.cpp index 6dce46ed6b..cf88a570c5 100644 --- a/src/test/protocol/TER_test.cpp +++ b/src/test/protocol/TER_test.cpp @@ -14,8 +14,8 @@ struct TER_test : public beast::unit_test::suite for (auto i = -400; i < 400; ++i) { TER t = TER::fromInt(i); - auto inRange = isTelLocal(t) || isTemMalformed(t) || isTefFailure(t) || isTerRetry(t) || isTesSuccess(t) || - isTecClaim(t); + auto inRange = isTelLocal(t) || isTemMalformed(t) || isTefFailure(t) || isTerRetry(t) || + isTesSuccess(t) || isTecClaim(t); std::string token, text; auto good = transResultInfo(t, token, text); @@ -48,11 +48,16 @@ struct TER_test : public beast::unit_test::suite // unless they are the same types. using To_t = std::decay_t(tup))>; using From_t = std::decay_t(tup))>; - static_assert(std::is_same::value == std::is_convertible::value, "Convert err"); static_assert( - std::is_same::value == std::is_constructible::value, "Construct err"); + std::is_same::value == std::is_convertible::value, + "Convert err"); static_assert( - std::is_same::value == std::is_assignable::value, "Assign err"); + std::is_same::value == std::is_constructible::value, + "Construct err"); + static_assert( + std::is_same::value == + std::is_assignable::value, + "Assign err"); // Assignment or conversion from integer to type should never work. static_assert(!std::is_convertible::value, "Convert err"); @@ -62,7 +67,11 @@ struct TER_test : public beast::unit_test::suite }; // Fast iteration over the tuple. - template class Func, typename Tup> + template < + std::size_t I1, + std::size_t I2, + template class Func, + typename Tup> std::enable_if_t testIterate(Tup const& tup, beast::unit_test::suite& s) { @@ -72,7 +81,11 @@ struct TER_test : public beast::unit_test::suite } // Slow iteration over the tuple. - template class Func, typename Tup> + template < + std::size_t I1, + std::size_t I2, + template class Func, + typename Tup> std::enable_if_t testIterate(Tup const& tup, beast::unit_test::suite& s) { @@ -82,7 +95,11 @@ struct TER_test : public beast::unit_test::suite } // Finish iteration over the tuple. - template class Func, typename Tup> + template < + std::size_t I1, + std::size_t I2, + template class Func, + typename Tup> std::enable_if_t testIterate(Tup const& tup, beast::unit_test::suite& s) { @@ -97,8 +114,8 @@ struct TER_test : public beast::unit_test::suite // are not valid. // Examples of each kind of enum. - static auto const terEnums = - std::make_tuple(telLOCAL_ERROR, temMALFORMED, tefFAILURE, terRETRY, tesSUCCESS, tecCLAIM); + static auto const terEnums = std::make_tuple( + telLOCAL_ERROR, temMALFORMED, tefFAILURE, terRETRY, tesSUCCESS, tecCLAIM); static int const hiIndex{std::tuple_size::value - 1}; // Verify that enums cannot be converted to other enum types. diff --git a/src/test/resource/Logic_test.cpp b/src/test/resource/Logic_test.cpp index f3e44e8b32..de57c715bc 100644 --- a/src/test/resource/Logic_test.cpp +++ b/src/test/resource/Logic_test.cpp @@ -24,7 +24,8 @@ public: using clock_type = boost::base_from_member; public: - explicit TestLogic(beast::Journal journal) : Logic(beast::insight::NullCollector::New(), member, journal) + explicit TestLogic(beast::Journal journal) + : Logic(beast::insight::NullCollector::New(), member, journal) { } diff --git a/src/test/rpc/AMMInfo_test.cpp b/src/test/rpc/AMMInfo_test.cpp index cf515d7c84..d3be04ff96 100644 --- a/src/test/rpc/AMMInfo_test.cpp +++ b/src/test/rpc/AMMInfo_test.cpp @@ -44,20 +44,26 @@ public: BEAST_EXPECT(jv[jss::error_message] == "Account malformed."); }); - std::vector, std::optional, TestAccount, bool>> const invalidParams = { - {xrpIssue(), std::nullopt, None, false}, - {std::nullopt, USD.issue(), None, false}, - {xrpIssue(), std::nullopt, Alice, false}, - {std::nullopt, USD.issue(), Alice, false}, - {xrpIssue(), USD.issue(), Alice, false}, - {std::nullopt, std::nullopt, None, true}}; + std::vector, std::optional, TestAccount, bool>> const + invalidParams = { + {xrpIssue(), std::nullopt, None, false}, + {std::nullopt, USD.issue(), None, false}, + {xrpIssue(), std::nullopt, Alice, false}, + {std::nullopt, USD.issue(), Alice, false}, + {xrpIssue(), USD.issue(), Alice, false}, + {std::nullopt, std::nullopt, None, true}}; // Invalid parameters testAMM([&](AMM& ammAlice, Env&) { for (auto const& [iss1, iss2, acct, ignoreParams] : invalidParams) { auto const jv = ammAlice.ammRpcInfo( - std::nullopt, std::nullopt, iss1, iss2, accountId(ammAlice, acct), ignoreParams); + std::nullopt, + std::nullopt, + iss1, + iss2, + accountId(ammAlice, acct), + ignoreParams); BEAST_EXPECT(jv[jss::error_message] == "Invalid parameters."); } }); @@ -95,7 +101,8 @@ public: // Invalid AMM account id testAMM([&](AMM& ammAlice, Env&) { - auto const jv = ammAlice.ammRpcInfo(std::nullopt, std::nullopt, std::nullopt, std::nullopt, bogie.id()); + auto const jv = ammAlice.ammRpcInfo( + std::nullopt, std::nullopt, std::nullopt, std::nullopt, bogie.id()); BEAST_EXPECT(jv[jss::error_message] == "Account malformed."); }); @@ -113,7 +120,12 @@ public: for (auto const& [iss1, iss2, acct, ignoreParams] : invalidParamsBadAccount) { auto const jv = ammAlice.ammRpcInfo( - std::nullopt, std::nullopt, iss1, iss2, accountId(ammAlice, acct), ignoreParams); + std::nullopt, + std::nullopt, + iss1, + iss2, + accountId(ammAlice, acct), + ignoreParams); BEAST_EXPECT(jv[jss::error_message] == "Invalid parameters."); } }); @@ -123,10 +135,17 @@ public: for (auto const& [iss1, iss2, acct, ignoreParams] : invalidParamsBadAccount) { auto const jv = ammAlice.ammRpcInfo( - std::nullopt, std::nullopt, iss1, iss2, accountId(ammAlice, acct), ignoreParams, 3); + std::nullopt, + std::nullopt, + iss1, + iss2, + accountId(ammAlice, acct), + ignoreParams, + 3); BEAST_EXPECT( jv[jss::error_message] == - (acct == Bogie ? std::string("Account malformed.") : std::string("Invalid parameters."))); + (acct == Bogie ? std::string("Account malformed.") + : std::string("Invalid parameters."))); } }); } @@ -140,7 +159,12 @@ public: testAMM([&](AMM& ammAlice, Env&) { BEAST_EXPECT(ammAlice.expectAmmRpcInfo(XRP(10000), USD(10000), IOUAmount{10000000, 0})); BEAST_EXPECT(ammAlice.expectAmmRpcInfo( - XRP(10000), USD(10000), IOUAmount{10000000, 0}, std::nullopt, std::nullopt, ammAlice.ammAccount())); + XRP(10000), + USD(10000), + IOUAmount{10000000, 0}, + std::nullopt, + std::nullopt, + ammAlice.ammAccount())); }); } @@ -152,7 +176,8 @@ public: using namespace jtx; testAMM( [&](AMM& ammAlice, Env& env) { - BEAST_EXPECT(ammAlice.expectAmmRpcInfo(XRP(10000), USD(10000), IOUAmount{10000000, 0})); + BEAST_EXPECT( + ammAlice.expectAmmRpcInfo(XRP(10000), USD(10000), IOUAmount{10000000, 0})); std::unordered_map votes; votes.insert({alice.human(), 0}); for (int i = 0; i < 7; ++i) @@ -191,10 +216,13 @@ public: { std::unordered_set authAccounts = { carol.human(), bob.human(), ed.human(), bill.human()}; - auto const ammInfo = i - ? ammAlice.ammRpcInfo() - : ammAlice.ammRpcInfo( - std::nullopt, std::nullopt, std::nullopt, std::nullopt, ammAlice.ammAccount()); + auto const ammInfo = i ? ammAlice.ammRpcInfo() + : ammAlice.ammRpcInfo( + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + ammAlice.ammAccount()); auto const& amm = ammInfo[jss::amm]; try { @@ -218,10 +246,11 @@ public: auto const auctionSlot = amm[jss::auction_slot]; for (std::uint8_t i = 0; i < 4; ++i) { - if (!BEAST_EXPECT( - authAccounts.contains(auctionSlot[jss::auth_accounts][i][jss::account].asString()))) + if (!BEAST_EXPECT(authAccounts.contains( + auctionSlot[jss::auth_accounts][i][jss::account].asString()))) return; - authAccounts.erase(auctionSlot[jss::auth_accounts][i][jss::account].asString()); + authAccounts.erase( + auctionSlot[jss::auth_accounts][i][jss::account].asString()); } if (!BEAST_EXPECT(authAccounts.empty())) return; @@ -231,7 +260,8 @@ public: auctionSlot[jss::price][jss::value].asString() == "5600" && auctionSlot[jss::price][jss::currency].asString() == to_string(ammAlice.lptIssue().currency) && - auctionSlot[jss::price][jss::issuer].asString() == to_string(ammAlice.lptIssue().account)); + auctionSlot[jss::price][jss::issuer].asString() == + to_string(ammAlice.lptIssue().account)); } catch (std::exception const& e) { @@ -270,7 +300,8 @@ public: testcase("Invalid amm field"); testAMM([&](AMM& amm, Env&) { - auto const resp = amm.ammRpcInfo(std::nullopt, jss::validated.c_str(), std::nullopt, std::nullopt, gw); + auto const resp = amm.ammRpcInfo( + std::nullopt, jss::validated.c_str(), std::nullopt, std::nullopt, gw); BEAST_EXPECT(resp.isMember("error") && resp["error"] == "actNotFound"); }); } diff --git a/src/test/rpc/AccountCurrencies_test.cpp b/src/test/rpc/AccountCurrencies_test.cpp index f467b50adc..c317bfc31c 100644 --- a/src/test/rpc/AccountCurrencies_test.cpp +++ b/src/test/rpc/AccountCurrencies_test.cpp @@ -23,9 +23,11 @@ class AccountCurrencies_test : public beast::unit_test::suite Json::Value params; params[jss::account] = Account{"bob"}.human(); params[jss::ledger_hash] = 1; - auto const result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; + auto const result = + env.rpc("json", "account_currencies", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); - BEAST_EXPECT(result[jss::error_message] == "Invalid field 'ledger_hash', not hex string."); + BEAST_EXPECT( + result[jss::error_message] == "Invalid field 'ledger_hash', not hex string."); } { // missing account field @@ -73,7 +75,8 @@ class AccountCurrencies_test : public beast::unit_test::suite { Json::Value params; params[jss::account] = "llIIOO"; // these are invalid in bitcoin alphabet - auto const result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; + auto const result = + env.rpc("json", "account_currencies", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "actMalformed"); BEAST_EXPECT(result[jss::error_message] == "Account malformed."); } @@ -82,7 +85,8 @@ class AccountCurrencies_test : public beast::unit_test::suite // Cannot use a seed as account Json::Value params; params[jss::account] = "Bob"; - auto const result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; + auto const result = + env.rpc("json", "account_currencies", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "actMalformed"); BEAST_EXPECT(result[jss::error_message] == "Account malformed."); } @@ -90,7 +94,8 @@ class AccountCurrencies_test : public beast::unit_test::suite { // ask for nonexistent account Json::Value params; params[jss::account] = Account{"bob"}.human(); - auto const result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; + auto const result = + env.rpc("json", "account_currencies", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "actNotFound"); BEAST_EXPECT(result[jss::error_message] == "Account not found."); } @@ -121,8 +126,10 @@ class AccountCurrencies_test : public beast::unit_test::suite auto result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; auto arrayCheck = [&result]( - Json::StaticString const& fld, std::vector> const& expected) -> bool { - bool stat = result.isMember(fld) && result[fld].isArray() && result[fld].size() == expected.size(); + Json::StaticString const& fld, + std::vector> const& expected) -> bool { + bool stat = result.isMember(fld) && result[fld].isArray() && + result[fld].size() == expected.size(); for (size_t i = 0; stat && i < expected.size(); ++i) { stat &= (to_string(expected[i].value().currency) == result[fld][i].asString()); diff --git a/src/test/rpc/AccountInfo_test.cpp b/src/test/rpc/AccountInfo_test.cpp index bdc8e63e3d..a67eef996d 100644 --- a/src/test/rpc/AccountInfo_test.cpp +++ b/src/test/rpc/AccountInfo_test.cpp @@ -106,13 +106,15 @@ public: { // account_info without the "signer_lists" argument. auto const info = env.rpc("json", "account_info", to_string(withoutSigners)); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); BEAST_EXPECT(!info[jss::result][jss::account_data].isMember(jss::signer_lists)); } { // account_info with the "signer_lists" argument. auto const info = env.rpc("json", "account_info", to_string(withSigners)); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& data = info[jss::result][jss::account_data]; BEAST_EXPECT(data.isMember(jss::signer_lists)); auto const& signerLists = data[jss::signer_lists]; @@ -128,13 +130,15 @@ public: { // account_info without the "signer_lists" argument. auto const info = env.rpc("json", "account_info", to_string(withoutSigners)); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); BEAST_EXPECT(!info[jss::result][jss::account_data].isMember(jss::signer_lists)); } { // account_info with the "signer_lists" argument. auto const info = env.rpc("json", "account_info", to_string(withSigners)); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& data = info[jss::result][jss::account_data]; BEAST_EXPECT(data.isMember(jss::signer_lists)); auto const& signerLists = data[jss::signer_lists]; @@ -175,7 +179,8 @@ public: { // account_info with the "signer_lists" argument. auto const info = env.rpc("json", "account_info", to_string(withSigners)); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& data = info[jss::result][jss::account_data]; BEAST_EXPECT(data.isMember(jss::signer_lists)); auto const& signerLists = data[jss::signer_lists]; @@ -215,8 +220,8 @@ public: withSigners[jss::account] = alice.human(); withSigners[jss::signer_lists] = true; - auto const withSignersAsString = std::string("{ ") + "\"api_version\": 2, \"account\": \"" + alice.human() + - "\", " + "\"signer_lists\": asdfggh }"; + auto const withSignersAsString = std::string("{ ") + "\"api_version\": 2, \"account\": \"" + + alice.human() + "\", " + "\"signer_lists\": asdfggh }"; // Alice has no SignerList yet. { @@ -349,7 +354,8 @@ public: { // account_info without the "signer_lists" argument. auto const info = env.rpc("json2", withoutSigners); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); BEAST_EXPECT(!info[jss::result][jss::account_data].isMember(jss::signer_lists)); BEAST_EXPECT(info.isMember(jss::jsonrpc) && info[jss::jsonrpc] == "2.0"); BEAST_EXPECT(info.isMember(jss::ripplerpc) && info[jss::ripplerpc] == "2.0"); @@ -358,7 +364,8 @@ public: { // account_info with the "signer_lists" argument. auto const info = env.rpc("json2", withSigners); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& data = info[jss::result][jss::account_data]; BEAST_EXPECT(data.isMember(jss::signer_lists)); auto const& signerLists = data[jss::signer_lists]; @@ -371,13 +378,17 @@ public: { // Do both of the above as a batch job auto const info = env.rpc("json2", '[' + withoutSigners + ", " + withSigners + ']'); - BEAST_EXPECT(info[0u].isMember(jss::result) && info[0u][jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info[0u].isMember(jss::result) && + info[0u][jss::result].isMember(jss::account_data)); BEAST_EXPECT(!info[0u][jss::result][jss::account_data].isMember(jss::signer_lists)); BEAST_EXPECT(info[0u].isMember(jss::jsonrpc) && info[0u][jss::jsonrpc] == "2.0"); BEAST_EXPECT(info[0u].isMember(jss::ripplerpc) && info[0u][jss::ripplerpc] == "2.0"); BEAST_EXPECT(info[0u].isMember(jss::id) && info[0u][jss::id] == 5); - BEAST_EXPECT(info[1u].isMember(jss::result) && info[1u][jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info[1u].isMember(jss::result) && + info[1u][jss::result].isMember(jss::account_data)); auto const& data = info[1u][jss::result][jss::account_data]; BEAST_EXPECT(data.isMember(jss::signer_lists)); auto const& signerLists = data[jss::signer_lists]; @@ -396,7 +407,8 @@ public: { // account_info without the "signer_lists" argument. auto const info = env.rpc("json2", withoutSigners); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); BEAST_EXPECT(!info[jss::result][jss::account_data].isMember(jss::signer_lists)); BEAST_EXPECT(info.isMember(jss::jsonrpc) && info[jss::jsonrpc] == "2.0"); BEAST_EXPECT(info.isMember(jss::ripplerpc) && info[jss::ripplerpc] == "2.0"); @@ -405,7 +417,8 @@ public: { // account_info with the "signer_lists" argument. auto const info = env.rpc("json2", withSigners); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& data = info[jss::result][jss::account_data]; BEAST_EXPECT(data.isMember(jss::signer_lists)); auto const& signerLists = data[jss::signer_lists]; @@ -449,7 +462,8 @@ public: { // account_info with the "signer_lists" argument. auto const info = env.rpc("json2", withSigners); - BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT( + info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& data = info[jss::result][jss::account_data]; BEAST_EXPECT(data.isMember(jss::signer_lists)); auto const& signerLists = data[jss::signer_lists]; @@ -525,11 +539,12 @@ public: BEAST_EXPECT(f2.value()); } - static constexpr std::array, 4> disallowIncomingFlags{ - {{"disallowIncomingCheck", asfDisallowIncomingCheck}, - {"disallowIncomingNFTokenOffer", asfDisallowIncomingNFTokenOffer}, - {"disallowIncomingPayChan", asfDisallowIncomingPayChan}, - {"disallowIncomingTrustline", asfDisallowIncomingTrustline}}}; + static constexpr std::array, 4> + disallowIncomingFlags{ + {{"disallowIncomingCheck", asfDisallowIncomingCheck}, + {"disallowIncomingNFTokenOffer", asfDisallowIncomingNFTokenOffer}, + {"disallowIncomingPayChan", asfDisallowIncomingPayChan}, + {"disallowIncomingTrustline", asfDisallowIncomingTrustline}}}; for (auto& asf : disallowIncomingFlags) { diff --git a/src/test/rpc/AccountLines_test.cpp b/src/test/rpc/AccountLines_test.cpp index 1f5f190cfa..f91b2aed1c 100644 --- a/src/test/rpc/AccountLines_test.cpp +++ b/src/test/rpc/AccountLines_test.cpp @@ -22,7 +22,8 @@ public: // account_lines with no account. auto const lines = env.rpc("json", "account_lines", "{ }"); BEAST_EXPECT( - lines[jss::result][jss::error_message] == RPC::missing_field_error(jss::account)[jss::error_message]); + lines[jss::result][jss::error_message] == + RPC::missing_field_error(jss::account)[jss::error_message]); } { // account_lines with a malformed account. @@ -30,7 +31,8 @@ public: params[jss::account] = "n9MJkEKHDhy5eTLuHUQeAAjo382frHNbFK4C8hcwN4nwM2SrLdBj"; auto const lines = env.rpc("json", "account_lines", to_string(params)); BEAST_EXPECT( - lines[jss::result][jss::error_message] == RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); + lines[jss::result][jss::error_message] == + RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); } { // test account non-string @@ -56,7 +58,8 @@ public: params[jss::account] = alice.human(); auto const lines = env.rpc("json", "account_lines", to_string(params)); BEAST_EXPECT( - lines[jss::result][jss::error_message] == RPC::make_error(rpcACT_NOT_FOUND)[jss::error_message]); + lines[jss::result][jss::error_message] == + RPC::make_error(rpcACT_NOT_FOUND)[jss::error_message]); } env.fund(XRP(10000), alice); env.close(); @@ -78,7 +81,8 @@ public: params[jss::ledger_index] = "nonsense"; auto const lines = env.rpc("json", "account_lines", to_string(params)); BEAST_EXPECT( - lines[jss::result][jss::error_message] == "Invalid field 'ledger_index', not string or number."); + lines[jss::result][jss::error_message] == + "Invalid field 'ledger_index', not string or number."); } { // Specify a different ledger that doesn't exist. @@ -138,23 +142,24 @@ public: BEAST_EXPECT(ledger58Info.seq == 58); // A re-usable test for historic ledgers. - auto testAccountLinesHistory = [this, &env](Account const& account, LedgerHeader const& info, int count) { - // Get account_lines by ledger index. - Json::Value paramsSeq; - paramsSeq[jss::account] = account.human(); - paramsSeq[jss::ledger_index] = info.seq; - auto const linesSeq = env.rpc("json", "account_lines", to_string(paramsSeq)); - BEAST_EXPECT(linesSeq[jss::result][jss::lines].isArray()); - BEAST_EXPECT(linesSeq[jss::result][jss::lines].size() == count); + auto testAccountLinesHistory = + [this, &env](Account const& account, LedgerHeader const& info, int count) { + // Get account_lines by ledger index. + Json::Value paramsSeq; + paramsSeq[jss::account] = account.human(); + paramsSeq[jss::ledger_index] = info.seq; + auto const linesSeq = env.rpc("json", "account_lines", to_string(paramsSeq)); + BEAST_EXPECT(linesSeq[jss::result][jss::lines].isArray()); + BEAST_EXPECT(linesSeq[jss::result][jss::lines].size() == count); - // Get account_lines by ledger hash. - Json::Value paramsHash; - paramsHash[jss::account] = account.human(); - paramsHash[jss::ledger_hash] = to_string(info.hash); - auto const linesHash = env.rpc("json", "account_lines", to_string(paramsHash)); - BEAST_EXPECT(linesHash[jss::result][jss::lines].isArray()); - BEAST_EXPECT(linesHash[jss::result][jss::lines].size() == count); - }; + // Get account_lines by ledger hash. + Json::Value paramsHash; + paramsHash[jss::account] = account.human(); + paramsHash[jss::ledger_hash] = to_string(info.hash); + auto const linesHash = env.rpc("json", "account_lines", to_string(paramsHash)); + BEAST_EXPECT(linesHash[jss::result][jss::lines].isArray()); + BEAST_EXPECT(linesHash[jss::result][jss::lines].size() == count); + }; // Alice should have no trust lines in ledger 3. testAccountLinesHistory(alice, ledger3Info, 0); @@ -185,7 +190,8 @@ public: params[jss::ledger_index] = Json::objectValue; auto const lines = env.rpc("json", "account_lines", to_string(params))[jss::result]; BEAST_EXPECT(lines[jss::error] == "invalidParams"); - BEAST_EXPECT(lines[jss::error_message] == "Invalid field 'ledger_index', not string or number."); + BEAST_EXPECT( + lines[jss::error_message] == "Invalid field 'ledger_index', not string or number."); } { // alice should have 52 trust lines in the current ledger. @@ -215,7 +221,8 @@ public: params[jss::peer] = "n9MJkEKHDhy5eTLuHUQeAAjo382frHNbFK4C8hcwN4nwM2SrLdBj"; auto const lines = env.rpc("json", "account_lines", to_string(params)); BEAST_EXPECT( - lines[jss::result][jss::error_message] == RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); + lines[jss::result][jss::error_message] == + RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); } { // A negative limit should fail. @@ -224,7 +231,8 @@ public: params[jss::limit] = -1; auto const lines = env.rpc("json", "account_lines", to_string(params)); BEAST_EXPECT( - lines[jss::result][jss::error_message] == RPC::expected_field_message(jss::limit, "unsigned integer")); + lines[jss::result][jss::error_message] == + RPC::expected_field_message(jss::limit, "unsigned integer")); } { // Limit the response to 1 trust line. @@ -260,7 +268,8 @@ public: paramsD[jss::marker] = marker; auto const linesD = env.rpc("json", "account_lines", to_string(paramsD)); BEAST_EXPECT( - linesD[jss::result][jss::error_message] == RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); + linesD[jss::result][jss::error_message] == + RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); } { // A non-string marker should also fail. @@ -268,7 +277,9 @@ public: params[jss::account] = alice.human(); params[jss::marker] = true; auto const lines = env.rpc("json", "account_lines", to_string(params)); - BEAST_EXPECT(lines[jss::result][jss::error_message] == RPC::expected_field_message(jss::marker, "string")); + BEAST_EXPECT( + lines[jss::result][jss::error_message] == + RPC::expected_field_message(jss::marker, "string")); } { // Check that the flags we expect from alice to gw2 are present. @@ -347,7 +358,8 @@ public: Json::Value aliceObjectsParams; aliceObjectsParams[jss::account] = alice.human(); aliceObjectsParams[jss::limit] = 10; - Json::Value const aliceObjects = env.rpc("json", "account_objects", to_string(aliceObjectsParams)); + Json::Value const aliceObjects = + env.rpc("json", "account_objects", to_string(aliceObjectsParams)); Json::Value const& aliceSignerList = aliceObjects[jss::result][jss::account_objects][0u]; if (!(aliceSignerList[sfLedgerEntryType.jsonName] == jss::SignerList)) { @@ -455,7 +467,8 @@ public: linesEndParams[jss::marker] = linesBeg[jss::result][jss::marker]; auto const linesEnd = env.rpc("json", "account_lines", to_string(linesEndParams)); BEAST_EXPECT( - linesEnd[jss::result][jss::error_message] == RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); + linesEnd[jss::result][jss::error_message] == + RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); } void @@ -531,11 +544,19 @@ public: env(token::createOffer(alice, beckyNFtokenID, drops(1)), token::owner(becky)); env(token::createOffer(becky, aliceNFtokenID, drops(1)), token::owner(alice)); - env(token::createOffer(becky, beckyNFtokenID, drops(1)), txflags(tfSellNFToken), token::destination(alice)); - env(token::createOffer(alice, aliceNFtokenID, drops(1)), txflags(tfSellNFToken), token::destination(becky)); + env(token::createOffer(becky, beckyNFtokenID, drops(1)), + txflags(tfSellNFToken), + token::destination(alice)); + env(token::createOffer(alice, aliceNFtokenID, drops(1)), + txflags(tfSellNFToken), + token::destination(becky)); - env(token::createOffer(gw1, beckyNFtokenID, drops(1)), token::owner(becky), token::destination(alice)); - env(token::createOffer(gw1, aliceNFtokenID, drops(1)), token::owner(alice), token::destination(becky)); + env(token::createOffer(gw1, beckyNFtokenID, drops(1)), + token::owner(becky), + token::destination(alice)); + env(token::createOffer(gw1, aliceNFtokenID, drops(1)), + token::owner(alice), + token::destination(becky)); env(token::createOffer(becky, beckyNFtokenID, drops(1)), txflags(tfSellNFToken)); env(token::createOffer(alice, aliceNFtokenID, drops(1)), txflags(tfSellNFToken)); @@ -567,15 +588,16 @@ public: // Now make repeated calls to `account_lines` with a limit of 1. // That should iterate all of alice's relevant objects, even though // the list will be empty for most calls. - auto getNextLine = [](Env& env, Account const& alice, std::optional const marker) { - Json::Value params(Json::objectValue); - params[jss::account] = alice.human(); - params[jss::limit] = 1; - if (marker) - params[jss::marker] = *marker; + auto getNextLine = + [](Env& env, Account const& alice, std::optional const marker) { + Json::Value params(Json::objectValue); + params[jss::account] = alice.human(); + params[jss::limit] = 1; + if (marker) + params[jss::marker] = *marker; - return env.rpc("json", "account_lines", to_string(params)); - }; + return env.rpc("json", "account_lines", to_string(params)); + }; auto aliceLines = getNextLine(env, alice, std::nullopt); constexpr std::size_t expectedIterations = 16; @@ -583,11 +605,17 @@ public: constexpr std::size_t expectedNFTs = 1; std::size_t foundLines = 0; - auto hasMarker = [](auto const& aliceLines) { return aliceLines[jss::result].isMember(jss::marker); }; - auto marker = [](auto const& aliceLines) { return aliceLines[jss::result][jss::marker].asString(); }; + auto hasMarker = [](auto const& aliceLines) { + return aliceLines[jss::result].isMember(jss::marker); + }; + auto marker = [](auto const& aliceLines) { + return aliceLines[jss::result][jss::marker].asString(); + }; auto checkLines = [](auto const& aliceLines) { - return aliceLines.isMember(jss::result) && !aliceLines[jss::result].isMember(jss::error_message) && - aliceLines[jss::result].isMember(jss::lines) && aliceLines[jss::result][jss::lines].isArray() && + return aliceLines.isMember(jss::result) && + !aliceLines[jss::result].isMember(jss::error_message) && + aliceLines[jss::result].isMember(jss::lines) && + aliceLines[jss::result][jss::lines].isArray() && aliceLines[jss::result][jss::lines].size() <= 1; }; @@ -610,7 +638,8 @@ public: Json::Value aliceObjectsParams2; aliceObjectsParams2[jss::account] = alice.human(); aliceObjectsParams2[jss::limit] = 200; - Json::Value const aliceObjects = env.rpc("json", "account_objects", to_string(aliceObjectsParams2)); + Json::Value const aliceObjects = + env.rpc("json", "account_objects", to_string(aliceObjectsParams2)); BEAST_EXPECT(aliceObjects.isMember(jss::result)); BEAST_EXPECT(!aliceObjects[jss::result].isMember(jss::error_message)); BEAST_EXPECT(aliceObjects[jss::result].isMember(jss::account_objects)); @@ -618,7 +647,9 @@ public: // account_objects does not currently return NFTPages. If // that ever changes, without also changing account_lines, // this test will need to be updated. - BEAST_EXPECT(aliceObjects[jss::result][jss::account_objects].size() == iterations + expectedNFTs); + BEAST_EXPECT( + aliceObjects[jss::result][jss::account_objects].size() == + iterations + expectedNFTs); // If ledger object association ever changes, for whatever // reason, this test will need to be updated. BEAST_EXPECTS(iterations == expectedIterations, std::to_string(iterations)); @@ -627,7 +658,8 @@ public: Json::Value beckyObjectsParams; beckyObjectsParams[jss::account] = becky.human(); beckyObjectsParams[jss::limit] = 200; - Json::Value const beckyObjects = env.rpc("json", "account_objects", to_string(beckyObjectsParams)); + Json::Value const beckyObjects = + env.rpc("json", "account_objects", to_string(beckyObjectsParams)); BEAST_EXPECT(beckyObjects.isMember(jss::result)); BEAST_EXPECT(!beckyObjects[jss::result].isMember(jss::error_message)); BEAST_EXPECT(beckyObjects[jss::result].isMember(jss::account_objects)); @@ -666,7 +698,9 @@ public: request[jss::ripplerpc] = "2.0"; request[jss::id] = 5; auto const lines = env.rpc("json2", to_string(request)); - BEAST_EXPECT(lines[jss::error][jss::message] == RPC::missing_field_error(jss::account)[jss::error_message]); + BEAST_EXPECT( + lines[jss::error][jss::message] == + RPC::missing_field_error(jss::account)[jss::error_message]); BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); @@ -682,7 +716,9 @@ public: request[jss::id] = 5; request[jss::params] = params; auto const lines = env.rpc("json2", to_string(request)); - BEAST_EXPECT(lines[jss::error][jss::message] == RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); + BEAST_EXPECT( + lines[jss::error][jss::message] == + RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); @@ -699,7 +735,9 @@ public: request[jss::id] = 5; request[jss::params] = params; auto const lines = env.rpc("json2", to_string(request)); - BEAST_EXPECT(lines[jss::error][jss::message] == RPC::make_error(rpcACT_NOT_FOUND)[jss::error_message]); + BEAST_EXPECT( + lines[jss::error][jss::message] == + RPC::make_error(rpcACT_NOT_FOUND)[jss::error_message]); BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); @@ -738,7 +776,9 @@ public: request[jss::id] = 5; request[jss::params] = params; auto const lines = env.rpc("json2", to_string(request)); - BEAST_EXPECT(lines[jss::error][jss::message] == "Invalid field 'ledger_index', not string or number."); + BEAST_EXPECT( + lines[jss::error][jss::message] == + "Invalid field 'ledger_index', not string or number."); BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); @@ -810,7 +850,10 @@ public: BEAST_EXPECT(ledger58Info.seq == 58); // A re-usable test for historic ledgers. - auto testAccountLinesHistory = [this, &env](Account const& account, LedgerHeader const& info, int count) { + auto testAccountLinesHistory = [this, &env]( + Account const& account, + LedgerHeader const& info, + int count) { // Get account_lines by ledger index. Json::Value paramsSeq; paramsSeq[jss::account] = account.human(); @@ -925,7 +968,9 @@ public: request[jss::id] = 5; request[jss::params] = params; auto const lines = env.rpc("json2", to_string(request)); - BEAST_EXPECT(lines[jss::error][jss::message] == RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); + BEAST_EXPECT( + lines[jss::error][jss::message] == + RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); @@ -943,7 +988,8 @@ public: request[jss::params] = params; auto const lines = env.rpc("json2", to_string(request)); BEAST_EXPECT( - lines[jss::error][jss::message] == RPC::expected_field_message(jss::limit, "unsigned integer")); + lines[jss::error][jss::message] == + RPC::expected_field_message(jss::limit, "unsigned integer")); BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); @@ -1014,7 +1060,9 @@ public: requestD[jss::id] = 5; requestD[jss::params] = paramsD; auto const linesD = env.rpc("json2", to_string(requestD)); - BEAST_EXPECT(linesD[jss::error][jss::message] == RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); + BEAST_EXPECT( + linesD[jss::error][jss::message] == + RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); BEAST_EXPECT(linesD.isMember(jss::jsonrpc) && linesD[jss::jsonrpc] == "2.0"); BEAST_EXPECT(linesD.isMember(jss::ripplerpc) && linesD[jss::ripplerpc] == "2.0"); BEAST_EXPECT(linesD.isMember(jss::id) && linesD[jss::id] == 5); @@ -1031,7 +1079,9 @@ public: request[jss::id] = 5; request[jss::params] = params; auto const lines = env.rpc("json2", to_string(request)); - BEAST_EXPECT(lines[jss::error][jss::message] == RPC::expected_field_message(jss::marker, "string")); + BEAST_EXPECT( + lines[jss::error][jss::message] == + RPC::expected_field_message(jss::marker, "string")); BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); @@ -1186,7 +1236,9 @@ public: linesEndRequest[jss::id] = 5; linesEndRequest[jss::params] = linesEndParams; auto const linesEnd = env.rpc("json2", to_string(linesEndRequest)); - BEAST_EXPECT(linesEnd[jss::error][jss::message] == RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); + BEAST_EXPECT( + linesEnd[jss::error][jss::message] == + RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); BEAST_EXPECT(linesEnd.isMember(jss::jsonrpc) && linesEnd[jss::jsonrpc] == "2.0"); BEAST_EXPECT(linesEnd.isMember(jss::ripplerpc) && linesEnd[jss::ripplerpc] == "2.0"); BEAST_EXPECT(linesEnd.isMember(jss::id) && linesEnd[jss::id] == 5); diff --git a/src/test/rpc/AccountObjects_test.cpp b/src/test/rpc/AccountObjects_test.cpp index 0dec2bde7f..7c1877136d 100644 --- a/src/test/rpc/AccountObjects_test.cpp +++ b/src/test/rpc/AccountObjects_test.cpp @@ -2,13 +2,12 @@ #include #include -#include - #include #include #include #include #include +#include #include @@ -160,7 +159,8 @@ public: params[jss::account] = bob.human(); params[jss::type] = 10; auto resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'type', not string."); + BEAST_EXPECT( + resp[jss::result][jss::error_message] == "Invalid field 'type', not string."); } // test error on type param not a valid type { @@ -176,7 +176,9 @@ public: params[jss::account] = bob.human(); params[jss::limit] = -1; auto resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'limit', not unsigned integer."); + BEAST_EXPECT( + resp[jss::result][jss::error_message] == + "Invalid field 'limit', not unsigned integer."); } // test errors on marker { @@ -196,7 +198,8 @@ public: std::string mark = to_string(resume_marker); params[jss::marker] = 10; resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'marker', not string."); + BEAST_EXPECT( + resp[jss::result][jss::error_message] == "Invalid field 'marker', not string."); params[jss::marker] = "This is a string with no comma"; resp = env.rpc("json", "account_objects", to_string(params)); @@ -526,7 +529,8 @@ public: Account const gw{"gateway"}; auto const USD = gw["USD"]; - auto const features = testable_amendments() | featureXChainBridge | featurePermissionedDomains; + auto const features = + testable_amendments() | featureXChainBridge | featurePermissionedDomains; Env env(*this, features); // Make a lambda we can use to get "account_objects" easily. @@ -597,7 +601,8 @@ public: auto const& nftPage = resp[jss::result][jss::account_objects][0u]; BEAST_EXPECT(nftPage[sfNFTokens.jsonName].size() == 1); BEAST_EXPECT( - nftPage[sfNFTokens.jsonName][0u][sfNFToken.jsonName][sfNFTokenID.jsonName] == to_string(nftID)); + nftPage[sfNFTokens.jsonName][0u][sfNFToken.jsonName][sfNFTokenID.jsonName] == + to_string(nftID)); } // Set up a trust line so we can find it. @@ -675,7 +680,9 @@ public: BEAST_EXPECT(acctObjsIsSize(resp, 1)); auto const& permissionedDomain = resp[jss::result][jss::account_objects][0u]; - BEAST_EXPECT(permissionedDomain.isMember(jss::Owner) && (permissionedDomain[jss::Owner] == gw.human())); + BEAST_EXPECT( + permissionedDomain.isMember(jss::Owner) && + (permissionedDomain[jss::Owner] == gw.human())); bool const check1 = BEAST_EXPECT( permissionedDomain.isMember(jss::AcceptedCredentials) && permissionedDomain[jss::AcceptedCredentials].isArray() && @@ -684,9 +691,11 @@ public: if (check1) { - auto const& credential = permissionedDomain[jss::AcceptedCredentials][0u][jss::Credential]; + auto const& credential = + permissionedDomain[jss::AcceptedCredentials][0u][jss::Credential]; BEAST_EXPECT( - credential.isMember(sfIssuer.jsonName) && (credential[sfIssuer.jsonName] == issuer.human())); + credential.isMember(sfIssuer.jsonName) && + (credential[sfIssuer.jsonName] == issuer.human())); BEAST_EXPECT( credential.isMember(sfCredentialType.jsonName) && (credential[sfCredentialType.jsonName] == strHex(credentialType1))); @@ -769,8 +778,18 @@ public: // xchain_create_account_claim_id should be present on the door // account (Account::master) to collect the signatures until a // quorum is reached - scEnv(test::jtx::create_account_attestation( - x.scAttester, x.jvb, x.mcCarol, amt, x.reward, x.payees[0], true, 1, x.scuAlice, x.signers[0])); + scEnv( + test::jtx::create_account_attestation( + x.scAttester, + x.jvb, + x.mcCarol, + amt, + x.reward, + x.payees[0], + true, + 1, + x.scuAlice, + x.signers[0])); scEnv.close(); auto scEnvAcctObjs = [&](Account const& acct, char const* type) { @@ -783,12 +802,17 @@ public: { // Find the xchain_create_account_claim_id - Json::Value const resp = scEnvAcctObjs(Account::master, jss::xchain_owned_create_account_claim_id); + Json::Value const resp = + scEnvAcctObjs(Account::master, jss::xchain_owned_create_account_claim_id); BEAST_EXPECT(acctObjsIsSize(resp, 1)); - auto const& xchain_create_account_claim_id = resp[jss::result][jss::account_objects][0u]; - BEAST_EXPECT(xchain_create_account_claim_id[sfAccount.jsonName] == Account::master.human()); - BEAST_EXPECT(xchain_create_account_claim_id[sfXChainAccountCreateCount.getJsonName()].asUInt() == 1); + auto const& xchain_create_account_claim_id = + resp[jss::result][jss::account_objects][0u]; + BEAST_EXPECT( + xchain_create_account_claim_id[sfAccount.jsonName] == Account::master.human()); + BEAST_EXPECT( + xchain_create_account_claim_id[sfXChainAccountCreateCount.getJsonName()] + .asUInt() == 1); } } @@ -897,7 +921,8 @@ public: return v; }(); - std::uint32_t const expectedAccountObjects{static_cast(std::size(expectedLedgerTypes))}; + std::uint32_t const expectedAccountObjects{ + static_cast(std::size(expectedLedgerTypes))}; if (BEAST_EXPECT(acctObjsIsSize(resp, expectedAccountObjects))) { @@ -937,7 +962,8 @@ public: }; // Make a lambda we can use to check the number of fetched // account objects and their ledger type - auto expectObjects = [&](Json::Value const& resp, std::vector const& types) -> bool { + auto expectObjects = [&](Json::Value const& resp, + std::vector const& types) -> bool { if (!acctObjsIsSize(resp, types.size())) return false; std::vector typesOut; @@ -957,16 +983,21 @@ public: std::vector typesOut; getTypes(resp, typesOut); // request next two objects - resp = acctObjs(amm.ammAccount(), std::nullopt, 10, resp[jss::result][jss::marker].asString()); + resp = acctObjs( + amm.ammAccount(), std::nullopt, 10, resp[jss::result][jss::marker].asString()); getTypes(resp, typesOut); BEAST_EXPECT( (typesOut == std::vector{ - jss::AMM.c_str(), jss::RippleState.c_str(), jss::RippleState.c_str(), jss::RippleState.c_str()})); + jss::AMM.c_str(), + jss::RippleState.c_str(), + jss::RippleState.c_str(), + jss::RippleState.c_str()})); // filter by state: there are three trustlines resp = acctObjs(amm.ammAccount(), jss::state, 10); - BEAST_EXPECT( - expectObjects(resp, {jss::RippleState.c_str(), jss::RippleState.c_str(), jss::RippleState.c_str()})); + BEAST_EXPECT(expectObjects( + resp, + {jss::RippleState.c_str(), jss::RippleState.c_str(), jss::RippleState.c_str()})); // AMM account doesn't own offers BEAST_EXPECT(acctObjsIsSize(acctObjs(amm.ammAccount(), jss::offer), 0)); // gw account doesn't own AMM object @@ -1079,7 +1110,8 @@ public: // test an invalid marker that has a non-hex character BEAST_EXPECT(testInvalidMarker( - "00000000F51DFC2A09D62CBBA1DFBDD4691DAC96AD98B900000000000000000G", "Invalid field \'marker\'.")); + "00000000F51DFC2A09D62CBBA1DFBDD4691DAC96AD98B900000000000000000G", + "Invalid field \'marker\'.")); // this lambda function is used to create some fake marker using given // taxon and sequence because we want to test some unassociated markers @@ -1090,17 +1122,18 @@ public: std::uint16_t flags = 0, std::uint16_t fee = 0) { // the marker has the exact same format as an NFTokenID - return to_string(NFTokenMint::createNFTokenID(flags, fee, issuer, nft::toTaxon(taxon), tokenSeq)); + return to_string( + NFTokenMint::createNFTokenID(flags, fee, issuer, nft::toTaxon(taxon), tokenSeq)); }; // test an unassociated marker which does not exist in the NFTokenIDs - BEAST_EXPECT( - testInvalidMarker(createFakeNFTMarker(bob.id(), 0x000000000, 0x00000000), "Invalid field \'marker\'.")); + BEAST_EXPECT(testInvalidMarker( + createFakeNFTMarker(bob.id(), 0x000000000, 0x00000000), "Invalid field \'marker\'.")); // test an unassociated marker which exceeds the maximum value of the // existing NFTokenID - BEAST_EXPECT( - testInvalidMarker(createFakeNFTMarker(bob.id(), 0xFFFFFFFF, 0xFFFFFFFF), "Invalid field \'marker\'.")); + BEAST_EXPECT(testInvalidMarker( + createFakeNFTMarker(bob.id(), 0xFFFFFFFF, 0xFFFFFFFF), "Invalid field \'marker\'.")); } void diff --git a/src/test/rpc/AccountOffers_test.cpp b/src/test/rpc/AccountOffers_test.cpp index ffa1d70992..55e60f8caa 100644 --- a/src/test/rpc/AccountOffers_test.cpp +++ b/src/test/rpc/AccountOffers_test.cpp @@ -12,7 +12,8 @@ public: static bool checkMarker(Json::Value const& val) { - return val.isMember(jss::marker) && val[jss::marker].isString() && val[jss::marker].asString().size() > 0; + return val.isMember(jss::marker) && val[jss::marker].isString() && + val[jss::marker].asString().size() > 0; } void @@ -52,7 +53,8 @@ public: Json::Value jvParams; jvParams[jss::account] = bob.human(); jvParams[jss::limit] = 1u; - auto const jrr_l = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; + auto const jrr_l = + env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; auto const& jro_l = jrr_l[jss::offers]; BEAST_EXPECT(checkMarker(jrr_l)); // 9u is the expected size, since one account object is a trustline @@ -115,7 +117,8 @@ public: Json::Value jvParams; jvParams[jss::account] = bob.human(); jvParams[jss::limit] = 1u; - auto const jrr_l_1 = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; + auto const jrr_l_1 = + env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; auto const& jro_l_1 = jrr_l_1[jss::offers]; // there is a difference in the validation of the limit param // between admin and non-admin requests. with admin requests, the @@ -130,7 +133,8 @@ public: // second item...with previous marker passed jvParams[jss::marker] = jrr_l_1[jss::marker]; - auto const jrr_l_2 = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; + auto const jrr_l_2 = + env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; auto const& jro_l_2 = jrr_l_2[jss::offers]; BEAST_EXPECT(checkMarker(jrr_l_2)); BEAST_EXPECT(checkArraySize(jro_l_2, 1u)); @@ -139,7 +143,8 @@ public: // last item...with previous marker passed jvParams[jss::marker] = jrr_l_2[jss::marker]; jvParams[jss::limit] = 10u; - auto const jrr_l_3 = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; + auto const jrr_l_3 = + env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; auto const& jro_l_3 = jrr_l_3[jss::offers]; BEAST_EXPECT(!jrr_l_3.isMember(jss::marker)); BEAST_EXPECT(checkArraySize(jro_l_3, 1u)); @@ -155,7 +160,8 @@ public: Json::Value jvParams; jvParams[jss::account] = bob.human(); jvParams[jss::limit] = 0u; - auto const jrr = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; + auto const jrr = + env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(jrr.isMember(jss::error_message)); } } @@ -205,7 +211,8 @@ public: // empty string account Json::Value jvParams; jvParams[jss::account] = ""; - auto const jrr = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; + auto const jrr = + env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(jrr[jss::error] == "actMalformed"); BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT(jrr[jss::error_message] == "Account malformed."); @@ -224,7 +231,8 @@ public: Json::Value jvParams; jvParams[jss::account] = bob.human(); jvParams[jss::limit] = "0"; // NOT an integer - auto const jrr = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; + auto const jrr = + env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'limit', not unsigned integer."); @@ -235,10 +243,12 @@ public: Json::Value jvParams; jvParams[jss::account] = bob.human(); jvParams[jss::marker] = "NOT_A_MARKER"; - auto const jrr = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; + auto const jrr = + env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::status] == "error"); - BEAST_EXPECTS(jrr[jss::error_message] == "Invalid field 'marker'.", jrr.toStyledString()); + BEAST_EXPECTS( + jrr[jss::error_message] == "Invalid field 'marker'.", jrr.toStyledString()); } { @@ -246,7 +256,8 @@ public: Json::Value jvParams; jvParams[jss::account] = bob.human(); jvParams[jss::marker] = 1; - auto const jrr = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; + auto const jrr = + env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'marker', not string."); @@ -257,7 +268,8 @@ public: Json::Value jvParams; jvParams[jss::account] = bob.human(); jvParams[jss::ledger_index] = 10u; - auto const jrr = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; + auto const jrr = + env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(jrr[jss::error] == "lgrNotFound"); BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT(jrr[jss::error_message] == "ledgerNotFound"); diff --git a/src/test/rpc/AccountSet_test.cpp b/src/test/rpc/AccountSet_test.cpp index 2e238773f9..d342bf366a 100644 --- a/src/test/rpc/AccountSet_test.cpp +++ b/src/test/rpc/AccountSet_test.cpp @@ -1,12 +1,11 @@ #include -#include - #include #include #include #include #include +#include namespace xrpl { @@ -44,7 +43,8 @@ public: env(regkey(alice, alie)); env.close(); - auto testFlags = [this, &alice, &alie, &env](std::initializer_list goodFlags) { + auto testFlags = [this, &alice, &alie, &env]( + std::initializer_list goodFlags) { std::uint32_t const orig_flags = (*env.le(alice))[sfFlags]; for (std::uint32_t flag{1u}; flag < std::numeric_limits::digits; ++flag) { @@ -248,7 +248,8 @@ public: env.fund(XRP(10000), alice); auto jt = noop(alice); - std::string const locator = "9633EC8AF54F16B5286DB1D7B519EF49EEFC050C0C8AC4384F1D88ACD1BFDF05"; + std::string const locator = + "9633EC8AF54F16B5286DB1D7B519EF49EEFC050C0C8AC4384F1D88ACD1BFDF05"; jt[sfWalletLocator.fieldName] = locator; env(jt); BEAST_EXPECT(to_string((*env.le(alice))[sfWalletLocator]) == locator); @@ -292,24 +293,25 @@ public: testcase("TransferRate"); using namespace test::jtx; - auto doTests = [this](FeatureBitset const& features, std::initializer_list testData) { - Env env(*this, features); + auto doTests = + [this](FeatureBitset const& features, std::initializer_list testData) { + Env env(*this, features); - Account const alice("alice"); - env.fund(XRP(10000), alice); + Account const alice("alice"); + env.fund(XRP(10000), alice); - for (auto const& r : testData) - { - env(rate(alice, r.set), ter(r.code)); - env.close(); + for (auto const& r : testData) + { + env(rate(alice, r.set), ter(r.code)); + env.close(); - // If the field is not present expect the default value - if (!(*env.le(alice))[~sfTransferRate]) - BEAST_EXPECT(r.get == 1.0); - else - BEAST_EXPECT(*(*env.le(alice))[~sfTransferRate] == r.get * QUALITY_ONE); - } - }; + // If the field is not present expect the default value + if (!(*env.le(alice))[~sfTransferRate]) + BEAST_EXPECT(r.get == 1.0); + else + BEAST_EXPECT(*(*env.le(alice))[~sfTransferRate] == r.get * QUALITY_ONE); + } + }; doTests( testable_amendments(), @@ -405,13 +407,15 @@ public: // We'll insert a replacement for the account root // with the higher (currently invalid) transfer rate. auto replacement = std::make_shared(*sle, sle->key()); - (*replacement)[sfTransferRate] = static_cast(transferRate * QUALITY_ONE); + (*replacement)[sfTransferRate] = + static_cast(transferRate * QUALITY_ONE); view.rawReplace(replacement); return true; }); auto const amount = USD(1); - auto const amountWithRate = toAmount(multiply(amount.value(), Rate(transferRate * QUALITY_ONE))); + auto const amountWithRate = + toAmount(multiply(amount.value(), Rate(transferRate * QUALITY_ONE))); env(pay(gw, alice, USD(10))); env(pay(alice, bob, amount), sendmax(USD(10))); diff --git a/src/test/rpc/AccountTx_test.cpp b/src/test/rpc/AccountTx_test.cpp index 3cc9dbc77c..5015b960f9 100644 --- a/src/test/rpc/AccountTx_test.cpp +++ b/src/test/rpc/AccountTx_test.cpp @@ -62,13 +62,16 @@ class AccountTx_test : public beast::unit_test::suite for (Json::Value const& metaNode : txNode[jss::meta][sfAffectedNodes.jsonName]) { if (metaNode.isMember(sfCreatedNode.jsonName)) - createdNodes.insert(metaNode[sfCreatedNode.jsonName][sfLedgerEntryType.jsonName].asString()); + createdNodes.insert( + metaNode[sfCreatedNode.jsonName][sfLedgerEntryType.jsonName].asString()); else if (metaNode.isMember(sfDeletedNode.jsonName)) - deletedNodes.insert(metaNode[sfDeletedNode.jsonName][sfLedgerEntryType.jsonName].asString()); + deletedNodes.insert( + metaNode[sfDeletedNode.jsonName][sfLedgerEntryType.jsonName].asString()); else if (metaNode.isMember(sfModifiedNode.jsonName)) - modifiedNodes.insert(metaNode[sfModifiedNode.jsonName][sfLedgerEntryType.jsonName].asString()); + modifiedNodes.insert( + metaNode[sfModifiedNode.jsonName][sfLedgerEntryType.jsonName].asString()); else fail("Unexpected or unlabeled node type in metadata.", __FILE__, __LINE__); @@ -102,16 +105,20 @@ class AccountTx_test : public beast::unit_test::suite case 1: return j.isMember(jss::result) && (j[jss::result][jss::status] == "success") && (j[jss::result][jss::transactions].size() == 2) && - (j[jss::result][jss::transactions][0u][jss::tx][jss::TransactionType] == jss::AccountSet) && - (j[jss::result][jss::transactions][1u][jss::tx][jss::TransactionType] == jss::Payment) && - (j[jss::result][jss::transactions][1u][jss::tx][jss::DeliverMax] == "10000000010") && + (j[jss::result][jss::transactions][0u][jss::tx][jss::TransactionType] == + jss::AccountSet) && + (j[jss::result][jss::transactions][1u][jss::tx][jss::TransactionType] == + jss::Payment) && + (j[jss::result][jss::transactions][1u][jss::tx][jss::DeliverMax] == + "10000000010") && (j[jss::result][jss::transactions][1u][jss::tx][jss::Amount] == j[jss::result][jss::transactions][1u][jss::tx][jss::DeliverMax]); case 2: case 3: if (j.isMember(jss::result) && (j[jss::result][jss::status] == "success") && (j[jss::result][jss::transactions].size() == 2) && - (j[jss::result][jss::transactions][0u][jss::tx_json][jss::TransactionType] == jss::AccountSet)) + (j[jss::result][jss::transactions][0u][jss::tx_json] + [jss::TransactionType] == jss::AccountSet)) { auto const& payment = j[jss::result][jss::transactions][1u]; @@ -123,7 +130,8 @@ class AccountTx_test : public beast::unit_test::suite (payment[jss::hash] == "9F3085D85F472D1CC29627F260DF68EDE59D42D1D0C33E345" "ECF0D4CE981D0A8") && - (payment[jss::validated] == true) && (payment[jss::ledger_index] == 3) && + (payment[jss::validated] == true) && + (payment[jss::ledger_index] == 3) && (payment[jss::ledger_hash] == "5476DCD816EA04CBBA57D47BBF1FC58A5217CC93A5ADD79CB" "580A5AFDD727E33") && @@ -171,14 +179,16 @@ class AccountTx_test : public beast::unit_test::suite if (apiVersion < 2u) BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); else - BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); + BEAST_EXPECT( + isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); p[jss::ledger_index_min] = 1; p[jss::ledger_index_max] = 2; if (apiVersion < 2u) BEAST_EXPECT(noTxs(env.rpc("json", "account_tx", to_string(p)))); else - BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); + BEAST_EXPECT( + isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); p[jss::ledger_index_min] = 2; p[jss::ledger_index_max] = 1; @@ -196,7 +206,8 @@ class AccountTx_test : public beast::unit_test::suite if (apiVersion < 2u) BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); else - BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); + BEAST_EXPECT( + isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); p[jss::ledger_index_min] = env.current()->header().seq; BEAST_EXPECT(isErr( @@ -214,7 +225,8 @@ class AccountTx_test : public beast::unit_test::suite if (apiVersion < 2u) BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); else - BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); + BEAST_EXPECT( + isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); p[jss::ledger_index_max] = 3; BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); @@ -278,7 +290,8 @@ class AccountTx_test : public beast::unit_test::suite if (apiVersion < 2u) BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); else - BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); + BEAST_EXPECT( + isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); } // test account non-string { @@ -396,7 +409,8 @@ class AccountTx_test : public beast::unit_test::suite // Test case: limit = 10 should succeed (valid integer) p[jss::limit] = 10; - BEAST_EXPECT(env.rpc("json", "account_tx", to_string(p))[jss::result][jss::status] == "success"); + BEAST_EXPECT( + env.rpc("json", "account_tx", to_string(p))[jss::result][jss::status] == "success"); } } @@ -672,7 +686,9 @@ class AccountTx_test : public beast::unit_test::suite // The first two transactions listed in sanity haven't happened yet. constexpr unsigned int beckyDeletedOffset = 2; - BEAST_EXPECT(std::size(sanity) == result[jss::result][jss::transactions].size() + beckyDeletedOffset); + BEAST_EXPECT( + std::size(sanity) == + result[jss::result][jss::transactions].size() + beckyDeletedOffset); Json::Value const& txs{result[jss::result][jss::transactions]}; @@ -684,7 +700,8 @@ class AccountTx_test : public beast::unit_test::suite // All it takes is a large enough XRP payment to resurrect // becky's account. Try too small a payment. - env(pay(alice, becky, drops(env.current()->fees().accountReserve(0)) - XRP(1)), ter(tecNO_DST_INSUF_XRP)); + env(pay(alice, becky, drops(env.current()->fees().accountReserve(0)) - XRP(1)), + ter(tecNO_DST_INSUF_XRP)); env.close(); // Actually resurrect becky's account. @@ -756,7 +773,9 @@ class AccountTx_test : public beast::unit_test::suite // alice creates issuance mptAlice.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback | tfMPTRequireAuth | tfMPTCanTransfer}); + {.ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanClawback | tfMPTRequireAuth | tfMPTCanTransfer}); checkAliceAcctTx(3, jss::MPTokenIssuanceCreate); diff --git a/src/test/rpc/AmendmentBlocked_test.cpp b/src/test/rpc/AmendmentBlocked_test.cpp index 73a8c6d299..e61f22fa0e 100644 --- a/src/test/rpc/AmendmentBlocked_test.cpp +++ b/src/test/rpc/AmendmentBlocked_test.cpp @@ -1,10 +1,10 @@ #include #include -#include #include #include +#include namespace xrpl { @@ -63,7 +63,8 @@ class AmendmentBlocked_test : public beast::unit_test::suite pf_req[jss::destination_amount] = bob["USD"](20).value().getJson(JsonOptions::none); jr = wsc->invoke("path_find", pf_req)[jss::result]; BEAST_EXPECT( - jr.isMember(jss::alternatives) && jr[jss::alternatives].isArray() && jr[jss::alternatives].size() == 1); + jr.isMember(jss::alternatives) && jr[jss::alternatives].isArray() && + jr[jss::alternatives].size() == 1); BEAST_EXPECT(!jr.isMember(jss::warnings)); // submit @@ -127,7 +128,8 @@ class AmendmentBlocked_test : public beast::unit_test::suite pf_req[jss::destination_amount] = bob["USD"](20).value().getJson(JsonOptions::none); jr = wsc->invoke("path_find", pf_req)[jss::result]; BEAST_EXPECT( - jr.isMember(jss::alternatives) && jr[jss::alternatives].isArray() && jr[jss::alternatives].size() == 1); + jr.isMember(jss::alternatives) && jr[jss::alternatives].isArray() && + jr[jss::alternatives].size() == 1); BEAST_EXPECT(!jr.isMember(jss::warnings)); // submit diff --git a/src/test/rpc/BookChanges_test.cpp b/src/test/rpc/BookChanges_test.cpp index 4ea4b8233b..6bd71b141b 100644 --- a/src/test/rpc/BookChanges_test.cpp +++ b/src/test/rpc/BookChanges_test.cpp @@ -74,7 +74,8 @@ public: using namespace jtx; FeatureBitset const all{ - jtx::testable_amendments() | featurePermissionedDomains | featureCredentials | featurePermissionedDEX}; + jtx::testable_amendments() | featurePermissionedDomains | featureCredentials | + featurePermissionedDEX}; Env env(*this, all); PermissionedDEX permDex(env); diff --git a/src/test/rpc/Book_test.cpp b/src/test/rpc/Book_test.cpp index 543e163432..c9d93b87a6 100644 --- a/src/test/rpc/Book_test.cpp +++ b/src/test/rpc/Book_test.cpp @@ -15,7 +15,11 @@ namespace test { class Book_test : public beast::unit_test::suite { std::string - getBookDir(jtx::Env& env, Issue const& in, Issue const& out, std::optional const& domain = std::nullopt) + getBookDir( + jtx::Env& env, + Issue const& in, + Issue const& out, + std::optional const& domain = std::nullopt) { std::string dir; auto uBookBase = getBookBase({in, out, domain}); @@ -67,7 +71,8 @@ public: } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 0); + BEAST_EXPECT( + jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 0); BEAST_EXPECT(!jv[jss::result].isMember(jss::asks)); BEAST_EXPECT(!jv[jss::result].isMember(jss::bids)); } @@ -143,11 +148,14 @@ public: } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 1); BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerGets] == XRP(200).value().getJson(JsonOptions::none)); + jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 1); BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerPays] == USD(100).value().getJson(JsonOptions::none)); + jv[jss::result][jss::offers][0u][jss::TakerGets] == + XRP(200).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::offers][0u][jss::TakerPays] == + USD(100).value().getJson(JsonOptions::none)); BEAST_EXPECT(!jv[jss::result].isMember(jss::asks)); BEAST_EXPECT(!jv[jss::result].isMember(jss::bids)); } @@ -217,8 +225,10 @@ public: } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT(jv[jss::result].isMember(jss::asks) && jv[jss::result][jss::asks].size() == 0); - BEAST_EXPECT(jv[jss::result].isMember(jss::bids) && jv[jss::result][jss::bids].size() == 0); + BEAST_EXPECT( + jv[jss::result].isMember(jss::asks) && jv[jss::result][jss::asks].size() == 0); + BEAST_EXPECT( + jv[jss::result].isMember(jss::bids) && jv[jss::result][jss::bids].size() == 0); BEAST_EXPECT(!jv[jss::result].isMember(jss::offers)); } @@ -301,12 +311,22 @@ public: } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT(jv[jss::result].isMember(jss::asks) && jv[jss::result][jss::asks].size() == 1); - BEAST_EXPECT(jv[jss::result].isMember(jss::bids) && jv[jss::result][jss::bids].size() == 1); - BEAST_EXPECT(jv[jss::result][jss::asks][0u][jss::TakerGets] == USD(100).value().getJson(JsonOptions::none)); - BEAST_EXPECT(jv[jss::result][jss::asks][0u][jss::TakerPays] == XRP(500).value().getJson(JsonOptions::none)); - BEAST_EXPECT(jv[jss::result][jss::bids][0u][jss::TakerGets] == XRP(200).value().getJson(JsonOptions::none)); - BEAST_EXPECT(jv[jss::result][jss::bids][0u][jss::TakerPays] == USD(100).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result].isMember(jss::asks) && jv[jss::result][jss::asks].size() == 1); + BEAST_EXPECT( + jv[jss::result].isMember(jss::bids) && jv[jss::result][jss::bids].size() == 1); + BEAST_EXPECT( + jv[jss::result][jss::asks][0u][jss::TakerGets] == + USD(100).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::asks][0u][jss::TakerPays] == + XRP(500).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::bids][0u][jss::TakerGets] == + XRP(200).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::bids][0u][jss::TakerPays] == + USD(100).value().getJson(JsonOptions::none)); BEAST_EXPECT(!jv[jss::result].isMember(jss::offers)); } @@ -391,7 +411,8 @@ public: } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 0); + BEAST_EXPECT( + jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 0); BEAST_EXPECT(!jv[jss::result].isMember(jss::asks)); BEAST_EXPECT(!jv[jss::result].isMember(jss::bids)); } @@ -504,15 +525,20 @@ public: } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 2); BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerGets] == XRP(200).value().getJson(JsonOptions::none)); + jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 2); BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerPays] == USD(100).value().getJson(JsonOptions::none)); + jv[jss::result][jss::offers][0u][jss::TakerGets] == + XRP(200).value().getJson(JsonOptions::none)); BEAST_EXPECT( - jv[jss::result][jss::offers][1u][jss::TakerGets] == CNY(200).value().getJson(JsonOptions::none)); + jv[jss::result][jss::offers][0u][jss::TakerPays] == + USD(100).value().getJson(JsonOptions::none)); BEAST_EXPECT( - jv[jss::result][jss::offers][1u][jss::TakerPays] == JPY(100).value().getJson(JsonOptions::none)); + jv[jss::result][jss::offers][1u][jss::TakerGets] == + CNY(200).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::offers][1u][jss::TakerPays] == + JPY(100).value().getJson(JsonOptions::none)); BEAST_EXPECT(!jv[jss::result].isMember(jss::asks)); BEAST_EXPECT(!jv[jss::result].isMember(jss::bids)); } @@ -614,8 +640,10 @@ public: } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT(jv[jss::result].isMember(jss::asks) && jv[jss::result][jss::asks].size() == 0); - BEAST_EXPECT(jv[jss::result].isMember(jss::bids) && jv[jss::result][jss::bids].size() == 0); + BEAST_EXPECT( + jv[jss::result].isMember(jss::asks) && jv[jss::result][jss::asks].size() == 0); + BEAST_EXPECT( + jv[jss::result].isMember(jss::bids) && jv[jss::result][jss::bids].size() == 0); BEAST_EXPECT(!jv[jss::result].isMember(jss::offers)); } @@ -744,16 +772,34 @@ public: } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT(jv[jss::result].isMember(jss::asks) && jv[jss::result][jss::asks].size() == 2); - BEAST_EXPECT(jv[jss::result].isMember(jss::bids) && jv[jss::result][jss::bids].size() == 2); - BEAST_EXPECT(jv[jss::result][jss::asks][0u][jss::TakerGets] == USD(100).value().getJson(JsonOptions::none)); - BEAST_EXPECT(jv[jss::result][jss::asks][0u][jss::TakerPays] == XRP(500).value().getJson(JsonOptions::none)); - BEAST_EXPECT(jv[jss::result][jss::asks][1u][jss::TakerGets] == JPY(100).value().getJson(JsonOptions::none)); - BEAST_EXPECT(jv[jss::result][jss::asks][1u][jss::TakerPays] == CNY(500).value().getJson(JsonOptions::none)); - BEAST_EXPECT(jv[jss::result][jss::bids][0u][jss::TakerGets] == XRP(200).value().getJson(JsonOptions::none)); - BEAST_EXPECT(jv[jss::result][jss::bids][0u][jss::TakerPays] == USD(100).value().getJson(JsonOptions::none)); - BEAST_EXPECT(jv[jss::result][jss::bids][1u][jss::TakerGets] == CNY(200).value().getJson(JsonOptions::none)); - BEAST_EXPECT(jv[jss::result][jss::bids][1u][jss::TakerPays] == JPY(100).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result].isMember(jss::asks) && jv[jss::result][jss::asks].size() == 2); + BEAST_EXPECT( + jv[jss::result].isMember(jss::bids) && jv[jss::result][jss::bids].size() == 2); + BEAST_EXPECT( + jv[jss::result][jss::asks][0u][jss::TakerGets] == + USD(100).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::asks][0u][jss::TakerPays] == + XRP(500).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::asks][1u][jss::TakerGets] == + JPY(100).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::asks][1u][jss::TakerPays] == + CNY(500).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::bids][0u][jss::TakerGets] == + XRP(200).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::bids][0u][jss::TakerPays] == + USD(100).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::bids][1u][jss::TakerGets] == + CNY(200).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::bids][1u][jss::TakerPays] == + JPY(100).value().getJson(JsonOptions::none)); BEAST_EXPECT(!jv[jss::result].isMember(jss::offers)); } @@ -858,7 +904,8 @@ public: } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 0); + BEAST_EXPECT( + jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 0); BEAST_EXPECT(!jv[jss::result].isMember(jss::asks)); BEAST_EXPECT(!jv[jss::result].isMember(jss::bids)); } @@ -907,7 +954,8 @@ public: BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jval) { auto const& t = jval[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == USD(10).value().getJson(JsonOptions::none) && t[jss::owner_funds] == "100" && + t[jss::TakerGets] == USD(10).value().getJson(JsonOptions::none) && + t[jss::owner_funds] == "100" && t[jss::TakerPays] == XRP(4000).value().getJson(JsonOptions::none); })); @@ -917,7 +965,8 @@ public: BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jval) { auto const& t = jval[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == USD(5).value().getJson(JsonOptions::none) && t[jss::owner_funds] == "50" && + t[jss::TakerGets] == USD(5).value().getJson(JsonOptions::none) && + t[jss::owner_funds] == "50" && t[jss::TakerPays] == XRP(2000).value().getJson(JsonOptions::none); })); @@ -1204,7 +1253,8 @@ public: jvParams[jss::taker_gets] = Json::objectValue; auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_pays.currency', not string."); + BEAST_EXPECT( + jrr[jss::error_message] == "Invalid field 'taker_pays.currency', not string."); } { @@ -1224,7 +1274,8 @@ public: jvParams[jss::taker_gets][jss::currency] = 1; auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_gets.currency', not string."); + BEAST_EXPECT( + jrr[jss::error_message] == "Invalid field 'taker_gets.currency', not string."); } { @@ -1234,7 +1285,8 @@ public: jvParams[jss::taker_gets][jss::currency] = "XRP"; auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "srcCurMalformed"); - BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_pays.currency', bad currency."); + BEAST_EXPECT( + jrr[jss::error_message] == "Invalid field 'taker_pays.currency', bad currency."); } { @@ -1244,7 +1296,8 @@ public: jvParams[jss::taker_gets][jss::currency] = "NOT_VALID"; auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "dstAmtMalformed"); - BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_gets.currency', bad currency."); + BEAST_EXPECT( + jrr[jss::error_message] == "Invalid field 'taker_gets.currency', bad currency."); } { @@ -1255,7 +1308,8 @@ public: jvParams[jss::taker_gets][jss::issuer] = 1; auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_gets.issuer', not string."); + BEAST_EXPECT( + jrr[jss::error_message] == "Invalid field 'taker_gets.issuer', not string."); } { @@ -1266,7 +1320,8 @@ public: jvParams[jss::taker_gets][jss::currency] = "USD"; auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_pays.issuer', not string."); + BEAST_EXPECT( + jrr[jss::error_message] == "Invalid field 'taker_pays.issuer', not string."); } { @@ -1277,7 +1332,8 @@ public: jvParams[jss::taker_gets][jss::currency] = "USD"; auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "srcIsrMalformed"); - BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_pays.issuer', bad issuer."); + BEAST_EXPECT( + jrr[jss::error_message] == "Invalid field 'taker_pays.issuer', bad issuer."); } { @@ -1288,7 +1344,9 @@ public: jvParams[jss::taker_gets][jss::currency] = "USD"; auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "srcIsrMalformed"); - BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_pays.issuer', bad issuer account one."); + BEAST_EXPECT( + jrr[jss::error_message] == + "Invalid field 'taker_pays.issuer', bad issuer account one."); } { @@ -1299,7 +1357,8 @@ public: jvParams[jss::taker_gets][jss::issuer] = gw.human() + "DEAD"; auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "dstIsrMalformed"); - BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_gets.issuer', bad issuer."); + BEAST_EXPECT( + jrr[jss::error_message] == "Invalid field 'taker_gets.issuer', bad issuer."); } { @@ -1310,7 +1369,9 @@ public: jvParams[jss::taker_gets][jss::issuer] = toBase58(noAccount()); auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "dstIsrMalformed"); - BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_gets.issuer', bad issuer account one."); + BEAST_EXPECT( + jrr[jss::error_message] == + "Invalid field 'taker_gets.issuer', bad issuer account one."); } { @@ -1337,7 +1398,9 @@ public: jvParams[jss::taker_gets][jss::issuer] = gw.human(); auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "srcIsrMalformed"); - BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_pays.issuer', expected non-XRP issuer."); + BEAST_EXPECT( + jrr[jss::error_message] == + "Invalid field 'taker_pays.issuer', expected non-XRP issuer."); } { @@ -1494,7 +1557,8 @@ public: using namespace jtx; FeatureBitset const all{ - jtx::testable_amendments() | featurePermissionedDomains | featureCredentials | featurePermissionedDEX}; + jtx::testable_amendments() | featurePermissionedDomains | featureCredentials | + featurePermissionedDEX}; Env env(*this, all); PermissionedDEX permDex(env); @@ -1515,7 +1579,8 @@ public: BEAST_EXPECT(jrr[jss::offers].size() == 1); auto const jrOffer = jrr[jss::offers][0u]; BEAST_EXPECT(jrOffer[sfAccount.fieldName] == alice.human()); - BEAST_EXPECT(jrOffer[sfBookDirectory.fieldName] == getBookDir(env, XRP, USD.issue(), domainID)); + BEAST_EXPECT( + jrOffer[sfBookDirectory.fieldName] == getBookDir(env, XRP, USD.issue(), domainID)); BEAST_EXPECT(jrOffer[sfBookNode.fieldName] == "0"); BEAST_EXPECT(jrOffer[jss::Flags] == 0); BEAST_EXPECT(jrOffer[sfLedgerEntryType.fieldName] == jss::Offer); @@ -1541,12 +1606,17 @@ public: } auto checkSubBooks = [&](Json::Value const& jv) { - BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 1); BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerGets] == USD(10).value().getJson(JsonOptions::none)); + jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 1); BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerPays] == XRP(10).value().getJson(JsonOptions::none)); - BEAST_EXPECT(jv[jss::result][jss::offers][0u][sfDomainID.jsonName].asString() == to_string(domainID)); + jv[jss::result][jss::offers][0u][jss::TakerGets] == + USD(10).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::offers][0u][jss::TakerPays] == + XRP(10).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::offers][0u][sfDomainID.jsonName].asString() == + to_string(domainID)); }; // book_offers: requesting domain book returns hybrid offer @@ -1598,7 +1668,8 @@ public: auto jv = wsc->invoke("subscribe", books); if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 0); + BEAST_EXPECT( + jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 0); } } @@ -1609,7 +1680,8 @@ public: using namespace jtx; FeatureBitset const all{ - jtx::testable_amendments() | featurePermissionedDomains | featureCredentials | featurePermissionedDEX}; + jtx::testable_amendments() | featurePermissionedDomains | featureCredentials | + featurePermissionedDEX}; Env env(*this, all); PermissionedDEX permDex(env); @@ -1630,7 +1702,8 @@ public: BEAST_EXPECT(jrr[jss::offers].size() == 1); auto const jrOffer = jrr[jss::offers][0u]; BEAST_EXPECT(jrOffer[sfAccount.fieldName] == alice.human()); - BEAST_EXPECT(jrOffer[sfBookDirectory.fieldName] == getBookDir(env, XRP, USD.issue(), domainID)); + BEAST_EXPECT( + jrOffer[sfBookDirectory.fieldName] == getBookDir(env, XRP, USD.issue(), domainID)); BEAST_EXPECT(jrOffer[sfBookNode.fieldName] == "0"); BEAST_EXPECT(jrOffer[jss::Flags] == lsfHybrid); BEAST_EXPECT(jrOffer[sfLedgerEntryType.fieldName] == jss::Offer); @@ -1656,12 +1729,17 @@ public: } auto checkSubBooks = [&](Json::Value const& jv) { - BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 1); BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerGets] == USD(10).value().getJson(JsonOptions::none)); + jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 1); BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerPays] == XRP(10).value().getJson(JsonOptions::none)); - BEAST_EXPECT(jv[jss::result][jss::offers][0u][sfDomainID.jsonName].asString() == to_string(domainID)); + jv[jss::result][jss::offers][0u][jss::TakerGets] == + USD(10).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::offers][0u][jss::TakerPays] == + XRP(10).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + jv[jss::result][jss::offers][0u][sfDomainID.jsonName].asString() == + to_string(domainID)); }; // book_offers: requesting domain book returns hybrid offer diff --git a/src/test/rpc/DeliveredAmount_test.cpp b/src/test/rpc/DeliveredAmount_test.cpp index 8d376893ec..e024e249c3 100644 --- a/src/test/rpc/DeliveredAmount_test.cpp +++ b/src/test/rpc/DeliveredAmount_test.cpp @@ -228,14 +228,16 @@ class DeliveredAmount_test : public beast::unit_test::suite // Check stream update while (true) { - auto const r = wsc->findMsg(1s, [&](auto const& jv) { return jv[jss::ledger_index] == 4; }); + auto const r = wsc->findMsg( + 1s, [&](auto const& jv) { return jv[jss::ledger_index] == 4; }); if (!r) break; if (!r->isMember(jss::transaction)) continue; - BEAST_EXPECT(checkDeliveredAmount.checkTxn((*r)[jss::transaction], (*r)[jss::meta])); + BEAST_EXPECT( + checkDeliveredAmount.checkTxn((*r)[jss::transaction], (*r)[jss::meta])); } } BEAST_EXPECT(checkDeliveredAmount.checkExpectedCounters()); @@ -290,8 +292,8 @@ class DeliveredAmount_test : public beast::unit_test::suite jvParams[jss::ledger_index] = 4u; jvParams[jss::transactions] = true; jvParams[jss::expand] = true; - auto const jtxn = - env.rpc("json", "ledger", to_string(jvParams))[jss::result][jss::ledger][jss::transactions]; + auto const jtxn = env.rpc( + "json", "ledger", to_string(jvParams))[jss::result][jss::ledger][jss::transactions]; for (auto const& t : jtxn) BEAST_EXPECT(checkDeliveredAmount.checkTxn(t, t[jss::metaData])); BEAST_EXPECT(checkDeliveredAmount.checkExpectedCounters()); @@ -311,7 +313,8 @@ class DeliveredAmount_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}, .close = false}); - mptAlice.create({.transferFee = 25000, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); + mptAlice.create( + {.transferFee = 25000, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); auto const MPT = mptAlice["MPT"]; mptAlice.authorize({.account = bob}); @@ -330,8 +333,10 @@ class DeliveredAmount_test : public beast::unit_test::suite if (features[fixMPTDeliveredAmount]) { - BEAST_EXPECT(meta[sfDeliveredAmount.jsonName] == STAmount{MPT(800)}.getJson(JsonOptions::none)); - BEAST_EXPECT(meta[jss::delivered_amount] == STAmount{MPT(800)}.getJson(JsonOptions::none)); + BEAST_EXPECT( + meta[sfDeliveredAmount.jsonName] == STAmount{MPT(800)}.getJson(JsonOptions::none)); + BEAST_EXPECT( + meta[jss::delivered_amount] == STAmount{MPT(800)}.getJson(JsonOptions::none)); } else { @@ -347,8 +352,10 @@ class DeliveredAmount_test : public beast::unit_test::suite if (features[fixMPTDeliveredAmount]) { - BEAST_EXPECT(meta[sfDeliveredAmount.jsonName] == STAmount{MPT(960)}.getJson(JsonOptions::none)); - BEAST_EXPECT(meta[jss::delivered_amount] == STAmount{MPT(960)}.getJson(JsonOptions::none)); + BEAST_EXPECT( + meta[sfDeliveredAmount.jsonName] == STAmount{MPT(960)}.getJson(JsonOptions::none)); + BEAST_EXPECT( + meta[jss::delivered_amount] == STAmount{MPT(960)}.getJson(JsonOptions::none)); } else { diff --git a/src/test/rpc/DepositAuthorized_test.cpp b/src/test/rpc/DepositAuthorized_test.cpp index e8abfd58b8..755609439c 100644 --- a/src/test/rpc/DepositAuthorized_test.cpp +++ b/src/test/rpc/DepositAuthorized_test.cpp @@ -58,27 +58,44 @@ public: // becky is authorized to deposit to herself. validateDepositAuthResult( - env.rpc("json", "deposit_authorized", depositAuthArgs(becky, becky, "validated").toStyledString()), true); + env.rpc( + "json", + "deposit_authorized", + depositAuthArgs(becky, becky, "validated").toStyledString()), + true); // alice should currently be authorized to deposit to becky. validateDepositAuthResult( - env.rpc("json", "deposit_authorized", depositAuthArgs(alice, becky, "validated").toStyledString()), true); + env.rpc( + "json", + "deposit_authorized", + depositAuthArgs(alice, becky, "validated").toStyledString()), + true); // becky sets the DepositAuth flag in the current ledger. env(fset(becky, asfDepositAuth)); // alice is no longer authorized to deposit to becky in current ledger. validateDepositAuthResult( - env.rpc("json", "deposit_authorized", depositAuthArgs(alice, becky).toStyledString()), false); + env.rpc("json", "deposit_authorized", depositAuthArgs(alice, becky).toStyledString()), + false); env.close(); // becky is still authorized to deposit to herself. validateDepositAuthResult( - env.rpc("json", "deposit_authorized", depositAuthArgs(becky, becky, "validated").toStyledString()), true); + env.rpc( + "json", + "deposit_authorized", + depositAuthArgs(becky, becky, "validated").toStyledString()), + true); // It's not a reciprocal arrangement. becky can deposit to alice. validateDepositAuthResult( - env.rpc("json", "deposit_authorized", depositAuthArgs(becky, alice, "current").toStyledString()), true); + env.rpc( + "json", + "deposit_authorized", + depositAuthArgs(becky, alice, "current").toStyledString()), + true); // becky creates a deposit authorization for alice. env(deposit::auth(becky, alice)); @@ -86,22 +103,29 @@ public: // alice is now authorized to deposit to becky. validateDepositAuthResult( - env.rpc("json", "deposit_authorized", depositAuthArgs(alice, becky, "closed").toStyledString()), true); + env.rpc( + "json", + "deposit_authorized", + depositAuthArgs(alice, becky, "closed").toStyledString()), + true); // carol is still not authorized to deposit to becky. validateDepositAuthResult( - env.rpc("json", "deposit_authorized", depositAuthArgs(carol, becky).toStyledString()), false); + env.rpc("json", "deposit_authorized", depositAuthArgs(carol, becky).toStyledString()), + false); // becky clears the DepositAuth flag so carol becomes authorized. env(fclear(becky, asfDepositAuth)); env.close(); validateDepositAuthResult( - env.rpc("json", "deposit_authorized", depositAuthArgs(carol, becky).toStyledString()), true); + env.rpc("json", "deposit_authorized", depositAuthArgs(carol, becky).toStyledString()), + true); // alice is still authorized to deposit to becky. validateDepositAuthResult( - env.rpc("json", "deposit_authorized", depositAuthArgs(alice, becky).toStyledString()), true); + env.rpc("json", "deposit_authorized", depositAuthArgs(alice, becky).toStyledString()), + true); } // Test malformed cases. @@ -114,7 +138,8 @@ public: Account const becky{"becky"}; // Lambda that checks the (error) result of deposit_authorized. - auto verifyErr = [this](Json::Value const& result, char const* error, char const* errorMsg) { + auto verifyErr = [this]( + Json::Value const& result, char const* error, char const* errorMsg) { BEAST_EXPECT(result[jss::result][jss::status] == jss::error); BEAST_EXPECT(result[jss::result][jss::error] == error); BEAST_EXPECT(result[jss::result][jss::error_message] == errorMsg); @@ -154,7 +179,8 @@ public: Json::Value args{depositAuthArgs(alice, becky)}; args[jss::destination_account] = 7.3; Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; - verifyErr(result, "invalidParams", "Invalid field 'destination_account', not a string."); + verifyErr( + result, "invalidParams", "Invalid field 'destination_account', not a string."); } { // Corrupt destination_account field. @@ -167,7 +193,8 @@ public: // Request an invalid ledger. Json::Value args{depositAuthArgs(alice, becky, "-1")}; Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; - verifyErr(result, "invalidParams", "Invalid field 'ledger_index', not string or number."); + verifyErr( + result, "invalidParams", "Invalid field 'ledger_index', not string or number."); } { // Request a ledger that doesn't exist yet as a string. @@ -219,7 +246,9 @@ public: if (result.isMember(jss::deposit_authorized)) BEAST_EXPECT(result[jss::deposit_authorized] == authorized); if (authorized) - BEAST_EXPECT(result.isMember(jss::deposit_authorized) && (result[jss::deposit_authorized] == true)); + BEAST_EXPECT( + result.isMember(jss::deposit_authorized) && + (result[jss::deposit_authorized] == true)); BEAST_EXPECT(result.isMember(jss::error) == !error.empty()); if (!error.empty()) @@ -314,7 +343,8 @@ public: args[jss::credentials].append("hello world"); auto const jv = env.rpc("json", "deposit_authorized", args.toStyledString()); - checkCredentialsResponse(jv[jss::result], alice, becky, false, {"hello world"}, "invalidParams"); + checkCredentialsResponse( + jv[jss::result], alice, becky, false, {"hello world"}, "invalidParams"); } { @@ -345,8 +375,11 @@ public: "deposit_authorized with credentials not authorized: " "credential not accepted"); auto const jv = env.rpc( - "json", "deposit_authorized", depositAuthArgs(alice, becky, "validated", {credIdx}).toStyledString()); - checkCredentialsResponse(jv[jss::result], alice, becky, false, {credIdx}, "badCredentials"); + "json", + "deposit_authorized", + depositAuthArgs(alice, becky, "validated", {credIdx}).toStyledString()); + checkCredentialsResponse( + jv[jss::result], alice, becky, false, {credIdx}, "badCredentials"); } // alice accept credentials @@ -359,7 +392,8 @@ public: "json", "deposit_authorized", depositAuthArgs(alice, becky, "validated", {credIdx, credIdx}).toStyledString()); - checkCredentialsResponse(jv[jss::result], alice, becky, false, {credIdx, credIdx}, "badCredentials"); + checkCredentialsResponse( + jv[jss::result], alice, becky, false, {credIdx, credIdx}, "badCredentials"); } { @@ -386,14 +420,19 @@ public: testcase("deposit_authorized too long credentials"); auto const jv = env.rpc( - "json", "deposit_authorized", depositAuthArgs(alice, becky, "validated", credIds).toStyledString()); - checkCredentialsResponse(jv[jss::result], alice, becky, false, credIds, "invalidParams"); + "json", + "deposit_authorized", + depositAuthArgs(alice, becky, "validated", credIds).toStyledString()); + checkCredentialsResponse( + jv[jss::result], alice, becky, false, credIds, "invalidParams"); } { testcase("deposit_authorized with credentials"); auto const jv = env.rpc( - "json", "deposit_authorized", depositAuthArgs(alice, becky, "validated", {credIdx}).toStyledString()); + "json", + "deposit_authorized", + depositAuthArgs(alice, becky, "validated", {credIdx}).toStyledString()); checkCredentialsResponse(jv[jss::result], alice, becky, true, {credIdx}); } @@ -410,7 +449,9 @@ public: testcase("deposit_authorized account without preauth"); jv = env.rpc( - "json", "deposit_authorized", depositAuthArgs(becky, alice, "validated", {credBecky}).toStyledString()); + "json", + "deposit_authorized", + depositAuthArgs(becky, alice, "validated", {credBecky}).toStyledString()); checkCredentialsResponse(jv[jss::result], becky, alice, true, {credBecky}); } @@ -426,8 +467,11 @@ public: // alice try to use credential for different account jv = env.rpc( - "json", "deposit_authorized", depositAuthArgs(becky, alice, "validated", {credDiana}).toStyledString()); - checkCredentialsResponse(jv[jss::result], becky, alice, false, {credDiana}, "badCredentials"); + "json", + "deposit_authorized", + depositAuthArgs(becky, alice, "validated", {credDiana}).toStyledString()); + checkCredentialsResponse( + jv[jss::result], becky, alice, false, {credDiana}, "badCredentials"); } { @@ -435,7 +479,8 @@ public: // check expired credentials char const credType2[] = "random"; - std::uint32_t const x = env.current()->header().parentCloseTime.time_since_epoch().count() + 40; + std::uint32_t const x = + env.current()->header().parentCloseTime.time_since_epoch().count() + 40; // create credentials with expire time 40s auto jv = credentials::create(alice, carol, credType2); @@ -474,7 +519,8 @@ public: "deposit_authorized", depositAuthArgs(alice, becky, "validated", {credIdx2}).toStyledString()); - checkCredentialsResponse(jv[jss::result], alice, becky, false, {credIdx2}, "badCredentials"); + checkCredentialsResponse( + jv[jss::result], alice, becky, false, {credIdx2}, "badCredentials"); } } } diff --git a/src/test/rpc/Feature_test.cpp b/src/test/rpc/Feature_test.cpp index 21596634e3..a802aed482 100644 --- a/src/test/rpc/Feature_test.cpp +++ b/src/test/rpc/Feature_test.cpp @@ -1,7 +1,6 @@ #include -#include - +#include #include #include @@ -41,11 +40,15 @@ class Feature_test : public beast::unit_test::suite if (vote == VoteBehavior::Obsolete) { - BEAST_EXPECT(allAmendments.contains(name) && allAmendments.at(name) == AmendmentSupport::Retired); + BEAST_EXPECT( + allAmendments.contains(name) && + allAmendments.at(name) == AmendmentSupport::Retired); } else { - BEAST_EXPECT(allAmendments.contains(name) && allAmendments.at(name) == AmendmentSupport::Supported); + BEAST_EXPECT( + allAmendments.contains(name) && + allAmendments.at(name) == AmendmentSupport::Supported); } } BEAST_EXPECT(down + obsolete == xrpl::detail::numDownVotedAmendments()); @@ -94,21 +97,25 @@ class Feature_test : public beast::unit_test::suite if (BEAST_EXPECT(registered)) { BEAST_EXPECT(featureToName(*registered) == feature); - BEAST_EXPECT(bitsetIndexToFeature(featureToBitsetIndex(*registered)) == *registered); + BEAST_EXPECT( + bitsetIndexToFeature(featureToBitsetIndex(*registered)) == *registered); } } // Test an arbitrary unknown feature uint256 zero{0}; BEAST_EXPECT(featureToName(zero) == to_string(zero)); - BEAST_EXPECT(featureToName(zero) == "0000000000000000000000000000000000000000000000000000000000000000"); + BEAST_EXPECT( + featureToName(zero) == + "0000000000000000000000000000000000000000000000000000000000000000"); // Test looking up an unknown feature BEAST_EXPECT(!getRegisteredFeature("unknown")); // Test a random sampling of the variables. If any of these get retired // or removed, swap out for any other feature. - BEAST_EXPECT(featureToName(fixRemoveNFTokenAutoTrustLine) == "fixRemoveNFTokenAutoTrustLine"); + BEAST_EXPECT( + featureToName(fixRemoveNFTokenAutoTrustLine) == "fixRemoveNFTokenAutoTrustLine"); BEAST_EXPECT(featureToName(featureBatch) == "Batch"); BEAST_EXPECT(featureToName(featureDID) == "DID"); BEAST_EXPECT(featureToName(fixIncludeKeyletFields) == "fixIncludeKeyletFields"); @@ -135,14 +142,17 @@ class Feature_test : public beast::unit_test::suite // default config - so all should be disabled, and // supported. Some may be vetoed. bool expectVeto = (votes.at(feature[jss::name].asString()) == VoteBehavior::DefaultNo); - bool expectObsolete = (votes.at(feature[jss::name].asString()) == VoteBehavior::Obsolete); + bool expectObsolete = + (votes.at(feature[jss::name].asString()) == VoteBehavior::Obsolete); BEAST_EXPECTS( feature.isMember(jss::enabled) && !feature[jss::enabled].asBool(), feature[jss::name].asString() + " enabled"); BEAST_EXPECTS( feature.isMember(jss::vetoed) && feature[jss::vetoed].isBool() == !expectObsolete && - (!feature[jss::vetoed].isBool() || feature[jss::vetoed].asBool() == expectVeto) && - (feature[jss::vetoed].isBool() || feature[jss::vetoed].asString() == "Obsolete"), + (!feature[jss::vetoed].isBool() || + feature[jss::vetoed].asBool() == expectVeto) && + (feature[jss::vetoed].isBool() || + feature[jss::vetoed].asString() == "Obsolete"), feature[jss::name].asString() + " vetoed"); BEAST_EXPECTS( feature.isMember(jss::supported) && feature[jss::supported].asBool(), @@ -162,9 +172,9 @@ class Feature_test : public beast::unit_test::suite BEAST_EXPECTS(jrr[jss::status] == jss::success, "status"); jrr.removeMember(jss::status); BEAST_EXPECT(jrr.size() == 1); - BEAST_EXPECT( - jrr.isMember("12523DF04B553A0B1AD74F42DDB741DE8DC06A03FC089A0EF197E" - "2A87F1D8107")); + BEAST_EXPECT(jrr.isMember( + "12523DF04B553A0B1AD74F42DDB741DE8DC06A03FC089A0EF197E" + "2A87F1D8107")); auto feature = *(jrr.begin()); BEAST_EXPECTS(feature[jss::name] == "fixAMMOverflowOffer", "name"); @@ -239,7 +249,8 @@ class Feature_test : public beast::unit_test::suite (*it).isMember(jss::enabled) && (*it)[jss::enabled].asBool() == expectEnabled, (*it)[jss::name].asString() + " enabled"); BEAST_EXPECTS( - (*it).isMember(jss::supported) && (*it)[jss::supported].asBool() == expectSupported, + (*it).isMember(jss::supported) && + (*it)[jss::supported].asBool() == expectSupported, (*it)[jss::name].asString() + " supported"); BEAST_EXPECT(!(*it).isMember(jss::vetoed)); BEAST_EXPECT(!(*it).isMember(jss::majority)); @@ -269,7 +280,8 @@ class Feature_test : public beast::unit_test::suite params[jss::vetoed] = true; auto const result = env.rpc("json", "feature", to_string(params))[jss::result]; BEAST_EXPECTS(result[jss::error] == "noPermission", result[jss::error].asString()); - BEAST_EXPECT(result[jss::error_message] == "You don't have permission for this command."); + BEAST_EXPECT( + result[jss::error_message] == "You don't have permission for this command."); } } @@ -300,12 +312,15 @@ class Feature_test : public beast::unit_test::suite (*it).isMember(jss::enabled) && (*it)[jss::enabled].asBool() == expectEnabled, (*it)[jss::name].asString() + " enabled"); if (expectEnabled) - BEAST_EXPECTS(!(*it).isMember(jss::vetoed), (*it)[jss::name].asString() + " vetoed"); + BEAST_EXPECTS( + !(*it).isMember(jss::vetoed), (*it)[jss::name].asString() + " vetoed"); else BEAST_EXPECTS( (*it).isMember(jss::vetoed) && (*it)[jss::vetoed].isBool() == !expectObsolete && - (!(*it)[jss::vetoed].isBool() || (*it)[jss::vetoed].asBool() == expectVeto) && - ((*it)[jss::vetoed].isBool() || (*it)[jss::vetoed].asString() == "Obsolete"), + (!(*it)[jss::vetoed].isBool() || + (*it)[jss::vetoed].asBool() == expectVeto) && + ((*it)[jss::vetoed].isBool() || + (*it)[jss::vetoed].asString() == "Obsolete"), (*it)[jss::name].asString() + " vetoed"); BEAST_EXPECTS( (*it).isMember(jss::supported) && (*it)[jss::supported].asBool() == expectSupported, @@ -331,10 +346,14 @@ class Feature_test : public beast::unit_test::suite { if (!BEAST_EXPECT(feature.isMember(jss::name))) return; - BEAST_EXPECTS(!feature.isMember(jss::majority), feature[jss::name].asString() + " majority"); + BEAST_EXPECTS( + !feature.isMember(jss::majority), feature[jss::name].asString() + " majority"); BEAST_EXPECTS(!feature.isMember(jss::count), feature[jss::name].asString() + " count"); - BEAST_EXPECTS(!feature.isMember(jss::threshold), feature[jss::name].asString() + " threshold"); - BEAST_EXPECTS(!feature.isMember(jss::validations), feature[jss::name].asString() + " validations"); + BEAST_EXPECTS( + !feature.isMember(jss::threshold), feature[jss::name].asString() + " threshold"); + BEAST_EXPECTS( + !feature.isMember(jss::validations), + feature[jss::name].asString() + " validations"); BEAST_EXPECTS(!feature.isMember(jss::vote), feature[jss::name].asString() + " vote"); } @@ -364,18 +383,23 @@ class Feature_test : public beast::unit_test::suite if (!BEAST_EXPECT(feature.isMember(jss::name))) return; bool expectVeto = (votes.at(feature[jss::name].asString()) == VoteBehavior::DefaultNo); - bool expectObsolete = (votes.at(feature[jss::name].asString()) == VoteBehavior::Obsolete); + bool expectObsolete = + (votes.at(feature[jss::name].asString()) == VoteBehavior::Obsolete); BEAST_EXPECTS( (expectVeto || expectObsolete) ^ feature.isMember(jss::majority), feature[jss::name].asString() + " majority"); BEAST_EXPECTS( feature.isMember(jss::vetoed) && feature[jss::vetoed].isBool() == !expectObsolete && - (!feature[jss::vetoed].isBool() || feature[jss::vetoed].asBool() == expectVeto) && - (feature[jss::vetoed].isBool() || feature[jss::vetoed].asString() == "Obsolete"), + (!feature[jss::vetoed].isBool() || + feature[jss::vetoed].asBool() == expectVeto) && + (feature[jss::vetoed].isBool() || + feature[jss::vetoed].asString() == "Obsolete"), feature[jss::name].asString() + " vetoed"); BEAST_EXPECTS(feature.isMember(jss::count), feature[jss::name].asString() + " count"); - BEAST_EXPECTS(feature.isMember(jss::threshold), feature[jss::name].asString() + " threshold"); - BEAST_EXPECTS(feature.isMember(jss::validations), feature[jss::name].asString() + " validations"); + BEAST_EXPECTS( + feature.isMember(jss::threshold), feature[jss::name].asString() + " threshold"); + BEAST_EXPECTS( + feature.isMember(jss::validations), feature[jss::name].asString() + " validations"); BEAST_EXPECT(feature[jss::count] == ((expectVeto || expectObsolete) ? 0 : 1)); BEAST_EXPECT(feature[jss::threshold] == 1); BEAST_EXPECT(feature[jss::validations] == 1); @@ -439,8 +463,8 @@ class Feature_test : public beast::unit_test::suite Env env{*this}; auto const& supportedAmendments = detail::supportedAmendments(); - auto obsoleteFeature = - std::find_if(std::begin(supportedAmendments), std::end(supportedAmendments), [](auto const& pair) { + auto obsoleteFeature = std::find_if( + std::begin(supportedAmendments), std::end(supportedAmendments), [](auto const& pair) { return pair.second == VoteBehavior::Obsolete; }); @@ -460,7 +484,9 @@ class Feature_test : public beast::unit_test::suite return; auto feature = *(jrr.begin()); BEAST_EXPECTS(feature[jss::name] == featureName, "name"); - BEAST_EXPECTS(feature[jss::vetoed].isString() && feature[jss::vetoed].asString() == "Obsolete", "vetoed"); + BEAST_EXPECTS( + feature[jss::vetoed].isString() && feature[jss::vetoed].asString() == "Obsolete", + "vetoed"); jrr = env.rpc("feature", featureName, "reject")[jss::result]; if (!BEAST_EXPECTS(jrr[jss::status] == jss::success, "status")) @@ -470,7 +496,9 @@ class Feature_test : public beast::unit_test::suite return; feature = *(jrr.begin()); BEAST_EXPECTS(feature[jss::name] == featureName, "name"); - BEAST_EXPECTS(feature[jss::vetoed].isString() && feature[jss::vetoed].asString() == "Obsolete", "vetoed"); + BEAST_EXPECTS( + feature[jss::vetoed].isString() && feature[jss::vetoed].asString() == "Obsolete", + "vetoed"); jrr = env.rpc("feature", featureName, "accept")[jss::result]; if (!BEAST_EXPECTS(jrr[jss::status] == jss::success, "status")) @@ -480,7 +508,9 @@ class Feature_test : public beast::unit_test::suite return; feature = *(jrr.begin()); BEAST_EXPECTS(feature[jss::name] == featureName, "name"); - BEAST_EXPECTS(feature[jss::vetoed].isString() && feature[jss::vetoed].asString() == "Obsolete", "vetoed"); + BEAST_EXPECTS( + feature[jss::vetoed].isString() && feature[jss::vetoed].asString() == "Obsolete", + "vetoed"); // anything other than accept or reject is an error jrr = env.rpc("feature", featureName, "maybe"); diff --git a/src/test/rpc/GRPCTestClientBase.h b/src/test/rpc/GRPCTestClientBase.h index 3c39cd1747..495dcc22bc 100644 --- a/src/test/rpc/GRPCTestClientBase.h +++ b/src/test/rpc/GRPCTestClientBase.h @@ -12,9 +12,14 @@ namespace test { struct GRPCTestClientBase { explicit GRPCTestClientBase(std::string const& port) - : stub_(org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub(grpc::CreateChannel( - beast::IP::Endpoint(boost::asio::ip::make_address(getEnvLocalhostAddr()), std::stoi(port)).to_string(), - grpc::InsecureChannelCredentials()))) + : stub_( + org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub( + grpc::CreateChannel( + beast::IP::Endpoint( + boost::asio::ip::make_address(getEnvLocalhostAddr()), + std::stoi(port)) + .to_string(), + grpc::InsecureChannelCredentials()))) { } diff --git a/src/test/rpc/GetAggregatePrice_test.cpp b/src/test/rpc/GetAggregatePrice_test.cpp index e6cfb3a229..b900afa178 100644 --- a/src/test/rpc/GetAggregatePrice_test.cpp +++ b/src/test/rpc/GetAggregatePrice_test.cpp @@ -98,7 +98,10 @@ public: // oracles have wrong asset pair env.fund(XRP(1'000), owner); Oracle oracle( - env, {.owner = owner, .series = {{"XRP", "EUR", 740, 1}}, .fee = static_cast(baseFee.drops())}); + env, + {.owner = owner, + .series = {{"XRP", "EUR", 740, 1}}, + .fee = static_cast(baseFee.drops())}); ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{owner, oracle.documentID()}}}); BEAST_EXPECT(ret[jss::error].asString() == "objectNotFound"); @@ -106,7 +109,8 @@ public: std::vector invalidTrim = {NoneTag, 0, 26, -1, 1.2, "", "none", "1.2"}; for (auto const& v : invalidTrim) { - ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{owner, oracle.documentID()}}}, v); + ret = + Oracle::aggregatePrice(env, "XRP", "USD", {{{owner, oracle.documentID()}}}, v); BEAST_EXPECT(ret[jss::error].asString() == "invalidParams"); } @@ -114,7 +118,8 @@ public: std::vector invalidTime = {NoneTag, -1, 1.2, "", "none", "1.2"}; for (auto const& v : invalidTime) { - ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{owner, oracle.documentID()}}}, std::nullopt, v); + ret = Oracle::aggregatePrice( + env, "XRP", "USD", {{{owner, oracle.documentID()}}}, std::nullopt, v); BEAST_EXPECT(ret[jss::error].asString() == "invalidParams"); } } @@ -226,7 +231,11 @@ public: for (int i = 0; i < 3; ++i) { Oracle oracle( - env, {.owner = oracles[i].first, .documentID = asUInt(*oracles[i].second), .fee = baseFee}, false); + env, + {.owner = oracles[i].first, + .documentID = asUInt(*oracles[i].second), + .fee = baseFee}, + false); // push XRP/USD by more than three ledgers, so this price // oracle is not included in the dataset oracle.set(UpdateArg{.series = {{"XRP", "EUR", 740, 1}}, .fee = baseFee}); @@ -236,7 +245,11 @@ public: for (int i = 3; i < 6; ++i) { Oracle oracle( - env, {.owner = oracles[i].first, .documentID = asUInt(*oracles[i].second), .fee = baseFee}, false); + env, + {.owner = oracles[i].first, + .documentID = asUInt(*oracles[i].second), + .fee = baseFee}, + false); // push XRP/USD by two ledgers, so this price // is included in the dataset oracle.set(UpdateArg{.series = {{"XRP", "EUR", 740, 1}}, .fee = baseFee}); @@ -271,7 +284,11 @@ public: for (int i = 0; i < oracles.size(); ++i) { Oracle oracle( - env, {.owner = oracles[i].first, .documentID = asUInt(*oracles[i].second), .fee = baseFee}, false); + env, + {.owner = oracles[i].first, + .documentID = asUInt(*oracles[i].second), + .fee = baseFee}, + false); // push XRP/USD by two ledgers, so this price // is included in the dataset oracle.set(UpdateArg{.series = {{"XRP", "USD", 740, 1}}, .fee = baseFee}); diff --git a/src/test/rpc/JSONRPC_test.cpp b/src/test/rpc/JSONRPC_test.cpp index f0329748e1..87c7d3dcd0 100644 --- a/src/test/rpc/JSONRPC_test.cpp +++ b/src/test/rpc/JSONRPC_test.cpp @@ -1,7 +1,6 @@ #include #include -#include #include #include #include @@ -10,6 +9,7 @@ #include #include #include +#include namespace xrpl { @@ -850,7 +850,10 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"Secret does not match account.", "Secret does not match account.", "", "Missing field 'tx_json.Signers'."}}}, + {{"Secret does not match account.", + "Secret does not match account.", + "", + "Missing field 'tx_json.Signers'."}}}, {"Minimal offline sign_for.", __LINE__, @@ -909,7 +912,10 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"Disallowed seed.", "Disallowed seed.", "Disallowed seed.", "Missing field 'tx_json.Signers'."}}}, + {{"Disallowed seed.", + "Disallowed seed.", + "Disallowed seed.", + "Missing field 'tx_json.Signers'."}}}, {"Missing 'Account' in sign_for.", __LINE__, @@ -1155,7 +1161,10 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType" : "Payment" } })", - {{"Already multisigned.", "Already multisigned.", "Invalid signature.", "Invalid signature."}}}, + {{"Already multisigned.", + "Already multisigned.", + "Invalid signature.", + "Invalid signature."}}}, {"Non-empty 'SigningPubKey' in sign_for.", __LINE__, @@ -1336,7 +1345,10 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"Missing field 'secret'.", "Missing field 'secret'.", "Missing field 'account'.", "Invalid signature."}}}, + {{"Missing field 'secret'.", + "Missing field 'secret'.", + "Missing field 'account'.", + "Invalid signature."}}}, {"Missing tx_json in submit_multisigned.", __LINE__, @@ -1352,7 +1364,10 @@ static constexpr TxnTestData txnTestArray[] = { } ] })", - {{"Missing field 'secret'.", "Missing field 'secret'.", "Missing field 'account'.", "Missing field 'tx_json'."}}}, + {{"Missing field 'secret'.", + "Missing field 'secret'.", + "Missing field 'account'.", + "Missing field 'tx_json'."}}}, {"Missing sequence in submit_multisigned.", __LINE__, @@ -1541,7 +1556,10 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"Missing field 'secret'.", "Missing field 'secret'.", "Missing field 'account'.", "Source account not found."}}}, + {{"Missing field 'secret'.", + "Missing field 'secret'.", + "Missing field 'account'.", + "Source account not found."}}}, {"Missing Fee in submit_multisigned.", __LINE__, @@ -2101,8 +2119,14 @@ public: jt.jv.removeMember(jss::Fee); jt.jv.removeMember(jss::TxnSignature); req[jss::tx_json] = jt.jv; - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrack, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(result.size() == 0); BEAST_EXPECT( req[jss::tx_json].isMember(jss::Fee) && @@ -2165,8 +2189,14 @@ public: alice)); req[jss::tx_json] = jt.jv; - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrack, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(result.size() == 0); BEAST_EXPECT( req[jss::tx_json].isMember(jss::Fee) && @@ -2186,11 +2216,18 @@ public: { Json::Value req; Json::Reader().parse("{ \"fee_mult_max\" : 1, \"tx_json\" : { } } ", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrack, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT(req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == baseFee); + BEAST_EXPECT( + req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == baseFee); } { @@ -2199,18 +2236,31 @@ public: "{ \"fee_mult_max\" : 3, \"fee_div_max\" : 2, " "\"tx_json\" : { } } ", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrack, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT(req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == baseFee); + BEAST_EXPECT( + req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == baseFee); } { Json::Value req; Json::Reader().parse("{ \"fee_mult_max\" : 0, \"tx_json\" : { } } ", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrack, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(RPC::contains_error(result)); BEAST_EXPECT(!req[jss::tx_json].isMember(jss::Fee)); @@ -2224,8 +2274,14 @@ public: "{ \"fee_mult_max\" : 3, \"fee_div_max\" : 6, " "\"tx_json\" : { } } ", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrack, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(RPC::contains_error(result)); BEAST_EXPECT(!req[jss::tx_json].isMember(jss::Fee)); @@ -2237,8 +2293,14 @@ public: "{ \"fee_mult_max\" : 0, \"fee_div_max\" : 2, " "\"tx_json\" : { } } ", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrack, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(RPC::contains_error(result)); BEAST_EXPECT(!req[jss::tx_json].isMember(jss::Fee)); @@ -2250,8 +2312,14 @@ public: "{ \"fee_mult_max\" : 10, \"fee_div_max\" : 0, " "\"tx_json\" : { } } ", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrack, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(RPC::contains_error(result)); BEAST_EXPECT(!req[jss::tx_json].isMember(jss::Fee)); @@ -2262,8 +2330,14 @@ public: Json::Value req; test::jtx::Account const alice("alice"); req[jss::tx_json] = test::jtx::acctdelete(env.master.human(), alice.human()); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrack, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(result.size() == 0); BEAST_EXPECT( @@ -2293,8 +2367,14 @@ public: "tx_json" : { } })", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrackOuter, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(!RPC::contains_error(result)); BEAST_EXPECT(req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == 10); @@ -2309,8 +2389,14 @@ public: "tx_json" : { } })", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrackOuter, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(!RPC::contains_error(result)); BEAST_EXPECT(req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == 10); @@ -2331,11 +2417,18 @@ public: "tx_json" : { } })", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrackOuter, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT(req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == 8889); + BEAST_EXPECT( + req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == 8889); } { @@ -2347,8 +2440,14 @@ public: "tx_json" : { } })", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrackOuter, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(RPC::contains_error(result)); BEAST_EXPECT(!req[jss::tx_json].isMember(jss::Fee)); @@ -2364,8 +2463,14 @@ public: "tx_json" : { } })", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrackOuter, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(RPC::contains_error(result)); BEAST_EXPECT(!req[jss::tx_json].isMember(jss::Fee)); @@ -2381,11 +2486,18 @@ public: "tx_json" : { } })", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrackOuter, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT(req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == 8889); + BEAST_EXPECT( + req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == 8889); } { @@ -2397,8 +2509,14 @@ public: "tx_json" : { } })", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrackOuter, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(RPC::contains_error(result)); } @@ -2412,8 +2530,14 @@ public: "tx_json" : { } })", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrackOuter, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(RPC::contains_error(result)); } @@ -2428,8 +2552,14 @@ public: "tx_json" : { } })", req); - Json::Value result = - checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); + Json::Value result = checkFee( + req, + Role::ADMIN, + true, + env.app().config(), + feeTrackOuter, + env.app().getTxQ(), + env.app()); BEAST_EXPECT(RPC::contains_error(result)); } @@ -2445,7 +2575,8 @@ public: auto result = rpcResult[jss::result]; BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT(result[jss::tx_json].isMember(jss::Fee) && result[jss::tx_json][jss::Fee] == "10"); + BEAST_EXPECT( + result[jss::tx_json].isMember(jss::Fee) && result[jss::tx_json][jss::Fee] == "10"); BEAST_EXPECT( result[jss::tx_json].isMember(jss::Sequence) && result[jss::tx_json][jss::Sequence].isConvertibleTo(Json::ValueType::uintValue)); @@ -2470,7 +2601,9 @@ public: auto result = rpcResult[jss::result]; BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT(result[jss::tx_json].isMember(jss::Fee) && result[jss::tx_json][jss::Fee] == "7813"); + BEAST_EXPECT( + result[jss::tx_json].isMember(jss::Fee) && + result[jss::tx_json][jss::Fee] == "7813"); BEAST_EXPECT( result[jss::tx_json].isMember(jss::Sequence) && result[jss::tx_json][jss::Sequence].isConvertibleTo(Json::ValueType::uintValue)); @@ -2495,7 +2628,8 @@ public: auto result = rpcResult[jss::result]; BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT(result[jss::tx_json].isMember(jss::Fee) && result[jss::tx_json][jss::Fee] == "47"); + BEAST_EXPECT( + result[jss::tx_json].isMember(jss::Fee) && result[jss::tx_json][jss::Fee] == "47"); BEAST_EXPECT( result[jss::tx_json].isMember(jss::Sequence) && result[jss::tx_json][jss::Sequence].isConvertibleTo(Json::ValueType::uintValue)); @@ -2525,7 +2659,9 @@ public: auto result = rpcResult[jss::result]; BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT(result[jss::tx_json].isMember(jss::Fee) && result[jss::tx_json][jss::Fee] == "6806"); + BEAST_EXPECT( + result[jss::tx_json].isMember(jss::Fee) && + result[jss::tx_json][jss::Fee] == "6806"); BEAST_EXPECT( result[jss::tx_json].isMember(jss::Sequence) && result[jss::tx_json][jss::Sequence].isConvertibleTo(Json::ValueType::uintValue)); @@ -2552,7 +2688,9 @@ public: auto result = rpcResult[jss::result]; BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT(result[jss::tx_json].isMember(jss::NetworkID) && result[jss::tx_json][jss::NetworkID] == 1025); + BEAST_EXPECT( + result[jss::tx_json].isMember(jss::NetworkID) && + result[jss::tx_json][jss::NetworkID] == 1025); } } @@ -2632,7 +2770,8 @@ public: if (RPC::contains_error(req)) Throw("Internal JSONRPC_test error. Bad test JSON."); - static Role const testedRoles[] = {Role::GUEST, Role::USER, Role::ADMIN, Role::FORBID}; + static Role const testedRoles[] = { + Role::GUEST, Role::USER, Role::ADMIN, Role::FORBID}; for (Role testRole : testedRoles) { @@ -2647,7 +2786,8 @@ public: { auto const submitFn = get<1>(testFunc); assert(submitFn != nullptr); - result = submitFn(req, 1, NetworkOPs::FailHard::yes, testRole, 1s, env.app(), processTxn); + result = submitFn( + req, 1, NetworkOPs::FailHard::yes, testRole, 1s, env.app(), processTxn); } std::string errStr; @@ -2661,8 +2801,8 @@ public: else { std::ostringstream description; - description << txnTest.description << " Called " << get<2>(testFunc) << "(). Got \'" << errStr - << "\'"; + description << txnTest.description << " Called " << get<2>(testFunc) + << "(). Got \'" << errStr << "\'"; fail(description.str(), __FILE__, txnTest.line); } } diff --git a/src/test/rpc/KeyGeneration_test.cpp b/src/test/rpc/KeyGeneration_test.cpp index 987985070d..3bffb9dc83 100644 --- a/src/test/rpc/KeyGeneration_test.cpp +++ b/src/test/rpc/KeyGeneration_test.cpp @@ -93,7 +93,9 @@ public: BEAST_EXPECT(result.isMember(jss::public_key_hex)); BEAST_EXPECT(result.isMember(jss::key_type)); - expectEquals(result[jss::key_type], params.isMember(jss::key_type) ? params[jss::key_type] : "secp256k1"); + expectEquals( + result[jss::key_type], + params.isMember(jss::key_type) ? params[jss::key_type] : "secp256k1"); BEAST_EXPECT(!result.isMember(jss::warning)); std::string seed = result[jss::master_seed].asString(); @@ -115,7 +117,9 @@ public: 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::key_type], params.isMember(jss::key_type) ? params[jss::key_type] : "secp256k1"); + expectEquals( + result[jss::key_type], + params.isMember(jss::key_type) ? params[jss::key_type] : "secp256k1"); return result; } @@ -148,7 +152,10 @@ public: } void - testLegacyPassphrase(char const* value, std::optional const& keyType, key_strings const& strings) + testLegacyPassphrase( + char const* value, + std::optional const& keyType, + key_strings const& strings) { Json::Value params; if (keyType) @@ -423,7 +430,9 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT(error[jss::error_message] == "The secret field is not allowed if key_type is used."); + BEAST_EXPECT( + error[jss::error_message] == + "The secret field is not allowed if key_type is used."); } // Specify unknown or bad "key_type" @@ -703,7 +712,8 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); - BEAST_EXPECT(error[jss::error_message] == "Specified seed is for an Ed25519 wallet."); + BEAST_EXPECT( + error[jss::error_message] == "Specified seed is for an Ed25519 wallet."); } { @@ -733,7 +743,8 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); - BEAST_EXPECT(error[jss::error_message] == "Specified seed is for an Ed25519 wallet."); + BEAST_EXPECT( + error[jss::error_message] == "Specified seed is for an Ed25519 wallet."); } }; diff --git a/src/test/rpc/LedgerClosed_test.cpp b/src/test/rpc/LedgerClosed_test.cpp index d6b67ce406..2bc5c2b0c9 100644 --- a/src/test/rpc/LedgerClosed_test.cpp +++ b/src/test/rpc/LedgerClosed_test.cpp @@ -21,7 +21,9 @@ public: env.fund(XRP(10000), alice); auto lc_result = env.rpc("ledger_closed")[jss::result]; - BEAST_EXPECT(lc_result[jss::ledger_hash] == "CCC3B3E88CCAC17F1BE6B4A648A55999411F19E3FE55EB721960EB0DF28EDDA5"); + BEAST_EXPECT( + lc_result[jss::ledger_hash] == + "CCC3B3E88CCAC17F1BE6B4A648A55999411F19E3FE55EB721960EB0DF28EDDA5"); BEAST_EXPECT(lc_result[jss::ledger_index] == 2); env.close(); @@ -34,7 +36,9 @@ public: BEAST_EXPECT((*ar_alice)[sfBalance] == XRP(10000)); lc_result = env.rpc("ledger_closed")[jss::result]; - BEAST_EXPECT(lc_result[jss::ledger_hash] == "0F1A9E0C109ADEF6DA2BDE19217C12BBEC57174CBDBD212B0EBDC1CEDB853185"); + BEAST_EXPECT( + lc_result[jss::ledger_hash] == + "0F1A9E0C109ADEF6DA2BDE19217C12BBEC57174CBDBD212B0EBDC1CEDB853185"); BEAST_EXPECT(lc_result[jss::ledger_index] == 3); } diff --git a/src/test/rpc/LedgerData_test.cpp b/src/test/rpc/LedgerData_test.cpp index 0148185276..e139ba24b4 100644 --- a/src/test/rpc/LedgerData_test.cpp +++ b/src/test/rpc/LedgerData_test.cpp @@ -12,7 +12,8 @@ public: static bool checkMarker(Json::Value const& val) { - return val.isMember(jss::marker) && val[jss::marker].isString() && val[jss::marker].asString().size() > 0; + return val.isMember(jss::marker) && val[jss::marker].isString() && + val[jss::marker].asString().size() > 0; } void @@ -43,7 +44,9 @@ public: jvParams[jss::binary] = false; { auto const jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; - BEAST_EXPECT(jrr[jss::ledger_current_index].isIntegral() && jrr[jss::ledger_current_index].asInt() > 0); + BEAST_EXPECT( + jrr[jss::ledger_current_index].isIntegral() && + jrr[jss::ledger_current_index].asInt() > 0); BEAST_EXPECT(checkMarker(jrr)); BEAST_EXPECT(checkArraySize(jrr[jss::state], max_limit)); } @@ -53,7 +56,8 @@ public: { jvParams[jss::limit] = max_limit + delta; auto const jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; - BEAST_EXPECT(checkArraySize(jrr[jss::state], (delta > 0 && !asAdmin) ? max_limit : max_limit + delta)); + BEAST_EXPECT(checkArraySize( + jrr[jss::state], (delta > 0 && !asAdmin) ? max_limit : max_limit + delta)); } } @@ -80,7 +84,9 @@ public: jvParams[jss::ledger_index] = "current"; jvParams[jss::binary] = true; auto const jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; - BEAST_EXPECT(jrr[jss::ledger_current_index].isIntegral() && jrr[jss::ledger_current_index].asInt() > 0); + BEAST_EXPECT( + jrr[jss::ledger_current_index].isIntegral() && + jrr[jss::ledger_current_index].asInt() > 0); BEAST_EXPECT(!jrr.isMember(jss::marker)); BEAST_EXPECT(checkArraySize(jrr[jss::state], num_accounts + 4)); } @@ -192,7 +198,8 @@ public: jvParams[jss::ledger_index] = "closed"; auto jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; if (BEAST_EXPECT(jrr.isMember(jss::ledger))) - BEAST_EXPECT(jrr[jss::ledger][jss::ledger_hash] == to_string(env.closed()->header().hash)); + BEAST_EXPECT( + jrr[jss::ledger][jss::ledger_hash] == to_string(env.closed()->header().hash)); } { // Closed ledger with binary form @@ -230,7 +237,8 @@ public: // Make sure fixInnerObjTemplate2 doesn't break amendments. for (FeatureBitset const& features : - {testable_amendments() - fixInnerObjTemplate2, testable_amendments() | fixInnerObjTemplate2}) + {testable_amendments() - fixInnerObjTemplate2, + testable_amendments() | fixInnerObjTemplate2}) { using namespace std::chrono; Env env{*this, envconfig(validator, ""), features}; @@ -291,7 +299,8 @@ public: jv[jss::Account] = Account{"bob5"}.human(); jv[jss::Destination] = Account{"bob6"}.human(); jv[jss::Amount] = XRP(50).value().getJson(JsonOptions::none); - jv[sfFinishAfter.fieldName] = NetClock::time_point{env.now() + 10s}.time_since_epoch().count(); + jv[sfFinishAfter.fieldName] = + NetClock::time_point{env.now() + 10s}.time_since_epoch().count(); env(jv); } @@ -303,7 +312,8 @@ public: jv[jss::Amount] = XRP(100).value().getJson(JsonOptions::none); jv[jss::SettleDelay] = NetClock::duration{10s}.count(); jv[sfPublicKey.fieldName] = strHex(Account{"bob6"}.pk().slice()); - jv[sfCancelAfter.fieldName] = NetClock::time_point{env.now() + 300s}.time_since_epoch().count(); + jv[sfCancelAfter.fieldName] = + NetClock::time_point{env.now() + 300s}.time_since_epoch().count(); env(jv); } diff --git a/src/test/rpc/LedgerEntry_test.cpp b/src/test/rpc/LedgerEntry_test.cpp index 5d12e7bb83..9d274b3549 100644 --- a/src/test/rpc/LedgerEntry_test.cpp +++ b/src/test/rpc/LedgerEntry_test.cpp @@ -5,8 +5,6 @@ #include #include -#include - #include #include #include @@ -15,6 +13,7 @@ #include #include + namespace xrpl { namespace test { @@ -55,7 +54,8 @@ std::vector> mappings{ FieldType getFieldType(Json::StaticString fieldName) { - auto it = std::ranges::find_if(mappings, [&fieldName](auto const& pair) { return pair.first == fieldName; }); + auto it = std::ranges::find_if( + mappings, [&fieldName](auto const& pair) { return pair.first == fieldName; }); if (it != mappings.end()) { return it->second; @@ -93,7 +93,8 @@ getTypeName(FieldType typeID) case FieldType::UInt64Field: return "number"; default: - Throw("unknown type " + std::to_string(static_cast(typeID))); + Throw( + "unknown type " + std::to_string(static_cast(typeID))); } } @@ -117,14 +118,15 @@ class LedgerEntry_test : public beast::unit_test::suite { BEAST_EXPECTS( jv[jss::error_message] == Json::nullValue || jv[jss::error_message] == "", - "Expected no error message, received \"" + jv[jss::error_message].asString() + "\", at line " + - std::to_string(location.line()) + ", " + jv.toStyledString()); + "Expected no error message, received \"" + jv[jss::error_message].asString() + + "\", at line " + std::to_string(location.line()) + ", " + jv.toStyledString()); } else if (BEAST_EXPECT(jv.isMember(jss::error_message))) BEAST_EXPECTS( jv[jss::error_message] == msg, - "Expected error message \"" + msg + "\", received \"" + jv[jss::error_message].asString() + - "\", at line " + std::to_string(location.line()) + ", " + jv.toStyledString()); + "Expected error message \"" + msg + "\", received \"" + + jv[jss::error_message].asString() + "\", at line " + + std::to_string(location.line()) + ", " + jv.toStyledString()); } std::vector @@ -216,7 +218,8 @@ class LedgerEntry_test : public beast::unit_test::suite case FieldType::UInt64Field: return badUInt64Values; default: - Throw("unknown type " + std::to_string(static_cast(fieldType))); + Throw( + "unknown type " + std::to_string(static_cast(fieldType))); } } @@ -261,7 +264,8 @@ class LedgerEntry_test : public beast::unit_test::suite case FieldType::UInt64Field: return 1; default: - Throw("unknown type " + std::to_string(static_cast(typeID))); + Throw( + "unknown type " + std::to_string(static_cast(typeID))); } } @@ -279,18 +283,20 @@ class LedgerEntry_test : public beast::unit_test::suite if (required) { correctRequest.removeMember(fieldName); - Json::Value const jrr = - env.rpc(apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; + Json::Value const jrr = env.rpc( + apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; if (apiVersion < 2u) checkErrorValue(jrr, "unknownOption", "", location); else - checkErrorValue(jrr, "invalidParams", "No ledger_entry params provided.", location); + checkErrorValue( + jrr, "invalidParams", "No ledger_entry params provided.", location); } auto tryField = [&](Json::Value fieldValue) -> void { correctRequest[fieldName] = fieldValue; - Json::Value const jrr = - env.rpc(apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; - auto const expectedErrMsg = RPC::expected_field_message(fieldName, getTypeName(typeID)); + Json::Value const jrr = env.rpc( + apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; + auto const expectedErrMsg = + RPC::expected_field_message(fieldName, getTypeName(typeID)); checkErrorValue(jrr, expectedError, expectedErrMsg, location); }; @@ -321,22 +327,33 @@ class LedgerEntry_test : public beast::unit_test::suite if (required) { correctRequest[parentFieldName].removeMember(fieldName); - Json::Value const jrr = - env.rpc(apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; - checkErrorValue(jrr, "malformedRequest", RPC::missing_field_message(fieldName.c_str()), location); + Json::Value const jrr = env.rpc( + apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; + checkErrorValue( + jrr, + "malformedRequest", + RPC::missing_field_message(fieldName.c_str()), + location); correctRequest[parentFieldName][fieldName] = Json::nullValue; - Json::Value const jrr2 = - env.rpc(apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; - checkErrorValue(jrr2, "malformedRequest", RPC::missing_field_message(fieldName.c_str()), location); + Json::Value const jrr2 = env.rpc( + apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; + checkErrorValue( + jrr2, + "malformedRequest", + RPC::missing_field_message(fieldName.c_str()), + location); } auto tryField = [&](Json::Value fieldValue) -> void { correctRequest[parentFieldName][fieldName] = fieldValue; - Json::Value const jrr = - env.rpc(apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; + Json::Value const jrr = env.rpc( + apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; checkErrorValue( - jrr, expectedError, RPC::expected_field_message(fieldName, getTypeName(typeID)), location); + jrr, + expectedError, + RPC::expected_field_message(fieldName, getTypeName(typeID)), + location); }; auto const& badValues = getBadValues(typeID); @@ -354,7 +371,14 @@ class LedgerEntry_test : public beast::unit_test::suite Json::StaticString const& parentField, std::source_location const location = std::source_location::current()) { - testMalformedField(env, Json::Value{}, parentField, FieldType::HashField, "malformedRequest", true, location); + testMalformedField( + env, + Json::Value{}, + parentField, + FieldType::HashField, + "malformedRequest", + true, + location); } struct Subfield @@ -372,7 +396,13 @@ class LedgerEntry_test : public beast::unit_test::suite std::source_location const location = std::source_location::current()) { testMalformedField( - env, Json::Value{}, parentField, FieldType::HashOrObjectField, "malformedRequest", true, location); + env, + Json::Value{}, + parentField, + FieldType::HashOrObjectField, + "malformedRequest", + true, + location); Json::Value correctOutput; correctOutput[parentField] = Json::objectValue; @@ -424,9 +454,10 @@ class LedgerEntry_test : public beast::unit_test::suite forAllApiVersions([&, this](unsigned apiVersion) { auto tryField = [&](Json::Value fieldValue) -> void { jvParams[jss::ledger_hash] = fieldValue; - Json::Value const jrr = - env.rpc(apiVersion, "json", "ledger_entry", to_string(jvParams))[jss::result]; - checkErrorValue(jrr, "invalidParams", "Invalid field 'ledger_hash', not hex string."); + Json::Value const jrr = env.rpc( + apiVersion, "json", "ledger_entry", to_string(jvParams))[jss::result]; + checkErrorValue( + jrr, "invalidParams", "Invalid field 'ledger_hash', not hex string."); }; auto const& badValues = getBadValues(typeId); @@ -456,7 +487,8 @@ class LedgerEntry_test : public beast::unit_test::suite "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAA"; jvParams[jss::api_version] = apiVersion; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; if (apiVersion < 2u) checkErrorValue(jrr, "unknownOption", ""); @@ -494,7 +526,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::account_root] = alice.human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); BEAST_EXPECT(jrr[jss::node][jss::Account] == alice.human()); BEAST_EXPECT(jrr[jss::node][sfBalance.jsonName] == "10000000000"); @@ -511,7 +544,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::account_root] = alice.human(); jvParams[jss::binary] = 1; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node_binary)); BEAST_EXPECT(jrr[jss::node_binary] == aliceAcctRootBinary); } @@ -519,7 +553,8 @@ class LedgerEntry_test : public beast::unit_test::suite // Request alice's account root using the index. Json::Value jvParams; jvParams[jss::index] = accountRootIndex; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(!jrr.isMember(jss::node_binary)); BEAST_EXPECT(jrr.isMember(jss::node)); BEAST_EXPECT(jrr[jss::node][jss::Account] == alice.human()); @@ -530,7 +565,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::index] = accountRootIndex; jvParams[jss::binary] = 0; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); BEAST_EXPECT(jrr[jss::node][jss::Account] == alice.human()); BEAST_EXPECT(jrr[jss::node][sfBalance.jsonName] == "10000000000"); @@ -540,7 +576,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::account] = alice.human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); BEAST_EXPECT(jrr[jss::node][jss::Account] == alice.human()); BEAST_EXPECT(jrr[jss::node][sfBalance.jsonName] == "10000000000"); @@ -549,14 +586,16 @@ class LedgerEntry_test : public beast::unit_test::suite { // Check malformed cases Json::Value jvParams; - testMalformedField(env, jvParams, jss::account_root, FieldType::AccountField, "malformedAddress"); + testMalformedField( + env, jvParams, jss::account_root, FieldType::AccountField, "malformedAddress"); } { // Request an account that is not in the ledger. Json::Value jvParams; jvParams[jss::account_root] = Account("bob").human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } } @@ -581,17 +620,21 @@ class LedgerEntry_test : public beast::unit_test::suite // Create Amendments vector (enabled amendments) std::vector enabledAmendments; enabledAmendments.push_back( - uint256::fromVoid("42426C4D4F1009EE67080A9B7965B44656D7" - "714D104A72F9B4369F97ABF044EE")); + uint256::fromVoid( + "42426C4D4F1009EE67080A9B7965B44656D7" + "714D104A72F9B4369F97ABF044EE")); enabledAmendments.push_back( - uint256::fromVoid("4C97EBA926031A7CF7D7B36FDE3ED66DDA54" - "21192D63DE53FFB46E43B9DC8373")); + uint256::fromVoid( + "4C97EBA926031A7CF7D7B36FDE3ED66DDA54" + "21192D63DE53FFB46E43B9DC8373")); enabledAmendments.push_back( - uint256::fromVoid("03BDC0099C4E14163ADA272C1B6F6FABB448" - "CC3E51F522F978041E4B57D9158C")); + uint256::fromVoid( + "03BDC0099C4E14163ADA272C1B6F6FABB448" + "CC3E51F522F978041E4B57D9158C")); enabledAmendments.push_back( - uint256::fromVoid("35291ADD2D79EB6991343BDA0912269C817D" - "0F094B02226C1C14AD2858962ED4")); + uint256::fromVoid( + "35291ADD2D79EB6991343BDA0912269C817D" + "0F094B02226C1C14AD2858962ED4")); sle->setFieldV256(sfAmendments, STVector256(enabledAmendments)); // Create Majorities array @@ -600,16 +643,18 @@ class LedgerEntry_test : public beast::unit_test::suite auto majority1 = STObject::makeInnerObject(sfMajority); majority1.setFieldH256( sfAmendment, - uint256::fromVoid("7BB62DC13EC72B775091E9C71BF8CF97E122" - "647693B50C5E87A80DFD6FCFAC50")); + uint256::fromVoid( + "7BB62DC13EC72B775091E9C71BF8CF97E122" + "647693B50C5E87A80DFD6FCFAC50")); majority1.setFieldU32(sfCloseTime, 779561310); majorities.push_back(std::move(majority1)); auto majority2 = STObject::makeInnerObject(sfMajority); majority2.setFieldH256( sfAmendment, - uint256::fromVoid("755C971C29971C9F20C6F080F2ED96F87884" - "E40AD19554A5EBECDCEC8A1F77FE")); + uint256::fromVoid( + "755C971C29971C9F20C6F080F2ED96F87884" + "E40AD19554A5EBECDCEC8A1F77FE")); majority2.setFieldU32(sfCloseTime, 779561310); majorities.push_back(std::move(majority2)); @@ -623,12 +668,14 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::amendments] = to_string(keylet.key); - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Amendments); } // negative tests - testMalformedField(env, Json::Value{}, jss::amendments, FieldType::FixedHashField, "malformedRequest"); + testMalformedField( + env, Json::Value{}, jss::amendments, FieldType::FixedHashField, "malformedRequest"); } void @@ -650,7 +697,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::amm] = to_string(amm.ammID()); auto const result = env.rpc("json", "ledger_entry", to_string(jvParams)); BEAST_EXPECT( - result.isObject() && result.isMember(jss::result) && !result[jss::result].isMember(jss::error) && + result.isObject() && result.isMember(jss::result) && + !result[jss::result].isMember(jss::error) && result[jss::result].isMember(jss::node) && result[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && result[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::AMM); @@ -673,7 +721,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::amm] = ammParams; auto const result = env.rpc("json", "ledger_entry", to_string(jvParams)); BEAST_EXPECT( - result.isObject() && result.isMember(jss::result) && !result[jss::result].isMember(jss::error) && + result.isObject() && result.isMember(jss::result) && + !result[jss::result].isMember(jss::error) && result[jss::result].isMember(jss::node) && result[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && result[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::AMM); @@ -710,7 +759,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::check] = to_string(checkId.key); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Check); BEAST_EXPECT(jrr[jss::node][sfSendMax.jsonName] == "100000000"); } @@ -721,13 +771,15 @@ class LedgerEntry_test : public beast::unit_test::suite { Json::Value jvParams; jvParams[jss::account_root] = alice.human(); - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; accountRootIndex = jrr[jss::index].asString(); } Json::Value jvParams; jvParams[jss::check] = accountRootIndex; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "unexpectedLedgerType", "Unexpected ledger type."); } { @@ -760,8 +812,8 @@ class LedgerEntry_test : public beast::unit_test::suite // Succeed auto jv = credentials::ledgerEntry(env, alice, issuer, credType); BEAST_EXPECT( - jv.isObject() && jv.isMember(jss::result) && !jv[jss::result].isMember(jss::error) && - jv[jss::result].isMember(jss::node) && + jv.isObject() && jv.isMember(jss::result) && + !jv[jss::result].isMember(jss::error) && jv[jss::result].isMember(jss::node) && jv[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::Credential); @@ -769,8 +821,8 @@ class LedgerEntry_test : public beast::unit_test::suite jv = credentials::ledgerEntry(env, credIdx); BEAST_EXPECT( - jv.isObject() && jv.isMember(jss::result) && !jv[jss::result].isMember(jss::error) && - jv[jss::result].isMember(jss::node) && + jv.isObject() && jv.isMember(jss::result) && + !jv[jss::result].isMember(jss::error) && jv[jss::result].isMember(jss::node) && jv[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::Credential); } @@ -819,7 +871,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::delegate][jss::account] = alice.human(); jvParams[jss::delegate][jss::authorize] = bob.human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Delegate); BEAST_EXPECT(jrr[jss::node][sfAccount.jsonName] == alice.human()); BEAST_EXPECT(jrr[jss::node][sfAuthorize.jsonName] == bob.human()); @@ -830,7 +883,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::delegate] = delegateIndex; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Delegate); BEAST_EXPECT(jrr[jss::node][sfAccount.jsonName] == alice.human()); BEAST_EXPECT(jrr[jss::node][sfAuthorize.jsonName] == bob.human()); @@ -873,7 +927,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::deposit_preauth][jss::owner] = alice.human(); jvParams[jss::deposit_preauth][jss::authorized] = becky.human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::DepositPreauth); BEAST_EXPECT(jrr[jss::node][sfAccount.jsonName] == alice.human()); @@ -885,7 +940,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::deposit_preauth] = depositPreauthIndex; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::DepositPreauth); BEAST_EXPECT(jrr[jss::node][sfAccount.jsonName] == alice.human()); @@ -943,8 +999,8 @@ class LedgerEntry_test : public beast::unit_test::suite auto const jrr = env.rpc("json", "ledger_entry", to_string(jvParams)); BEAST_EXPECT( - jrr.isObject() && jrr.isMember(jss::result) && !jrr[jss::result].isMember(jss::error) && - jrr[jss::result].isMember(jss::node) && + jrr.isObject() && jrr.isMember(jss::result) && + !jrr[jss::result].isMember(jss::error) && jrr[jss::result].isMember(jss::node) && jrr[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && jrr[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::DepositPreauth); } @@ -963,9 +1019,11 @@ class LedgerEntry_test : public beast::unit_test::suite arr.append(jo); jvParams[jss::deposit_preauth][jss::authorized_credentials] = arr; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; - auto const expectedErrMsg = fieldValue.isNull() ? RPC::missing_field_message(jss::issuer.c_str()) - : RPC::expected_field_message(jss::issuer, "AccountID"); + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + auto const expectedErrMsg = fieldValue.isNull() + ? RPC::missing_field_message(jss::issuer.c_str()) + : RPC::expected_field_message(jss::issuer, "AccountID"); checkErrorValue(jrr, "malformedAuthorizedCredentials", expectedErrMsg); }; @@ -1012,7 +1070,8 @@ class LedgerEntry_test : public beast::unit_test::suite arr.append(jo); jvParams[jss::deposit_preauth][jss::authorized_credentials] = arr; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; auto const expectedErrMsg = fieldValue.isNull() ? RPC::missing_field_message(jss::credential_type.c_str()) : RPC::expected_field_message(jss::credential_type, "hex string"); @@ -1173,13 +1232,15 @@ class LedgerEntry_test : public beast::unit_test::suite BEAST_EXPECT(jrr[jss::ledger_index] == 5); } - std::string const dirRootIndex = "A33EC6BB85FB5674074C4A3A43373BB17645308F3EAE1933E3E35252162B217D"; + std::string const dirRootIndex = + "A33EC6BB85FB5674074C4A3A43373BB17645308F3EAE1933E3E35252162B217D"; { // Locate directory by index. Json::Value jvParams; jvParams[jss::directory] = dirRootIndex; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfIndexes.jsonName].size() == 32); } { @@ -1187,7 +1248,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::directory] = Json::objectValue; jvParams[jss::directory][jss::dir_root] = dirRootIndex; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::index] == dirRootIndex); } { @@ -1196,7 +1258,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::directory] = Json::objectValue; jvParams[jss::directory][jss::owner] = alice.human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::index] == dirRootIndex); } { @@ -1205,7 +1268,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::directory] = Json::objectValue; jvParams[jss::directory][jss::dir_root] = dirRootIndex; jvParams[jss::directory][jss::sub_index] = 1; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::index] != dirRootIndex); BEAST_EXPECT(jrr[jss::node][sfIndexes.jsonName].size() == 2); } @@ -1216,7 +1280,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::directory][jss::owner] = alice.human(); jvParams[jss::directory][jss::sub_index] = 1; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::index] != dirRootIndex); BEAST_EXPECT(jrr[jss::node][sfIndexes.jsonName].size() == 2); } @@ -1224,7 +1289,8 @@ class LedgerEntry_test : public beast::unit_test::suite // Bad directory argument. Json::Value jvParams; jvParams[jss::ledger_hash] = ledgerHash; - testMalformedField(env, jvParams, jss::directory, FieldType::HashOrObjectField, "malformedRequest"); + testMalformedField( + env, jvParams, jss::directory, FieldType::HashOrObjectField, "malformedRequest"); } { // Non-integer sub_index. @@ -1233,7 +1299,13 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::directory][jss::dir_root] = dirRootIndex; jvParams[jss::ledger_hash] = ledgerHash; testMalformedSubfield( - env, jvParams, jss::directory, jss::sub_index, FieldType::UInt64Field, "malformedRequest", false); + env, + jvParams, + jss::directory, + jss::sub_index, + FieldType::UInt64Field, + "malformedRequest", + false); } { // Malformed owner entry. @@ -1242,7 +1314,13 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::ledger_hash] = ledgerHash; testMalformedSubfield( - env, jvParams, jss::directory, jss::owner, FieldType::AccountField, "malformedAddress", false); + env, + jvParams, + jss::directory, + jss::owner, + FieldType::AccountField, + "malformedAddress", + false); } { // Malformed directory object. Specifies both dir_root and owner. @@ -1251,8 +1329,10 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::directory][jss::owner] = alice.human(); jvParams[jss::directory][jss::dir_root] = dirRootIndex; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; - checkErrorValue(jrr, "malformedRequest", "Must have exactly one of `owner` and `dir_root` fields."); + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + checkErrorValue( + jrr, "malformedRequest", "Must have exactly one of `owner` and `dir_root` fields."); } { // Incomplete directory object. Missing both dir_root and owner. @@ -1260,8 +1340,10 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::directory] = Json::objectValue; jvParams[jss::directory][jss::sub_index] = 1; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; - checkErrorValue(jrr, "malformedRequest", "Must have exactly one of `owner` and `dir_root` fields."); + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + checkErrorValue( + jrr, "malformedRequest", "Must have exactly one of `owner` and `dir_root` fields."); } } @@ -1301,7 +1383,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::escrow] = Json::objectValue; jvParams[jss::escrow][jss::owner] = alice.human(); jvParams[jss::escrow][jss::seq] = env.seq(alice) - 1; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][jss::Amount] == XRP(333).value().getText()); escrowIndex = jrr[jss::index].asString(); } @@ -1310,12 +1393,14 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::escrow] = escrowIndex; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][jss::Amount] == XRP(333).value().getText()); } { // Malformed escrow fields - runLedgerEntryTest(env, jss::escrow, {{jss::owner, "malformedOwner"}, {jss::seq, "malformedSeq"}}); + runLedgerEntryTest( + env, jss::escrow, {{jss::owner, "malformedOwner"}, {jss::seq, "malformedSeq"}}); } } @@ -1331,12 +1416,14 @@ class LedgerEntry_test : public beast::unit_test::suite Keylet const keylet = keylet::fees(); Json::Value jvParams; jvParams[jss::fee] = to_string(keylet.key); - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::FeeSettings); } // negative tests - testMalformedField(env, Json::Value{}, jss::fee, FieldType::FixedHashField, "malformedRequest"); + testMalformedField( + env, Json::Value{}, jss::fee, FieldType::FixedHashField, "malformedRequest"); } void @@ -1351,12 +1438,14 @@ class LedgerEntry_test : public beast::unit_test::suite Keylet const keylet = keylet::skip(); Json::Value jvParams; jvParams[jss::hashes] = to_string(keylet.key); - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::LedgerHashes); } // negative tests - testMalformedField(env, Json::Value{}, jss::hashes, FieldType::FixedHashField, "malformedRequest"); + testMalformedField( + env, Json::Value{}, jss::hashes, FieldType::FixedHashField, "malformedRequest"); } void @@ -1375,12 +1464,15 @@ class LedgerEntry_test : public beast::unit_test::suite env(token::mint(issuer, 0), txflags(tfTransferable)); env.close(); uint256 const offerID = keylet::nftoffer(issuer, env.seq(issuer)).key; - env(token::createOffer(issuer, nftokenID0, drops(1)), token::destination(buyer), txflags(tfSellNFToken)); + env(token::createOffer(issuer, nftokenID0, drops(1)), + token::destination(buyer), + txflags(tfSellNFToken)); { Json::Value jvParams; jvParams[jss::nft_offer] = to_string(offerID); - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::NFTokenOffer); BEAST_EXPECT(jrr[jss::node][sfOwner.jsonName] == issuer.human()); BEAST_EXPECT(jrr[jss::node][sfNFTokenID.jsonName] == to_string(nftokenID0)); @@ -1411,7 +1503,8 @@ class LedgerEntry_test : public beast::unit_test::suite { Json::Value jvParams; jvParams[jss::nft_page] = to_string(nftpage.key); - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::NFTokenPage); } @@ -1449,9 +1542,10 @@ class LedgerEntry_test : public beast::unit_test::suite sle->setFieldArray(sfDisabledValidators, disabledValidators); sle->setFieldH256( sfPreviousTxnID, - uint256::fromVoid("8D47FFE664BE6C335108DF689537625855A6" - "A95160CC6D351341B9" - "2624D9C5E3")); + uint256::fromVoid( + "8D47FFE664BE6C335108DF689537625855A6" + "A95160CC6D351341B9" + "2624D9C5E3")); sle->setFieldU32(sfPreviousTxnLgrSeq, 91442944); view.rawInsert(sle); @@ -1462,12 +1556,14 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::nunl] = to_string(keylet.key); - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::NegativeUNL); } // negative tests - testMalformedField(env, Json::Value{}, jss::nunl, FieldType::FixedHashField, "malformedRequest"); + testMalformedField( + env, Json::Value{}, jss::nunl, FieldType::FixedHashField, "malformedRequest"); } void @@ -1494,7 +1590,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::offer][jss::account] = alice.human(); jvParams[jss::offer][jss::seq] = env.seq(alice) - 1; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][jss::TakerGets] == "322000000"); offerIndex = jrr[jss::index].asString(); } @@ -1502,13 +1599,17 @@ class LedgerEntry_test : public beast::unit_test::suite // Request the offer using its index. Json::Value jvParams; jvParams[jss::offer] = offerIndex; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][jss::TakerGets] == "322000000"); } { // Malformed offer fields - runLedgerEntryTest(env, jss::offer, {{jss::account, "malformedAddress"}, {jss::seq, "malformedRequest"}}); + runLedgerEntryTest( + env, + jss::offer, + {{jss::account, "malformedAddress"}, {jss::seq, "malformedRequest"}}); } } @@ -1551,7 +1652,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::payment_channel] = to_string(payChanIndex); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfAmount.jsonName] == "57000000"); BEAST_EXPECT(jrr[jss::node][sfBalance.jsonName] == "0"); BEAST_EXPECT(jrr[jss::node][sfSettleDelay.jsonName] == 18); @@ -1561,7 +1663,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::payment_channel] = ledgerHash; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } @@ -1602,7 +1705,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[fieldName][jss::accounts][1u] = gw.human(); jvParams[fieldName][jss::currency] = "USD"; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfBalance.jsonName][jss::value] == "-97"); BEAST_EXPECT(jrr[jss::node][sfHighLimit.jsonName][jss::value] == "999"); } @@ -1624,7 +1728,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[fieldName][jss::accounts][0u] = alice.human(); jvParams[fieldName][jss::currency] = "USD"; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue( jrr, "malformedRequest", @@ -1641,7 +1746,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[fieldName][jss::accounts][2u] = alice.human(); jvParams[fieldName][jss::currency] = "USD"; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue( jrr, "malformedRequest", @@ -1660,9 +1766,12 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[fieldName][jss::accounts][1u] = gw.human(); jvParams[fieldName][jss::currency] = "USD"; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue( - jrr, "malformedAddress", RPC::expected_field_message(jss::accounts, "array of Accounts")); + jrr, + "malformedAddress", + RPC::expected_field_message(jss::accounts, "array of Accounts")); } { @@ -1672,9 +1781,12 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[fieldName][jss::accounts][1u] = badAccount; jvParams[fieldName][jss::currency] = "USD"; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue( - jrr, "malformedAddress", RPC::expected_field_message(jss::accounts, "array of Accounts")); + jrr, + "malformedAddress", + RPC::expected_field_message(jss::accounts, "array of Accounts")); } }; @@ -1694,7 +1806,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[fieldName][jss::accounts][1u] = alice.human(); jvParams[fieldName][jss::currency] = "USD"; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "malformedRequest", "Cannot have a trustline to self."); } } @@ -1731,7 +1844,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ticket] = to_string(getTicketIndex(env.master, tkt1 - 1)); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } { @@ -1739,7 +1853,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ticket] = to_string(getTicketIndex(env.master, tkt1)); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Ticket); BEAST_EXPECT(jrr[jss::node][sfTicketSequence.jsonName] == tkt1); } @@ -1750,8 +1865,10 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::ticket][jss::account] = env.master.human(); jvParams[jss::ticket][jss::ticket_seq] = tkt1 + 1; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT(jrr[jss::node][jss::index] == to_string(getTicketIndex(env.master, tkt1 + 1))); + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT( + jrr[jss::node][jss::index] == to_string(getTicketIndex(env.master, tkt1 + 1))); } { // Not a valid ticket requested by account and sequence. @@ -1760,7 +1877,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::ticket][jss::account] = env.master.human(); jvParams[jss::ticket][jss::ticket_seq] = tkt1 + 2; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } { @@ -1768,7 +1886,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ticket] = to_string(keylet::account(env.master).key); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "unexpectedLedgerType", "Unexpected ledger type."); } @@ -1816,7 +1935,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::did] = alice.human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfDIDDocument.jsonName] == strHex(std::string{"data"})); BEAST_EXPECT(jrr[jss::node][sfURI.jsonName] == strHex(std::string{"uri"})); } @@ -1825,13 +1945,15 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::did] = env.master.human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } { // Malformed DID index Json::Value jvParams; - testMalformedField(env, jvParams, jss::did, FieldType::AccountField, "malformedAddress"); + testMalformedField( + env, jvParams, jss::did, FieldType::AccountField, "malformedAddress"); } } @@ -1845,7 +1967,8 @@ class LedgerEntry_test : public beast::unit_test::suite Env env(*this); Account const owner("owner"); env.fund(XRP(1'000), owner); - Oracle oracle(env, {.owner = owner, .fee = static_cast(env.current()->fees().base.drops())}); + Oracle oracle( + env, {.owner = owner, .fee = static_cast(env.current()->fees().base.drops())}); { // test basic malformed scenarios @@ -1918,8 +2041,8 @@ class LedgerEntry_test : public beast::unit_test::suite {.transferFee = 10, .metadata = "123", .ownerCount = 1, - .flags = tfMPTCanLock | tfMPTRequireAuth | tfMPTCanEscrow | tfMPTCanTrade | tfMPTCanTransfer | - tfMPTCanClawback}); + .flags = tfMPTCanLock | tfMPTRequireAuth | tfMPTCanEscrow | tfMPTCanTrade | + tfMPTCanTransfer | tfMPTCanClawback}); mptAlice.authorize({.account = bob, .holderCount = 1}); std::string const ledgerHash{to_string(env.closed()->header().hash)}; @@ -1930,7 +2053,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::mpt_issuance] = strHex(mptAlice.issuanceID()); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfMPTokenMetadata.jsonName] == strHex(std::string{"123"})); BEAST_EXPECT(jrr[jss::node][jss::mpt_issuance_id] == strHex(mptAlice.issuanceID())); } @@ -1939,7 +2063,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::mpt_issuance] = badMptID; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } { @@ -1949,8 +2074,10 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::mptoken][jss::account] = bob.human(); jvParams[jss::mptoken][jss::mpt_issuance_id] = strHex(mptAlice.issuanceID()); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT(jrr[jss::node][sfMPTokenIssuanceID.jsonName] == strHex(mptAlice.issuanceID())); + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT( + jrr[jss::node][sfMPTokenIssuanceID.jsonName] == strHex(mptAlice.issuanceID())); } { // Request the MPToken using a bad mptIssuanceID. @@ -1959,13 +2086,15 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::mptoken][jss::account] = bob.human(); jvParams[jss::mptoken][jss::mpt_issuance_id] = badMptID; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } { // Malformed MPTIssuance index Json::Value jvParams; - testMalformedField(env, jvParams, jss::mptoken, FieldType::HashOrObjectField, "malformedRequest"); + testMalformedField( + env, jvParams, jss::mptoken, FieldType::HashOrObjectField, "malformedRequest"); } } @@ -1999,8 +2128,8 @@ class LedgerEntry_test : public beast::unit_test::suite params[jss::permissioned_domain][jss::seq] = seq; auto jv = env.rpc("json", "ledger_entry", to_string(params)); BEAST_EXPECT( - jv.isObject() && jv.isMember(jss::result) && !jv[jss::result].isMember(jss::error) && - jv[jss::result].isMember(jss::node) && + jv.isObject() && jv.isMember(jss::result) && + !jv[jss::result].isMember(jss::error) && jv[jss::result].isMember(jss::node) && jv[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::PermissionedDomain); @@ -2012,8 +2141,8 @@ class LedgerEntry_test : public beast::unit_test::suite params[jss::permissioned_domain] = pdIdx; jv = env.rpc("json", "ledger_entry", to_string(params)); BEAST_EXPECT( - jv.isObject() && jv.isMember(jss::result) && !jv[jss::result].isMember(jss::error) && - jv[jss::result].isMember(jss::node) && + jv.isObject() && jv.isMember(jss::result) && + !jv[jss::result].isMember(jss::error) && jv[jss::result].isMember(jss::node) && jv[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::PermissionedDomain); } @@ -2073,7 +2202,8 @@ class LedgerEntry_test : public beast::unit_test::suite if (good) { BEAST_EXPECTS( - jv.isObject() && jv.isMember(jss::result) && !jv[jss::result].isMember(jss::error) && + jv.isObject() && jv.isMember(jss::result) && + !jv[jss::result].isMember(jss::error) && jv[jss::result].isMember(jss::node) && jv[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == expectedType, @@ -2082,7 +2212,8 @@ class LedgerEntry_test : public beast::unit_test::suite else { BEAST_EXPECTS( - jv.isObject() && jv.isMember(jss::result) && jv[jss::result].isMember(jss::error) && + jv.isObject() && jv.isMember(jss::result) && + jv[jss::result].isMember(jss::error) && !jv[jss::result].isMember(jss::node) && jv[jss::result][jss::error] == expectedError.value_or("entryNotFound"), to_string(jv)); @@ -2264,20 +2395,23 @@ class LedgerEntry_test : public beast::unit_test::suite if (good) { BEAST_EXPECTS( - jv.isObject() && jv.isMember(jss::result) && !jv[jss::result].isMember(jss::error) && + jv.isObject() && jv.isMember(jss::result) && + !jv[jss::result].isMember(jss::error) && jv[jss::result].isMember(jss::node) && jv[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::LedgerHashes, to_string(jv)); BEAST_EXPECTS( - jv[jss::result].isMember(jss::node) && jv[jss::result][jss::node].isMember("Hashes") && + jv[jss::result].isMember(jss::node) && + jv[jss::result][jss::node].isMember("Hashes") && jv[jss::result][jss::node]["Hashes"].size() == expectedCount, to_string(jv[jss::result][jss::node]["Hashes"].size())); } else { BEAST_EXPECTS( - jv.isObject() && jv.isMember(jss::result) && jv[jss::result].isMember(jss::error) && + jv.isObject() && jv.isMember(jss::result) && + jv[jss::result].isMember(jss::error) && !jv[jss::result].isMember(jss::node) && jv[jss::result][jss::error] == expectedError.value_or("entryNotFound"), to_string(jv)); @@ -2294,111 +2428,114 @@ class LedgerEntry_test : public beast::unit_test::suite * @param expectedCount: The number of Hashes expected in the * object if "good". */ - auto test = [&](Json::Value ledger, Keylet const& expectedKey, bool good, int expectedCount = 0) { - testcase << "LedgerHashes: seq: " << env.current()->header().seq << " \"hashes\":" << to_string(ledger) - << (good ? "" : " not") << " found"; + auto test = + [&](Json::Value ledger, Keylet const& expectedKey, bool good, int expectedCount = 0) { + testcase << "LedgerHashes: seq: " << env.current()->header().seq + << " \"hashes\":" << to_string(ledger) << (good ? "" : " not") << " found"; - auto const hexKey = strHex(expectedKey.key); + auto const hexKey = strHex(expectedKey.key); - { - // Test bad values - // "hashes":null - Json::Value params; - params[jss::ledger_index] = jss::validated; - params[jss::hashes] = Json::nullValue; - auto jv = env.rpc("json", "ledger_entry", to_string(params)); - checkResult(false, jv, 0, "malformedRequest"); - BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); - } + { + // Test bad values + // "hashes":null + Json::Value params; + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = Json::nullValue; + auto jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, 0, "malformedRequest"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } - { - Json::Value params; - // "hashes":"non-uint string" - params[jss::ledger_index] = jss::validated; - params[jss::hashes] = "arbitrary string"; - auto const jv = env.rpc("json", "ledger_entry", to_string(params)); - checkResult(false, jv, 0, "malformedRequest"); - BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); - } + { + Json::Value params; + // "hashes":"non-uint string" + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = "arbitrary string"; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, 0, "malformedRequest"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } - { - Json::Value params; - // "hashes":"uint string" is invalid, too - params[jss::ledger_index] = jss::validated; - params[jss::hashes] = "10"; - auto const jv = env.rpc("json", "ledger_entry", to_string(params)); - checkResult(false, jv, 0, "malformedRequest"); - BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); - } + { + Json::Value params; + // "hashes":"uint string" is invalid, too + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = "10"; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, 0, "malformedRequest"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } - { - Json::Value params; - // "hashes":false - params[jss::ledger_index] = jss::validated; - params[jss::hashes] = false; - auto const jv = env.rpc("json", "ledger_entry", to_string(params)); - checkResult(false, jv, 0, "invalidParams"); - BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); - } + { + Json::Value params; + // "hashes":false + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = false; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, 0, "invalidParams"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } - { - Json::Value params; - // "hashes":-1 - params[jss::ledger_index] = jss::validated; - params[jss::hashes] = -1; - auto const jv = env.rpc("json", "ledger_entry", to_string(params)); - checkResult(false, jv, 0, "internal"); - BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); - } + { + Json::Value params; + // "hashes":-1 + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = -1; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, 0, "internal"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } - // "hashes":[incorrect index hash] - { - Json::Value params; - auto const badKey = strHex(expectedKey.key + uint256{1}); - params[jss::ledger_index] = jss::validated; - params[jss::hashes] = badKey; - auto const jv = env.rpc("json", "ledger_entry", to_string(params)); - checkResult(false, jv, 0, "entryNotFound"); - BEAST_EXPECT(jv[jss::result][jss::index] == badKey); - } + // "hashes":[incorrect index hash] + { + Json::Value params; + auto const badKey = strHex(expectedKey.key + uint256{1}); + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = badKey; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, 0, "entryNotFound"); + BEAST_EXPECT(jv[jss::result][jss::index] == badKey); + } - { - Json::Value params; - // Test good values - // Use the "hashes":ledger notation - params[jss::ledger_index] = jss::validated; - params[jss::hashes] = ledger; - auto const jv = env.rpc("json", "ledger_entry", to_string(params)); - checkResult(good, jv, expectedCount); - // Index will always be returned for valid parameters. - std::string const pdIdx = jv[jss::result][jss::index].asString(); - BEAST_EXPECTS(hexKey == pdIdx, strHex(pdIdx)); - } + { + Json::Value params; + // Test good values + // Use the "hashes":ledger notation + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = ledger; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(good, jv, expectedCount); + // Index will always be returned for valid parameters. + std::string const pdIdx = jv[jss::result][jss::index].asString(); + BEAST_EXPECTS(hexKey == pdIdx, strHex(pdIdx)); + } - { - Json::Value params; - // "hashes":"[index hash]" - params[jss::ledger_index] = jss::validated; - params[jss::hashes] = hexKey; - auto const jv = env.rpc("json", "ledger_entry", to_string(params)); - checkResult(good, jv, expectedCount); - // Index is correct either way - BEAST_EXPECTS( - hexKey == jv[jss::result][jss::index].asString(), strHex(jv[jss::result][jss::index].asString())); - } + { + Json::Value params; + // "hashes":"[index hash]" + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = hexKey; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(good, jv, expectedCount); + // Index is correct either way + BEAST_EXPECTS( + hexKey == jv[jss::result][jss::index].asString(), + strHex(jv[jss::result][jss::index].asString())); + } - { - Json::Value params; - // Use the "index":"[index hash]" notation - params[jss::ledger_index] = jss::validated; - params[jss::index] = hexKey; - auto const jv = env.rpc("json", "ledger_entry", to_string(params)); - checkResult(good, jv, expectedCount); - // Index is correct either way - BEAST_EXPECTS( - hexKey == jv[jss::result][jss::index].asString(), strHex(jv[jss::result][jss::index].asString())); - } - }; + { + Json::Value params; + // Use the "index":"[index hash]" notation + params[jss::ledger_index] = jss::validated; + params[jss::index] = hexKey; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(good, jv, expectedCount); + // Index is correct either way + BEAST_EXPECTS( + hexKey == jv[jss::result][jss::index].asString(), + strHex(jv[jss::result][jss::index].asString())); + } + }; // short skip list test(true, keylet::skip(), true, 2); @@ -2491,7 +2628,8 @@ public: } }; -class LedgerEntry_XChain_test : public beast::unit_test::suite, public test::jtx::XChainBridgeObjects +class LedgerEntry_XChain_test : public beast::unit_test::suite, + public test::jtx::XChainBridgeObjects { void checkErrorValue(Json::Value const& jv, std::string const& err, std::string const& msg) @@ -2527,7 +2665,8 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, public test::jtx Json::Value jvParams; jvParams[jss::bridge_account] = mcDoor.human(); jvParams[jss::bridge] = jvb; - Json::Value const jrr = mcEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + mcEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); auto r = jrr[jss::node]; @@ -2556,7 +2695,8 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, public test::jtx // request the bridge via RPC by index Json::Value jvParams; jvParams[jss::index] = bridge_index; - Json::Value const jrr = mcEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + mcEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); BEAST_EXPECT(jrr[jss::node] == mcBridge); @@ -2568,7 +2708,8 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, public test::jtx jvParams[jss::bridge_account] = Account::master.human(); jvParams[jss::bridge] = jvb; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = mcEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + mcEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } @@ -2584,7 +2725,8 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, public test::jtx Json::Value jvParams; jvParams[jss::bridge_account] = mcDoor.human(); jvParams[jss::bridge] = jvb; - Json::Value const jrr = mcEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + mcEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); auto r = jrr[jss::node]; @@ -2617,7 +2759,8 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, public test::jtx Json::Value jvParams; jvParams[jss::xchain_owned_claim_id] = jvXRPBridgeRPC; jvParams[jss::xchain_owned_claim_id][jss::xchain_owned_claim_id] = 1; - Json::Value const jrr = scEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + scEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); auto r = jrr[jss::node]; @@ -2634,7 +2777,8 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, public test::jtx Json::Value jvParams; jvParams[jss::xchain_owned_claim_id] = jvXRPBridgeRPC; jvParams[jss::xchain_owned_claim_id][jss::xchain_owned_claim_id] = 2; - Json::Value const jrr = scEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = + scEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); auto r = jrr[jss::node]; @@ -2690,8 +2834,10 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, public test::jtx // request the create account claim_id via RPC Json::Value jvParams; jvParams[jss::xchain_owned_create_account_claim_id] = jvXRPBridgeRPC; - jvParams[jss::xchain_owned_create_account_claim_id][jss::xchain_owned_create_account_claim_id] = 1; - Json::Value const jrr = scEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + jvParams[jss::xchain_owned_create_account_claim_id] + [jss::xchain_owned_create_account_claim_id] = 1; + Json::Value const jrr = + scEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); auto r = jrr[jss::node]; @@ -2706,13 +2852,16 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, public test::jtx auto attest = r[sfXChainCreateAccountAttestations.jsonName]; BEAST_EXPECT(attest.isArray()); BEAST_EXPECT(attest.size() == 3); - BEAST_EXPECT(attest[Json::Value::UInt(0)].isMember(sfXChainCreateAccountProofSig.jsonName)); + BEAST_EXPECT( + attest[Json::Value::UInt(0)].isMember(sfXChainCreateAccountProofSig.jsonName)); Json::Value a[num_attest]; for (size_t i = 0; i < num_attest; ++i) { a[i] = attest[Json::Value::UInt(0)][sfXChainCreateAccountProofSig.jsonName]; - BEAST_EXPECT(a[i].isMember(jss::Amount) && a[i][jss::Amount].asInt() == 1000 * drop_per_xrp); - BEAST_EXPECT(a[i].isMember(jss::Destination) && a[i][jss::Destination] == scCarol.human()); + BEAST_EXPECT( + a[i].isMember(jss::Amount) && a[i][jss::Amount].asInt() == 1000 * drop_per_xrp); + BEAST_EXPECT( + a[i].isMember(jss::Destination) && a[i][jss::Destination] == scCarol.human()); BEAST_EXPECT( a[i].isMember(sfAttestationSignerAccount.jsonName) && std::any_of(signers.begin(), signers.end(), [&](signer const& s) { @@ -2724,7 +2873,8 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, public test::jtx return a[i][sfAttestationRewardAccount.jsonName] == account.human(); })); BEAST_EXPECT( - a[i].isMember(sfWasLockingChainSend.jsonName) && a[i][sfWasLockingChainSend.jsonName] == 1); + a[i].isMember(sfWasLockingChainSend.jsonName) && + a[i][sfWasLockingChainSend.jsonName] == 1); BEAST_EXPECT( a[i].isMember(sfSignatureReward.jsonName) && a[i][sfSignatureReward.jsonName].asInt() == 1 * drop_per_xrp); @@ -2742,8 +2892,10 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, public test::jtx // request the create account claim_id via RPC Json::Value jvParams; jvParams[jss::xchain_owned_create_account_claim_id] = jvXRPBridgeRPC; - jvParams[jss::xchain_owned_create_account_claim_id][jss::xchain_owned_create_account_claim_id] = 1; - Json::Value const jrr = scEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + jvParams[jss::xchain_owned_create_account_claim_id] + [jss::xchain_owned_create_account_claim_id] = 1; + Json::Value const jrr = + scEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } } diff --git a/src/test/rpc/LedgerRPC_test.cpp b/src/test/rpc/LedgerRPC_test.cpp index a656db558c..d45f50c657 100644 --- a/src/test/rpc/LedgerRPC_test.cpp +++ b/src/test/rpc/LedgerRPC_test.cpp @@ -32,7 +32,8 @@ class LedgerRPC_test : public beast::unit_test::suite else if (BEAST_EXPECT(jv.isMember(jss::error_message))) BEAST_EXPECTS( jv[jss::error_message] == msg, - "Expected error message \"" + msg + "\", received \"" + jv[jss::error_message].asString() + "\""); + "Expected error message \"" + msg + "\", received \"" + + jv[jss::error_message].asString() + "\""); } // Corrupt a valid address by replacing the 10th character with '!'. @@ -77,7 +78,8 @@ class LedgerRPC_test : public beast::unit_test::suite // using current identifier auto const jrr = env.rpc("ledger", "current")[jss::result]; BEAST_EXPECT(jrr[jss::ledger][jss::closed] == false); - BEAST_EXPECT(jrr[jss::ledger][jss::ledger_index] == std::to_string(env.current()->header().seq)); + BEAST_EXPECT( + jrr[jss::ledger][jss::ledger_index] == std::to_string(env.current()->header().seq)); BEAST_EXPECT(jrr[jss::ledger_current_index] == env.current()->header().seq); } } @@ -102,7 +104,8 @@ class LedgerRPC_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ledger_index] = "potato"; auto const jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; - checkErrorValue(jrr, "invalidParams", "Invalid field 'ledger_index', not string or number."); + checkErrorValue( + jrr, "invalidParams", "Invalid field 'ledger_index', not string or number."); } { @@ -110,7 +113,8 @@ class LedgerRPC_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ledger_index] = -1; auto const jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; - checkErrorValue(jrr, "invalidParams", "Invalid field 'ledger_index', not string or number."); + checkErrorValue( + jrr, "invalidParams", "Invalid field 'ledger_index', not string or number."); } { @@ -268,7 +272,8 @@ class LedgerRPC_test : public beast::unit_test::suite jvParams[jss::ledger] = "invalid"; jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'ledger', not string or number."); + BEAST_EXPECT( + jrr[jss::error_message] == "Invalid field 'ledger', not string or number."); // numeric index jvParams[jss::ledger] = 4; @@ -351,7 +356,8 @@ class LedgerRPC_test : public beast::unit_test::suite jvParams[jss::ledger_index] = "invalid"; jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'ledger_index', not string or number."); + BEAST_EXPECT( + jrr[jss::error_message] == "Invalid field 'ledger_index', not string or number."); // numeric index for (auto i : {1, 2, 3, 4, 5, 6}) @@ -640,7 +646,8 @@ class LedgerRPC_test : public beast::unit_test::suite // jss::type is a deprecated field BEAST_EXPECT( - jrr.isMember(jss::warnings) && jrr[jss::warnings].isArray() && jrr[jss::warnings].size() == 1 && + jrr.isMember(jss::warnings) && jrr[jss::warnings].isArray() && + jrr[jss::warnings].size() == 1 && jrr[jss::warnings][0u][jss::id].asInt() == warnRPC_FIELDS_DEPRECATED); } { @@ -653,11 +660,13 @@ class LedgerRPC_test : public beast::unit_test::suite BEAST_EXPECT(jrr[jss::ledger].isMember(jss::accountState)); BEAST_EXPECT(jrr[jss::ledger][jss::accountState].isArray()); BEAST_EXPECT( - hashesLedgerEntryIndex > 0 && jrr[jss::ledger][jss::accountState][hashesLedgerEntryIndex] == index); + hashesLedgerEntryIndex > 0 && + jrr[jss::ledger][jss::accountState][hashesLedgerEntryIndex] == index); // jss::type is a deprecated field BEAST_EXPECT( - jrr.isMember(jss::warnings) && jrr[jss::warnings].isArray() && jrr[jss::warnings].size() == 1 && + jrr.isMember(jss::warnings) && jrr[jss::warnings].isArray() && + jrr[jss::warnings].size() == 1 && jrr[jss::warnings][0u][jss::id].asInt() == warnRPC_FIELDS_DEPRECATED); } } diff --git a/src/test/rpc/LedgerRequest_test.cpp b/src/test/rpc/LedgerRequest_test.cpp index 6a1bb2fb89..18c717ec19 100644 --- a/src/test/rpc/LedgerRequest_test.cpp +++ b/src/test/rpc/LedgerRequest_test.cpp @@ -14,10 +14,13 @@ namespace RPC { class LedgerRequest_test : public beast::unit_test::suite { - static constexpr char const* hash1 = "3020EB9E7BE24EF7D7A060CB051583EC117384636D1781AFB5B87F3E348DA489"; - static constexpr char const* accounthash1 = "BD8A3D72CA73DDE887AD63666EC2BAD07875CBA997A102579B5B95ECDFFEAED8"; + static constexpr char const* hash1 = + "3020EB9E7BE24EF7D7A060CB051583EC117384636D1781AFB5B87F3E348DA489"; + static constexpr char const* accounthash1 = + "BD8A3D72CA73DDE887AD63666EC2BAD07875CBA997A102579B5B95ECDFFEAED8"; - static constexpr char const* zerohash = "0000000000000000000000000000000000000000000000000000000000000000"; + static constexpr char const* zerohash = + "0000000000000000000000000000000000000000000000000000000000000000"; public: void @@ -56,7 +59,8 @@ public: { auto const result = env.rpc("ledger_request", "1"); BEAST_EXPECT( - !RPC::contains_error(result[jss::result]) && result[jss::result][jss::ledger_index] == 1 && + !RPC::contains_error(result[jss::result]) && + result[jss::result][jss::ledger_index] == 1 && result[jss::result].isMember(jss::ledger)); BEAST_EXPECT( result[jss::result][jss::ledger].isMember(jss::ledger_hash) && @@ -66,7 +70,8 @@ public: { auto const result = env.rpc("ledger_request", "2"); BEAST_EXPECT( - !RPC::contains_error(result[jss::result]) && result[jss::result][jss::ledger_index] == 2 && + !RPC::contains_error(result[jss::result]) && + result[jss::result][jss::ledger_index] == 2 && result[jss::result].isMember(jss::ledger)); BEAST_EXPECT( result[jss::result][jss::ledger].isMember(jss::ledger_hash) && @@ -76,7 +81,8 @@ public: { auto const result = env.rpc("ledger_request", "3"); BEAST_EXPECT( - !RPC::contains_error(result[jss::result]) && result[jss::result][jss::ledger_index] == 3 && + !RPC::contains_error(result[jss::result]) && + result[jss::result][jss::ledger_index] == 3 && result[jss::result].isMember(jss::ledger)); BEAST_EXPECT( result[jss::result][jss::ledger].isMember(jss::ledger_hash) && @@ -87,8 +93,8 @@ public: { auto const r = env.rpc("ledger_request", ledgerHash); BEAST_EXPECT( - !RPC::contains_error(r[jss::result]) && r[jss::result][jss::ledger_index] == 3 && - r[jss::result].isMember(jss::ledger)); + !RPC::contains_error(r[jss::result]) && + r[jss::result][jss::ledger_index] == 3 && r[jss::result].isMember(jss::ledger)); BEAST_EXPECT( r[jss::result][jss::ledger].isMember(jss::ledger_hash) && r[jss::result][jss::ledger][jss::ledger_hash] == ledgerHash); @@ -102,7 +108,8 @@ public: BEAST_EXPECT( RPC::contains_error(result[jss::result]) && - result[jss::result][jss::error_message] == "Invalid field 'ledger_hash', not hex string."); + result[jss::result][jss::error_message] == + "Invalid field 'ledger_hash', not hex string."); } { @@ -110,7 +117,9 @@ public: auto const result = env.rpc("ledger_request", ledgerHash); - BEAST_EXPECT(!RPC::contains_error(result[jss::result]) && result[jss::result][jss::have_header] == false); + BEAST_EXPECT( + !RPC::contains_error(result[jss::result]) && + result[jss::result][jss::have_header] == false); } { @@ -164,7 +173,8 @@ public: BEAST_EXPECT(result[jss::ledger][jss::transaction_hash] == zerohash); result = env.rpc("ledger_request", "2")[jss::result]; - constexpr char const* hash2 = "CCC3B3E88CCAC17F1BE6B4A648A55999411F19E3FE55EB721960EB0DF28EDDA5"; + constexpr char const* hash2 = + "CCC3B3E88CCAC17F1BE6B4A648A55999411F19E3FE55EB721960EB0DF28EDDA5"; BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "2"); BEAST_EXPECT(result[jss::ledger][jss::total_coins] == "100000000000000000"); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); @@ -176,7 +186,8 @@ public: BEAST_EXPECT(result[jss::ledger][jss::transaction_hash] == zerohash); result = env.rpc("ledger_request", "3")[jss::result]; - constexpr char const* hash3 = "9FFD8AE09190D5002FE4252A1B29EABCF40DABBCE3B42619C6BD0BE381D51103"; + constexpr char const* hash3 = + "9FFD8AE09190D5002FE4252A1B29EABCF40DABBCE3B42619C6BD0BE381D51103"; BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "3"); BEAST_EXPECT(result[jss::ledger][jss::total_coins] == "99999999999999980"); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); @@ -190,7 +201,8 @@ public: "CBD7F0948EBFA2241DE4EA627939A0FFEE6B80A90FE09C42C825DA546E9B73FF"); result = env.rpc("ledger_request", "4")[jss::result]; - constexpr char const* hash4 = "7C9B614445517B8C6477E0AB10A35FFC1A23A34FEA41A91ECBDE884CC097C6E1"; + constexpr char const* hash4 = + "7C9B614445517B8C6477E0AB10A35FFC1A23A34FEA41A91ECBDE884CC097C6E1"; BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "4"); BEAST_EXPECT(result[jss::ledger][jss::total_coins] == "99999999999999960"); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); @@ -204,7 +216,8 @@ public: "9BBDDBF926100DFFF364E16268F544B19F5B9BC6ECCBBC104F98D13FA9F3BC35"); result = env.rpc("ledger_request", "5")[jss::result]; - constexpr char const* hash5 = "98885D02145CCE4AD2605F1809F17188DB2053B14ED399CAC985DD8E03DCA8C0"; + constexpr char const* hash5 = + "98885D02145CCE4AD2605F1809F17188DB2053B14ED399CAC985DD8E03DCA8C0"; BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "5"); BEAST_EXPECT(result[jss::ledger][jss::total_coins] == "99999999999999940"); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); @@ -239,7 +252,8 @@ public: "AB868A6CFEEC779C2FF845C0AF00A642259986AF40C01976A7F842B6918936" "C7"; jvParams[jss::ledger_index] = "1"; - auto const result = env.rpc("json", "ledger_request", jvParams.toStyledString())[jss::result]; + auto const result = + env.rpc("json", "ledger_request", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); BEAST_EXPECT(result[jss::status] == "error"); BEAST_EXPECT( @@ -251,7 +265,8 @@ public: { Json::Value jvParams; jvParams[jss::ledger_index] = "index"; - auto const result = env.rpc("json", "ledger_request", jvParams.toStyledString())[jss::result]; + auto const result = + env.rpc("json", "ledger_request", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); BEAST_EXPECT(result[jss::status] == "error"); BEAST_EXPECT(result[jss::error_message] == "Invalid field 'ledger_index', not number."); diff --git a/src/test/rpc/NoRippleCheck_test.cpp b/src/test/rpc/NoRippleCheck_test.cpp index 0857561fda..c436c1d7b1 100644 --- a/src/test/rpc/NoRippleCheck_test.cpp +++ b/src/test/rpc/NoRippleCheck_test.cpp @@ -77,7 +77,8 @@ class NoRippleCheck_test : public beast::unit_test::suite params[jss::limit] = -1; auto const result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); - BEAST_EXPECT(result[jss::error_message] == "Invalid field 'limit', not unsigned integer."); + BEAST_EXPECT( + result[jss::error_message] == "Invalid field 'limit', not unsigned integer."); } { // invalid ledger (hash) @@ -87,7 +88,8 @@ class NoRippleCheck_test : public beast::unit_test::suite params[jss::ledger_hash] = 1; auto const result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); - BEAST_EXPECT(result[jss::error_message] == "Invalid field 'ledger_hash', not hex string."); + BEAST_EXPECT( + result[jss::error_message] == "Invalid field 'ledger_hash', not hex string."); } { // account not found @@ -134,7 +136,8 @@ class NoRippleCheck_test : public beast::unit_test::suite params[jss::ledger] = Json::objectValue; auto const result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); - BEAST_EXPECT(result[jss::error_message] == "Invalid field 'ledger', not string or number."); + BEAST_EXPECT( + result[jss::error_message] == "Invalid field 'ledger', not string or number."); } } @@ -214,7 +217,8 @@ class NoRippleCheck_test : public beast::unit_test::suite } BEAST_EXPECT(result[jss::transactions][txs.size() - 1][jss::Account] == alice.human()); - BEAST_EXPECT(result[jss::transactions][txs.size() - 1][jss::TransactionType] == jss::TrustSet); + BEAST_EXPECT( + result[jss::transactions][txs.size() - 1][jss::TransactionType] == jss::TrustSet); BEAST_EXPECT( result[jss::transactions][txs.size() - 1][jss::LimitAmount] == gw["USD"](100).value().getJson(JsonOptions::none)); @@ -263,14 +267,15 @@ class NoRippleCheckLimits_test : public beast::unit_test::suite using namespace xrpl::Resource; using namespace std::chrono; using namespace beast::IP; - auto c = - env.app().getResourceManager().newInboundEndpoint(Endpoint::from_string(test::getEnvLocalhostAddr())); + auto c = env.app().getResourceManager().newInboundEndpoint( + Endpoint::from_string(test::getEnvLocalhostAddr())); // if we go above the warning threshold, reset if (c.balance() > warningThreshold) { using ct = beast::abstract_clock; - c.entry().local_balance = DecayingSample{steady_clock::now()}; + c.entry().local_balance = + DecayingSample{steady_clock::now()}; } }; diff --git a/src/test/rpc/NoRipple_test.cpp b/src/test/rpc/NoRipple_test.cpp index 9cfc69ccd5..27f13aa3e2 100644 --- a/src/test/rpc/NoRipple_test.cpp +++ b/src/test/rpc/NoRipple_test.cpp @@ -247,7 +247,8 @@ public: testSetAndClear(); auto withFeatsTests = [this](FeatureBitset features) { - forAllApiVersions([&, this](unsigned testVersion) { testDefaultRipple(features, testVersion); }); + forAllApiVersions( + [&, this](unsigned testVersion) { testDefaultRipple(features, testVersion); }); testNegativeBalance(features); testPairwise(features); }; diff --git a/src/test/rpc/OwnerInfo_test.cpp b/src/test/rpc/OwnerInfo_test.cpp index 9e3fee04c2..8a09fed467 100644 --- a/src/test/rpc/OwnerInfo_test.cpp +++ b/src/test/rpc/OwnerInfo_test.cpp @@ -92,14 +92,21 @@ class OwnerInfo_test : public beast::unit_test::suite BEAST_EXPECT( lines[0u][sfBalance.fieldName] == - (STAmount{Issue{to_currency("CNY"), noAccount()}, 0}.value().getJson(JsonOptions::none))); - BEAST_EXPECT(lines[0u][sfHighLimit.fieldName] == alice["CNY"](1000).value().getJson(JsonOptions::none)); - BEAST_EXPECT(lines[0u][sfLowLimit.fieldName] == gw["CNY"](0).value().getJson(JsonOptions::none)); + (STAmount{Issue{to_currency("CNY"), noAccount()}, 0}.value().getJson( + JsonOptions::none))); + BEAST_EXPECT( + lines[0u][sfHighLimit.fieldName] == + alice["CNY"](1000).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + lines[0u][sfLowLimit.fieldName] == gw["CNY"](0).value().getJson(JsonOptions::none)); BEAST_EXPECT( lines[1u][sfBalance.fieldName] == - (STAmount{Issue{to_currency("USD"), noAccount()}, 0}.value().getJson(JsonOptions::none))); - BEAST_EXPECT(lines[1u][sfHighLimit.fieldName] == alice["USD"](1000).value().getJson(JsonOptions::none)); + (STAmount{Issue{to_currency("USD"), noAccount()}, 0}.value().getJson( + JsonOptions::none))); + BEAST_EXPECT( + lines[1u][sfHighLimit.fieldName] == + alice["USD"](1000).value().getJson(JsonOptions::none)); BEAST_EXPECT(lines[1u][sfLowLimit.fieldName] == USD(0).value().getJson(JsonOptions::none)); if (!BEAST_EXPECT(result[jss::accepted].isMember(jss::offers))) @@ -109,8 +116,10 @@ class OwnerInfo_test : public beast::unit_test::suite return; BEAST_EXPECT(offers[0u][jss::Account] == alice.human()); - BEAST_EXPECT(offers[0u][sfTakerGets.fieldName] == XRP(1000).value().getJson(JsonOptions::none)); - BEAST_EXPECT(offers[0u][sfTakerPays.fieldName] == USD(1).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + offers[0u][sfTakerGets.fieldName] == XRP(1000).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + offers[0u][sfTakerPays.fieldName] == USD(1).value().getJson(JsonOptions::none)); // current ledger entry if (!BEAST_EXPECT(result[jss::current].isMember(jss::ripple_lines))) @@ -121,15 +130,23 @@ class OwnerInfo_test : public beast::unit_test::suite BEAST_EXPECT( lines[0u][sfBalance.fieldName] == - (STAmount{Issue{to_currency("CNY"), noAccount()}, -50}.value().getJson(JsonOptions::none))); - BEAST_EXPECT(lines[0u][sfHighLimit.fieldName] == alice["CNY"](1000).value().getJson(JsonOptions::none)); - BEAST_EXPECT(lines[0u][sfLowLimit.fieldName] == gw["CNY"](0).value().getJson(JsonOptions::none)); + (STAmount{Issue{to_currency("CNY"), noAccount()}, -50}.value().getJson( + JsonOptions::none))); + BEAST_EXPECT( + lines[0u][sfHighLimit.fieldName] == + alice["CNY"](1000).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + lines[0u][sfLowLimit.fieldName] == gw["CNY"](0).value().getJson(JsonOptions::none)); BEAST_EXPECT( lines[1u][sfBalance.fieldName] == - (STAmount{Issue{to_currency("USD"), noAccount()}, -50}.value().getJson(JsonOptions::none))); - BEAST_EXPECT(lines[1u][sfHighLimit.fieldName] == alice["USD"](1000).value().getJson(JsonOptions::none)); - BEAST_EXPECT(lines[1u][sfLowLimit.fieldName] == gw["USD"](0).value().getJson(JsonOptions::none)); + (STAmount{Issue{to_currency("USD"), noAccount()}, -50}.value().getJson( + JsonOptions::none))); + BEAST_EXPECT( + lines[1u][sfHighLimit.fieldName] == + alice["USD"](1000).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + lines[1u][sfLowLimit.fieldName] == gw["USD"](0).value().getJson(JsonOptions::none)); if (!BEAST_EXPECT(result[jss::current].isMember(jss::offers))) return; @@ -140,8 +157,10 @@ class OwnerInfo_test : public beast::unit_test::suite BEAST_EXPECT(offers[1u] == result[jss::accepted][jss::offers][0u]); BEAST_EXPECT(offers[0u][jss::Account] == alice.human()); - BEAST_EXPECT(offers[0u][sfTakerGets.fieldName] == XRP(1000).value().getJson(JsonOptions::none)); - BEAST_EXPECT(offers[0u][sfTakerPays.fieldName] == CNY(2).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + offers[0u][sfTakerGets.fieldName] == XRP(1000).value().getJson(JsonOptions::none)); + BEAST_EXPECT( + offers[0u][sfTakerPays.fieldName] == CNY(2).value().getJson(JsonOptions::none)); } public: diff --git a/src/test/rpc/RPCCall_test.cpp b/src/test/rpc/RPCCall_test.cpp index 26f7ed0f18..e4ef3aca6a 100644 --- a/src/test/rpc/RPCCall_test.cpp +++ b/src/test/rpc/RPCCall_test.cpp @@ -78,7 +78,9 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_channels: account and ledger hash.", __LINE__, - {"account_channels", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "rD5MbavGfiSC5m7mkxy1FANuT7s3HxqpoF"}, + {"account_channels", + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "rD5MbavGfiSC5m7mkxy1FANuT7s3HxqpoF"}, RPCCallTestData::no_exception, R"({ "method" : "account_channels", @@ -92,7 +94,9 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_channels: account and ledger index.", __LINE__, - {"account_channels", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "r9emE59aTWb85t64dAebKrxYMBTpzK5yR7"}, + {"account_channels", + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "r9emE59aTWb85t64dAebKrxYMBTpzK5yR7"}, RPCCallTestData::no_exception, R"({ "method" : "account_channels", @@ -106,7 +110,9 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_channels: two accounts.", __LINE__, - {"account_channels", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA"}, + {"account_channels", + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA"}, RPCCallTestData::no_exception, R"({ "method" : "account_channels", @@ -138,7 +144,10 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_channels: two accounts and ledger index.", __LINE__, - {"account_channels", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", "90210"}, + {"account_channels", + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", + "90210"}, RPCCallTestData::no_exception, R"({ "method" : "account_channels", @@ -491,7 +500,10 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_lines: peer and numeric ledger index.", __LINE__, - {"account_lines", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", "888888888"}, + {"account_lines", + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", + "888888888"}, RPCCallTestData::no_exception, R"({ "method" : "account_lines", @@ -506,7 +518,10 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_lines: peer and text ledger index.", __LINE__, - {"account_lines", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", "closed"}, + {"account_lines", + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", + "closed"}, RPCCallTestData::no_exception, R"({ "method" : "account_lines", @@ -655,7 +670,10 @@ static RPCCallTestData const rpcCallTestArray[] = { { "account_lines: invalid ledger selector.", __LINE__, - {"account_lines", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", "not_a_ledger"}, + {"account_lines", + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", + "not_a_ledger"}, RPCCallTestData::no_exception, R"({ "method" : "account_lines", @@ -1121,7 +1139,13 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_tx: ledger_index_min and _max plus trailing params.", __LINE__, - {"account_tx", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "-1", "413", "binary", "count", "descending"}, + {"account_tx", + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "-1", + "413", + "binary", + "count", + "descending"}, RPCCallTestData::no_exception, R"({ "method" : "account_tx", @@ -1155,7 +1179,14 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_tx: ledger_index_min and _max, limit, trailing args.", __LINE__, - {"account_tx", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "247", "-1", "300", "count", "descending", "binary"}, + {"account_tx", + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "247", + "-1", + "300", + "count", + "descending", + "binary"}, RPCCallTestData::no_exception, R"({ "method" : "account_tx", @@ -1191,7 +1222,14 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_tx: ledger_index_min and _max, limit, offset, trailing.", __LINE__, - {"account_tx", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "589", "590", "67", "45", "descending", "count"}, + {"account_tx", + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "589", + "590", + "67", + "45", + "descending", + "count"}, RPCCallTestData::no_exception, R"({ "method" : "account_tx", @@ -1342,7 +1380,14 @@ static RPCCallTestData const rpcCallTestArray[] = { {// Note: this really shouldn't throw, but does at the moment. "account_tx: RIPD-1570.", __LINE__, - {"account_tx", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "-1", "-1", "2", "false", "false", "false"}, + {"account_tx", + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "-1", + "-1", + "2", + "false", + "false", + "false"}, RPCCallTestData::bad_cast, R"()"}, @@ -1417,7 +1462,11 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"book_offers: add issuer and numeric ledger index.", __LINE__, - {"book_offers", "USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "EUR", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", "666"}, + {"book_offers", + "USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "EUR", + "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", + "666"}, RPCCallTestData::no_exception, R"({ "method" : "book_offers", @@ -1438,7 +1487,11 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"book_offers: add issuer and text ledger index.", __LINE__, - {"book_offers", "USD", "EUR/rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", "current"}, + {"book_offers", + "USD", + "EUR/rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", + "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", + "current"}, RPCCallTestData::no_exception, R"({ "method" : "book_offers", @@ -2332,7 +2385,10 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"deposit_authorized: with text ledger index.", __LINE__, - {"deposit_authorized", "source_account_NotValidated", "destination_account_NotValidated", "validated"}, + {"deposit_authorized", + "source_account_NotValidated", + "destination_account_NotValidated", + "validated"}, RPCCallTestData::no_exception, R"({ "method" : "deposit_authorized", @@ -2836,7 +2892,11 @@ static RPCCallTestData const rpcCallTestArray[] = { }, RPCCallTestData::bad_cast, R"()"}, - {"get_counts: count too large.", __LINE__, {"get_counts", "4294967296"}, RPCCallTestData::bad_cast, R"()"}, + {"get_counts: count too large.", + __LINE__, + {"get_counts", "4294967296"}, + RPCCallTestData::bad_cast, + R"()"}, // json // ------------------------------------------------------------------------ @@ -4537,7 +4597,12 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"sign: too many arguments.", __LINE__, - {"sign", "my_secret", R"({"json_argument":true})", "offline", "CounterpartySignature", "extra"}, + {"sign", + "my_secret", + R"({"json_argument":true})", + "offline", + "CounterpartySignature", + "extra"}, RPCCallTestData::no_exception, R"({ "method" : "sign", @@ -4612,7 +4677,11 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"sign_for: offline.", __LINE__, - {"sign_for", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "my_secret", R"({"json_argument":true})", "offline"}, + {"sign_for", + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "my_secret", + R"({"json_argument":true})", + "offline"}, RPCCallTestData::no_exception, R"({ "method" : "sign_for", @@ -4648,7 +4717,12 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"sign_for: too many arguments.", __LINE__, - {"sign_for", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "my_secret", R"({"json_argument":true})", "offline", "extra"}, + {"sign_for", + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "my_secret", + R"({"json_argument":true})", + "offline", + "extra"}, RPCCallTestData::no_exception, R"({ "method" : "sign_for", @@ -4681,7 +4755,11 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"sign_for: invalid final argument.", __LINE__, - {"sign_for", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "my_secret", R"({"json_argument":true})", "ofline"}, + {"sign_for", + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", + "my_secret", + R"({"json_argument":true})", + "ofline"}, RPCCallTestData::no_exception, R"({ "method" : "sign_for", @@ -4784,7 +4862,12 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"submit: too many arguments.", __LINE__, - {"submit", "my_secret", R"({"json_argument":true})", "offline", "CounterpartySignature", "extra"}, + {"submit", + "my_secret", + R"({"json_argument":true})", + "offline", + "CounterpartySignature", + "extra"}, RPCCallTestData::no_exception, R"({ "method" : "submit", @@ -5049,7 +5132,9 @@ static RPCCallTestData const rpcCallTestArray[] = { // ----------------------------------------------------------- {"transaction_entry: ledger index.", __LINE__, - {"transaction_entry", "0123456789ABCDEFGHIJKLMNOPQRSTUV0123456789ABCDEFGHIJKLMNOPQRSTUV", "4294967295"}, + {"transaction_entry", + "0123456789ABCDEFGHIJKLMNOPQRSTUV0123456789ABCDEFGHIJKLMNOPQRSTUV", + "4294967295"}, RPCCallTestData::no_exception, R"({ "method" : "transaction_entry", @@ -5063,7 +5148,9 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"transaction_entry: text ledger index.", __LINE__, - {"transaction_entry", "0123456789ABCDEFGHIJKLMNOPQRSTUV0123456789ABCDEFGHIJKLMNOPQRSTUV", "current"}, + {"transaction_entry", + "0123456789ABCDEFGHIJKLMNOPQRSTUV0123456789ABCDEFGHIJKLMNOPQRSTUV", + "current"}, RPCCallTestData::no_exception, R"({ "method" : "transaction_entry", @@ -5110,7 +5197,10 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"transaction_entry: too many arguments.", __LINE__, - {"transaction_entry", "0123456789ABCDEFGHIJKLMNOPQRSTUV0123456789ABCDEFGHIJKLMNOPQRSTUV", "validated", "extra"}, + {"transaction_entry", + "0123456789ABCDEFGHIJKLMNOPQRSTUV0123456789ABCDEFGHIJKLMNOPQRSTUV", + "validated", + "extra"}, RPCCallTestData::no_exception, R"({ "method" : "transaction_entry", @@ -5759,7 +5849,9 @@ public: testRPCCall(unsigned apiVersion) { testcase << "RPCCall API version " << apiVersion; - if (!BEAST_EXPECT(apiVersion >= RPC::apiMinimumSupportedVersion && apiVersion <= RPC::apiMaximumValidVersion)) + if (!BEAST_EXPECT( + apiVersion >= RPC::apiMinimumSupportedVersion && + apiVersion <= RPC::apiMaximumValidVersion)) return; test::jtx::Env env(*this, makeNetworkConfig(11111)); // Used only for its Journal. @@ -5772,7 +5864,8 @@ public: std::vector const args{rpcCallTest.args.begin(), rpcCallTest.args.end()}; - char const* const expVersioned = (apiVersion - RPC::apiMinimumSupportedVersion) < rpcCallTest.exp.size() + char const* const expVersioned = + (apiVersion - RPC::apiMinimumSupportedVersion) < rpcCallTest.exp.size() ? rpcCallTest.exp[apiVersion - RPC::apiMinimumSupportedVersion] : rpcCallTest.exp.back(); @@ -5785,7 +5878,8 @@ public: } catch (std::bad_cast const&) { - if ((rpcCallTest.throwsWhat == RPCCallTestData::bad_cast) && (std::strlen(expVersioned) == 0)) + if ((rpcCallTest.throwsWhat == RPCCallTestData::bad_cast) && + (std::strlen(expVersioned) == 0)) { pass(); } @@ -5803,8 +5897,8 @@ public: // Lambda to remove the "params[0u]:error_code" field if present. // Error codes are not expected to be stable between releases. auto rmErrorCode = [](Json::Value& json) { - if (json.isMember(jss::params) && json[jss::params].isArray() && json[jss::params].size() > 0 && - json[jss::params][0u].isObject()) + if (json.isMember(jss::params) && json[jss::params].isArray() && + json[jss::params].size() > 0 && json[jss::params][0u].isObject()) { json[jss::params][0u].removeMember(jss::error_code); } diff --git a/src/test/rpc/RobustTransaction_test.cpp b/src/test/rpc/RobustTransaction_test.cpp index 0934543fe0..0d47a39573 100644 --- a/src/test/rpc/RobustTransaction_test.cpp +++ b/src/test/rpc/RobustTransaction_test.cpp @@ -185,8 +185,8 @@ public: } // Check balance - auto ff = - jv[jss::result][jss::transactions][0u][jss::meta]["AffectedNodes"][1u]["ModifiedNode"]["FinalFields"]; + auto ff = jv[jss::result][jss::transactions][0u][jss::meta]["AffectedNodes"][1u] + ["ModifiedNode"]["FinalFields"]; BEAST_EXPECT(ff[jss::Account] == Account("bob").human()); BEAST_EXPECT(ff["Balance"] == "10001000000"); } @@ -261,7 +261,8 @@ public: // Wait for the jobqueue to process everything env.app().getJobQueue().rendezvous(); - BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jval) { return jval[jss::type] == "ledgerClosed"; })); + BEAST_EXPECT(wsc->findMsg( + 5s, [&](auto const& jval) { return jval[jss::type] == "ledgerClosed"; })); } { @@ -313,7 +314,8 @@ public: // Wait for the jobqueue to process everything env.app().getJobQueue().rendezvous(); - BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jval) { return jval[jss::type] == "ledgerClosed"; })); + BEAST_EXPECT(wsc->findMsg( + 5s, [&](auto const& jval) { return jval[jss::type] == "ledgerClosed"; })); } { @@ -348,8 +350,8 @@ public: } // Check balance - auto ff = - jv[jss::result][jss::transactions][0u][jss::meta]["AffectedNodes"][1u]["ModifiedNode"]["FinalFields"]; + auto ff = jv[jss::result][jss::transactions][0u][jss::meta]["AffectedNodes"][1u] + ["ModifiedNode"]["FinalFields"]; BEAST_EXPECT(ff[jss::Account] == Account("bob").human()); BEAST_EXPECT(ff["Balance"] == "10001000000"); } @@ -398,8 +400,9 @@ public: { // Check stream update - BEAST_EXPECT(wsc->findMsg( - 5s, [&](auto const& jv) { return jv[jss::transaction][jss::TransactionType] == jss::AccountSet; })); + BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { + return jv[jss::transaction][jss::TransactionType] == jss::AccountSet; + })); } { diff --git a/src/test/rpc/Roles_test.cpp b/src/test/rpc/Roles_test.cpp index 1750532a10..a4f9de2284 100644 --- a/src/test/rpc/Roles_test.cpp +++ b/src/test/rpc/Roles_test.cpp @@ -29,7 +29,8 @@ class Roles_test : public beast::unit_test::suite Env env(*this); BEAST_EXPECT(env.rpc("ping")["result"]["role"] == "admin"); - BEAST_EXPECT(makeWSClient(env.app().config())->invoke("ping")["result"]["unlimited"].asBool()); + BEAST_EXPECT( + makeWSClient(env.app().config())->invoke("ping")["result"]["unlimited"].asBool()); } { Env env{*this, envconfig(no_admin)}; @@ -225,7 +226,8 @@ class Roles_test : public beast::unit_test::suite { Env env{*this, envconfig(admin_localnet)}; BEAST_EXPECT(env.rpc("ping")["result"]["role"] == "admin"); - BEAST_EXPECT(makeWSClient(env.app().config())->invoke("ping")["result"]["unlimited"].asBool()); + BEAST_EXPECT( + makeWSClient(env.app().config())->invoke("ping")["result"]["unlimited"].asBool()); } { diff --git a/src/test/rpc/ServerDefinitions_test.cpp b/src/test/rpc/ServerDefinitions_test.cpp index 20bd6ba363..69533939cd 100644 --- a/src/test/rpc/ServerDefinitions_test.cpp +++ b/src/test/rpc/ServerDefinitions_test.cpp @@ -42,8 +42,10 @@ public: BEAST_EXPECT(firstField[1][jss::type].asString() == "Unknown"); } - BEAST_EXPECT(result[jss::result][jss::LEDGER_ENTRY_TYPES]["AccountRoot"].asUInt() == 97); - BEAST_EXPECT(result[jss::result][jss::TRANSACTION_RESULTS]["tecDIR_FULL"].asUInt() == 121); + BEAST_EXPECT( + result[jss::result][jss::LEDGER_ENTRY_TYPES]["AccountRoot"].asUInt() == 97); + BEAST_EXPECT( + result[jss::result][jss::TRANSACTION_RESULTS]["tecDIR_FULL"].asUInt() == 121); BEAST_EXPECT(result[jss::result][jss::TRANSACTION_TYPES]["Payment"].asUInt() == 0); BEAST_EXPECT(result[jss::result][jss::TYPES]["AccountID"].asUInt() == 8); diff --git a/src/test/rpc/ServerInfo_test.cpp b/src/test/rpc/ServerInfo_test.cpp index 054c3e563a..9fdfe5e13b 100644 --- a/src/test/rpc/ServerInfo_test.cpp +++ b/src/test/rpc/ServerInfo_test.cpp @@ -1,10 +1,10 @@ #include -#include #include #include #include +#include #include @@ -81,7 +81,8 @@ admin = 127.0.0.1 auto const& git = info[jss::git]; BEAST_EXPECT(git.isMember(jss::hash) || git.isMember(jss::branch)); BEAST_EXPECT( - !git.isMember(jss::hash) || (git[jss::hash].isString() && git[jss::hash].asString().size() == 40)); + !git.isMember(jss::hash) || + (git[jss::hash].isString() && git[jss::hash].asString().size() == 40)); BEAST_EXPECT( !git.isMember(jss::branch) || (git[jss::branch].isString() && git[jss::branch].asString().size() != 0)); @@ -115,7 +116,9 @@ admin = 127.0.0.1 BEAST_EXPECT(!result[jss::result].isMember(jss::error)); BEAST_EXPECT(result[jss::result][jss::status] == "success"); BEAST_EXPECT(result[jss::result].isMember(jss::info)); - BEAST_EXPECT(result[jss::result][jss::info][jss::pubkey_validator] == validator_data::public_key); + BEAST_EXPECT( + result[jss::result][jss::info][jss::pubkey_validator] == + validator_data::public_key); auto const& ports = result[jss::result][jss::info][jss::ports]; BEAST_EXPECT(ports.isArray() && ports.size() == 3); diff --git a/src/test/rpc/Simulate_test.cpp b/src/test/rpc/Simulate_test.cpp index 194b0296ec..d1b1cd02fc 100644 --- a/src/test/rpc/Simulate_test.cpp +++ b/src/test/rpc/Simulate_test.cpp @@ -59,7 +59,8 @@ class Simulate_test : public beast::unit_test::suite int const expectedSequence, XRPAmount const& expectedFee) { - return checkBasicReturnValidity(result, tx, expectedSequence, expectedFee.jsonClipped().asString()); + return checkBasicReturnValidity( + result, tx, expectedSequence, expectedFee.jsonClipped().asString()); } void @@ -106,8 +107,11 @@ class Simulate_test : public beast::unit_test::suite testTxJsonMetadataField( jtx::Env& env, Json::Value const& tx, - std::function const& - validate, + std::function const& validate, Json::Value const& expectedMetadataKey, Json::Value const& expectedMetadataValue) { @@ -115,8 +119,13 @@ class Simulate_test : public beast::unit_test::suite Json::Value params; params[jss::tx_json] = tx; - validate(env.rpc("json", "simulate", to_string(params)), tx, expectedMetadataKey, expectedMetadataValue); - validate(env.rpc("simulate", to_string(tx)), tx, expectedMetadataKey, expectedMetadataValue); + validate( + env.rpc("json", "simulate", to_string(params)), + tx, + expectedMetadataKey, + expectedMetadataValue); + validate( + env.rpc("simulate", to_string(tx)), tx, expectedMetadataKey, expectedMetadataValue); BEAST_EXPECTS(env.current()->txCount() == 0, std::to_string(env.current()->txCount())); } @@ -147,7 +156,9 @@ class Simulate_test : public beast::unit_test::suite // No params Json::Value const params = Json::objectValue; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT(resp[jss::result][jss::error_message] == "Neither `tx_blob` nor `tx_json` included."); + BEAST_EXPECT( + resp[jss::result][jss::error_message] == + "Neither `tx_blob` nor `tx_json` included."); } { // Providing both `tx_json` and `tx_blob` @@ -156,7 +167,9 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_blob] = "1200"; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT(resp[jss::result][jss::error_message] == "Can only include one of `tx_blob` and `tx_json`."); + BEAST_EXPECT( + resp[jss::result][jss::error_message] == + "Can only include one of `tx_blob` and `tx_json`."); } { // `binary` isn't a boolean @@ -180,7 +193,8 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = Json::objectValue; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT(resp[jss::result][jss::error_message] == "Missing field 'tx.TransactionType'."); + BEAST_EXPECT( + resp[jss::result][jss::error_message] == "Missing field 'tx.TransactionType'."); } { // No tx.Account @@ -214,7 +228,8 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = ""; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'tx_json', not object."); + BEAST_EXPECT( + resp[jss::result][jss::error_message] == "Invalid field 'tx_json', not object."); } { // `seed` field included @@ -269,7 +284,9 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT(resp[jss::result][jss::error_exception] == "Field 'Destination' is required but missing."); + BEAST_EXPECT( + resp[jss::result][jss::error_exception] == + "Field 'Destination' is required but missing."); } { // Bad account @@ -281,7 +298,8 @@ class Simulate_test : public beast::unit_test::suite auto const resp = env.rpc("json", "simulate", to_string(params)); BEAST_EXPECTS( - resp[jss::result][jss::error] == "srcActMalformed", resp[jss::result][jss::error].toStyledString()); + resp[jss::result][jss::error] == "srcActMalformed", + resp[jss::result][jss::error].toStyledString()); BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'tx.Account'."); } { @@ -330,7 +348,8 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT(resp[jss::result][jss::error_message] == "Field 'tx_json.foo' is unknown."); + BEAST_EXPECT( + resp[jss::result][jss::error_message] == "Field 'tx_json.foo' is unknown."); } { // non-`"binary"` second param for CLI @@ -350,7 +369,8 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT(resp[jss::result][jss::error_message] == "Transaction should not be signed."); + BEAST_EXPECT( + resp[jss::result][jss::error_message] == "Transaction should not be signed."); } { // Signed multisig transaction @@ -371,7 +391,8 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT(resp[jss::result][jss::error_message] == "Transaction should not be signed."); + BEAST_EXPECT( + resp[jss::result][jss::error_message] == "Transaction should not be signed."); } } @@ -459,7 +480,8 @@ class Simulate_test : public beast::unit_test::suite BEAST_EXPECT(result[jss::engine_result] == "tesSUCCESS"); BEAST_EXPECT(result[jss::engine_result_code] == 0); BEAST_EXPECT( - result[jss::engine_result_message] == "The simulated transaction would have been applied."); + result[jss::engine_result_message] == + "The simulated transaction would have been applied."); if (BEAST_EXPECT(result.isMember(jss::meta) || result.isMember(jss::meta_blob))) { @@ -581,11 +603,14 @@ class Simulate_test : public beast::unit_test::suite auto finalFields = modifiedNode[sfFinalFields]; BEAST_EXPECT( finalFields[sfBalance] == - std::to_string(100'000'000'000'000'000 - env.current()->fees().base.drops())); + std::to_string( + 100'000'000'000'000'000 - + env.current()->fees().base.drops())); } } BEAST_EXPECT(metadata[sfTransactionIndex.jsonName] == 0); - BEAST_EXPECT(metadata[sfTransactionResult.jsonName] == "tecNO_DST_INSUF_XRP"); + BEAST_EXPECT( + metadata[sfTransactionResult.jsonName] == "tecNO_DST_INSUF_XRP"); } }; @@ -634,12 +659,14 @@ class Simulate_test : public beast::unit_test::suite result, tx, env.seq(alice), - tx.isMember(jss::Signers) ? env.current()->fees().base * 2 : env.current()->fees().base); + tx.isMember(jss::Signers) ? env.current()->fees().base * 2 + : env.current()->fees().base); BEAST_EXPECT(result[jss::engine_result] == "tesSUCCESS"); BEAST_EXPECT(result[jss::engine_result_code] == 0); BEAST_EXPECT( - result[jss::engine_result_message] == "The simulated transaction would have been applied."); + result[jss::engine_result_message] == + "The simulated transaction would have been applied."); if (BEAST_EXPECT(result.isMember(jss::meta) || result.isMember(jss::meta_blob))) { @@ -713,7 +740,8 @@ class Simulate_test : public beast::unit_test::suite std::function const& testSimulation = [&](Json::Value const& resp, Json::Value const& tx) { auto result = resp[jss::result]; - checkBasicReturnValidity(result, tx, env.seq(env.master), env.current()->fees().base); + checkBasicReturnValidity( + result, tx, env.seq(env.master), env.current()->fees().base); BEAST_EXPECT(result[jss::engine_result] == "tefMASTER_DISABLED"); BEAST_EXPECT(result[jss::engine_result_code] == -188); @@ -766,11 +794,13 @@ class Simulate_test : public beast::unit_test::suite std::function const& testSimulation = [&](Json::Value const& resp, Json::Value const& tx) { auto result = resp[jss::result]; - checkBasicReturnValidity(result, tx, env.seq(env.master), env.current()->fees().base * 2); + checkBasicReturnValidity( + result, tx, env.seq(env.master), env.current()->fees().base * 2); BEAST_EXPECT(result[jss::engine_result] == "temINVALID"); BEAST_EXPECT(result[jss::engine_result_code] == -277); - BEAST_EXPECT(result[jss::engine_result_message] == "The transaction is ill-formed."); + BEAST_EXPECT( + result[jss::engine_result_message] == "The transaction is ill-formed."); BEAST_EXPECT(!result.isMember(jss::meta) && !result.isMember(jss::meta_blob)); }; @@ -826,12 +856,16 @@ class Simulate_test : public beast::unit_test::suite { auto validateOutput = [&](Json::Value const& resp, Json::Value const& tx) { auto result = resp[jss::result]; - checkBasicReturnValidity(result, tx, env.seq(alice), env.current()->fees().base * 2); + checkBasicReturnValidity( + result, tx, env.seq(alice), env.current()->fees().base * 2); BEAST_EXPECTS( - result[jss::engine_result] == "tefBAD_SIGNATURE", result[jss::engine_result].toStyledString()); + result[jss::engine_result] == "tefBAD_SIGNATURE", + result[jss::engine_result].toStyledString()); BEAST_EXPECT(result[jss::engine_result_code] == -186); - BEAST_EXPECT(result[jss::engine_result_message] == "A signature is provided for a non-signer."); + BEAST_EXPECT( + result[jss::engine_result_message] == + "A signature is provided for a non-signer."); BEAST_EXPECT(!result.isMember(jss::meta) && !result.isMember(jss::meta_blob)); }; @@ -913,12 +947,15 @@ class Simulate_test : public beast::unit_test::suite for (auto const& node : metadata[sfAffectedNodes.jsonName]) { if (node.isMember(sfDeletedNode.jsonName) && - node[sfDeletedNode.jsonName][sfLedgerEntryType.jsonName].asString() == "Credential") + node[sfDeletedNode.jsonName][sfLedgerEntryType.jsonName] + .asString() == "Credential") { - auto const deleted = node[sfDeletedNode.jsonName][sfFinalFields.jsonName]; + auto const deleted = + node[sfDeletedNode.jsonName][sfFinalFields.jsonName]; found = deleted[jss::Issuer] == issuer.human() && deleted[jss::Subject] == subject.human() && - deleted["CredentialType"] == strHex(std::string_view(credType)); + deleted["CredentialType"] == + strHex(std::string_view(credType)); break; } } @@ -952,7 +989,8 @@ class Simulate_test : public beast::unit_test::suite auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle[jss::result].isMember(jss::node) && + jle[jss::result][jss::node].isMember("LedgerEntryType") && jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && jle[jss::result][jss::node][jss::Issuer] == issuer.human() && jle[jss::result][jss::node][jss::Subject] == subject.human() && @@ -982,7 +1020,8 @@ class Simulate_test : public beast::unit_test::suite BEAST_EXPECT(result[jss::engine_result] == "tesSUCCESS"); BEAST_EXPECT(result[jss::engine_result_code] == 0); BEAST_EXPECT( - result[jss::engine_result_message] == "The simulated transaction would have been applied."); + result[jss::engine_result_message] == + "The simulated transaction would have been applied."); if (BEAST_EXPECT(result.isMember(jss::meta) || result.isMember(jss::meta_blob))) { @@ -1056,7 +1095,8 @@ class Simulate_test : public beast::unit_test::suite BEAST_EXPECT(result[jss::engine_result] == "tesSUCCESS"); BEAST_EXPECT(result[jss::engine_result_code] == 0); BEAST_EXPECT( - result[jss::engine_result_message] == "The simulated transaction would have been applied."); + result[jss::engine_result_message] == + "The simulated transaction would have been applied."); if (BEAST_EXPECT(result.isMember(jss::meta) || result.isMember(jss::meta_blob))) { @@ -1098,7 +1138,8 @@ class Simulate_test : public beast::unit_test::suite Json::Value mptIssuanceId = to_string(makeMptID(env.seq(alice), alice)); // test mpt issuance id - testTxJsonMetadataField(env, tx, validateOutput, jss::mpt_issuance_id, mptIssuanceId); + testTxJsonMetadataField( + env, tx, validateOutput, jss::mpt_issuance_id, mptIssuanceId); } } } diff --git a/src/test/rpc/Status_test.cpp b/src/test/rpc/Status_test.cpp index ac387196fe..01fc81430f 100644 --- a/src/test/rpc/Status_test.cpp +++ b/src/test/rpc/Status_test.cpp @@ -112,7 +112,11 @@ private: template void - expectFill(std::string const& label, Type status, Status::Strings messages, std::string const& message) + expectFill( + std::string const& label, + Type status, + Status::Strings messages, + std::string const& message) { value_.clear(); fillJson(Status(status, messages)); @@ -124,14 +128,18 @@ private: expect(bool(error), prefix + "No error."); auto code = error[jss::code].asInt(); - expect(status == code, prefix + "Wrong status " + std::to_string(code) + " != " + std::to_string(status)); + expect( + status == code, + prefix + "Wrong status " + std::to_string(code) + " != " + std::to_string(status)); auto m = error[jss::message].asString(); expect(m == message, m + " != " + message); auto d = error[jss::data]; size_t s1 = d.size(), s2 = messages.size(); - expect(s1 == s2, prefix + "Data sizes differ " + std::to_string(s1) + " != " + std::to_string(s2)); + expect( + s1 == s2, + prefix + "Data sizes differ " + std::to_string(s1) + " != " + std::to_string(s2)); for (auto i = 0; i < std::min(s1, s2); ++i) { auto ds = d[i].asString(); @@ -145,7 +153,11 @@ private: testcase("error"); expectFill("temBAD_AMOUNT", temBAD_AMOUNT, {}, "temBAD_AMOUNT: Malformed: Bad amount."); - expectFill("rpcBAD_SYNTAX", rpcBAD_SYNTAX, {"An error.", "Another error."}, "badSyntax: Syntax error."); + expectFill( + "rpcBAD_SYNTAX", + rpcBAD_SYNTAX, + {"An error.", "Another error."}, + "badSyntax: Syntax error."); expectFill("integer message", 23, {"Stuff."}, "23"); } diff --git a/src/test/rpc/Subscribe_test.cpp b/src/test/rpc/Subscribe_test.cpp index cce45fb4ef..d83711324d 100644 --- a/src/test/rpc/Subscribe_test.cpp +++ b/src/test/rpc/Subscribe_test.cpp @@ -3,14 +3,15 @@ #include #include -#include -#include #include #include +#include #include #include #include +#include +#include #include @@ -57,7 +58,8 @@ public: env.app().getOPs().reportFeeChange(); // Check stream update - BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { return jv[jss::type] == "serverStatus"; })); + BEAST_EXPECT( + wsc->findMsg(5s, [&](auto const& jv) { return jv[jss::type] == "serverStatus"; })); } { @@ -106,7 +108,8 @@ public: BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::result][jss::ledger_index] == 2); - BEAST_EXPECT(jv[jss::result][jss::network_id] == env.app().config().NETWORK_ID); + BEAST_EXPECT( + jv[jss::result][jss::network_id] == env.app().getNetworkIDService().getNetworkID()); } { @@ -115,7 +118,8 @@ public: // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::ledger_index] == 3 && jv[jss::network_id] == env.app().config().NETWORK_ID; + return jv[jss::ledger_index] == 3 && + jv[jss::network_id] == env.app().getNetworkIDService().getNetworkID(); })); } @@ -125,7 +129,8 @@ public: // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::ledger_index] == 4 && jv[jss::network_id] == env.app().config().NETWORK_ID; + return jv[jss::ledger_index] == 4 && + jv[jss::network_id] == env.app().getNetworkIDService().getNetworkID(); })); } @@ -170,7 +175,8 @@ public: // Check stream update for payment transaction BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"][jss::Account] // + return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"] + [jss::Account] // == Account("alice").human() && jv[jss::transaction][jss::TransactionType] // == jss::Payment && @@ -184,8 +190,8 @@ public: // Check stream update for accountset transaction BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"]["FinalFields"][jss::Account] == - Account("alice").human(); + return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"]["FinalFields"] + [jss::Account] == Account("alice").human(); })); env.fund(XRP(10000), "bob"); @@ -193,7 +199,8 @@ public: // Check stream update for payment transaction BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"][jss::Account] // + return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"] + [jss::Account] // == Account("bob").human() && jv[jss::transaction][jss::TransactionType] // == jss::Payment && @@ -207,8 +214,8 @@ public: // Check stream update for accountset transaction BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"]["FinalFields"][jss::Account] == - Account("bob").human(); + return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"]["FinalFields"] + [jss::Account] == Account("bob").human(); })); } @@ -251,13 +258,13 @@ public: // Check stream updates BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][1u]["ModifiedNode"]["FinalFields"][jss::Account] == - Account("alice").human(); + return jv[jss::meta]["AffectedNodes"][1u]["ModifiedNode"]["FinalFields"] + [jss::Account] == Account("alice").human(); })); BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"]["LowLimit"][jss::issuer] == - Account("alice").human(); + return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"]["LowLimit"] + [jss::issuer] == Account("alice").human(); })); } @@ -307,7 +314,8 @@ public: // Check stream update for payment transaction BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"][jss::Account] // + return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"] + [jss::Account] // == Account("alice").human() && jv[jss::close_time_iso] // == "2000-01-01T00:00:10Z" && @@ -330,8 +338,8 @@ public: // Check stream update for accountset transaction BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"]["FinalFields"][jss::Account] == - Account("alice").human(); + return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"]["FinalFields"] + [jss::Account] == Account("alice").human(); })); } @@ -396,7 +404,8 @@ public: std::string const valPublicKey = toBase58( TokenType::NodePublic, - derivePublicKey(KeyType::secp256k1, generateSecretKey(KeyType::secp256k1, *parsedseed))); + derivePublicKey( + KeyType::secp256k1, generateSecretKey(KeyType::secp256k1, *parsedseed))); auto wsc = makeWSClient(env.app().config()); Json::Value stream; @@ -451,7 +460,7 @@ public: if (!jv.isMember(jss::validated_hash)) return false; - uint32_t netID = env.app().config().NETWORK_ID; + uint32_t netID = env.app().getNetworkIDService().getNetworkID(); if (!jv.isMember(jss::network_id) || jv[jss::network_id] != netID) return false; @@ -510,7 +519,7 @@ public: jv[jss::streams][0u] = "ledger"; jr = env.rpc("json", "subscribe", to_string(jv))[jss::result]; BEAST_EXPECT(jr[jss::status] == "success"); - BEAST_EXPECT(jr[jss::network_id] == env.app().config().NETWORK_ID); + BEAST_EXPECT(jr[jss::network_id] == env.app().getNetworkIDService().getNetworkID()); jr = env.rpc("json", "unsubscribe", to_string(jv))[jss::result]; BEAST_EXPECT(jr[jss::status] == "success"); @@ -678,7 +687,8 @@ public: // NOTE: this error is slightly incongruous with the // equivalent source currency error BEAST_EXPECT(jr[jss::error] == "dstAmtMalformed"); - BEAST_EXPECT(jr[jss::error_message] == "Destination amount/currency/issuer is malformed."); + BEAST_EXPECT( + jr[jss::error_message] == "Destination amount/currency/issuer is malformed."); } { @@ -692,7 +702,8 @@ public: // NOTE: this error is slightly incongruous with the // equivalent source currency error BEAST_EXPECT(jr[jss::error] == "dstAmtMalformed"); - BEAST_EXPECT(jr[jss::error_message] == "Destination amount/currency/issuer is malformed."); + BEAST_EXPECT( + jr[jss::error_message] == "Destination amount/currency/issuer is malformed."); } { @@ -850,7 +861,9 @@ public: * and in the same order. * If sizeCompare is false, txHistoryVec is allowed to be larger. */ - auto hashCompare = [](IdxHashVec const& accountVec, IdxHashVec const& txHistoryVec, bool sizeCompare) -> bool { + auto hashCompare = [](IdxHashVec const& accountVec, + IdxHashVec const& txHistoryVec, + bool sizeCompare) -> bool { if (accountVec.empty() || txHistoryVec.empty()) return false; if (sizeCompare && accountVec.size() != (txHistoryVec.size())) @@ -979,7 +992,8 @@ public: auto wscTxHistory = makeWSClient(env.app().config()); Json::Value request; request[jss::account_history_tx_stream] = Json::objectValue; - request[jss::account_history_tx_stream][jss::account] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; + request[jss::account_history_tx_stream][jss::account] = + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; auto jv = wscTxHistory->invoke("subscribe", request); if (!BEAST_EXPECT(goodSubRPC(jv))) return; @@ -1005,7 +1019,8 @@ public: r = getTxHash(*wscTxHistory, bobFullHistoryVec, 1); if (!BEAST_EXPECT(r.first && r.second)) return; - BEAST_EXPECT(std::get<1>(bobFullHistoryVec.back()) == std::get<1>(genesisFullHistoryVec.back())); + BEAST_EXPECT( + std::get<1>(bobFullHistoryVec.back()) == std::get<1>(genesisFullHistoryVec.back())); /* * unsubscribe to prepare next test @@ -1013,7 +1028,8 @@ public: jv = wscTxHistory->invoke("unsubscribe", request); if (!BEAST_EXPECT(goodSubRPC(jv))) return; - request[jss::account_history_tx_stream][jss::account] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; + request[jss::account_history_tx_stream][jss::account] = + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; jv = wscTxHistory->invoke("unsubscribe", request); BEAST_EXPECT(goodSubRPC(jv)); @@ -1030,13 +1046,15 @@ public: BEAST_EXPECT(getTxHash(*wscTxHistory, bobFullHistoryVec, 31).second); jv = wscTxHistory->invoke("unsubscribe", request); - request[jss::account_history_tx_stream][jss::account] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; + request[jss::account_history_tx_stream][jss::account] = + "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; jv = wscTxHistory->invoke("subscribe", request); genesisFullHistoryVec.clear(); BEAST_EXPECT(getTxHash(*wscTxHistory, genesisFullHistoryVec, 31).second); jv = wscTxHistory->invoke("unsubscribe", request); - BEAST_EXPECT(std::get<1>(bobFullHistoryVec.back()) == std::get<1>(genesisFullHistoryVec.back())); + BEAST_EXPECT( + std::get<1>(bobFullHistoryVec.back()) == std::get<1>(genesisFullHistoryVec.back())); } { @@ -1157,7 +1175,9 @@ public: env.close(); // many payments, and close lots of ledgers - auto oneRound = [&](int numPayments) { return sendPayments(env, alice, carol, numPayments, 300); }; + auto oneRound = [&](int numPayments) { + return sendPayments(env, alice, carol, numPayments, 300); + }; // subscribe Json::Value request; @@ -1199,7 +1219,8 @@ public: using namespace jtx; using namespace std::chrono_literals; FeatureBitset const all{ - jtx::testable_amendments() | featurePermissionedDomains | featureCredentials | featurePermissionedDEX}; + jtx::testable_amendments() | featurePermissionedDomains | featureCredentials | + featurePermissionedDEX}; Env env(*this, all); PermissionedDEX permDex(env); @@ -1231,7 +1252,8 @@ public: auto const jrOffer = jv[jss::changes][0u]; return (jv[jss::changes][0u][jss::domain]).asString() == strHex(domainID) && - jrOffer[jss::currency_a].asString() == "XRP_drops" && jrOffer[jss::volume_a].asString() == "5000000" && + jrOffer[jss::currency_a].asString() == "XRP_drops" && + jrOffer[jss::volume_a].asString() == "5000000" && jrOffer[jss::currency_b].asString() == "rHUKYAZyUFn8PCZWbPfwHfbVQXTYrYKkHb/USD" && jrOffer[jss::volume_b].asString() == "5"; })); @@ -1380,7 +1402,9 @@ public: // Alice creates sell offer and set broker as destination uint256 const offerAliceToBroker = keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId, drops(1)), token::destination(broker), txflags(tfSellNFToken)); + env(token::createOffer(alice, nftId, drops(1)), + token::destination(broker), + txflags(tfSellNFToken)); env.close(); verifyNFTokenOfferID(offerAliceToBroker); diff --git a/src/test/rpc/TransactionEntry_test.cpp b/src/test/rpc/TransactionEntry_test.cpp index 6302de4efa..14e75d04da 100644 --- a/src/test/rpc/TransactionEntry_test.cpp +++ b/src/test/rpc/TransactionEntry_test.cpp @@ -55,7 +55,8 @@ class TransactionEntry_test : public beast::unit_test::suite BEAST_EXPECT(result[jss::status] == "error"); } - std::string const txHash{"E2FE8D4AF3FCC3944DDF6CD8CDDC5E3F0AD50863EF8919AFEF10CB6408CD4D05"}; + std::string const txHash{ + "E2FE8D4AF3FCC3944DDF6CD8CDDC5E3F0AD50863EF8919AFEF10CB6408CD4D05"}; // Command line format { @@ -194,17 +195,19 @@ class TransactionEntry_test : public beast::unit_test::suite params[jss::ledger_hash] = resIndex[jss::ledger_hash]; params[jss::tx_hash] = txhash; params[jss::api_version] = apiVersion; - Json::Value const resHash = env.client().invoke("transaction_entry", params)[jss::result]; + Json::Value const resHash = + env.client().invoke("transaction_entry", params)[jss::result]; BEAST_EXPECT(resHash == resIndex); } // Use the command line form with the index. - Json::Value const clIndex{env.rpc(apiVersion, "transaction_entry", txhash, std::to_string(index))}; + Json::Value const clIndex{ + env.rpc(apiVersion, "transaction_entry", txhash, std::to_string(index))}; BEAST_EXPECT(clIndex["result"] == resIndex); // Use the command line form with the ledger_hash. - Json::Value const clHash{ - env.rpc(apiVersion, "transaction_entry", txhash, resIndex[jss::ledger_hash].asString())}; + Json::Value const clHash{env.rpc( + apiVersion, "transaction_entry", txhash, resIndex[jss::ledger_hash].asString())}; BEAST_EXPECT(clHash["result"] == resIndex); }; @@ -213,11 +216,13 @@ class TransactionEntry_test : public beast::unit_test::suite env.fund(XRP(10000), A1); auto fund_1_tx = to_string(env.tx()->getTransactionID()); - BEAST_EXPECT(fund_1_tx == "F4E9DF90D829A9E8B423FF68C34413E240D8D8BB0EFD080DF08114ED398E2506"); + BEAST_EXPECT( + fund_1_tx == "F4E9DF90D829A9E8B423FF68C34413E240D8D8BB0EFD080DF08114ED398E2506"); env.fund(XRP(10000), A2); auto fund_2_tx = to_string(env.tx()->getTransactionID()); - BEAST_EXPECT(fund_2_tx == "6853CD8226A05068C951CB1F54889FF4E40C5B440DC1C5BA38F114C4E0B1E705"); + BEAST_EXPECT( + fund_2_tx == "6853CD8226A05068C951CB1F54889FF4E40C5B440DC1C5BA38F114C4E0B1E705"); env.close(); @@ -257,7 +262,8 @@ class TransactionEntry_test : public beast::unit_test::suite // refunds fees with a payment after TrustSet..so just ignore the type // in the check below auto trust_tx = to_string(env.tx()->getTransactionID()); - BEAST_EXPECT(trust_tx == "C992D97D88FF444A1AB0C06B27557EC54B7F7DA28254778E60238BEA88E0C101"); + BEAST_EXPECT( + trust_tx == "C992D97D88FF444A1AB0C06B27557EC54B7F7DA28254778E60238BEA88E0C101"); env(pay(A2, A1, A2["USD"](5))); auto pay_tx = to_string(env.tx()->getTransactionID()); @@ -305,7 +311,8 @@ class TransactionEntry_test : public beast::unit_test::suite env(offer(A2, XRP(100), A2["USD"](1))); auto offer_tx = to_string(env.tx()->getTransactionID()); - BEAST_EXPECT(offer_tx == "5FCC1A27A7664F82A0CC4BE5766FBBB7C560D52B93AA7B550CD33B27AEC7EFFB"); + BEAST_EXPECT( + offer_tx == "5FCC1A27A7664F82A0CC4BE5766FBBB7C560D52B93AA7B550CD33B27AEC7EFFB"); env.close(); check_tx( diff --git a/src/test/rpc/Transaction_test.cpp b/src/test/rpc/Transaction_test.cpp index acc8bccf61..ebe3f3135d 100644 --- a/src/test/rpc/Transaction_test.cpp +++ b/src/test/rpc/Transaction_test.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -65,7 +66,11 @@ class Transaction_test : public beast::unit_test::suite auto const& tx = txns[i]; auto const& meta = metas[i]; auto const result = env.rpc( - COMMAND, to_string(tx->getTransactionID()), BINARY, to_string(startLegSeq), to_string(endLegSeq)); + COMMAND, + to_string(tx->getTransactionID()), + BINARY, + to_string(startLegSeq), + to_string(endLegSeq)); BEAST_EXPECT(result[jss::result][jss::status] == jss::success); BEAST_EXPECT(result[jss::result][jss::tx] == strHex(tx->getSerializer().getData())); @@ -83,7 +88,8 @@ class Transaction_test : public beast::unit_test::suite to_string(endLegSeq + deltaEndSeq)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == NOT_FOUND); if (deltaEndSeq) BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); @@ -121,18 +127,23 @@ class Transaction_test : public beast::unit_test::suite to_string(endLegSeq + deltaEndSeq)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == NOT_FOUND); BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); } // Provide range without providing the `binary` // field. (Tests parameter parsing) { - auto const result = - env.rpc(COMMAND, to_string(tx->getTransactionID()), to_string(startLegSeq), to_string(endLegSeq)); + auto const result = env.rpc( + COMMAND, + to_string(tx->getTransactionID()), + to_string(startLegSeq), + to_string(endLegSeq)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == NOT_FOUND); BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); } @@ -141,10 +152,14 @@ class Transaction_test : public beast::unit_test::suite // field. (Tests parameter parsing) { auto const result = env.rpc( - COMMAND, to_string(tx->getTransactionID()), to_string(startLegSeq), to_string(deletedLedger - 1)); + COMMAND, + to_string(tx->getTransactionID()), + to_string(startLegSeq), + to_string(deletedLedger - 1)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == NOT_FOUND); BEAST_EXPECT(result[jss::result][jss::searched_all].asBool()); } @@ -153,7 +168,10 @@ class Transaction_test : public beast::unit_test::suite // field. (Tests parameter parsing) { auto const result = env.rpc( - COMMAND, to_string(txns[0]->getTransactionID()), to_string(startLegSeq), to_string(deletedLedger - 1)); + COMMAND, + to_string(txns[0]->getTransactionID()), + to_string(startLegSeq), + to_string(deletedLedger - 1)); BEAST_EXPECT(result[jss::result][jss::status] == jss::success); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); @@ -168,7 +186,9 @@ class Transaction_test : public beast::unit_test::suite to_string(deletedLedger - 1), to_string(startLegSeq)); - BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); + BEAST_EXPECT( + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } @@ -176,28 +196,39 @@ class Transaction_test : public beast::unit_test::suite // Provide an invalid range: (min < 0) { auto const result = env.rpc( - COMMAND, to_string(tx->getTransactionID()), BINARY, to_string(-1), to_string(deletedLedger - 1)); + COMMAND, + to_string(tx->getTransactionID()), + BINARY, + to_string(-1), + to_string(deletedLedger - 1)); - BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); + BEAST_EXPECT( + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } // Provide an invalid range: (min < 0, max < 0) { - auto const result = - env.rpc(COMMAND, to_string(tx->getTransactionID()), BINARY, to_string(-20), to_string(-10)); + auto const result = env.rpc( + COMMAND, to_string(tx->getTransactionID()), BINARY, to_string(-20), to_string(-10)); - BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); + BEAST_EXPECT( + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } // Provide an invalid range: (only one value) { - auto const result = env.rpc(COMMAND, to_string(tx->getTransactionID()), BINARY, to_string(20)); + auto const result = + env.rpc(COMMAND, to_string(tx->getTransactionID()), BINARY, to_string(20)); - BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); + BEAST_EXPECT( + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } @@ -226,7 +257,8 @@ class Transaction_test : public beast::unit_test::suite to_string(startLegSeq + 1001)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == EXCESSIVE); + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == EXCESSIVE); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } @@ -247,7 +279,7 @@ class Transaction_test : public beast::unit_test::suite char const* EXCESSIVE = RPC::get_error_info(rpcEXCESSIVE_LGR_RANGE).token; Env env{*this, makeNetworkConfig(11111)}; - uint32_t netID = env.app().config().NETWORK_ID; + uint32_t netID = env.app().getNetworkIDService().getNetworkID(); auto const alice = Account("alice"); env.fund(XRP(1000), alice); @@ -287,11 +319,12 @@ class Transaction_test : public beast::unit_test::suite auto const ctid = *RPC::encodeCTID(endLegSeq, tx->getSeqValue(), netID); for (int deltaEndSeq = 0; deltaEndSeq < 2; ++deltaEndSeq) { - auto const result = - env.rpc(COMMAND, ctid, BINARY, to_string(startLegSeq), to_string(endLegSeq + deltaEndSeq)); + auto const result = env.rpc( + COMMAND, ctid, BINARY, to_string(startLegSeq), to_string(endLegSeq + deltaEndSeq)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == NOT_FOUND); if (deltaEndSeq) BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); @@ -323,22 +356,25 @@ class Transaction_test : public beast::unit_test::suite } for (int deltaEndSeq = 0; deltaEndSeq < 2; ++deltaEndSeq) + { + auto const result = env.rpc( + COMMAND, ctid, BINARY, to_string(startLegSeq), to_string(endLegSeq + deltaEndSeq)); + + BEAST_EXPECT( + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == NOT_FOUND); + BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); + } + + // Provide range without providing the `binary` + // field. (Tests parameter parsing) { auto const result = - env.rpc(COMMAND, ctid, BINARY, to_string(startLegSeq), to_string(endLegSeq + deltaEndSeq)); + env.rpc(COMMAND, ctid, to_string(startLegSeq), to_string(endLegSeq)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); - BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); - } - - // Provide range without providing the `binary` - // field. (Tests parameter parsing) - { - auto const result = env.rpc(COMMAND, ctid, to_string(startLegSeq), to_string(endLegSeq)); - - BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == NOT_FOUND); BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); } @@ -346,10 +382,12 @@ class Transaction_test : public beast::unit_test::suite // Provide range without providing the `binary` // field. (Tests parameter parsing) { - auto const result = env.rpc(COMMAND, ctid, to_string(startLegSeq), to_string(deletedLedger - 1)); + auto const result = + env.rpc(COMMAND, ctid, to_string(startLegSeq), to_string(deletedLedger - 1)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == NOT_FOUND); BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); } @@ -371,18 +409,24 @@ class Transaction_test : public beast::unit_test::suite // Provide an invalid range: (min > max) { - auto const result = env.rpc(COMMAND, ctid, BINARY, to_string(deletedLedger - 1), to_string(startLegSeq)); + auto const result = env.rpc( + COMMAND, ctid, BINARY, to_string(deletedLedger - 1), to_string(startLegSeq)); - BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); + BEAST_EXPECT( + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } // Provide an invalid range: (min < 0) { - auto const result = env.rpc(COMMAND, ctid, BINARY, to_string(-1), to_string(deletedLedger - 1)); + auto const result = + env.rpc(COMMAND, ctid, BINARY, to_string(-1), to_string(deletedLedger - 1)); - BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); + BEAST_EXPECT( + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } @@ -391,7 +435,9 @@ class Transaction_test : public beast::unit_test::suite { auto const result = env.rpc(COMMAND, ctid, BINARY, to_string(-20), to_string(-10)); - BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); + BEAST_EXPECT( + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } @@ -400,7 +446,9 @@ class Transaction_test : public beast::unit_test::suite { auto const result = env.rpc(COMMAND, ctid, BINARY, to_string(20)); - BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); + BEAST_EXPECT( + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } @@ -421,10 +469,12 @@ class Transaction_test : public beast::unit_test::suite // Provide an invalid range: (max - min > 1000) { - auto const result = env.rpc(COMMAND, ctid, BINARY, to_string(startLegSeq), to_string(startLegSeq + 1001)); + auto const result = env.rpc( + COMMAND, ctid, BINARY, to_string(startLegSeq), to_string(startLegSeq + 1001)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == EXCESSIVE); + result[jss::result][jss::status] == jss::error && + result[jss::result][jss::error] == EXCESSIVE); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } @@ -460,12 +510,14 @@ class Transaction_test : public beast::unit_test::suite BEAST_EXPECT(!RPC::encodeCTID(0x0FFF'FFFFUL, 0xFFFFU, 0x1'0000U)); // Test case 5: Valid input values - auto const expected51 = std::optional>(std::make_tuple(0, 0, 0)); + auto const expected51 = + std::optional>(std::make_tuple(0, 0, 0)); BEAST_EXPECT(RPC::decodeCTID("C000000000000000") == expected51); - auto const expected52 = std::optional>(std::make_tuple(1U, 2U, 3U)); + auto const expected52 = + std::optional>(std::make_tuple(1U, 2U, 3U)); BEAST_EXPECT(RPC::decodeCTID("C000000100020003") == expected52); - auto const expected53 = - std::optional>(std::make_tuple(13249191UL, 12911U, 49221U)); + auto const expected53 = std::optional>( + std::make_tuple(13249191UL, 12911U, 49221U)); BEAST_EXPECT(RPC::decodeCTID("C0CA2AA7326FC045") == expected53); // Test case 6: ctid not a string or big int @@ -486,7 +538,8 @@ class Transaction_test : public beast::unit_test::suite // Test case 11: Valid input values BEAST_EXPECT( (RPC::decodeCTID(0xCFFF'FFFF'FFFF'FFFFULL) == - std::optional>(std::make_tuple(0x0FFF'FFFFUL, 0xFFFFU, 0xFFFFU)))); + std::optional>( + std::make_tuple(0x0FFF'FFFFUL, 0xFFFFU, 0xFFFFU)))); BEAST_EXPECT( (RPC::decodeCTID(0xC000'0000'0000'0000ULL) == std::optional>(std::make_tuple(0, 0, 0)))); @@ -495,7 +548,8 @@ class Transaction_test : public beast::unit_test::suite std::optional>(std::make_tuple(1U, 2U, 3U)))); BEAST_EXPECT( (RPC::decodeCTID(0xC0CA'2AA7'326F'C045ULL) == - std::optional>(std::make_tuple(1324'9191UL, 12911U, 49221U)))); + std::optional>( + std::make_tuple(1324'9191UL, 12911U, 49221U)))); // Test case 12: ctid not exactly 16 nibbles BEAST_EXPECT(!RPC::decodeCTID(0xC003'FFFF'FFFF'FFF)); @@ -520,7 +574,7 @@ class Transaction_test : public beast::unit_test::suite for (uint32_t netID : {11111, 65535, 65536}) { Env env{*this, makeNetworkConfig(netID)}; - BEAST_EXPECT(netID == env.app().config().NETWORK_ID); + BEAST_EXPECT(netID == env.app().getNetworkIDService().getNetworkID()); auto const alice = Account("alice"); auto const bob = Account("bob"); @@ -550,7 +604,7 @@ class Transaction_test : public beast::unit_test::suite // test querying with mixed case ctid { Env env{*this, makeNetworkConfig(11111)}; - std::uint32_t const netID = env.app().config().NETWORK_ID; + std::uint32_t const netID = env.app().getNetworkIDService().getNetworkID(); Account const alice = Account("alice"); Account const bob = Account("bob"); @@ -591,7 +645,7 @@ class Transaction_test : public beast::unit_test::suite for (uint32_t netID : {2, 1024, 65535, 65536}) { Env env{*this, makeNetworkConfig(netID)}; - BEAST_EXPECT(netID == env.app().config().NETWORK_ID); + BEAST_EXPECT(netID == env.app().getNetworkIDService().getNetworkID()); auto const alice = Account("alice"); auto const bob = Account("bob"); @@ -623,7 +677,7 @@ class Transaction_test : public beast::unit_test::suite // test the wrong network ID was submitted { Env env{*this, makeNetworkConfig(21337)}; - uint32_t netID = env.app().config().NETWORK_ID; + uint32_t netID = env.app().getNetworkIDService().getNetworkID(); auto const alice = Account("alice"); auto const bob = Account("bob"); @@ -676,7 +730,8 @@ class Transaction_test : public beast::unit_test::suite std::shared_ptr txn = env.tx(); env.close(); - std::shared_ptr meta = env.closed()->txRead(env.tx()->getTransactionID()).second; + std::shared_ptr meta = + env.closed()->txRead(env.tx()->getTransactionID()).second; Json::Value expected = txn->getJson(JsonOptions::none); expected[jss::DeliverMax] = expected[jss::Amount]; @@ -710,7 +765,8 @@ class Transaction_test : public beast::unit_test::suite for (auto memberIt = expected.begin(); memberIt != expected.end(); memberIt++) { std::string const name = memberIt.memberName(); - auto const& result_transaction = (apiVersion > 1 ? result[jss::result][jss::tx_json] : result[jss::result]); + auto const& result_transaction = + (apiVersion > 1 ? result[jss::result][jss::tx_json] : result[jss::result]); if (BEAST_EXPECT(result_transaction.isMember(name))) { auto const received = result_transaction[name]; @@ -743,7 +799,8 @@ class Transaction_test : public beast::unit_test::suite env.fund(XRP(1000000), alice, gw); std::shared_ptr const txn = env.tx(); BEAST_EXPECT( - to_string(txn->getTransactionID()) == "3F8BDE5A5F82C4F4708E5E9255B713E303E6E1A371FD5C7A704AFD1387C23981"); + to_string(txn->getTransactionID()) == + "3F8BDE5A5F82C4F4708E5E9255B713E303E6E1A371FD5C7A704AFD1387C23981"); env.close(); std::shared_ptr meta = env.closed()->txRead(txn->getTransactionID()).second; diff --git a/src/test/rpc/ValidatorRPC_test.cpp b/src/test/rpc/ValidatorRPC_test.cpp index a46d198b5a..829e2699a7 100644 --- a/src/test/rpc/ValidatorRPC_test.cpp +++ b/src/test/rpc/ValidatorRPC_test.cpp @@ -130,7 +130,8 @@ public: BEAST_EXPECT(jrrnUnlSize == 2); for (std::uint32_t x = 0; x < jrrnUnlSize; ++x) { - auto parsedKey = parseBase58(TokenType::NodePublic, jrrnUnl[x].asString()); + auto parsedKey = + parseBase58(TokenType::NodePublic, jrrnUnl[x].asString()); BEAST_EXPECT(parsedKey); if (parsedKey) BEAST_EXPECT(disabledKeys.find(*parsedKey) != disabledKeys.end()); @@ -148,7 +149,9 @@ public: { using namespace test::jtx; - auto toStr = [](PublicKey const& publicKey) { return toBase58(TokenType::NodePublic, publicKey); }; + auto toStr = [](PublicKey const& publicKey) { + return toBase58(TokenType::NodePublic, publicKey); + }; // Validator keys that will be in the published list std::vector validators = { @@ -164,7 +167,13 @@ public: NetClock::time_point const validFrom2{validUntil - 60s}; NetClock::time_point const validUntil2{validFrom2 + 3600s}; auto server = make_TrustedPublisherServer( - worker.get_io_context(), validators, validUntil, {{validFrom2, validUntil2}}, false, 1, false); + worker.get_io_context(), + validators, + validUntil, + {{validFrom2, validUntil2}}, + false, + 1, + false); //---------------------------------------------------------------------- // Publisher list site unavailable v1 @@ -177,7 +186,8 @@ public: *this, envconfig([&](std::unique_ptr cfg) { cfg->section(SECTION_VALIDATOR_LIST_SITES).append(siteURI); - cfg->section(SECTION_VALIDATOR_LIST_KEYS).append(strHex(server->publisherPublic())); + cfg->section(SECTION_VALIDATOR_LIST_KEYS) + .append(strHex(server->publisherPublic())); return cfg; }), }; @@ -195,7 +205,9 @@ public: } { auto const jrr = env.rpc("validators")[jss::result]; - BEAST_EXPECT(jrr[jss::validation_quorum].asUInt() == std::numeric_limits::max()); + BEAST_EXPECT( + jrr[jss::validation_quorum].asUInt() == + std::numeric_limits::max()); BEAST_EXPECT(jrr[jss::local_static_keys].size() == 0); BEAST_EXPECT(jrr[jss::trusted_validator_keys].size() == 0); BEAST_EXPECT(jrr[jss::validator_list][jss::expiration] == "unknown"); @@ -234,7 +246,8 @@ public: *this, envconfig([&](std::unique_ptr cfg) { cfg->section(SECTION_VALIDATOR_LIST_SITES).append(siteURI); - cfg->section(SECTION_VALIDATOR_LIST_KEYS).append(strHex(server->publisherPublic())); + cfg->section(SECTION_VALIDATOR_LIST_KEYS) + .append(strHex(server->publisherPublic())); return cfg; }), }; @@ -252,7 +265,9 @@ public: } { auto const jrr = env.rpc("validators")[jss::result]; - BEAST_EXPECT(jrr[jss::validation_quorum].asUInt() == std::numeric_limits::max()); + BEAST_EXPECT( + jrr[jss::validation_quorum].asUInt() == + std::numeric_limits::max()); BEAST_EXPECT(jrr[jss::local_static_keys].size() == 0); BEAST_EXPECT(jrr[jss::trusted_validator_keys].size() == 0); BEAST_EXPECT(jrr[jss::validator_list][jss::expiration] == "unknown"); @@ -294,7 +309,8 @@ public: *this, envconfig([&](std::unique_ptr cfg) { cfg->section(SECTION_VALIDATOR_LIST_SITES).append(siteURI); - cfg->section(SECTION_VALIDATOR_LIST_KEYS).append(strHex(server->publisherPublic())); + cfg->section(SECTION_VALIDATOR_LIST_KEYS) + .append(strHex(server->publisherPublic())); return cfg; }), }; @@ -306,16 +322,22 @@ public: startKeys.insert(calcNodeID(val.masterPublic)); env.app().validators().updateTrusted( - startKeys, env.timeKeeper().now(), env.app().getOPs(), env.app().overlay(), env.app().getHashRouter()); + startKeys, + env.timeKeeper().now(), + env.app().getOPs(), + env.app().overlay(), + env.app().getHashRouter()); { auto const jrr = env.rpc("server_info")[jss::result]; - BEAST_EXPECT(jrr[jss::info][jss::validator_list][jss::expiration] == to_string(validUntil)); + BEAST_EXPECT( + jrr[jss::info][jss::validator_list][jss::expiration] == to_string(validUntil)); } { auto const jrr = env.rpc("server_state")[jss::result]; BEAST_EXPECT( - jrr[jss::state][jss::validator_list_expires].asUInt() == validUntil.time_since_epoch().count()); + jrr[jss::state][jss::validator_list_expires].asUInt() == + validUntil.time_since_epoch().count()); } { auto const jrr = env.rpc("validators")[jss::result]; @@ -380,7 +402,8 @@ public: *this, envconfig([&](std::unique_ptr cfg) { cfg->section(SECTION_VALIDATOR_LIST_SITES).append(siteURI); - cfg->section(SECTION_VALIDATOR_LIST_KEYS).append(strHex(server->publisherPublic())); + cfg->section(SECTION_VALIDATOR_LIST_KEYS) + .append(strHex(server->publisherPublic())); return cfg; }), }; @@ -392,16 +415,22 @@ public: startKeys.insert(calcNodeID(val.masterPublic)); env.app().validators().updateTrusted( - startKeys, env.timeKeeper().now(), env.app().getOPs(), env.app().overlay(), env.app().getHashRouter()); + startKeys, + env.timeKeeper().now(), + env.app().getOPs(), + env.app().overlay(), + env.app().getHashRouter()); { auto const jrr = env.rpc("server_info")[jss::result]; - BEAST_EXPECT(jrr[jss::info][jss::validator_list][jss::expiration] == to_string(validUntil2)); + BEAST_EXPECT( + jrr[jss::info][jss::validator_list][jss::expiration] == to_string(validUntil2)); } { auto const jrr = env.rpc("server_state")[jss::result]; BEAST_EXPECT( - jrr[jss::state][jss::validator_list_expires].asUInt() == validUntil2.time_since_epoch().count()); + jrr[jss::state][jss::validator_list_expires].asUInt() == + validUntil2.time_since_epoch().count()); } { auto const jrr = env.rpc("validators")[jss::result]; @@ -433,7 +462,8 @@ public: BEAST_EXPECT(jp[jss::pubkey_publisher] == strHex(server->publisherPublic())); BEAST_EXPECT(jp[jss::expiration] == to_string(validUntil)); BEAST_EXPECT(jp[jss::version] == 2); - if (BEAST_EXPECT(jp.isMember(jss::remaining)) && BEAST_EXPECT(jp[jss::remaining].isArray()) && + if (BEAST_EXPECT(jp.isMember(jss::remaining)) && + BEAST_EXPECT(jp[jss::remaining].isArray()) && BEAST_EXPECT(jp[jss::remaining].size() == 1)) { auto const& r = jp[jss::remaining][0u]; @@ -483,7 +513,8 @@ public: Env env{*this}; auto result = env.rpc("validation_create"); BEAST_EXPECT(result.isMember(jss::result) && result[jss::result][jss::status] == "success"); - result = env.rpc("validation_create", "BAWL MAN JADE MOON DOVE GEM SON NOW HAD ADEN GLOW TIRE"); + result = + env.rpc("validation_create", "BAWL MAN JADE MOON DOVE GEM SON NOW HAD ADEN GLOW TIRE"); BEAST_EXPECT(result.isMember(jss::result) && result[jss::result][jss::status] == "success"); } diff --git a/src/test/rpc/Version_test.cpp b/src/test/rpc/Version_test.cpp index 1dec8627ed..c86bb8a660 100644 --- a/src/test/rpc/Version_test.cpp +++ b/src/test/rpc/Version_test.cpp @@ -24,7 +24,8 @@ class Version_test : public beast::unit_test::suite auto jrr = env.rpc( "json", "version", - "{\"api_version\": " + std::to_string(RPC::apiMaximumSupportedVersion) + "}")[jss::result]; + "{\"api_version\": " + std::to_string(RPC::apiMaximumSupportedVersion) + + "}")[jss::result]; BEAST_EXPECT(isCorrectReply(jrr)); jrr = env.rpc("version")[jss::result]; @@ -49,7 +50,9 @@ class Version_test : public beast::unit_test::suite }; auto re = env.rpc( - "json", "version", "{\"api_version\": " + std::to_string(RPC::apiMinimumSupportedVersion - 1) + "}"); + "json", + "version", + "{\"api_version\": " + std::to_string(RPC::apiMinimumSupportedVersion - 1) + "}"); BEAST_EXPECT(badVersion(re)); BEAST_EXPECT(env.app().config().BETA_RPC_API); @@ -57,7 +60,10 @@ class Version_test : public beast::unit_test::suite "json", "version", "{\"api_version\": " + - std::to_string(std::max(RPC::apiMaximumSupportedVersion.value, RPC::apiBetaVersion.value) + 1) + "}"); + std::to_string( + std::max(RPC::apiMaximumSupportedVersion.value, RPC::apiBetaVersion.value) + + 1) + + "}"); BEAST_EXPECT(badVersion(re)); re = env.rpc("json", "version", "{\"api_version\": \"a\"}"); @@ -69,7 +75,8 @@ class Version_test : public beast::unit_test::suite { testcase("test getAPIVersionNumber function"); - unsigned int versionIfUnspecified = RPC::apiVersionIfUnspecified < RPC::apiMinimumSupportedVersion + unsigned int versionIfUnspecified = + RPC::apiVersionIfUnspecified < RPC::apiMinimumSupportedVersion ? RPC::apiInvalidVersion : RPC::apiVersionIfUnspecified; @@ -150,14 +157,17 @@ class Version_test : public beast::unit_test::suite "\"id\": 5, " "\"method\": \"version\", " "\"params\": {}}"; - auto const with_wrong_api_verion = std::string("{ ") + + auto const with_wrong_api_verion = + std::string("{ ") + "\"jsonrpc\": \"2.0\", " "\"ripplerpc\": \"2.0\", " "\"id\": 6, " "\"method\": \"version\", " "\"params\": { " "\"api_version\": " + - std::to_string(std::max(RPC::apiMaximumSupportedVersion.value, RPC::apiBetaVersion.value) + 1) + "}}"; + std::to_string( + std::max(RPC::apiMaximumSupportedVersion.value, RPC::apiBetaVersion.value) + 1) + + "}}"; auto re = env.rpc("json2", '[' + without_api_verion + ", " + with_wrong_api_verion + ']'); if (!BEAST_EXPECT(re.isArray())) @@ -203,12 +213,15 @@ class Version_test : public beast::unit_test::suite if (!BEAST_EXPECT(env.app().config().BETA_RPC_API == true)) return; - auto jrr = - env.rpc("json", "version", "{\"api_version\": " + std::to_string(RPC::apiBetaVersion) + "}")[jss::result]; + auto jrr = env.rpc( + "json", + "version", + "{\"api_version\": " + std::to_string(RPC::apiBetaVersion) + "}")[jss::result]; if (!BEAST_EXPECT(jrr.isMember(jss::version))) return; - if (!BEAST_EXPECT(jrr[jss::version].isMember(jss::first)) && jrr[jss::version].isMember(jss::last)) + if (!BEAST_EXPECT(jrr[jss::version].isMember(jss::first)) && + jrr[jss::version].isMember(jss::last)) return; BEAST_EXPECT(jrr[jss::version][jss::first] == RPC::apiMinimumSupportedVersion.value); BEAST_EXPECT(jrr[jss::version][jss::last] == RPC::apiBetaVersion.value); diff --git a/src/test/server/ServerStatus_test.cpp b/src/test/server/ServerStatus_test.cpp index ccfdf2fd2b..dc92375428 100644 --- a/src/test/server/ServerStatus_test.cpp +++ b/src/test/server/ServerStatus_test.cpp @@ -4,13 +4,13 @@ #include #include -#include -#include #include #include #include #include +#include +#include #include #include @@ -98,7 +98,11 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en } auto - makeHTTPRequest(std::string const& host, uint16_t port, std::string const& body, myFields const& fields) + makeHTTPRequest( + std::string const& host, + uint16_t port, + std::string const& body, + myFields const& fields) { using namespace boost::asio; using namespace boost::beast::http; @@ -259,8 +263,9 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en void testAdminRequest(std::string const& proto, bool admin, bool credentials) { - testcase << "Admin request over " << proto << ", config " << (admin ? "enabled" : "disabled") - << ", credentials " << (credentials ? "" : "not ") << "set"; + testcase << "Admin request over " << proto << ", config " + << (admin ? "enabled" : "disabled") << ", credentials " + << (credentials ? "" : "not ") << "set"; using namespace jtx; Env env{*this, makeConfig(proto, admin, credentials)}; @@ -272,34 +277,41 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en if (admin && credentials) { - auto const user = env.app().config()[proto_ws ? "port_ws" : "port_rpc"].get("admin_user"); + auto const user = + env.app().config()[proto_ws ? "port_ws" : "port_rpc"].get( + "admin_user"); auto const password = - env.app().config()[proto_ws ? "port_ws" : "port_rpc"].get("admin_password"); + env.app().config()[proto_ws ? "port_ws" : "port_rpc"].get( + "admin_password"); // 1 - FAILS with wrong pass jrr = makeAdminRequest(env, proto, *user, *password + "_")[jss::result]; BEAST_EXPECT(jrr["error"] == proto_ws ? "forbidden" : "noPermission"); BEAST_EXPECT( - jrr["error_message"] == proto_ws ? "Bad credentials." : "You don't have permission for this command."); + jrr["error_message"] == proto_ws ? "Bad credentials." + : "You don't have permission for this command."); // 2 - FAILS with password in an object jrr = makeAdminRequest(env, proto, *user, *password, true)[jss::result]; BEAST_EXPECT(jrr["error"] == proto_ws ? "forbidden" : "noPermission"); BEAST_EXPECT( - jrr["error_message"] == proto_ws ? "Bad credentials." : "You don't have permission for this command."); + jrr["error_message"] == proto_ws ? "Bad credentials." + : "You don't have permission for this command."); // 3 - FAILS with wrong user jrr = makeAdminRequest(env, proto, *user + "_", *password)[jss::result]; BEAST_EXPECT(jrr["error"] == proto_ws ? "forbidden" : "noPermission"); BEAST_EXPECT( - jrr["error_message"] == proto_ws ? "Bad credentials." : "You don't have permission for this command."); + jrr["error_message"] == proto_ws ? "Bad credentials." + : "You don't have permission for this command."); // 4 - FAILS no credentials jrr = makeAdminRequest(env, proto, "", "")[jss::result]; BEAST_EXPECT(jrr["error"] == proto_ws ? "forbidden" : "noPermission"); BEAST_EXPECT( - jrr["error_message"] == proto_ws ? "Bad credentials." : "You don't have permission for this command."); + jrr["error_message"] == proto_ws ? "Bad credentials." + : "You don't have permission for this command."); // 5 - SUCCEEDS with proper credentials jrr = makeAdminRequest(env, proto, *user, *password)[jss::result]; @@ -321,7 +333,8 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en jrr = makeAdminRequest(env, proto, "", "")[jss::result]; BEAST_EXPECT(jrr["error"] == proto_ws ? "forbidden" : "noPermission"); BEAST_EXPECT( - jrr["error_message"] == proto_ws ? "Bad credentials." : "You don't have permission for this command."); + jrr["error_message"] == proto_ws ? "Bad credentials." + : "You don't have permission for this command."); } } @@ -441,7 +454,8 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en // The essence of this test is to have a client and server configured // out-of-phase with respect to ssl (secure client and insecure server // or vice-versa) - testcase << "Connect fails: " << client_protocol << " client to " << server_protocol << " server"; + testcase << "Connect fails: " << client_protocol << " client to " << server_protocol + << " server"; using namespace jtx; Env env{*this, makeConfig(server_protocol)}; @@ -454,7 +468,8 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en } else { - doWSRequest(env, yield, client_protocol == "wss" || client_protocol == "wss2", resp, ec); + doWSRequest( + env, yield, client_protocol == "wss" || client_protocol == "wss2", resp, ec); BEAST_EXPECT(ec); } } @@ -495,7 +510,8 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en BEAST_EXPECT(resp.result() == boost::beast::http::status::forbidden); auto const user = env.app().config().section("port_rpc").get("user").value(); - auto const pass = env.app().config().section("port_rpc").get("password").value(); + auto const pass = + env.app().config().section("port_rpc").get("password").value(); // try with the correct user/pass, but not encoded auth.set("Authorization", "Basic " + user + ":" + pass); @@ -547,7 +563,8 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en int testTo = (limit == 0) ? 50 : limit + 1; while (connectionCount < testTo) { - clients.emplace_back(std::make_pair(ip::tcp::socket{ios}, boost::beast::multi_buffer{})); + clients.emplace_back( + std::make_pair(ip::tcp::socket{ios}, boost::beast::multi_buffer{})); async_connect(clients.back().first, it, yield[ec]); BEAST_EXPECT(!ec); auto req = makeHTTPRequest(ip, port, to_string(jr), {}); @@ -586,7 +603,8 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en doRequest(yield, makeWSUpgrade(ip, port), ip, port, true, resp, ec); BEAST_EXPECT(resp.result() == boost::beast::http::status::switching_protocols); BEAST_EXPECT(resp.find("Upgrade") != resp.end() && resp["Upgrade"] == "websocket"); - BEAST_EXPECT(resp.find("Connection") != resp.end() && boost::iequals(resp["Connection"], "upgrade")); + BEAST_EXPECT( + resp.find("Connection") != resp.end() && boost::iequals(resp["Connection"], "upgrade")); } void @@ -650,8 +668,9 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en Json::Value resp; Json::Reader jr; - if (!BEAST_EXPECT( - jr.parse(boost::lexical_cast(boost::beast::make_printable(sb.data())), resp))) + if (!BEAST_EXPECT(jr.parse( + boost::lexical_cast(boost::beast::make_printable(sb.data())), + resp))) return Json::objectValue; sb.consume(sb.size()); return resp; @@ -728,7 +747,8 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en boost::system::error_code ec; response resp; - doRequest(yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); + doRequest( + yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; @@ -763,7 +783,8 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en si[jss::state][jss::warnings][0u][jss::id].asInt() == warnRPC_UNSUPPORTED_MAJORITY); // but status does not indicate a problem - doRequest(yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); + doRequest( + yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; @@ -773,7 +794,8 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en // with ELB_SUPPORT, status still does not indicate a problem env.app().config().ELB_SUPPORT = true; - doRequest(yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); + doRequest( + yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; @@ -826,7 +848,8 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en boost::system::error_code ec; response resp; - doRequest(yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); + doRequest( + yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; @@ -844,7 +867,9 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en // RPC request server_info again, now AB should be returned si = env.rpc("server_info")[jss::result]; BEAST_EXPECT(si.isMember(jss::info)); - BEAST_EXPECT(si[jss::info].isMember(jss::amendment_blocked) && si[jss::info][jss::amendment_blocked] == true); + BEAST_EXPECT( + si[jss::info].isMember(jss::amendment_blocked) && + si[jss::info][jss::amendment_blocked] == true); BEAST_EXPECT( si[jss::info].isMember(jss::warnings) && si[jss::info][jss::warnings].isArray() && si[jss::info][jss::warnings].size() == 1 && @@ -852,7 +877,9 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en // RPC request server_state again, now AB should be returned si = env.rpc("server_state")[jss::result]; - BEAST_EXPECT(si[jss::state].isMember(jss::amendment_blocked) && si[jss::state][jss::amendment_blocked] == true); + BEAST_EXPECT( + si[jss::state].isMember(jss::amendment_blocked) && + si[jss::state][jss::amendment_blocked] == true); BEAST_EXPECT( si[jss::state].isMember(jss::warnings) && si[jss::state][jss::warnings].isArray() && si[jss::state][jss::warnings].size() == 1 && @@ -860,7 +887,8 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en // but status does not indicate because it still relies on ELB // being enabled - doRequest(yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); + doRequest( + yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; @@ -869,7 +897,8 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en env.app().config().ELB_SUPPORT = true; - doRequest(yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); + doRequest( + yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; diff --git a/src/test/server/Server_test.cpp b/src/test/server/Server_test.cpp index 7347bf238c..f7250de7fa 100644 --- a/src/test/server/Server_test.cpp +++ b/src/test/server/Server_test.cpp @@ -35,7 +35,8 @@ public: { private: boost::asio::io_context io_context_; - std::optional> work_; + std::optional> + work_; std::thread thread_; public: @@ -65,7 +66,8 @@ public: beast::unit_test::suite& suite_; public: - explicit TestSink(beast::unit_test::suite& suite) : Sink(beast::severities::kWarning, false), suite_(suite) + explicit TestSink(beast::unit_test::suite& suite) + : Sink(beast::severities::kWarning, false), suite_(suite) { } @@ -106,7 +108,10 @@ public: } Handoff - onHandoff(Session& session, http_request_type&& request, boost::asio::ip::tcp::endpoint remote_address) + onHandoff( + Session& session, + http_request_type&& request, + boost::asio::ip::tcp::endpoint remote_address) { return Handoff{}; } @@ -122,7 +127,9 @@ public: } void - onWSMessage(std::shared_ptr session, std::vector const&) + onWSMessage( + std::shared_ptr session, + std::vector const&) { } @@ -275,7 +282,8 @@ public: TestHandler handler; auto s = make_Server(handler, thread.get_io_context(), journal); std::vector serverPort(1); - serverPort.back().ip = boost::asio::ip::make_address(getEnvLocalhostAddr()), serverPort.back().port = 0; + serverPort.back().ip = boost::asio::ip::make_address(getEnvLocalhostAddr()), + serverPort.back().port = 0; serverPort.back().protocol.insert("http"); auto eps = s->ports(serverPort); test_request(eps.begin()->second); @@ -308,7 +316,10 @@ public: } Handoff - onHandoff(Session& session, http_request_type&& request, boost::asio::ip::tcp::endpoint remote_address) + onHandoff( + Session& session, + http_request_type&& request, + boost::asio::ip::tcp::endpoint remote_address) { return Handoff{}; } @@ -319,7 +330,9 @@ public: } void - onWSMessage(std::shared_ptr session, std::vector const& buffers) + onWSMessage( + std::shared_ptr session, + std::vector const& buffers) { } @@ -343,7 +356,8 @@ public: TestThread thread; auto s = make_Server(h, thread.get_io_context(), journal); std::vector serverPort(1); - serverPort.back().ip = boost::asio::ip::make_address(getEnvLocalhostAddr()), serverPort.back().port = 0; + serverPort.back().ip = boost::asio::ip::make_address(getEnvLocalhostAddr()), + serverPort.back().port = 0; serverPort.back().protocol.insert("http"); s->ports(serverPort); } @@ -392,7 +406,8 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT(messages.find("Invalid value '0' for key 'port' in [port_rpc]") == std::string::npos); + BEAST_EXPECT( + messages.find("Invalid value '0' for key 'port' in [port_rpc]") == std::string::npos); except([&] { Env env{ @@ -403,7 +418,8 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT(messages.find("Invalid value '0' for key 'port' in [server]") != std::string::npos); + BEAST_EXPECT( + messages.find("Invalid value '0' for key 'port' in [server]") != std::string::npos); except([&] { Env env{ diff --git a/src/test/shamap/SHAMapSync_test.cpp b/src/test/shamap/SHAMapSync_test.cpp index 1add7a629e..81305c4dab 100644 --- a/src/test/shamap/SHAMapSync_test.cpp +++ b/src/test/shamap/SHAMapSync_test.cpp @@ -109,7 +109,8 @@ public: unexpected(a.size() < 1, "NodeSize"); - BEAST_EXPECT(destination.addRootNode(source.getHash(), makeSlice(a[0].second), nullptr).isGood()); + BEAST_EXPECT(destination.addRootNode(source.getHash(), makeSlice(a[0].second), nullptr) + .isGood()); } do @@ -145,7 +146,8 @@ public: // Don't use BEAST_EXPECT here b/c it will be called a // non-deterministic number of times and the number of tests run // should be deterministic - if (!destination.addKnownNode(b[i].first, makeSlice(b[i].second), nullptr).isUseful()) + if (!destination.addKnownNode(b[i].first, makeSlice(b[i].second), nullptr) + .isUseful()) fail("", __FILE__, __LINE__); } } while (true); diff --git a/src/test/shamap/SHAMap_test.cpp b/src/test/shamap/SHAMap_test.cpp index c91cc63749..1eb050178c 100644 --- a/src/test/shamap/SHAMap_test.cpp +++ b/src/test/shamap/SHAMap_test.cpp @@ -196,40 +196,56 @@ public: testcase("build/tear unbacked"); { constexpr std::array keys{ - uint256("b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8"), - uint256("b92881fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8"), - uint256("b92691fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8"), - uint256("b92791fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8"), - uint256("b91891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8"), - uint256("b99891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8"), - uint256("f22891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8"), - uint256("292891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8")}; + uint256( + "b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8"), + uint256( + "b92881fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8"), + uint256( + "b92691fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8"), + uint256( + "b92791fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8"), + uint256( + "b91891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8"), + uint256( + "b99891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8"), + uint256( + "f22891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8"), + uint256( + "292891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8")}; constexpr std::array hashes{ - uint256("B7387CFEA0465759ADC718E8C42B52D2309D179B326E239EB5075C" - "64B6281F7F"), - uint256("FBC195A9592A54AB44010274163CB6BA95F497EC5BA0A883184546" - "7FB2ECE266"), - uint256("4E7D2684B65DFD48937FFB775E20175C43AF0C94066F7D5679F51A" - "E756795B75"), - uint256("7A2F312EB203695FFD164E038E281839EEF06A1B99BFC263F3CECC" - "6C74F93E07"), - uint256("395A6691A372387A703FB0F2C6D2C405DAF307D0817F8F0E207596" - "462B0E3A3E"), - uint256("D044C0A696DE3169CC70AE216A1564D69DE96582865796142CE7D9" - "8A84D9DDE4"), - uint256("76DCC77C4027309B5A91AD164083264D70B77B5E43E08AEDA5EBF9" - "4361143615"), - uint256("DF4220E93ADC6F5569063A01B4DC79F8DB9553B6A3222ADE23DEA0" - "2BBE7230E5")}; + uint256( + "B7387CFEA0465759ADC718E8C42B52D2309D179B326E239EB5075C" + "64B6281F7F"), + uint256( + "FBC195A9592A54AB44010274163CB6BA95F497EC5BA0A883184546" + "7FB2ECE266"), + uint256( + "4E7D2684B65DFD48937FFB775E20175C43AF0C94066F7D5679F51A" + "E756795B75"), + uint256( + "7A2F312EB203695FFD164E038E281839EEF06A1B99BFC263F3CECC" + "6C74F93E07"), + uint256( + "395A6691A372387A703FB0F2C6D2C405DAF307D0817F8F0E207596" + "462B0E3A3E"), + uint256( + "D044C0A696DE3169CC70AE216A1564D69DE96582865796142CE7D9" + "8A84D9DDE4"), + uint256( + "76DCC77C4027309B5A91AD164083264D70B77B5E43E08AEDA5EBF9" + "4361143615"), + uint256( + "DF4220E93ADC6F5569063A01B4DC79F8DB9553B6A3222ADE23DEA0" + "2BBE7230E5")}; SHAMap map(SHAMapType::FREE, f); if (!backed) @@ -238,7 +254,8 @@ public: BEAST_EXPECT(map.getHash() == beast::zero); for (int k = 0; k < keys.size(); ++k) { - BEAST_EXPECT(map.addItem(SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(keys[k], IntToVUC(k)))); + BEAST_EXPECT(map.addItem( + SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(keys[k], IntToVUC(k)))); BEAST_EXPECT(map.getHash().as_uint256() == hashes[k]); map.invariants(); } @@ -258,22 +275,30 @@ public: { constexpr std::array keys{ - uint256("f22891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8"), - uint256("b99891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8"), - uint256("b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8"), - uint256("b92881fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8"), - uint256("b92791fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8"), - uint256("b92691fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8"), - uint256("b91891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8"), - uint256("292891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" - "5a772c6ca8")}; + uint256( + "f22891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8"), + uint256( + "b99891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8"), + uint256( + "b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8"), + uint256( + "b92881fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8"), + uint256( + "b92791fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8"), + uint256( + "b92691fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8"), + uint256( + "b91891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8"), + uint256( + "292891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e" + "5a772c6ca8")}; tests::TestNodeFamily tf{journal}; SHAMap map{SHAMapType::FREE, tf}; @@ -313,7 +338,8 @@ class SHAMapPathProof_test : public beast::unit_test::suite for (unsigned char c = 1; c < 100; ++c) { uint256 k(c); - map.addItem(SHAMapNodeType::tnACCOUNT_STATE, make_shamapitem(k, Slice{k.data(), k.size()})); + map.addItem( + SHAMapNodeType::tnACCOUNT_STATE, make_shamapitem(k, Slice{k.data(), k.size()})); map.invariants(); auto root = map.getHash().as_uint256(); diff --git a/src/test/shamap/common.h b/src/test/shamap/common.h index fe2a1884da..8284051d44 100644 --- a/src/test/shamap/common.h +++ b/src/test/shamap/common.h @@ -25,13 +25,19 @@ public: TestNodeFamily(beast::Journal j) : fbCache_(std::make_shared("App family full below cache", clock_, j)) , tnCache_( - std::make_shared("App family tree node cache", 65536, std::chrono::minutes{1}, clock_, j)) + std::make_shared( + "App family tree node cache", + 65536, + std::chrono::minutes{1}, + clock_, + j)) , j_(j) { Section testSection; testSection.set("type", "memory"); testSection.set("path", "SHAMap_test"); - db_ = NodeStore::Manager::instance().make_Database(megabytes(4), scheduler_, 1, testSection, j); + db_ = NodeStore::Manager::instance().make_Database( + megabytes(4), scheduler_, 1, testSection, j); } NodeStore::Database& diff --git a/src/test/unit_test/FileDirGuard.h b/src/test/unit_test/FileDirGuard.h index cf2eab7adb..b551b9389d 100644 --- a/src/test/unit_test/FileDirGuard.h +++ b/src/test/unit_test/FileDirGuard.h @@ -32,7 +32,8 @@ protected: if (is_directory(toRm) && is_empty(toRm)) remove(toRm); else - test_.log << "Expected " << toRm.string() << " to be an empty existing directory." << std::endl; + test_.log << "Expected " << toRm.string() << " to be an empty existing directory." + << std::endl; } public: @@ -128,7 +129,8 @@ public: else { if (created_) - test_.log << "Expected " << file_.string() << " to be an existing file." << std::endl; + test_.log << "Expected " << file_.string() << " to be an existing file." + << std::endl; } } catch (std::exception& e) diff --git a/src/test/unit_test/SuiteJournal.h b/src/test/unit_test/SuiteJournal.h index ad5f298b74..1eeefb68aa 100644 --- a/src/test/unit_test/SuiteJournal.h +++ b/src/test/unit_test/SuiteJournal.h @@ -105,7 +105,8 @@ class StreamSink : public beast::Journal::Sink std::stringstream strm_; public: - StreamSink(beast::severities::Severity threshold = beast::severities::kDebug) : Sink(threshold, false) + StreamSink(beast::severities::Severity threshold = beast::severities::kDebug) + : Sink(threshold, false) { } diff --git a/src/test/unit_test/multi_runner.cpp b/src/test/unit_test/multi_runner.cpp index eefd0c8250..3838f128f0 100644 --- a/src/test/unit_test/multi_runner.cpp +++ b/src/test/unit_test/multi_runner.cpp @@ -49,7 +49,10 @@ results::add(suite_results const& r) if (elapsed >= std::chrono::seconds{1}) { auto const iter = std::lower_bound( - top.begin(), top.end(), elapsed, [](run_time const& t1, typename clock_type::duration const& t2) { + top.begin(), + top.end(), + elapsed, + [](run_time const& t1, typename clock_type::duration const& t2) { return t1.second > t2; }); @@ -207,7 +210,10 @@ multi_runner_base::multi_runner_base() } shared_mem_ = boost::interprocess::shared_memory_object{ - std::conditional_t{}, + std::conditional_t< + IsParent, + boost::interprocess::create_only_t, + boost::interprocess::open_only_t>{}, shared_mem_name_, boost::interprocess::read_write}; @@ -457,7 +463,10 @@ multi_runner_parent::add_failures(std::size_t failures) //------------------------------------------------------------------------------ multi_runner_child::multi_runner_child(std::size_t num_jobs, bool quiet, bool print_log) - : job_index_{checkout_job_index()}, num_jobs_{num_jobs}, quiet_{quiet}, print_log_{!quiet || print_log} + : job_index_{checkout_job_index()} + , num_jobs_{num_jobs} + , quiet_{quiet} + , print_log_{!quiet || print_log} { if (num_jobs_ > 1) { @@ -478,7 +487,8 @@ multi_runner_child::multi_runner_child(std::size_t num_jobs, bool quiet, bool pr if (cur_count == last_count) { // assume parent process is no longer alive - std::cerr << "multi_runner_child " << job_index_ << ": Assuming parent died, exiting.\n"; + std::cerr << "multi_runner_child " << job_index_ + << ": Assuming parent died, exiting.\n"; std::exit(EXIT_FAILURE); } } @@ -533,8 +543,8 @@ multi_runner_child::on_suite_end() 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; + s << (suite_results_.failed > 0 ? "failed: " : "") << suite_results_.name << " had " + << suite_results_.failed << " failures." << std::endl; message_queue_send(MessageType::log, s.str()); } results_.add(suite_results_); @@ -552,7 +562,8 @@ multi_runner_child::on_case_begin(std::string const& name) std::stringstream s; if (num_jobs_ > 1) s << job_index_ << "> "; - s << suite_results_.name << (case_results_.name.empty() ? "" : (" " + case_results_.name)) << '\n'; + s << suite_results_.name << (case_results_.name.empty() ? "" : (" " + case_results_.name)) + << '\n'; message_queue_send(MessageType::log, s.str()); } diff --git a/src/test/unit_test/multi_runner.h b/src/test/unit_test/multi_runner.h index 28ecaf85f9..8148079292 100644 --- a/src/test/unit_test/multi_runner.h +++ b/src/test/unit_test/multi_runner.h @@ -231,7 +231,8 @@ public: /** A class to run a subset of unit tests */ -class multi_runner_child : public beast::unit_test::runner, private detail::multi_runner_base +class multi_runner_child : public beast::unit_test::runner, + private detail::multi_runner_base { private: std::size_t job_index_; diff --git a/src/tests/libxrpl/basics/Slice.cpp b/src/tests/libxrpl/basics/Slice.cpp index 4373f98168..8fef0d61a3 100644 --- a/src/tests/libxrpl/basics/Slice.cpp +++ b/src/tests/libxrpl/basics/Slice.cpp @@ -7,9 +7,9 @@ using namespace xrpl; -static std::uint8_t const data[] = {0xa8, 0xa1, 0x38, 0x45, 0x23, 0xec, 0xe4, 0x23, 0x71, 0x6d, 0x2a, - 0x18, 0xb4, 0x70, 0xcb, 0xf5, 0xac, 0x2d, 0x89, 0x4d, 0x19, 0x9c, - 0xf0, 0x2c, 0x15, 0xd1, 0xf9, 0x9b, 0x66, 0xd2, 0x30, 0xd3}; +static std::uint8_t const data[] = { + 0xa8, 0xa1, 0x38, 0x45, 0x23, 0xec, 0xe4, 0x23, 0x71, 0x6d, 0x2a, 0x18, 0xb4, 0x70, 0xcb, 0xf5, + 0xac, 0x2d, 0x89, 0x4d, 0x19, 0x9c, 0xf0, 0x2c, 0x15, 0xd1, 0xf9, 0x9b, 0x66, 0xd2, 0x30, 0xd3}; TEST(Slice, equality_and_inequality) { diff --git a/src/tests/libxrpl/basics/tagged_integer.cpp b/src/tests/libxrpl/basics/tagged_integer.cpp index e24b299442..09f8b6787b 100644 --- a/src/tests/libxrpl/basics/tagged_integer.cpp +++ b/src/tests/libxrpl/basics/tagged_integer.cpp @@ -53,15 +53,25 @@ static_assert( !std::is_assignable::value, "TagUInt3 should not be assignable with a std::uint64_t"); -static_assert(std::is_assignable::value, "TagUInt1 should be assignable with a TagUInt1"); +static_assert( + std::is_assignable::value, + "TagUInt1 should be assignable with a TagUInt1"); -static_assert(!std::is_assignable::value, "TagUInt1 should not be assignable with a TagUInt2"); +static_assert( + !std::is_assignable::value, + "TagUInt1 should not be assignable with a TagUInt2"); -static_assert(std::is_assignable::value, "TagUInt3 should be assignable with a TagUInt1"); +static_assert( + std::is_assignable::value, + "TagUInt3 should be assignable with a TagUInt1"); -static_assert(!std::is_assignable::value, "TagUInt1 should not be assignable with a TagUInt3"); +static_assert( + !std::is_assignable::value, + "TagUInt1 should not be assignable with a TagUInt3"); -static_assert(!std::is_assignable::value, "TagUInt3 should not be assignable with a TagUInt1"); +static_assert( + !std::is_assignable::value, + "TagUInt3 should not be assignable with a TagUInt1"); // Check convertibility of tagged_integers static_assert( @@ -80,11 +90,17 @@ static_assert( !std::is_convertible::value, "std::uint64_t should not be convertible to a TagUInt2"); -static_assert(!std::is_convertible::value, "TagUInt1 should not be convertible to TagUInt2"); +static_assert( + !std::is_convertible::value, + "TagUInt1 should not be convertible to TagUInt2"); -static_assert(!std::is_convertible::value, "TagUInt1 should not be convertible to TagUInt3"); +static_assert( + !std::is_convertible::value, + "TagUInt1 should not be convertible to TagUInt3"); -static_assert(!std::is_convertible::value, "TagUInt2 should not be convertible to a TagUInt3"); +static_assert( + !std::is_convertible::value, + "TagUInt2 should not be convertible to a TagUInt3"); using TagInt = tagged_integer; diff --git a/src/tests/libxrpl/json/Value.cpp b/src/tests/libxrpl/json/Value.cpp index 1d1131b209..cbca7c88a8 100644 --- a/src/tests/libxrpl/json/Value.cpp +++ b/src/tests/libxrpl/json/Value.cpp @@ -201,7 +201,11 @@ TEST(json_value, different_types) TEST(json_value, compare_strings) { - auto doCompare = [&](Json::Value const& lhs, Json::Value const& rhs, bool lhsEqRhs, bool lhsLtRhs, int line) { + auto doCompare = [&](Json::Value const& lhs, + Json::Value const& rhs, + bool lhsEqRhs, + bool lhsLtRhs, + int line) { SCOPED_TRACE(line); EXPECT_EQ((lhs == rhs), lhsEqRhs); EXPECT_NE((lhs != rhs), lhsEqRhs); diff --git a/src/tests/libxrpl/json/Writer.cpp b/src/tests/libxrpl/json/Writer.cpp index 54c3221858..7016b4322d 100644 --- a/src/tests/libxrpl/json/Writer.cpp +++ b/src/tests/libxrpl/json/Writer.cpp @@ -156,7 +156,8 @@ TEST_F(WriterFixture, complex_object) writer->startSet(Writer::array, "subarray"); writer->append(23.5); writer->finishAll(); - checkOutputAndReset(R"({"hello":"world","array":[true,12,[{"goodbye":"cruel world.","subarray":[23.5]}]]})"); + checkOutputAndReset( + R"({"hello":"world","array":[true,12,[{"goodbye":"cruel world.","subarray":[23.5]}]]})"); } TEST_F(WriterFixture, json_value) diff --git a/src/tests/libxrpl/net/HTTPClient.cpp b/src/tests/libxrpl/net/HTTPClient.cpp index 72a351f9b7..1e93d47c3c 100644 --- a/src/tests/libxrpl/net/HTTPClient.cpp +++ b/src/tests/libxrpl/net/HTTPClient.cpp @@ -147,7 +147,8 @@ private: boost::beast::http::request req; // Read the HTTP request asynchronously - co_await boost::beast::http::async_read(socket, buffer, req, boost::asio::use_awaitable); + co_await boost::beast::http::async_read( + socket, buffer, req, boost::asio::use_awaitable); // Create response boost::beast::http::response res; @@ -219,7 +220,8 @@ runHTTPTest( auto start = std::chrono::steady_clock::now(); while (server.ioc().run_one() != 0) { - if (std::chrono::steady_clock::now() - start >= std::chrono::seconds(10) || server.finished()) + if (std::chrono::steady_clock::now() - start >= std::chrono::seconds(10) || + server.finished()) { break; } @@ -258,7 +260,8 @@ TEST(HTTPClient, case_insensitive_content_length) std::string resultData; boost::system::error_code resultError; - bool testCompleted = runHTTPTest(server, "/test", completed, resultStatus, resultData, resultError); + bool testCompleted = + runHTTPTest(server, "/test", completed, resultStatus, resultData, resultError); // Verify results EXPECT_TRUE(testCompleted); @@ -280,7 +283,8 @@ TEST(HTTPClient, basic_http_request) std::string resultData; boost::system::error_code resultError; - bool testCompleted = runHTTPTest(server, "/basic", completed, resultStatus, resultData, resultError); + bool testCompleted = + runHTTPTest(server, "/basic", completed, resultStatus, resultData, resultError); EXPECT_TRUE(testCompleted); EXPECT_FALSE(resultError); @@ -299,7 +303,8 @@ TEST(HTTPClient, empty_response) std::string resultData; boost::system::error_code resultError; - bool testCompleted = runHTTPTest(server, "/empty", completed, resultStatus, resultData, resultError); + bool testCompleted = + runHTTPTest(server, "/empty", completed, resultStatus, resultData, resultError); EXPECT_TRUE(testCompleted); EXPECT_FALSE(resultError); @@ -322,7 +327,8 @@ TEST(HTTPClient, different_status_codes) std::string resultData; boost::system::error_code resultError; - bool testCompleted = runHTTPTest(server, "/status", completed, resultStatus, resultData, resultError); + bool testCompleted = + runHTTPTest(server, "/status", completed, resultStatus, resultData, resultError); EXPECT_TRUE(testCompleted); EXPECT_FALSE(resultError); diff --git a/src/xrpld/app/consensus/RCLConsensus.cpp b/src/xrpld/app/consensus/RCLConsensus.cpp index 35f8eec1a3..98dccc0089 100644 --- a/src/xrpld/app/consensus/RCLConsensus.cpp +++ b/src/xrpld/app/consensus/RCLConsensus.cpp @@ -7,11 +7,7 @@ #include #include #include -#include -#include -#include #include -#include #include #include #include @@ -22,9 +18,13 @@ #include #include #include +#include +#include #include #include #include +#include +#include #include #include @@ -41,7 +41,14 @@ RCLConsensus::RCLConsensus( Consensus::clock_type const& clock, ValidatorKeys const& validatorKeys, beast::Journal journal) - : adaptor_(app, std::move(feeVote), ledgerMaster, localTxs, inboundTransactions, validatorKeys, journal) + : adaptor_( + app, + std::move(feeVote), + ledgerMaster, + localTxs, + inboundTransactions, + validatorKeys, + journal) , consensus_(clock, adaptor_, journal) , j_(journal) { @@ -109,8 +116,11 @@ RCLConsensus::Adaptor::acquireLedger(LedgerHash const& hash) } XRPL_ASSERT( - !built->open() && built->isImmutable(), "xrpl::RCLConsensus::Adaptor::acquireLedger : valid ledger state"); - XRPL_ASSERT(built->header().hash == hash, "xrpl::RCLConsensus::Adaptor::acquireLedger : ledger hash match"); + !built->open() && built->isImmutable(), + "xrpl::RCLConsensus::Adaptor::acquireLedger : valid ledger state"); + XRPL_ASSERT( + built->header().hash == hash, + "xrpl::RCLConsensus::Adaptor::acquireLedger : ledger hash match"); // Notify inbound transactions of the new ledger sequence number inboundTransactions_.newRound(built->header().seq); @@ -164,7 +174,8 @@ void RCLConsensus::Adaptor::propose(RCLCxPeerPos::Proposal const& proposal) { JLOG(j_.trace()) << (proposal.isBowOut() ? "We bow out: " : "We propose: ") - << xrpl::to_string(proposal.prevLedger()) << " -> " << xrpl::to_string(proposal.position()); + << xrpl::to_string(proposal.prevLedger()) << " -> " + << xrpl::to_string(proposal.position()); protocol::TMProposeSet prop; @@ -189,7 +200,12 @@ RCLConsensus::Adaptor::propose(RCLCxPeerPos::Proposal const& proposal) prop.set_signature(sig.data(), sig.size()); auto const suppression = proposalUniqueId( - proposal.position(), proposal.prevLedger(), proposal.proposeSeq(), proposal.closeTime(), keys.publicKey, sig); + proposal.position(), + proposal.prevLedger(), + proposal.proposeSeq(), + proposal.closeTime(), + keys.publicKey, + sig); app_.getHashRouter().addSuppression(suppression); @@ -232,11 +248,15 @@ RCLConsensus::Adaptor::proposersFinished(RCLCxLedger const& ledger, LedgerHash c } uint256 -RCLConsensus::Adaptor::getPrevLedger(uint256 ledgerID, RCLCxLedger const& ledger, ConsensusMode mode) +RCLConsensus::Adaptor::getPrevLedger( + uint256 ledgerID, + RCLCxLedger const& ledger, + ConsensusMode mode) { RCLValidations& vals = app_.getValidations(); uint256 netLgr = vals.getPreferred( - RCLValidatedLedger{ledger.ledger_, vals.adaptor().journal()}, ledgerMaster_.getValidLedgerIndex()); + RCLValidatedLedger{ledger.ledger_, vals.adaptor().journal()}, + ledgerMaster_.getValidLedgerIndex()); if (netLgr != ledgerID) { @@ -250,8 +270,10 @@ RCLConsensus::Adaptor::getPrevLedger(uint256 ledgerID, RCLCxLedger const& ledger } auto -RCLConsensus::Adaptor::onClose(RCLCxLedger const& ledger, NetClock::time_point const& closeTime, ConsensusMode mode) - -> Result +RCLConsensus::Adaptor::onClose( + RCLCxLedger const& ledger, + NetClock::time_point const& closeTime, + ConsensusMode mode) -> Result { bool const wrongLCL = mode == ConsensusMode::wrongLedger; bool const proposing = mode == ConsensusMode::proposing; @@ -275,7 +297,9 @@ RCLConsensus::Adaptor::onClose(RCLCxLedger const& ledger, NetClock::time_point c JLOG(j_.trace()) << "Adding open ledger TX " << tx.first->getTransactionID(); Serializer s(2048); tx.first->add(s); - initialSet->addItem(SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(tx.first->getTransactionID(), s.slice())); + initialSet->addItem( + SHAMapNodeType::tnTRANSACTION_NM, + make_shamapitem(tx.first->getTransactionID(), s.slice())); } // Add pseudo-transactions to the set @@ -285,8 +309,9 @@ RCLConsensus::Adaptor::onClose(RCLCxLedger const& ledger, NetClock::time_point c { // previous ledger was flag ledger, add fee and amendment // pseudo-transactions - auto validations = app_.validators().negativeUNLFilter( - app_.getValidations().getTrustedForLedger(prevLedger->header().parentHash, prevLedger->seq() - 1)); + auto validations = + app_.validators().negativeUNLFilter(app_.getValidations().getTrustedForLedger( + prevLedger->header().parentHash, prevLedger->seq() - 1)); if (validations.size() >= app_.validators().quorum()) { feeVote_->doVoting(prevLedger, validations, initialSet); @@ -298,7 +323,11 @@ RCLConsensus::Adaptor::onClose(RCLCxLedger const& ledger, NetClock::time_point c // previous ledger was a voting ledger, // so the current consensus session is for a flag ledger, // add negative UNL pseudo-transactions - nUnlVote_.doVoting(prevLedger, app_.validators().getTrustedMasterKeys(), app_.getValidations(), initialSet); + nUnlVote_.doVoting( + prevLedger, + app_.validators().getTrustedMasterKeys(), + app_.getValidations(), + initialSet); } } @@ -310,9 +339,10 @@ RCLConsensus::Adaptor::onClose(RCLCxLedger const& ledger, NetClock::time_point c LedgerIndex const seq = prevLedger->header().seq + 1; RCLCensorshipDetector::TxIDSeqVec proposed; - initialSet->visitLeaves([&proposed, seq](boost::intrusive_ptr const& item) { - proposed.emplace_back(item->key(), seq); - }); + initialSet->visitLeaves( + [&proposed, seq](boost::intrusive_ptr const& item) { + proposed.emplace_back(item->key(), seq); + }); censorshipDetector_.propose(std::move(proposed)); } @@ -353,16 +383,17 @@ RCLConsensus::Adaptor::onAccept( Json::Value&& consensusJson, bool const validating) { - app_.getJobQueue().addJob(jtACCEPT, "AcceptLedger", [=, this, cj = std::move(consensusJson)]() mutable { - // Note that no lock is held or acquired during this job. - // This is because generic Consensus guarantees that once a ledger - // is accepted, the consensus results and capture by reference state - // will not change until startRound is called (which happens via - // endConsensus). - RclConsensusLogger clog("onAccept", validating, j_); - this->doAccept(result, prevLedger, closeResolution, rawCloseTimes, mode, std::move(cj)); - this->app_.getOPs().endConsensus(clog.ss()); - }); + app_.getJobQueue().addJob( + jtACCEPT, "AcceptLedger", [=, this, cj = std::move(consensusJson)]() mutable { + // Note that no lock is held or acquired during this job. + // This is because generic Consensus guarantees that once a ledger + // is accepted, the consensus results and capture by reference state + // will not change until startRound is called (which happens via + // endConsensus). + RclConsensusLogger clog("onAccept", validating, j_); + this->doAccept(result, prevLedger, closeResolution, rawCloseTimes, mode, std::move(cj)); + this->app_.getOPs().endConsensus(clog.ss()); + }); } void @@ -395,12 +426,15 @@ RCLConsensus::Adaptor::doAccept( else { // We agreed on a close time - consensusCloseTime = effCloseTime(consensusCloseTime, closeResolution, prevLedger.closeTime()); + consensusCloseTime = + effCloseTime(consensusCloseTime, closeResolution, prevLedger.closeTime()); closeTimeCorrect = true; } - JLOG(j_.debug()) << "Report: Prop=" << (proposing ? "yes" : "no") << " val=" << (validating_ ? "yes" : "no") - << " corLCL=" << (haveCorrectLCL ? "yes" : "no") << " fail=" << (consensusFail ? "yes" : "no"); + JLOG(j_.debug()) << "Report: Prop=" << (proposing ? "yes" : "no") + << " val=" << (validating_ ? "yes" : "no") + << " corLCL=" << (haveCorrectLCL ? "yes" : "no") + << " fail=" << (consensusFail ? "yes" : "no"); JLOG(j_.debug()) << "Report: Prev = " << prevLedger.id() << ":" << prevLedger.seq(); //-------------------------------------------------------------------------- @@ -451,7 +485,9 @@ RCLConsensus::Adaptor::doAccept( std::vector accepted; result.txns.map_->visitLeaves( - [&accepted](boost::intrusive_ptr const& item) { accepted.push_back(item->key()); }); + [&accepted](boost::intrusive_ptr const& item) { + accepted.push_back(item->key()); + }); // Track all the transactions which failed or were marked as retriable for (auto const& r : retriableTxs) @@ -459,7 +495,8 @@ RCLConsensus::Adaptor::doAccept( censorshipDetector_.check( std::move(accepted), - [curr = built.seq(), j = app_.journal("CensorshipDetector"), &failed](uint256 const& id, LedgerIndex seq) { + [curr = built.seq(), j = app_.journal("CensorshipDetector"), &failed]( + uint256 const& id, LedgerIndex seq) { if (failed.count(id)) return true; @@ -468,7 +505,8 @@ RCLConsensus::Adaptor::doAccept( if (wait && (wait % censorshipWarnInternal == 0)) { std::ostringstream ss; - ss << "Potential Censorship: Eligible tx " << id << ", which we are tracking since ledger " << seq + ss << "Potential Censorship: Eligible tx " << id + << ", which we are tracking since ledger " << seq << " has not been included as of ledger " << curr << "."; JLOG(j.warn()) << ss.str(); @@ -596,7 +634,8 @@ RCLConsensus::Adaptor::doAccept( for (auto const& [t, v] : rawCloseTimes.peers) { - JLOG(j_.info()) << std::to_string(v) << " time votes for " << std::to_string(t.time_since_epoch().count()); + JLOG(j_.info()) << std::to_string(v) << " time votes for " + << std::to_string(t.time_since_epoch().count()); closeCount += v; closeTotal += std::chrono::duration_cast(t.time_since_epoch()) * v; } @@ -608,14 +647,18 @@ RCLConsensus::Adaptor::doAccept( using duration = std::chrono::duration; using time_point = std::chrono::time_point; auto offset = time_point{closeTotal} - std::chrono::time_point_cast(closeTime); - JLOG(j_.info()) << "Our close offset is estimated at " << offset.count() << " (" << closeCount << ")"; + JLOG(j_.info()) << "Our close offset is estimated at " << offset.count() << " (" + << closeCount << ")"; app_.timeKeeper().adjustCloseTime(offset); } } void -RCLConsensus::Adaptor::notify(protocol::NodeEvent ne, RCLCxLedger const& ledger, bool haveCorrectLCL) +RCLConsensus::Adaptor::notify( + protocol::NodeEvent ne, + RCLCxLedger const& ledger, + bool haveCorrectLCL) { protocol::TMStatusChange s; @@ -626,7 +669,8 @@ RCLConsensus::Adaptor::notify(protocol::NodeEvent ne, RCLCxLedger const& ledger, s.set_ledgerseq(ledger.seq()); s.set_networktime(app_.timeKeeper().now().time_since_epoch().count()); - s.set_ledgerhashprevious(ledger.parentID().begin(), std::decay_t::bytes); + s.set_ledgerhashprevious( + ledger.parentID().begin(), std::decay_t::bytes); s.set_ledgerhash(ledger.id().begin(), std::decay_t::bytes); std::uint32_t uMin, uMax; @@ -665,7 +709,14 @@ RCLConsensus::Adaptor::buildLCL( return buildLedger(*replayData, tapNONE, app_, j_); } return buildLedger( - previousLedger.ledger_, closeTime, closeTimeCorrect, closeResolution, app_, retriableTxs, failedTxs, j_); + previousLedger.ledger_, + closeTime, + closeTimeCorrect, + closeResolution, + app_, + retriableTxs, + failedTxs, + j_); }(); // Update fee computations based on accepted txs @@ -702,7 +753,11 @@ RCLConsensus::Adaptor::validate(RCLCxLedger const& ledger, RCLTxSet const& txns, auto const& keys = *validatorKeys_.keys; auto v = std::make_shared( - lastValidationTime_, keys.publicKey, keys.secretKey, validatorKeys_.nodeID, [&](STValidation& v) { + lastValidationTime_, + keys.publicKey, + keys.secretKey, + validatorKeys_.nodeID, + [&](STValidation& v) { v.setFieldH256(sfLedgerHash, ledger.id()); v.setFieldH256(sfConsensusHash, txns.id()); @@ -741,7 +796,8 @@ RCLConsensus::Adaptor::validate(RCLCxLedger const& ledger, RCLTxSet const& txns, // Amendments // FIXME: pass `v` and have the function insert the array // directly? - auto const amendments = app_.getAmendmentTable().doValidation(getEnabledAmendments(*ledger.ledger_)); + auto const amendments = + app_.getAmendmentTable().doValidation(getEnabledAmendments(*ledger.ledger_)); if (!amendments.empty()) v.setFieldV256(sfAmendments, STVector256(sfAmendments, amendments)); @@ -767,11 +823,13 @@ RCLConsensus::Adaptor::validate(RCLCxLedger const& ledger, RCLTxSet const& txns, void RCLConsensus::Adaptor::onModeChange(ConsensusMode before, ConsensusMode after) { - JLOG(j_.info()) << "Consensus mode change before=" << to_string(before) << ", after=" << to_string(after); + JLOG(j_.info()) << "Consensus mode change before=" << to_string(before) + << ", after=" << to_string(after); // If we were proposing but aren't any longer, we need to reset the // censorship tracking to avoid bogus warnings. - if ((before == ConsensusMode::proposing || before == ConsensusMode::observing) && before != after) + if ((before == ConsensusMode::proposing || before == ConsensusMode::observing) && + before != after) censorshipDetector_.reset(); mode_ = after; @@ -790,7 +848,9 @@ RCLConsensus::getJson(bool full) const } void -RCLConsensus::timerEntry(NetClock::time_point const& now, std::unique_ptr const& clog) +RCLConsensus::timerEntry( + NetClock::time_point const& now, + std::unique_ptr const& clog) { try { @@ -827,7 +887,9 @@ RCLConsensus::gotTxSet(NetClock::time_point const& now, RCLTxSet const& txSet) //! @see Consensus::simulate void -RCLConsensus::simulate(NetClock::time_point const& now, std::optional consensusDelay) +RCLConsensus::simulate( + NetClock::time_point const& now, + std::optional consensusDelay) { std::lock_guard _{mutex_}; consensus_.simulate(now, consensusDelay); @@ -845,7 +907,8 @@ RCLConsensus::Adaptor::preStartRound(RCLCxLedger const& prevLgr, hash_set= app_.getMaxDisallowedLedger() && !app_.getOPs().isBlocked(); + validating_ = validatorKeys_.keys && prevLgr.seq() >= app_.getMaxDisallowedLedger() && + !app_.getOPs().isBlocked(); // If we are not running in standalone mode and there's a configured UNL, // check to make sure that it's not expired. @@ -865,12 +928,14 @@ RCLConsensus::Adaptor::preStartRound(RCLCxLedger const& prevLgr, hash_set& trustedKeys) const +RCLConsensus::Adaptor::laggards( + Ledger_t::Seq const seq, + hash_set& trustedKeys) const { return app_.getValidations().laggards(seq, trustedKeys); } @@ -931,10 +998,12 @@ RCLConsensus::startRound( std::unique_ptr const& clog) { std::lock_guard _{mutex_}; - consensus_.startRound(now, prevLgrId, prevLgr, nowUntrusted, adaptor_.preStartRound(prevLgr, nowTrusted), clog); + consensus_.startRound( + now, prevLgrId, prevLgr, nowUntrusted, adaptor_.preStartRound(prevLgr, nowTrusted), clog); } -RclConsensusLogger::RclConsensusLogger(char const* label, bool const validating, beast::Journal j) : j_(j) +RclConsensusLogger::RclConsensusLogger(char const* label, bool const validating, beast::Journal j) + : j_(j) { if (!validating && !j.info()) return; @@ -949,11 +1018,11 @@ RclConsensusLogger::~RclConsensusLogger() { if (!ss_) return; - auto const duration = - std::chrono::duration_cast(std::chrono::steady_clock::now() - start_); + auto const duration = std::chrono::duration_cast( + std::chrono::steady_clock::now() - start_); std::stringstream outSs; - outSs << header_ << "duration " << (duration.count() / 1000) << '.' << std::setw(3) << std::setfill('0') - << (duration.count() % 1000) << "s. " << ss_->str(); + outSs << header_ << "duration " << (duration.count() / 1000) << '.' << std::setw(3) + << std::setfill('0') << (duration.count() % 1000) << "s. " << ss_->str(); j_.sink().writeAlways(beast::severities::kInfo, outSs.str()); } diff --git a/src/xrpld/app/consensus/RCLConsensus.h b/src/xrpld/app/consensus/RCLConsensus.h index 3e1b27cd9c..15d36a1aa6 100644 --- a/src/xrpld/app/consensus/RCLConsensus.h +++ b/src/xrpld/app/consensus/RCLConsensus.h @@ -275,7 +275,10 @@ class RCLConsensus @return Tentative consensus result */ Result - onClose(RCLCxLedger const& ledger, NetClock::time_point const& closeTime, ConsensusMode mode); + onClose( + RCLCxLedger const& ledger, + NetClock::time_point const& closeTime, + ConsensusMode mode); /** Process the accepted ledger. @@ -457,7 +460,9 @@ public: //! @see Consensus::timerEntry void - timerEntry(NetClock::time_point const& now, std::unique_ptr const& clog = {}); + timerEntry( + NetClock::time_point const& now, + std::unique_ptr const& clog = {}); //! @see Consensus::gotTxSet void @@ -473,7 +478,9 @@ public: //! @see Consensus::simulate void - simulate(NetClock::time_point const& now, std::optional consensusDelay); + simulate( + NetClock::time_point const& now, + std::optional consensusDelay); //! @see Consensus::proposal bool diff --git a/src/xrpld/app/consensus/RCLCxPeerPos.h b/src/xrpld/app/consensus/RCLCxPeerPos.h index b9ef492aae..5dad4a33eb 100644 --- a/src/xrpld/app/consensus/RCLCxPeerPos.h +++ b/src/xrpld/app/consensus/RCLCxPeerPos.h @@ -36,7 +36,11 @@ public: @param proposal The consensus proposal */ - RCLCxPeerPos(PublicKey const& publicKey, Slice const& signature, uint256 const& suppress, Proposal&& proposal); + RCLCxPeerPos( + PublicKey const& publicKey, + Slice const& signature, + uint256 const& suppress, + Proposal&& proposal); //! Verify the signing hash of the proposal bool diff --git a/src/xrpld/app/consensus/RCLCxTx.h b/src/xrpld/app/consensus/RCLCxTx.h index b7bde11a3b..0af43f7477 100644 --- a/src/xrpld/app/consensus/RCLCxTx.h +++ b/src/xrpld/app/consensus/RCLCxTx.h @@ -155,7 +155,8 @@ public: for (auto const& [k, v] : delta) { XRPL_ASSERT( - (v.first && !v.second) || (v.second && !v.first), "xrpl::RCLTxSet::compare : either side is set"); + (v.first && !v.second) || (v.second && !v.first), + "xrpl::RCLTxSet::compare : either side is set"); ret[k] = static_cast(v.first); } diff --git a/src/xrpld/app/consensus/RCLValidations.cpp b/src/xrpld/app/consensus/RCLValidations.cpp index 8c99ea9939..60e02f53b4 100644 --- a/src/xrpld/app/consensus/RCLValidations.cpp +++ b/src/xrpld/app/consensus/RCLValidations.cpp @@ -15,11 +15,14 @@ namespace xrpl { -RCLValidatedLedger::RCLValidatedLedger(MakeGenesis) : ledgerID_{0}, ledgerSeq_{0}, j_{beast::Journal::getNullSink()} +RCLValidatedLedger::RCLValidatedLedger(MakeGenesis) + : ledgerID_{0}, ledgerSeq_{0}, j_{beast::Journal::getNullSink()} { } -RCLValidatedLedger::RCLValidatedLedger(std::shared_ptr const& ledger, beast::Journal j) +RCLValidatedLedger::RCLValidatedLedger( + std::shared_ptr const& ledger, + beast::Journal j) : ledgerID_{ledger->header().hash}, ledgerSeq_{ledger->seq()}, j_{j} { auto const hashIndex = ledger->read(keylet::skip()); @@ -32,7 +35,8 @@ RCLValidatedLedger::RCLValidatedLedger(std::shared_ptr const& ledg ancestors_ = hashIndex->getFieldV256(sfHashes).value(); } else - JLOG(j_.warn()) << "Ledger " << ledgerSeq_ << ":" << ledgerID_ << " missing recent ancestor hashes"; + JLOG(j_.warn()) << "Ledger " << ledgerSeq_ << ":" << ledgerID_ + << " missing recent ancestor hashes"; } auto @@ -63,8 +67,9 @@ RCLValidatedLedger::operator[](Seq const& s) const -> ID return ancestors_[ancestors_.size() - diff]; } - JLOG(j_.warn()) << "Unable to determine hash of ancestor seq=" << s << " from ledger hash=" << ledgerID_ - << " seq=" << ledgerSeq_ << " (available: " << minSeq() << "-" << seq() << ")"; + JLOG(j_.warn()) << "Unable to determine hash of ancestor seq=" << s + << " from ledger hash=" << ledgerID_ << " seq=" << ledgerSeq_ + << " (available: " << minSeq() << "-" << seq() << ")"; // Default ID that is less than all others return ID{0}; } @@ -103,7 +108,10 @@ RCLValidationsAdaptor::acquire(LedgerHash const& hash) { using namespace std::chrono_literals; auto ledger = perf::measureDurationAndLog( - [&]() { return app_.getLedgerMaster().getLedgerByHash(hash); }, "getLedgerByHash", 10ms, j_); + [&]() { return app_.getLedgerMaster().getLedgerByHash(hash); }, + "getLedgerByHash", + 10ms, + j_); if (!ledger) { @@ -118,8 +126,11 @@ RCLValidationsAdaptor::acquire(LedgerHash const& hash) return std::nullopt; } - XRPL_ASSERT(!ledger->open() && ledger->isImmutable(), "xrpl::RCLValidationsAdaptor::acquire : valid ledger state"); - XRPL_ASSERT(ledger->header().hash == hash, "xrpl::RCLValidationsAdaptor::acquire : ledger hash match"); + XRPL_ASSERT( + !ledger->open() && ledger->isImmutable(), + "xrpl::RCLValidationsAdaptor::acquire : valid ledger state"); + XRPL_ASSERT( + ledger->header().hash == hash, "xrpl::RCLValidationsAdaptor::acquire : ledger hash match"); return RCLValidatedLedger(std::move(ledger), j_); } @@ -160,7 +171,8 @@ handleNewValidation( XRPL_ASSERT(j, "xrpl::handleNewValidation : journal is available"); if (j.has_value()) { - JLOG(j->trace()) << "Bypassing checkAccept for validation " << val->getLedgerHash(); + JLOG(j->trace()) + << "Bypassing checkAccept for validation " << val->getLedgerHash(); } } else @@ -179,8 +191,8 @@ handleNewValidation( // counterintuitively, we *especially* want to forward such validations, // so that our peers will also observe them and take independent notice of // such validators, informing their operators. - if (auto const ls = - val->isTrusted() ? validations.adaptor().journal().error() : validations.adaptor().journal().info(); + if (auto const ls = val->isTrusted() ? validations.adaptor().journal().error() + : validations.adaptor().journal().info(); ls.active()) { auto const id = [&masterKey, &signingKey]() { @@ -193,12 +205,14 @@ handleNewValidation( }(); if (outcome == ValStatus::conflicting) - ls << "Byzantine Behavior Detector: " << (val->isTrusted() ? "trusted " : "untrusted ") << id - << ": Conflicting validation for " << seq << "!\n[" << val->getSerializer().slice() << "]"; + ls << "Byzantine Behavior Detector: " << (val->isTrusted() ? "trusted " : "untrusted ") + << id << ": Conflicting validation for " << seq << "!\n[" + << val->getSerializer().slice() << "]"; if (outcome == ValStatus::multiple) - ls << "Byzantine Behavior Detector: " << (val->isTrusted() ? "trusted " : "untrusted ") << id - << ": Multiple validations for " << seq << "/" << hash << "!\n[" << val->getSerializer().slice() << "]"; + ls << "Byzantine Behavior Detector: " << (val->isTrusted() ? "trusted " : "untrusted ") + << id << ": Multiple validations for " << seq << "/" << hash << "!\n[" + << val->getSerializer().slice() << "]"; } } diff --git a/src/xrpld/app/ledger/AcceptedLedger.cpp b/src/xrpld/app/ledger/AcceptedLedger.cpp index 89806c2337..339c5f57c7 100644 --- a/src/xrpld/app/ledger/AcceptedLedger.cpp +++ b/src/xrpld/app/ledger/AcceptedLedger.cpp @@ -4,13 +4,14 @@ namespace xrpl { -AcceptedLedger::AcceptedLedger(std::shared_ptr const& ledger, Application& app) : mLedger(ledger) +AcceptedLedger::AcceptedLedger(std::shared_ptr const& ledger) : mLedger(ledger) { transactions_.reserve(256); auto insertAll = [&](auto const& txns) { for (auto const& item : txns) - transactions_.emplace_back(std::make_unique(ledger, item.first, item.second)); + transactions_.emplace_back( + std::make_unique(ledger, item.first, item.second)); }; transactions_.reserve(256); diff --git a/src/xrpld/app/ledger/AcceptedLedger.h b/src/xrpld/app/ledger/AcceptedLedger.h index c0f186c781..23cee6ce35 100644 --- a/src/xrpld/app/ledger/AcceptedLedger.h +++ b/src/xrpld/app/ledger/AcceptedLedger.h @@ -1,6 +1,8 @@ #pragma once -#include +#include +#include +#include namespace xrpl { @@ -23,7 +25,7 @@ namespace xrpl { class AcceptedLedger : public CountedObject { public: - AcceptedLedger(std::shared_ptr const& ledger, Application& app); + AcceptedLedger(std::shared_ptr const& ledger); std::shared_ptr const& getLedger() const diff --git a/src/xrpld/app/ledger/AccountStateSF.cpp b/src/xrpld/app/ledger/AccountStateSF.cpp index 048a46e810..79c1f0eaf6 100644 --- a/src/xrpld/app/ledger/AccountStateSF.cpp +++ b/src/xrpld/app/ledger/AccountStateSF.cpp @@ -3,8 +3,12 @@ namespace xrpl { void -AccountStateSF::gotNode(bool, SHAMapHash const& nodeHash, std::uint32_t ledgerSeq, Blob&& nodeData, SHAMapNodeType) - const +AccountStateSF::gotNode( + bool, + SHAMapHash const& nodeHash, + std::uint32_t ledgerSeq, + Blob&& nodeData, + SHAMapNodeType) const { db_.store(hotACCOUNT_NODE, std::move(nodeData), nodeHash.as_uint256(), ledgerSeq); } diff --git a/src/xrpld/app/ledger/AccountStateSF.h b/src/xrpld/app/ledger/AccountStateSF.h index fb9da3a616..d17f3540ea 100644 --- a/src/xrpld/app/ledger/AccountStateSF.h +++ b/src/xrpld/app/ledger/AccountStateSF.h @@ -17,8 +17,12 @@ public: } void - gotNode(bool fromFilter, SHAMapHash const& nodeHash, std::uint32_t ledgerSeq, Blob&& nodeData, SHAMapNodeType type) - const override; + gotNode( + bool fromFilter, + SHAMapHash const& nodeHash, + std::uint32_t ledgerSeq, + Blob&& nodeData, + SHAMapNodeType type) const override; std::optional getNode(SHAMapHash const& nodeHash) const override; diff --git a/src/xrpld/app/ledger/BuildLedger.h b/src/xrpld/app/ledger/BuildLedger.h index 7b4b85c4aa..32d45daea3 100644 --- a/src/xrpld/app/ledger/BuildLedger.h +++ b/src/xrpld/app/ledger/BuildLedger.h @@ -50,6 +50,10 @@ buildLedger( @return The newly built ledger */ std::shared_ptr -buildLedger(LedgerReplay const& replayData, ApplyFlags applyFlags, Application& app, beast::Journal j); +buildLedger( + LedgerReplay const& replayData, + ApplyFlags applyFlags, + Application& app, + beast::Journal j); } // namespace xrpl diff --git a/src/xrpld/app/ledger/ConsensusTransSetSF.cpp b/src/xrpld/app/ledger/ConsensusTransSetSF.cpp index 6a8dbd3d7d..575a1a1460 100644 --- a/src/xrpld/app/ledger/ConsensusTransSetSF.cpp +++ b/src/xrpld/app/ledger/ConsensusTransSetSF.cpp @@ -1,6 +1,5 @@ #include #include -#include #include #include @@ -8,6 +7,7 @@ #include #include #include +#include namespace xrpl { @@ -50,7 +50,8 @@ ConsensusTransSetSF::gotNode( } catch (std::exception const& ex) { - JLOG(j_.warn()) << "Fetched invalid transaction in proposed set. Exception: " << ex.what(); + JLOG(j_.warn()) << "Fetched invalid transaction in proposed set. Exception: " + << ex.what(); } } } diff --git a/src/xrpld/app/ledger/ConsensusTransSetSF.h b/src/xrpld/app/ledger/ConsensusTransSetSF.h index 855577ecee..f439ef9cfa 100644 --- a/src/xrpld/app/ledger/ConsensusTransSetSF.h +++ b/src/xrpld/app/ledger/ConsensusTransSetSF.h @@ -21,8 +21,12 @@ public: // Note that the nodeData is overwritten by this call void - gotNode(bool fromFilter, SHAMapHash const& nodeHash, std::uint32_t ledgerSeq, Blob&& nodeData, SHAMapNodeType type) - const override; + gotNode( + bool fromFilter, + SHAMapHash const& nodeHash, + std::uint32_t ledgerSeq, + Blob&& nodeData, + SHAMapNodeType type) const override; std::optional getNode(SHAMapHash const& nodeHash) const override; diff --git a/src/xrpld/app/ledger/InboundLedger.h b/src/xrpld/app/ledger/InboundLedger.h index 46a8cf19b5..ef1362365d 100644 --- a/src/xrpld/app/ledger/InboundLedger.h +++ b/src/xrpld/app/ledger/InboundLedger.h @@ -166,7 +166,8 @@ private: // Data we have received from peers std::mutex mReceivedDataLock; - std::vector, std::shared_ptr>> mReceivedData; + std::vector, std::shared_ptr>> + mReceivedData; bool mReceiveDispatched; std::unique_ptr mPeerSet; }; diff --git a/src/xrpld/app/ledger/InboundLedgers.h b/src/xrpld/app/ledger/InboundLedgers.h index 30eb69ab7a..ecac6e07e4 100644 --- a/src/xrpld/app/ledger/InboundLedgers.h +++ b/src/xrpld/app/ledger/InboundLedgers.h @@ -34,7 +34,10 @@ public: // VFALCO TODO Remove the dependency on the Peer object. // virtual bool - gotLedgerData(LedgerHash const& ledgerHash, std::shared_ptr, std::shared_ptr) = 0; + gotLedgerData( + LedgerHash const& ledgerHash, + std::shared_ptr, + std::shared_ptr) = 0; virtual void gotStaleData(std::shared_ptr packet) = 0; diff --git a/src/xrpld/app/ledger/InboundTransactions.h b/src/xrpld/app/ledger/InboundTransactions.h index 7b85f56c5f..21c7ba0159 100644 --- a/src/xrpld/app/ledger/InboundTransactions.h +++ b/src/xrpld/app/ledger/InboundTransactions.h @@ -44,7 +44,10 @@ public: * @param message The LedgerData message. */ virtual void - gotData(uint256 const& setHash, std::shared_ptr peer, std::shared_ptr message) = 0; + gotData( + uint256 const& setHash, + std::shared_ptr peer, + std::shared_ptr message) = 0; /** Add a transaction set. * diff --git a/src/xrpld/app/ledger/Ledger.cpp b/src/xrpld/app/ledger/Ledger.cpp index 0f44601679..bde5ca010a 100644 --- a/src/xrpld/app/ledger/Ledger.cpp +++ b/src/xrpld/app/ledger/Ledger.cpp @@ -3,13 +3,13 @@ #include #include #include -#include #include #include #include #include #include +#include #include #include #include @@ -108,7 +108,8 @@ public: txs_iter_impl(txs_iter_impl const&) = default; - txs_iter_impl(bool metadata, SHAMap::const_iterator iter) : metadata_(metadata), iter_(std::move(iter)) + txs_iter_impl(bool metadata, SHAMap::const_iterator iter) + : metadata_(metadata), iter_(std::move(iter)) { } @@ -144,7 +145,11 @@ public: //------------------------------------------------------------------------------ -Ledger::Ledger(create_genesis_t, Config const& config, std::vector const& amendments, Family& family) +Ledger::Ledger( + create_genesis_t, + Config const& config, + std::vector const& amendments, + Family& family) : mImmutable(false) , txMap_(SHAMapType::TRANSACTION, family) , stateMap_(SHAMapType::STATE, family) @@ -155,7 +160,8 @@ Ledger::Ledger(create_genesis_t, Config const& config, std::vector cons header_.drops = INITIAL_XRP; header_.closeTimeResolution = ledgerGenesisTimeResolution; - static auto const id = calcAccountID(generateKeyPair(KeyType::secp256k1, generateSeed("masterpassphrase")).first); + static auto const id = + calcAccountID(generateKeyPair(KeyType::secp256k1, generateSeed("masterpassphrase")).first); { auto const sle = std::make_shared(keylet::account(id)); sle->setFieldU32(sfSequence, 1); @@ -219,7 +225,8 @@ Ledger::Ledger( JLOG(j.warn()) << "Don't have transaction root for ledger" << header_.seq; } - if (header_.accountHash.isNonZero() && !stateMap_.fetchRoot(SHAMapHash{header_.accountHash}, nullptr)) + if (header_.accountHash.isNonZero() && + !stateMap_.fetchRoot(SHAMapHash{header_.accountHash}, nullptr)) { loaded = false; JLOG(j.warn()) << "Don't have state data root for ledger" << header_.seq; @@ -279,7 +286,11 @@ Ledger::Ledger(LedgerHeader const& info, Config const& config, Family& family) header_.hash = calculateLedgerHash(header_); } -Ledger::Ledger(std::uint32_t ledgerSeq, NetClock::time_point closeTime, Config const& config, Family& family) +Ledger::Ledger( + std::uint32_t ledgerSeq, + NetClock::time_point closeTime, + Config const& config, + Family& family) : mImmutable(false) , txMap_(SHAMapType::TRANSACTION, family) , stateMap_(SHAMapType::STATE, family) @@ -314,7 +325,10 @@ Ledger::setImmutable(bool rehash) } void -Ledger::setAccepted(NetClock::time_point closeTime, NetClock::duration closeResolution, bool correctCloseTime) +Ledger::setAccepted( + NetClock::time_point closeTime, + NetClock::duration closeResolution, + bool correctCloseTime) { // Used when we witnessed the consensus. XRPL_ASSERT(!open(), "xrpl::Ledger::setAccepted : valid ledger state"); @@ -329,7 +343,8 @@ bool Ledger::addSLE(SLE const& sle) { auto const s = sle.getSerializer(); - return stateMap_.addItem(SHAMapNodeType::tnACCOUNT_STATE, make_shamapitem(sle.key(), s.slice())); + return stateMap_.addItem( + SHAMapNodeType::tnACCOUNT_STATE, make_shamapitem(sle.key(), s.slice())); } //------------------------------------------------------------------------------ @@ -486,7 +501,8 @@ Ledger::rawInsert(std::shared_ptr const& sle) { Serializer ss; sle->add(ss); - if (!stateMap_.addGiveItem(SHAMapNodeType::tnACCOUNT_STATE, make_shamapitem(sle->key(), ss.slice()))) + if (!stateMap_.addGiveItem( + SHAMapNodeType::tnACCOUNT_STATE, make_shamapitem(sle->key(), ss.slice()))) LogicError("Ledger::rawInsert: key already exists"); } @@ -495,7 +511,8 @@ Ledger::rawReplace(std::shared_ptr const& sle) { Serializer ss; sle->add(ss); - if (!stateMap_.updateGiveItem(SHAMapNodeType::tnACCOUNT_STATE, make_shamapitem(sle->key(), ss.slice()))) + if (!stateMap_.updateGiveItem( + SHAMapNodeType::tnACCOUNT_STATE, make_shamapitem(sle->key(), ss.slice()))) LogicError("Ledger::rawReplace: key not found"); } @@ -614,7 +631,9 @@ Ledger::setup() void Ledger::defaultFees(Config const& config) { - XRPL_ASSERT(fees_.base == 0 && fees_.reserve == 0 && fees_.increment == 0, "xrpl::Ledger::defaultFees : zero fees"); + XRPL_ASSERT( + fees_.base == 0 && fees_.reserve == 0 && fees_.increment == 0, + "xrpl::Ledger::defaultFees : zero fees"); if (fees_.base == 0) fees_.base = config.FEES.reference_fee; if (fees_.reserve == 0) @@ -790,7 +809,8 @@ bool Ledger::assertSensible(beast::Journal ledgerJ) const { if (header_.hash.isNonZero() && header_.accountHash.isNonZero() && - (header_.accountHash == stateMap_.getHash().as_uint256()) && (header_.txHash == txMap_.getHash().as_uint256())) + (header_.accountHash == stateMap_.getHash().as_uint256()) && + (header_.txHash == txMap_.getHash().as_uint256())) { return true; } @@ -838,7 +858,8 @@ Ledger::updateSkipList() created = false; } - XRPL_ASSERT(hashes.size() <= 256, "xrpl::Ledger::updateSkipList : first maximum hashes size"); + XRPL_ASSERT( + hashes.size() <= 256, "xrpl::Ledger::updateSkipList : first maximum hashes size"); hashes.push_back(header_.parentHash); sle->setFieldV256(sfHashes, STVector256(hashes)); sle->setFieldU32(sfLastLedgerSequence, prevIndex); @@ -878,18 +899,12 @@ Ledger::updateSkipList() bool Ledger::isFlagLedger() const { - return header_.seq % FLAG_LEDGER_INTERVAL == 0; + return ::xrpl::isFlagLedger(header_.seq); } bool Ledger::isVotingLedger() const { - return (header_.seq + 1) % FLAG_LEDGER_INTERVAL == 0; -} - -bool -isFlagLedger(LedgerIndex seq) -{ - return seq % FLAG_LEDGER_INTERVAL == 0; + return ::xrpl::isVotingLedger(header_.seq + 1); } static bool @@ -918,7 +933,11 @@ saveValidatedLedger(Application& app, std::shared_ptr const& ledge Returns false on error */ bool -pendSaveValidated(Application& app, std::shared_ptr const& ledger, bool isSynchronous, bool isCurrent) +pendSaveValidated( + Application& app, + std::shared_ptr const& ledger, + bool isSynchronous, + bool isCurrent) { if (!app.getHashRouter().setFlags(ledger->header().hash, HashRouterFlags::SAVED)) { @@ -947,9 +966,9 @@ pendSaveValidated(Application& app, std::shared_ptr const& ledger, // See if we can use the JobQueue. if (!isSynchronous && app.getJobQueue().addJob( - isCurrent ? jtPUBLEDGER : jtPUBOLDLEDGER, std::to_string(ledger->seq()), [&app, ledger, isCurrent]() { - saveValidatedLedger(app, ledger, isCurrent); - })) + isCurrent ? jtPUBLEDGER : jtPUBOLDLEDGER, + std::to_string(ledger->seq()), + [&app, ledger, isCurrent]() { saveValidatedLedger(app, ledger, isCurrent); })) { return true; } @@ -985,8 +1004,8 @@ std::shared_ptr loadLedgerHelper(LedgerHeader const& info, Application& app, bool acquire) { bool loaded; - auto ledger = - std::make_shared(info, loaded, acquire, app.config(), app.getNodeFamily(), app.journal("Ledger")); + auto ledger = std::make_shared( + info, loaded, acquire, app.config(), app.getNodeFamily(), app.journal("Ledger")); if (!loaded) ledger.reset(); @@ -995,7 +1014,10 @@ loadLedgerHelper(LedgerHeader const& info, Application& app, bool acquire) } static void -finishLoadByIndexOrHash(std::shared_ptr const& ledger, Config const& config, beast::Journal j) +finishLoadByIndexOrHash( + std::shared_ptr const& ledger, + Config const& config, + beast::Journal j) { if (!ledger) return; @@ -1022,7 +1044,8 @@ getLatestLedger(Application& app) std::shared_ptr loadByIndex(std::uint32_t ledgerIndex, Application& app, bool acquire) { - if (std::optional info = app.getRelationalDatabase().getLedgerInfoByIndex(ledgerIndex)) + if (std::optional info = + app.getRelationalDatabase().getLedgerInfoByIndex(ledgerIndex)) { std::shared_ptr ledger = loadLedgerHelper(*info, app, acquire); finishLoadByIndexOrHash(ledger, app.config(), app.journal("Ledger")); @@ -1034,11 +1057,14 @@ loadByIndex(std::uint32_t ledgerIndex, Application& app, bool acquire) std::shared_ptr loadByHash(uint256 const& ledgerHash, Application& app, bool acquire) { - if (std::optional info = app.getRelationalDatabase().getLedgerInfoByHash(ledgerHash)) + if (std::optional info = + app.getRelationalDatabase().getLedgerInfoByHash(ledgerHash)) { std::shared_ptr ledger = loadLedgerHelper(*info, app, acquire); finishLoadByIndexOrHash(ledger, app.config(), app.journal("Ledger")); - XRPL_ASSERT(!ledger || ledger->header().hash == ledgerHash, "xrpl::loadByHash : ledger hash match if loaded"); + XRPL_ASSERT( + !ledger || ledger->header().hash == ledgerHash, + "xrpl::loadByHash : ledger hash match if loaded"); return ledger; } return {}; diff --git a/src/xrpld/app/ledger/Ledger.h b/src/xrpld/app/ledger/Ledger.h index cbfbc0030f..f040e93369 100644 --- a/src/xrpld/app/ledger/Ledger.h +++ b/src/xrpld/app/ledger/Ledger.h @@ -81,7 +81,11 @@ public: Amendments specified are enabled in the genesis ledger */ - Ledger(create_genesis_t, Config const& config, std::vector const& amendments, Family& family); + Ledger( + create_genesis_t, + Config const& config, + std::vector const& amendments, + Family& family); Ledger(LedgerHeader const& info, Config const& config, Family& family); @@ -106,7 +110,11 @@ public: Ledger(Ledger const& previous, NetClock::time_point closeTime); // used for database ledgers - Ledger(std::uint32_t ledgerSeq, NetClock::time_point closeTime, Config const& config, Family& family); + Ledger( + std::uint32_t ledgerSeq, + NetClock::time_point closeTime, + Config const& config, + Family& family); ~Ledger() = default; @@ -238,7 +246,10 @@ public: } void - setAccepted(NetClock::time_point closeTime, NetClock::duration closeResolution, bool correctCloseTime); + setAccepted( + NetClock::time_point closeTime, + NetClock::duration closeResolution, + bool correctCloseTime); void setImmutable(bool rehash = true); @@ -391,11 +402,6 @@ private: /** A ledger wrapped in a CachedView. */ using CachedLedger = CachedView; -std::uint32_t constexpr FLAG_LEDGER_INTERVAL = 256; -/** Returns true if the given ledgerIndex is a flag ledgerIndex */ -bool -isFlagLedger(LedgerIndex seq); - //------------------------------------------------------------------------------ // // API @@ -403,7 +409,11 @@ isFlagLedger(LedgerIndex seq); //------------------------------------------------------------------------------ extern bool -pendSaveValidated(Application& app, std::shared_ptr const& ledger, bool isSynchronous, bool isCurrent); +pendSaveValidated( + Application& app, + std::shared_ptr const& ledger, + bool isSynchronous, + bool isCurrent); std::shared_ptr loadLedgerHelper(LedgerHeader const& sinfo, Application& app, bool acquire); diff --git a/src/xrpld/app/ledger/LedgerHistory.cpp b/src/xrpld/app/ledger/LedgerHistory.cpp index 50fe56fd90..f2e2afb3e6 100644 --- a/src/xrpld/app/ledger/LedgerHistory.cpp +++ b/src/xrpld/app/ledger/LedgerHistory.cpp @@ -20,7 +20,12 @@ LedgerHistory::LedgerHistory(beast::insight::Collector::ptr const& collector, Ap std::chrono::seconds{app_.config().getValueFor(SizedItem::ledgerAge)}, stopwatch(), app_.journal("TaggedCache")) - , m_consensus_validated("ConsensusValidated", 64, std::chrono::minutes{5}, stopwatch(), app_.journal("TaggedCache")) + , m_consensus_validated( + "ConsensusValidated", + 64, + std::chrono::minutes{5}, + stopwatch(), + app_.journal("TaggedCache")) , j_(app.journal("LedgerHistory")) { } @@ -31,11 +36,13 @@ LedgerHistory::insert(std::shared_ptr const& ledger, bool validate if (!ledger->isImmutable()) LogicError("mutable Ledger in insert"); - XRPL_ASSERT(ledger->stateMap().getHash().isNonZero(), "xrpl::LedgerHistory::insert : nonzero hash"); + XRPL_ASSERT( + ledger->stateMap().getHash().isNonZero(), "xrpl::LedgerHistory::insert : nonzero hash"); std::unique_lock sl(m_ledgers_by_hash.peekMutex()); - bool const alreadyHad = m_ledgers_by_hash.canonicalize_replace_cache(ledger->header().hash, ledger); + bool const alreadyHad = + m_ledgers_by_hash.canonicalize_replace_cache(ledger->header().hash, ledger); if (validated) mLedgersByIndex[ledger->header().seq] = ledger->header().hash; @@ -71,13 +78,15 @@ LedgerHistory::getLedgerBySeq(LedgerIndex index) if (!ret) return ret; - XRPL_ASSERT(ret->header().seq == index, "xrpl::LedgerHistory::getLedgerBySeq : result sequence match"); + XRPL_ASSERT( + ret->header().seq == index, "xrpl::LedgerHistory::getLedgerBySeq : result sequence match"); { // Add this ledger to the local tracking by index std::unique_lock sl(m_ledgers_by_hash.peekMutex()); - XRPL_ASSERT(ret->isImmutable(), "xrpl::LedgerHistory::getLedgerBySeq : immutable result ledger"); + XRPL_ASSERT( + ret->isImmutable(), "xrpl::LedgerHistory::getLedgerBySeq : immutable result ledger"); m_ledgers_by_hash.canonicalize_replace_client(ret->header().hash, ret); mLedgersByIndex[ret->header().seq] = ret->header().hash; return (ret->header().seq == index) ? ret : nullptr; @@ -107,10 +116,14 @@ LedgerHistory::getLedgerByHash(LedgerHash const& hash) if (!ret) return ret; - XRPL_ASSERT(ret->isImmutable(), "xrpl::LedgerHistory::getLedgerByHash : immutable loaded ledger"); - XRPL_ASSERT(ret->header().hash == hash, "xrpl::LedgerHistory::getLedgerByHash : loaded ledger hash match"); + XRPL_ASSERT( + ret->isImmutable(), "xrpl::LedgerHistory::getLedgerByHash : immutable loaded ledger"); + XRPL_ASSERT( + ret->header().hash == hash, + "xrpl::LedgerHistory::getLedgerByHash : loaded ledger hash match"); m_ledgers_by_hash.canonicalize_replace_client(ret->header().hash, ret); - XRPL_ASSERT(ret->header().hash == hash, "xrpl::LedgerHistory::getLedgerByHash : result hash match"); + XRPL_ASSERT( + ret->header().hash == hash, "xrpl::LedgerHistory::getLedgerByHash : result hash match"); return ret; } @@ -122,17 +135,23 @@ log_one(ReadView const& ledger, uint256 const& tx, char const* msg, beast::Journ if (metaData != nullptr) { - JLOG(j.debug()) << "MISMATCH on TX " << tx << ": " << msg << " is missing this transaction:\n" + JLOG(j.debug()) << "MISMATCH on TX " << tx << ": " << msg + << " is missing this transaction:\n" << metaData->getJson(JsonOptions::none); } else { - JLOG(j.debug()) << "MISMATCH on TX " << tx << ": " << msg << " is missing this transaction."; + JLOG(j.debug()) << "MISMATCH on TX " << tx << ": " << msg + << " is missing this transaction."; } } static void -log_metadata_difference(ReadView const& builtLedger, ReadView const& validLedger, uint256 const& tx, beast::Journal j) +log_metadata_difference( + ReadView const& builtLedger, + ReadView const& validLedger, + uint256 const& tx, + beast::Journal j) { auto getMeta = [](ReadView const& ledger, uint256 const& txID) { std::optional ret; @@ -144,7 +163,8 @@ log_metadata_difference(ReadView const& builtLedger, ReadView const& validLedger auto validMetaData = getMeta(validLedger, tx); auto builtMetaData = getMeta(builtLedger, tx); - XRPL_ASSERT(validMetaData || builtMetaData, "xrpl::log_metadata_difference : some metadata present"); + XRPL_ASSERT( + validMetaData || builtMetaData, "xrpl::log_metadata_difference : some metadata present"); if (validMetaData && builtMetaData) { @@ -169,9 +189,11 @@ log_metadata_difference(ReadView const& builtLedger, ReadView const& validLedger { JLOG(j.debug()) << "MISMATCH on TX " << tx << ": Different result and index!"; JLOG(j.debug()) << " Built:" - << " Result: " << builtMetaData->getResult() << " Index: " << builtMetaData->getIndex(); + << " Result: " << builtMetaData->getResult() + << " Index: " << builtMetaData->getIndex(); JLOG(j.debug()) << " Valid:" - << " Result: " << validMetaData->getResult() << " Index: " << validMetaData->getIndex(); + << " Result: " << validMetaData->getResult() + << " Index: " << validMetaData->getIndex(); } else if (result_diff) { @@ -194,7 +216,8 @@ log_metadata_difference(ReadView const& builtLedger, ReadView const& validLedger { if (result_diff && index_diff) { - JLOG(j.debug()) << "MISMATCH on TX " << tx << ": Different result, index and nodes!"; + JLOG(j.debug()) << "MISMATCH on TX " << tx + << ": Different result, index and nodes!"; JLOG(j.debug()) << " Built:\n" << builtMetaData->getJson(JsonOptions::none); JLOG(j.debug()) << " Valid:\n" << validMetaData->getJson(JsonOptions::none); } @@ -255,7 +278,9 @@ leaves(SHAMap const& sm) std::vector v; for (auto const& item : sm) v.push_back(&item); - std::sort(v.begin(), v.end(), [](SHAMapItem const* lhs, SHAMapItem const* rhs) { return lhs->key() < rhs->key(); }); + std::sort(v.begin(), v.end(), [](SHAMapItem const* lhs, SHAMapItem const* rhs) { + return lhs->key() < rhs->key(); + }); return v; } @@ -282,7 +307,8 @@ LedgerHistory::handleMismatch( } XRPL_ASSERT( - builtLedger->header().seq == validLedger->header().seq, "xrpl::LedgerHistory::handleMismatch : sequence match"); + builtLedger->header().seq == validLedger->header().seq, + "xrpl::LedgerHistory::handleMismatch : sequence match"); if (auto stream = j_.debug()) { @@ -315,7 +341,8 @@ LedgerHistory::handleMismatch( << " built: " << to_string(*builtConsensusHash) << " validated: " << to_string(*validatedConsensusHash); else - JLOG(j_.error()) << "MISMATCH with same consensus transaction set: " << to_string(*builtConsensusHash); + JLOG(j_.error()) << "MISMATCH with same consensus transaction set: " + << to_string(*builtConsensusHash); } // Find differences between built and valid ledgers @@ -382,9 +409,14 @@ LedgerHistory::builtLedger( { if (entry->validated.value() != hash) { - JLOG(j_.error()) << "MISMATCH: seq=" << index << " validated:" << entry->validated.value() - << " then:" << hash; - handleMismatch(hash, entry->validated.value(), consensusHash, entry->validatedConsensusHash, consensus); + JLOG(j_.error()) << "MISMATCH: seq=" << index + << " validated:" << entry->validated.value() << " then:" << hash; + handleMismatch( + hash, + entry->validated.value(), + consensusHash, + entry->validatedConsensusHash, + consensus); } else { @@ -399,7 +431,9 @@ LedgerHistory::builtLedger( } void -LedgerHistory::validatedLedger(std::shared_ptr const& ledger, std::optional const& consensusHash) +LedgerHistory::validatedLedger( + std::shared_ptr const& ledger, + std::optional const& consensusHash) { LedgerIndex index = ledger->header().seq; LedgerHash hash = ledger->header().hash; @@ -414,9 +448,14 @@ LedgerHistory::validatedLedger(std::shared_ptr const& ledger, std: { if (entry->built.value() != hash) { - JLOG(j_.error()) << "MISMATCH: seq=" << index << " built:" << entry->built.value() << " then:" << hash; + JLOG(j_.error()) << "MISMATCH: seq=" << index << " built:" << entry->built.value() + << " then:" << hash; handleMismatch( - entry->built.value(), hash, entry->builtConsensusHash, consensusHash, entry->consensus.value()); + entry->built.value(), + hash, + entry->builtConsensusHash, + consensusHash, + entry->consensus.value()); } else { diff --git a/src/xrpld/app/ledger/LedgerHistory.h b/src/xrpld/app/ledger/LedgerHistory.h index e8784eb599..6ec279b28a 100644 --- a/src/xrpld/app/ledger/LedgerHistory.h +++ b/src/xrpld/app/ledger/LedgerHistory.h @@ -63,7 +63,9 @@ public: /** Report that we have validated a particular ledger */ void - validatedLedger(std::shared_ptr const&, std::optional const& consensusHash); + validatedLedger( + std::shared_ptr const&, + std::optional const& consensusHash); /** Repair a hash to index mapping @param ledgerIndex The index whose mapping is to be repaired diff --git a/src/xrpld/app/ledger/LedgerMaster.h b/src/xrpld/app/ledger/LedgerMaster.h index ceb9fa9045..c25e553455 100644 --- a/src/xrpld/app/ledger/LedgerMaster.h +++ b/src/xrpld/app/ledger/LedgerMaster.h @@ -185,7 +185,10 @@ public: void checkAccept(uint256 const& hash, std::uint32_t seq); void - consensusBuilt(std::shared_ptr const& ledger, uint256 const& consensusHash, Json::Value consensus); + consensusBuilt( + std::shared_ptr const& ledger, + uint256 const& consensusHash, + Json::Value consensus); void setBuildingLedger(LedgerIndex index); diff --git a/src/xrpld/app/ledger/LedgerReplayTask.h b/src/xrpld/app/ledger/LedgerReplayTask.h index 94eeee5f51..028e7ba0bd 100644 --- a/src/xrpld/app/ledger/LedgerReplayTask.h +++ b/src/xrpld/app/ledger/LedgerReplayTask.h @@ -42,7 +42,10 @@ public: * @param finishLedgerHash hash of the last ledger in the range * @param totalNumLedgers number of ledgers to download */ - TaskParameter(InboundLedger::Reason r, uint256 const& finishLedgerHash, std::uint32_t totalNumLedgers); + TaskParameter( + InboundLedger::Reason r, + uint256 const& finishLedgerHash, + std::uint32_t totalNumLedgers); /** * fill all the fields that was not filled during construction diff --git a/src/xrpld/app/ledger/LedgerReplayer.h b/src/xrpld/app/ledger/LedgerReplayer.h index 0d08e5a76f..218d22fb07 100644 --- a/src/xrpld/app/ledger/LedgerReplayer.h +++ b/src/xrpld/app/ledger/LedgerReplayer.h @@ -52,7 +52,10 @@ std::uint32_t constexpr MAX_QUEUED_TASKS = 100; class LedgerReplayer final { public: - LedgerReplayer(Application& app, InboundLedgers& inboundLedgers, std::unique_ptr peerSetBuilder); + LedgerReplayer( + Application& app, + InboundLedgers& inboundLedgers, + std::unique_ptr peerSetBuilder); ~LedgerReplayer(); @@ -86,7 +89,9 @@ public: * @note info and txns must have been verified against the ledger hash */ void - gotReplayDelta(LedgerHeader const& info, std::map>&& txns); + gotReplayDelta( + LedgerHeader const& info, + std::map>&& txns); /** Remove completed tasks */ void diff --git a/src/xrpld/app/ledger/LedgerToJson.h b/src/xrpld/app/ledger/LedgerToJson.h index 8cde134d23..9def1c3826 100644 --- a/src/xrpld/app/ledger/LedgerToJson.h +++ b/src/xrpld/app/ledger/LedgerToJson.h @@ -12,14 +12,26 @@ namespace xrpl { struct LedgerFill { - LedgerFill(ReadView const& l, RPC::Context const* ctx, int o = 0, std::vector q = {}) + LedgerFill( + ReadView const& l, + RPC::Context const* ctx, + int o = 0, + std::vector q = {}) : ledger(l), options(o), txQueue(std::move(q)), context(ctx) { if (context) closeTime = context->ledgerMaster.getCloseTimeBySeq(ledger.seq()); } - enum Options { dumpTxrp = 1, dumpState = 2, expand = 4, full = 8, binary = 16, ownerFunds = 32, dumpQueue = 64 }; + enum Options { + dumpTxrp = 1, + dumpState = 2, + expand = 4, + full = 8, + binary = 16, + ownerFunds = 32, + dumpQueue = 64 + }; ReadView const& ledger; int options; diff --git a/src/xrpld/app/ledger/OpenLedger.h b/src/xrpld/app/ledger/OpenLedger.h index 187086862c..76123bafae 100644 --- a/src/xrpld/app/ledger/OpenLedger.h +++ b/src/xrpld/app/ledger/OpenLedger.h @@ -60,7 +60,10 @@ public: @param ledger A closed ledger */ - explicit OpenLedger(std::shared_ptr const& ledger, CachedSLEs& cache, beast::Journal journal); + explicit OpenLedger( + std::shared_ptr const& ledger, + CachedSLEs& cache, + beast::Journal journal); /** Returns `true` if there are no transactions. diff --git a/src/xrpld/app/ledger/OrderBookDB.h b/src/xrpld/app/ledger/OrderBookDB.h deleted file mode 100644 index da604d7e22..0000000000 --- a/src/xrpld/app/ledger/OrderBookDB.h +++ /dev/null @@ -1,75 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include - -#include -#include - -namespace xrpl { - -class OrderBookDB -{ -public: - explicit OrderBookDB(Application& app); - - void - setup(std::shared_ptr const& ledger); - void - update(std::shared_ptr const& ledger); - - void - addOrderBook(Book const&); - - /** @return a list of all orderbooks that want this issuerID and currencyID. - */ - std::vector - getBooksByTakerPays(Issue const&, std::optional const& domain = std::nullopt); - - /** @return a count of all orderbooks that want this issuerID and - currencyID. */ - int - getBookSize(Issue const&, std::optional const& domain = std::nullopt); - - bool - isBookToXRP(Issue const&, std::optional domain = std::nullopt); - - BookListeners::pointer - getBookListeners(Book const&); - BookListeners::pointer - makeBookListeners(Book const&); - - // see if this txn effects any orderbook - void - processTxn(std::shared_ptr const& ledger, AcceptedLedgerTx const& alTx, MultiApiJson const& jvObj); - -private: - Application& app_; - - // Maps order books by "issue in" to "issue out": - hardened_hash_map> allBooks_; - - hardened_hash_map, hardened_hash_set> domainBooks_; - - // does an order book to XRP exist - hash_set xrpBooks_; - - // does an order book to XRP exist - hash_set> xrpDomainBooks_; - - std::recursive_mutex mLock; - - using BookToListenersMap = hash_map; - - BookToListenersMap mListeners; - - std::atomic seq_; - - beast::Journal const j_; -}; - -} // namespace xrpl diff --git a/src/xrpld/app/ledger/OrderBookDB.cpp b/src/xrpld/app/ledger/OrderBookDBImpl.cpp similarity index 81% rename from src/xrpld/app/ledger/OrderBookDB.cpp rename to src/xrpld/app/ledger/OrderBookDBImpl.cpp index 81a3bf5e4a..a4eb0fb1ca 100644 --- a/src/xrpld/app/ledger/OrderBookDB.cpp +++ b/src/xrpld/app/ledger/OrderBookDBImpl.cpp @@ -1,24 +1,33 @@ #include -#include -#include -#include -#include -#include +#include #include #include #include +#include +#include namespace xrpl { -OrderBookDB::OrderBookDB(Application& app) : app_(app), seq_(0), j_(app.journal("OrderBookDB")) +OrderBookDBImpl::OrderBookDBImpl(ServiceRegistry& registry, OrderBookDBConfig const& config) + : registry_(registry) + , pathSearchMax_(config.pathSearchMax) + , standalone_(config.standalone) + , seq_(0) + , j_(registry.journal("OrderBookDB")) { } -void -OrderBookDB::setup(std::shared_ptr const& ledger) +std::unique_ptr +make_OrderBookDB(ServiceRegistry& registry, OrderBookDBConfig const& config) { - if (!app_.config().standalone() && app_.getOPs().isNeedNetworkLedger()) + return std::make_unique(registry, config); +} + +void +OrderBookDBImpl::setup(std::shared_ptr const& ledger) +{ + if (!standalone_ && registry_.getOPs().isNeedNetworkLedger()) { JLOG(j_.warn()) << "Eliding full order book update: no ledger"; return; @@ -40,25 +49,29 @@ OrderBookDB::setup(std::shared_ptr const& ledger) JLOG(j_.debug()) << "Full order book update: " << seq << " to " << ledger->seq(); - if (app_.config().PATH_SEARCH_MAX != 0) + if (pathSearchMax_ != 0) { - if (app_.config().standalone()) + if (standalone_) update(ledger); else - app_.getJobQueue().addJob(jtUPDATE_PF, "OrderBookUpd", [this, ledger]() { update(ledger); }); + registry_.getJobQueue().addJob( + jtUPDATE_PF, "OrderBookUpd" + std::to_string(ledger->seq()), [this, ledger]() { + update(ledger); + }); } } void -OrderBookDB::update(std::shared_ptr const& ledger) +OrderBookDBImpl::update(std::shared_ptr const& ledger) { - if (app_.config().PATH_SEARCH_MAX == 0) + if (pathSearchMax_ == 0) return; // pathfinding has been disabled // A newer full update job is pending if (auto const seq = seq_.load(); seq > ledger->seq()) { - JLOG(j_.debug()) << "Eliding update for " << ledger->seq() << " because of pending update to later " << seq; + JLOG(j_.debug()) << "Eliding update for " << ledger->seq() + << " because of pending update to later " << seq; return; } @@ -79,7 +92,7 @@ OrderBookDB::update(std::shared_ptr const& ledger) { for (auto& sle : ledger->sles) { - if (app_.isStopping()) + if (registry_.isStopping()) { JLOG(j_.info()) << "Update halted because the process is stopping"; seq_.store(0); @@ -143,11 +156,11 @@ OrderBookDB::update(std::shared_ptr const& ledger) xrpDomainBooks_.swap(xrpDomainBooks); } - app_.getLedgerMaster().newOrderBookDB(); + registry_.getLedgerMaster().newOrderBookDB(); } void -OrderBookDB::addOrderBook(Book const& book) +OrderBookDBImpl::addOrderBook(Book const& book) { bool toXRP = isXRP(book.out); @@ -166,7 +179,7 @@ OrderBookDB::addOrderBook(Book const& book) // return list of all orderbooks that want this issuerID and currencyID std::vector -OrderBookDB::getBooksByTakerPays(Issue const& issue, std::optional const& domain) +OrderBookDBImpl::getBooksByTakerPays(Issue const& issue, std::optional const& domain) { std::vector ret; @@ -194,7 +207,7 @@ OrderBookDB::getBooksByTakerPays(Issue const& issue, std::optional cons } int -OrderBookDB::getBookSize(Issue const& issue, std::optional const& domain) +OrderBookDBImpl::getBookSize(Issue const& issue, std::optional const& domain) { std::lock_guard sl(mLock); @@ -213,7 +226,7 @@ OrderBookDB::getBookSize(Issue const& issue, std::optional const& domai } bool -OrderBookDB::isBookToXRP(Issue const& issue, std::optional domain) +OrderBookDBImpl::isBookToXRP(Issue const& issue, std::optional domain) { std::lock_guard sl(mLock); if (domain) @@ -222,7 +235,7 @@ OrderBookDB::isBookToXRP(Issue const& issue, std::optional domain) } BookListeners::pointer -OrderBookDB::makeBookListeners(Book const& book) +OrderBookDBImpl::makeBookListeners(Book const& book) { std::lock_guard sl(mLock); auto ret = getBookListeners(book); @@ -242,7 +255,7 @@ OrderBookDB::makeBookListeners(Book const& book) } BookListeners::pointer -OrderBookDB::getBookListeners(Book const& book) +OrderBookDBImpl::getBookListeners(Book const& book) { BookListeners::pointer ret; std::lock_guard sl(mLock); @@ -257,7 +270,7 @@ OrderBookDB::getBookListeners(Book const& book) // Based on the meta, send the meta to the streams that are listening. // We need to determine which streams a given meta effects. void -OrderBookDB::processTxn( +OrderBookDBImpl::processTxn( std::shared_ptr const& ledger, AcceptedLedgerTx const& alTx, MultiApiJson const& jvObj) @@ -278,8 +291,8 @@ OrderBookDB::processTxn( if (node.getFieldU16(sfLedgerEntryType) == ltOFFER) { auto process = [&, this](SField const& field) { - if (auto data = dynamic_cast(node.peekAtPField(field)); - data && data->isFieldPresent(sfTakerPays) && data->isFieldPresent(sfTakerGets)) + if (auto data = dynamic_cast(node.peekAtPField(field)); data && + data->isFieldPresent(sfTakerPays) && data->isFieldPresent(sfTakerGets)) { auto listeners = getBookListeners( {data->getFieldAmount(sfTakerGets).issue(), diff --git a/src/xrpld/app/ledger/OrderBookDBImpl.h b/src/xrpld/app/ledger/OrderBookDBImpl.h new file mode 100644 index 0000000000..d9043f942e --- /dev/null +++ b/src/xrpld/app/ledger/OrderBookDBImpl.h @@ -0,0 +1,96 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace xrpl { + +/** Configuration for OrderBookDB */ +struct OrderBookDBConfig +{ + int pathSearchMax; + bool standalone; +}; + +/** Create an OrderBookDB instance. + + @param registry Service registry for accessing other services + @param config Configuration parameters + @return A new OrderBookDB instance +*/ +std::unique_ptr +make_OrderBookDB(ServiceRegistry& registry, OrderBookDBConfig const& config); + +class OrderBookDBImpl final : public OrderBookDB +{ +public: + OrderBookDBImpl(ServiceRegistry& registry, OrderBookDBConfig const& config); + + // OrderBookDB interface implementation + void + setup(std::shared_ptr const& ledger) override; + + void + addOrderBook(Book const& book) override; + + std::vector + getBooksByTakerPays(Issue const& issue, std::optional const& domain = std::nullopt) + override; + + int + getBookSize(Issue const& issue, std::optional const& domain = std::nullopt) override; + + bool + isBookToXRP(Issue const& issue, std::optional domain = std::nullopt) override; + + // OrderBookDBImpl-specific methods + void + update(std::shared_ptr const& ledger); + + // see if this txn effects any orderbook + void + processTxn( + std::shared_ptr const& ledger, + AcceptedLedgerTx const& alTx, + MultiApiJson const& jvObj) override; + + BookListeners::pointer + getBookListeners(Book const&) override; + BookListeners::pointer + makeBookListeners(Book const&) override; + +private: + ServiceRegistry& registry_; + int const pathSearchMax_; + bool const standalone_; + + // Maps order books by "issue in" to "issue out": + hardened_hash_map> allBooks_; + + hardened_hash_map, hardened_hash_set> domainBooks_; + + // does an order book to XRP exist + hash_set xrpBooks_; + + // does an order book to XRP exist + hash_set> xrpDomainBooks_; + + std::recursive_mutex mLock; + + using BookToListenersMap = hash_map; + + BookToListenersMap mListeners; + + std::atomic seq_; + + beast::Journal const j_; +}; + +} // namespace xrpl diff --git a/src/xrpld/app/ledger/TransactionMaster.h b/src/xrpld/app/ledger/TransactionMaster.h index 039ff5cb99..1c5894d3bb 100644 --- a/src/xrpld/app/ledger/TransactionMaster.h +++ b/src/xrpld/app/ledger/TransactionMaster.h @@ -42,11 +42,18 @@ public: fetch(uint256 const&, ClosedInterval const& range, error_code_i& ec); std::shared_ptr - fetch(boost::intrusive_ptr const& item, SHAMapNodeType type, std::uint32_t uCommitLedger); + fetch( + boost::intrusive_ptr const& item, + SHAMapNodeType type, + std::uint32_t uCommitLedger); // return value: true = we had the transaction already bool - inLedger(uint256 const& hash, std::uint32_t ledger, std::optional tseq, std::optional netID); + inLedger( + uint256 const& hash, + std::uint32_t ledger, + std::optional tseq, + std::optional netID); void canonicalize(std::shared_ptr* pTransaction); diff --git a/src/xrpld/app/ledger/TransactionStateSF.cpp b/src/xrpld/app/ledger/TransactionStateSF.cpp index ee2febbd83..11d3c83058 100644 --- a/src/xrpld/app/ledger/TransactionStateSF.cpp +++ b/src/xrpld/app/ledger/TransactionStateSF.cpp @@ -11,7 +11,9 @@ TransactionStateSF::gotNode( SHAMapNodeType type) const { - XRPL_ASSERT(type != SHAMapNodeType::tnTRANSACTION_NM, "xrpl::TransactionStateSF::gotNode : valid input"); + XRPL_ASSERT( + type != SHAMapNodeType::tnTRANSACTION_NM, + "xrpl::TransactionStateSF::gotNode : valid input"); db_.store(hotTRANSACTION_NODE, std::move(nodeData), nodeHash.as_uint256(), ledgerSeq); } diff --git a/src/xrpld/app/ledger/TransactionStateSF.h b/src/xrpld/app/ledger/TransactionStateSF.h index 2851884cfd..9ca84c2610 100644 --- a/src/xrpld/app/ledger/TransactionStateSF.h +++ b/src/xrpld/app/ledger/TransactionStateSF.h @@ -17,8 +17,12 @@ public: } void - gotNode(bool fromFilter, SHAMapHash const& nodeHash, std::uint32_t ledgerSeq, Blob&& nodeData, SHAMapNodeType type) - const override; + gotNode( + bool fromFilter, + SHAMapHash const& nodeHash, + std::uint32_t ledgerSeq, + Blob&& nodeData, + SHAMapNodeType type) const override; std::optional getNode(SHAMapHash const& nodeHash) const override; diff --git a/src/xrpld/app/ledger/detail/BuildLedger.cpp b/src/xrpld/app/ledger/detail/BuildLedger.cpp index 1414441b35..c4f8f9e60a 100644 --- a/src/xrpld/app/ledger/detail/BuildLedger.cpp +++ b/src/xrpld/app/ledger/detail/BuildLedger.cpp @@ -2,10 +2,11 @@ #include #include #include +#include #include -#include #include +#include namespace xrpl { @@ -88,8 +89,8 @@ applyTransactions( // Attempt to apply all of the retriable transactions for (int pass = 0; pass < LEDGER_TOTAL_PASSES; ++pass) { - JLOG(j.debug()) << (certainRetry ? "Pass: " : "Final pass: ") << pass << " begins (" << txns.size() - << " transactions)"; + JLOG(j.debug()) << (certainRetry ? "Pass: " : "Final pass: ") << pass << " begins (" + << txns.size() << " transactions)"; int changes = 0; auto it = txns.begin(); @@ -130,8 +131,8 @@ applyTransactions( } } - JLOG(j.debug()) << (certainRetry ? "Pass: " : "Final pass: ") << pass << " completed (" << changes - << " changes)"; + JLOG(j.debug()) << (certainRetry ? "Pass: " : "Final pass: ") << pass << " completed (" + << changes << " changes)"; // Accumulate changes. count += changes; @@ -163,7 +164,8 @@ buildLedger( std::set& failedTxns, beast::Journal j) { - JLOG(j.debug()) << "Report: Transaction Set = " << txns.key() << ", close " << closeTime.time_since_epoch().count() + JLOG(j.debug()) << "Report: Transaction Set = " << txns.key() << ", close " + << closeTime.time_since_epoch().count() << (closeTimeCorrect ? "" : " (incorrect)"); return buildLedgerImpl( @@ -179,18 +181,24 @@ buildLedger( auto const applied = applyTransactions(app, built, txns, failedTxns, accum, j); if (!txns.empty() || !failedTxns.empty()) - JLOG(j.debug()) << "Applied " << applied << " transactions; " << failedTxns.size() << " failed and " - << txns.size() << " will be retried. " - << "Total transactions in ledger (including Inner Batch): " << accum.txCount(); + JLOG(j.debug()) << "Applied " << applied << " transactions; " << failedTxns.size() + << " failed and " << txns.size() << " will be retried. " + << "Total transactions in ledger (including Inner Batch): " + << accum.txCount(); else JLOG(j.debug()) << "Applied " << applied << " transactions. " - << "Total transactions in ledger (including Inner Batch): " << accum.txCount(); + << "Total transactions in ledger (including Inner Batch): " + << accum.txCount(); }); } // Build a ledger by replaying std::shared_ptr -buildLedger(LedgerReplay const& replayData, ApplyFlags applyFlags, Application& app, beast::Journal j) +buildLedger( + LedgerReplay const& replayData, + ApplyFlags applyFlags, + Application& app, + beast::Journal j) { auto const& replayLedger = replayData.replay(); diff --git a/src/xrpld/app/ledger/detail/InboundLedger.cpp b/src/xrpld/app/ledger/detail/InboundLedger.cpp index 3c8f61a915..4dd8ab887e 100644 --- a/src/xrpld/app/ledger/detail/InboundLedger.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedger.cpp @@ -61,7 +61,12 @@ InboundLedger::InboundLedger( Reason reason, clock_type& clock, std::unique_ptr peerSet) - : TimeoutCounter(app, hash, ledgerAcquireTimeout, {jtLEDGER_DATA, "InboundLedger", 5}, app.journal("InboundLedger")) + : TimeoutCounter( + app, + hash, + ledgerAcquireTimeout, + {jtLEDGER_DATA, "InboundLedger", 5}, + app.journal("InboundLedger")) , m_clock(clock) , mHaveHeader(false) , mHaveState(false) @@ -115,8 +120,9 @@ std::size_t InboundLedger::getPeerCount() const { auto const& peerIds = mPeerSet->getPeerIds(); - return std::count_if( - peerIds.begin(), peerIds.end(), [this](auto id) { return (app_.overlay().findPeerByShortID(id) != nullptr); }); + return std::count_if(peerIds.begin(), peerIds.end(), [this](auto id) { + return (app_.overlay().findPeerByShortID(id) != nullptr); + }); } void @@ -164,7 +170,8 @@ InboundLedger::~InboundLedger() { JLOG(journal_.debug()) << "Acquire " << hash_ << " abort " << ((timeouts_ == 0) ? std::string() - : (std::string("timeouts:") + std::to_string(timeouts_) + " ")) + : (std::string("timeouts:") + + std::to_string(timeouts_) + " ")) << mStats.get(); } } @@ -216,7 +223,8 @@ InboundLedger::tryDB(NodeStore::Database& srcDB) if (mLedger->header().hash != hash_ || (mSeq != 0 && mSeq != mLedger->header().seq)) { // We know for a fact the ledger can never be acquired - JLOG(journal_.warn()) << "hash " << hash_ << " seq " << std::to_string(mSeq) << " cannot be a ledger"; + JLOG(journal_.warn()) + << "hash " << hash_ << " seq " << std::to_string(mSeq) << " cannot be a ledger"; mLedger.reset(); failed_ = true; } @@ -253,7 +261,8 @@ InboundLedger::tryDB(NodeStore::Database& srcDB) return; // Store the ledger header in the ledger's database - mLedger->stateMap().family().db().store(hotLEDGER, std::move(*data), hash_, mLedger->header().seq); + mLedger->stateMap().family().db().store( + hotLEDGER, std::move(*data), hash_, mLedger->header().seq); } if (mSeq == 0) @@ -394,8 +403,9 @@ InboundLedger::done() touch(); JLOG(journal_.debug()) << "Acquire " << hash_ << (failed_ ? " fail " : " ") - << ((timeouts_ == 0) ? std::string() - : (std::string("timeouts:") + std::to_string(timeouts_) + " ")) + << ((timeouts_ == 0) + ? std::string() + : (std::string("timeouts:") + std::to_string(timeouts_) + " ")) << mStats.get(); XRPL_ASSERT(complete_ || failed_, "xrpl::InboundLedger::done : complete or failed"); @@ -532,7 +542,8 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) tmGL.set_itype(protocol::liBASE); if (mSeq != 0) tmGL.set_ledgerseq(mSeq); - JLOG(journal_.trace()) << "Sending header request to " << (peer ? "selected peer" : "all peers"); + JLOG(journal_.trace()) << "Sending header request to " + << (peer ? "selected peer" : "all peers"); mPeerSet->sendRequest(tmGL, peer); return; } @@ -571,7 +582,8 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) // we need the root node tmGL.set_itype(protocol::liAS_NODE); *tmGL.add_nodeids() = SHAMapNodeID().getRawString(); - JLOG(journal_.trace()) << "Sending AS root request to " << (peer ? "selected peer" : "all peers"); + JLOG(journal_.trace()) + << "Sending AS root request to " << (peer ? "selected peer" : "all peers"); mPeerSet->sendRequest(tmGL, peer); return; } @@ -611,8 +623,8 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) *(tmGL.add_nodeids()) = id.first.getRawString(); } - JLOG(journal_.trace()) << "Sending AS node request (" << nodes.size() << ") to " - << (peer ? "selected peer" : "all peers"); + JLOG(journal_.trace()) << "Sending AS node request (" << nodes.size() + << ") to " << (peer ? "selected peer" : "all peers"); mPeerSet->sendRequest(tmGL, peer); return; } @@ -641,7 +653,8 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) // we need the root node tmGL.set_itype(protocol::liTX_NODE); *(tmGL.add_nodeids()) = SHAMapNodeID().getRawString(); - JLOG(journal_.trace()) << "Sending TX root request to " << (peer ? "selected peer" : "all peers"); + JLOG(journal_.trace()) + << "Sending TX root request to " << (peer ? "selected peer" : "all peers"); mPeerSet->sendRequest(tmGL, peer); return; } @@ -689,20 +702,23 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) if (complete_ || failed_) { - JLOG(journal_.debug()) << "Done:" << (complete_ ? " complete" : "") << (failed_ ? " failed " : " ") - << mLedger->header().seq; + JLOG(journal_.debug()) << "Done:" << (complete_ ? " complete" : "") + << (failed_ ? " failed " : " ") << mLedger->header().seq; sl.unlock(); done(); } } void -InboundLedger::filterNodes(std::vector>& nodes, TriggerReason reason) +InboundLedger::filterNodes( + std::vector>& nodes, + TriggerReason reason) { // Sort nodes so that the ones we haven't recently // requested come before the ones we have. - auto dup = std::stable_partition( - nodes.begin(), nodes.end(), [this](auto const& item) { return mRecentNodes.count(item.second) == 0; }); + auto dup = std::stable_partition(nodes.begin(), nodes.end(), [this](auto const& item) { + return mRecentNodes.count(item.second) == 0; + }); // If everything is a duplicate we don't want to send // any query at all except on a timeout where we need @@ -750,7 +766,8 @@ InboundLedger::takeHeader(std::string const& data) mLedger = std::make_shared(deserializeHeader(makeSlice(data)), app_.config(), *f); if (mLedger->header().hash != hash_ || (mSeq != 0 && mSeq != mLedger->header().seq)) { - JLOG(journal_.warn()) << "Acquire hash mismatch: " << mLedger->header().hash << "!=" << hash_; + JLOG(journal_.warn()) << "Acquire hash mismatch: " << mLedger->header().hash + << "!=" << hash_; mLedger.reset(); return false; } @@ -803,16 +820,19 @@ InboundLedger::receiveNode(protocol::TMLedgerData& packet, SHAMapAddNode& san) return; } - auto [map, rootHash, filter] = [&]() -> std::tuple> { + auto [map, rootHash, filter] = + [&]() -> std::tuple> { if (packet.type() == protocol::liTX_NODE) return { mLedger->txMap(), SHAMapHash{mLedger->header().txHash}, - std::make_unique(mLedger->txMap().family().db(), app_.getLedgerMaster())}; + std::make_unique( + mLedger->txMap().family().db(), app_.getLedgerMaster())}; return { mLedger->stateMap(), SHAMapHash{mLedger->header().accountHash}, - std::make_unique(mLedger->stateMap().family().db(), app_.getLedgerMaster())}; + std::make_unique( + mLedger->stateMap().family().db(), app_.getLedgerMaster())}; }(); try @@ -885,7 +905,8 @@ InboundLedger::takeAsRootNode(Slice const& data, SHAMapAddNode& san) } AccountStateSF filter(mLedger->stateMap().family().db(), app_.getLedgerMaster()); - san += mLedger->stateMap().addRootNode(SHAMapHash{mLedger->header().accountHash}, data, &filter); + san += + mLedger->stateMap().addRootNode(SHAMapHash{mLedger->header().accountHash}, data, &filter); return san.isGood(); } @@ -950,7 +971,9 @@ InboundLedger::getNeededHashes() Returns 'true' if we need to dispatch */ bool -InboundLedger::gotData(std::weak_ptr peer, std::shared_ptr const& data) +InboundLedger::gotData( + std::weak_ptr peer, + std::shared_ptr const& data) { std::lock_guard sl(mReceivedDataLock); @@ -1058,7 +1081,8 @@ InboundLedger::processData(std::shared_ptr peer, protocol::TMLedgerData& p SHAMapAddNode san; receiveNode(packet, san); - JLOG(journal_.debug()) << "Ledger " << ((packet.type() == protocol::liTX_NODE) ? "TX" : "AS") + JLOG(journal_.debug()) << "Ledger " + << ((packet.type() == protocol::liTX_NODE) ? "TX" : "AS") << " node stats: " << san.get(); if (san.isUseful()) @@ -1133,7 +1157,8 @@ struct PeerDataCounts outFunc(v); } #else - std::sample(counts.begin(), counts.end(), boost::make_function_output_iterator(outFunc), n, rng); + std::sample( + counts.begin(), counts.end(), boost::make_function_output_iterator(outFunc), n, rng); #endif } }; @@ -1184,7 +1209,9 @@ InboundLedger::runData() // Select a random sample of the peers that gives us the most nodes that are // useful dataCounts.prune(); - dataCounts.sampleN(maxUsefulPeers, [&](std::shared_ptr const& peer) { trigger(peer, TriggerReason::reply); }); + dataCounts.sampleN(maxUsefulPeers, [&](std::shared_ptr const& peer) { + trigger(peer, TriggerReason::reply); + }); } Json::Value diff --git a/src/xrpld/app/ledger/detail/InboundLedgers.cpp b/src/xrpld/app/ledger/detail/InboundLedgers.cpp index 626f58b686..a8ae530bde 100644 --- a/src/xrpld/app/ledger/detail/InboundLedgers.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedgers.cpp @@ -1,7 +1,6 @@ #include #include #include -#include #include #include @@ -10,6 +9,7 @@ #include #include #include +#include #include #include @@ -51,7 +51,8 @@ public: acquire(uint256 const& hash, std::uint32_t seq, InboundLedger::Reason reason) override { auto doAcquire = [&, seq, reason]() -> std::shared_ptr { - XRPL_ASSERT(hash.isNonZero(), "xrpl::InboundLedgersImp::acquire::doAcquire : nonzero hash"); + XRPL_ASSERT( + hash.isNonZero(), "xrpl::InboundLedgersImp::acquire::doAcquire : nonzero hash"); // probably not the right rule if (app_.getOPs().isNeedNetworkLedger() && (reason != InboundLedger::Reason::GENERIC) && @@ -115,7 +116,8 @@ public: } catch (std::exception const& e) { - JLOG(j_.warn()) << "Exception thrown for acquiring new inbound ledger " << hash << ": " << e.what(); + JLOG(j_.warn()) << "Exception thrown for acquiring new inbound ledger " << hash << ": " + << e.what(); } catch (...) { @@ -159,17 +161,21 @@ public: /** We received a TMLedgerData from a peer. */ bool - gotLedgerData(LedgerHash const& hash, std::shared_ptr peer, std::shared_ptr packet) - override + gotLedgerData( + LedgerHash const& hash, + std::shared_ptr peer, + std::shared_ptr packet) override { if (auto ledger = find(hash)) { - JLOG(j_.trace()) << "Got data (" << packet->nodes().size() << ") for acquiring ledger: " << hash; + JLOG(j_.trace()) << "Got data (" << packet->nodes().size() + << ") for acquiring ledger: " << hash; // Stash the data for later processing and see if we need to // dispatch if (ledger->gotData(std::weak_ptr(peer), packet)) - app_.getJobQueue().addJob(jtLEDGER_DATA, "ProcessLData", [ledger]() { ledger->runData(); }); + app_.getJobQueue().addJob( + jtLEDGER_DATA, "ProcessLData", [ledger]() { ledger->runData(); }); return true; } @@ -180,7 +186,8 @@ public: // useful. if (packet->type() == protocol::liAS_NODE) { - app_.getJobQueue().addJob(jtLEDGER_DATA, "GotStaleData", [this, packet]() { gotStaleData(packet); }); + app_.getJobQueue().addJob( + jtLEDGER_DATA, "GotStaleData", [this, packet]() { gotStaleData(packet); }); } return false; @@ -367,9 +374,11 @@ public: beast::expire(mRecentFailures, kReacquireInterval); } - JLOG(j_.debug()) << "Swept " << stuffToSweep.size() << " out of " << total << " inbound ledgers. Duration: " - << std::chrono::duration_cast(m_clock.now() - start).count() - << "ms"; + JLOG(j_.debug()) + << "Swept " << stuffToSweep.size() << " out of " << total + << " inbound ledgers. Duration: " + << std::chrono::duration_cast(m_clock.now() - start).count() + << "ms"; } void diff --git a/src/xrpld/app/ledger/detail/InboundTransactions.cpp b/src/xrpld/app/ledger/detail/InboundTransactions.cpp index 36ebb7bd9e..b6f4c961c1 100644 --- a/src/xrpld/app/ledger/detail/InboundTransactions.cpp +++ b/src/xrpld/app/ledger/detail/InboundTransactions.cpp @@ -2,12 +2,12 @@ #include #include #include -#include #include #include #include #include +#include #include #include @@ -30,7 +30,8 @@ public: TransactionAcquire::pointer mAcquire; std::shared_ptr mSet; - InboundTransactionSet(std::uint32_t seq, std::shared_ptr const& set) : mSeq(seq), mSet(set) + InboundTransactionSet(std::uint32_t seq, std::shared_ptr const& set) + : mSeq(seq), mSet(set) { ; } @@ -55,7 +56,8 @@ public: , m_peerSetBuilder(std::move(peerSetBuilder)) , j_(app_.journal("InboundTransactions")) { - m_zeroSet.mSet = std::make_shared(SHAMapType::TRANSACTION, uint256(), app_.getNodeFamily()); + m_zeroSet.mSet = + std::make_shared(SHAMapType::TRANSACTION, uint256(), app_.getNodeFamily()); m_zeroSet.mSet->setUnbacked(); } @@ -112,12 +114,15 @@ public: /** We received a TMLedgerData from a peer. */ void - gotData(LedgerHash const& hash, std::shared_ptr peer, std::shared_ptr packet_ptr) - override + gotData( + LedgerHash const& hash, + std::shared_ptr peer, + std::shared_ptr packet_ptr) override { protocol::TMLedgerData& packet = *packet_ptr; - JLOG(j_.trace()) << "Got data (" << packet.nodes().size() << ") for acquiring ledger: " << hash; + JLOG(j_.trace()) << "Got data (" << packet.nodes().size() + << ") for acquiring ledger: " << hash; TransactionAcquire::pointer ta = getAcquire(hash); @@ -244,7 +249,8 @@ make_InboundTransactions( beast::insight::Collector::ptr const& collector, std::function const&, bool)> gotSet) { - return std::make_unique(app, collector, std::move(gotSet), make_PeerSetBuilder(app)); + return std::make_unique( + app, collector, std::move(gotSet), make_PeerSetBuilder(app)); } } // namespace xrpl diff --git a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp index f54c79f9c0..ad9c6a277d 100644 --- a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp +++ b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp @@ -1,10 +1,10 @@ #include #include #include -#include #include #include +#include namespace xrpl { @@ -242,14 +242,20 @@ private: @return `true` if the ledger was cleaned. */ bool - doLedger(LedgerIndex const& ledgerIndex, LedgerHash const& ledgerHash, bool doNodes, bool doTxns) + doLedger( + LedgerIndex const& ledgerIndex, + LedgerHash const& ledgerHash, + bool doNodes, + bool doTxns) { - auto nodeLedger = app_.getInboundLedgers().acquire(ledgerHash, ledgerIndex, InboundLedger::Reason::GENERIC); + auto nodeLedger = app_.getInboundLedgers().acquire( + ledgerHash, ledgerIndex, InboundLedger::Reason::GENERIC); if (!nodeLedger) { JLOG(j_.debug()) << "Ledger " << ledgerIndex << " not available"; app_.getLedgerMaster().clearLedger(ledgerIndex); - app_.getInboundLedgers().acquire(ledgerHash, ledgerIndex, InboundLedger::Reason::GENERIC); + app_.getInboundLedgers().acquire( + ledgerHash, ledgerIndex, InboundLedger::Reason::GENERIC); return false; } @@ -272,7 +278,8 @@ private: { JLOG(j_.debug()) << "Ledger " << ledgerIndex << " is missing nodes"; app_.getLedgerMaster().clearLedger(ledgerIndex); - app_.getInboundLedgers().acquire(ledgerHash, ledgerIndex, InboundLedger::Reason::GENERIC); + app_.getInboundLedgers().acquire( + ledgerHash, ledgerIndex, InboundLedger::Reason::GENERIC); return false; } @@ -323,8 +330,8 @@ private: { // We found the hash and sequence of a better reference // ledger. - referenceLedger = - app_.getInboundLedgers().acquire(refHash, refIndex, InboundLedger::Reason::GENERIC); + referenceLedger = app_.getInboundLedgers().acquire( + refHash, refIndex, InboundLedger::Reason::GENERIC); if (referenceLedger) ledgerHash = getLedgerHash(referenceLedger, ledgerIndex); } diff --git a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp index f06beda768..e22351fc77 100644 --- a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp +++ b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp @@ -62,7 +62,8 @@ LedgerDeltaAcquire::trigger(std::size_t limit, ScopedLockType& sl) peerSet_->addPeers( limit, [this](auto peer) { - return peer->supportsFeature(ProtocolFeature::LedgerReplay) && peer->hasLedger(hash_, ledgerSeq_); + return peer->supportsFeature(ProtocolFeature::LedgerReplay) && + peer->hasLedger(hash_, ledgerSeq_); }, [this](auto peer) { if (peer->supportsFeature(ProtocolFeature::LedgerReplay)) @@ -169,7 +170,9 @@ LedgerDeltaAcquire::tryBuild(std::shared_ptr const& parent) if (failed_ || !complete_ || !replayTemp_) return {}; - XRPL_ASSERT(parent->seq() + 1 == replayTemp_->seq(), "xrpl::LedgerDeltaAcquire::tryBuild : parent sequence match"); + XRPL_ASSERT( + parent->seq() + 1 == replayTemp_->seq(), + "xrpl::LedgerDeltaAcquire::tryBuild : parent sequence match"); XRPL_ASSERT( parent->header().hash == replayTemp_->header().parentHash, "xrpl::LedgerDeltaAcquire::tryBuild : parent hash match"); @@ -186,7 +189,8 @@ LedgerDeltaAcquire::tryBuild(std::shared_ptr const& parent) { failed_ = true; complete_ = false; - JLOG(journal_.error()) << "tryBuild failed " << hash_ << " with parent " << parent->header().hash; + JLOG(journal_.error()) << "tryBuild failed " << hash_ << " with parent " + << parent->header().hash; Throw("Cannot replay ledger"); } } @@ -204,23 +208,24 @@ LedgerDeltaAcquire::onLedgerBuilt(ScopedLockType& sl, std::optionalfullLedger_, &app = this->app_]() { - for (auto reason : reasons) - { - switch (reason) + app_.getJobQueue().addJob( + jtREPLAY_TASK, "OnLedBuilt", [=, ledger = this->fullLedger_, &app = this->app_]() { + for (auto reason : reasons) { - case InboundLedger::Reason::GENERIC: - app.getLedgerMaster().storeLedger(ledger); - break; - default: - // TODO for other use cases - break; + switch (reason) + { + case InboundLedger::Reason::GENERIC: + app.getLedgerMaster().storeLedger(ledger); + break; + default: + // TODO for other use cases + break; + } } - } - if (firstTime) - app.getLedgerMaster().tryAdvance(); - }); + if (firstTime) + app.getLedgerMaster().tryAdvance(); + }); } void diff --git a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.h b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.h index 66b8f27b85..2877d997e6 100644 --- a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.h +++ b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.h @@ -65,7 +65,9 @@ public: * @note info and Txns must have been verified against the ledger hash */ void - processData(LedgerHeader const& info, std::map>&& orderedTxns); + processData( + LedgerHeader const& info, + std::map>&& orderedTxns); /** * Try to build the ledger if not already diff --git a/src/xrpld/app/ledger/detail/LedgerMaster.cpp b/src/xrpld/app/ledger/detail/LedgerMaster.cpp index 1fd1a8a8b2..8072b619e1 100644 --- a/src/xrpld/app/ledger/detail/LedgerMaster.cpp +++ b/src/xrpld/app/ledger/detail/LedgerMaster.cpp @@ -3,12 +3,8 @@ #include #include #include -#include #include #include -#include -#include -#include #include #include #include @@ -25,11 +21,15 @@ #include #include #include +#include +#include #include #include #include #include #include +#include +#include #include #include @@ -72,7 +72,8 @@ shouldAcquire( return minimumOnline.has_value() && candidateLedger >= *minimumOnline; }(); - JLOG(j.trace()) << "Missing ledger " << candidateLedger << (ret ? " should" : " should NOT") << " be acquired"; + JLOG(j.trace()) << "Missing ledger " << candidateLedger << (ret ? " should" : " should NOT") + << " be acquired"; return ret; } @@ -88,7 +89,12 @@ LedgerMaster::LedgerMaster( , 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_("FetchPack", 65536, std::chrono::seconds{45}, stopwatch, app_.journal("TaggedCache")) + , fetch_packs_( + "FetchPack", + 65536, + std::chrono::seconds{45}, + stopwatch, + app_.journal("TaggedCache")) , m_stats(std::bind(&LedgerMaster::collect_metrics, this), collector) { } @@ -311,8 +317,8 @@ LedgerMaster::canBeCurrent(std::shared_ptr const& ledger) auto validLedger = getValidatedLedger(); if (validLedger && (ledger->header().seq < validLedger->header().seq)) { - JLOG(m_journal.trace()) << "Candidate for current ledger has low seq " << ledger->header().seq << " < " - << validLedger->header().seq; + JLOG(m_journal.trace()) << "Candidate for current ledger has low seq " + << ledger->header().seq << " < " << validLedger->header().seq; return false; } @@ -328,8 +334,9 @@ LedgerMaster::canBeCurrent(std::shared_ptr const& ledger) if ((validLedger || (ledger->header().seq > 10)) && ((std::max(closeTime, ledgerClose) - std::min(closeTime, ledgerClose)) > 5min)) { - JLOG(m_journal.warn()) << "Candidate for current ledger has close time " << to_string(ledgerClose) - << " at network time " << to_string(closeTime) << " seq " << ledger->header().seq; + JLOG(m_journal.warn()) << "Candidate for current ledger has close time " + << to_string(ledgerClose) << " at network time " + << to_string(closeTime) << " seq " << ledger->header().seq; return false; } @@ -343,15 +350,15 @@ LedgerMaster::canBeCurrent(std::shared_ptr const& ledger) LedgerIndex maxSeq = validLedger->header().seq + 10; if (closeTime > validLedger->header().parentCloseTime) - maxSeq += - std::chrono::duration_cast(closeTime - validLedger->header().parentCloseTime) - .count() / + maxSeq += std::chrono::duration_cast( + closeTime - validLedger->header().parentCloseTime) + .count() / 2; if (ledger->header().seq > maxSeq) { - JLOG(m_journal.warn()) << "Candidate for current ledger has high seq " << ledger->header().seq << " > " - << maxSeq; + JLOG(m_journal.warn()) << "Candidate for current ledger has high seq " + << ledger->header().seq << " > " << maxSeq; return false; } @@ -611,16 +618,19 @@ LedgerMaster::tryFill(std::shared_ptr ledger) mCompleteLedgers.insert(range(minHas, maxHas)); } maxHas = minHas; - ledgerHashes = app_.getRelationalDatabase().getHashesByIndex((seq < 500) ? 0 : (seq - 499), seq); + ledgerHashes = + app_.getRelationalDatabase().getHashesByIndex((seq < 500) ? 0 : (seq - 499), seq); it = ledgerHashes.find(seq); if (it == ledgerHashes.end()) break; - if (!nodeStore.fetchNodeObject(ledgerHashes.begin()->second.ledgerHash, ledgerHashes.begin()->first)) + if (!nodeStore.fetchNodeObject( + ledgerHashes.begin()->second.ledgerHash, ledgerHashes.begin()->first)) { // The ledger is not backed by the node store - JLOG(m_journal.warn()) << "SQL DB ledger sequence " << seq << " mismatches node store"; + JLOG(m_journal.warn()) + << "SQL DB ledger sequence " << seq << " mismatches node store"; break; } } @@ -707,7 +717,8 @@ LedgerMaster::fixMismatch(ReadView const& ledger) } catch (std::exception const& ex) { - JLOG(m_journal.warn()) << "fixMismatch encounters partial ledger. Exception: " << ex.what(); + JLOG(m_journal.warn()) + << "fixMismatch encounters partial ledger. Exception: " << ex.what(); clearLedger(lSeq); return; } @@ -722,8 +733,8 @@ LedgerMaster::fixMismatch(ReadView const& ledger) // we closed the seam if (invalidate != 0) { - JLOG(m_journal.warn()) - << "Match at " << lSeq << ", " << invalidate << " prior ledgers invalidated"; + JLOG(m_journal.warn()) << "Match at " << lSeq << ", " << invalidate + << " prior ledgers invalidated"; } return; @@ -743,12 +754,17 @@ LedgerMaster::fixMismatch(ReadView const& ledger) } void -LedgerMaster::setFullLedger(std::shared_ptr const& ledger, bool isSynchronous, bool isCurrent) +LedgerMaster::setFullLedger( + std::shared_ptr const& ledger, + bool isSynchronous, + bool isCurrent) { // A new ledger has been accepted as part of the trusted chain - JLOG(m_journal.debug()) << "Ledger " << ledger->header().seq << " accepted :" << ledger->header().hash; + JLOG(m_journal.debug()) << "Ledger " << ledger->header().seq + << " accepted :" << ledger->header().hash; XRPL_ASSERT( - ledger->stateMap().getHash().isNonZero(), "xrpl::LedgerMaster::setFullLedger : nonzero ledger state hash"); + ledger->stateMap().getHash().isNonZero(), + "xrpl::LedgerMaster::setFullLedger : nonzero ledger state hash"); ledger->setValidated(); ledger->setFull(); @@ -817,7 +833,8 @@ LedgerMaster::checkAccept(uint256 const& hash, std::uint32_t seq) if (seq < mValidLedgerSeq) return; - auto validations = app_.validators().negativeUNLFilter(app_.getValidations().getTrustedForLedger(hash, seq)); + auto validations = app_.validators().negativeUNLFilter( + app_.getValidations().getTrustedForLedger(hash, seq)); valCount = validations.size(); if (valCount >= app_.validators().quorum()) { @@ -890,8 +907,8 @@ LedgerMaster::checkAccept(std::shared_ptr const& ledger) return; } - JLOG(m_journal.info()) << "Advancing accepted ledger to " << ledger->header().seq << " with >= " << minVal - << " validations"; + JLOG(m_journal.info()) << "Advancing accepted ledger to " << ledger->header().seq + << " with >= " << minVal << " validations"; ledger->setValidated(); ledger->setFull(); @@ -953,8 +970,8 @@ LedgerMaster::checkAccept(std::shared_ptr const& ledger) if (upgradeWarningPrevTime_ == TimeKeeper::time_point()) { // Have not printed the warning before, check if need to print. - auto const vals = - app_.getValidations().getTrustedForLedger(ledger->header().parentHash, ledger->header().seq - 1); + auto const vals = app_.getValidations().getTrustedForLedger( + ledger->header().parentHash, ledger->header().seq - 1); std::size_t higherVersionCount = 0; std::size_t rippledCount = 0; for (auto const& v : vals) @@ -975,7 +992,8 @@ LedgerMaster::checkAccept(std::shared_ptr const& ledger) constexpr std::size_t reportingPercent = 90; constexpr std::size_t cutoffPercent = 60; auto const unlSize{app_.validators().getQuorumKeys().second.size()}; - needPrint = unlSize > 0 && calculatePercent(vals.size(), unlSize) >= reportingPercent && + needPrint = unlSize > 0 && + calculatePercent(vals.size(), unlSize) >= reportingPercent && calculatePercent(higherVersionCount, rippledCount) >= cutoffPercent; } } @@ -1021,7 +1039,8 @@ LedgerMaster::consensusBuilt( if (ledger->header().seq <= mValidLedgerSeq) { auto stream = app_.journal("LedgerConsensus").info(); - JLOG(stream) << "Consensus built old ledger: " << ledger->header().seq << " <= " << mValidLedgerSeq; + JLOG(stream) << "Consensus built old ledger: " << ledger->header().seq + << " <= " << mValidLedgerSeq; return; } @@ -1144,7 +1163,8 @@ LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl if (mValidLedgerSeq > (mPubLedgerSeq + MAX_LEDGER_GAP)) { - JLOG(m_journal.warn()) << "Gap in validated ledger stream " << mPubLedgerSeq << " - " << mValidLedgerSeq - 1; + JLOG(m_journal.warn()) << "Gap in validated ledger stream " << mPubLedgerSeq << " - " + << mValidLedgerSeq - 1; auto valLedger = mValidLedger.get(); ret.push_back(valLedger); @@ -1188,7 +1208,8 @@ LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl else if (hash->isZero()) { // LCOV_EXCL_START - JLOG(m_journal.fatal()) << "Ledger: " << valSeq << " does not have hash for " << seq; + JLOG(m_journal.fatal()) + << "Ledger: " << valSeq << " does not have hash for " << seq; UNREACHABLE( "xrpl::LedgerMaster::findNewLedgersToPublish : ledger " "not found"); @@ -1203,7 +1224,8 @@ LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl { // Can we try to acquire the ledger we need? if (!ledger && (++acqCount < ledger_fetch_size_)) - ledger = app_.getInboundLedgers().acquire(*hash, seq, InboundLedger::Reason::GENERIC); + ledger = app_.getInboundLedgers().acquire( + *hash, seq, InboundLedger::Reason::GENERIC); } // Did we acquire the next ledger we need to publish? @@ -1219,7 +1241,8 @@ LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl } catch (std::exception const& ex) { - JLOG(m_journal.error()) << "Exception while trying to find ledgers to publish: " << ex.what(); + JLOG(m_journal.error()) << "Exception while trying to find ledgers to publish: " + << ex.what(); } if (app_.config().LEDGER_REPLAY) @@ -1234,17 +1257,20 @@ LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl auto finishLedger = valLedger; while (startLedger->seq() + 1 < finishLedger->seq()) { - if (auto const parent = mLedgerHistory.getLedgerByHash(finishLedger->header().parentHash); parent) + if (auto const parent = + mLedgerHistory.getLedgerByHash(finishLedger->header().parentHash); + parent) { finishLedger = parent; } else { auto numberLedgers = finishLedger->seq() - startLedger->seq() + 1; - JLOG(m_journal.debug()) << "Publish LedgerReplays " << numberLedgers - << " ledgers, from seq=" << startLedger->header().seq << ", " - << startLedger->header().hash << " to seq=" << finishLedger->header().seq - << ", " << finishLedger->header().hash; + JLOG(m_journal.debug()) + << "Publish LedgerReplays " << numberLedgers + << " ledgers, from seq=" << startLedger->header().seq << ", " + << startLedger->header().hash << " to seq=" << finishLedger->header().seq + << ", " << finishLedger->header().hash; app_.getLedgerReplayer().replay( InboundLedger::Reason::GENERIC, finishLedger->header().hash, numberLedgers); break; @@ -1268,7 +1294,9 @@ LedgerMaster::tryAdvance() app_.getJobQueue().addJob(jtADVANCE, "AdvanceLedger", [this]() { std::unique_lock sl(m_mutex); - XRPL_ASSERT(!mValidLedger.empty() && mAdvanceThread, "xrpl::LedgerMaster::tryAdvance : has valid ledger"); + XRPL_ASSERT( + !mValidLedger.empty() && mAdvanceThread, + "xrpl::LedgerMaster::tryAdvance : has valid ledger"); JLOG(m_journal.trace()) << "advanceThread<"; @@ -1308,7 +1336,8 @@ LedgerMaster::updatePaths() { std::lock_guard ml(m_mutex); - if (!mValidLedger.empty() && (!mPathLedger || (mPathLedger->header().seq != mValidLedgerSeq))) + if (!mValidLedger.empty() && + (!mPathLedger || (mPathLedger->header().seq != mValidLedgerSeq))) { // We have a new valid ledger since the last full pathfinding mPathLedger = mValidLedger.get(); lastLedger = mPathLedger; @@ -1329,7 +1358,8 @@ LedgerMaster::updatePaths() if (!standalone_) { // don't pathfind with a ledger that's more than 60 seconds old using namespace std::chrono; - auto age = time_point_cast(app_.timeKeeper().closeTime()) - lastLedger->header().closeTime; + auto age = time_point_cast(app_.timeKeeper().closeTime()) - + lastLedger->header().closeTime; if (age > 1min) { JLOG(m_journal.debug()) << "Published ledger too old for updating paths"; @@ -1375,13 +1405,17 @@ LedgerMaster::updatePaths() { // our parent is the problem app_.getInboundLedgers().acquire( - lastLedger->header().parentHash, lastLedger->header().seq - 1, InboundLedger::Reason::GENERIC); + lastLedger->header().parentHash, + lastLedger->header().seq - 1, + InboundLedger::Reason::GENERIC); } else { // this ledger is the problem app_.getInboundLedgers().acquire( - lastLedger->header().hash, lastLedger->header().seq, InboundLedger::Reason::GENERIC); + lastLedger->header().hash, + lastLedger->header().seq, + InboundLedger::Reason::GENERIC); } } } @@ -1422,7 +1456,8 @@ LedgerMaster::newPFWork(char const* name, std::unique_lock { if (!app_.isStopping() && mPathFindThread < 2 && app_.getPathRequests().requestsPending()) { - JLOG(m_journal.debug()) << "newPFWork: Creating job. path find threads: " << mPathFindThread; + JLOG(m_journal.debug()) << "newPFWork: Creating job. path find threads: " + << mPathFindThread; if (app_.getJobQueue().addJob(jtUPDATE_PF, name, [this]() { updatePaths(); })) { ++mPathFindThread; @@ -1696,7 +1731,8 @@ LedgerMaster::fetchForHistory( if (!app_.getInboundLedgers().isFailure(*hash)) { ledger = app_.getInboundLedgers().acquire(*hash, missing, reason); - if (!ledger && missing != fetch_seq_ && missing > app_.getNodeStore().earliestLedgerSeq()) + if (!ledger && missing != fetch_seq_ && + missing > app_.getNodeStore().earliestLedgerSeq()) { JLOG(m_journal.trace()) << "fetchForHistory want fetch pack " << missing; fetch_seq_ = missing; @@ -1728,7 +1764,8 @@ LedgerMaster::fetchForHistory( std::lock_guard lock(m_mutex); mFillInProgress = seq; } - app_.getJobQueue().addJob(jtADVANCE, "TryFill", [this, ledger]() { tryFill(ledger); }); + app_.getJobQueue().addJob( + jtADVANCE, "TryFill", [this, ledger]() { tryFill(ledger); }); } progress = true; } @@ -1738,7 +1775,8 @@ 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(ledger_fetch_size_, (missing - fetchSz) + 1) : 0; try { for (std::uint32_t i = 0; i < fetchSz; ++i) @@ -1766,7 +1804,8 @@ LedgerMaster::fetchForHistory( JLOG(m_journal.fatal()) << "Pub:" << mPubLedgerSeq << " Val:" << mValidLedgerSeq; JLOG(m_journal.fatal()) << "Ledgers: " << app_.getLedgerMaster().getCompleteLedgers(); JLOG(m_journal.fatal()) << "Acquire reason: " - << (reason == InboundLedger::Reason::HISTORY ? "HISTORY" : "NOT HISTORY"); + << (reason == InboundLedger::Reason::HISTORY ? "HISTORY" + : "NOT HISTORY"); clearLedger(missing + 1); progress = true; } @@ -1785,7 +1824,8 @@ LedgerMaster::doAdvance(std::unique_lock& sl) if (pubLedgers.empty()) { if (!standalone_ && !app_.getFeeTrack().isLoadedLocal() && - (app_.getJobQueue().getJobCount(jtPUBOLDLEDGER) < 10) && (mValidLedgerSeq == mPubLedgerSeq) && + (app_.getJobQueue().getJobCount(jtPUBOLDLEDGER) < 10) && + (mValidLedgerSeq == mPubLedgerSeq) && (getValidatedLedgerAge() < MAX_LEDGER_AGE_ACQUIRE) && (app_.getNodeStore().getWriteLoad() < MAX_WRITE_LOAD_ACQUIRE)) { @@ -1795,7 +1835,9 @@ LedgerMaster::doAdvance(std::unique_lock& sl) { std::lock_guard sll(mCompleteLock); missing = prevMissing( - mCompleteLedgers, mPubLedger->header().seq, app_.getNodeStore().earliestLedgerSeq()); + mCompleteLedgers, + mPubLedger->header().seq, + app_.getNodeStore().earliestLedgerSeq()); } if (missing) { @@ -1831,7 +1873,8 @@ LedgerMaster::doAdvance(std::unique_lock& sl) } else { - JLOG(m_journal.trace()) << "tryAdvance found " << pubLedgers.size() << " ledgers to publish"; + JLOG(m_journal.trace()) + << "tryAdvance found " << pubLedgers.size() << " ledgers to publish"; for (auto const& ledger : pubLedgers) { { diff --git a/src/xrpld/app/ledger/detail/LedgerReplay.cpp b/src/xrpld/app/ledger/detail/LedgerReplay.cpp index e77adc9700..d115402115 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplay.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplay.cpp @@ -3,7 +3,9 @@ namespace xrpl { -LedgerReplay::LedgerReplay(std::shared_ptr parent, std::shared_ptr replay) +LedgerReplay::LedgerReplay( + std::shared_ptr parent, + std::shared_ptr replay) : parent_{std::move(parent)}, replay_{std::move(replay)} { for (auto const& item : replay_->txMap()) diff --git a/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp b/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp index 4fcb924c27..73fcf77e4e 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp @@ -14,7 +14,8 @@ LedgerReplayMsgHandler::LedgerReplayMsgHandler(Application& app, LedgerReplayer& } protocol::TMProofPathResponse -LedgerReplayMsgHandler::processProofPathRequest(std::shared_ptr const& msg) +LedgerReplayMsgHandler::processProofPathRequest( + std::shared_ptr const& msg) { protocol::TMProofPathRequest& packet = *msg; protocol::TMProofPathResponse reply; @@ -57,7 +58,8 @@ LedgerReplayMsgHandler::processProofPathRequest(std::shared_ptrsize(); + JLOG(journal_.debug()) << "getProofPath for the node " << key << " of ledger " << ledgerHash + << " path length " << path->size(); return reply; } bool -LedgerReplayMsgHandler::processProofPathResponse(std::shared_ptr const& msg) +LedgerReplayMsgHandler::processProofPathResponse( + std::shared_ptr const& msg) { protocol::TMProofPathResponse& reply = *msg; if (reply.has_error() || !reply.has_key() || !reply.has_ledgerhash() || !reply.has_type() || @@ -144,7 +147,8 @@ LedgerReplayMsgHandler::processProofPathResponse(std::shared_ptr const& msg) +LedgerReplayMsgHandler::processReplayDeltaRequest( + std::shared_ptr const& msg) { protocol::TMReplayDeltaRequest& packet = *msg; protocol::TMReplayDeltaResponse reply; @@ -182,7 +186,8 @@ LedgerReplayMsgHandler::processReplayDeltaRequest(std::shared_ptr const& msg) +LedgerReplayMsgHandler::processReplayDeltaResponse( + std::shared_ptr const& msg) { protocol::TMReplayDeltaResponse& reply = *msg; if (reply.has_error() || !reply.has_ledgerheader()) @@ -227,7 +232,8 @@ LedgerReplayMsgHandler::processReplayDeltaResponse(std::shared_ptr const& sList) +LedgerReplayTask::TaskParameter::update( + uint256 const& hash, + std::uint32_t seq, + std::vector const& sList) { if (finishHash_ != hash || sList.size() + 1 < totalLedgers_ || full_) return false; @@ -28,7 +31,9 @@ LedgerReplayTask::TaskParameter::update(uint256 const& hash, std::uint32_t seq, skipList_ = sList; skipList_.emplace_back(finishHash_); startHash_ = skipList_[skipList_.size() - totalLedgers_]; - XRPL_ASSERT(startHash_.isNonZero(), "xrpl::LedgerReplayTask::TaskParameter::update : nonzero start hash"); + XRPL_ASSERT( + startHash_.isNonZero(), + "xrpl::LedgerReplayTask::TaskParameter::update : nonzero start hash"); startSeq_ = finishSeq_ - totalLedgers_ + 1; full_ = true; return true; @@ -72,9 +77,10 @@ LedgerReplayTask::LedgerReplayTask( , inboundLedgers_(inboundLedgers) , replayer_(replayer) , parameter_(parameter) - , maxTimeouts_(std::max( - LedgerReplayParameters::TASK_MAX_TIMEOUTS_MINIMUM, - parameter.totalLedgers_ * LedgerReplayParameters::TASK_MAX_TIMEOUTS_MULTIPLIER)) + , maxTimeouts_( + std::max( + LedgerReplayParameters::TASK_MAX_TIMEOUTS_MINIMUM, + parameter.totalLedgers_ * LedgerReplayParameters::TASK_MAX_TIMEOUTS_MULTIPLIER)) , skipListAcquirer_(skipListAcquirer) { JLOG(journal_.trace()) << "Create " << hash_; @@ -126,12 +132,13 @@ LedgerReplayTask::trigger(ScopedLockType& sl) parent_ = app_.getLedgerMaster().getLedgerByHash(parameter_.startHash_); if (!parent_) { - parent_ = - inboundLedgers_.acquire(parameter_.startHash_, parameter_.startSeq_, InboundLedger::Reason::GENERIC); + parent_ = inboundLedgers_.acquire( + parameter_.startHash_, parameter_.startSeq_, InboundLedger::Reason::GENERIC); } if (parent_) { - JLOG(journal_.trace()) << "Got start ledger " << parameter_.startHash_ << " for task " << hash_; + JLOG(journal_.trace()) + << "Got start ledger " << parameter_.startHash_ << " for task " << hash_; } } @@ -151,9 +158,10 @@ void LedgerReplayTask::tryAdvance(ScopedLockType& sl) { JLOG(journal_.trace()) << "tryAdvance task " << hash_ - << (parameter_.full_ ? ", full parameter" : ", waiting to fill parameter") - << ", deltaIndex=" << deltaToBuild_ << ", totalDeltas=" << deltas_.size() << ", parent " - << (parent_ ? parent_->header().hash : uint256()); + << (parameter_.full_ ? ", full parameter" + : ", waiting to fill parameter") + << ", deltaIndex=" << deltaToBuild_ << ", totalDeltas=" << deltas_.size() + << ", parent " << (parent_ ? parent_->header().hash : uint256()); bool shouldTry = parent_ && parameter_.full_ && parameter_.totalLedgers_ - 1 == deltas_.size(); if (!shouldTry) @@ -165,11 +173,13 @@ LedgerReplayTask::tryAdvance(ScopedLockType& sl) { auto& delta = deltas_[deltaToBuild_]; XRPL_ASSERT( - parent_->seq() + 1 == delta->ledgerSeq_, "xrpl::LedgerReplayTask::tryAdvance : consecutive sequence"); + parent_->seq() + 1 == delta->ledgerSeq_, + "xrpl::LedgerReplayTask::tryAdvance : consecutive sequence"); if (auto l = delta->tryBuild(parent_); l) { - JLOG(journal_.debug()) << "Task " << hash_ << " got ledger " << l->header().hash - << " deltaIndex=" << deltaToBuild_ << " totalDeltas=" << deltas_.size(); + JLOG(journal_.debug()) + << "Task " << hash_ << " got ledger " << l->header().hash + << " deltaIndex=" << deltaToBuild_ << " totalDeltas=" << deltas_.size(); parent_ = l; } else @@ -186,7 +196,10 @@ LedgerReplayTask::tryAdvance(ScopedLockType& sl) } void -LedgerReplayTask::updateSkipList(uint256 const& hash, std::uint32_t seq, std::vector const& sList) +LedgerReplayTask::updateSkipList( + uint256 const& hash, + std::uint32_t seq, + std::vector const& sList) { { ScopedLockType sl(mtx_); diff --git a/src/xrpld/app/ledger/detail/LedgerReplayer.cpp b/src/xrpld/app/ledger/detail/LedgerReplayer.cpp index b52abc5624..f649eb4d95 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayer.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayer.cpp @@ -22,10 +22,14 @@ LedgerReplayer::~LedgerReplayer() } void -LedgerReplayer::replay(InboundLedger::Reason r, uint256 const& finishLedgerHash, std::uint32_t totalNumLedgers) +LedgerReplayer::replay( + InboundLedger::Reason r, + uint256 const& finishLedgerHash, + std::uint32_t totalNumLedgers) { XRPL_ASSERT( - finishLedgerHash.isNonZero() && totalNumLedgers > 0 && totalNumLedgers <= LedgerReplayParameters::MAX_TASK_SIZE, + finishLedgerHash.isNonZero() && totalNumLedgers > 0 && + totalNumLedgers <= LedgerReplayParameters::MAX_TASK_SIZE, "xrpl::LedgerReplayer::replay : valid inputs"); LedgerReplayTask::TaskParameter parameter(r, finishLedgerHash, totalNumLedgers); @@ -52,7 +56,8 @@ LedgerReplayer::replay(InboundLedger::Reason r, uint256 const& finishLedgerHash, return; } } - JLOG(j_.info()) << "Replay " << totalNumLedgers << " ledgers. Finish ledger hash " << parameter.finishHash_; + JLOG(j_.info()) << "Replay " << totalNumLedgers << " ledgers. Finish ledger hash " + << parameter.finishHash_; auto i = skipLists_.find(parameter.finishHash_); if (i != skipLists_.end()) @@ -66,7 +71,8 @@ LedgerReplayer::replay(InboundLedger::Reason r, uint256 const& finishLedgerHash, newSkipList = true; } - task = std::make_shared(app_, inboundLedgers_, *this, skipList, std::move(parameter)); + task = std::make_shared( + app_, inboundLedgers_, *this, skipList, std::move(parameter)); tasks_.push_back(task); } @@ -90,10 +96,13 @@ LedgerReplayer::createDeltas(std::shared_ptr task) JLOG(j_.trace()) << "Creating " << parameter.totalLedgers_ - 1 << " deltas"; if (parameter.totalLedgers_ > 1) { - auto skipListItem = std::find(parameter.skipList_.begin(), parameter.skipList_.end(), parameter.startHash_); - if (skipListItem == parameter.skipList_.end() || ++skipListItem == parameter.skipList_.end()) + auto skipListItem = + std::find(parameter.skipList_.begin(), parameter.skipList_.end(), parameter.startHash_); + if (skipListItem == parameter.skipList_.end() || + ++skipListItem == parameter.skipList_.end()) { - JLOG(j_.error()) << "Task parameter error when creating deltas " << parameter.finishHash_; + JLOG(j_.error()) << "Task parameter error when creating deltas " + << parameter.finishHash_; return; } @@ -128,7 +137,9 @@ LedgerReplayer::createDeltas(std::shared_ptr task) } void -LedgerReplayer::gotSkipList(LedgerHeader const& info, boost::intrusive_ptr const& item) +LedgerReplayer::gotSkipList( + LedgerHeader const& info, + boost::intrusive_ptr const& item) { std::shared_ptr skipList = {}; { @@ -149,7 +160,9 @@ LedgerReplayer::gotSkipList(LedgerHeader const& info, boost::intrusive_ptr>&& txns) +LedgerReplayer::gotReplayDelta( + LedgerHeader const& info, + std::map>&& txns) { std::shared_ptr delta = {}; { @@ -175,8 +188,8 @@ LedgerReplayer::sweep() auto const start = std::chrono::steady_clock::now(); { std::lock_guard lock(mtx_); - JLOG(j_.debug()) << "Sweeping, LedgerReplayer has " << tasks_.size() << " tasks, " << skipLists_.size() - << " skipLists, and " << deltas_.size() << " deltas."; + JLOG(j_.debug()) << "Sweeping, LedgerReplayer has " << tasks_.size() << " tasks, " + << skipLists_.size() << " skipLists, and " << deltas_.size() << " deltas."; tasks_.erase( std::remove_if( @@ -206,10 +219,11 @@ LedgerReplayer::sweep() removeCannotLocked(skipLists_); removeCannotLocked(deltas_); } - JLOG(j_.debug()) - << " LedgerReplayer sweep lock duration " - << std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count() - << "ms"; + JLOG(j_.debug()) << " LedgerReplayer sweep lock duration " + << std::chrono::duration_cast( + std::chrono::steady_clock::now() - start) + .count() + << "ms"; } void diff --git a/src/xrpld/app/ledger/detail/LedgerToJson.cpp b/src/xrpld/app/ledger/detail/LedgerToJson.cpp index a675550537..038a5ae742 100644 --- a/src/xrpld/app/ledger/detail/LedgerToJson.cpp +++ b/src/xrpld/app/ledger/detail/LedgerToJson.cpp @@ -36,7 +36,8 @@ void fillJson(Json::Value& json, bool closed, LedgerHeader const& info, bool bFull, unsigned apiVersion) { json[jss::parent_hash] = to_string(info.parentHash); - json[jss::ledger_index] = (apiVersion > 1) ? Json::Value(info.seq) : Json::Value(std::to_string(info.seq)); + json[jss::ledger_index] = + (apiVersion > 1) ? Json::Value(info.seq) : Json::Value(std::to_string(info.seq)); if (closed) { @@ -120,10 +121,14 @@ fillJsonTx( // If applicable, insert delivered amount if (txnType == ttPAYMENT || txnType == ttCHECK_CASH) RPC::insertDeliveredAmount( - txJson[jss::meta], fill.ledger, txn, {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); + txJson[jss::meta], + fill.ledger, + txn, + {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); // If applicable, insert mpt issuance id - RPC::insertMPTokenIssuanceID(txJson[jss::meta], txn, {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); + RPC::insertMPTokenIssuanceID( + txJson[jss::meta], txn, {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); } if (!fill.ledger.open()) @@ -150,7 +155,10 @@ fillJsonTx( // If applicable, insert delivered amount if (txnType == ttPAYMENT || txnType == ttCHECK_CASH) RPC::insertDeliveredAmount( - txJson[jss::metaData], fill.ledger, txn, {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); + txJson[jss::metaData], + fill.ledger, + txn, + {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); // If applicable, insert mpt issuance id RPC::insertMPTokenIssuanceID( @@ -168,7 +176,11 @@ fillJsonTx( if (account != amount.getIssuer()) { auto const ownerFunds = accountFunds( - fill.ledger, account, amount, fhIGNORE_FREEZE, beast::Journal{beast::Journal::getNullSink()}); + fill.ledger, + account, + amount, + fhIGNORE_FREEZE, + beast::Journal{beast::Journal::getNullSink()}); txJson[jss::owner_funds] = ownerFunds.getText(); } } diff --git a/src/xrpld/app/ledger/detail/OpenLedger.cpp b/src/xrpld/app/ledger/detail/OpenLedger.cpp index 698862d4da..a26751bc64 100644 --- a/src/xrpld/app/ledger/detail/OpenLedger.cpp +++ b/src/xrpld/app/ledger/detail/OpenLedger.cpp @@ -1,19 +1,22 @@ #include #include -#include #include -#include #include #include +#include #include #include +#include #include namespace xrpl { -OpenLedger::OpenLedger(std::shared_ptr const& ledger, CachedSLEs& cache, beast::Journal journal) +OpenLedger::OpenLedger( + std::shared_ptr const& ledger, + CachedSLEs& cache, + beast::Journal journal) : j_(journal), cache_(cache), current_(create(ledger->rules(), ledger)) { } @@ -79,9 +82,8 @@ OpenLedger::accept( *ledger, boost::adaptors::transform( current_->txs, - [](std::pair, std::shared_ptr> const& p) { - return p.first; - }), + [](std::pair, std::shared_ptr> const& + p) { return p.first; }), retries, flags, j_); @@ -137,7 +139,8 @@ OpenLedger::accept( std::shared_ptr OpenLedger::create(Rules const& rules, std::shared_ptr const& ledger) { - return std::make_shared(open_ledger, rules, std::make_shared(ledger, cache_)); + return std::make_shared( + open_ledger, rules, std::make_shared(ledger, cache_)); } auto diff --git a/src/xrpld/app/ledger/detail/SkipListAcquire.cpp b/src/xrpld/app/ledger/detail/SkipListAcquire.cpp index 353b4fdbc8..0fb1239c49 100644 --- a/src/xrpld/app/ledger/detail/SkipListAcquire.cpp +++ b/src/xrpld/app/ledger/detail/SkipListAcquire.cpp @@ -54,7 +54,8 @@ SkipListAcquire::trigger(std::size_t limit, ScopedLockType& sl) peerSet_->addPeers( limit, [this](auto peer) { - return peer->supportsFeature(ProtocolFeature::LedgerReplay) && peer->hasLedger(hash_, 0); + return peer->supportsFeature(ProtocolFeature::LedgerReplay) && + peer->hasLedger(hash_, 0); }, [this](auto peer) { if (peer->supportsFeature(ProtocolFeature::LedgerReplay)) @@ -68,7 +69,8 @@ SkipListAcquire::trigger(std::size_t limit, ScopedLockType& sl) } else { - JLOG(journal_.trace()) << "Add a no feature peer " << peer->id() << " for " << hash_; + JLOG(journal_.trace()) + << "Add a no feature peer " << peer->id() << " for " << hash_; if (++noFeaturePeerCount_ >= LedgerReplayParameters::MAX_NO_FEATURE_PEER_COUNT) { JLOG(journal_.debug()) << "Fall back for " << hash_; @@ -106,7 +108,9 @@ SkipListAcquire::pmDowncast() } void -SkipListAcquire::processData(std::uint32_t ledgerSeq, boost::intrusive_ptr const& item) +SkipListAcquire::processData( + std::uint32_t ledgerSeq, + boost::intrusive_ptr const& item) { XRPL_ASSERT(ledgerSeq != 0 && item, "xrpl::SkipListAcquire::processData : valid inputs"); ScopedLockType sl(mtx_); @@ -154,7 +158,8 @@ SkipListAcquire::getData() const void SkipListAcquire::retrieveSkipList(std::shared_ptr const& ledger, ScopedLockType& sl) { - if (auto const hashIndex = ledger->read(keylet::skip()); hashIndex && hashIndex->isFieldPresent(sfHashes)) + if (auto const hashIndex = ledger->read(keylet::skip()); + hashIndex && hashIndex->isFieldPresent(sfHashes)) { auto const& slist = hashIndex->getFieldV256(sfHashes).value(); if (!slist.empty()) @@ -170,7 +175,10 @@ SkipListAcquire::retrieveSkipList(std::shared_ptr const& ledger, S } void -SkipListAcquire::onSkipListAcquired(std::vector const& skipList, std::uint32_t ledgerSeq, ScopedLockType& sl) +SkipListAcquire::onSkipListAcquired( + std::vector const& skipList, + std::uint32_t ledgerSeq, + ScopedLockType& sl) { complete_ = true; data_ = std::make_shared(ledgerSeq, skipList); diff --git a/src/xrpld/app/ledger/detail/SkipListAcquire.h b/src/xrpld/app/ledger/detail/SkipListAcquire.h index f3bfb60bee..5a79e8ae5c 100644 --- a/src/xrpld/app/ledger/detail/SkipListAcquire.h +++ b/src/xrpld/app/ledger/detail/SkipListAcquire.h @@ -113,7 +113,10 @@ private: * @param sl lock. this function must be called with the lock */ void - onSkipListAcquired(std::vector const& skipList, std::uint32_t ledgerSeq, ScopedLockType& sl); + onSkipListAcquired( + std::vector const& skipList, + std::uint32_t ledgerSeq, + ScopedLockType& sl); /** * Call the OnSkipListDataCB callbacks diff --git a/src/xrpld/app/ledger/detail/TimeoutCounter.cpp b/src/xrpld/app/ledger/detail/TimeoutCounter.cpp index 0ce6de0d34..e2d4409717 100644 --- a/src/xrpld/app/ledger/detail/TimeoutCounter.cpp +++ b/src/xrpld/app/ledger/detail/TimeoutCounter.cpp @@ -52,17 +52,20 @@ TimeoutCounter::queueJob(ScopedLockType& sl) if (isDone()) return; if (queueJobParameter_.jobLimit && - app_.getJobQueue().getJobCountTotal(queueJobParameter_.jobType) >= queueJobParameter_.jobLimit) + app_.getJobQueue().getJobCountTotal(queueJobParameter_.jobType) >= + queueJobParameter_.jobLimit) { - JLOG(journal_.debug()) << "Deferring " << queueJobParameter_.jobName << " timer due to load"; + JLOG(journal_.debug()) << "Deferring " << queueJobParameter_.jobName + << " timer due to load"; setTimer(sl); return; } - app_.getJobQueue().addJob(queueJobParameter_.jobType, queueJobParameter_.jobName, [wptr = pmDowncast()]() { - if (auto sptr = wptr.lock(); sptr) - sptr->invokeOnTimer(); - }); + app_.getJobQueue().addJob( + queueJobParameter_.jobType, queueJobParameter_.jobName, [wptr = pmDowncast()]() { + if (auto sptr = wptr.lock(); sptr) + sptr->invokeOnTimer(); + }); } void diff --git a/src/xrpld/app/ledger/detail/TransactionAcquire.cpp b/src/xrpld/app/ledger/detail/TransactionAcquire.cpp index f838a912eb..8cc26b1da6 100644 --- a/src/xrpld/app/ledger/detail/TransactionAcquire.cpp +++ b/src/xrpld/app/ledger/detail/TransactionAcquire.cpp @@ -3,7 +3,8 @@ #include #include #include -#include + +#include #include @@ -19,8 +20,16 @@ enum { MAX_TIMEOUTS = 20, }; -TransactionAcquire::TransactionAcquire(Application& app, uint256 const& hash, std::unique_ptr peerSet) - : TimeoutCounter(app, hash, TX_ACQUIRE_TIMEOUT, {jtTXN_DATA, "TxAcq", {}}, app.journal("TransactionAcquire")) +TransactionAcquire::TransactionAcquire( + Application& app, + uint256 const& hash, + std::unique_ptr peerSet) + : TimeoutCounter( + app, + hash, + TX_ACQUIRE_TIMEOUT, + {jtTXN_DATA, "TxAcq", {}}, + app.journal("TransactionAcquire")) , mHaveRoot(false) , mPeerSet(std::move(peerSet)) { @@ -50,8 +59,9 @@ TransactionAcquire::done() // not be called. That's fine. According to David the giveSet() call // just updates the consensus and related structures when we acquire // a transaction set. No need to update them if we're shutting down. - app_.getJobQueue().addJob( - jtTXN_DATA, "ComplAcquire", [pap, hash, map]() { pap->getInboundTransactions().giveSet(hash, map, true); }); + app_.getJobQueue().addJob(jtTXN_DATA, "ComplAcquire", [pap, hash, map]() { + pap->getInboundTransactions().giveSet(hash, map, true); + }); } } @@ -93,7 +103,8 @@ TransactionAcquire::trigger(std::shared_ptr const& peer) if (!mHaveRoot) { - JLOG(journal_.trace()) << "TransactionAcquire::trigger " << (peer ? "havePeer" : "noPeer") << " no root"; + JLOG(journal_.trace()) << "TransactionAcquire::trigger " << (peer ? "havePeer" : "noPeer") + << " no root"; protocol::TMGetLedger tmGL; tmGL.set_ledgerhash(hash_.begin(), hash_.size()); tmGL.set_itype(protocol::liTS_CANDIDATE); @@ -193,7 +204,8 @@ TransactionAcquire::takeNodes( } catch (std::exception const& ex) { - JLOG(journal_.error()) << "Peer " << peer->id() << " sent us junky transaction node data: " << ex.what(); + JLOG(journal_.error()) << "Peer " << peer->id() + << " sent us junky transaction node data: " << ex.what(); return SHAMapAddNode::invalid(); } } @@ -202,7 +214,9 @@ void TransactionAcquire::addPeers(std::size_t limit) { mPeerSet->addPeers( - limit, [this](auto peer) { return peer->hasTxSet(hash_); }, [this](auto peer) { trigger(peer); }); + limit, + [this](auto peer) { return peer->hasTxSet(hash_); }, + [this](auto peer) { trigger(peer); }); } void diff --git a/src/xrpld/app/ledger/detail/TransactionAcquire.h b/src/xrpld/app/ledger/detail/TransactionAcquire.h index 4345c74fc6..a39f6a2f35 100644 --- a/src/xrpld/app/ledger/detail/TransactionAcquire.h +++ b/src/xrpld/app/ledger/detail/TransactionAcquire.h @@ -19,7 +19,9 @@ public: ~TransactionAcquire() = default; SHAMapAddNode - takeNodes(std::vector> const& data, std::shared_ptr const&); + takeNodes( + std::vector> const& data, + std::shared_ptr const&); void init(int startPeers); diff --git a/src/xrpld/app/ledger/detail/TransactionMaster.cpp b/src/xrpld/app/ledger/detail/TransactionMaster.cpp index 834234dd4e..b45dbd5ba9 100644 --- a/src/xrpld/app/ledger/detail/TransactionMaster.cpp +++ b/src/xrpld/app/ledger/detail/TransactionMaster.cpp @@ -9,7 +9,13 @@ namespace xrpl { TransactionMaster::TransactionMaster(Application& app) - : mApp(app), mCache("TransactionCache", 65536, std::chrono::minutes{30}, stopwatch(), mApp.journal("TaggedCache")) + : mApp(app) + , mCache( + "TransactionCache", + 65536, + std::chrono::minutes{30}, + stopwatch(), + mApp.journal("TaggedCache")) { } @@ -57,7 +63,10 @@ TransactionMaster::fetch(uint256 const& txnID, error_code_i& ec) } std::variant, std::shared_ptr>, TxSearched> -TransactionMaster::fetch(uint256 const& txnID, ClosedInterval const& range, error_code_i& ec) +TransactionMaster::fetch( + uint256 const& txnID, + ClosedInterval const& range, + error_code_i& ec) { using TxPair = std::pair, std::shared_ptr>; @@ -78,7 +87,10 @@ TransactionMaster::fetch(uint256 const& txnID, ClosedInterval const& r } std::shared_ptr -TransactionMaster::fetch(boost::intrusive_ptr const& item, SHAMapNodeType type, std::uint32_t uCommitLedger) +TransactionMaster::fetch( + boost::intrusive_ptr const& item, + SHAMapNodeType type, + std::uint32_t uCommitLedger) { std::shared_ptr txn; auto iTx = fetch_from_cache(item->key()); diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index 7a59d586e0..91cc387d54 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include #include #include #include @@ -15,17 +15,16 @@ #include #include #include -#include -#include -#include -#include #include #include #include #include +#include +#include #include #include -#include +#include +#include #include #include #include @@ -36,10 +35,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -48,7 +49,9 @@ #include #include #include +#include #include +#include #include #include @@ -157,6 +160,7 @@ public: NodeCache m_tempNodeCache; CachedSLEs cachedSLEs_; + std::unique_ptr networkIDService_; std::optional> nodeIdentity_; ValidatorKeys const validatorKeys_; @@ -164,8 +168,7 @@ public: std::unique_ptr m_nodeStore; NodeFamily nodeFamily_; - // VFALCO TODO Make OrderBookDB abstract - OrderBookDB m_orderBookDB; + std::unique_ptr m_orderBookDB; std::unique_ptr m_pathRequests; std::unique_ptr m_ledgerMaster; std::unique_ptr ledgerCleaner_; @@ -234,78 +237,104 @@ public: //-------------------------------------------------------------------------- - ApplicationImp(std::unique_ptr config, std::unique_ptr logs, std::unique_ptr timeKeeper) + ApplicationImp( + std::unique_ptr config, + std::unique_ptr logs, + std::unique_ptr timeKeeper) : BasicApp(numberOfThreads(*config)) , config_(std::move(config)) , logs_(std::move(logs)) , timeKeeper_(std::move(timeKeeper)) - , instanceCookie_(1 + rand_int(crypto_prng(), std::numeric_limits::max() - 1)) + , instanceCookie_( + 1 + rand_int(crypto_prng(), std::numeric_limits::max() - 1)) , m_journal(logs_->journal("Application")) // PerfLog must be started before any other threads are launched. - , perfLog_(perf::make_PerfLog( - perf::setup_PerfLog(config_->section("perf"), config_->CONFIG_DIR), - *this, - logs_->journal("PerfLog"), - [this] { signalStop("PerfLog"); })) + , perfLog_( + perf::make_PerfLog( + perf::setup_PerfLog(config_->section("perf"), config_->CONFIG_DIR), + *this, + logs_->journal("PerfLog"), + [this] { signalStop("PerfLog"); })) , m_txMaster(*this) - , m_collectorManager(make_CollectorManager(config_->section(SECTION_INSIGHT), logs_->journal("Collector"))) + , m_collectorManager( + make_CollectorManager(config_->section(SECTION_INSIGHT), logs_->journal("Collector"))) - , m_jobQueue(std::make_unique( - [](std::unique_ptr const& config) { - if (config->standalone() && !config->FORCE_MULTI_THREAD) - return 1; + , m_jobQueue( + std::make_unique( + [](std::unique_ptr const& config) { + if (config->standalone() && !config->FORCE_MULTI_THREAD) + return 1; - if (config->WORKERS) - return config->WORKERS; + if (config->WORKERS) + return config->WORKERS; - auto count = static_cast(std::thread::hardware_concurrency()); + 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) - count = 6 + std::min(count, 8); - else if (config->NODE_SIZE >= 3 && count >= 8) - count = 4 + std::min(count, 6); - else - count = 2 + std::min(count, 4); + // 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) + count = 6 + std::min(count, 8); + else if (config->NODE_SIZE >= 3 && count >= 8) + count = 4 + std::min(count, 6); + else + count = 2 + std::min(count, 4); - return count; - }(config_), - m_collectorManager->group("jobq"), - logs_->journal("JobQueue"), - *logs_, - *perfLog_)) + return count; + }(config_), + m_collectorManager->group("jobq"), + logs_->journal("JobQueue"), + *logs_, + *perfLog_)) , m_nodeStoreScheduler(*m_jobQueue) - , m_shaMapStore(make_SHAMapStore(*this, m_nodeStoreScheduler, logs_->journal("SHAMapStore"))) + , m_shaMapStore( + make_SHAMapStore(*this, m_nodeStoreScheduler, logs_->journal("SHAMapStore"))) - , m_tempNodeCache("NodeCache", 16384, std::chrono::seconds{90}, stopwatch(), logs_->journal("TaggedCache")) + , m_tempNodeCache( + "NodeCache", + 16384, + std::chrono::seconds{90}, + stopwatch(), + logs_->journal("TaggedCache")) - , cachedSLEs_("Cached SLEs", 0, std::chrono::minutes(1), stopwatch(), logs_->journal("CachedSLEs")) + , cachedSLEs_( + "Cached SLEs", + 0, + std::chrono::minutes(1), + stopwatch(), + logs_->journal("CachedSLEs")) + + , networkIDService_(std::make_unique(config_->NETWORK_ID)) , validatorKeys_(*config_, m_journal) - , m_resourceManager(Resource::make_Manager(m_collectorManager->collector(), logs_->journal("Resource"))) + , m_resourceManager( + Resource::make_Manager(m_collectorManager->collector(), logs_->journal("Resource"))) - , m_nodeStore(m_shaMapStore->makeNodeStore(config_->PREFETCH_WORKERS > 0 ? config_->PREFETCH_WORKERS : 4)) + , m_nodeStore(m_shaMapStore->makeNodeStore( + config_->PREFETCH_WORKERS > 0 ? config_->PREFETCH_WORKERS : 4)) , nodeFamily_(*this, *m_collectorManager) - , m_orderBookDB(*this) + , m_orderBookDB(make_OrderBookDB(*this, {config_->PATH_SEARCH_MAX, config_->standalone()})) , m_pathRequests( - std::make_unique(*this, logs_->journal("PathRequest"), m_collectorManager->collector())) + std::make_unique( + *this, + logs_->journal("PathRequest"), + m_collectorManager->collector())) - , m_ledgerMaster(std::make_unique( - *this, - stopwatch(), - m_collectorManager->collector(), - logs_->journal("LedgerMaster"))) + , m_ledgerMaster( + std::make_unique( + *this, + stopwatch(), + m_collectorManager->collector(), + logs_->journal("LedgerMaster"))) , ledgerCleaner_(make_LedgerCleaner(*this, logs_->journal("LedgerCleaner"))) @@ -317,9 +346,15 @@ public: , m_inboundTransactions(make_InboundTransactions( *this, m_collectorManager->collector(), - [this](std::shared_ptr const& set, bool fromAcquire) { gotTXSet(set, fromAcquire); })) + [this](std::shared_ptr const& set, bool fromAcquire) { + gotTXSet(set, fromAcquire); + })) - , m_ledgerReplayer(std::make_unique(*this, *m_inboundLedgers, make_PeerSetBuilder(*this))) + , m_ledgerReplayer( + std::make_unique( + *this, + *m_inboundLedgers, + make_PeerSetBuilder(*this))) , m_acceptedLedgerCache( "AcceptedLedger", @@ -343,19 +378,21 @@ public: , cluster_(std::make_unique(logs_->journal("Overlay"))) - , peerReservations_(std::make_unique(logs_->journal("PeerReservationTable"))) + , peerReservations_( + std::make_unique(logs_->journal("PeerReservationTable"))) , validatorManifests_(std::make_unique(logs_->journal("ManifestCache"))) , publisherManifests_(std::make_unique(logs_->journal("ManifestCache"))) - , validators_(std::make_unique( - *validatorManifests_, - *publisherManifests_, - *timeKeeper_, - config_->legacy("database_path"), - logs_->journal("ValidatorList"), - config_->VALIDATION_QUORUM)) + , validators_( + std::make_unique( + *validatorManifests_, + *publisherManifests_, + *timeKeeper_, + config_->legacy("database_path"), + logs_->journal("ValidatorList"), + config_->VALIDATION_QUORUM)) , validatorSites_(std::make_unique(*this)) @@ -613,7 +650,7 @@ public: OrderBookDB& getOrderBookDB() override { - return m_orderBookDB; + return *m_orderBookDB; } PathRequests& @@ -628,6 +665,12 @@ public: return cachedSLEs_; } + NetworkIDService& + getNetworkIDService() override + { + return *networkIDService_; + } + AmendmentTable& getAmendmentTable() override { @@ -785,15 +828,16 @@ public: { auto j = logs_->journal("NodeObject"); NodeStore::DummyScheduler dummyScheduler; - std::unique_ptr source = NodeStore::Manager::instance().make_Database( - megabytes(config_->getValueFor(SizedItem::burstSize, std::nullopt)), - dummyScheduler, - 0, - config_->section(ConfigSection::importNodeDatabase()), - j); + std::unique_ptr source = + NodeStore::Manager::instance().make_Database( + megabytes(config_->getValueFor(SizedItem::burstSize, std::nullopt)), + dummyScheduler, + 0, + config_->section(ConfigSection::importNodeDatabase()), + j); - JLOG(j.warn()) << "Starting node import from '" << source->getName() << "' to '" << m_nodeStore->getName() - << "'."; + JLOG(j.warn()) << "Starting node import from '" << source->getName() << "' to '" + << m_nodeStore->getName() << "'."; using namespace std::chrono; auto const start = steady_clock::now(); @@ -801,7 +845,8 @@ public: m_nodeStore->importDatabase(*source); auto const elapsed = duration_cast(steady_clock::now() - start); - JLOG(j.warn()) << "Node import from '" << source->getName() << "' took " << elapsed.count() << " seconds."; + JLOG(j.warn()) << "Node import from '" << source->getName() << "' took " + << elapsed.count() << " seconds."; } return true; @@ -823,23 +868,27 @@ public: setSweepTimer() { // Only start the timer if waitHandlerCounter_ is not yet joined. - if (auto optionalCountedHandler = waitHandlerCounter_.wrap([this](boost::system::error_code const& e) { - if (e.value() == boost::system::errc::success) - { - m_jobQueue->addJob(jtSWEEP, "sweep", [this]() { doSweep(); }); - } - // Recover as best we can if an unexpected error occurs. - if (e.value() != boost::system::errc::success && e.value() != boost::asio::error::operation_aborted) - { - // Try again later and hope for the best. - JLOG(m_journal.error()) << "Sweep timer got error '" << e.message() << "'. Restarting timer."; - setSweepTimer(); - } - })) + if (auto optionalCountedHandler = + waitHandlerCounter_.wrap([this](boost::system::error_code const& e) { + if (e.value() == boost::system::errc::success) + { + m_jobQueue->addJob(jtSWEEP, "sweep", [this]() { doSweep(); }); + } + // Recover as best we can if an unexpected error occurs. + if (e.value() != boost::system::errc::success && + e.value() != boost::asio::error::operation_aborted) + { + // Try again later and hope for the best. + JLOG(m_journal.error()) + << "Sweep timer got error '" << e.message() << "'. Restarting timer."; + setSweepTimer(); + } + })) { using namespace std::chrono; sweepTimer_.expires_after( - seconds{config_->SWEEP_INTERVAL.value_or(config_->getValueFor(SizedItem::sweepInterval))}); + seconds{config_->SWEEP_INTERVAL.value_or( + config_->getValueFor(SizedItem::sweepInterval))}); sweepTimer_.async_wait(std::move(*optionalCountedHandler)); } } @@ -848,20 +897,23 @@ public: setEntropyTimer() { // Only start the timer if waitHandlerCounter_ is not yet joined. - if (auto optionalCountedHandler = waitHandlerCounter_.wrap([this](boost::system::error_code const& e) { - if (e.value() == boost::system::errc::success) - { - crypto_prng().mix_entropy(); - setEntropyTimer(); - } - // Recover as best we can if an unexpected error occurs. - if (e.value() != boost::system::errc::success && e.value() != boost::asio::error::operation_aborted) - { - // Try again later and hope for the best. - JLOG(m_journal.error()) << "Entropy timer got error '" << e.message() << "'. Restarting timer."; - setEntropyTimer(); - } - })) + if (auto optionalCountedHandler = + waitHandlerCounter_.wrap([this](boost::system::error_code const& e) { + if (e.value() == boost::system::errc::success) + { + crypto_prng().mix_entropy(); + setEntropyTimer(); + } + // Recover as best we can if an unexpected error occurs. + if (e.value() != boost::system::errc::success && + e.value() != boost::asio::error::operation_aborted) + { + // Try again later and hope for the best. + JLOG(m_journal.error()) << "Entropy timer got error '" << e.message() + << "'. Restarting timer."; + setEntropyTimer(); + } + })) { using namespace std::chrono_literals; entropyTimer_.expires_after(5min); @@ -872,7 +924,8 @@ public: void doSweep() { - XRPL_ASSERT(relationalDatabase_, "xrpl::ApplicationImp::doSweep : non-null relational database"); + XRPL_ASSERT( + relationalDatabase_, "xrpl::ApplicationImp::doSweep : non-null relational database"); if (!config_->standalone() && !relationalDatabase_->transactionDbHasSpace(*config_)) { signalStop("Out of transaction DB space"); @@ -883,23 +936,28 @@ public: // have listeners register for "onSweep ()" notification. { - std::shared_ptr const fullBelowCache = nodeFamily_.getFullBelowCache(); + std::shared_ptr const fullBelowCache = + nodeFamily_.getFullBelowCache(); - std::shared_ptr const treeNodeCache = nodeFamily_.getTreeNodeCache(); + std::shared_ptr const treeNodeCache = + nodeFamily_.getTreeNodeCache(); std::size_t const oldFullBelowSize = fullBelowCache->size(); std::size_t const oldTreeNodeSize = treeNodeCache->size(); nodeFamily_.sweep(); - JLOG(m_journal.debug()) << "NodeFamily::FullBelowCache sweep. Size before: " << oldFullBelowSize - << "; size after: " << fullBelowCache->size(); + JLOG(m_journal.debug()) + << "NodeFamily::FullBelowCache sweep. Size before: " << oldFullBelowSize + << "; size after: " << fullBelowCache->size(); - JLOG(m_journal.debug()) << "NodeFamily::TreeNodeCache sweep. Size before: " << oldTreeNodeSize - << "; size after: " << treeNodeCache->size(); + JLOG(m_journal.debug()) + << "NodeFamily::TreeNodeCache sweep. Size before: " << oldTreeNodeSize + << "; size after: " << treeNodeCache->size(); } { - TaggedCache const& masterTxCache = getMasterTransaction().getCache(); + TaggedCache const& masterTxCache = + getMasterTransaction().getCache(); std::size_t const oldMasterTxSize = masterTxCache.size(); @@ -913,8 +971,9 @@ public: getLedgerMaster().sweep(); - JLOG(m_journal.debug()) << "LedgerMaster sweep. Size before: " << oldLedgerMasterCacheSize - << "; size after: " << getLedgerMaster().getFetchPackCacheSize(); + JLOG(m_journal.debug()) + << "LedgerMaster sweep. Size before: " << oldLedgerMasterCacheSize + << "; size after: " << getLedgerMaster().getFetchPackCacheSize(); } { // NodeCache == TaggedCache @@ -933,25 +992,30 @@ public: getValidations().expire(m_journal); - JLOG(m_journal.debug()) << "Validations Current expire. Size before: " << oldCurrentCacheSize - << "; size after: " << getValidations().sizeOfCurrentCache(); + JLOG(m_journal.debug()) + << "Validations Current expire. Size before: " << oldCurrentCacheSize + << "; size after: " << getValidations().sizeOfCurrentCache(); - JLOG(m_journal.debug()) << "Validations SeqEnforcer expire. Size before: " << oldSizeSeqEnforcesSize - << "; size after: " << getValidations().sizeOfSeqEnforcersCache(); + JLOG(m_journal.debug()) + << "Validations SeqEnforcer expire. Size before: " << oldSizeSeqEnforcesSize + << "; size after: " << getValidations().sizeOfSeqEnforcersCache(); - JLOG(m_journal.debug()) << "Validations ByLedger expire. Size before: " << oldByLedgerSize - << "; size after: " << getValidations().sizeOfByLedgerCache(); + JLOG(m_journal.debug()) + << "Validations ByLedger expire. Size before: " << oldByLedgerSize + << "; size after: " << getValidations().sizeOfByLedgerCache(); - JLOG(m_journal.debug()) << "Validations BySequence expire. Size before: " << oldBySequenceSize - << "; size after: " << getValidations().sizeOfBySequenceCache(); + JLOG(m_journal.debug()) + << "Validations BySequence expire. Size before: " << oldBySequenceSize + << "; size after: " << getValidations().sizeOfBySequenceCache(); } { std::size_t const oldInboundLedgersSize = getInboundLedgers().cacheSize(); getInboundLedgers().sweep(); - JLOG(m_journal.debug()) << "InboundLedgers sweep. Size before: " << oldInboundLedgersSize - << "; size after: " << getInboundLedgers().cacheSize(); + JLOG(m_journal.debug()) + << "InboundLedgers sweep. Size before: " << oldInboundLedgersSize + << "; size after: " << getInboundLedgers().cacheSize(); } { size_t const oldTasksSize = getLedgerReplayer().tasksSize(); @@ -963,19 +1027,22 @@ public: JLOG(m_journal.debug()) << "LedgerReplayer tasks sweep. Size before: " << oldTasksSize << "; size after: " << getLedgerReplayer().tasksSize(); - JLOG(m_journal.debug()) << "LedgerReplayer deltas sweep. Size before: " << oldDeltasSize - << "; size after: " << getLedgerReplayer().deltasSize(); + JLOG(m_journal.debug()) + << "LedgerReplayer deltas sweep. Size before: " << oldDeltasSize + << "; size after: " << getLedgerReplayer().deltasSize(); - JLOG(m_journal.debug()) << "LedgerReplayer skipLists sweep. Size before: " << oldSkipListsSize - << "; size after: " << getLedgerReplayer().skipListsSize(); + JLOG(m_journal.debug()) + << "LedgerReplayer skipLists sweep. Size before: " << oldSkipListsSize + << "; size after: " << getLedgerReplayer().skipListsSize(); } { std::size_t const oldAcceptedLedgerSize = m_acceptedLedgerCache.size(); m_acceptedLedgerCache.sweep(); - JLOG(m_journal.debug()) << "AcceptedLedgerCache sweep. Size before: " << oldAcceptedLedgerSize - << "; size after: " << m_acceptedLedgerCache.size(); + JLOG(m_journal.debug()) + << "AcceptedLedgerCache sweep. Size before: " << oldAcceptedLedgerSize + << "; size after: " << m_acceptedLedgerCache.size(); } { std::size_t const oldCachedSLEsSize = cachedSLEs_.size(); @@ -1017,7 +1084,11 @@ private: loadLedgerFromFile(std::string const& ledgerID); bool - loadOldLedger(std::string const& ledgerID, bool replay, bool isFilename, std::optional trapTxID); + loadOldLedger( + std::string const& ledgerID, + bool replay, + bool isFilename, + std::optional trapTxID); void setMaxDisallowedLedger(); @@ -1115,7 +1186,12 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) Section const& upVoted = config_->section(SECTION_AMENDMENTS); m_amendmentTable = make_AmendmentTable( - *this, config().AMENDMENT_MAJORITY_TIME, supported, upVoted, downVoted, logs_->journal("Amendments")); + *this, + config().AMENDMENT_MAJORITY_TIME, + supported, + upVoted, + downVoted, + logs_->journal("Amendments")); } Pathfinder::initPathTable(); @@ -1128,7 +1204,9 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) startGenesisLedger(); } - else if (startUp == StartUpType::LOAD || startUp == StartUpType::LOAD_FILE || startUp == StartUpType::REPLAY) + else if ( + startUp == StartUpType::LOAD || startUp == StartUpType::LOAD_FILE || + startUp == StartUpType::REPLAY) { JLOG(m_journal.info()) << "Loading specified Ledger"; @@ -1170,7 +1248,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) m_ledgerMaster->setLedgerRangePresent(forcedRange->first, forcedRange->second); } - m_orderBookDB.setup(getLedgerMaster().getCurrentLedger()); + m_orderBookDB->setup(getLedgerMaster().getCurrentLedger()); nodeIdentity_ = getNodeIdentity(*this, cmdline); @@ -1324,7 +1402,8 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) if (!jrReader.parse(cmd, jvCommand)) { - JLOG(m_journal.fatal()) << "Couldn't parse entry in [" << SECTION_RPC_STARTUP << "]: '" << cmd; + JLOG(m_journal.fatal()) + << "Couldn't parse entry in [" << SECTION_RPC_STARTUP << "]: '" << cmd; } if (!config_->quiet()) @@ -1450,8 +1529,9 @@ ApplicationImp::run() validatorSites_->stop(); // TODO Store manifests in manifests.sqlite instead of wallet.db - validatorManifests_->save( - getWalletDB(), "ValidatorManifests", [this](PublicKey const& pubKey) { return validators().listed(pubKey); }); + validatorManifests_->save(getWalletDB(), "ValidatorManifests", [this](PublicKey const& pubKey) { + return validators().listed(pubKey); + }); publisherManifests_->save(getWalletDB(), "PublisherManifests", [this](PublicKey const& pubKey) { return validators().trustedPublisher(pubKey); @@ -1537,8 +1617,9 @@ ApplicationImp::fdRequired() const void ApplicationImp::startGenesisLedger() { - std::vector const initialAmendments = - (config_->START_UP == StartUpType::FRESH) ? m_amendmentTable->getDesired() : std::vector{}; + std::vector const initialAmendments = (config_->START_UP == StartUpType::FRESH) + ? m_amendmentTable->getDesired() + : std::vector{}; std::shared_ptr const genesis = std::make_shared(create_genesis, *config_, initialAmendments, nodeFamily_); @@ -1660,7 +1741,8 @@ ApplicationImp::loadLedgerFromFile(std::string const& name) } if (ledger.get().isMember("total_coins")) { - totalDrops = beast::lexicalCastThrow(ledger.get()["total_coins"].asString()); + totalDrops = + beast::lexicalCastThrow(ledger.get()["total_coins"].asString()); } ledger = ledger.get()["accountState"]; @@ -1758,7 +1840,12 @@ ApplicationImp::loadOldLedger( { // Try to build the ledger from the back end auto il = std::make_shared( - *this, hash, 0, InboundLedger::Reason::GENERIC, stopwatch(), make_DummyPeerSet(*this)); + *this, + hash, + 0, + InboundLedger::Reason::GENERIC, + stopwatch(), + make_DummyPeerSet(*this)); if (il->checkLocal()) loadLedger = il->getLedger(); } @@ -1835,7 +1922,8 @@ ApplicationImp::loadOldLedger( "get the older rules.\n*** CONTINUING ***\n"; } - JLOG(m_journal.info()) << "Loading ledger " << loadLedger->header().hash << " seq:" << loadLedger->header().seq; + JLOG(m_journal.info()) << "Loading ledger " << loadLedger->header().hash + << " seq:" << loadLedger->header().seq; if (loadLedger->header().accountHash.isZero()) { @@ -1999,9 +2087,13 @@ Application::Application() : beast::PropertyStream::Source("app") //------------------------------------------------------------------------------ std::unique_ptr -make_Application(std::unique_ptr config, std::unique_ptr logs, std::unique_ptr timeKeeper) +make_Application( + std::unique_ptr config, + std::unique_ptr logs, + std::unique_ptr timeKeeper) { - return std::make_unique(std::move(config), std::move(logs), std::move(timeKeeper)); + return std::make_unique( + std::move(config), std::move(logs), std::move(timeKeeper)); } void diff --git a/src/xrpld/app/main/Application.h b/src/xrpld/app/main/Application.h index 5ecc84c11c..433992bcda 100644 --- a/src/xrpld/app/main/Application.h +++ b/src/xrpld/app/main/Application.h @@ -153,20 +153,16 @@ public: virtual int fdRequired() const = 0; - /** Retrieve the "wallet database" */ - virtual DatabaseCon& - getWalletDB() = 0; - /** Ensure that a newly-started validator does not sign proposals older * than the last ledger it persisted. */ virtual LedgerIndex getMaxDisallowedLedger() = 0; - - virtual std::optional const& - trapTxID() const = 0; }; std::unique_ptr -make_Application(std::unique_ptr config, std::unique_ptr logs, std::unique_ptr timeKeeper); +make_Application( + std::unique_ptr config, + std::unique_ptr logs, + std::unique_ptr timeKeeper); } // namespace xrpl diff --git a/src/xrpld/app/main/CollectorManager.cpp b/src/xrpld/app/main/CollectorManager.cpp index 7a3306b60b..353a49de91 100644 --- a/src/xrpld/app/main/CollectorManager.cpp +++ b/src/xrpld/app/main/CollectorManager.cpp @@ -17,7 +17,8 @@ public: if (server == "statsd") { - beast::IP::Endpoint const address(beast::IP::Endpoint::from_string(get(params, "address"))); + beast::IP::Endpoint const address( + beast::IP::Endpoint::from_string(get(params, "address"))); std::string const& prefix(get(params, "prefix")); m_collector = beast::insight::StatsDCollector::New(address, prefix, journal); diff --git a/src/xrpld/app/main/GRPCServer.cpp b/src/xrpld/app/main/GRPCServer.cpp index 9b07728eb8..ced252cb71 100644 --- a/src/xrpld/app/main/GRPCServer.cpp +++ b/src/xrpld/app/main/GRPCServer.cpp @@ -24,7 +24,8 @@ getEndpoint(std::string const& peer) peerClean = peer.substr(first + 1); } - std::optional endpoint = beast::IP::Endpoint::from_string_checked(peerClean); + std::optional endpoint = + beast::IP::Endpoint::from_string_checked(peerClean); if (endpoint) return beast::IP::to_asio_endpoint(endpoint.value()); } @@ -69,7 +70,15 @@ std::shared_ptr GRPCServerImpl::CallData::clone() { return std::make_shared>( - service_, cq_, app_, bindListener_, handler_, forward_, requiredCondition_, loadType_, secureGatewayIPs_); + service_, + cq_, + app_, + bindListener_, + handler_, + forward_, + requiredCondition_, + loadType_, + secureGatewayIPs_); } template @@ -90,8 +99,8 @@ GRPCServerImpl::CallData::process() // ensures that finished is always true when this CallData object // is returned as a tag in handleRpcs(), after sending the response finished_ = true; - auto coro = - app_.getJobQueue().postCoro(JobType::jtRPC, "gRPC-Client", [thisShared](std::shared_ptr coro) { + auto coro = app_.getJobQueue().postCoro( + JobType::jtRPC, "gRPC-Client", [thisShared](std::shared_ptr coro) { thisShared->process(coro); }); @@ -113,7 +122,8 @@ GRPCServerImpl::CallData::process(std::shared_ptr::process(std::shared_ptr> requests = setupListeners(); auto erase = [&requests](Processor* ptr) { - auto it = std::find_if( - requests.begin(), requests.end(), [ptr](std::shared_ptr& sPtr) { return sPtr.get() == ptr; }); + auto it = + std::find_if(requests.begin(), requests.end(), [ptr](std::shared_ptr& sPtr) { + return sPtr.get() == ptr; + }); BOOST_ASSERT(it != requests.end()); it->swap(requests.back()); requests.pop_back(); @@ -428,60 +442,71 @@ GRPCServerImpl::setupListeners() auto addToRequests = [&requests](auto callData) { requests.push_back(std::move(callData)); }; { - using cd = CallData; + using cd = + CallData; - addToRequests(std::make_shared( - service_, - *cq_, - app_, - &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedger, - doLedgerGrpc, - &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedger, - RPC::NO_CONDITION, - Resource::feeMediumBurdenRPC, - secureGatewayIPs_)); + addToRequests( + std::make_shared( + service_, + *cq_, + app_, + &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedger, + doLedgerGrpc, + &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedger, + RPC::NO_CONDITION, + Resource::feeMediumBurdenRPC, + secureGatewayIPs_)); } { - using cd = CallData; + using cd = CallData< + org::xrpl::rpc::v1::GetLedgerDataRequest, + org::xrpl::rpc::v1::GetLedgerDataResponse>; - addToRequests(std::make_shared( - service_, - *cq_, - app_, - &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedgerData, - doLedgerDataGrpc, - &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedgerData, - RPC::NO_CONDITION, - Resource::feeMediumBurdenRPC, - secureGatewayIPs_)); + addToRequests( + std::make_shared( + service_, + *cq_, + app_, + &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedgerData, + doLedgerDataGrpc, + &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedgerData, + RPC::NO_CONDITION, + Resource::feeMediumBurdenRPC, + secureGatewayIPs_)); } { - using cd = CallData; + using cd = CallData< + org::xrpl::rpc::v1::GetLedgerDiffRequest, + org::xrpl::rpc::v1::GetLedgerDiffResponse>; - addToRequests(std::make_shared( - service_, - *cq_, - app_, - &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedgerDiff, - doLedgerDiffGrpc, - &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedgerDiff, - RPC::NO_CONDITION, - Resource::feeMediumBurdenRPC, - secureGatewayIPs_)); + addToRequests( + std::make_shared( + service_, + *cq_, + app_, + &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedgerDiff, + doLedgerDiffGrpc, + &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedgerDiff, + RPC::NO_CONDITION, + Resource::feeMediumBurdenRPC, + secureGatewayIPs_)); } { - using cd = CallData; + using cd = CallData< + org::xrpl::rpc::v1::GetLedgerEntryRequest, + org::xrpl::rpc::v1::GetLedgerEntryResponse>; - addToRequests(std::make_shared( - service_, - *cq_, - app_, - &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedgerEntry, - doLedgerEntryGrpc, - &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedgerEntry, - RPC::NO_CONDITION, - Resource::feeMediumBurdenRPC, - secureGatewayIPs_)); + addToRequests( + std::make_shared( + service_, + *cq_, + app_, + &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedgerEntry, + doLedgerEntryGrpc, + &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedgerEntry, + RPC::NO_CONDITION, + Resource::feeMediumBurdenRPC, + secureGatewayIPs_)); } return requests; } diff --git a/src/xrpld/app/main/GRPCServer.h b/src/xrpld/app/main/GRPCServer.h index fdac2b6484..037c91df93 100644 --- a/src/xrpld/app/main/GRPCServer.h +++ b/src/xrpld/app/main/GRPCServer.h @@ -3,13 +3,13 @@ #include #include #include -#include #include #include #include #include #include +#include #include @@ -89,8 +89,11 @@ private: static unsigned constexpr apiVersion = 1; template - using Forward = std::function< - grpc::Status(org::xrpl::rpc::v1::XRPLedgerAPIService::Stub*, grpc::ClientContext*, Request, Response*)>; + using Forward = std::function; public: explicit GRPCServerImpl(Application& app); @@ -123,7 +126,8 @@ public: private: // Class encompassing the state and logic needed to serve a request. template - class CallData : public Processor, public std::enable_shared_from_this> + class CallData : public Processor, + public std::enable_shared_from_this> { private: // The means of communication with the gRPC runtime for an asynchronous diff --git a/src/xrpld/app/main/LoadManager.cpp b/src/xrpld/app/main/LoadManager.cpp index d1336b20d9..5d2bd9a81e 100644 --- a/src/xrpld/app/main/LoadManager.cpp +++ b/src/xrpld/app/main/LoadManager.cpp @@ -1,10 +1,10 @@ #include #include -#include -#include #include #include +#include +#include #include #include @@ -115,7 +115,8 @@ LoadManager::run() { if (timeSpentStalled < stallFatalLogMessageTimeLimit) { - JLOG(journal_.warn()) << "Server stalled for " << timeSpentStalled.count() << " seconds."; + JLOG(journal_.warn()) + << "Server stalled for " << timeSpentStalled.count() << " seconds."; if (app_.getJobQueue().isOverloaded()) { @@ -124,7 +125,8 @@ LoadManager::run() } else { - JLOG(journal_.fatal()) << "Server stalled for " << timeSpentStalled.count() << " seconds."; + JLOG(journal_.fatal()) + << "Server stalled for " << timeSpentStalled.count() << " seconds."; JLOG(journal_.fatal()) << "JobQueue: " << app_.getJobQueue().getJson(0); } } @@ -145,7 +147,8 @@ LoadManager::run() bool change = false; if (app_.getJobQueue().isOverloaded()) { - JLOG(journal_.info()) << "Raising local fee (JQ overload): " << app_.getJobQueue().getJson(0); + JLOG(journal_.info()) << "Raising local fee (JQ overload): " + << app_.getJobQueue().getJson(0); change = app_.getFeeTrack().raiseLocalFee(); } else diff --git a/src/xrpld/app/main/Main.cpp b/src/xrpld/app/main/Main.cpp index 7bdccd12a7..83bdb51ec1 100644 --- a/src/xrpld/app/main/Main.cpp +++ b/src/xrpld/app/main/Main.cpp @@ -86,11 +86,11 @@ adjustDescriptorLimit(int needed, beast::Journal j) if (needed > available) { - j.fatal() << "Insufficient number of file descriptors: " << needed << " are needed, but only " << available - << " are available."; + j.fatal() << "Insufficient number of file descriptors: " << needed + << " are needed, but only " << available << " are available."; - std::cerr << "Insufficient number of file descriptors: " << needed << " are needed, but only " << available - << " are available.\n"; + std::cerr << "Insufficient number of file descriptors: " << needed + << " are needed, but only " << available << " are available.\n"; return false; } @@ -224,7 +224,8 @@ anyMissing(Runner& runner, multi_selector const& pred) { auto const missing = pred.size() - runner.suites(); runner.add_failures(missing); - std::cout << "Failed: " << missing << " filters did not match any existing test suites" << std::endl; + std::cout << "Failed: " << missing << " filters did not match any existing test suites" + << std::endl; return true; } return false; @@ -275,7 +276,8 @@ runUnitTests( } for (std::size_t i = 0; i < num_jobs; ++i) - children.emplace_back(boost::process::v1::exe = exe_name, boost::process::v1::args = args); + children.emplace_back( + boost::process::v1::exe = exe_name, boost::process::v1::args = args); int bad_child_exits = 0; int terminated_child_exits = 0; @@ -355,10 +357,12 @@ run(int argc, char** argv) po::options_description data("Ledger/Data Options"); data.add_options()("import", importText.c_str())( - "ledger", po::value(), "Load the specified ledger and start from the value given.")( + "ledger", + po::value(), + "Load the specified ledger and start from the value given.")( "ledgerfile", po::value(), "Load the specified ledger file.")( - "load", "Load the current ledger from the local DB.")("net", "Get the initial ledger from the network.")( - "replay", "Replay a ledger close.")( + "load", "Load the current ledger from the local DB.")( + "net", "Get the initial ledger from the network.")("replay", "Replay a ledger close.")( "trap_tx_hash", po::value(), "Trap a specific transaction during replay.")( "start", "Start from a fresh Ledger.")("vacuum", "VACUUM the transaction db.")( "valid", "Consider the initial ledger a valid network ledger."); @@ -395,12 +399,15 @@ run(int argc, char** argv) "is made available to each suite that runs. Interpretation of the " "argument is handled individually by any suite that accesses it -- " "as such, it typically only make sense to provide this when running " - "a single suite.")("unittest-ipv6", "Use IPv6 localhost when running unittests (default is IPv4).")( + "a single suite.")( + "unittest-ipv6", "Use IPv6 localhost when running unittests (default is IPv4).")( "unittest-log", "Force unit test log message output. Only useful in combination with " "--quiet, in which case log messages will print but suite/case names " "will not.")( - "unittest-jobs", po::value(), "Number of unittest jobs to run in parallel (child processes)."); + "unittest-jobs", + po::value(), + "Number of unittest jobs to run in parallel (child processes)."); #endif // ENABLE_TESTS // These are hidden options, not intended to be shown in the usage/help @@ -533,7 +540,11 @@ run(int argc, char** argv) auto configFile = vm.count("conf") ? vm["conf"].as() : std::string(); // config file, quiet flag. - config->setup(configFile, bool(vm.count("quiet")), bool(vm.count("silent")), bool(vm.count("standalone"))); + config->setup( + configFile, + bool(vm.count("quiet")), + bool(vm.count("silent")), + bool(vm.count("standalone"))); if (vm.count("vacuum")) { @@ -565,7 +576,9 @@ run(int argc, char** argv) auto const r = [&vm]() -> std::vector { std::vector strVec; boost::split( - strVec, vm["force_ledger_present_range"].as(), boost::algorithm::is_any_of(",")); + strVec, + vm["force_ledger_present_range"].as(), + boost::algorithm::is_any_of(",")); std::vector result; for (auto& s : strVec) { @@ -736,12 +749,13 @@ run(int argc, char** argv) // say 1.7 or higher if (config->had_trailing_comments()) { - JLOG(logs->journal("Application").warn()) << "Trailing comments were seen in your config file. " - << "The treatment of inline/trailing comments has changed " - "recently. " - << "Any `#` characters NOT intended to delimit comments should " - "be " - << "preceded by a \\"; + JLOG(logs->journal("Application").warn()) + << "Trailing comments were seen in your config file. " + << "The treatment of inline/trailing comments has changed " + "recently. " + << "Any `#` characters NOT intended to delimit comments should " + "be " + << "preceded by a \\"; } // We want at least 1024 file descriptors. We'll @@ -752,7 +766,8 @@ run(int argc, char** argv) if (vm.count("debug")) setDebugLogSink(logs->makeSink("Debug", beast::severities::kTrace)); - auto app = make_Application(std::move(config), std::move(logs), std::make_unique()); + auto app = + make_Application(std::move(config), std::move(logs), std::make_unique()); if (!app->setup(vm)) return -1; @@ -773,7 +788,8 @@ run(int argc, char** argv) // We have an RPC command to process: beast::setCurrentThreadName("rippled: rpc"); - return RPCCall::fromCommandLine(*config, vm["parameters"].as>(), *logs); + return RPCCall::fromCommandLine( + *config, vm["parameters"].as>(), *logs); // LCOV_EXCL_STOP } diff --git a/src/xrpld/app/main/NodeStoreScheduler.cpp b/src/xrpld/app/main/NodeStoreScheduler.cpp index 1b3ff4ab03..1ca8e80523 100644 --- a/src/xrpld/app/main/NodeStoreScheduler.cpp +++ b/src/xrpld/app/main/NodeStoreScheduler.cpp @@ -27,7 +27,9 @@ NodeStoreScheduler::onFetch(NodeStore::FetchReport const& report) return; jobQueue_.addLoadEvents( - report.fetchType == NodeStore::FetchType::async ? jtNS_ASYNC_READ : jtNS_SYNC_READ, 1, report.elapsed); + report.fetchType == NodeStore::FetchType::async ? jtNS_ASYNC_READ : jtNS_SYNC_READ, + 1, + report.elapsed); } void diff --git a/src/xrpld/app/misc/AmendmentTableImpl.h b/src/xrpld/app/misc/AmendmentTableImpl.h new file mode 100644 index 0000000000..fe7c067d5a --- /dev/null +++ b/src/xrpld/app/misc/AmendmentTableImpl.h @@ -0,0 +1,18 @@ +#pragma once + +#include + +#include + +namespace xrpl { + +std::unique_ptr +make_AmendmentTable( + ServiceRegistry& registry, + std::chrono::seconds majorityTime, + std::vector const& supported, + Section const& enabled, + Section const& vetoed, + beast::Journal journal); + +} // namespace xrpl diff --git a/src/xrpld/app/misc/CanonicalTXSet.cpp b/src/xrpld/app/misc/CanonicalTXSet.cpp index 6e6102afe7..f971c100eb 100644 --- a/src/xrpld/app/misc/CanonicalTXSet.cpp +++ b/src/xrpld/app/misc/CanonicalTXSet.cpp @@ -32,8 +32,12 @@ CanonicalTXSet::accountKey(AccountID const& account) void CanonicalTXSet::insert(std::shared_ptr const& txn) { - map_.insert(std::make_pair( - Key(accountKey(txn->getAccountID(sfAccount)), txn->getSeqProxy(), txn->getTransactionID()), txn)); + map_.insert( + std::make_pair( + Key(accountKey(txn->getAccountID(sfAccount)), + txn->getSeqProxy(), + txn->getTransactionID()), + txn)); } std::shared_ptr @@ -57,7 +61,8 @@ CanonicalTXSet::popAcctTransaction(std::shared_ptr const& tx) Key const after(effectiveAccount, seqProxy, beast::zero); auto const itrNext{map_.lower_bound(after)}; if (itrNext != map_.end() && itrNext->first.getAccount() == effectiveAccount && - (!itrNext->second->getSeqProxy().isSeq() || itrNext->second->getSeqProxy().value() == seqProxy.value() + 1)) + (!itrNext->second->getSeqProxy().isSeq() || + itrNext->second->getSeqProxy().value() == seqProxy.value() + 1)) { result = std::move(itrNext->second); map_.erase(itrNext); diff --git a/src/xrpld/app/misc/FeeVoteImpl.cpp b/src/xrpld/app/misc/FeeVoteImpl.cpp index 4c38b561f6..5cb203115a 100644 --- a/src/xrpld/app/misc/FeeVoteImpl.cpp +++ b/src/xrpld/app/misc/FeeVoteImpl.cpp @@ -54,7 +54,8 @@ VotableValue::getVotes() const -> std::pair for (auto const& [key, val] : voteMap_) { // Take most voted value between current and target, inclusive - if ((key <= std::max(target_, current_)) && (key >= std::min(target_, current_)) && (val > weight)) + if ((key <= std::max(target_, current_)) && (key >= std::min(target_, current_)) && + (val > weight)) { ourVote = key; weight = val; @@ -89,7 +90,8 @@ public: //-------------------------------------------------------------------------- -FeeVoteImpl::FeeVoteImpl(FeeSetup const& setup, beast::Journal journal) : target_(setup), journal_(journal) +FeeVoteImpl::FeeVoteImpl(FeeSetup const& setup, beast::Journal journal) + : target_(setup), journal_(journal) { } @@ -101,17 +103,22 @@ FeeVoteImpl::doValidation(Fees const& lastFees, Rules const& rules, STValidation // not send a value. if (rules.enabled(featureXRPFees)) { - auto vote = [&v, this](auto const current, XRPAmount target, char const* name, auto const& sfield) { - if (current != target) - { - JLOG(journal_.info()) << "Voting for " << name << " of " << target; + auto vote = + [&v, this](auto const current, XRPAmount target, char const* name, auto const& sfield) { + if (current != target) + { + JLOG(journal_.info()) << "Voting for " << name << " of " << target; - v[sfield] = target; - } - }; + v[sfield] = target; + } + }; vote(lastFees.base, target_.reference_fee, "base fee", sfBaseFeeDrops); vote(lastFees.reserve, target_.account_reserve, "base reserve", sfReserveBaseDrops); - vote(lastFees.increment, target_.owner_reserve, "reserve increment", sfReserveIncrementDrops); + vote( + lastFees.increment, + target_.owner_reserve, + "reserve increment", + sfReserveIncrementDrops); } else { @@ -134,7 +141,12 @@ 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.increment, target_.owner_reserve, to32, "reserve increment", sfReserveIncrement); + vote( + lastFees.increment, + target_.owner_reserve, + to32, + "reserve increment", + sfReserveIncrement); } } @@ -146,7 +158,8 @@ FeeVoteImpl::doVoting( { // LCL must be flag ledger XRPL_ASSERT( - lastClosedLedger && isFlagLedger(lastClosedLedger->seq()), "xrpl::FeeVoteImpl::doVoting : has a flag ledger"); + lastClosedLedger && isFlagLedger(lastClosedLedger->seq()), + "xrpl::FeeVoteImpl::doVoting : has a flag ledger"); detail::VotableValue baseFeeVote(lastClosedLedger->fees().base, target_.reference_fee); @@ -157,21 +170,22 @@ FeeVoteImpl::doVoting( auto const& rules = lastClosedLedger->rules(); if (rules.enabled(featureXRPFees)) { - auto doVote = - [](std::shared_ptr const& val, detail::VotableValue& value, SF_AMOUNT const& xrpField) { - if (auto const field = ~val->at(~xrpField); field && field->native()) - { - auto const vote = field->xrp(); - if (isLegalAmountSigned(vote)) - value.addVote(vote); - else - value.noVote(); - } + auto doVote = [](std::shared_ptr const& val, + detail::VotableValue& value, + SF_AMOUNT const& xrpField) { + if (auto const field = ~val->at(~xrpField); field && field->native()) + { + auto const vote = field->xrp(); + if (isLegalAmountSigned(vote)) + value.addVote(vote); else - { value.noVote(); - } - }; + } + else + { + value.noVote(); + } + }; for (auto const& val : set) { @@ -184,26 +198,27 @@ FeeVoteImpl::doVoting( } else { - auto doVote = - [](std::shared_ptr const& val, detail::VotableValue& value, auto const& valueField) { - if (auto const field = val->at(~valueField)) - { - using XRPType = XRPAmount::value_type; - auto const vote = *field; - if (vote <= std::numeric_limits::max() && - isLegalAmountSigned(XRPAmount{unsafe_cast(vote)})) - value.addVote(XRPAmount{unsafe_cast(vote)}); - else - // Invalid amounts will be treated as if they're - // not provided. Don't throw because this value is - // provided by an external entity. - value.noVote(); - } + auto doVote = [](std::shared_ptr const& val, + detail::VotableValue& value, + auto const& valueField) { + if (auto const field = val->at(~valueField)) + { + using XRPType = XRPAmount::value_type; + auto const vote = *field; + if (vote <= std::numeric_limits::max() && + isLegalAmountSigned(XRPAmount{unsafe_cast(vote)})) + value.addVote(XRPAmount{unsafe_cast(vote)}); else - { + // Invalid amounts will be treated as if they're + // not provided. Don't throw because this value is + // provided by an external entity. value.noVote(); - } - }; + } + else + { + value.noVote(); + } + }; for (auto const& val : set) { @@ -228,8 +243,8 @@ FeeVoteImpl::doVoting( // add transactions to our position if (baseFee.second || baseReserve.second || incReserve.second) { - JLOG(journal_.warn()) << "We are voting for a fee change: " << baseFee.first << "/" << baseReserve.first << "/" - << incReserve.first; + JLOG(journal_.warn()) << "We are voting for a fee change: " << baseFee.first << "/" + << baseReserve.first << "/" << incReserve.first; STTx feeTx(ttFEE, [=, &rules](auto& obj) { obj[sfAccount] = AccountID(); @@ -245,8 +260,10 @@ FeeVoteImpl::doVoting( // Without the featureXRPFees amendment, these fields are // required. obj[sfBaseFee] = baseFee.first.dropsAs(baseFeeVote.current()); - obj[sfReserveBase] = baseReserve.first.dropsAs(baseReserveVote.current()); - obj[sfReserveIncrement] = incReserve.first.dropsAs(incReserveVote.current()); + obj[sfReserveBase] = + baseReserve.first.dropsAs(baseReserveVote.current()); + obj[sfReserveIncrement] = + incReserve.first.dropsAs(incReserveVote.current()); obj[sfReferenceFeeUnits] = Config::FEE_UNITS_DEPRECATED; } }); @@ -258,7 +275,8 @@ FeeVoteImpl::doVoting( Serializer s; feeTx.add(s); - if (!initialPosition->addGiveItem(SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(txID, s.slice()))) + if (!initialPosition->addGiveItem( + SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(txID, s.slice()))) { JLOG(journal_.warn()) << "Ledger already had fee change"; } diff --git a/src/xrpld/app/misc/NegativeUNLVote.cpp b/src/xrpld/app/misc/NegativeUNLVote.cpp index d4a64a34dd..6673785b61 100644 --- a/src/xrpld/app/misc/NegativeUNLVote.cpp +++ b/src/xrpld/app/misc/NegativeUNLVote.cpp @@ -68,14 +68,16 @@ NegativeUNLVote::doVoting( if (!candidates.toDisableCandidates.empty()) { auto n = choose(prevLedger->header().hash, candidates.toDisableCandidates); - XRPL_ASSERT(nidToKeyMap.contains(n), "xrpl::NegativeUNLVote::doVoting : found node to disable"); + XRPL_ASSERT( + nidToKeyMap.contains(n), "xrpl::NegativeUNLVote::doVoting : found node to disable"); addTx(seq, nidToKeyMap.at(n), ToDisable, initialSet); } if (!candidates.toReEnableCandidates.empty()) { auto n = choose(prevLedger->header().hash, candidates.toReEnableCandidates); - XRPL_ASSERT(nidToKeyMap.contains(n), "xrpl::NegativeUNLVote::doVoting : found node to enable"); + XRPL_ASSERT( + nidToKeyMap.contains(n), "xrpl::NegativeUNLVote::doVoting : found node to enable"); addTx(seq, nidToKeyMap.at(n), ToReEnable, initialSet); } } @@ -97,7 +99,8 @@ NegativeUNLVote::addTx( Serializer s; negUnlTx.add(s); if (!initialSet->addGiveItem( - SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(negUnlTx.getTransactionID(), s.slice()))) + SHAMapNodeType::tnTRANSACTION_NM, + make_shamapitem(negUnlTx.getTransactionID(), s.slice()))) { JLOG(j_.warn()) << "N-UNL: ledger seq=" << seq << ", add ttUNL_MODIFY tx failed"; } @@ -105,7 +108,8 @@ NegativeUNLVote::addTx( { JLOG(j_.debug()) << "N-UNL: ledger seq=" << seq << ", add a ttUNL_MODIFY Tx with txID: " << negUnlTx.getTransactionID() - << ", the validator to " << (modify == ToDisable ? "disable: " : "re-enable: ") << vp; + << ", the validator to " + << (modify == ToDisable ? "disable: " : "re-enable: ") << vp; } } @@ -152,8 +156,8 @@ NegativeUNLVote::buildScoreTable( auto const numAncestors = ledgerAncestors.size(); if (numAncestors < FLAG_LEDGER_INTERVAL) { - JLOG(j_.debug()) << "N-UNL: ledger " << seq << " not enough history. Can trace back only " << numAncestors - << " ledgers."; + JLOG(j_.debug()) << "N-UNL: ledger " << seq << " not enough history. Can trace back only " + << numAncestors << " ledgers."; return {}; } @@ -168,7 +172,8 @@ NegativeUNLVote::buildScoreTable( // the score table. for (int i = 0; i < FLAG_LEDGER_INTERVAL; ++i) { - for (auto const& v : validations.getTrustedForLedger(ledgerAncestors[numAncestors - 1 - i], seq - 2 - i)) + for (auto const& v : + validations.getTrustedForLedger(ledgerAncestors[numAncestors - 1 - i], seq - 2 - i)) { if (scoreTable.count(v->getNodeID())) ++scoreTable[v->getNodeID()]; @@ -184,12 +189,15 @@ NegativeUNLVote::buildScoreTable( }(); if (myValidationCount < negativeUNLMinLocalValsToVote) { - JLOG(j_.debug()) << "N-UNL: ledger " << seq << ". Local node only issued " << myValidationCount - << " validations in last " << FLAG_LEDGER_INTERVAL << " ledgers." + JLOG(j_.debug()) << "N-UNL: ledger " << seq << ". Local node only issued " + << myValidationCount << " validations in last " << FLAG_LEDGER_INTERVAL + << " ledgers." << " The reliability measurement could be wrong."; return {}; } - else if (myValidationCount > negativeUNLMinLocalValsToVote && myValidationCount <= FLAG_LEDGER_INTERVAL) + else if ( + myValidationCount > negativeUNLMinLocalValsToVote && + myValidationCount <= FLAG_LEDGER_INTERVAL) { return scoreTable; } @@ -198,7 +206,8 @@ NegativeUNLVote::buildScoreTable( // cannot happen because validations.getTrustedForLedger does not // return multiple validations of the same ledger from a validator. JLOG(j_.error()) << "N-UNL: ledger " << seq << ". Local node issued " << myValidationCount - << " validations in last " << FLAG_LEDGER_INTERVAL << " ledgers. Too many!"; + << " validations in last " << FLAG_LEDGER_INTERVAL + << " ledgers. Too many!"; return {}; } } @@ -211,7 +220,8 @@ NegativeUNLVote::findAllCandidates( { // Compute if need to find more validators to disable auto const canAdd = [&]() -> bool { - auto const maxNegativeListed = static_cast(std::ceil(unl.size() * negativeUNLMaxListed)); + auto const maxNegativeListed = + static_cast(std::ceil(unl.size() * negativeUNLMaxListed)); std::size_t negativeListed = 0; for (auto const& n : unl) { @@ -220,8 +230,9 @@ NegativeUNLVote::findAllCandidates( } bool const result = negativeListed < maxNegativeListed; JLOG(j_.trace()) << "N-UNL: nodeId " << myId_ << " lowWaterMark " << negativeUNLLowWaterMark - << " highWaterMark " << negativeUNLHighWaterMark << " canAdd " << result << " negativeListed " - << negativeListed << " maxNegativeListed " << maxNegativeListed; + << " highWaterMark " << negativeUNLHighWaterMark << " canAdd " << result + << " negativeListed " << negativeListed << " maxNegativeListed " + << maxNegativeListed; return result; }(); @@ -235,7 +246,8 @@ NegativeUNLVote::findAllCandidates( // (2) has less than negativeUNLLowWaterMark validations, // (3) is not in negUnl, and // (4) is not a new validator. - if (canAdd && score < negativeUNLLowWaterMark && !negUnl.count(nodeId) && !newValidators_.count(nodeId)) + if (canAdd && score < negativeUNLLowWaterMark && !negUnl.count(nodeId) && + !newValidators_.count(nodeId)) { JLOG(j_.trace()) << "N-UNL: toDisable candidate " << nodeId; candidates.toDisableCandidates.push_back(nodeId); diff --git a/src/xrpld/app/misc/NegativeUNLVote.h b/src/xrpld/app/misc/NegativeUNLVote.h index 4019d32f13..95646af034 100644 --- a/src/xrpld/app/misc/NegativeUNLVote.h +++ b/src/xrpld/app/misc/NegativeUNLVote.h @@ -125,7 +125,11 @@ private: * @param initialSet the transaction set */ void - addTx(LedgerIndex seq, PublicKey const& vp, NegativeUNLModify modify, std::shared_ptr const& initialSet); + addTx( + LedgerIndex seq, + PublicKey const& vp, + NegativeUNLModify modify, + std::shared_ptr const& initialSet); /** * Pick one candidate from a vector of candidates. diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index 7da26ada40..8178611c61 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -6,24 +7,20 @@ #include #include #include -#include #include #include #include -#include #include -#include -#include -#include #include #include #include #include #include +#include #include -#include #include #include +#include #include #include #include @@ -38,9 +35,13 @@ #include #include #include +#include +#include #include #include #include +#include +#include #include #include #include @@ -50,6 +51,8 @@ #include #include #include +#include +#include #include #include @@ -179,7 +182,10 @@ class NetworkOPsImp final : public NetworkOPs { ServerFeeSummary() = default; - ServerFeeSummary(XRPAmount fee, TxQ::Metrics&& escalationMetrics, LoadFeeTrack const& loadFeeTrack); + ServerFeeSummary( + XRPAmount fee, + TxQ::Metrics&& escalationMetrics, + LoadFeeTrack const& loadFeeTrack); bool operator!=(ServerFeeSummary const& b) const; @@ -197,7 +203,7 @@ class NetworkOPsImp final : public NetworkOPs public: NetworkOPsImp( - Application& app, + ServiceRegistry& registry, NetworkOPs::clock_type& clock, bool standalone, std::size_t minPeerCount, @@ -208,7 +214,7 @@ public: boost::asio::io_context& io_svc, beast::Journal journal, beast::insight::Collector::ptr const& collector) - : app_(app) + : registry_(registry) , m_journal(journal) , m_localTX(make_LocalTxs()) , mMode(start_valid ? OperatingMode::FULL : OperatingMode::DISCONNECTED) @@ -216,16 +222,21 @@ public: , clusterTimer_(io_svc) , accountHistoryTxTimer_(io_svc) , mConsensus( - app, - make_FeeVote(setup_FeeVote(app_.config().section("voting")), app_.logs().journal("FeeVote")), + registry_.app(), + make_FeeVote( + setup_FeeVote(registry_.app().config().section("voting")), + registry_.logs().journal("FeeVote")), ledgerMaster, *m_localTX, - app.getInboundTransactions(), + registry.getInboundTransactions(), beast::get_abstract_clock(), validatorKeys, - app_.logs().journal("LedgerConsensus")) - , validatorPK_(validatorKeys.keys ? validatorKeys.keys->publicKey : decltype(validatorPK_){}) - , validatorMasterPK_(validatorKeys.keys ? validatorKeys.keys->masterPublicKey : decltype(validatorMasterPK_){}) + registry_.logs().journal("LedgerConsensus")) + , validatorPK_( + validatorKeys.keys ? validatorKeys.keys->publicKey : decltype(validatorPK_){}) + , validatorMasterPK_( + validatorKeys.keys ? validatorKeys.keys->masterPublicKey + : decltype(validatorMasterPK_){}) , m_ledgerMaster(ledgerMaster) , m_job_queue(job_queue) , m_standalone(standalone) @@ -261,8 +272,11 @@ public: submitTransaction(std::shared_ptr const&) override; void - processTransaction(std::shared_ptr& transaction, bool bUnlimited, bool bLocal, FailHard failType) - override; + processTransaction( + std::shared_ptr& transaction, + bool bUnlimited, + bool bLocal, + FailHard failType) override; void processTransactionSet(CanonicalTXSet const& set) override; @@ -288,7 +302,10 @@ public: * @param failType fail_hard setting from transaction submission. */ void - doTransactionAsync(std::shared_ptr transaction, bool bUnlimited, FailHard failtype); + doTransactionAsync( + std::shared_ptr transaction, + bool bUnlimited, + FailHard failtype); private: bool @@ -356,7 +373,8 @@ private: public: bool - beginConsensus(uint256 const& networkClosed, std::unique_ptr const& clog) override; + beginConsensus(uint256 const& networkClosed, std::unique_ptr const& clog) + override; void endConsensus(std::unique_ptr const& clog) override; void @@ -439,22 +457,27 @@ public: // InfoSub::Source. // void - subAccount(InfoSub::ref ispListener, hash_set const& vnaAccountIDs, bool rt) override; + subAccount(InfoSub::ref ispListener, hash_set const& vnaAccountIDs, bool rt) + override; void - unsubAccount(InfoSub::ref ispListener, hash_set const& vnaAccountIDs, bool rt) override; + unsubAccount(InfoSub::ref ispListener, hash_set const& vnaAccountIDs, bool rt) + override; // Just remove the subscription from the tracking // not from the InfoSub. Needed for InfoSub destruction void - unsubAccountInternal(std::uint64_t seq, hash_set const& vnaAccountIDs, bool rt) override; + unsubAccountInternal(std::uint64_t seq, hash_set const& vnaAccountIDs, bool rt) + override; error_code_i subAccountHistory(InfoSub::ref ispListener, AccountID const& account) override; void - unsubAccountHistory(InfoSub::ref ispListener, AccountID const& account, bool historyOnly) override; + unsubAccountHistory(InfoSub::ref ispListener, AccountID const& account, bool historyOnly) + override; void - unsubAccountHistoryInternal(std::uint64_t seq, AccountID const& account, bool historyOnly) override; + unsubAccountHistoryInternal(std::uint64_t seq, AccountID const& account, bool historyOnly) + override; bool subLedger(InfoSub::ref ispListener, Json::Value& jvResult) override; @@ -545,7 +568,8 @@ public: } catch (boost::system::system_error const& e) { - JLOG(m_journal.error()) << "NetworkOPs: accountHistoryTxTimer cancel error: " << e.what(); + JLOG(m_journal.error()) + << "NetworkOPs: accountHistoryTxTimer cancel error: " << e.what(); } } // Make sure that any waitHandlers pending in our timers are done. @@ -653,19 +677,22 @@ private: InfoSub::wptr sinkWptr_; std::shared_ptr index_; }; - using SubAccountHistoryMapType = hash_map>; + using SubAccountHistoryMapType = + hash_map>; /** * @note called while holding mSubLock */ void - subAccountHistoryStart(std::shared_ptr const& ledger, SubAccountHistoryInfoWeak& subInfo); + subAccountHistoryStart( + std::shared_ptr const& ledger, + SubAccountHistoryInfoWeak& subInfo); void addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo); void setAccountHistoryJobTimer(SubAccountHistoryInfoWeak subInfo); - Application& app_; + ServiceRegistry& registry_; beast::Journal m_journal; std::unique_ptr m_localTX; @@ -742,15 +769,19 @@ private: template Stats(Handler const& handler, beast::insight::Collector::ptr const& collector) : hook(collector->make_hook(handler)) - , disconnected_duration(collector->make_gauge("State_Accounting", "Disconnected_duration")) + , disconnected_duration( + collector->make_gauge("State_Accounting", "Disconnected_duration")) , connected_duration(collector->make_gauge("State_Accounting", "Connected_duration")) , syncing_duration(collector->make_gauge("State_Accounting", "Syncing_duration")) , tracking_duration(collector->make_gauge("State_Accounting", "Tracking_duration")) , full_duration(collector->make_gauge("State_Accounting", "Full_duration")) - , disconnected_transitions(collector->make_gauge("State_Accounting", "Disconnected_transitions")) - , connected_transitions(collector->make_gauge("State_Accounting", "Connected_transitions")) + , disconnected_transitions( + collector->make_gauge("State_Accounting", "Disconnected_transitions")) + , connected_transitions( + collector->make_gauge("State_Accounting", "Connected_transitions")) , syncing_transitions(collector->make_gauge("State_Accounting", "Syncing_transitions")) - , tracking_transitions(collector->make_gauge("State_Accounting", "Tracking_transitions")) + , tracking_transitions( + collector->make_gauge("State_Accounting", "Tracking_transitions")) , full_transitions(collector->make_gauge("State_Accounting", "Full_transitions")) { } @@ -779,7 +810,8 @@ private: //------------------------------------------------------------------------------ -static std::array const stateNames{{"disconnected", "connected", "syncing", "tracking", "full"}}; +static std::array const stateNames{ + {"disconnected", "connected", "syncing", "tracking", "full"}}; std::array const NetworkOPsImp::states_ = stateNames; @@ -847,7 +879,7 @@ NetworkOPsImp::getHostId(bool forAdmin) // For non-admin uses hash the node public key into a // single RFC1751 word: static std::string const shroudedHostId = [this]() { - auto const& id = app_.nodeIdentity(); + auto const& id = registry_.app().nodeIdentity(); return RFC1751::getWordFromBlob(id.first.data(), id.first.size()); }(); @@ -861,7 +893,7 @@ NetworkOPsImp::setStateTimer() setHeartbeatTimer(); // Only do this work if a cluster is configured - if (app_.cluster().size() != 0) + if (registry_.cluster().size() != 0) setClusterTimer(); } @@ -880,10 +912,12 @@ NetworkOPsImp::setTimer( onExpire(); } // Recover as best we can if an unexpected error occurs. - if (e.value() != boost::system::errc::success && e.value() != boost::asio::error::operation_aborted) + if (e.value() != boost::system::errc::success && + e.value() != boost::asio::error::operation_aborted) { // Try again later and hope for the best. - JLOG(m_journal.error()) << "Timer got error '" << e.message() << "'. Restarting timer."; + JLOG(m_journal.error()) + << "Timer got error '" << e.message() << "'. Restarting timer."; onError(); } })) @@ -899,7 +933,9 @@ NetworkOPsImp::setHeartbeatTimer() setTimer( heartbeatTimer_, mConsensus.parms().ledgerGRANULARITY, - [this]() { m_job_queue.addJob(jtNETOP_TIMER, "NetHeart", [this]() { processHeartbeatTimer(); }); }, + [this]() { + m_job_queue.addJob(jtNETOP_TIMER, "NetHeart", [this]() { processHeartbeatTimer(); }); + }, [this]() { setHeartbeatTimer(); }); } @@ -911,14 +947,17 @@ NetworkOPsImp::setClusterTimer() setTimer( clusterTimer_, 10s, - [this]() { m_job_queue.addJob(jtNETOP_CLUSTER, "NetCluster", [this]() { processClusterTimer(); }); }, + [this]() { + m_job_queue.addJob(jtNETOP_CLUSTER, "NetCluster", [this]() { processClusterTimer(); }); + }, [this]() { setClusterTimer(); }); } void NetworkOPsImp::setAccountHistoryJobTimer(SubAccountHistoryInfoWeak subInfo) { - JLOG(m_journal.debug()) << "Scheduling AccountHistory job for account " << toBase58(subInfo.index_->accountId_); + JLOG(m_journal.debug()) << "Scheduling AccountHistory job for account " + << toBase58(subInfo.index_->accountId_); using namespace std::chrono_literals; setTimer( accountHistoryTxTimer_, @@ -932,13 +971,13 @@ NetworkOPsImp::processHeartbeatTimer() { RclConsensusLogger clog("Heartbeat Timer", mConsensus.validating(), m_journal); { - std::unique_lock lock{app_.getMasterMutex()}; + std::unique_lock lock{registry_.app().getMasterMutex()}; // VFALCO NOTE This is for diagnosing a crash on exit - LoadManager& mgr(app_.getLoadManager()); + LoadManager& mgr(registry_.getLoadManager()); mgr.heartbeat(); - std::size_t const numPeers = app_.overlay().size(); + std::size_t const numPeers = registry_.overlay().size(); // do we have sufficient peers? If not, we are disconnected. if (numPeers < minPeerCount_) @@ -954,8 +993,8 @@ NetworkOPsImp::processHeartbeatTimer() } else { - CLOG(clog.ss()) << "already DISCONNECTED. too few peers (" << numPeers << "), need at least " - << minPeerCount_; + CLOG(clog.ss()) << "already DISCONNECTED. too few peers (" << numPeers + << "), need at least " << minPeerCount_; } // MasterMutex lock need not be held to call setHeartbeatTimer() @@ -990,7 +1029,7 @@ NetworkOPsImp::processHeartbeatTimer() CLOG(clog.ss()) << ". "; } - mConsensus.timerEntry(app_.timeKeeper().closeTime(), clog.ss()); + mConsensus.timerEntry(registry_.timeKeeper().closeTime(), clog.ss()); CLOG(clog.ss()) << "consensus phase " << to_string(mLastConsensusPhase); ConsensusPhase const currPhase = mConsensus.phase(); @@ -1008,16 +1047,17 @@ NetworkOPsImp::processHeartbeatTimer() void NetworkOPsImp::processClusterTimer() { - if (app_.cluster().size() == 0) + if (registry_.cluster().size() == 0) return; using namespace std::chrono_literals; - bool const update = app_.cluster().update( - app_.nodeIdentity().first, + bool const update = registry_.cluster().update( + registry_.app().nodeIdentity().first, "", - (m_ledgerMaster.getValidatedLedgerAge() <= 4min) ? app_.getFeeTrack().getLocalFee() : 0, - app_.timeKeeper().now()); + (m_ledgerMaster.getValidatedLedgerAge() <= 4min) ? registry_.getFeeTrack().getLocalFee() + : 0, + registry_.timeKeeper().now()); if (!update) { @@ -1027,7 +1067,7 @@ NetworkOPsImp::processClusterTimer() } protocol::TMCluster cluster; - app_.cluster().for_each([&cluster](ClusterNode const& node) { + registry_.cluster().for_each([&cluster](ClusterNode const& node) { protocol::TMClusterNode& n = *cluster.add_clusternodes(); n.set_publickey(toBase58(TokenType::NodePublic, node.identity())); n.set_reporttime(node.getReportTime().time_since_epoch().count()); @@ -1036,14 +1076,15 @@ NetworkOPsImp::processClusterTimer() n.set_nodename(node.name()); }); - Resource::Gossip gossip = app_.getResourceManager().exportConsumers(); + Resource::Gossip gossip = registry_.getResourceManager().exportConsumers(); for (auto& item : gossip.items) { protocol::TMLoadSource& node = *cluster.add_loadsources(); node.set_name(to_string(item.address)); node.set_cost(item.balance); } - app_.overlay().foreach(send_if(std::make_shared(cluster, protocol::mtCLUSTER), peer_in_cluster())); + registry_.overlay().foreach( + send_if(std::make_shared(cluster, protocol::mtCLUSTER), peer_in_cluster())); setClusterTimer(); } @@ -1088,7 +1129,7 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) auto const trans = sterilize(*iTrans); auto const txid = trans->getTransactionID(); - auto const flags = app_.getHashRouter().getFlags(txid); + auto const flags = registry_.getHashRouter().getFlags(txid); if ((flags & HashRouterFlags::BAD) != HashRouterFlags::UNDEFINED) { @@ -1099,7 +1140,7 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) try { auto const [validity, reason] = - checkValidity(app_.getHashRouter(), *trans, m_ledgerMaster.getValidatedRules(), app_.config()); + checkValidity(registry_.getHashRouter(), *trans, m_ledgerMaster.getValidatedRules()); if (validity != Validity::Valid) { @@ -1116,7 +1157,7 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) std::string reason; - auto tx = std::make_shared(trans, reason, app_); + auto tx = std::make_shared(trans, reason, registry_.app()); m_job_queue.addJob(jtTRANSACTION, "SubmitTxn", [this, tx]() { auto t = tx; @@ -1127,7 +1168,7 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) bool NetworkOPsImp::preProcessTransaction(std::shared_ptr& transaction) { - auto const newFlags = app_.getHashRouter().getFlags(transaction->getID()); + auto const newFlags = registry_.getHashRouter().getFlags(transaction->getID()); if ((newFlags & HashRouterFlags::BAD) != HashRouterFlags::UNDEFINED) { @@ -1148,15 +1189,16 @@ NetworkOPsImp::preProcessTransaction(std::shared_ptr& transaction) { transaction->setStatus(INVALID); transaction->setResult(temINVALID_FLAG); - app_.getHashRouter().setFlags(transaction->getID(), HashRouterFlags::BAD); + registry_.getHashRouter().setFlags(transaction->getID(), HashRouterFlags::BAD); return false; } // NOTE ximinez - I think this check is redundant, // but I'm not 100% sure yet. // If so, only cost is looking up HashRouter flags. - auto const [validity, reason] = checkValidity(app_.getHashRouter(), sttx, view->rules(), app_.config()); - XRPL_ASSERT(validity == Validity::Valid, "xrpl::NetworkOPsImp::processTransaction : valid validity"); + auto const [validity, reason] = checkValidity(registry_.getHashRouter(), sttx, view->rules()); + XRPL_ASSERT( + validity == Validity::Valid, "xrpl::NetworkOPsImp::processTransaction : valid validity"); // Not concerned with local checks at this point. if (validity == Validity::SigBad) @@ -1164,12 +1206,12 @@ NetworkOPsImp::preProcessTransaction(std::shared_ptr& transaction) JLOG(m_journal.info()) << "Transaction has bad signature: " << reason; transaction->setStatus(INVALID); transaction->setResult(temBAD_SIGNATURE); - app_.getHashRouter().setFlags(transaction->getID(), HashRouterFlags::BAD); + registry_.getHashRouter().setFlags(transaction->getID(), HashRouterFlags::BAD); return false; } // canonicalize can change our pointer - app_.getMasterTransaction().canonicalize(&transaction); + registry_.getMasterTransaction().canonicalize(&transaction); return true; } @@ -1194,7 +1236,10 @@ NetworkOPsImp::processTransaction( } void -NetworkOPsImp::doTransactionAsync(std::shared_ptr transaction, bool bUnlimited, FailHard failType) +NetworkOPsImp::doTransactionAsync( + std::shared_ptr transaction, + bool bUnlimited, + FailHard failType) { std::lock_guard lock(mMutex); @@ -1214,7 +1259,10 @@ NetworkOPsImp::doTransactionAsync(std::shared_ptr transaction, bool } void -NetworkOPsImp::doTransactionSync(std::shared_ptr transaction, bool bUnlimited, FailHard failType) +NetworkOPsImp::doTransactionSync( + std::shared_ptr transaction, + bool bUnlimited, + FailHard failType) { std::unique_lock lock(mMutex); @@ -1224,8 +1272,9 @@ NetworkOPsImp::doTransactionSync(std::shared_ptr transaction, bool transaction->setApplying(); } - doTransactionSyncBatch( - lock, [&transaction](std::unique_lock const&) { return transaction->getApplying(); }); + doTransactionSyncBatch(lock, [&transaction](std::unique_lock const&) { + return transaction->getApplying(); + }); } void @@ -1265,7 +1314,7 @@ NetworkOPsImp::processTransactionSet(CanonicalTXSet const& set) for (auto const& [_, tx] : set) { std::string reason; - auto transaction = std::make_shared(tx, reason, app_); + auto transaction = std::make_shared(tx, reason, registry_.app()); if (transaction->getStatus() == INVALID) { @@ -1273,7 +1322,7 @@ NetworkOPsImp::processTransactionSet(CanonicalTXSet const& set) { JLOG(m_journal.trace()) << "Exception checking transaction: " << reason; } - app_.getHashRouter().setFlags(tx->getTransactionID(), HashRouterFlags::BAD); + registry_.getHashRouter().setFlags(tx->getTransactionID(), HashRouterFlags::BAD); continue; } @@ -1314,8 +1363,9 @@ NetworkOPsImp::processTransactionSet(CanonicalTXSet const& set) doTransactionSyncBatch(lock, [&](std::unique_lock const&) { XRPL_ASSERT(lock.owns_lock(), "xrpl::NetworkOPsImp::processTransactionSet has lock"); - return std::any_of( - mTransactions.begin(), mTransactions.end(), [](auto const& t) { return t.transaction->getApplying(); }); + return std::any_of(mTransactions.begin(), mTransactions.end(), [](auto const& t) { + return t.transaction->getApplying(); + }); }); } @@ -1340,20 +1390,21 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) std::vector transactions; mTransactions.swap(transactions); XRPL_ASSERT(!transactions.empty(), "xrpl::NetworkOPsImp::apply : non-empty transactions"); - XRPL_ASSERT(mDispatchState != DispatchState::running, "xrpl::NetworkOPsImp::apply : is not running"); + XRPL_ASSERT( + mDispatchState != DispatchState::running, "xrpl::NetworkOPsImp::apply : is not running"); mDispatchState = DispatchState::running; batchLock.unlock(); { - std::unique_lock masterLock{app_.getMasterMutex(), std::defer_lock}; + std::unique_lock masterLock{registry_.app().getMasterMutex(), std::defer_lock}; bool changed = false; { std::unique_lock ledgerLock{m_ledgerMaster.peekMutex(), std::defer_lock}; std::lock(masterLock, ledgerLock); - app_.openLedger().modify([&](OpenView& view, beast::Journal j) { + registry_.openLedger().modify([&](OpenView& view, beast::Journal j) { for (TransactionStatus& e : transactions) { // we check before adding to the batch @@ -1364,7 +1415,8 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) if (e.failType == FailHard::yes) flags |= tapFAIL_HARD; - auto const result = app_.getTxQ().apply(app_, view, e.transaction->getSTransaction(), flags, j); + auto const result = registry_.getTxQ().apply( + registry_.app(), view, e.transaction->getSTransaction(), flags, j); e.result = result.ter; e.applied = result.applied; changed = changed || result.applied; @@ -1379,7 +1431,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) if (auto const l = m_ledgerMaster.getValidatedLedger()) validatedLedgerIndex = l->header().seq; - auto newOL = app_.openLedger().current(); + auto newOL = registry_.openLedger().current(); for (TransactionStatus& e : transactions) { e.transaction->clearSubmitResult(); @@ -1393,7 +1445,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) e.transaction->setResult(e.result); if (isTemMalformed(e.result)) - app_.getHashRouter().setFlags(e.transaction->getID(), HashRouterFlags::BAD); + registry_.getHashRouter().setFlags(e.transaction->getID(), HashRouterFlags::BAD); #ifdef DEBUG if (e.result != tesSUCCESS) @@ -1420,14 +1472,15 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) auto const& txCur = e.transaction->getSTransaction(); std::size_t count = 0; - for (auto txNext = m_ledgerMaster.popAcctTransaction(txCur); txNext && count < maxPoppedTransactions; + for (auto txNext = m_ledgerMaster.popAcctTransaction(txCur); + txNext && count < maxPoppedTransactions; txNext = m_ledgerMaster.popAcctTransaction(txCur), ++count) { if (!batchLock.owns_lock()) batchLock.lock(); std::string reason; auto const trans = sterilize(*txNext); - auto t = std::make_shared(trans, reason, app_); + auto t = std::make_shared(trans, reason, registry_.app()); if (t->getApplying()) break; submit_held.emplace_back(t, false, false, FailHard::no); @@ -1459,9 +1512,11 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) { if (e.failType != FailHard::yes) { - auto const lastLedgerSeq = e.transaction->getSTransaction()->at(~sfLastLedgerSequence); - auto const ledgersLeft = lastLedgerSeq ? *lastLedgerSeq - m_ledgerMaster.getCurrentLedgerIndex() - : std::optional{}; + auto const lastLedgerSeq = + e.transaction->getSTransaction()->at(~sfLastLedgerSequence); + auto const ledgersLeft = lastLedgerSeq + ? *lastLedgerSeq - m_ledgerMaster.getCurrentLedgerIndex() + : std::optional{}; // If any of these conditions are met, the transaction can // be held: // 1. It was submitted locally. (Note that this flag is only @@ -1479,7 +1534,8 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) // up!) // if (e.local || (ledgersLeft && ledgersLeft <= LocalTxs::holdLedgers) || - app_.getHashRouter().setFlags(e.transaction->getID(), HashRouterFlags::HELD)) + registry_.getHashRouter().setFlags( + e.transaction->getID(), HashRouterFlags::HELD)) { // transaction should be held JLOG(m_journal.debug()) << "Transaction should be held: " << e.result; @@ -1491,8 +1547,8 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) JLOG(m_journal.debug()) << "Not holding transaction " << e.transaction->getID() << ": " << (e.local ? "local" : "network") << ", " - << "result: " << e.result - << " ledgers left: " << (ledgersLeft ? to_string(*ledgersLeft) : "unspecified"); + << "result: " << e.result << " ledgers left: " + << (ledgersLeft ? to_string(*ledgersLeft) : "unspecified"); } } else @@ -1505,15 +1561,17 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) if (addLocal && !enforceFailHard) { - m_localTX->push_back(m_ledgerMaster.getCurrentLedgerIndex(), e.transaction->getSTransaction()); + m_localTX->push_back( + m_ledgerMaster.getCurrentLedgerIndex(), e.transaction->getSTransaction()); e.transaction->setKept(); } - if ((e.applied || ((mMode != OperatingMode::FULL) && (e.failType != FailHard::yes) && e.local) || + if ((e.applied || + ((mMode != OperatingMode::FULL) && (e.failType != FailHard::yes) && e.local) || (e.result == terQUEUED)) && !enforceFailHard) { - auto const toSkip = app_.getHashRouter().shouldRelay(e.transaction->getID()); + auto const toSkip = registry_.getHashRouter().shouldRelay(e.transaction->getID()); if (auto const sttx = *(e.transaction->getSTransaction()); toSkip && // Skip relaying if it's an inner batch txn. The flag should // only be set if the Batch feature is enabled. If Batch is @@ -1527,19 +1585,21 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) sttx.add(s); tx.set_rawtransaction(s.data(), s.size()); tx.set_status(protocol::tsCURRENT); - tx.set_receivetimestamp(app_.timeKeeper().now().time_since_epoch().count()); + tx.set_receivetimestamp( + registry_.timeKeeper().now().time_since_epoch().count()); tx.set_deferred(e.result == terQUEUED); // FIXME: This should be when we received it - app_.overlay().relay(e.transaction->getID(), tx, *toSkip); + registry_.overlay().relay(e.transaction->getID(), tx, *toSkip); e.transaction->setBroadcast(); } } if (validatedLedgerIndex) { - auto [fee, accountSeq, availableSeq] = - app_.getTxQ().getTxRequiredFeeAndSeq(*newOL, e.transaction->getSTransaction()); - e.transaction->setCurrentLedgerState(*validatedLedgerIndex, fee, accountSeq, availableSeq); + auto [fee, accountSeq, availableSeq] = registry_.getTxQ().getTxRequiredFeeAndSeq( + *newOL, e.transaction->getSTransaction()); + e.transaction->setCurrentLedgerState( + *validatedLedgerIndex, fee, accountSeq, availableSeq); } } } @@ -1713,7 +1773,7 @@ NetworkOPsImp::checkLastClosedLedger(Overlay::PeerSequence const& peerList, uint //------------------------------------------------------------------------- // Determine preferred last closed ledger - auto& validations = app_.getValidations(); + auto& validations = registry_.getValidations(); JLOG(m_journal.debug()) << "ValidationTrie " << Json::Compact(validations.getJsonTrie()); // Will rely on peer LCL if no trusted validations exist @@ -1758,7 +1818,8 @@ NetworkOPsImp::checkLastClosedLedger(Overlay::PeerSequence const& peerList, uint auto consensus = m_ledgerMaster.getLedgerByHash(closedLedger); if (!consensus) - consensus = app_.getInboundLedgers().acquire(closedLedger, 0, InboundLedger::Reason::CONSENSUS); + consensus = registry_.getInboundLedgers().acquire( + closedLedger, 0, InboundLedger::Reason::CONSENSUS); if (consensus && (!m_ledgerMaster.canBeCurrent(consensus) || @@ -1799,7 +1860,7 @@ NetworkOPsImp::switchLastClosedLedger(std::shared_ptr const& newLC clearNeedNetworkLedger(); // Update fee computations. - app_.getTxQ().processClosedLedger(app_, *newLCL, true); + registry_.getTxQ().processClosedLedger(registry_.app(), *newLCL, true); // Caller must own master lock { @@ -1807,14 +1868,14 @@ NetworkOPsImp::switchLastClosedLedger(std::shared_ptr const& newLC // open ledger. Then apply local tx. auto retries = m_localTX->getTxSet(); - auto const lastVal = app_.getLedgerMaster().getValidatedLedger(); + auto const lastVal = registry_.getLedgerMaster().getValidatedLedger(); std::optional rules; if (lastVal) - rules = makeRulesGivenLedger(*lastVal, app_.config().features); + rules = makeRulesGivenLedger(*lastVal, registry_.app().config().features); else - rules.emplace(app_.config().features); - app_.openLedger().accept( - app_, + rules.emplace(registry_.app().config().features); + registry_.openLedger().accept( + registry_.app(), *rules, newLCL, OrderedTxs({}), @@ -1824,7 +1885,7 @@ NetworkOPsImp::switchLastClosedLedger(std::shared_ptr const& newLC "jump", [&](OpenView& view, beast::Journal j) { // Stuff the ledger with transactions from the queue. - return app_.getTxQ().accept(app_, view); + return registry_.getTxQ().accept(registry_.app(), view); }); } @@ -1833,21 +1894,26 @@ NetworkOPsImp::switchLastClosedLedger(std::shared_ptr const& newLC protocol::TMStatusChange s; s.set_newevent(protocol::neSWITCHED_LEDGER); s.set_ledgerseq(newLCL->header().seq); - s.set_networktime(app_.timeKeeper().now().time_since_epoch().count()); - s.set_ledgerhashprevious(newLCL->header().parentHash.begin(), newLCL->header().parentHash.size()); + s.set_networktime(registry_.timeKeeper().now().time_since_epoch().count()); + s.set_ledgerhashprevious( + newLCL->header().parentHash.begin(), newLCL->header().parentHash.size()); s.set_ledgerhash(newLCL->header().hash.begin(), newLCL->header().hash.size()); - app_.overlay().foreach(send_always(std::make_shared(s, protocol::mtSTATUS_CHANGE))); + registry_.overlay().foreach( + send_always(std::make_shared(s, protocol::mtSTATUS_CHANGE))); } bool -NetworkOPsImp::beginConsensus(uint256 const& networkClosed, std::unique_ptr const& clog) +NetworkOPsImp::beginConsensus( + uint256 const& networkClosed, + std::unique_ptr const& clog) { XRPL_ASSERT(networkClosed.isNonZero(), "xrpl::NetworkOPsImp::beginConsensus : nonzero input"); auto closingInfo = m_ledgerMaster.getCurrentLedger()->header(); - JLOG(m_journal.info()) << "Consensus time for #" << closingInfo.seq << " with LCL " << closingInfo.parentHash; + JLOG(m_journal.info()) << "Consensus time for #" << closingInfo.seq << " with LCL " + << closingInfo.parentHash; auto prevLedger = m_ledgerMaster.getLedgerByHash(closingInfo.parentHash); @@ -1874,23 +1940,28 @@ NetworkOPsImp::beginConsensus(uint256 const& networkClosed, std::unique_ptrnegativeUNL()); - TrustChanges const changes = app_.validators().updateTrusted( - app_.getValidations().getCurrentNodeIDs(), + registry_.validators().setNegativeUNL(prevLedger->negativeUNL()); + TrustChanges const changes = registry_.validators().updateTrusted( + registry_.getValidations().getCurrentNodeIDs(), closingInfo.parentCloseTime, *this, - app_.overlay(), - app_.getHashRouter()); + registry_.overlay(), + registry_.getHashRouter()); if (!changes.added.empty() || !changes.removed.empty()) { - app_.getValidations().trustChanged(changes.added, changes.removed); + registry_.getValidations().trustChanged(changes.added, changes.removed); // Update the AmendmentTable so it tracks the current validators. - app_.getAmendmentTable().trustChanged(app_.validators().getQuorumKeys().second); + registry_.getAmendmentTable().trustChanged(registry_.validators().getQuorumKeys().second); } mConsensus.startRound( - app_.timeKeeper().closeTime(), networkClosed, prevLedger, changes.removed, changes.added, clog); + registry_.timeKeeper().closeTime(), + networkClosed, + prevLedger, + changes.removed, + changes.added, + clog); ConsensusPhase const currPhase = mConsensus.phase(); if (mLastConsensusPhase != currPhase) @@ -1925,7 +1996,7 @@ NetworkOPsImp::processTrustedProposal(RCLCxPeerPos peerPos) return false; } - return mConsensus.peerProposal(app_.timeKeeper().closeTime(), peerPos); + return mConsensus.peerProposal(registry_.timeKeeper().closeTime(), peerPos); } void @@ -1939,11 +2010,11 @@ NetworkOPsImp::mapComplete(std::shared_ptr const& map, bool fromAcquire) protocol::TMHaveTransactionSet msg; msg.set_hash(map->getHash().as_uint256().begin(), 256 / 8); msg.set_status(protocol::tsHAVE); - app_.overlay().foreach(send_always(std::make_shared(msg, protocol::mtHAVE_SET))); + registry_.overlay().foreach(send_always(std::make_shared(msg, protocol::mtHAVE_SET))); // We acquired it because consensus asked us to if (fromAcquire) - mConsensus.gotTxSet(app_.timeKeeper().closeTime(), RCLTxSet{map}); + mConsensus.gotTxSet(registry_.timeKeeper().closeTime(), RCLTxSet{map}); } void @@ -1951,7 +2022,7 @@ NetworkOPsImp::endConsensus(std::unique_ptr const& clog) { uint256 deadLedger = m_ledgerMaster.getClosedLedger()->header().parentHash; - for (auto const& it : app_.overlay().getActivePeers()) + for (auto const& it : registry_.overlay().getActivePeers()) { if (it && (it->getClosedLedgerHash() == deadLedger)) { @@ -1961,7 +2032,7 @@ NetworkOPsImp::endConsensus(std::unique_ptr const& clog) } uint256 networkClosed; - bool ledgerChange = checkLastClosedLedger(app_.overlay().getActivePeers(), networkClosed); + bool ledgerChange = checkLastClosedLedger(registry_.overlay().getActivePeers(), networkClosed); if (networkClosed.isZero()) { @@ -1984,13 +2055,15 @@ NetworkOPsImp::endConsensus(std::unique_ptr const& clog) setMode(OperatingMode::TRACKING); } - if (((mMode == OperatingMode::CONNECTED) || (mMode == OperatingMode::TRACKING)) && !ledgerChange) + if (((mMode == OperatingMode::CONNECTED) || (mMode == OperatingMode::TRACKING)) && + !ledgerChange) { // check if the ledger is good enough to go to FULL // Note: Do not go to FULL if we don't have the previous ledger // check if the ledger is bad enough to go to CONNECTED -- TODO auto current = m_ledgerMaster.getCurrentLedger(); - if (app_.timeKeeper().now() < (current->header().parentCloseTime + 2 * current->header().closeTimeResolution)) + if (registry_.timeKeeper().now() < + (current->header().parentCloseTime + 2 * current->header().closeTimeResolution)) { setMode(OperatingMode::FULL); } @@ -2059,15 +2132,16 @@ NetworkOPsImp::ServerFeeSummary::ServerFeeSummary( bool NetworkOPsImp::ServerFeeSummary::operator!=(NetworkOPsImp::ServerFeeSummary const& b) const { - if (loadFactorServer != b.loadFactorServer || loadBaseServer != b.loadBaseServer || baseFee != b.baseFee || - em.has_value() != b.em.has_value()) + if (loadFactorServer != b.loadFactorServer || loadBaseServer != b.loadBaseServer || + baseFee != b.baseFee || em.has_value() != b.em.has_value()) return true; if (em && b.em) { return ( em->minProcessingFeeLevel != b.em->minProcessingFeeLevel || - em->openLedgerFeeLevel != b.em->openLedgerFeeLevel || em->referenceFeeLevel != b.em->referenceFeeLevel); + em->openLedgerFeeLevel != b.em->openLedgerFeeLevel || + em->referenceFeeLevel != b.em->referenceFeeLevel); } return false; @@ -2096,9 +2170,9 @@ NetworkOPsImp::pubServer() Json::Value jvObj(Json::objectValue); ServerFeeSummary f{ - app_.openLedger().current()->fees().base, - app_.getTxQ().getMetrics(*app_.openLedger().current()), - app_.getFeeTrack()}; + registry_.openLedger().current()->fees().base, + registry_.getTxQ().getMetrics(*registry_.openLedger().current()), + registry_.getFeeTrack()}; jvObj[jss::type] = "serverStatus"; jvObj[jss::server_status] = strOperatingMode(); @@ -2110,7 +2184,8 @@ NetworkOPsImp::pubServer() { auto const loadFactor = std::max( safe_cast(f.loadFactorServer), - mulDiv(f.em->openLedgerFeeLevel, f.loadBaseServer, f.em->referenceFeeLevel).value_or(xrpl::muldiv_max)); + mulDiv(f.em->openLedgerFeeLevel, f.loadBaseServer, f.em->referenceFeeLevel) + .value_or(xrpl::muldiv_max)); jvObj[jss::load_factor] = trunc32(loadFactor); jvObj[jss::load_factor_fee_escalation] = f.em->openLedgerFeeLevel.jsonClipped(); @@ -2189,7 +2264,7 @@ NetworkOPsImp::pubValidation(std::shared_ptr const& val) jvObj[jss::flags] = val->getFlags(); jvObj[jss::signing_time] = *(*val)[~sfSigningTime]; jvObj[jss::data] = strHex(val->getSerializer().slice()); - jvObj[jss::network_id] = app_.config().NETWORK_ID; + jvObj[jss::network_id] = registry_.getNetworkIDService().getNetworkID(); if (auto version = (*val)[~sfServerVersion]) jvObj[jss::server_version] = std::to_string(*version); @@ -2200,7 +2275,7 @@ NetworkOPsImp::pubValidation(std::shared_ptr const& val) if (auto hash = (*val)[~sfValidatedHash]) jvObj[jss::validated_hash] = strHex(*hash); - auto const masterKey = app_.validatorManifests().getMasterKey(signerPublic); + auto const masterKey = registry_.validatorManifests().getMasterKey(signerPublic); if (masterKey != signerPublic) jvObj[jss::master_key] = toBase58(TokenType::NodePublic, masterKey); @@ -2237,10 +2312,12 @@ NetworkOPsImp::pubValidation(std::shared_ptr const& val) if (auto const baseFeeXRP = ~val->at(~sfBaseFeeDrops); baseFeeXRP && baseFeeXRP->native()) jvObj[jss::base_fee] = baseFeeXRP->xrp().jsonClipped(); - if (auto const reserveBaseXRP = ~val->at(~sfReserveBaseDrops); reserveBaseXRP && reserveBaseXRP->native()) + if (auto const reserveBaseXRP = ~val->at(~sfReserveBaseDrops); + reserveBaseXRP && reserveBaseXRP->native()) jvObj[jss::reserve_base] = reserveBaseXRP->xrp().jsonClipped(); - if (auto const reserveIncXRP = ~val->at(~sfReserveIncrementDrops); reserveIncXRP && reserveIncXRP->native()) + if (auto const reserveIncXRP = ~val->at(~sfReserveIncrementDrops); + reserveIncXRP && reserveIncXRP->native()) jvObj[jss::reserve_inc] = reserveIncXRP->xrp().jsonClipped(); // NOTE Use MultiApiJson to publish two slightly different JSON objects @@ -2307,12 +2384,12 @@ NetworkOPsImp::setMode(OperatingMode om) using namespace std::chrono_literals; if (om == OperatingMode::CONNECTED) { - if (app_.getLedgerMaster().getValidatedLedgerAge() < 1min) + if (registry_.getLedgerMaster().getValidatedLedgerAge() < 1min) om = OperatingMode::SYNCING; } else if (om == OperatingMode::SYNCING) { - if (app_.getLedgerMaster().getValidatedLedgerAge() >= 1min) + if (registry_.getLedgerMaster().getValidatedLedgerAge() >= 1min) om = OperatingMode::CONNECTED; } @@ -2344,16 +2421,17 @@ NetworkOPsImp::recvValidation(std::shared_ptr const& val, std::str else pendingValidations_.insert(val->getLedgerHash()); scope_unlock unlock(lock); - handleNewValidation(app_, val, source, bypassAccept, m_journal); + handleNewValidation(registry_.app(), val, source, bypassAccept, m_journal); } catch (std::exception const& e) { - JLOG(m_journal.warn()) << "Exception thrown for handling new validation " << val->getLedgerHash() << ": " - << e.what(); + JLOG(m_journal.warn()) << "Exception thrown for handling new validation " + << val->getLedgerHash() << ": " << e.what(); } catch (...) { - JLOG(m_journal.warn()) << "Unknown exception thrown for handling new validation " << val->getLedgerHash(); + JLOG(m_journal.warn()) << "Unknown exception thrown for handling new validation " + << val->getLedgerHash(); } if (bypassAccept == BypassAccept::no) { @@ -2366,7 +2444,7 @@ NetworkOPsImp::recvValidation(std::shared_ptr const& val, std::str JLOG(m_journal.debug()) << [this, &val]() -> auto { std::stringstream ss; ss << "VALIDATION: " << val->render() << " master_key: "; - auto master = app_.validators().getTrustedKey(val->getSignerPublic()); + auto master = registry_.validators().getTrustedKey(val->getSignerPublic()); if (master) { ss << toBase58(TokenType::NodePublic, *master); @@ -2380,7 +2458,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 app_.config().RELAY_UNTRUSTED_VALIDATIONS == 1 || val->isTrusted(); + return registry_.app().config().RELAY_UNTRUSTED_VALIDATIONS == 1 || val->isTrusted(); } Json::Value @@ -2422,7 +2500,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) "One or more unsupported amendments have reached majority. " "Upgrade to the latest version before they are activated " "to avoid being amendment blocked."; - if (auto const expected = app_.getAmendmentTable().firstUnsupportedExpected()) + if (auto const expected = registry_.getAmendmentTable().firstUnsupportedExpected()) { auto& d = w[jss::details] = Json::objectValue; d[jss::expected_date] = expected->time_since_epoch().count(); @@ -2439,23 +2517,24 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) info[jss::hostid] = getHostId(admin); // domain: if configured with a domain, report it: - if (!app_.config().SERVER_DOMAIN.empty()) - info[jss::server_domain] = app_.config().SERVER_DOMAIN; + if (!registry_.app().config().SERVER_DOMAIN.empty()) + info[jss::server_domain] = registry_.app().config().SERVER_DOMAIN; info[jss::build_version] = BuildInfo::getVersionString(); info[jss::server_state] = strOperatingMode(admin); - info[jss::time] = to_string(std::chrono::floor(std::chrono::system_clock::now())); + info[jss::time] = + to_string(std::chrono::floor(std::chrono::system_clock::now())); if (needNetworkLedger_) info[jss::network_ledger] = "waiting"; - info[jss::validation_quorum] = static_cast(app_.validators().quorum()); + info[jss::validation_quorum] = static_cast(registry_.validators().quorum()); if (admin) { - switch (app_.config().NODE_SIZE) + switch (registry_.app().config().NODE_SIZE) { case 0: info[jss::node_size] = "tiny"; @@ -2474,12 +2553,13 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) break; } - auto when = app_.validators().expires(); + auto when = registry_.validators().expires(); if (!human) { if (when) - info[jss::validator_list_expires] = safe_cast(when->time_since_epoch().count()); + info[jss::validator_list_expires] = + safe_cast(when->time_since_epoch().count()); else info[jss::validator_list_expires] = 0; } @@ -2487,7 +2567,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) { auto& x = (info[jss::validator_list] = Json::objectValue); - x[jss::count] = static_cast(app_.validators().count()); + x[jss::count] = static_cast(registry_.validators().count()); if (when) { @@ -2500,7 +2580,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) { x[jss::expiration] = to_string(*when); - if (*when > app_.timeKeeper().now()) + if (*when > registry_.timeKeeper().now()) x[jss::status] = "active"; else x[jss::status] = "expired"; @@ -2525,11 +2605,12 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) } #endif } - info[jss::io_latency_ms] = static_cast(app_.getIOLatency().count()); + info[jss::io_latency_ms] = static_cast(registry_.app().getIOLatency().count()); if (admin) { - if (auto const localPubKey = app_.validators().localPublicKey(); localPubKey && app_.getValidationPublicKey()) + if (auto const localPubKey = registry_.validators().localPublicKey(); + localPubKey && registry_.app().getValidationPublicKey()) { info[jss::pubkey_validator] = toBase58(TokenType::NodePublic, localPubKey.value()); } @@ -2541,17 +2622,17 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (counters) { - info[jss::counters] = app_.getPerfLog().countersJson(); + info[jss::counters] = registry_.getPerfLog().countersJson(); Json::Value nodestore(Json::objectValue); - app_.getNodeStore().getCountsJson(nodestore); + registry_.getNodeStore().getCountsJson(nodestore); info[jss::counters][jss::nodestore] = nodestore; - info[jss::current_activities] = app_.getPerfLog().currentJson(); + info[jss::current_activities] = registry_.getPerfLog().currentJson(); } - info[jss::pubkey_node] = toBase58(TokenType::NodePublic, app_.nodeIdentity().first); + info[jss::pubkey_node] = toBase58(TokenType::NodePublic, registry_.app().nodeIdentity().first); - info[jss::complete_ledgers] = app_.getLedgerMaster().getCompleteLedgers(); + info[jss::complete_ledgers] = registry_.getLedgerMaster().getCompleteLedgers(); if (amendmentBlocked_) info[jss::amendment_blocked] = true; @@ -2561,14 +2642,15 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (fp != 0) info[jss::fetch_pack] = Json::UInt(fp); - info[jss::peers] = Json::UInt(app_.overlay().size()); + info[jss::peers] = Json::UInt(registry_.overlay().size()); Json::Value lastClose = Json::objectValue; lastClose[jss::proposers] = Json::UInt(mConsensus.prevProposers()); if (human) { - lastClose[jss::converge_time_s] = std::chrono::duration{mConsensus.prevRoundTime()}.count(); + lastClose[jss::converge_time_s] = + std::chrono::duration{mConsensus.prevRoundTime()}.count(); } else { @@ -2582,21 +2664,24 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (admin) info[jss::load] = m_job_queue.getJson(); - if (auto const netid = app_.overlay().networkID()) + if (auto const netid = registry_.overlay().networkID()) info[jss::network_id] = static_cast(*netid); - auto const escalationMetrics = app_.getTxQ().getMetrics(*app_.openLedger().current()); + auto const escalationMetrics = registry_.getTxQ().getMetrics(*registry_.openLedger().current()); - auto const loadFactorServer = app_.getFeeTrack().getLoadFactor(); - auto const loadBaseServer = app_.getFeeTrack().getLoadBase(); + auto const loadFactorServer = registry_.getFeeTrack().getLoadFactor(); + auto const loadBaseServer = registry_.getFeeTrack().getLoadBase(); /* Scale the escalated fee level to unitless "load factor". In practice, this just strips the units, but it will continue to work correctly if either base value ever changes. */ - auto const loadFactorFeeEscalation = - mulDiv(escalationMetrics.openLedgerFeeLevel, loadBaseServer, escalationMetrics.referenceFeeLevel) - .value_or(xrpl::muldiv_max); + auto const loadFactorFeeEscalation = mulDiv( + escalationMetrics.openLedgerFeeLevel, + loadBaseServer, + escalationMetrics.referenceFeeLevel) + .value_or(xrpl::muldiv_max); - auto const loadFactor = std::max(safe_cast(loadFactorServer), loadFactorFeeEscalation); + auto const loadFactor = + std::max(safe_cast(loadFactorServer), loadFactorFeeEscalation); if (!human) { @@ -2622,23 +2707,25 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (admin) { - std::uint32_t fee = app_.getFeeTrack().getLocalFee(); + std::uint32_t fee = registry_.getFeeTrack().getLocalFee(); if (fee != loadBaseServer) info[jss::load_factor_local] = static_cast(fee) / loadBaseServer; - fee = app_.getFeeTrack().getRemoteFee(); + fee = registry_.getFeeTrack().getRemoteFee(); if (fee != loadBaseServer) info[jss::load_factor_net] = static_cast(fee) / loadBaseServer; - fee = app_.getFeeTrack().getClusterFee(); + fee = registry_.getFeeTrack().getClusterFee(); if (fee != loadBaseServer) info[jss::load_factor_cluster] = static_cast(fee) / loadBaseServer; } if (escalationMetrics.openLedgerFeeLevel != escalationMetrics.referenceFeeLevel && (admin || loadFactorFeeEscalation != loadFactor)) info[jss::load_factor_fee_escalation] = - escalationMetrics.openLedgerFeeLevel.decimalFromReference(escalationMetrics.referenceFeeLevel); + escalationMetrics.openLedgerFeeLevel.decimalFromReference( + escalationMetrics.referenceFeeLevel); if (escalationMetrics.minProcessingFeeLevel != escalationMetrics.referenceFeeLevel) info[jss::load_factor_fee_queue] = - escalationMetrics.minProcessingFeeLevel.decimalFromReference(escalationMetrics.referenceFeeLevel); + escalationMetrics.minProcessingFeeLevel.decimalFromReference( + escalationMetrics.referenceFeeLevel); } bool valid = false; @@ -2661,7 +2748,8 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) l[jss::base_fee] = baseFee.jsonClipped(); l[jss::reserve_base] = lpClosed->fees().reserve.jsonClipped(); l[jss::reserve_inc] = lpClosed->fees().increment.jsonClipped(); - l[jss::close_time] = Json::Value::UInt(lpClosed->header().closeTime.time_since_epoch().count()); + l[jss::close_time] = + Json::Value::UInt(lpClosed->header().closeTime.time_since_epoch().count()); } else { @@ -2669,7 +2757,8 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) l[jss::reserve_base_xrp] = lpClosed->fees().reserve.decimalXRP(); l[jss::reserve_inc_xrp] = lpClosed->fees().increment.decimalXRP(); - if (auto const closeOffset = app_.timeKeeper().closeOffset(); std::abs(closeOffset.count()) >= 60) + if (auto const closeOffset = registry_.timeKeeper().closeOffset(); + std::abs(closeOffset.count()) >= 60) l[jss::close_time_offset] = static_cast(closeOffset.count()); constexpr std::chrono::seconds highAgeThreshold{1000000}; @@ -2681,7 +2770,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) else { auto lCloseTime = lpClosed->header().closeTime; - auto closeTime = app_.timeKeeper().closeTime(); + auto closeTime = registry_.timeKeeper().closeTime(); if (lCloseTime <= closeTime) { using namespace std::chrono_literals; @@ -2705,21 +2794,23 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) accounting_.json(info); info[jss::uptime] = UptimeClock::now().time_since_epoch().count(); - info[jss::jq_trans_overflow] = std::to_string(app_.overlay().getJqTransOverflow()); - info[jss::peer_disconnects] = std::to_string(app_.overlay().getPeerDisconnect()); - info[jss::peer_disconnects_resources] = std::to_string(app_.overlay().getPeerDisconnectCharges()); + info[jss::jq_trans_overflow] = std::to_string(registry_.overlay().getJqTransOverflow()); + info[jss::peer_disconnects] = std::to_string(registry_.overlay().getPeerDisconnect()); + info[jss::peer_disconnects_resources] = + std::to_string(registry_.overlay().getPeerDisconnectCharges()); // This array must be sorted in increasing order. - static constexpr std::array protocols{"http", "https", "peer", "ws", "ws2", "wss", "wss2"}; + static constexpr std::array protocols{ + "http", "https", "peer", "ws", "ws2", "wss", "wss2"}; static_assert(std::is_sorted(std::begin(protocols), std::end(protocols))); { Json::Value ports{Json::arrayValue}; - for (auto const& port : app_.getServerHandler().setup().ports) + for (auto const& port : registry_.getServerHandler().setup().ports) { // 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.admin_nets_v4.empty() && port.admin_nets_v6.empty() && + port.admin_user.empty() && port.admin_password.empty())) continue; std::vector proto; std::set_intersection( @@ -2738,9 +2829,9 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) } } - if (app_.config().exists(SECTION_PORT_GRPC)) + if (registry_.app().config().exists(SECTION_PORT_GRPC)) { - auto const& grpcSection = app_.config().section(SECTION_PORT_GRPC); + auto const& grpcSection = registry_.app().config().section(SECTION_PORT_GRPC); auto const optPort = grpcSection.get("port"); if (optPort && grpcSection.get("ip")) { @@ -2759,13 +2850,13 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) void NetworkOPsImp::clearLedgerFetch() { - app_.getInboundLedgers().clearFailures(); + registry_.getInboundLedgers().clearFailures(); } Json::Value NetworkOPsImp::getLedgerFetchInfo() { - return app_.getInboundLedgers().getInfo(); + return registry_.getInboundLedgers().getInfo(); } void @@ -2814,17 +2905,22 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) // Ledgers are published only when they acquire sufficient validations // Holes are filled across connection loss or other catastrophe - std::shared_ptr alpAccepted = app_.getAcceptedLedgerCache().fetch(lpAccepted->header().hash); + std::shared_ptr alpAccepted = + registry_.getAcceptedLedgerCache().fetch(lpAccepted->header().hash); if (!alpAccepted) { - alpAccepted = std::make_shared(lpAccepted, app_); - app_.getAcceptedLedgerCache().canonicalize_replace_client(lpAccepted->header().hash, alpAccepted); + alpAccepted = std::make_shared(lpAccepted); + registry_.getAcceptedLedgerCache().canonicalize_replace_client( + lpAccepted->header().hash, alpAccepted); } - XRPL_ASSERT(alpAccepted->getLedger().get() == lpAccepted.get(), "xrpl::NetworkOPsImp::pubLedger : accepted input"); + XRPL_ASSERT( + alpAccepted->getLedger().get() == lpAccepted.get(), + "xrpl::NetworkOPsImp::pubLedger : accepted input"); { - JLOG(m_journal.debug()) << "Publishing ledger " << lpAccepted->header().seq << " " << lpAccepted->header().hash; + JLOG(m_journal.debug()) << "Publishing ledger " << lpAccepted->header().seq << " " + << lpAccepted->header().hash; std::lock_guard sl(mSubLock); @@ -2835,9 +2931,10 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) jvObj[jss::type] = "ledgerClosed"; jvObj[jss::ledger_index] = lpAccepted->header().seq; jvObj[jss::ledger_hash] = to_string(lpAccepted->header().hash); - jvObj[jss::ledger_time] = Json::Value::UInt(lpAccepted->header().closeTime.time_since_epoch().count()); + jvObj[jss::ledger_time] = + Json::Value::UInt(lpAccepted->header().closeTime.time_since_epoch().count()); - jvObj[jss::network_id] = app_.config().NETWORK_ID; + jvObj[jss::network_id] = registry_.getNetworkIDService().getNetworkID(); if (!lpAccepted->rules().enabled(featureXRPFees)) jvObj[jss::fee_ref] = Config::FEE_UNITS_DEPRECATED; @@ -2849,7 +2946,7 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) if (mMode >= OperatingMode::SYNCING) { - jvObj[jss::validated_ledgers] = app_.getLedgerMaster().getCompleteLedgers(); + jvObj[jss::validated_ledgers] = registry_.getLedgerMaster().getCompleteLedgers(); } auto it = mStreamMaps[sLedger].begin(); @@ -2917,9 +3014,9 @@ void NetworkOPsImp::reportFeeChange() { ServerFeeSummary f{ - app_.openLedger().current()->fees().base, - app_.getTxQ().getMetrics(*app_.openLedger().current()), - app_.getFeeTrack()}; + registry_.openLedger().current()->fees().base, + registry_.getTxQ().getMetrics(*registry_.openLedger().current()), + registry_.getFeeTrack()}; // only schedule the job if something has changed if (f != mLastFeeSummary) @@ -2980,11 +3077,12 @@ NetworkOPsImp::transJson( lookup.second && lookup.second->isFieldPresent(sfTransactionIndex)) { uint32_t const txnSeq = lookup.second->getFieldU32(sfTransactionIndex); - uint32_t netID = app_.config().NETWORK_ID; + uint32_t netID = registry_.getNetworkIDService().getNetworkID(); if (transaction->isFieldPresent(sfNetworkID)) netID = transaction->getFieldU32(sfNetworkID); - if (std::optional ctid = RPC::encodeCTID(ledger->header().seq, txnSeq, netID); ctid) + if (std::optional ctid = RPC::encodeCTID(ledger->header().seq, txnSeq, netID); + ctid) jvObj[jss::ctid] = *ctid; } if (!ledger->open()) @@ -3018,7 +3116,8 @@ NetworkOPsImp::transJson( // If the offer create is not self funded then add the owner balance if (account != amount.issue().account) { - auto const ownerFunds = accountFunds(*ledger, account, amount, fhIGNORE_FREEZE, app_.journal("View")); + auto const ownerFunds = + accountFunds(*ledger, account, amount, fhIGNORE_FREEZE, registry_.journal("View")); jvObj[jss::transaction][jss::owner_funds] = ownerFunds.getText(); } } @@ -3095,7 +3194,7 @@ NetworkOPsImp::pubValidatedTransaction( } if (transaction.getResult() == tesSUCCESS) - app_.getOrderBookDB().processTxn(ledger, transaction, jvObj); + registry_.getOrderBookDB().processTxn(ledger, transaction, jvObj); pubAccountTransaction(ledger, transaction, last); } @@ -3119,7 +3218,8 @@ NetworkOPsImp::pubAccountTransaction( { for (auto const& affectedAccount : transaction.getAffected()) { - if (auto simiIt = mSubRTAccount.find(affectedAccount); simiIt != mSubRTAccount.end()) + if (auto simiIt = mSubRTAccount.find(affectedAccount); + simiIt != mSubRTAccount.end()) { auto it = simiIt->second.begin(); @@ -3156,7 +3256,8 @@ NetworkOPsImp::pubAccountTransaction( } } - if (auto historyIt = mSubAccountHistory.find(affectedAccount); historyIt != mSubAccountHistory.end()) + if (auto historyIt = mSubAccountHistory.find(affectedAccount); + historyIt != mSubAccountHistory.end()) { auto& subs = historyIt->second; auto it = subs.begin(); @@ -3171,7 +3272,8 @@ NetworkOPsImp::pubAccountTransaction( if (auto isSptr = info.sinkWptr_.lock(); isSptr) { - accountHistoryNotify.emplace_back(SubAccountHistoryInfo{isSptr, info.index_}); + accountHistoryNotify.emplace_back( + SubAccountHistoryInfo{isSptr, info.index_}); ++it; } else @@ -3248,7 +3350,8 @@ NetworkOPsImp::pubProposedAccountTransaction( { for (auto const& affectedAccount : tx->getMentionedAccounts()) { - if (auto simiIt = mSubRTAccount.find(affectedAccount); simiIt != mSubRTAccount.end()) + if (auto simiIt = mSubRTAccount.find(affectedAccount); + simiIt != mSubRTAccount.end()) { auto it = simiIt->second.begin(); @@ -3304,7 +3407,10 @@ NetworkOPsImp::pubProposedAccountTransaction( // void -NetworkOPsImp::subAccount(InfoSub::ref isrListener, hash_set const& vnaAccountIDs, bool rt) +NetworkOPsImp::subAccount( + InfoSub::ref isrListener, + hash_set const& vnaAccountIDs, + bool rt) { SubInfoMapType& subMap = rt ? mSubRTAccount : mSubAccount; @@ -3337,7 +3443,10 @@ NetworkOPsImp::subAccount(InfoSub::ref isrListener, hash_set const& v } void -NetworkOPsImp::unsubAccount(InfoSub::ref isrListener, hash_set const& vnaAccountIDs, bool rt) +NetworkOPsImp::unsubAccount( + InfoSub::ref isrListener, + hash_set const& vnaAccountIDs, + bool rt) { for (auto const& naAccountID : vnaAccountIDs) { @@ -3350,7 +3459,10 @@ NetworkOPsImp::unsubAccount(InfoSub::ref isrListener, hash_set const& } void -NetworkOPsImp::unsubAccountInternal(std::uint64_t uSeq, hash_set const& vnaAccountIDs, bool rt) +NetworkOPsImp::unsubAccountInternal( + std::uint64_t uSeq, + hash_set const& vnaAccountIDs, + bool rt) { std::lock_guard sl(mSubLock); @@ -3381,7 +3493,7 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) static auto const databaseType = [&]() -> DatabaseType { // Use a dynamic_cast to return DatabaseType::None // on failure. - if (dynamic_cast(&app_.getRelationalDatabase())) + if (dynamic_cast(®istry_.getRelationalDatabase())) { return DatabaseType::Sqlite; } @@ -3392,8 +3504,8 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) { // LCOV_EXCL_START UNREACHABLE("xrpl::NetworkOPsImp::addAccountHistoryJob : no database"); - JLOG(m_journal.error()) << "AccountHistory job for account " << toBase58(subInfo.index_->accountId_) - << " no database"; + JLOG(m_journal.error()) << "AccountHistory job for account " + << toBase58(subInfo.index_->accountId_) << " no database"; if (auto sptr = subInfo.sinkWptr_.lock(); sptr) { sptr->send(rpcError(rpcINTERNAL), true); @@ -3403,244 +3515,262 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) // LCOV_EXCL_STOP } - app_.getJobQueue().addJob(jtCLIENT_ACCT_HIST, "HistTxStream", [this, dbType = databaseType, subInfo]() { - auto const& accountId = subInfo.index_->accountId_; - auto& lastLedgerSeq = subInfo.index_->historyLastLedgerSeq_; - auto& txHistoryIndex = subInfo.index_->historyTxIndex_; + registry_.getJobQueue().addJob( + jtCLIENT_ACCT_HIST, "HistTxStream", [this, dbType = databaseType, subInfo]() { + auto const& accountId = subInfo.index_->accountId_; + auto& lastLedgerSeq = subInfo.index_->historyLastLedgerSeq_; + auto& txHistoryIndex = subInfo.index_->historyTxIndex_; - JLOG(m_journal.trace()) << "AccountHistory job for account " << toBase58(accountId) - << " started. lastLedgerSeq=" << lastLedgerSeq; + JLOG(m_journal.trace()) << "AccountHistory job for account " << toBase58(accountId) + << " started. lastLedgerSeq=" << lastLedgerSeq; - auto isFirstTx = [&](std::shared_ptr const& tx, std::shared_ptr const& meta) -> bool { - /* - * genesis account: first tx is the one with seq 1 - * other account: first tx is the one created the account - */ - if (accountId == genesisAccountId) - { - auto stx = tx->getSTransaction(); - if (stx->getAccountID(sfAccount) == accountId && stx->getSeqValue() == 1) - return true; - } - - for (auto& node : meta->getNodes()) - { - if (node.getFieldU16(sfLedgerEntryType) != ltACCOUNT_ROOT) - continue; - - if (node.isFieldPresent(sfNewFields)) + auto isFirstTx = [&](std::shared_ptr const& tx, + std::shared_ptr const& meta) -> bool { + /* + * genesis account: first tx is the one with seq 1 + * other account: first tx is the one created the account + */ + if (accountId == genesisAccountId) { - if (auto inner = dynamic_cast(node.peekAtPField(sfNewFields)); inner) + auto stx = tx->getSTransaction(); + if (stx->getAccountID(sfAccount) == accountId && stx->getSeqValue() == 1) + return true; + } + + for (auto& node : meta->getNodes()) + { + if (node.getFieldU16(sfLedgerEntryType) != ltACCOUNT_ROOT) + continue; + + if (node.isFieldPresent(sfNewFields)) { - if (inner->isFieldPresent(sfAccount) && inner->getAccountID(sfAccount) == accountId) + if (auto inner = + dynamic_cast(node.peekAtPField(sfNewFields)); + inner) { - return true; + if (inner->isFieldPresent(sfAccount) && + inner->getAccountID(sfAccount) == accountId) + { + return true; + } } } } - } - return false; - }; + return false; + }; - auto send = [&](Json::Value const& jvObj, bool unsubscribe) -> bool { - if (auto sptr = subInfo.sinkWptr_.lock()) - { - sptr->send(jvObj, true); - if (unsubscribe) - unsubAccountHistory(sptr, accountId, false); - return true; - } - - return false; - }; - - auto sendMultiApiJson = [&](MultiApiJson const& jvObj, bool unsubscribe) -> bool { - if (auto sptr = subInfo.sinkWptr_.lock()) - { - jvObj.visit( - sptr->getApiVersion(), // - [&](Json::Value const& jv) { sptr->send(jv, true); }); - - if (unsubscribe) - unsubAccountHistory(sptr, accountId, false); - return true; - } - - return false; - }; - - auto getMoreTxns = [&](std::uint32_t minLedger, - std::uint32_t maxLedger, - std::optional marker) - -> std::optional< - std::pair>> { - switch (dbType) - { - case Sqlite: { - auto db = static_cast(&app_.getRelationalDatabase()); - RelationalDatabase::AccountTxPageOptions options{accountId, minLedger, maxLedger, marker, 0, true}; - return db->newestAccountTxPage(options); - } - // LCOV_EXCL_START - default: { - UNREACHABLE( - "xrpl::NetworkOPsImp::addAccountHistoryJob : " - "getMoreTxns : invalid database type"); - return {}; - } - // LCOV_EXCL_STOP - } - }; - - /* - * search backward until the genesis ledger or asked to stop - */ - while (lastLedgerSeq >= 2 && !subInfo.index_->stopHistorical_) - { - int feeChargeCount = 0; - if (auto sptr = subInfo.sinkWptr_.lock(); sptr) - { - sptr->getConsumer().charge(Resource::feeMediumBurdenRPC); - ++feeChargeCount; - } - else - { - JLOG(m_journal.trace()) << "AccountHistory job for account " << toBase58(accountId) - << " no InfoSub. Fee charged " << feeChargeCount << " times."; - return; - } - - // try to search in 1024 ledgers till reaching genesis ledgers - auto startLedgerSeq = (lastLedgerSeq > 1024 + 2 ? lastLedgerSeq - 1024 : 2); - JLOG(m_journal.trace()) << "AccountHistory job for account " << toBase58(accountId) - << ", working on ledger range [" << startLedgerSeq << "," << lastLedgerSeq << "]"; - - auto haveRange = [&]() -> bool { - std::uint32_t validatedMin = UINT_MAX; - std::uint32_t validatedMax = 0; - auto haveSomeValidatedLedgers = app_.getLedgerMaster().getValidatedRange(validatedMin, validatedMax); - - return haveSomeValidatedLedgers && validatedMin <= startLedgerSeq && lastLedgerSeq <= validatedMax; - }(); - - if (!haveRange) - { - JLOG(m_journal.debug()) << "AccountHistory reschedule job for account " << toBase58(accountId) - << ", incomplete ledger range [" << startLedgerSeq << "," << lastLedgerSeq - << "]"; - setAccountHistoryJobTimer(subInfo); - return; - } - - std::optional marker{}; - while (!subInfo.index_->stopHistorical_) - { - auto dbResult = getMoreTxns(startLedgerSeq, lastLedgerSeq, marker); - if (!dbResult) + auto send = [&](Json::Value const& jvObj, bool unsubscribe) -> bool { + if (auto sptr = subInfo.sinkWptr_.lock()) { - // LCOV_EXCL_START - UNREACHABLE( - "xrpl::NetworkOPsImp::addAccountHistoryJob : " - "getMoreTxns failed"); - JLOG(m_journal.debug()) - << "AccountHistory job for account " << toBase58(accountId) << " getMoreTxns failed."; - send(rpcError(rpcINTERNAL), true); - return; - // LCOV_EXCL_STOP + sptr->send(jvObj, true); + if (unsubscribe) + unsubAccountHistory(sptr, accountId, false); + return true; } - auto const& txns = dbResult->first; - marker = dbResult->second; - size_t num_txns = txns.size(); - for (size_t i = 0; i < num_txns; ++i) - { - auto const& [tx, meta] = txns[i]; + return false; + }; - if (!tx || !meta) - { - JLOG(m_journal.debug()) - << "AccountHistory job for account " << toBase58(accountId) << " empty tx or meta."; - send(rpcError(rpcINTERNAL), true); - return; + auto sendMultiApiJson = [&](MultiApiJson const& jvObj, bool unsubscribe) -> bool { + if (auto sptr = subInfo.sinkWptr_.lock()) + { + jvObj.visit( + sptr->getApiVersion(), // + [&](Json::Value const& jv) { sptr->send(jv, true); }); + + if (unsubscribe) + unsubAccountHistory(sptr, accountId, false); + return true; + } + + return false; + }; + + auto getMoreTxns = [&](std::uint32_t minLedger, + std::uint32_t maxLedger, + std::optional marker) + -> std::optional>> { + switch (dbType) + { + case Sqlite: { + auto db = static_cast(®istry_.getRelationalDatabase()); + RelationalDatabase::AccountTxPageOptions options{ + accountId, minLedger, maxLedger, marker, 0, true}; + return db->newestAccountTxPage(options); } - auto curTxLedger = app_.getLedgerMaster().getLedgerBySeq(tx->getLedger()); - if (!curTxLedger) + // LCOV_EXCL_START + default: { + UNREACHABLE( + "xrpl::NetworkOPsImp::addAccountHistoryJob : " + "getMoreTxns : invalid database type"); + return {}; + } + // LCOV_EXCL_STOP + } + }; + + /* + * search backward until the genesis ledger or asked to stop + */ + while (lastLedgerSeq >= 2 && !subInfo.index_->stopHistorical_) + { + int feeChargeCount = 0; + if (auto sptr = subInfo.sinkWptr_.lock(); sptr) + { + sptr->getConsumer().charge(Resource::feeMediumBurdenRPC); + ++feeChargeCount; + } + else + { + JLOG(m_journal.trace()) + << "AccountHistory job for account " << toBase58(accountId) + << " no InfoSub. Fee charged " << feeChargeCount << " times."; + return; + } + + // try to search in 1024 ledgers till reaching genesis ledgers + auto startLedgerSeq = (lastLedgerSeq > 1024 + 2 ? lastLedgerSeq - 1024 : 2); + JLOG(m_journal.trace()) << "AccountHistory job for account " << toBase58(accountId) + << ", working on ledger range [" << startLedgerSeq << "," + << lastLedgerSeq << "]"; + + auto haveRange = [&]() -> bool { + std::uint32_t validatedMin = UINT_MAX; + std::uint32_t validatedMax = 0; + auto haveSomeValidatedLedgers = + registry_.getLedgerMaster().getValidatedRange(validatedMin, validatedMax); + + return haveSomeValidatedLedgers && validatedMin <= startLedgerSeq && + lastLedgerSeq <= validatedMax; + }(); + + if (!haveRange) + { + JLOG(m_journal.debug()) << "AccountHistory reschedule job for account " + << toBase58(accountId) << ", incomplete ledger range [" + << startLedgerSeq << "," << lastLedgerSeq << "]"; + setAccountHistoryJobTimer(subInfo); + return; + } + + std::optional marker{}; + while (!subInfo.index_->stopHistorical_) + { + auto dbResult = getMoreTxns(startLedgerSeq, lastLedgerSeq, marker); + if (!dbResult) { // LCOV_EXCL_START UNREACHABLE( "xrpl::NetworkOPsImp::addAccountHistoryJob : " - "getLedgerBySeq failed"); - JLOG(m_journal.debug()) - << "AccountHistory job for account " << toBase58(accountId) << " no ledger."; - send(rpcError(rpcINTERNAL), true); - return; - // LCOV_EXCL_STOP - } - std::shared_ptr stTxn = tx->getSTransaction(); - if (!stTxn) - { - // LCOV_EXCL_START - UNREACHABLE( - "NetworkOPsImp::addAccountHistoryJob : " - "getSTransaction failed"); - JLOG(m_journal.debug()) - << "AccountHistory job for account " << toBase58(accountId) << " getSTransaction failed."; + "getMoreTxns failed"); + JLOG(m_journal.debug()) << "AccountHistory job for account " + << toBase58(accountId) << " getMoreTxns failed."; send(rpcError(rpcINTERNAL), true); return; // LCOV_EXCL_STOP } - auto const mRef = std::ref(*meta); - auto const trR = meta->getResultTER(); - MultiApiJson jvTx = transJson(stTxn, trR, true, curTxLedger, mRef); - - jvTx.set(jss::account_history_tx_index, txHistoryIndex--); - if (i + 1 == num_txns || txns[i + 1].first->getLedger() != tx->getLedger()) - jvTx.set(jss::account_history_boundary, true); - - if (isFirstTx(tx, meta)) + auto const& txns = dbResult->first; + marker = dbResult->second; + size_t num_txns = txns.size(); + for (size_t i = 0; i < num_txns; ++i) { - jvTx.set(jss::account_history_tx_first, true); - sendMultiApiJson(jvTx, false); + auto const& [tx, meta] = txns[i]; + if (!tx || !meta) + { + JLOG(m_journal.debug()) << "AccountHistory job for account " + << toBase58(accountId) << " empty tx or meta."; + send(rpcError(rpcINTERNAL), true); + return; + } + auto curTxLedger = + registry_.getLedgerMaster().getLedgerBySeq(tx->getLedger()); + if (!curTxLedger) + { + // LCOV_EXCL_START + UNREACHABLE( + "xrpl::NetworkOPsImp::addAccountHistoryJob : " + "getLedgerBySeq failed"); + JLOG(m_journal.debug()) << "AccountHistory job for account " + << toBase58(accountId) << " no ledger."; + send(rpcError(rpcINTERNAL), true); + return; + // LCOV_EXCL_STOP + } + std::shared_ptr stTxn = tx->getSTransaction(); + if (!stTxn) + { + // LCOV_EXCL_START + UNREACHABLE( + "NetworkOPsImp::addAccountHistoryJob : " + "getSTransaction failed"); + JLOG(m_journal.debug()) + << "AccountHistory job for account " << toBase58(accountId) + << " getSTransaction failed."; + send(rpcError(rpcINTERNAL), true); + return; + // LCOV_EXCL_STOP + } + + auto const mRef = std::ref(*meta); + auto const trR = meta->getResultTER(); + MultiApiJson jvTx = transJson(stTxn, trR, true, curTxLedger, mRef); + + jvTx.set(jss::account_history_tx_index, txHistoryIndex--); + if (i + 1 == num_txns || txns[i + 1].first->getLedger() != tx->getLedger()) + jvTx.set(jss::account_history_boundary, true); + + if (isFirstTx(tx, meta)) + { + jvTx.set(jss::account_history_tx_first, true); + sendMultiApiJson(jvTx, false); + + JLOG(m_journal.trace()) + << "AccountHistory job for account " << toBase58(accountId) + << " done, found last tx."; + return; + } + else + { + sendMultiApiJson(jvTx, false); + } + } + + if (marker) + { JLOG(m_journal.trace()) - << "AccountHistory job for account " << toBase58(accountId) << " done, found last tx."; - return; + << "AccountHistory job for account " << toBase58(accountId) + << " paging, marker=" << marker->ledgerSeq << ":" << marker->txnSeq; } else { - sendMultiApiJson(jvTx, false); + break; } } - if (marker) + if (!subInfo.index_->stopHistorical_) { - JLOG(m_journal.trace()) << "AccountHistory job for account " << toBase58(accountId) - << " paging, marker=" << marker->ledgerSeq << ":" << marker->txnSeq; - } - else - { - break; + lastLedgerSeq = startLedgerSeq - 1; + if (lastLedgerSeq <= 1) + { + JLOG(m_journal.trace()) + << "AccountHistory job for account " << toBase58(accountId) + << " done, reached genesis ledger."; + return; + } } } - - if (!subInfo.index_->stopHistorical_) - { - lastLedgerSeq = startLedgerSeq - 1; - if (lastLedgerSeq <= 1) - { - JLOG(m_journal.trace()) - << "AccountHistory job for account " << toBase58(accountId) << " done, reached genesis ledger."; - return; - } - } - } - }); + }); } void -NetworkOPsImp::subAccountHistoryStart(std::shared_ptr const& ledger, SubAccountHistoryInfoWeak& subInfo) +NetworkOPsImp::subAccountHistoryStart( + std::shared_ptr const& ledger, + SubAccountHistoryInfoWeak& subInfo) { subInfo.index_->separationLedgerSeq_ = ledger->seq(); auto const& accountId = subInfo.index_->accountId_; @@ -3657,8 +3787,9 @@ NetworkOPsImp::subAccountHistoryStart(std::shared_ptr const& led { if (sleAcct->getFieldU32(sfSequence) == 1) { - JLOG(m_journal.debug()) << "subAccountHistoryStart, genesis account " << toBase58(accountId) - << " does not have tx, no need to add AccountHistory job."; + JLOG(m_journal.debug()) + << "subAccountHistoryStart, genesis account " << toBase58(accountId) + << " does not have tx, no need to add AccountHistory job."; return; } } @@ -3675,8 +3806,8 @@ NetworkOPsImp::subAccountHistoryStart(std::shared_ptr const& led subInfo.index_->historyLastLedgerSeq_ = ledger->seq(); subInfo.index_->haveHistorical_ = true; - JLOG(m_journal.debug()) << "subAccountHistoryStart, add AccountHistory job: accountId=" << toBase58(accountId) - << ", currentLedgerSeq=" << ledger->seq(); + JLOG(m_journal.debug()) << "subAccountHistoryStart, add AccountHistory job: accountId=" + << toBase58(accountId) << ", currentLedgerSeq=" << ledger->seq(); addAccountHistoryJob(subInfo); } @@ -3686,7 +3817,8 @@ NetworkOPsImp::subAccountHistory(InfoSub::ref isrListener, AccountID const& acco { if (!isrListener->insertSubAccountHistory(accountId)) { - JLOG(m_journal.debug()) << "subAccountHistory, already subscribed to account " << toBase58(accountId); + JLOG(m_journal.debug()) << "subAccountHistory, already subscribed to account " + << toBase58(accountId); return rpcINVALID_PARAMS; } @@ -3704,7 +3836,7 @@ NetworkOPsImp::subAccountHistory(InfoSub::ref isrListener, AccountID const& acco simIterator->second.emplace(isrListener->getSeq(), ahi); } - auto const ledger = app_.getLedgerMaster().getValidatedLedger(); + auto const ledger = registry_.getLedgerMaster().getValidatedLedger(); if (ledger) { subAccountHistoryStart(ledger, ahi); @@ -3721,7 +3853,10 @@ NetworkOPsImp::subAccountHistory(InfoSub::ref isrListener, AccountID const& acco } void -NetworkOPsImp::unsubAccountHistory(InfoSub::ref isrListener, AccountID const& account, bool historyOnly) +NetworkOPsImp::unsubAccountHistory( + InfoSub::ref isrListener, + AccountID const& account, + bool historyOnly) { if (!historyOnly) isrListener->deleteSubAccountHistory(account); @@ -3729,7 +3864,10 @@ NetworkOPsImp::unsubAccountHistory(InfoSub::ref isrListener, AccountID const& ac } void -NetworkOPsImp::unsubAccountHistoryInternal(std::uint64_t seq, AccountID const& account, bool historyOnly) +NetworkOPsImp::unsubAccountHistoryInternal( + std::uint64_t seq, + AccountID const& account, + bool historyOnly) { std::lock_guard sl(mSubLock); auto simIterator = mSubAccountHistory.find(account); @@ -3758,7 +3896,7 @@ NetworkOPsImp::unsubAccountHistoryInternal(std::uint64_t seq, AccountID const& a bool NetworkOPsImp::subBook(InfoSub::ref isrListener, Book const& book) { - if (auto listeners = app_.getOrderBookDB().makeBookListeners(book)) + if (auto listeners = registry_.getOrderBookDB().makeBookListeners(book)) listeners->addSubscriber(isrListener); else { @@ -3772,7 +3910,7 @@ NetworkOPsImp::subBook(InfoSub::ref isrListener, Book const& book) bool NetworkOPsImp::unsubBook(std::uint64_t uSeq, Book const& book) { - if (auto listeners = app_.getOrderBookDB().getBookListeners(book)) + if (auto listeners = registry_.getOrderBookDB().getBookListeners(book)) listeners->removeSubscriber(uSeq); return true; @@ -3791,7 +3929,7 @@ NetworkOPsImp::acceptLedger(std::optional consensusDe // FIXME Could we improve on this and remove the need for a specialized // API in Consensus? beginConsensus(m_ledgerMaster.getClosedLedger()->header().hash, {}); - mConsensus.simulate(app_.timeKeeper().closeTime(), consensusDelay); + mConsensus.simulate(registry_.timeKeeper().closeTime(), consensusDelay); return m_ledgerMaster.getCurrentLedger()->header().seq; } @@ -3803,18 +3941,19 @@ NetworkOPsImp::subLedger(InfoSub::ref isrListener, Json::Value& jvResult) { jvResult[jss::ledger_index] = lpClosed->header().seq; jvResult[jss::ledger_hash] = to_string(lpClosed->header().hash); - jvResult[jss::ledger_time] = Json::Value::UInt(lpClosed->header().closeTime.time_since_epoch().count()); + jvResult[jss::ledger_time] = + Json::Value::UInt(lpClosed->header().closeTime.time_since_epoch().count()); if (!lpClosed->rules().enabled(featureXRPFees)) jvResult[jss::fee_ref] = Config::FEE_UNITS_DEPRECATED; jvResult[jss::fee_base] = lpClosed->fees().base.jsonClipped(); jvResult[jss::reserve_base] = lpClosed->fees().reserve.jsonClipped(); jvResult[jss::reserve_inc] = lpClosed->fees().increment.jsonClipped(); - jvResult[jss::network_id] = app_.config().NETWORK_ID; + jvResult[jss::network_id] = registry_.getNetworkIDService().getNetworkID(); } if ((mMode >= OperatingMode::SYNCING) && !isNeedNetworkLedger()) { - jvResult[jss::validated_ledgers] = app_.getLedgerMaster().getCompleteLedgers(); + jvResult[jss::validated_ledgers] = registry_.getLedgerMaster().getCompleteLedgers(); } std::lock_guard sl(mSubLock); @@ -3873,13 +4012,14 @@ NetworkOPsImp::subServer(InfoSub::ref isrListener, Json::Value& jvResult, bool a // CHECKME: is it necessary to provide a random number here? beast::rngfill(uRandom.begin(), uRandom.size(), crypto_prng()); - auto const& feeTrack = app_.getFeeTrack(); + auto const& feeTrack = registry_.getFeeTrack(); jvResult[jss::random] = to_string(uRandom); jvResult[jss::server_status] = strOperatingMode(admin); jvResult[jss::load_base] = feeTrack.getLoadBase(); jvResult[jss::load_factor] = feeTrack.getLoadFactor(); jvResult[jss::hostid] = getHostId(admin); - jvResult[jss::pubkey_node] = toBase58(TokenType::NodePublic, app_.nodeIdentity().first); + jvResult[jss::pubkey_node] = + toBase58(TokenType::NodePublic, registry_.app().nodeIdentity().first); std::lock_guard sl(mSubLock); return mStreamMaps[sServer].emplace(isrListener->getSeq(), isrListener).second; @@ -4054,7 +4194,8 @@ NetworkOPsImp::getBookPage( ReadView const& view = *lpLedger; - bool const bGlobalFreeze = isGlobalFrozen(view, book.out.account) || isGlobalFrozen(view, book.in.account); + bool const bGlobalFreeze = + isGlobalFrozen(view, book.out.account) || isGlobalFrozen(view, book.in.account); bool bDone = false; bool bDirectAdvance = true; @@ -4065,7 +4206,7 @@ NetworkOPsImp::getBookPage( STAmount saDirRate; auto const rate = transferRate(view, book.out.account); - auto viewJ = app_.journal("View"); + auto viewJ = registry_.journal("View"); while (!bDone && iLimit-- > 0) { @@ -4137,7 +4278,12 @@ NetworkOPsImp::getBookPage( // Did not find balance in table. saOwnerFunds = accountHolds( - view, uOfferOwnerID, book.out.currency, book.out.account, fhZERO_IF_FROZEN, viewJ); + view, + uOfferOwnerID, + book.out.currency, + book.out.account, + fhZERO_IF_FROZEN, + viewJ); if (saOwnerFunds < beast::zero) { @@ -4178,7 +4324,8 @@ NetworkOPsImp::getBookPage( saTakerGetsFunded = saOwnerFundsLimit; saTakerGetsFunded.setJson(jvOffer[jss::taker_gets_funded]); - std::min(saTakerPays, multiply(saTakerGetsFunded, saDirRate, saTakerPays.issue())) + std::min( + saTakerPays, multiply(saTakerGetsFunded, saDirRate, saTakerPays.issue())) .setJson(jvOffer[jss::taker_pays_funded]); } @@ -4239,7 +4386,8 @@ NetworkOPsImp::getBookPage( auto const rate = transferRate(lesActive, book.out.account); - bool const bGlobalFreeze = lesActive.isGlobalFrozen(book.out.account) || lesActive.isGlobalFrozen(book.in.account); + bool const bGlobalFreeze = + lesActive.isGlobalFrozen(book.out.account) || lesActive.isGlobalFrozen(book.in.account); while (iLimit-- > 0 && obIterator.nextOffer()) { @@ -4277,8 +4425,8 @@ NetworkOPsImp::getBookPage( { // Did not find balance in table. - saOwnerFunds = - lesActive.accountHolds(uOfferOwnerID, book.out.currency, book.out.account, fhZERO_IF_FROZEN); + saOwnerFunds = lesActive.accountHolds( + uOfferOwnerID, book.out.currency, book.out.account, fhZERO_IF_FROZEN); if (saOwnerFunds.isNegative()) { @@ -4350,22 +4498,31 @@ inline void NetworkOPsImp::collect_metrics() { auto [counters, mode, start, initialSync] = accounting_.getCounterData(); - auto const current = - std::chrono::duration_cast(std::chrono::steady_clock::now() - start); + auto const current = std::chrono::duration_cast( + std::chrono::steady_clock::now() - start); counters[static_cast(mode)].dur += current; std::lock_guard lock(m_statsMutex); - m_stats.disconnected_duration.set(counters[static_cast(OperatingMode::DISCONNECTED)].dur.count()); - m_stats.connected_duration.set(counters[static_cast(OperatingMode::CONNECTED)].dur.count()); - m_stats.syncing_duration.set(counters[static_cast(OperatingMode::SYNCING)].dur.count()); - m_stats.tracking_duration.set(counters[static_cast(OperatingMode::TRACKING)].dur.count()); + m_stats.disconnected_duration.set( + counters[static_cast(OperatingMode::DISCONNECTED)].dur.count()); + m_stats.connected_duration.set( + counters[static_cast(OperatingMode::CONNECTED)].dur.count()); + m_stats.syncing_duration.set( + counters[static_cast(OperatingMode::SYNCING)].dur.count()); + m_stats.tracking_duration.set( + counters[static_cast(OperatingMode::TRACKING)].dur.count()); m_stats.full_duration.set(counters[static_cast(OperatingMode::FULL)].dur.count()); - m_stats.disconnected_transitions.set(counters[static_cast(OperatingMode::DISCONNECTED)].transitions); - m_stats.connected_transitions.set(counters[static_cast(OperatingMode::CONNECTED)].transitions); - m_stats.syncing_transitions.set(counters[static_cast(OperatingMode::SYNCING)].transitions); - m_stats.tracking_transitions.set(counters[static_cast(OperatingMode::TRACKING)].transitions); - m_stats.full_transitions.set(counters[static_cast(OperatingMode::FULL)].transitions); + m_stats.disconnected_transitions.set( + counters[static_cast(OperatingMode::DISCONNECTED)].transitions); + m_stats.connected_transitions.set( + counters[static_cast(OperatingMode::CONNECTED)].transitions); + m_stats.syncing_transitions.set( + counters[static_cast(OperatingMode::SYNCING)].transitions); + m_stats.tracking_transitions.set( + counters[static_cast(OperatingMode::TRACKING)].transitions); + m_stats.full_transitions.set( + counters[static_cast(OperatingMode::FULL)].transitions); } void @@ -4377,7 +4534,8 @@ NetworkOPsImp::StateAccounting::mode(OperatingMode om) ++counters_[static_cast(om)].transitions; if (om == OperatingMode::FULL && counters_[static_cast(om)].transitions == 1) { - initialSyncUs_ = std::chrono::duration_cast(now - processStart_).count(); + initialSyncUs_ = + std::chrono::duration_cast(now - processStart_).count(); } counters_[static_cast(mode_)].dur += std::chrono::duration_cast(now - start_); @@ -4390,8 +4548,8 @@ void NetworkOPsImp::StateAccounting::json(Json::Value& obj) const { auto [counters, mode, start, initialSync] = getCounterData(); - auto const current = - std::chrono::duration_cast(std::chrono::steady_clock::now() - start); + auto const current = std::chrono::duration_cast( + std::chrono::steady_clock::now() - start); counters[static_cast(mode)].dur += current; obj[jss::state_accounting] = Json::objectValue; @@ -4413,7 +4571,7 @@ NetworkOPsImp::StateAccounting::json(Json::Value& obj) const std::unique_ptr make_NetworkOPs( - Application& app, + ServiceRegistry& registry, NetworkOPs::clock_type& clock, bool standalone, std::size_t minPeerCount, @@ -4426,7 +4584,7 @@ make_NetworkOPs( beast::insight::Collector::ptr const& collector) { return std::make_unique( - app, + registry, clock, standalone, minPeerCount, diff --git a/src/xrpld/app/misc/SHAMapStoreImp.cpp b/src/xrpld/app/misc/SHAMapStoreImp.cpp index c963d18d2c..47e9f0ef52 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.cpp +++ b/src/xrpld/app/misc/SHAMapStoreImp.cpp @@ -1,5 +1,4 @@ #include -#include #include #include #include @@ -7,6 +6,7 @@ #include #include #include +#include #include #include @@ -60,7 +60,10 @@ SHAMapStoreImp::SavedStateDB::setLastRotated(LedgerIndex seq) //------------------------------------------------------------------------------ -SHAMapStoreImp::SHAMapStoreImp(Application& app, NodeStore::Scheduler& scheduler, beast::Journal journal) +SHAMapStoreImp::SHAMapStoreImp( + Application& app, + NodeStore::Scheduler& scheduler, + beast::Journal journal) : app_(app) , scheduler_(scheduler) , journal_(journal) @@ -72,7 +75,8 @@ SHAMapStoreImp::SHAMapStoreImp(Application& app, NodeStore::Scheduler& scheduler Section& section{config.section(ConfigSection::nodeDatabase())}; if (section.empty()) { - Throw("Missing [" + ConfigSection::nodeDatabase() + "] entry in configuration file"); + Throw( + "Missing [" + ConfigSection::nodeDatabase() + "] entry in configuration file"); } // RocksDB only. Use sensible defaults if no values specified. @@ -107,10 +111,12 @@ SHAMapStoreImp::SHAMapStoreImp(Application& app, NodeStore::Scheduler& scheduler get_if_exists(section, "advisory_delete", advisoryDelete_); - auto const minInterval = config.standalone() ? minimumDeletionIntervalSA_ : minimumDeletionInterval_; + auto const minInterval = + config.standalone() ? minimumDeletionIntervalSA_ : minimumDeletionInterval_; if (deleteInterval_ < minInterval) { - Throw("online_delete must be at least " + std::to_string(minInterval)); + Throw( + "online_delete must be at least " + std::to_string(minInterval)); } if (config.LEDGER_HISTORY > deleteInterval_) @@ -201,7 +207,8 @@ bool SHAMapStoreImp::copyNode(std::uint64_t& nodeCount, SHAMapTreeNode const& node) { // Copy a single record from node to dbRotating_ - dbRotating_->fetchNodeObject(node.getHash().as_uint256(), 0, NodeStore::FetchType::synchronous, true); + dbRotating_->fetchNodeObject( + node.getHash().as_uint256(), 0, NodeStore::FetchType::synchronous, true); if (!(++nodeCount % checkHealthInterval_)) { if (healthWait() == stopping) @@ -251,14 +258,15 @@ SHAMapStoreImp::run() state_db_.setLastRotated(lastRotated); } - bool const readyToRotate = - validatedSeq >= lastRotated + deleteInterval_ && canDelete_ >= lastRotated - 1 && healthWait() == keepGoing; + bool const readyToRotate = validatedSeq >= lastRotated + deleteInterval_ && + canDelete_ >= lastRotated - 1 && healthWait() == keepGoing; // will delete up to (not including) lastRotated if (readyToRotate) { - JLOG(journal_.warn()) << "rotating validatedSeq " << validatedSeq << " lastRotated " << lastRotated - << " deleteInterval " << deleteInterval_ << " canDelete_ " << canDelete_ << " state " + JLOG(journal_.warn()) << "rotating validatedSeq " << validatedSeq << " lastRotated " + << lastRotated << " deleteInterval " << deleteInterval_ + << " canDelete_ " << canDelete_ << " state " << app_.getOPs().strOperatingMode(false) << " age " << ledgerMaster_->getValidatedLedgerAge().count() << 's'; @@ -272,18 +280,24 @@ SHAMapStoreImp::run() try { validatedLedger->stateMap().snapShot(false)->visitNodes( - std::bind(&SHAMapStoreImp::copyNode, this, std::ref(nodeCount), std::placeholders::_1)); + std::bind( + &SHAMapStoreImp::copyNode, + this, + std::ref(nodeCount), + std::placeholders::_1)); } catch (SHAMapMissingNode const& e) { - JLOG(journal_.error()) << "Missing node while copying ledger before rotate: " << e.what(); + JLOG(journal_.error()) + << "Missing node while copying ledger before rotate: " << e.what(); continue; } if (healthWait() == stopping) return; // Only log if we completed without a "health" abort - JLOG(journal_.debug()) << "copied ledger " << validatedSeq << " nodecount " << nodeCount; + JLOG(journal_.debug()) + << "copied ledger " << validatedSeq << " nodecount " << nodeCount; JLOG(journal_.debug()) << "freshening caches"; freshenCaches(); @@ -303,7 +317,8 @@ SHAMapStoreImp::run() lastRotated = validatedSeq; dbRotating_->rotate( - std::move(newBackend), [&](std::string const& writableName, std::string const& archiveName) { + std::move(newBackend), + [&](std::string const& writableName, std::string const& archiveName) { SavedState savedState; savedState.writableDb = writableName; savedState.archiveDb = archiveName; @@ -365,7 +380,9 @@ SHAMapStoreImp::dbPaths() bool archiveDbExists = false; std::vector pathsToDelete; - for (boost::filesystem::directory_iterator it(dbPath); it != boost::filesystem::directory_iterator(); ++it) + for (boost::filesystem::directory_iterator it(dbPath); + it != boost::filesystem::directory_iterator(); + ++it) { if (!state.writableDb.compare(it->path().string())) writableDbExists = true; @@ -375,19 +392,23 @@ SHAMapStoreImp::dbPaths() pathsToDelete.push_back(it->path()); } - if ((!writableDbExists && state.writableDb.size()) || (!archiveDbExists && state.archiveDb.size()) || - (writableDbExists != archiveDbExists) || state.writableDb.empty() != state.archiveDb.empty()) + if ((!writableDbExists && state.writableDb.size()) || + (!archiveDbExists && state.archiveDb.size()) || (writableDbExists != archiveDbExists) || + state.writableDb.empty() != state.archiveDb.empty()) { boost::filesystem::path stateDbPathName = app_.config().legacy("database_path"); stateDbPathName /= dbName_; stateDbPathName += "*"; journal_.error() << "state db error:\n" - << " writableDbExists " << writableDbExists << " archiveDbExists " << archiveDbExists << '\n' - << " writableDb '" << state.writableDb << "' archiveDb '" << state.archiveDb << "\n\n" + << " writableDbExists " << writableDbExists << " archiveDbExists " + << archiveDbExists << '\n' + << " writableDb '" << state.writableDb << "' archiveDb '" + << state.archiveDb << "\n\n" << "The existing data is in a corrupted state.\n" - << "To resume operation, remove the files matching " << stateDbPathName.string() - << " and contents of the directory " << get(section, "path") << '\n' + << "To resume operation, remove the files matching " + << stateDbPathName.string() << " and contents of the directory " + << get(section, "path") << '\n' << "Optionally, you can move those files to another\n" << "location if you wish to analyze or back up the data.\n" << "However, there is no guarantee that the data in its\n" @@ -457,15 +478,16 @@ SHAMapStoreImp::clearSql( return; } - JLOG(journal_.debug()) << "start deleting in: " << TableName << " from " << min << " to " << lastRotated; + JLOG(journal_.debug()) << "start deleting in: " << TableName << " from " << min << " to " + << lastRotated; while (min < lastRotated) { min = std::min(lastRotated, min + deleteBatch_); - JLOG(journal_.trace()) << "Begin: Delete up to " << deleteBatch_ << " rows with LedgerSeq < " << min - << " from: " << TableName; + JLOG(journal_.trace()) << "Begin: Delete up to " << deleteBatch_ + << " rows with LedgerSeq < " << min << " from: " << TableName; deleteBeforeSeq(min); - JLOG(journal_.trace()) << "End: Delete up to " << deleteBatch_ << " rows with LedgerSeq < " << min - << " from: " << TableName; + JLOG(journal_.trace()) << "End: Delete up to " << deleteBatch_ << " rows with LedgerSeq < " + << min << " from: " << TableName; if (healthWait() == stopping) return; if (min < lastRotated) @@ -547,8 +569,9 @@ SHAMapStoreImp::healthWait() { lock.unlock(); JLOG(journal_.warn()) << "Waiting " << recoveryWaitTime_.count() - << "s for node to stabilize. state: " << app_.getOPs().strOperatingMode(mode, false) - << ". age " << age.count() << 's'; + << "s for node to stabilize. state: " + << app_.getOPs().strOperatingMode(mode, false) << ". age " + << age.count() << 's'; std::this_thread::sleep_for(recoveryWaitTime_); age = ledgerMaster_->getValidatedLedgerAge(); mode = netOPs_->getOperatingMode(); diff --git a/src/xrpld/app/misc/Transaction.h b/src/xrpld/app/misc/Transaction.h index 0a51e1c021..fa126e6bb5 100644 --- a/src/xrpld/app/misc/Transaction.h +++ b/src/xrpld/app/misc/Transaction.h @@ -38,7 +38,8 @@ enum TransStatus { // This class is for constructing and examining transactions. // Transactions are static so manipulation functions are unnecessary. -class Transaction : public std::enable_shared_from_this, public CountedObject +class Transaction : public std::enable_shared_from_this, + public CountedObject { public: using pointer = std::shared_ptr; @@ -245,8 +246,15 @@ public: { CurrentLedgerState() = delete; - CurrentLedgerState(LedgerIndex li, XRPAmount fee, std::uint32_t accSeqNext, std::uint32_t accSeqAvail) - : validatedLedger{li}, minFeeRequired{fee}, accountSeqNext{accSeqNext}, accountSeqAvail{accSeqAvail} + CurrentLedgerState( + LedgerIndex li, + XRPAmount fee, + std::uint32_t accSeqNext, + std::uint32_t accSeqAvail) + : validatedLedger{li} + , minFeeRequired{fee} + , accountSeqNext{accSeqNext} + , accountSeqAvail{accSeqAvail} { } @@ -336,15 +344,26 @@ public: static Locator locate(uint256 const& id, Application& app); - static std::variant, std::shared_ptr>, TxSearched> - load(uint256 const& id, Application& app, error_code_i& ec); + static std:: + variant, std::shared_ptr>, TxSearched> + load(uint256 const& id, Application& app, error_code_i& ec); - static std::variant, std::shared_ptr>, TxSearched> - load(uint256 const& id, Application& app, ClosedInterval const& range, error_code_i& ec); + static std:: + variant, std::shared_ptr>, TxSearched> + load( + uint256 const& id, + Application& app, + ClosedInterval const& range, + error_code_i& ec); private: - static std::variant, std::shared_ptr>, TxSearched> - load(uint256 const& id, Application& app, std::optional> const& range, error_code_i& ec); + static std:: + variant, std::shared_ptr>, TxSearched> + load( + uint256 const& id, + Application& app, + std::optional> const& range, + error_code_i& ec); uint256 mTransactionID; diff --git a/src/xrpld/app/misc/TxQ.h b/src/xrpld/app/misc/TxQ.h index b50ff1a0b5..4f02d6d617 100644 --- a/src/xrpld/app/misc/TxQ.h +++ b/src/xrpld/app/misc/TxQ.h @@ -1,13 +1,12 @@ #pragma once -#include - #include #include #include #include #include #include +#include #include #include @@ -251,7 +250,12 @@ public: will return `{ terQUEUED, false }`. */ ApplyResult - apply(Application& app, OpenView& view, std::shared_ptr const& tx, ApplyFlags flags, beast::Journal j); + apply( + Application& app, + OpenView& view, + std::shared_ptr const& tx, + ApplyFlags flags, + beast::Journal j); /** Fill the new open ledger with transactions from the queue. @@ -338,7 +342,9 @@ public: private: // Implementation for nextQueuableSeq(). The passed lock must be held. SeqProxy - nextQueuableSeqImpl(std::shared_ptr const& sleAccount, std::lock_guard const&) const; + nextQueuableSeqImpl( + std::shared_ptr const& sleAccount, + std::lock_guard const&) const; /** Track and use the fee escalation metrics of the @@ -371,12 +377,16 @@ private: public: /// Constructor FeeMetrics(Setup const& setup, beast::Journal j) - : minimumTxnCount_(setup.standAlone ? setup.minimumTxnInLedgerSA : setup.minimumTxnInLedger) - , targetTxnCount_(setup.targetTxnInLedger < minimumTxnCount_ ? minimumTxnCount_ : setup.targetTxnInLedger) + : minimumTxnCount_( + setup.standAlone ? setup.minimumTxnInLedgerSA : setup.minimumTxnInLedger) + , targetTxnCount_( + setup.targetTxnInLedger < minimumTxnCount_ ? minimumTxnCount_ + : setup.targetTxnInLedger) , maximumTxnCount_( - setup.maximumTxnInLedger - ? *setup.maximumTxnInLedger < targetTxnCount_ ? targetTxnCount_ : *setup.maximumTxnInLedger - : std::optional(std::nullopt)) + setup.maximumTxnInLedger ? *setup.maximumTxnInLedger < targetTxnCount_ + ? targetTxnCount_ + : *setup.maximumTxnInLedger + : std::optional(std::nullopt)) , txnsExpected_(minimumTxnCount_) , recentTxnCounts_(setup.ledgersInQueue) , escalationMultiplier_(setup.minimumEscalationMultiplier) @@ -706,10 +716,11 @@ private: std::optional const& replacedTxIter, std::shared_ptr const& tx); - using FeeHook = - boost::intrusive::member_hook, &MaybeTx::byFeeListHook>; + using FeeHook = boost::intrusive:: + member_hook, &MaybeTx::byFeeListHook>; - using FeeMultiSet = boost::intrusive::multiset>; + using FeeMultiSet = + boost::intrusive::multiset>; using AccountMap = std::map; @@ -782,7 +793,10 @@ private: FeeMultiSet::iterator_type eraseAndAdvance(FeeMultiSet::const_iterator_type); /// Erase a range of items, based on TxQAccount::TxMap iterators TxQAccount::TxMap::iterator - erase(TxQAccount& txQAccount, TxQAccount::TxMap::const_iterator begin, TxQAccount::TxMap::const_iterator end); + erase( + TxQAccount& txQAccount, + TxQAccount::TxMap::const_iterator begin, + TxQAccount::TxMap::const_iterator end); /** All-or-nothing attempt to try to apply the queued txs for @@ -820,7 +834,8 @@ toDrops(FeeLevel const& level, XRPAmount baseFee) inline FeeLevel64 toFeeLevel(XRPAmount const& drops, XRPAmount const& baseFee) { - return mulDiv(drops, TxQ::baseLevel, baseFee).value_or(FeeLevel64(std::numeric_limits::max())); + return mulDiv(drops, TxQ::baseLevel, baseFee) + .value_or(FeeLevel64(std::numeric_limits::max())); } } // namespace xrpl diff --git a/src/xrpld/app/misc/ValidatorList.h b/src/xrpld/app/misc/ValidatorList.h index f93ac8a32f..e774da4713 100644 --- a/src/xrpld/app/misc/ValidatorList.h +++ b/src/xrpld/app/misc/ValidatorList.h @@ -292,7 +292,10 @@ public: struct MessageWithHash { explicit MessageWithHash() = default; - explicit MessageWithHash(std::shared_ptr const& message_, uint256 hash_, std::size_t num_); + explicit MessageWithHash( + std::shared_ptr const& message_, + uint256 hash_, + std::size_t num_); std::shared_ptr message; uint256 hash; std::size_t numVLs = 0; @@ -596,13 +599,14 @@ public: May be called concurrently */ void - for_each_available(std::function const& blobInfos, - PublicKey const& pubKey, - std::size_t maxSequence, - uint256 const& hash)> func) const; + for_each_available( + std::function const& blobInfos, + PublicKey const& pubKey, + std::size_t maxSequence, + uint256 const& hash)> func) const; /** Returns the current valid list for the given publisher key, if available, as a Json object. @@ -767,7 +771,9 @@ private: lock_guard const&); static void - buildBlobInfos(std::map& blobInfos, PublisherListCollection const& lists); + buildBlobInfos( + std::map& blobInfos, + PublisherListCollection const& lists); static std::map buildBlobInfos(PublisherListCollection const& lists); @@ -804,7 +810,10 @@ private: writing to a cache file, or serving to a /vl/ query */ static Json::Value - buildFileData(std::string const& pubKey, PublisherListCollection const& pubCollection, beast::Journal j); + buildFileData( + std::string const& pubKey, + PublisherListCollection const& pubCollection, + beast::Journal j); /** Build a Json representation of the collection, suitable for writing to a cache file, or serving to a /vl/ query diff --git a/src/xrpld/app/misc/ValidatorSite.h b/src/xrpld/app/misc/ValidatorSite.h index dc44e28bcb..9c2d45fb6d 100644 --- a/src/xrpld/app/misc/ValidatorSite.h +++ b/src/xrpld/app/misc/ValidatorSite.h @@ -207,17 +207,26 @@ private: /// Initiate request to given resource. /// lock over sites_mutex_ required void - makeRequest(std::shared_ptr resource, std::size_t siteIdx, std::lock_guard const&); + makeRequest( + std::shared_ptr resource, + std::size_t siteIdx, + std::lock_guard const&); /// Parse json response from validator list site. /// lock over sites_mutex_ required void - parseJsonResponse(std::string const& res, std::size_t siteIdx, std::lock_guard const&); + parseJsonResponse( + std::string const& res, + std::size_t siteIdx, + std::lock_guard const&); /// Interpret a redirect response. /// lock over sites_mutex_ required std::shared_ptr - processRedirect(detail::response_type& res, std::size_t siteIdx, std::lock_guard const&); + processRedirect( + detail::response_type& res, + std::size_t siteIdx, + std::lock_guard const&); /// If no sites are provided, or a site fails to load, /// get a list of local cache files from the ValidatorList. diff --git a/src/xrpld/app/misc/detail/AccountTxPaging.cpp b/src/xrpld/app/misc/detail/AccountTxPaging.cpp index e3fc2de4f8..63457f00ac 100644 --- a/src/xrpld/app/misc/detail/AccountTxPaging.cpp +++ b/src/xrpld/app/misc/detail/AccountTxPaging.cpp @@ -3,6 +3,7 @@ #include #include +#include #include namespace xrpl { @@ -30,7 +31,7 @@ convertBlobsToTxResult( Transaction::sqlTransactionStatus(status), ledger_index, metaset->getAsObject().getFieldU32(sfTransactionIndex), - app.config().NETWORK_ID); + app.getNetworkIDService().getNetworkID()); else tr->setStatus(Transaction::sqlTransactionStatus(status), ledger_index); diff --git a/src/xrpld/app/misc/detail/AmendmentTable.cpp b/src/xrpld/app/misc/detail/AmendmentTable.cpp index 3addfd2235..196584fe6f 100644 --- a/src/xrpld/app/misc/detail/AmendmentTable.cpp +++ b/src/xrpld/app/misc/detail/AmendmentTable.cpp @@ -1,7 +1,5 @@ -#include -#include -#include - +#include +#include #include #include #include @@ -42,7 +40,8 @@ parseSection(Section const& section) uint256 id; if (!id.parseHex(match[1])) - Throw("Invalid amendment ID '" + match[1] + "' in [" + section.name() + "]"); + Throw( + "Invalid amendment ID '" + match[1] + "' in [" + section.name() + "]"); names.push_back(std::make_pair(id, match[2])); } @@ -155,17 +154,19 @@ public: { auto const pkHuman = toBase58(TokenType::NodePublic, val->getSignerPublic()); // If this validation comes from one of our trusted validators... - if (auto const iter = recordedVotes_.find(val->getSignerPublic()); iter != recordedVotes_.end()) + if (auto const iter = recordedVotes_.find(val->getSignerPublic()); + iter != recordedVotes_.end()) { iter->second.timeout = newTimeout; if (val->isFieldPresent(sfAmendments)) { auto const& choices = val->getFieldV256(sfAmendments); iter->second.upVotes.assign(choices.begin(), choices.end()); - JLOG(j.debug()) << "recordVotes: Validation from trusted " << pkHuman << " has " << choices.size() - << " amendment votes: " + JLOG(j.debug()) << "recordVotes: Validation from trusted " << pkHuman << " has " + << choices.size() << " amendment votes: " << boost::algorithm::join( - iter->second.upVotes | boost::adaptors::transformed(to_string<256, void>), + iter->second.upVotes | + boost::adaptors::transformed(to_string<256, void>), ", "); // TODO: Maybe transform using to_short_string once #5126 is // merged @@ -177,7 +178,8 @@ public: { // This validator does not upVote any amendments right now. iter->second.upVotes.clear(); - JLOG(j.debug()) << "recordVotes: Validation from trusted " << pkHuman << " has no amendment votes."; + JLOG(j.debug()) << "recordVotes: Validation from trusted " << pkHuman + << " has no amendment votes."; } } else @@ -216,7 +218,8 @@ public: "expired"); using namespace std::chrono; auto const age = duration_cast(newTimeout - *votes.second.timeout); - JLOG(j.debug()) << "recordVotes: Using " << age.count() << "min old cached votes from " << pkHuman; + JLOG(j.debug()) << "recordVotes: Using " << age.count() + << "min old cached votes from " << pkHuman; } }); } @@ -282,7 +285,10 @@ private: int threshold_ = 0; public: - AmendmentSet(Rules const& rules, TrustedVotes const& trustedVotes, std::lock_guard const& lock) + AmendmentSet( + Rules const& rules, + TrustedVotes const& trustedVotes, + std::lock_guard const& lock) { // process validations for ledger before flag ledger. auto [trustedCount, newVotes] = trustedVotes.getVotes(rules, lock); @@ -293,7 +299,8 @@ public: threshold_ = std::max( 1L, static_cast( - (trustedValidations_ * amendmentMajorityCalcThreshold.num) / amendmentMajorityCalcThreshold.den)); + (trustedValidations_ * amendmentMajorityCalcThreshold.num) / + amendmentMajorityCalcThreshold.den)); } bool @@ -400,7 +407,7 @@ private: public: AmendmentTableImpl( - Application& app, + ServiceRegistry& registry, std::chrono::seconds majorityTime, std::vector const& supported, Section const& enabled, @@ -438,7 +445,10 @@ public: needValidatedLedger(LedgerIndex seq) const override; void - doValidatedLedger(LedgerIndex seq, std::set const& enabled, majorityAmendments_t const& majority) override; + doValidatedLedger( + LedgerIndex seq, + std::set const& enabled, + majorityAmendments_t const& majority) override; void trustChanged(hash_set const& allTrusted) override; @@ -461,13 +471,17 @@ public: //------------------------------------------------------------------------------ AmendmentTableImpl::AmendmentTableImpl( - Application& app, + ServiceRegistry& registry, std::chrono::seconds majorityTime, std::vector const& supported, Section const& enabled, Section const& vetoed, beast::Journal journal) - : lastUpdateSeq_(0), majorityTime_(majorityTime), unsupportedEnabled_(false), j_(journal), db_(app.getWalletDB()) + : lastUpdateSeq_(0) + , majorityTime_(majorityTime) + , unsupportedEnabled_(false) + , j_(journal) + , db_(registry.getWalletDB()) { std::lock_guard lock(mutex_); @@ -499,7 +513,8 @@ AmendmentTableImpl::AmendmentTableImpl( break; } - JLOG(j_.debug()) << "Amendment " << amendment << " (" << s.name << ") is supported and will be " + JLOG(j_.debug()) << "Amendment " << amendment << " (" << s.name + << ") is supported and will be " << (s.vote == AmendmentVote::up ? "up" : "down") << " voted by default if not enabled on the ledger."; } @@ -538,8 +553,9 @@ AmendmentTableImpl::AmendmentTableImpl( } else { - JLOG(j_.warn()) << "[veto_amendments] section in config has amendment " << '(' << a.first << ", " - << a.second << ") both [veto_amendments] and [amendments]."; + JLOG(j_.warn()) << "[veto_amendments] section in config has amendment " << '(' + << a.first << ", " << a.second + << ") both [veto_amendments] and [amendments]."; } } } @@ -559,14 +575,16 @@ AmendmentTableImpl::AmendmentTableImpl( } if (!amend_hash.parseHex(*amendment_hash)) { - Throw("Invalid amendment ID '" + *amendment_hash + " in wallet.db"); + Throw( + "Invalid amendment ID '" + *amendment_hash + " in wallet.db"); } if (*vote == AmendmentVote::down) { // Unknown amendments are effectively vetoed already if (auto s = get(amend_hash, lock)) { - JLOG(j_.info()) << "Amendment {" << *amendment_name << ", " << amend_hash << "} is downvoted."; + JLOG(j_.info()) << "Amendment {" << *amendment_name << ", " << amend_hash + << "} is downvoted."; if (!amendment_name->empty()) s->name = *amendment_name; // An obsolete amendment's vote can never be changed @@ -578,7 +596,8 @@ AmendmentTableImpl::AmendmentTableImpl( { AmendmentState& s = add(amend_hash, lock); - JLOG(j_.debug()) << "Amendment {" << *amendment_name << ", " << amend_hash << "} is upvoted."; + JLOG(j_.debug()) << "Amendment {" << *amendment_name << ", " << amend_hash + << "} is upvoted."; if (!amendment_name->empty()) s.name = *amendment_name; // An obsolete amendment's vote can never be changed @@ -629,9 +648,14 @@ AmendmentTableImpl::find(std::string const& name) const } void -AmendmentTableImpl::persistVote(uint256 const& amendment, std::string const& name, AmendmentVote vote) const +AmendmentTableImpl::persistVote( + uint256 const& amendment, + std::string const& name, + AmendmentVote vote) const { - XRPL_ASSERT(vote != AmendmentVote::obsolete, "xrpl::AmendmentTableImpl::persistVote : valid vote input"); + XRPL_ASSERT( + vote != AmendmentVote::obsolete, + "xrpl::AmendmentTableImpl::persistVote : valid vote input"); auto db = db_.checkoutDb(); voteAmendment(*db, amendment, name, vote); } @@ -724,7 +748,8 @@ AmendmentTableImpl::doValidation(std::set const& enabled) const amendments.reserve(amendmentMap_.size()); for (auto const& e : amendmentMap_) { - if (e.second.supported && e.second.vote == AmendmentVote::up && (enabled.count(e.first) == 0)) + if (e.second.supported && e.second.vote == AmendmentVote::up && + (enabled.count(e.first) == 0)) { amendments.push_back(e.first); JLOG(j_.info()) << "Voting for amendment " << e.second.name; @@ -753,8 +778,9 @@ AmendmentTableImpl::doVoting( majorityAmendments_t const& majorityAmendments, std::vector> const& valSet) { - JLOG(j_.trace()) << "voting at " << closeTime.time_since_epoch().count() << ": " << enabledAmendments.size() << ", " - << majorityAmendments.size() << ", " << valSet.size(); + JLOG(j_.trace()) << "voting at " << closeTime.time_since_epoch().count() << ": " + << enabledAmendments.size() << ", " << majorityAmendments.size() << ", " + << valSet.size(); std::lock_guard lock(mutex_); @@ -793,7 +819,8 @@ AmendmentTableImpl::doVoting( auto const logStr = [&entry, &vote]() { std::stringstream ss; - ss << entry.first << " (" << entry.second.name << ") has " << vote->votes(entry.first) << " votes"; + ss << entry.first << " (" << entry.second.name << ") has " << vote->votes(entry.first) + << " votes"; return ss.str(); }(); @@ -872,7 +899,8 @@ AmendmentTableImpl::doValidatedLedger( if (!s.supported) { - JLOG(j_.info()) << "Unsupported amendment " << hash << " reached majority at " << to_string(time); + JLOG(j_.info()) << "Unsupported amendment " << hash << " reached majority at " + << to_string(time); if (!firstUnsupportedExpected_ || firstUnsupportedExpected_ > time) firstUnsupportedExpected_ = time; } @@ -931,7 +959,8 @@ AmendmentTableImpl::getJson(bool isAdmin) const std::lock_guard lock(mutex_); for (auto const& e : amendmentMap_) { - injectJson(ret[to_string(e.first)] = Json::objectValue, e.first, e.second, isAdmin, lock); + injectJson( + ret[to_string(e.first)] = Json::objectValue, e.first, e.second, isAdmin, lock); } } return ret; @@ -957,14 +986,15 @@ AmendmentTableImpl::getJson(uint256 const& amendmentID, bool isAdmin) const std::unique_ptr make_AmendmentTable( - Application& app, + ServiceRegistry& registry, std::chrono::seconds majorityTime, std::vector const& supported, Section const& enabled, Section const& vetoed, beast::Journal journal) { - return std::make_unique(app, majorityTime, supported, enabled, vetoed, journal); + return std::make_unique( + registry, majorityTime, supported, enabled, vetoed, journal); } } // namespace xrpl diff --git a/src/xrpld/app/misc/detail/Manifest.cpp b/src/xrpld/app/misc/detail/Manifest.cpp index dfcbdbb3ad..4526bf6c16 100644 --- a/src/xrpld/app/misc/detail/Manifest.cpp +++ b/src/xrpld/app/misc/detail/Manifest.cpp @@ -145,13 +145,19 @@ template Stream& logMftAct(Stream& s, std::string const& action, PublicKey const& pk, std::uint32_t seq) { - s << "Manifest: " << action << ";Pk: " << toBase58(TokenType::NodePublic, pk) << ";Seq: " << seq << ";"; + s << "Manifest: " << action << ";Pk: " << toBase58(TokenType::NodePublic, pk) << ";Seq: " << seq + << ";"; return s; } template Stream& -logMftAct(Stream& s, std::string const& action, PublicKey const& pk, std::uint32_t seq, std::uint32_t oldSeq) +logMftAct( + Stream& s, + std::string const& action, + PublicKey const& pk, + std::uint32_t seq, + std::uint32_t oldSeq) { s << "Manifest: " << action << ";Pk: " << toBase58(TokenType::NodePublic, pk) << ";Seq: " << seq << ";OldSeq: " << oldSeq << ";"; @@ -233,9 +239,11 @@ loadValidatorToken(std::vector const& blob, beast::Journal journal) std::string tokenStr; tokenStr.reserve( - std::accumulate(blob.cbegin(), blob.cend(), std::size_t(0), [](std::size_t init, std::string const& s) { - return init + s.size(); - })); + std::accumulate( + blob.cbegin(), + blob.cend(), + std::size_t(0), + [](std::size_t init, std::string const& s) { return init + s.size(); })); for (auto const& line : blob) tokenStr += boost::algorithm::trim_copy(line); @@ -348,8 +356,8 @@ ManifestCache::applyManifest(Manifest m) // signature should be checked. Since `prewriteCheck` is run twice (see // comment below), `checkSignature` only needs to be set to true on the // first run. - auto prewriteCheck = - [this, &m](auto const& iter, bool checkSignature, auto const& lock) -> std::optional { + auto prewriteCheck = [this, &m](auto const& iter, bool checkSignature, auto const& lock) + -> std::optional { XRPL_ASSERT(lock.owns_lock(), "xrpl::ManifestCache::applyManifest::prewriteCheck : locked"); (void)lock; // not used. parameter is present to ensure the mutex is // locked when the lambda is called. @@ -406,9 +414,11 @@ ManifestCache::applyManifest(Manifest m) // Sanity check: the ephemeral key of this manifest should not be // used as the master or ephemeral key of another manifest: - if (auto const x = signingToMasterKeys_.find(*m.signingKey); x != signingToMasterKeys_.end()) + if (auto const x = signingToMasterKeys_.find(*m.signingKey); + x != signingToMasterKeys_.end()) { - JLOG(j_.warn()) << to_string(m) << ": Ephemeral key already used as ephemeral key for " + JLOG(j_.warn()) << to_string(m) + << ": Ephemeral key already used as ephemeral key for " << toBase58(TokenType::NodePublic, x->second); return ManifestDisposition::badEphemeralKey; @@ -416,7 +426,8 @@ ManifestCache::applyManifest(Manifest m) if (auto const x = map_.find(*m.signingKey); x != map_.end()) { - JLOG(j_.warn()) << to_string(m) << ": Ephemeral key used as master key for " << to_string(x->second); + JLOG(j_.warn()) << to_string(m) << ": Ephemeral key used as master key for " + << to_string(x->second); return ManifestDisposition::badEphemeralKey; } @@ -523,11 +534,12 @@ ManifestCache::load( if (!configRevocation.empty()) { std::string revocationStr; - revocationStr.reserve(std::accumulate( - configRevocation.cbegin(), - configRevocation.cend(), - std::size_t(0), - [](std::size_t init, std::string const& s) { return init + s.size(); })); + revocationStr.reserve( + std::accumulate( + configRevocation.cbegin(), + configRevocation.cend(), + std::size_t(0), + [](std::size_t init, std::string const& s) { return init + s.size(); })); for (auto const& line : configRevocation) revocationStr += boost::algorithm::trim_copy(line); diff --git a/src/xrpld/app/misc/detail/Transaction.cpp b/src/xrpld/app/misc/detail/Transaction.cpp index 8ffbc47b08..fae26873fb 100644 --- a/src/xrpld/app/misc/detail/Transaction.cpp +++ b/src/xrpld/app/misc/detail/Transaction.cpp @@ -1,18 +1,21 @@ #include #include -#include #include -#include #include #include +#include #include #include #include +#include namespace xrpl { -Transaction::Transaction(std::shared_ptr const& stx, std::string& reason, Application& app) noexcept +Transaction::Transaction( + std::shared_ptr const& stx, + std::string& reason, + Application& app) noexcept : mTransaction(stx), mApp(app), j_(app.journal("Ledger")) { try @@ -99,7 +102,11 @@ Transaction::load(uint256 const& id, Application& app, error_code_i& ec) } std::variant, std::shared_ptr>, TxSearched> -Transaction::load(uint256 const& id, Application& app, ClosedInterval const& range, error_code_i& ec) +Transaction::load( + uint256 const& id, + Application& app, + ClosedInterval const& range, + error_code_i& ec) { using op = std::optional>; diff --git a/src/xrpld/app/misc/detail/TxQ.cpp b/src/xrpld/app/misc/detail/TxQ.cpp index 61741b73f0..718b468ff0 100644 --- a/src/xrpld/app/misc/detail/TxQ.cpp +++ b/src/xrpld/app/misc/detail/TxQ.cpp @@ -1,12 +1,12 @@ #include #include #include -#include #include #include #include #include +#include #include #include @@ -55,27 +55,35 @@ getLastLedgerSequence(STTx const& tx) static FeeLevel64 increase(FeeLevel64 level, std::uint32_t increasePercent) { - return mulDiv(level, 100 + increasePercent, 100).value_or(static_cast(xrpl::muldiv_max)); + return mulDiv(level, 100 + increasePercent, 100) + .value_or(static_cast(xrpl::muldiv_max)); } ////////////////////////////////////////////////////////////////////////// std::size_t -TxQ::FeeMetrics::update(Application& app, ReadView const& view, bool timeLeap, TxQ::Setup const& setup) +TxQ::FeeMetrics::update( + Application& app, + ReadView const& view, + bool timeLeap, + TxQ::Setup const& setup) { std::vector feeLevels; auto const txBegin = view.txs.begin(); auto const txEnd = view.txs.end(); auto const size = std::distance(txBegin, txEnd); feeLevels.reserve(size); - std::for_each(txBegin, txEnd, [&](auto const& tx) { feeLevels.push_back(getFeeLevelPaid(view, *tx.first)); }); + std::for_each(txBegin, txEnd, [&](auto const& tx) { + feeLevels.push_back(getFeeLevelPaid(view, *tx.first)); + }); std::sort(feeLevels.begin(), feeLevels.end()); XRPL_ASSERT(size == feeLevels.size(), "xrpl::TxQ::FeeMetrics::update : fee levels size"); JLOG((timeLeap ? j_.warn() : j_.debug())) << "Ledger " << view.header().seq << " has " << size << " transactions. " - << "Ledgers are processing " << (timeLeap ? "slowly" : "as expected") << ". Expected transactions is currently " - << txnsExpected_ << " and multiplier is " << escalationMultiplier_; + << "Ledgers are processing " << (timeLeap ? "slowly" : "as expected") + << ". Expected transactions is currently " << txnsExpected_ << " and multiplier is " + << escalationMultiplier_; if (timeLeap) { @@ -84,16 +92,16 @@ TxQ::FeeMetrics::update(Application& app, ReadView const& view, bool timeLeap, T auto const cutPct = 100 - setup.slowConsensusDecreasePercent; // upperLimit must be >= minimumTxnCount_ or std::clamp can give // unexpected results - auto const upperLimit = - std::max(mulDiv(txnsExpected_, cutPct, 100).value_or(xrpl::muldiv_max), minimumTxnCount_); + auto const upperLimit = std::max( + mulDiv(txnsExpected_, cutPct, 100).value_or(xrpl::muldiv_max), minimumTxnCount_); txnsExpected_ = std::clamp( mulDiv(size, cutPct, 100).value_or(xrpl::muldiv_max), minimumTxnCount_, upperLimit); recentTxnCounts_.clear(); } else if (size > txnsExpected_ || size > targetTxnCount_) { - recentTxnCounts_.push_back( - mulDiv(size, 100 + setup.normalConsensusIncreasePercent, 100).value_or(xrpl::muldiv_max)); + recentTxnCounts_.push_back(mulDiv(size, 100 + setup.normalConsensusIncreasePercent, 100) + .value_or(xrpl::muldiv_max)); auto const iter = std::max_element(recentTxnCounts_.begin(), recentTxnCounts_.end()); BOOST_ASSERT(iter != recentTxnCounts_.end()); auto const next = [&] { @@ -123,11 +131,12 @@ TxQ::FeeMetrics::update(Application& app, ReadView const& view, bool timeLeap, T // evaluates to the middle element; for an even // number of elements, it will add the two elements // on either side of the "middle" and average them. - escalationMultiplier_ = (feeLevels[size / 2] + feeLevels[(size - 1) / 2] + FeeLevel64{1}) / 2; + escalationMultiplier_ = + (feeLevels[size / 2] + feeLevels[(size - 1) / 2] + FeeLevel64{1}) / 2; escalationMultiplier_ = std::max(escalationMultiplier_, setup.minimumEscalationMultiplier); } - JLOG(j_.debug()) << "Expected transactions updated to " << txnsExpected_ << " and multiplier updated to " - << escalationMultiplier_; + JLOG(j_.debug()) << "Expected transactions updated to " << txnsExpected_ + << " and multiplier updated to " << escalationMultiplier_; return size; } @@ -228,7 +237,8 @@ TxQ::FeeMetrics::escalatedSeriesFeeLevel( // are nearly nil. if (!sumNlast.first) return {sumNlast.first, FeeLevel64{sumNlast.second}}; - auto const totalFeeLevel = mulDiv(multiplier, sumNlast.second - sumNcurrent.second, target * target); + auto const totalFeeLevel = + mulDiv(multiplier, sumNlast.second - sumNcurrent.second, target * target); return {totalFeeLevel.has_value(), *totalFeeLevel}; } @@ -262,8 +272,9 @@ TxQ::MaybeTx::apply(Application& app, OpenView& view, beast::Journal j) if (pfResult->rules != view.rules() || pfResult->flags != flags) { - JLOG(j.debug()) << "Queued transaction " << txID << " rules or flags have changed. Flags from " - << pfResult->flags << " to " << flags; + JLOG(j.debug()) << "Queued transaction " << txID + << " rules or flags have changed. Flags from " << pfResult->flags << " to " + << flags; pfResult.emplace(preflight(app, view.rules(), pfResult->tx, flags, pfResult->j)); } @@ -273,7 +284,8 @@ TxQ::MaybeTx::apply(Application& app, OpenView& view, beast::Journal j) return doApply(pcresult, app, view); } -TxQ::TxQAccount::TxQAccount(std::shared_ptr const& txn) : TxQAccount(txn->getAccountID(sfAccount)) +TxQ::TxQAccount::TxQAccount(std::shared_ptr const& txn) + : TxQAccount(txn->getAccountID(sfAccount)) { } @@ -312,7 +324,8 @@ TxQ::TxQAccount::remove(SeqProxy seqProx) ////////////////////////////////////////////////////////////////////////// -TxQ::TxQ(Setup const& setup, beast::Journal j) : setup_(setup), j_(j), feeMetrics_(setup, j), maxSize_(std::nullopt) +TxQ::TxQ(Setup const& setup, beast::Journal j) + : setup_(setup), j_(j), feeMetrics_(setup, j), maxSize_(std::nullopt) { } @@ -343,7 +356,8 @@ TxQ::canBeHeld( // AccountTxnID is not supported by the transaction // queue yet, but should be added in the future. // tapFAIL_HARD transactions are never held - if (tx.isFieldPresent(sfPreviousTxnID) || tx.isFieldPresent(sfAccountTxnID) || (flags & tapFAIL_HARD)) + if (tx.isFieldPresent(sfPreviousTxnID) || tx.isFieldPresent(sfAccountTxnID) || + (flags & tapFAIL_HARD)) return telCAN_NOT_QUEUE; { @@ -409,11 +423,13 @@ TxQ::erase(TxQ::FeeMultiSet::const_iterator_type candidateIter) -> FeeMultiSet:: } auto -TxQ::eraseAndAdvance(TxQ::FeeMultiSet::const_iterator_type candidateIter) -> FeeMultiSet::iterator_type +TxQ::eraseAndAdvance(TxQ::FeeMultiSet::const_iterator_type candidateIter) + -> FeeMultiSet::iterator_type { auto& txQAccount = byAccount_.at(candidateIter->account); auto const accountIter = txQAccount.transactions.find(candidateIter->seqProxy); - XRPL_ASSERT(accountIter != txQAccount.transactions.end(), "xrpl::TxQ::eraseAndAdvance : account found"); + XRPL_ASSERT( + accountIter != txQAccount.transactions.end(), "xrpl::TxQ::eraseAndAdvance : account found"); // Note that sequence-based transactions must be applied in sequence order // from smallest to largest. But ticket-based transactions can be @@ -422,7 +438,8 @@ TxQ::eraseAndAdvance(TxQ::FeeMultiSet::const_iterator_type candidateIter) -> Fee candidateIter->seqProxy.isTicket() || accountIter == txQAccount.transactions.begin(), "xrpl::TxQ::eraseAndAdvance : ticket or sequence"); XRPL_ASSERT( - byFee_.iterator_to(accountIter->second) == candidateIter, "xrpl::TxQ::eraseAndAdvance : found in byFee"); + byFee_.iterator_to(accountIter->second) == candidateIter, + "xrpl::TxQ::eraseAndAdvance : found in byFee"); auto const accountNextIter = std::next(accountIter); // Check if the next transaction for this account is earlier in the queue, @@ -483,8 +500,8 @@ TxQ::tryClearAccountQueueUpThruTx( if (!requiredTotalFeeLevel.first) return {telINSUF_FEE_P, false}; - auto const totalFeeLevelPaid = - std::accumulate(beginTxIter, endTxIter, feeLevelPaid, [](auto const& total, auto const& txn) { + auto const totalFeeLevelPaid = std::accumulate( + beginTxIter, endTxIter, feeLevelPaid, [](auto const& total, auto const& txn) { return total + txn.second.feeLevel; }); @@ -660,7 +677,12 @@ TxQ::tryClearAccountQueueUpThruTx( // beyond that limit are rejected. // ApplyResult -TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& tx, ApplyFlags flags, beast::Journal j) +TxQ::apply( + Application& app, + OpenView& view, + std::shared_ptr const& tx, + ApplyFlags flags, + beast::Journal j) { NumberSO stNumberSO{view.rules().enabled(fixUniversalNumber)}; @@ -721,7 +743,8 @@ TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& // to individually check each queued ticket against the ledger. struct TxIter { - TxIter(TxQAccount::TxMap::iterator first_, TxQAccount::TxMap::iterator end_) : first(first_), end(end_) + TxIter(TxQAccount::TxMap::iterator first_, TxQAccount::TxMap::iterator end_) + : first(first_), end(end_) { } @@ -729,7 +752,8 @@ TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& TxQAccount::TxMap::iterator end; }; - std::optional const txIter = [accountIter, accountIsInQueue, acctSeqProx]() -> std::optional { + std::optional const txIter = + [accountIter, accountIsInQueue, acctSeqProx]() -> std::optional { if (!accountIsInQueue) return {}; @@ -773,7 +797,9 @@ TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& // If the transaction is intending to replace a transaction in the queue // identify the one that might be replaced. - auto replacedTxIter = [accountIsInQueue, &accountIter, txSeqProx]() -> std::optional { + auto replacedTxIter = [accountIsInQueue, + &accountIter, + txSeqProx]() -> std::optional { if (accountIsInQueue) { TxQAccount& txQAcct = accountIter->second; @@ -799,7 +825,8 @@ TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& // // We only need to check if txIter->first is a blocker because we // require that a blocker be alone in the account's queue. - if (acctTxCount == 1 && txIter->first->second.consequences().isBlocker() && (txIter->first->first != txSeqProx)) + if (acctTxCount == 1 && txIter->first->second.consequences().isBlocker() && + (txIter->first->first != txSeqProx)) { return {telCAN_NOT_QUEUE_BLOCKED, false}; } @@ -814,23 +841,25 @@ TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& // Is the current transaction's fee higher than // the queued transaction's fee + a percentage TxQAccount::TxMap::iterator const& existingIter = *replacedTxIter; - auto requiredRetryLevel = increase(existingIter->second.feeLevel, setup_.retrySequencePercent); - JLOG(j_.trace()) << "Found transaction in queue for account " << account << " with " << txSeqProx - << " new txn fee level is " << feeLevelPaid << ", old txn fee level is " - << existingIter->second.feeLevel << ", new txn needs fee level of " << requiredRetryLevel; + auto requiredRetryLevel = + increase(existingIter->second.feeLevel, setup_.retrySequencePercent); + JLOG(j_.trace()) << "Found transaction in queue for account " << account << " with " + << txSeqProx << " new txn fee level is " << feeLevelPaid + << ", old txn fee level is " << existingIter->second.feeLevel + << ", new txn needs fee level of " << requiredRetryLevel; if (feeLevelPaid > requiredRetryLevel) { // Continue, leaving the queued transaction marked for removal. // DO NOT REMOVE if the new tx fails, because there may // be other txs dependent on it in the queue. - JLOG(j_.trace()) << "Removing transaction from queue " << existingIter->second.txID << " in favor of " - << transactionID; + JLOG(j_.trace()) << "Removing transaction from queue " << existingIter->second.txID + << " in favor of " << transactionID; } else { // Drop the current transaction - JLOG(j_.trace()) << "Ignoring transaction " << transactionID << " in favor of queued " - << existingIter->second.txID; + JLOG(j_.trace()) << "Ignoring transaction " << transactionID + << " in favor of queued " << existingIter->second.txID; return {telCAN_NOT_QUEUE_FEE, false}; } } @@ -882,7 +911,8 @@ TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& { // If the transaction is queueable, create the multiTxn // object to hold the info we need to adjust for prior txns. - TER const ter{canBeHeld(*tx, flags, view, sleAccount, accountIter, replacedTxIter, lock)}; + TER const ter{ + canBeHeld(*tx, flags, view, sleAccount, accountIter, replacedTxIter, lock)}; if (!isTesSuccess(ter)) return {ter, false}; @@ -1012,7 +1042,8 @@ TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& if (totalFee >= balance || (reserve > 10 * base && totalFee >= reserve)) { // Drop the current transaction - JLOG(j_.trace()) << "Ignoring transaction " << transactionID << ". Total fees in flight too high."; + JLOG(j_.trace()) << "Ignoring transaction " << transactionID + << ". Total fees in flight too high."; return {telCAN_NOT_QUEUE_BALANCE, false}; } @@ -1026,7 +1057,8 @@ TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& // Subtract the fees and XRP spend from all of the other // transactions in the queue. That prevents a transaction // inserted in the middle from fouling up later transactions. - auto const potentialTotalSpend = totalFee + std::min(balance - std::min(balance, reserve), potentialSpend); + auto const potentialTotalSpend = + totalFee + std::min(balance - std::min(balance, reserve), potentialSpend); XRPL_ASSERT( potentialTotalSpend > XRPAmount{0} || (potentialTotalSpend == XRPAmount{0} && multiTxn->applyView.fees().base == 0), @@ -1037,8 +1069,9 @@ TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& // sequence, set the account to match it. If it has a ticket, use // the next queueable sequence, which is the closest approximation // to the most successful case. - sleBump->at(sfSequence) = - txSeqProx.isSeq() ? txSeqProx.value() : nextQueuableSeqImpl(sleAccount, lock).value(); + sleBump->at(sfSequence) = txSeqProx.isSeq() + ? txSeqProx.value() + : nextQueuableSeqImpl(sleAccount, lock).value(); } } @@ -1060,9 +1093,10 @@ TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& // Too low of a fee should get caught by preclaim XRPL_ASSERT(feeLevelPaid >= baseLevel, "xrpl::TxQ::apply : minimum fee"); - JLOG(j_.trace()) << "Transaction " << transactionID << " from account " << account << " has fee level of " - << feeLevelPaid << " needs at least " << requiredFeeLevel - << " to get in the open ledger, which has " << view.txCount() << " entries."; + JLOG(j_.trace()) << "Transaction " << transactionID << " from account " << account + << " has fee level of " << feeLevelPaid << " needs at least " + << requiredFeeLevel << " to get in the open ledger, which has " + << view.txCount() << " entries."; /* Quick heuristic check to see if it's worth checking that this tx has a high enough fee to clear all the txs in front of it in the queue. @@ -1082,8 +1116,8 @@ TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& conditions change, but don't waste the effort to clear). */ if (txSeqProx.isSeq() && txIter && multiTxn.has_value() && - txIter->first->second.retriesRemaining == MaybeTx::retriesAllowed && feeLevelPaid > requiredFeeLevel && - requiredFeeLevel > baseLevel) + txIter->first->second.retriesRemaining == MaybeTx::retriesAllowed && + feeLevelPaid > requiredFeeLevel && requiredFeeLevel > baseLevel) { OpenView sandbox(open_ledger, &view, view.rules()); @@ -1140,7 +1174,8 @@ TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& // queued. However, it can occur if settings are changed, // and there is unit test coverage. JLOG(j_.info()) << "Queue is full, and transaction " << transactionID - << " would kick a transaction from the same account (" << account << ") out of the queue."; + << " would kick a transaction from the same account (" << account + << ") out of the queue."; return {telCAN_NOT_QUEUE_FULL, false}; } auto const& endAccount = byAccount_.at(lastRIter->account); @@ -1173,10 +1208,11 @@ TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& // valuable, so kick out the cheapest transaction. auto dropRIter = endAccount.transactions.rbegin(); XRPL_ASSERT( - dropRIter->second.account == lastRIter->account, "xrpl::TxQ::apply : cheapest transaction found"); + dropRIter->second.account == lastRIter->account, + "xrpl::TxQ::apply : cheapest transaction found"); JLOG(j_.info()) << "Removing last item of account " << lastRIter->account - << " from queue with average fee of " << endEffectiveFeeLevel << " in favor of " - << transactionID << " with fee of " << feeLevelPaid; + << " from queue with average fee of " << endEffectiveFeeLevel + << " in favor of " << transactionID << " with fee of " << feeLevelPaid; erase(byFee_.iterator_to(dropRIter->second)); } else @@ -1212,8 +1248,9 @@ TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& // Then index it into the byFee lookup. byFee_.insert(candidate); - JLOG(j_.debug()) << "Added transaction " << candidate.txID << " with result " << transToken(pfResult.ter) - << " from " << (accountIsInQueue ? "existing" : "new") << " account " << candidate.account + JLOG(j_.debug()) << "Added transaction " << candidate.txID << " with result " + << transToken(pfResult.ter) << " from " + << (accountIsInQueue ? "existing" : "new") << " account " << candidate.account << " to queue." << " Flags: " << flags; @@ -1323,31 +1360,37 @@ TxQ::accept(Application& app, OpenView& view) // There is a sequence transaction at the front of the queue and // candidate has a later sequence, so skip this candidate. We // need to process sequence-based transactions in sequence order. - JLOG(j_.trace()) << "Skipping queued transaction " << candidateIter->txID << " from account " - << candidateIter->account << " as it is not the first."; + JLOG(j_.trace()) << "Skipping queued transaction " << candidateIter->txID + << " from account " << candidateIter->account + << " as it is not the first."; candidateIter++; continue; } auto const requiredFeeLevel = getRequiredFeeLevel(view, tapNONE, metricsSnapshot, lock); auto const feeLevelPaid = candidateIter->feeLevel; - JLOG(j_.trace()) << "Queued transaction " << candidateIter->txID << " from account " << candidateIter->account - << " has fee level of " << feeLevelPaid << " needs at least " << requiredFeeLevel; + JLOG(j_.trace()) << "Queued transaction " << candidateIter->txID << " from account " + << candidateIter->account << " has fee level of " << feeLevelPaid + << " needs at least " << requiredFeeLevel; if (feeLevelPaid >= requiredFeeLevel) { - JLOG(j_.trace()) << "Applying queued transaction " << candidateIter->txID << " to open ledger."; + JLOG(j_.trace()) << "Applying queued transaction " << candidateIter->txID + << " to open ledger."; auto const [txnResult, didApply, _metadata] = candidateIter->apply(app, view, j_); if (didApply) { // Remove the candidate from the queue - JLOG(j_.debug()) << "Queued transaction " << candidateIter->txID << " applied successfully with " - << transToken(txnResult) << ". Remove from queue."; + JLOG(j_.debug()) << "Queued transaction " << candidateIter->txID + << " applied successfully with " << transToken(txnResult) + << ". Remove from queue."; candidateIter = eraseAndAdvance(candidateIter); ledgerChanged = true; } - else if (isTefFailure(txnResult) || isTemMalformed(txnResult) || candidateIter->retriesRemaining <= 0) + else if ( + isTefFailure(txnResult) || isTemMalformed(txnResult) || + candidateIter->retriesRemaining <= 0) { if (candidateIter->retriesRemaining <= 0) account.retryPenalty = true; @@ -1376,9 +1419,10 @@ TxQ::accept(Application& app, OpenView& view) { // Since the failed transaction has a ticket, order // doesn't matter. Drop this one. - JLOG(j_.info()) << "Queue is nearly full, and transaction " << candidateIter->txID - << " failed with " << transToken(txnResult) - << ". Removing ticketed tx from account " << account.account; + JLOG(j_.info()) + << "Queue is nearly full, and transaction " << candidateIter->txID + << " failed with " << transToken(txnResult) + << ". Removing ticketed tx from account " << account.account; candidateIter = eraseAndAdvance(candidateIter); } else @@ -1389,11 +1433,13 @@ TxQ::accept(Application& app, OpenView& view) // this account. auto dropRIter = account.transactions.rbegin(); XRPL_ASSERT( - dropRIter->second.account == candidateIter->account, "xrpl::TxQ::accept : account check"); + dropRIter->second.account == candidateIter->account, + "xrpl::TxQ::accept : account check"); - JLOG(j_.info()) << "Queue is nearly full, and transaction " << candidateIter->txID - << " failed with " << transToken(txnResult) - << ". Removing last item from account " << account.account; + JLOG(j_.info()) + << "Queue is nearly full, and transaction " << candidateIter->txID + << " failed with " << transToken(txnResult) + << ". Removing last item from account " << account.account; auto endIter = byFee_.iterator_to(dropRIter->second); if (endIter != candidateIter) erase(endIter); @@ -1462,7 +1508,9 @@ TxQ::nextQueuableSeq(std::shared_ptr const& sleAccount) const // sequence number, that is not used by a transaction in the queue, must // be found and returned. SeqProxy -TxQ::nextQueuableSeqImpl(std::shared_ptr const& sleAccount, std::lock_guard const&) const +TxQ::nextQueuableSeqImpl( + std::shared_ptr const& sleAccount, + std::lock_guard const&) const { // If the account is not in the ledger or a non-account was passed // then return zero. We have no idea. @@ -1555,7 +1603,8 @@ TxQ::tryDirectApply( auto const [txnResult, didApply, metadata] = xrpl::apply(app, view, *tx, flags, j); JLOG(j_.trace()) << "New transaction " << transactionID - << (didApply ? " applied successfully with " : " failed with ") << transToken(txnResult); + << (didApply ? " applied successfully with " : " failed with ") + << transToken(txnResult); if (didApply) { @@ -1590,9 +1639,15 @@ TxQ::removeFromByFee( // queue, remove the transaction that is being replaced. auto deleteIter = byFee_.iterator_to((*replacedTxIter)->second); XRPL_ASSERT(deleteIter != byFee_.end(), "xrpl::TxQ::removeFromByFee : found in byFee"); - XRPL_ASSERT(&(*replacedTxIter)->second == &*deleteIter, "xrpl::TxQ::removeFromByFee : matching transaction"); - XRPL_ASSERT(deleteIter->seqProxy == tx->getSeqProxy(), "xrpl::TxQ::removeFromByFee : matching sequence"); - XRPL_ASSERT(deleteIter->account == (*tx)[sfAccount], "xrpl::TxQ::removeFromByFee : matching account"); + XRPL_ASSERT( + &(*replacedTxIter)->second == &*deleteIter, + "xrpl::TxQ::removeFromByFee : matching transaction"); + XRPL_ASSERT( + deleteIter->seqProxy == tx->getSeqProxy(), + "xrpl::TxQ::removeFromByFee : matching sequence"); + XRPL_ASSERT( + deleteIter->account == (*tx)[sfAccount], + "xrpl::TxQ::removeFromByFee : matching account"); erase(deleteIter); } @@ -1636,7 +1691,8 @@ TxQ::getTxRequiredFeeAndSeq(OpenView const& view, std::shared_ptr co std::uint32_t const accountSeq = sle ? (*sle)[sfSequence] : 0; std::uint32_t const availableSeq = nextQueuableSeqImpl(sle, lock).value(); return { - mulDiv(fee, baseFee, baseLevel).value_or(XRPAmount(std::numeric_limits::max())), + mulDiv(fee, baseFee, baseLevel) + .value_or(XRPAmount(std::numeric_limits::max())), accountSeq, availableSeq}; } @@ -1717,8 +1773,9 @@ TxQ::doRPC(Application& app) const drops[jss::base_fee] = to_string(baseFee); drops[jss::median_fee] = to_string(toDrops(metrics.medFeeLevel, baseFee)); - drops[jss::minimum_fee] = to_string( - toDrops(metrics.minProcessingFeeLevel, metrics.txCount >= metrics.txQMaxSize ? effectiveBaseFee : baseFee)); + drops[jss::minimum_fee] = to_string(toDrops( + metrics.minProcessingFeeLevel, + metrics.txCount >= metrics.txQMaxSize ? effectiveBaseFee : baseFee)); auto openFee = toDrops(metrics.openLedgerFeeLevel, effectiveBaseFee); if (effectiveBaseFee && toFeeLevel(openFee, effectiveBaseFee) < metrics.openLedgerFeeLevel) openFee += 1; @@ -1771,7 +1828,8 @@ setup_TxQ(Config const& config) minimum_txn_in_ledger.) */ set(setup.normalConsensusIncreasePercent, "normal_consensus_increase_percent", section); - setup.normalConsensusIncreasePercent = std::clamp(setup.normalConsensusIncreasePercent, 0u, 1000u); + setup.normalConsensusIncreasePercent = + std::clamp(setup.normalConsensusIncreasePercent, 0u, 1000u); /* If this percentage is outside of the 0-100 range, the results are nonsensical (uint overflows happen, so the limit grows diff --git a/src/xrpld/app/misc/detail/ValidatorKeys.cpp b/src/xrpld/app/misc/detail/ValidatorKeys.cpp index 8f24f14b40..59ddc6d702 100644 --- a/src/xrpld/app/misc/detail/ValidatorKeys.cpp +++ b/src/xrpld/app/misc/detail/ValidatorKeys.cpp @@ -12,7 +12,8 @@ ValidatorKeys::ValidatorKeys(Config const& config, beast::Journal j) if (config.exists(SECTION_VALIDATOR_TOKEN) && config.exists(SECTION_VALIDATION_SEED)) { configInvalid_ = true; - JLOG(j.fatal()) << "Cannot specify both [" SECTION_VALIDATION_SEED "] and [" SECTION_VALIDATOR_TOKEN "]"; + JLOG(j.fatal()) << "Cannot specify both [" SECTION_VALIDATION_SEED + "] and [" SECTION_VALIDATOR_TOKEN "]"; return; } @@ -45,7 +46,8 @@ ValidatorKeys::ValidatorKeys(Config const& config, beast::Journal j) } else if (config.exists(SECTION_VALIDATION_SEED)) { - auto const seed = parseBase58(config.section(SECTION_VALIDATION_SEED).lines().front()); + auto const seed = + parseBase58(config.section(SECTION_VALIDATION_SEED).lines().front()); if (!seed) { configInvalid_ = true; diff --git a/src/xrpld/app/misc/detail/ValidatorList.cpp b/src/xrpld/app/misc/detail/ValidatorList.cpp index 0edd0de9be..73db2f8bdb 100644 --- a/src/xrpld/app/misc/detail/ValidatorList.cpp +++ b/src/xrpld/app/misc/detail/ValidatorList.cpp @@ -1,5 +1,3 @@ -#include -#include #include #include @@ -7,12 +5,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include @@ -198,7 +198,8 @@ ValidatorList::load( auto const [_, inserted] = keyListings_.insert({*localPubKey_, listThreshold_}); if (inserted) { - JLOG(j_.debug()) << "Added own master key " << toBase58(TokenType::NodePublic, *localPubKey_); + JLOG(j_.debug()) << "Added own master key " + << toBase58(TokenType::NodePublic, *localPubKey_); } } @@ -300,7 +301,8 @@ ValidatorList::buildFileData( case 2: { Json::Value blobs(Json::arrayValue); - auto add = [&blobs, &outerManifest = pubCollection.rawManifest](PublisherList const& pubList) { + auto add = [&blobs, + &outerManifest = pubCollection.rawManifest](PublisherList const& pubList) { auto& blob = blobs.append(Json::objectValue); blob[jss::blob] = pubList.rawBlob; blob[jss::signature] = pubList.rawSignature; @@ -327,7 +329,8 @@ ValidatorList::buildFileData( } void -ValidatorList::cacheValidatorFile(ValidatorList::lock_guard const& lock, PublicKey const& pubKey) const +ValidatorList::cacheValidatorFile(ValidatorList::lock_guard const& lock, PublicKey const& pubKey) + const { if (dataPath_.empty()) return; @@ -348,7 +351,8 @@ ValidatorList::cacheValidatorFile(ValidatorList::lock_guard const& lock, PublicK if (ec) { // Log and ignore any file I/O exceptions - JLOG(j_.error()) << "Problem writing " << filename << " " << ec.value() << ": " << ec.message(); + JLOG(j_.error()) << "Problem writing " << filename << " " << ec.value() << ": " + << ec.message(); } } @@ -360,15 +364,16 @@ ValidatorList::parseBlobs(std::uint32_t version, Json::Value const& body) switch (version) { case 1: { - if (!body.isMember(jss::blob) || !body[jss::blob].isString() || !body.isMember(jss::signature) || - !body[jss::signature].isString() || + if (!body.isMember(jss::blob) || !body[jss::blob].isString() || + !body.isMember(jss::signature) || !body[jss::signature].isString() || // If the v2 field is present, the VL is malformed body.isMember(jss::blobs_v2)) return {}; ValidatorBlobInfo& info = result.emplace_back(); info.blob = body[jss::blob].asString(); info.signature = body[jss::signature].asString(); - XRPL_ASSERT(result.size() == 1, "xrpl::ValidatorList::parseBlobs : single element result"); + XRPL_ASSERT( + result.size() == 1, "xrpl::ValidatorList::parseBlobs : single element result"); return result; } // Treat unknown versions as if they're the latest version. This @@ -494,9 +499,13 @@ splitMessageParts( smallMsg.set_manifest(blob.manifest()); XRPL_ASSERT( - Message::totalSize(smallMsg) <= maximumMessageSize, "xrpl::splitMessageParts : maximum message size"); + Message::totalSize(smallMsg) <= maximumMessageSize, + "xrpl::splitMessageParts : maximum message size"); - messages.emplace_back(std::make_shared(smallMsg, protocol::mtVALIDATOR_LIST), sha512Half(smallMsg), 1); + messages.emplace_back( + std::make_shared(smallMsg, protocol::mtVALIDATOR_LIST), + sha512Half(smallMsg), + 1); return messages.back().numVLs; } else @@ -555,7 +564,8 @@ buildValidatorListMessage( Message::totalSize(msg) <= maximumMessageSize, "xrpl::buildValidatorListMessage(ValidatorBlobInfo) : maximum " "message size"); - messages.emplace_back(std::make_shared(msg, protocol::mtVALIDATOR_LIST), sha512Half(msg), 1); + messages.emplace_back( + std::make_shared(msg, protocol::mtVALIDATOR_LIST), sha512Half(msg), 1); return 1; } @@ -601,7 +611,9 @@ buildValidatorListMessage( else { messages.emplace_back( - std::make_shared(msg, protocol::mtVALIDATOR_LIST_COLLECTION), sha512Half(msg), msg.blobs_size()); + std::make_shared(msg, protocol::mtVALIDATOR_LIST_COLLECTION), + sha512Half(msg), + msg.blobs_size()); return messages.back().numVLs; } } @@ -624,15 +636,17 @@ ValidatorList::buildValidatorListMessages( "xrpl::ValidatorList::buildValidatorListMessages : empty messages " "input"); auto const& [currentSeq, currentBlob] = *blobInfos.begin(); - auto numVLs = std::accumulate(messages.begin(), messages.end(), 0, [](std::size_t total, MessageWithHash const& m) { - return total + m.numVLs; - }); + auto numVLs = std::accumulate( + messages.begin(), messages.end(), 0, [](std::size_t total, MessageWithHash const& m) { + return total + m.numVLs; + }); if (messageVersion == 2 && peerSequence < maxSequence) { // Version 2 if (messages.empty()) { - numVLs = buildValidatorListMessage(messages, peerSequence, rawVersion, rawManifest, blobInfos, maxSize); + numVLs = buildValidatorListMessage( + messages, peerSequence, rawVersion, rawManifest, blobInfos, maxSize); if (messages.empty()) // No message was generated. Create an empty placeholder so we // dont' repeat the work later. @@ -648,7 +662,11 @@ ValidatorList::buildValidatorListMessages( if (messages.empty()) { numVLs = buildValidatorListMessage( - messages, rawVersion, currentBlob.manifest ? *currentBlob.manifest : rawManifest, currentBlob, maxSize); + messages, + rawVersion, + currentBlob.manifest ? *currentBlob.manifest : rawManifest, + currentBlob, + maxSize); if (messages.empty()) // No message was generated. Create an empty placeholder so we // dont' repeat the work later. @@ -675,9 +693,10 @@ ValidatorList::sendValidatorList( HashRouter& hashRouter, beast::Journal j) { - std::size_t const messageVersion = peer.supportsFeature(ProtocolFeature::ValidatorList2Propagation) ? 2 - : peer.supportsFeature(ProtocolFeature::ValidatorListPropagation) ? 1 - : 0; + std::size_t const messageVersion = + peer.supportsFeature(ProtocolFeature::ValidatorList2Propagation) ? 2 + : peer.supportsFeature(ProtocolFeature::ValidatorListPropagation) ? 1 + : 0; if (!messageVersion) return; auto const [newPeerSequence, numVLs] = buildValidatorListMessages( @@ -703,21 +722,26 @@ ValidatorList::sendValidatorList( } // The only way sent wil be false is if the messages was too big, and // thus there will only be one entry without a message - XRPL_ASSERT(sent || messages.size() == 1, "xrpl::ValidatorList::sendValidatorList : sent or one message"); + XRPL_ASSERT( + sent || messages.size() == 1, + "xrpl::ValidatorList::sendValidatorList : sent or one message"); if (sent) { if (messageVersion > 1) - JLOG(j.debug()) << "Sent " << messages.size() << " validator list collection(s) containing " << numVLs - << " validator list(s) for " << strHex(publisherKey) << " with sequence range " - << peerSequence << ", " << newPeerSequence << " to " << peer.fingerprint(); + JLOG(j.debug()) << "Sent " << messages.size() + << " validator list collection(s) containing " << numVLs + << " validator list(s) for " << strHex(publisherKey) + << " with sequence range " << peerSequence << ", " + << newPeerSequence << " to " << peer.fingerprint(); else { XRPL_ASSERT( numVLs == 1, "xrpl::ValidatorList::sendValidatorList : one validator " "list"); - JLOG(j.debug()) << "Sent validator list for " << strHex(publisherKey) << " with sequence " - << newPeerSequence << " to " << peer.fingerprint(); + JLOG(j.debug()) << "Sent validator list for " << strHex(publisherKey) + << " with sequence " << newPeerSequence << " to " + << peer.fingerprint(); } } } @@ -738,7 +762,16 @@ ValidatorList::sendValidatorList( { std::vector messages; sendValidatorList( - peer, peerSequence, publisherKey, maxSequence, rawVersion, rawManifest, blobInfos, messages, hashRouter, j); + peer, + peerSequence, + publisherKey, + maxSequence, + rawVersion, + rawManifest, + blobInfos, + messages, + hashRouter, + j); } // static @@ -809,7 +842,8 @@ ValidatorList::broadcastBlobs( { if (blobInfos.empty()) buildBlobInfos(blobInfos, lists); - auto const v2 = peer->supportsFeature(ProtocolFeature::ValidatorList2Propagation); + auto const v2 = + peer->supportsFeature(ProtocolFeature::ValidatorList2Propagation); sendValidatorList( *peer, peerSequence, @@ -873,7 +907,14 @@ ValidatorList::applyListsAndBroadcast( { auto const& pubCollection = publisherLists_[*result.publisherKey]; - broadcastBlobs(*result.publisherKey, pubCollection, *pubCollection.maxSequence, hash, overlay, hashRouter, j_); + broadcastBlobs( + *result.publisherKey, + pubCollection, + *pubCollection.maxSequence, + hash, + overlay, + hashRouter, + j_); } return result; @@ -887,7 +928,8 @@ ValidatorList::applyLists( std::string siteUri, std::optional const& hash /* = {} */) { - if (std::count(std::begin(supportedListVersions), std::end(supportedListVersions), version) != 1) + if (std::count(std::begin(supportedListVersions), std::end(supportedListVersions), version) != + 1) return PublisherListStats{ListDisposition::unsupported_version}; std::lock_guard lock{mutex_}; @@ -895,11 +937,19 @@ ValidatorList::applyLists( PublisherListStats result; for (auto const& blobInfo : blobs) { - auto stats = - applyList(manifest, blobInfo.manifest, blobInfo.blob, blobInfo.signature, version, siteUri, hash, lock); + auto stats = applyList( + manifest, + blobInfo.manifest, + blobInfo.blob, + blobInfo.signature, + version, + siteUri, + hash, + lock); if (stats.bestDisposition() < result.bestDisposition() || - (stats.bestDisposition() == result.bestDisposition() && stats.sequence > result.sequence)) + (stats.bestDisposition() == result.bestDisposition() && + stats.sequence > result.sequence)) { stats.mergeDispositions(result); result = std::move(stats); @@ -990,13 +1040,16 @@ ValidatorList::updatePublisherList( if (!m || !keyListings_.count(m->masterKey)) { - JLOG(j_.warn()) << "List for " << strHex(pubKey) << " contained untrusted validator manifest"; + JLOG(j_.warn()) << "List for " << strHex(pubKey) + << " contained untrusted validator manifest"; continue; } - if (auto const r = validatorManifests_.applyManifest(std::move(*m)); r == ManifestDisposition::invalid) + if (auto const r = validatorManifests_.applyManifest(std::move(*m)); + r == ManifestDisposition::invalid) { - JLOG(j_.warn()) << "List for " << strHex(pubKey) << " contained invalid validator manifest"; + JLOG(j_.warn()) << "List for " << strHex(pubKey) + << " contained invalid validator manifest"; } } } @@ -1050,11 +1103,13 @@ ValidatorList::applyList( { auto const& pubCollection = publisherLists_[pubKey]; if (pubCollection.maxSequence && - (result == ListDisposition::same_sequence || result == ListDisposition::known_sequence)) + (result == ListDisposition::same_sequence || + result == ListDisposition::known_sequence)) { // We've seen something valid list for this publisher // already, so return what we know about it. - return PublisherListStats{result, pubKey, pubCollection.status, *pubCollection.maxSequence}; + return PublisherListStats{ + result, pubKey, pubCollection.status, *pubCollection.maxSequence}; } } return PublisherListStats{result}; @@ -1063,11 +1118,12 @@ ValidatorList::applyList( // Update publisher's list auto& pubCollection = publisherLists_[pubKey]; auto const sequence = list[jss::sequence].asUInt(); - auto const accepted = (result == ListDisposition::accepted || result == ListDisposition::expired); + auto const accepted = + (result == ListDisposition::accepted || result == ListDisposition::expired); if (accepted) - pubCollection.status = - result == ListDisposition::accepted ? PublisherStatus::available : PublisherStatus::expired; + pubCollection.status = result == ListDisposition::accepted ? PublisherStatus::available + : PublisherStatus::expired; pubCollection.rawManifest = globalManifest; if (!pubCollection.maxSequence || sequence > *pubCollection.maxSequence) pubCollection.maxSequence = sequence; @@ -1089,15 +1145,18 @@ ValidatorList::applyList( // Remove the entry in "remaining" pubCollection.remaining.erase(sequence); // Done - XRPL_ASSERT(publisher.sequence == sequence, "xrpl::ValidatorList::applyList : publisher sequence match"); + XRPL_ASSERT( + publisher.sequence == sequence, + "xrpl::ValidatorList::applyList : publisher sequence match"); } else { auto& publisher = accepted ? pubCollection.current : pubCollection.remaining[sequence]; publisher.sequence = sequence; - publisher.validFrom = TimeKeeper::time_point{ - TimeKeeper::duration{list.isMember(jss::effective) ? list[jss::effective].asUInt() : 0}}; - publisher.validUntil = TimeKeeper::time_point{TimeKeeper::duration{list[jss::expiration].asUInt()}}; + publisher.validFrom = TimeKeeper::time_point{TimeKeeper::duration{ + list.isMember(jss::effective) ? list[jss::effective].asUInt() : 0}}; + publisher.validUntil = + TimeKeeper::time_point{TimeKeeper::duration{list[jss::expiration].asUInt()}}; publisher.siteUri = std::move(siteUri); publisher.rawBlob = blob; publisher.rawSignature = signature; @@ -1118,11 +1177,13 @@ ValidatorList::applyList( if (val.isObject() && val.isMember(jss::validation_public_key) && val[jss::validation_public_key].isString()) { - std::optional const ret = strUnHex(val[jss::validation_public_key].asString()); + std::optional const ret = + strUnHex(val[jss::validation_public_key].asString()); if (!ret || !publicKeyType(makeSlice(*ret))) { - JLOG(j_.error()) << "Invalid node identity: " << val[jss::validation_public_key].asString(); + JLOG(j_.error()) + << "Invalid node identity: " << val[jss::validation_public_key].asString(); } else { @@ -1147,7 +1208,8 @@ ValidatorList::applyList( pubCollection.rawVersion = std::max(pubCollection.rawVersion, 2u); } - PublisherListStats const applyResult{result, pubKey, pubCollection.status, *pubCollection.maxSequence}; + PublisherListStats const applyResult{ + result, pubKey, pubCollection.status, *pubCollection.maxSequence}; if (accepted) { @@ -1249,14 +1311,16 @@ ValidatorList::verify( if (!r.parse(data, list)) return {ListDisposition::invalid, masterPubKey}; - if (list.isMember(jss::sequence) && list[jss::sequence].isInt() && list.isMember(jss::expiration) && - list[jss::expiration].isInt() && (!list.isMember(jss::effective) || list[jss::effective].isInt()) && + if (list.isMember(jss::sequence) && list[jss::sequence].isInt() && + list.isMember(jss::expiration) && list[jss::expiration].isInt() && + (!list.isMember(jss::effective) || list[jss::effective].isInt()) && list.isMember(jss::validators) && list[jss::validators].isArray()) { auto const sequence = list[jss::sequence].asUInt(); - auto const validFrom = TimeKeeper::time_point{ - TimeKeeper::duration{list.isMember(jss::effective) ? list[jss::effective].asUInt() : 0}}; - auto const validUntil = TimeKeeper::time_point{TimeKeeper::duration{list[jss::expiration].asUInt()}}; + auto const validFrom = TimeKeeper::time_point{TimeKeeper::duration{ + list.isMember(jss::effective) ? list[jss::effective].asUInt() : 0}}; + auto const validUntil = + TimeKeeper::time_point{TimeKeeper::duration{list[jss::expiration].asUInt()}}; auto const now = timeKeeper_.now(); auto const& listCollection = publisherLists_[masterPubKey]; if (validUntil <= validFrom) @@ -1548,7 +1612,8 @@ ValidatorList::getJson() const appendList(future, r); // Race conditions can happen, so make this check "fuzzy" XRPL_ASSERT( - future.validFrom > timeKeeper_.now() + 600s, "xrpl::ValidatorList::getJson : minimum valid from"); + future.validFrom > timeKeeper_.now() + 600s, + "xrpl::ValidatorList::getJson : minimum valid from"); } if (remaining.size()) curr[jss::remaining] = std::move(remaining); @@ -1595,13 +1660,14 @@ ValidatorList::for_each_listed(std::function func) } void -ValidatorList::for_each_available(std::function const& blobInfos, - PublicKey const& pubKey, - std::size_t maxSequence, - uint256 const& hash)> func) const +ValidatorList::for_each_available( + std::function const& blobInfos, + PublicKey const& pubKey, + std::size_t maxSequence, + uint256 const& hash)> func) const { std::shared_lock read_lock{mutex_}; @@ -1609,7 +1675,9 @@ ValidatorList::for_each_available(std::function -ValidatorList::getAvailable(std::string_view pubKey, std::optional forceVersion /* = {} */) +ValidatorList::getAvailable( + std::string_view pubKey, + std::optional forceVersion /* = {} */) { std::shared_lock read_lock{mutex_}; @@ -1646,7 +1716,10 @@ ValidatorList::getAvailable(std::string_view pubKey, std::optional 0) @@ -1688,7 +1761,8 @@ ValidatorList::calculateQuorum(std::size_t unlSize, std::size_t effectiveUnlSize auto const errorThreshold = std::min( listThreshold_, // publisherLists_.size() - listThreshold_ + 1); - XRPL_ASSERT(errorThreshold > 0, "xrpl::ValidatorList::calculateQuorum : nonzero error threshold"); + XRPL_ASSERT( + errorThreshold > 0, "xrpl::ValidatorList::calculateQuorum : nonzero error threshold"); if (unavailable >= errorThreshold) return std::numeric_limits::max(); } @@ -1727,7 +1801,8 @@ ValidatorList::calculateQuorum(std::size_t unlSize, std::size_t effectiveUnlSize // Note that the negative UNL protocol introduced the // AbsoluteMinimumQuorum which is 60% of the original UNL size. The // effective quorum should not be lower than it. - return static_cast(std::max(std::ceil(effectiveUnlSize * 0.8f), std::ceil(unlSize * 0.6f))); + return static_cast( + std::max(std::ceil(effectiveUnlSize * 0.8f), std::ceil(unlSize * 0.6f))); } TrustChanges @@ -1758,7 +1833,8 @@ ValidatorList::updateTrusted( if (iter != remaining.end() && iter->second.validFrom <= closeTime) { // Find the LAST candidate that is ready to go live. - for (auto next = std::next(iter); next != remaining.end() && next->second.validFrom <= closeTime; + for (auto next = std::next(iter); + next != remaining.end() && next->second.validFrom <= closeTime; ++iter, ++next) { XRPL_ASSERT( @@ -1775,13 +1851,17 @@ ValidatorList::updateTrusted( auto sequence = iter->first; auto& candidate = iter->second; auto& current = collection.current; - XRPL_ASSERT(candidate.validFrom <= closeTime, "xrpl::ValidatorList::updateTrusted : maximum time"); + XRPL_ASSERT( + candidate.validFrom <= closeTime, + "xrpl::ValidatorList::updateTrusted : maximum time"); auto const oldList = current.list; current = std::move(candidate); if (collection.status != PublisherStatus::available) collection.status = PublisherStatus::available; - XRPL_ASSERT(current.sequence == sequence, "xrpl::ValidatorList::updateTrusted : sequence match"); + XRPL_ASSERT( + current.sequence == sequence, + "xrpl::ValidatorList::updateTrusted : sequence match"); // If the list is expired, remove the validators so they don't // get processed in. The expiration check below will do the rest // of the work @@ -1804,7 +1884,8 @@ ValidatorList::updateTrusted( // Remove if expired // ValidatorLists specified in the local config file never expire. // Hence, the below steps are not relevant for localPublisherList - if (collection.status == PublisherStatus::available && collection.current.validUntil <= closeTime) + if (collection.status == PublisherStatus::available && + collection.current.validUntil <= closeTime) { removePublisherList(lock, pubKey, PublisherStatus::expired); ops.setUNLBlocked(); @@ -1830,7 +1911,9 @@ ValidatorList::updateTrusted( } else { - XRPL_ASSERT(kit->second >= listThreshold_, "xrpl::ValidatorList::updateTrusted : count meets threshold"); + XRPL_ASSERT( + kit->second >= listThreshold_, + "xrpl::ValidatorList::updateTrusted : count meets threshold"); ++it; } } @@ -1884,13 +1967,14 @@ ValidatorList::updateTrusted( } quorum_ = calculateQuorum(unlSize, effectiveUnlSize, seenSize); - JLOG(j_.debug()) << "Using quorum of " << quorum_ << " for new set of " << unlSize << " trusted validators (" - << trustChanges.added.size() << " added, " << trustChanges.removed.size() << " removed)"; + JLOG(j_.debug()) << "Using quorum of " << quorum_ << " for new set of " << unlSize + << " trusted validators (" << trustChanges.added.size() << " added, " + << trustChanges.removed.size() << " removed)"; if (unlSize < quorum_) { - JLOG(j_.warn()) << "New quorum of " << quorum_ << " exceeds the number of trusted validators (" << unlSize - << ")"; + JLOG(j_.warn()) << "New quorum of " << quorum_ + << " exceeds the number of trusted validators (" << unlSize << ")"; } if ((publisherLists_.size() || localPublisherList.list.size()) && unlSize == 0) @@ -1944,7 +2028,8 @@ ValidatorList::negativeUNLFilter(std::vector>&& va ret.begin(), ret.end(), [&](auto const& v) -> bool { - if (auto const masterKey = getTrustedKey(read_lock, v->getSignerPublic()); masterKey) + if (auto const masterKey = getTrustedKey(read_lock, v->getSignerPublic()); + masterKey) { return negativeUNL_.count(*masterKey); } diff --git a/src/xrpld/app/misc/detail/ValidatorSite.cpp b/src/xrpld/app/misc/detail/ValidatorSite.cpp index 7d440028cf..fb68bf5ef4 100644 --- a/src/xrpld/app/misc/detail/ValidatorSite.cpp +++ b/src/xrpld/app/misc/detail/ValidatorSite.cpp @@ -66,7 +66,10 @@ ValidatorSite::Site::Site(std::string uri) { } -ValidatorSite::ValidatorSite(Application& app, std::optional j, std::chrono::seconds timeout) +ValidatorSite::ValidatorSite( + Application& app, + std::optional j, + std::chrono::seconds timeout) : app_{app} , j_{j ? *j : app_.logs().journal("ValidatorSite")} , timer_{app_.getIOContext()} @@ -112,7 +115,9 @@ ValidatorSite::load(std::vector const& siteURIs) } bool -ValidatorSite::load(std::vector const& siteURIs, std::lock_guard const& lock_sites) +ValidatorSite::load( + std::vector const& siteURIs, + std::lock_guard const& lock_sites) { // If no sites are provided, act as if a site failed to load. if (siteURIs.empty()) @@ -181,10 +186,13 @@ ValidatorSite::stop() } void -ValidatorSite::setTimer(std::lock_guard const& site_lock, std::lock_guard const& state_lock) +ValidatorSite::setTimer( + std::lock_guard const& site_lock, + std::lock_guard const& state_lock) { - auto next = std::min_element( - sites_.begin(), sites_.end(), [](Site const& a, Site const& b) { return a.nextRefresh < b.nextRefresh; }); + auto next = std::min_element(sites_.begin(), sites_.end(), [](Site const& a, Site const& b) { + return a.nextRefresh < b.nextRefresh; + }); if (next != sites_.end()) { @@ -192,7 +200,8 @@ ValidatorSite::setTimer(std::lock_guard const& site_lock, std::lock_ cv_.notify_all(); timer_.expires_at(next->nextRefresh); auto idx = std::distance(sites_.begin(), next); - timer_.async_wait([this, idx](boost::system::error_code const& ec) { this->onTimer(idx, ec); }); + timer_.async_wait( + [this, idx](boost::system::error_code const& ec) { this->onTimer(idx, ec); }); } } @@ -217,13 +226,15 @@ ValidatorSite::makeRequest( { } }; - auto onFetch = [this, siteIdx, timeoutCancel]( - error_code const& err, endpoint_type const& endpoint, detail::response_type&& resp) { - timeoutCancel(); - onSiteFetch(err, endpoint, std::move(resp), siteIdx); - }; + auto onFetch = + [this, siteIdx, timeoutCancel]( + error_code const& err, endpoint_type const& endpoint, detail::response_type&& resp) { + timeoutCancel(); + onSiteFetch(err, endpoint, std::move(resp), siteIdx); + }; - auto onFetchFile = [this, siteIdx, timeoutCancel](error_code const& err, std::string const& resp) { + auto onFetchFile = [this, siteIdx, timeoutCancel]( + error_code const& err, std::string const& resp) { timeoutCancel(); onTextFetch(err, resp, siteIdx); }; @@ -258,7 +269,8 @@ ValidatorSite::makeRequest( else { BOOST_ASSERT(resource->pUrl.scheme == "file"); - sp = std::make_shared(resource->pUrl.path, app_.getIOContext(), onFetchFile); + sp = std::make_shared( + resource->pUrl.path, app_.getIOContext(), onFetchFile); } sites_[siteIdx].lastRequestSuccessful = false; @@ -268,7 +280,9 @@ ValidatorSite::makeRequest( // than requestTimeout_ to complete std::lock_guard lock_state{state_mutex_}; timer_.expires_after(requestTimeout_); - timer_.async_wait([this, siteIdx](boost::system::error_code const& ec) { this->onRequestTimeout(siteIdx, ec); }); + timer_.async_wait([this, siteIdx](boost::system::error_code const& ec) { + this->onRequestTimeout(siteIdx, ec); + }); } void @@ -322,7 +336,10 @@ ValidatorSite::onTimer(std::size_t siteIdx, error_code const& ec) { JLOG(j_.error()) << "Exception in " << __func__ << ": " << ex.what(); onSiteFetch( - boost::system::error_code{-1, boost::system::generic_category()}, {}, detail::response_type{}, siteIdx); + boost::system::error_code{-1, boost::system::generic_category()}, + {}, + detail::response_type{}, + siteIdx); } } @@ -337,7 +354,8 @@ ValidatorSite::parseJsonResponse( Json::Value body; if (!r.parse(res.data(), body)) { - JLOG(j_.warn()) << "Unable to parse JSON response from " << sites_[siteIdx].activeResource->uri; + JLOG(j_.warn()) << "Unable to parse JSON response from " + << sites_[siteIdx].activeResource->uri; throw std::runtime_error{"bad json"}; } return body; @@ -345,8 +363,9 @@ ValidatorSite::parseJsonResponse( auto const [valid, version, blobs] = [&body]() { // Check the easy fields first - bool valid = body.isObject() && body.isMember(jss::manifest) && body[jss::manifest].isString() && - body.isMember(jss::version) && body[jss::version].isInt(); + bool valid = body.isObject() && body.isMember(jss::manifest) && + body[jss::manifest].isString() && body.isMember(jss::version) && + body[jss::version].isInt(); // Check the version-specific blob & signature fields std::uint32_t version; std::vector blobs; @@ -361,18 +380,22 @@ ValidatorSite::parseJsonResponse( if (!valid) { - JLOG(j_.warn()) << "Missing fields in JSON response from " << sites_[siteIdx].activeResource->uri; + JLOG(j_.warn()) << "Missing fields in JSON response from " + << sites_[siteIdx].activeResource->uri; throw std::runtime_error{"missing fields"}; } auto const manifest = body[jss::manifest].asString(); - XRPL_ASSERT(version == body[jss::version].asUInt(), "xrpl::ValidatorSite::parseJsonResponse : version match"); + XRPL_ASSERT( + version == body[jss::version].asUInt(), + "xrpl::ValidatorSite::parseJsonResponse : version match"); auto const& uri = sites_[siteIdx].activeResource->uri; auto const hash = sha512Half(manifest, blobs, version); auto const applyResult = app_.validators().applyListsAndBroadcast( manifest, version, blobs, uri, hash, app_.overlay(), app_.getHashRouter(), app_.getOPs()); - sites_[siteIdx].lastRefreshStatus.emplace(Site::Status{clock_type::now(), applyResult.bestDisposition(), ""}); + sites_[siteIdx].lastRefreshStatus.emplace( + Site::Status{clock_type::now(), applyResult.bestDisposition(), ""}); for (auto const& [disp, count] : applyResult.dispositions) { @@ -382,28 +405,34 @@ ValidatorSite::parseJsonResponse( JLOG(j_.debug()) << "Applied " << count << " new validator list(s) from " << uri; break; case ListDisposition::expired: - JLOG(j_.debug()) << "Applied " << count << " expired validator list(s) from " << uri; + JLOG(j_.debug()) << "Applied " << count << " expired validator list(s) from " + << uri; break; case ListDisposition::same_sequence: - JLOG(j_.debug()) << "Ignored " << count << " validator list(s) with current sequence from " << uri; + JLOG(j_.debug()) << "Ignored " << count + << " validator list(s) with current sequence from " << uri; break; case ListDisposition::pending: - JLOG(j_.debug()) << "Processed " << count << " future validator list(s) from " << uri; + JLOG(j_.debug()) << "Processed " << count << " future validator list(s) from " + << uri; break; case ListDisposition::known_sequence: - JLOG(j_.debug()) << "Ignored " << count << " validator list(s) with future known sequence from " << uri; + JLOG(j_.debug()) << "Ignored " << count + << " validator list(s) with future known sequence from " << uri; break; case ListDisposition::stale: JLOG(j_.warn()) << "Ignored " << count << "stale validator list(s) from " << uri; break; case ListDisposition::untrusted: - JLOG(j_.warn()) << "Ignored " << count << " untrusted validator list(s) from " << uri; + JLOG(j_.warn()) << "Ignored " << count << " untrusted validator list(s) from " + << uri; break; case ListDisposition::invalid: JLOG(j_.warn()) << "Ignored " << count << " invalid validator list(s) from " << uri; break; case ListDisposition::unsupported_version: - JLOG(j_.warn()) << "Ignored " << count << " unsupported version validator list(s) from " << uri; + JLOG(j_.warn()) << "Ignored " << count + << " unsupported version validator list(s) from " << uri; break; default: BOOST_ASSERT(false); @@ -413,8 +442,10 @@ ValidatorSite::parseJsonResponse( if (body.isMember(jss::refresh_interval) && body[jss::refresh_interval].isNumeric()) { using namespace std::chrono_literals; - std::chrono::minutes const refresh = - std::clamp(std::chrono::minutes{body[jss::refresh_interval].asUInt()}, 1min, std::chrono::minutes{24h}); + std::chrono::minutes const refresh = std::clamp( + std::chrono::minutes{body[jss::refresh_interval].asUInt()}, + 1min, + std::chrono::minutes{24h}); sites_[siteIdx].refreshInterval = refresh; sites_[siteIdx].nextRefresh = clock_type::now() + sites_[siteIdx].refreshInterval; } @@ -437,12 +468,14 @@ ValidatorSite::processRedirect( if (sites_[siteIdx].redirCount == max_redirects) { - JLOG(j_.warn()) << "Exceeded max redirects for validator list at " << sites_[siteIdx].loadedResource->uri; + JLOG(j_.warn()) << "Exceeded max redirects for validator list at " + << sites_[siteIdx].loadedResource->uri; throw std::runtime_error{"max redirects"}; } - JLOG(j_.debug()) << "Got redirect for validator list from " << sites_[siteIdx].activeResource->uri - << " to new location " << res[field::location]; + JLOG(j_.debug()) << "Got redirect for validator list from " + << sites_[siteIdx].activeResource->uri << " to new location " + << res[field::location]; try { @@ -470,7 +503,8 @@ ValidatorSite::onSiteFetch( { if (endpoint != endpoint_type{}) sites_[siteIdx].lastRequestEndpoint = endpoint; - JLOG(j_.debug()) << "Got completion for " << sites_[siteIdx].activeResource->uri << " " << endpoint; + JLOG(j_.debug()) << "Got completion for " << sites_[siteIdx].activeResource->uri << " " + << endpoint; auto onError = [&](std::string const& errMsg, bool retry) { sites_[siteIdx].lastRefreshStatus.emplace( Site::Status{clock_type::now(), ListDisposition::invalid, errMsg}); @@ -483,8 +517,8 @@ ValidatorSite::onSiteFetch( }; if (ec) { - JLOG(j_.warn()) << "Problem retrieving from " << sites_[siteIdx].activeResource->uri << " " << endpoint - << " " << ec.value() << ":" << ec.message(); + JLOG(j_.warn()) << "Problem retrieving from " << sites_[siteIdx].activeResource->uri + << " " << endpoint << " " << ec.value() << ":" << ec.message(); onError("fetch error", true); } else @@ -508,7 +542,8 @@ ValidatorSite::onSiteFetch( "xrpl::ValidatorSite::onSiteFetch : non-null " "validator"); // for perm redirects, also update our starting URI - if (res.result() == status::moved_permanently || res.result() == status::permanent_redirect) + if (res.result() == status::moved_permanently || + res.result() == status::permanent_redirect) { sites_[siteIdx].startingResource = newLocation; } @@ -517,8 +552,9 @@ ValidatorSite::onSiteFetch( // state update/notify below } default: { - JLOG(j_.warn()) << "Request for validator list at " << sites_[siteIdx].activeResource->uri - << " " << endpoint << " returned bad status: " << res.result_int(); + JLOG(j_.warn()) << "Request for validator list at " + << sites_[siteIdx].activeResource->uri << " " << endpoint + << " returned bad status: " << res.result_int(); onError("bad result code", true); } } @@ -540,7 +576,10 @@ ValidatorSite::onSiteFetch( } void -ValidatorSite::onTextFetch(boost::system::error_code const& ec, std::string const& res, std::size_t siteIdx) +ValidatorSite::onTextFetch( + boost::system::error_code const& ec, + std::string const& res, + std::size_t siteIdx) { std::lock_guard lock_sites{sites_mutex_}; { @@ -548,8 +587,8 @@ ValidatorSite::onTextFetch(boost::system::error_code const& ec, std::string cons { if (ec) { - JLOG(j_.warn()) << "Problem retrieving from " << sites_[siteIdx].activeResource->uri << " " - << ec.value() << ": " << ec.message(); + JLOG(j_.warn()) << "Problem retrieving from " << sites_[siteIdx].activeResource->uri + << " " << ec.value() << ": " << ec.message(); throw std::runtime_error{"fetch error"}; } diff --git a/src/xrpld/app/misc/detail/WorkBase.h b/src/xrpld/app/misc/detail/WorkBase.h index e5fd72f118..35f04efe00 100644 --- a/src/xrpld/app/misc/detail/WorkBase.h +++ b/src/xrpld/app/misc/detail/WorkBase.h @@ -24,7 +24,8 @@ protected: using endpoint_type = boost::asio::ip::tcp::endpoint; public: - using callback_type = std::function; + using callback_type = + std::function; protected: using socket_type = boost::asio::ip::tcp::socket; @@ -130,14 +131,20 @@ WorkBase::run() { if (!strand_.running_in_this_thread()) return boost::asio::post( - ios_, boost::asio::bind_executor(strand_, std::bind(&WorkBase::run, impl().shared_from_this()))); + ios_, + boost::asio::bind_executor( + strand_, std::bind(&WorkBase::run, impl().shared_from_this()))); resolver_.async_resolve( host_, port_, boost::asio::bind_executor( strand_, - std::bind(&WorkBase::onResolve, impl().shared_from_this(), std::placeholders::_1, std::placeholders::_2))); + std::bind( + &WorkBase::onResolve, + impl().shared_from_this(), + std::placeholders::_1, + std::placeholders::_2))); } template @@ -149,7 +156,8 @@ WorkBase::cancel() return boost::asio::post( ios_, - boost::asio::bind_executor(strand_, std::bind(&WorkBase::cancel, impl().shared_from_this()))); + boost::asio::bind_executor( + strand_, std::bind(&WorkBase::cancel, impl().shared_from_this()))); } error_code ec; @@ -180,7 +188,11 @@ WorkBase::onResolve(error_code const& ec, results_type results) results, boost::asio::bind_executor( strand_, - std::bind(&WorkBase::onConnect, impl().shared_from_this(), std::placeholders::_1, std::placeholders::_2))); + std::bind( + &WorkBase::onConnect, + impl().shared_from_this(), + std::placeholders::_1, + std::placeholders::_2))); } template @@ -209,7 +221,8 @@ WorkBase::onStart() impl().stream(), req_, boost::asio::bind_executor( - strand_, std::bind(&WorkBase::onRequest, impl().shared_from_this(), std::placeholders::_1))); + strand_, + std::bind(&WorkBase::onRequest, impl().shared_from_this(), std::placeholders::_1))); } template @@ -224,7 +237,8 @@ WorkBase::onRequest(error_code const& ec) readBuf_, res_, boost::asio::bind_executor( - strand_, std::bind(&WorkBase::onResponse, impl().shared_from_this(), std::placeholders::_1))); + strand_, + std::bind(&WorkBase::onResponse, impl().shared_from_this(), std::placeholders::_1))); } template diff --git a/src/xrpld/app/misc/detail/WorkFile.h b/src/xrpld/app/misc/detail/WorkFile.h index 8d2d4edb50..896d7ddc71 100644 --- a/src/xrpld/app/misc/detail/WorkFile.h +++ b/src/xrpld/app/misc/detail/WorkFile.h @@ -60,7 +60,8 @@ WorkFile::run() { if (!strand_.running_in_this_thread()) return boost::asio::post( - ios_, boost::asio::bind_executor(strand_, std::bind(&WorkFile::run, shared_from_this()))); + ios_, + boost::asio::bind_executor(strand_, std::bind(&WorkFile::run, shared_from_this()))); error_code ec; auto const fileContents = getFileContents(ec, path_, megabytes(1)); diff --git a/src/xrpld/app/misc/detail/setup_HashRouter.cpp b/src/xrpld/app/misc/detail/setup_HashRouter.cpp new file mode 100644 index 0000000000..a0e63dd67e --- /dev/null +++ b/src/xrpld/app/misc/detail/setup_HashRouter.cpp @@ -0,0 +1,42 @@ +#include +#include + +#include + +namespace xrpl { + +HashRouter::Setup +setup_HashRouter(Config const& config) +{ + using namespace std::chrono; + + HashRouter::Setup setup; + auto const& section = config.section("hashrouter"); + + std::int32_t tmp{}; + + if (set(tmp, "hold_time", section)) + { + if (tmp < 12) + Throw( + "HashRouter hold time must be at least 12 seconds (the " + "approximate validation time for three ledgers)."); + setup.holdTime = seconds(tmp); + } + if (set(tmp, "relay_time", section)) + { + if (tmp < 8) + Throw( + "HashRouter relay time must be at least 8 seconds (the " + "approximate validation time for two ledgers)."); + setup.relayTime = seconds(tmp); + } + if (setup.relayTime > setup.holdTime) + { + Throw("HashRouter relay time must be less than or equal to hold time"); + } + + return setup; +} + +} // namespace xrpl diff --git a/src/xrpld/app/misc/make_NetworkOPs.h b/src/xrpld/app/misc/make_NetworkOPs.h new file mode 100644 index 0000000000..7dce966f04 --- /dev/null +++ b/src/xrpld/app/misc/make_NetworkOPs.h @@ -0,0 +1,32 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include + +#include + +namespace xrpl { + +class LedgerMaster; +class ValidatorKeys; + +std::unique_ptr +make_NetworkOPs( + ServiceRegistry& registry, + NetworkOPs::clock_type& clock, + bool standalone, + std::size_t minPeerCount, + bool start_valid, + JobQueue& job_queue, + LedgerMaster& ledgerMaster, + ValidatorKeys const& validatorKeys, + boost::asio::io_context& io_svc, + beast::Journal journal, + beast::insight::Collector::ptr const& collector); + +} // namespace xrpl diff --git a/src/xrpld/app/misc/setup_HashRouter.h b/src/xrpld/app/misc/setup_HashRouter.h new file mode 100644 index 0000000000..9b767d0170 --- /dev/null +++ b/src/xrpld/app/misc/setup_HashRouter.h @@ -0,0 +1,14 @@ +#pragma once + +#include + +namespace xrpl { + +// Forward declaration +class Config; + +/** Create HashRouter setup from configuration */ +HashRouter::Setup +setup_HashRouter(Config const& config); + +} // namespace xrpl diff --git a/src/xrpld/app/paths/AMMLiquidity.h b/src/xrpld/app/paths/AMMLiquidity.h index 441c3b6e3d..5c3ff2a8e6 100644 --- a/src/xrpld/app/paths/AMMLiquidity.h +++ b/src/xrpld/app/paths/AMMLiquidity.h @@ -1,13 +1,12 @@ #pragma once -#include -#include -#include - #include #include #include #include +#include +#include +#include namespace xrpl { diff --git a/src/xrpld/app/paths/AccountCurrencies.cpp b/src/xrpld/app/paths/AccountCurrencies.cpp index 8e51999018..92ba61e00e 100644 --- a/src/xrpld/app/paths/AccountCurrencies.cpp +++ b/src/xrpld/app/paths/AccountCurrencies.cpp @@ -3,7 +3,10 @@ namespace xrpl { hash_set -accountSourceCurrencies(AccountID const& account, std::shared_ptr const& lrCache, bool includeXRP) +accountSourceCurrencies( + AccountID const& account, + std::shared_ptr const& lrCache, + bool includeXRP) { hash_set currencies; @@ -34,7 +37,10 @@ accountSourceCurrencies(AccountID const& account, std::shared_ptr -accountDestCurrencies(AccountID const& account, std::shared_ptr const& lrCache, bool includeXRP) +accountDestCurrencies( + AccountID const& account, + std::shared_ptr const& lrCache, + bool includeXRP) { hash_set currencies; diff --git a/src/xrpld/app/paths/AccountCurrencies.h b/src/xrpld/app/paths/AccountCurrencies.h index eb8cc92aec..d8459de7f2 100644 --- a/src/xrpld/app/paths/AccountCurrencies.h +++ b/src/xrpld/app/paths/AccountCurrencies.h @@ -7,9 +7,15 @@ namespace xrpl { hash_set -accountDestCurrencies(AccountID const& account, std::shared_ptr const& cache, bool includeXRP); +accountDestCurrencies( + AccountID const& account, + std::shared_ptr const& cache, + bool includeXRP); hash_set -accountSourceCurrencies(AccountID const& account, std::shared_ptr const& lrLedger, bool includeXRP); +accountSourceCurrencies( + AccountID const& account, + std::shared_ptr const& lrLedger, + bool includeXRP); } // namespace xrpl diff --git a/src/xrpld/app/paths/PathRequest.cpp b/src/xrpld/app/paths/PathRequest.cpp index e2a3e14485..c6d0f59ff0 100644 --- a/src/xrpld/app/paths/PathRequest.cpp +++ b/src/xrpld/app/paths/PathRequest.cpp @@ -1,10 +1,7 @@ #include -#include -#include #include #include #include -#include #include #include #include @@ -14,6 +11,9 @@ #include #include #include +#include +#include +#include #include #include @@ -86,7 +86,8 @@ PathRequest::~PathRequest() full += "ms"; } stream << iIdentifier << " complete:" << fast << full - << " total:" << duration_cast(steady_clock::now() - created_).count() << "ms"; + << " total:" << duration_cast(steady_clock::now() - created_).count() + << "ms"; } bool @@ -285,7 +286,8 @@ PathRequest::parseJson(Json::Value const& jvParams) convert_all_ = saDstAmount == STAmount(saDstAmount.issue(), 1u, 0, true); if ((saDstAmount.getCurrency().isZero() && saDstAmount.getIssuer().isNonZero()) || - (saDstAmount.getCurrency() == badCurrency()) || (!convert_all_ && saDstAmount <= beast::zero)) + (saDstAmount.getCurrency() == badCurrency()) || + (!convert_all_ && saDstAmount <= beast::zero)) { jvStatus = rpcError(rpcDST_AMT_MALFORMED); return PFR_PJ_INVALID; @@ -449,7 +451,15 @@ PathRequest::getPathFinder( if (i != currency_map.end()) return i->second; auto pathfinder = std::make_unique( - cache, *raSrcAccount, *raDstAccount, currency, std::nullopt, dst_amount, saSendMax, domain, app_); + cache, + *raSrcAccount, + *raDstAccount, + currency, + std::nullopt, + dst_amount, + saSendMax, + domain, + app_); if (pathfinder->findPaths(level, continueCallback)) pathfinder->computePathRanks(max_paths_, continueCallback); else @@ -490,9 +500,11 @@ PathRequest::findPaths( { if (continueCallback && !continueCallback()) break; - JLOG(m_journal.debug()) << iIdentifier << " Trying to find paths: " << STAmount(issue, 1).getFullText(); + JLOG(m_journal.debug()) << iIdentifier + << " Trying to find paths: " << STAmount(issue, 1).getFullText(); - auto& pathfinder = getPathFinder(cache, currency_map, issue.currency, dst_amount, level, continueCallback); + auto& pathfinder = + getPathFinder(cache, currency_map, issue.currency, dst_amount, level, continueCallback); if (!pathfinder) { JLOG(m_journal.debug()) << iIdentifier << " No paths found"; @@ -500,8 +512,8 @@ PathRequest::findPaths( } STPath fullLiquidityPath; - auto ps = - pathfinder->getBestPaths(max_paths_, fullLiquidityPath, mContext[issue], issue.account, continueCallback); + auto ps = pathfinder->getBestPaths( + max_paths_, fullLiquidityPath, mContext[issue], issue.account, continueCallback); mContext[issue] = ps; auto const& sourceAccount = [&] { @@ -514,7 +526,8 @@ PathRequest::findPaths( return *raSrcAccount; }(); - STAmount saMaxAmount = saSendMax.value_or(STAmount(Issue{issue.currency, sourceAccount}, 1u, 0, true)); + STAmount saMaxAmount = + saSendMax.value_or(STAmount(Issue{issue.currency, sourceAccount}, 1u, 0, true)); JLOG(m_journal.debug()) << iIdentifier << " Paths found, calling rippleCalc"; @@ -554,11 +567,13 @@ PathRequest::findPaths( if (rc.result() != tesSUCCESS) { - JLOG(m_journal.warn()) << iIdentifier << " Failed with covering path " << transHuman(rc.result()); + JLOG(m_journal.warn()) + << iIdentifier << " Failed with covering path " << transHuman(rc.result()); } else { - JLOG(m_journal.debug()) << iIdentifier << " Extra path element gives " << transHuman(rc.result()); + JLOG(m_journal.debug()) + << iIdentifier << " Extra path element gives " << transHuman(rc.result()); } } @@ -582,7 +597,8 @@ PathRequest::findPaths( } else { - JLOG(m_journal.debug()) << iIdentifier << " rippleCalc returns " << transHuman(rc.result()); + JLOG(m_journal.debug()) + << iIdentifier << " rippleCalc returns " << transHuman(rc.result()); } } @@ -650,7 +666,8 @@ PathRequest::doUpdate( else if (bLastSuccess) { // decrement, if possible - if (iLevel > app_.config().PATH_SEARCH || (loaded && (iLevel > app_.config().PATH_SEARCH_FAST))) + if (iLevel > app_.config().PATH_SEARCH || + (loaded && (iLevel > app_.config().PATH_SEARCH_FAST))) --iLevel; } else diff --git a/src/xrpld/app/paths/PathRequest.h b/src/xrpld/app/paths/PathRequest.h index 864d2cb932..fde499a312 100644 --- a/src/xrpld/app/paths/PathRequest.h +++ b/src/xrpld/app/paths/PathRequest.h @@ -3,11 +3,11 @@ #include #include #include -#include #include #include #include +#include #include #include @@ -105,7 +105,11 @@ private: Returns false if the source currencies are invalid. */ bool - findPaths(std::shared_ptr const&, int const, Json::Value&, std::function const&); + findPaths( + std::shared_ptr const&, + int const, + Json::Value&, + std::function const&); int parseJson(Json::Value const&); diff --git a/src/xrpld/app/paths/PathRequests.cpp b/src/xrpld/app/paths/PathRequests.cpp index 2c1ef8cbad..35a6c7aa48 100644 --- a/src/xrpld/app/paths/PathRequests.cpp +++ b/src/xrpld/app/paths/PathRequests.cpp @@ -24,7 +24,8 @@ PathRequests::getLineCache(std::shared_ptr const& ledger, bool a std::uint32_t const lineSeq = lineCache ? lineCache->getLedger()->seq() : 0; std::uint32_t const lgrSeq = ledger->seq(); - JLOG(mJournal.debug()) << "getLineCache has cache for " << lineSeq << ", considering " << lgrSeq; + JLOG(mJournal.debug()) << "getLineCache has cache for " << lineSeq << ", considering " + << lgrSeq; if ((lineSeq == 0) || // no ledger (authoritative && (lgrSeq > lineSeq)) || // newer authoritative ledger @@ -35,7 +36,8 @@ PathRequests::getLineCache(std::shared_ptr const& ledger, bool a // Assign to the local before the member, because the member is a // weak_ptr, and will immediately discard it if there are no other // references. - lineCache_ = lineCache = std::make_shared(ledger, app_.journal("RippleLineCache")); + lineCache_ = lineCache = + std::make_shared(ledger, app_.journal("RippleLineCache")); } return lineCache; } @@ -58,7 +60,8 @@ PathRequests::updateAll(std::shared_ptr const& inLedger) bool newRequests = app_.getLedgerMaster().isNewPathRequest(); bool mustBreak = false; - JLOG(mJournal.trace()) << "updateAll seq=" << cache->getLedger()->seq() << ", " << requests.size() << " requests"; + JLOG(mJournal.trace()) << "updateAll seq=" << cache->getLedger()->seq() << ", " + << requests.size() << " requests"; int processed = 0, removed = 0; @@ -130,14 +133,15 @@ PathRequests::updateAll(std::shared_ptr const& inLedger) // Remove any dangling weak pointers or weak // pointers that refer to this path request. - auto ret = std::remove_if(requests_.begin(), requests_.end(), [&removed, &request](auto const& wl) { - auto r = wl.lock(); + auto ret = std::remove_if( + requests_.begin(), requests_.end(), [&removed, &request](auto const& wl) { + auto r = wl.lock(); - if (r && r != request) - return false; - ++removed; - return true; - }); + if (r && r != request) + return false; + ++removed; + return true; + }); requests_.erase(ret, requests_.end()); } @@ -180,7 +184,8 @@ PathRequests::updateAll(std::shared_ptr const& inLedger) } } while (!app_.getJobQueue().isStopping()); - JLOG(mJournal.debug()) << "updateAll complete: " << processed << " processed and " << removed << " removed"; + JLOG(mJournal.debug()) << "updateAll complete: " << processed << " processed and " << removed + << " removed"; } bool @@ -238,7 +243,8 @@ PathRequests::makeLegacyPathRequest( { // This assignment must take place before the // completion function is called - req = std::make_shared(app_, completion, consumer, ++mLastIdentifier, *this, mJournal); + req = std::make_shared( + app_, completion, consumer, ++mLastIdentifier, *this, mJournal); auto [valid, jvRes] = req->doCreate(getLineCache(inLedger, false), request); @@ -268,7 +274,8 @@ PathRequests::doLegacyPathRequest( { auto cache = std::make_shared(inLedger, app_.journal("RippleLineCache")); - auto req = std::make_shared(app_, [] {}, consumer, ++mLastIdentifier, *this, mJournal); + auto req = + std::make_shared(app_, [] {}, consumer, ++mLastIdentifier, *this, mJournal); auto [valid, jvRes] = req->doCreate(cache, request); if (valid) diff --git a/src/xrpld/app/paths/PathRequests.h b/src/xrpld/app/paths/PathRequests.h index f89ca3c4da..98f4be9fd7 100644 --- a/src/xrpld/app/paths/PathRequests.h +++ b/src/xrpld/app/paths/PathRequests.h @@ -14,7 +14,10 @@ class PathRequests { public: /** A collection of all PathRequest instances. */ - PathRequests(Application& app, beast::Journal journal, beast::insight::Collector::ptr const& collector) + PathRequests( + Application& app, + beast::Journal journal, + beast::insight::Collector::ptr const& collector) : app_(app), mJournal(journal), mLastIdentifier(0) { mFast = collector->make_event("pathfind_fast"); diff --git a/src/xrpld/app/paths/Pathfinder.cpp b/src/xrpld/app/paths/Pathfinder.cpp index b64ce0cc20..254db35ea5 100644 --- a/src/xrpld/app/paths/Pathfinder.cpp +++ b/src/xrpld/app/paths/Pathfinder.cpp @@ -1,7 +1,5 @@ -#include #include #include -#include #include #include @@ -9,7 +7,9 @@ #include #include #include +#include #include +#include #include @@ -62,7 +62,10 @@ struct AccountCandidate }; bool -compareAccountCandidate(std::uint32_t seq, AccountCandidate const& first, AccountCandidate const& second) +compareAccountCandidate( + std::uint32_t seq, + AccountCandidate const& first, + AccountCandidate const& second) { if (first.priority < second.priority) return false; @@ -153,7 +156,9 @@ Pathfinder::Pathfinder( , mSrcCurrency(uSrcCurrency) , mSrcIssuer(uSrcIssuer) , mSrcAmount(srcAmount.value_or(STAmount( - Issue{uSrcCurrency, uSrcIssuer.value_or(isXRP(uSrcCurrency) ? xrpAccount() : uSrcAccount)}, + Issue{ + uSrcCurrency, + uSrcIssuer.value_or(isXRP(uSrcCurrency) ? xrpAccount() : uSrcAccount)}, 1u, 0, true))) @@ -165,7 +170,8 @@ Pathfinder::Pathfinder( , j_(app.journal("Pathfinder")) { XRPL_ASSERT( - !uSrcIssuer || isXRP(uSrcCurrency) == isXRP(uSrcIssuer.value()), "xrpl::Pathfinder::Pathfinder : valid inputs"); + !uSrcIssuer || isXRP(uSrcCurrency) == isXRP(uSrcIssuer.value()), + "xrpl::Pathfinder::Pathfinder : valid inputs"); } bool @@ -183,7 +189,8 @@ Pathfinder::findPaths(int searchLevel, std::function const& continue // below - why don't we do it each time we return false? } - if (mSrcAccount == mDstAccount && mDstAccount == mEffectiveDst && mSrcCurrency == mDstAmount.getCurrency()) + if (mSrcAccount == mDstAccount && mDstAccount == mEffectiveDst && + mSrcCurrency == mDstAmount.getCurrency()) { // No need to send to same account with same currency. JLOG(j_.debug()) << "Tried to send to same issuer"; @@ -207,8 +214,8 @@ Pathfinder::findPaths(int searchLevel, std::function const& continue auto issuerString = mSrcIssuer ? to_string(*mSrcIssuer) : std::string("none"); JLOG(j_.trace()) << "findPaths>" << " mSrcAccount=" << mSrcAccount << " mDstAccount=" << mDstAccount - << " mDstAmount=" << mDstAmount.getFullText() << " mSrcCurrency=" << mSrcCurrency - << " mSrcIssuer=" << issuerString; + << " mDstAmount=" << mDstAmount.getFullText() + << " mSrcCurrency=" << mSrcCurrency << " mSrcIssuer=" << issuerString; if (!mLedger) { @@ -245,7 +252,8 @@ Pathfinder::findPaths(int searchLevel, std::function const& continue auto const reserve = STAmount(mLedger->fees().reserve); if (mDstAmount < reserve) { - JLOG(j_.debug()) << "New account not getting enough funding: " << mDstAmount << " < " << reserve; + JLOG(j_.debug()) << "New account not getting enough funding: " << mDstAmount << " < " + << reserve; return false; } } @@ -330,7 +338,15 @@ Pathfinder::getPathLiquidity( rcInput.partialPaymentAllowed = true; auto rc = path::RippleCalc::rippleCalculate( - sandbox, mSrcAmount, minDstAmount, mDstAccount, mSrcAccount, pathSet, mDomain, app_.logs(), &rcInput); + sandbox, + mSrcAmount, + minDstAmount, + mDstAccount, + mSrcAccount, + pathSet, + mDomain, + app_.logs(), + &rcInput); // If we can't get even the minimum liquidity requested, we're done. if (rc.result() != tesSUCCESS) return rc.result(); @@ -362,7 +378,8 @@ Pathfinder::getPathLiquidity( } catch (std::exception const& e) { - JLOG(j_.info()) << "checkpath: exception (" << e.what() << ") " << path.getJson(JsonOptions::none); + JLOG(j_.info()) << "checkpath: exception (" << e.what() << ") " + << path.getJson(JsonOptions::none); return tefEXCEPTION; } } @@ -449,7 +466,8 @@ Pathfinder::rankPaths( std::vector& rankedPaths, std::function const& continueCallback) { - JLOG(j_.trace()) << "rankPaths with " << paths.size() << " candidates, and " << maxPaths << " maximum"; + JLOG(j_.trace()) << "rankPaths with " << paths.size() << " candidates, and " << maxPaths + << " maximum"; rankedPaths.clear(); rankedPaths.reserve(paths.size()); @@ -474,7 +492,8 @@ Pathfinder::rankPaths( { STAmount liquidity; uint64_t uQuality; - auto const resultCode = getPathLiquidity(currentPath, saMinDstAmount, liquidity, uQuality); + auto const resultCode = + getPathLiquidity(currentPath, saMinDstAmount, liquidity, uQuality); if (resultCode != tesSUCCESS) { JLOG(j_.debug()) << "findPaths: dropping : " << transToken(resultCode) << ": " @@ -496,7 +515,9 @@ Pathfinder::rankPaths( // length of path // A better PathRank is lower, best are sorted to the beginning. std::sort( - rankedPaths.begin(), rankedPaths.end(), [&](Pathfinder::PathRank const& a, Pathfinder::PathRank const& b) { + rankedPaths.begin(), + rankedPaths.end(), + [&](Pathfinder::PathRank const& a, Pathfinder::PathRank const& b) { // 1) Higher quality (lower cost) is better if (!convert_all_ && a.quality != b.quality) return a.quality < b.quality; @@ -522,12 +543,14 @@ Pathfinder::getBestPaths( AccountID const& srcIssuer, std::function const& continueCallback) { - JLOG(j_.debug()) << "findPaths: " << mCompletePaths.size() << " paths and " << extraPaths.size() << " extras"; + JLOG(j_.debug()) << "findPaths: " << mCompletePaths.size() << " paths and " << extraPaths.size() + << " extras"; if (mCompletePaths.empty() && extraPaths.empty()) return mCompletePaths; - XRPL_ASSERT(fullLiquidityPath.empty(), "xrpl::Pathfinder::getBestPaths : first empty path result"); + XRPL_ASSERT( + fullLiquidityPath.empty(), "xrpl::Pathfinder::getBestPaths : first empty path result"); bool const issuerIsSender = isXRP(mSrcCurrency) || (srcIssuer == mSrcAccount); std::vector extraPathRanks; @@ -615,7 +638,8 @@ Pathfinder::getBestPaths( { // We found an extra path that can move the whole amount. fullLiquidityPath = (startsWithIssuer ? removeIssuer(path) : path); - JLOG(j_.debug()) << "Found extra full path: " << fullLiquidityPath.getJson(JsonOptions::none); + JLOG(j_.debug()) << "Found extra full path: " + << fullLiquidityPath.getJson(JsonOptions::none); } else { @@ -625,7 +649,8 @@ Pathfinder::getBestPaths( if (remaining > beast::zero) { - XRPL_ASSERT(fullLiquidityPath.empty(), "xrpl::Pathfinder::getBestPaths : second empty path result"); + XRPL_ASSERT( + fullLiquidityPath.empty(), "xrpl::Pathfinder::getBestPaths : second empty path result"); JLOG(j_.info()) << "Paths could not send " << remaining << " of " << mDstAmount; } else @@ -639,8 +664,8 @@ bool Pathfinder::issueMatchesOrigin(Issue const& issue) { bool matchingCurrency = (issue.currency == mSrcCurrency); - bool matchingAccount = - isXRP(issue.currency) || (mSrcIssuer && issue.account == mSrcIssuer) || issue.account == mSrcAccount; + bool matchingAccount = isXRP(issue.currency) || (mSrcIssuer && issue.account == mSrcIssuer) || + issue.account == mSrcAccount; return matchingCurrency && matchingAccount; } @@ -686,7 +711,8 @@ Pathfinder::getPathsOut( } else if ( rspEntry.getBalance() <= beast::zero && - (!rspEntry.getLimitPeer() || -rspEntry.getBalance() >= rspEntry.getLimitPeer() || + (!rspEntry.getLimitPeer() || + -rspEntry.getBalance() >= rspEntry.getLimitPeer() || (bAuthRequired && !rspEntry.getAuth()))) { } @@ -730,7 +756,9 @@ Pathfinder::addLinks( } STPathSet& -Pathfinder::addPathsForType(PathType const& pathType, std::function const& continueCallback) +Pathfinder::addPathsForType( + PathType const& pathType, + std::function const& continueCallback) { JLOG(j_.debug()) << "addPathsForType " << CollectionAndDelimiter(pathType, ", "); // See if the set of paths for this type already exists. @@ -752,8 +780,8 @@ Pathfinder::addPathsForType(PathType const& pathType, std::function STPathSet const& parentPaths = addPathsForType(parentPathType, continueCallback); STPathSet& pathsOut = mPaths[pathType]; - JLOG(j_.debug()) << "getPaths< adding onto '" << pathTypeToString(parentPathType) << "' to get '" - << pathTypeToString(pathType) << "'"; + JLOG(j_.debug()) << "getPaths< adding onto '" << pathTypeToString(parentPathType) + << "' to get '" << pathTypeToString(pathType) << "'"; int initialSize = mCompletePaths.size(); @@ -801,7 +829,10 @@ Pathfinder::addPathsForType(PathType const& pathType, std::function } bool -Pathfinder::isNoRipple(AccountID const& fromAccount, AccountID const& toAccount, Currency const& currency) +Pathfinder::isNoRipple( + AccountID const& fromAccount, + AccountID const& toAccount, + Currency const& currency) { auto sleRipple = mLedger->read(keylet::line(toAccount, fromAccount, currency)); @@ -827,7 +858,8 @@ Pathfinder::isNoRippleOut(STPath const& currentPath) // If there's only one item in the path, return true if that item specifies // no ripple on the output. A path with no ripple on its output can't be // followed by a link with no ripple on its input. - auto const& fromAccount = (currentPath.size() == 1) ? mSrcAccount : (currentPath.end() - 2)->getAccountID(); + auto const& fromAccount = + (currentPath.size() == 1) ? mSrcAccount : (currentPath.end() - 2)->getAccountID(); auto const& toAccount = endElement.getAccountID(); return isNoRipple(fromAccount, toAccount, endElement.getCurrency()); } @@ -874,7 +906,8 @@ Pathfinder::addLink( { if (mDstAmount.native() && !currentPath.empty()) { // non-default path to XRP destination - JLOG(j_.trace()) << "complete path found ax: " << currentPath.getJson(JsonOptions::none); + JLOG(j_.trace()) << "complete path found ax: " + << currentPath.getJson(JsonOptions::none); addUniquePath(mCompletePaths, currentPath); } } @@ -891,7 +924,8 @@ Pathfinder::addLink( bool const bDestOnly(addFlags & afAC_LAST); if (auto const lines = mRLCache->getRippleLines( - uEndAccount, bIsNoRippleOut ? LineDirection::incoming : LineDirection::outgoing)) + uEndAccount, + bIsNoRippleOut ? LineDirection::incoming : LineDirection::outgoing)) { auto& rippleLines = *lines; @@ -941,8 +975,8 @@ Pathfinder::addLink( // this is a complete path if (!currentPath.empty()) { - JLOG(j_.trace()) - << "complete path found ae: " << currentPath.getJson(JsonOptions::none); + JLOG(j_.trace()) << "complete path found ae: " + << currentPath.getJson(JsonOptions::none); addUniquePath(mCompletePaths, currentPath); } } @@ -960,7 +994,12 @@ Pathfinder::addLink( { // save this candidate int out = getPathsOut( - uEndCurrency, acct, direction, bIsEndCurrency, mEffectiveDst, continueCallback); + uEndCurrency, + acct, + direction, + bIsEndCurrency, + mEffectiveDst, + continueCallback); if (out) candidates.push_back({out, acct}); } @@ -973,7 +1012,10 @@ Pathfinder::addLink( candidates.begin(), candidates.end(), std::bind( - compareAccountCandidate, mLedger->seq(), std::placeholders::_1, std::placeholders::_2)); + compareAccountCandidate, + mLedger->seq(), + std::placeholders::_1, + std::placeholders::_2)); int count = candidates.size(); // allow more paths from source @@ -1010,14 +1052,16 @@ Pathfinder::addLink( // to XRP only if (!bOnXRP && app_.getOrderBookDB().isBookToXRP({uEndCurrency, uEndIssuer}, mDomain)) { - STPathElement pathElement(STPathElement::typeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()); + STPathElement pathElement( + STPathElement::typeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()); incompletePaths.assembleAdd(currentPath, pathElement); } } else { bool bDestOnly = (addFlags & afOB_LAST) != 0; - auto books = app_.getOrderBookDB().getBooksByTakerPays({uEndCurrency, uEndIssuer}, mDomain); + auto books = + app_.getOrderBookDB().getBooksByTakerPays({uEndCurrency, uEndIssuer}, mDomain); JLOG(j_.trace()) << books.size() << " books found from this currency/issuer"; for (auto const& book : books) @@ -1025,7 +1069,8 @@ Pathfinder::addLink( if (continueCallback && !continueCallback()) return; if (!currentPath.hasSeen(xrpAccount(), book.out.currency, book.out.account) && - !issueMatchesOrigin(book.out) && (!bDestOnly || (book.out.currency == mDstAmount.getCurrency()))) + !issueMatchesOrigin(book.out) && + (!bDestOnly || (book.out.currency == mDstAmount.getCurrency()))) { STPath newPath(currentPath); @@ -1033,19 +1078,22 @@ Pathfinder::addLink( { // to XRP // add the order book itself - newPath.emplace_back(STPathElement::typeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()); + newPath.emplace_back( + STPathElement::typeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()); if (mDstAmount.getCurrency().isZero()) { // destination is XRP, add account and path is // complete - JLOG(j_.trace()) << "complete path found bx: " << currentPath.getJson(JsonOptions::none); + JLOG(j_.trace()) << "complete path found bx: " + << currentPath.getJson(JsonOptions::none); addUniquePath(mCompletePaths, newPath); } else incompletePaths.push_back(newPath); } - else if (!currentPath.hasSeen(book.out.account, book.out.currency, book.out.account)) + else if (!currentPath.hasSeen( + book.out.account, book.out.currency, book.out.account)) { // Don't want the book if we've already seen the issuer // book -> account -> book @@ -1074,10 +1122,13 @@ Pathfinder::addLink( { // We skipped a required issuer } - else if (book.out.account == mEffectiveDst && book.out.currency == mDstAmount.getCurrency()) + else if ( + book.out.account == mEffectiveDst && + book.out.currency == mDstAmount.getCurrency()) { // with the destination account, this path is // complete - JLOG(j_.trace()) << "complete path found ba: " << currentPath.getJson(JsonOptions::none); + JLOG(j_.trace()) << "complete path found ba: " + << currentPath.getJson(JsonOptions::none); addUniquePath(mCompletePaths, newPath); } else @@ -1086,7 +1137,10 @@ Pathfinder::addLink( incompletePaths.assembleAdd( newPath, STPathElement( - STPathElement::typeAccount, book.out.account, book.out.currency, book.out.account)); + STPathElement::typeAccount, + book.out.account, + book.out.currency, + book.out.account)); } } } diff --git a/src/xrpld/app/paths/RippleLineCache.cpp b/src/xrpld/app/paths/RippleLineCache.cpp index aaef368cff..9916facdc2 100644 --- a/src/xrpld/app/paths/RippleLineCache.cpp +++ b/src/xrpld/app/paths/RippleLineCache.cpp @@ -11,8 +11,9 @@ RippleLineCache::RippleLineCache(std::shared_ptr const& ledger, RippleLineCache::~RippleLineCache() { - JLOG(journal_.debug()) << "destroyed for ledger " << ledger_->header().seq << " with " << lines_.size() - << " accounts and " << totalLineCount_ << " distinct trust lines."; + JLOG(journal_.debug()) << "destroyed for ledger " << ledger_->header().seq << " with " + << lines_.size() << " accounts and " << totalLineCount_ + << " distinct trust lines."; } std::shared_ptr> @@ -21,48 +22,55 @@ RippleLineCache::getRippleLines(AccountID const& accountID, LineDirection direct auto const hash = hasher_(accountID); AccountKey key(accountID, direction, hash); AccountKey otherkey( - accountID, direction == LineDirection::outgoing ? LineDirection::incoming : LineDirection::outgoing, hash); + accountID, + direction == LineDirection::outgoing ? LineDirection::incoming : LineDirection::outgoing, + hash); std::lock_guard sl(mLock); - auto [it, inserted] = [&]() { - if (auto otheriter = lines_.find(otherkey); otheriter != lines_.end()) - { - // The whole point of using the direction flag is to reduce the - // number of trust line objects held in memory. Ensure that there is - // only a single set of trustlines in the cache per account. - auto const size = otheriter->second ? otheriter->second->size() : 0; - JLOG(journal_.info()) << "Request for " << (direction == LineDirection::outgoing ? "outgoing" : "incoming") - << " trust lines for account " << accountID << " found " << size - << (direction == LineDirection::outgoing ? " incoming" : " outgoing") - << " trust lines. " - << (direction == LineDirection::outgoing ? "Deleting the subset of incoming" - : "Returning the superset of outgoing") - << " trust lines. "; - if (direction == LineDirection::outgoing) + auto [it, inserted] = + [&]() { + if (auto otheriter = lines_.find(otherkey); otheriter != lines_.end()) { - // This request is for the outgoing set, but there is already a - // subset of incoming lines in the cache. Erase that subset - // to be replaced by the full set. The full set will be built - // below, and will be returned, if needed, on subsequent calls - // for either value of outgoing. - XRPL_ASSERT(size <= totalLineCount_, "xrpl::RippleLineCache::getRippleLines : maximum lines"); - totalLineCount_ -= size; - lines_.erase(otheriter); + // The whole point of using the direction flag is to reduce the + // number of trust line objects held in memory. Ensure that there is + // only a single set of trustlines in the cache per account. + auto const size = otheriter->second ? otheriter->second->size() : 0; + JLOG(journal_.info()) + << "Request for " + << (direction == LineDirection::outgoing ? "outgoing" : "incoming") + << " trust lines for account " << accountID << " found " << size + << (direction == LineDirection::outgoing ? " incoming" : " outgoing") + << " trust lines. " + << (direction == LineDirection::outgoing ? "Deleting the subset of incoming" + : "Returning the superset of outgoing") + << " trust lines. "; + if (direction == LineDirection::outgoing) + { + // This request is for the outgoing set, but there is already a + // subset of incoming lines in the cache. Erase that subset + // to be replaced by the full set. The full set will be built + // below, and will be returned, if needed, on subsequent calls + // for either value of outgoing. + XRPL_ASSERT( + size <= totalLineCount_, + "xrpl::RippleLineCache::getRippleLines : maximum lines"); + totalLineCount_ -= size; + lines_.erase(otheriter); + } + else + { + // This request is for the incoming set, but there is + // already a superset of the outgoing trust lines in the cache. + // The path finding engine will disregard the non-rippling trust + // lines, so to prevent them from being stored twice, return the + // outgoing set. + key = otherkey; + return std::pair{otheriter, false}; + } } - else - { - // This request is for the incoming set, but there is - // already a superset of the outgoing trust lines in the cache. - // The path finding engine will disregard the non-rippling trust - // lines, so to prevent them from being stored twice, return the - // outgoing set. - key = otherkey; - return std::pair{otheriter, false}; - } - } - return lines_.emplace(key, nullptr); - }(); + return lines_.emplace(key, nullptr); + }(); if (inserted) { @@ -76,12 +84,16 @@ RippleLineCache::getRippleLines(AccountID const& accountID, LineDirection direct } XRPL_ASSERT( - !it->second || (it->second->size() > 0), "xrpl::RippleLineCache::getRippleLines : null or nonempty lines"); + !it->second || (it->second->size() > 0), + "xrpl::RippleLineCache::getRippleLines : null or nonempty lines"); auto const size = it->second ? it->second->size() : 0; - JLOG(journal_.trace()) << "getRippleLines for ledger " << ledger_->header().seq << " found " << size - << (key.direction_ == LineDirection::outgoing ? " outgoing" : " incoming") << " lines for " - << (inserted ? "new " : "existing ") << accountID << " out of a total of " << lines_.size() - << " accounts and " << totalLineCount_ << " trust lines"; + JLOG(journal_.trace()) << "getRippleLines for ledger " << ledger_->header().seq << " found " + << size + << (key.direction_ == LineDirection::outgoing ? " outgoing" + : " incoming") + << " lines for " << (inserted ? "new " : "existing ") << accountID + << " out of a total of " << lines_.size() << " accounts and " + << totalLineCount_ << " trust lines"; return it->second; } diff --git a/src/xrpld/app/paths/RippleLineCache.h b/src/xrpld/app/paths/RippleLineCache.h index 5dbdb414ee..c4ddad6c81 100644 --- a/src/xrpld/app/paths/RippleLineCache.h +++ b/src/xrpld/app/paths/RippleLineCache.h @@ -67,7 +67,8 @@ private: bool operator==(AccountKey const& lhs) const { - return hash_value_ == lhs.hash_value_ && account_ == lhs.account_ && direction_ == lhs.direction_; + return hash_value_ == lhs.hash_value_ && account_ == lhs.account_ && + direction_ == lhs.direction_; } std::size_t diff --git a/src/xrpld/app/paths/TrustLine.cpp b/src/xrpld/app/paths/TrustLine.cpp index f34dcbdf81..6c54aa52d7 100644 --- a/src/xrpld/app/paths/TrustLine.cpp +++ b/src/xrpld/app/paths/TrustLine.cpp @@ -38,14 +38,20 @@ PathFindTrustLine::makeItem(AccountID const& accountID, std::shared_ptr std::vector -getTrustLineItems(AccountID const& accountID, ReadView const& view, LineDirection direction = LineDirection::outgoing) +getTrustLineItems( + AccountID const& accountID, + ReadView const& view, + LineDirection direction = LineDirection::outgoing) { std::vector items; - forEachItem(view, accountID, [&items, &accountID, &direction](std::shared_ptr const& sleCur) { - auto ret = T::makeItem(accountID, sleCur); - if (ret && (direction == LineDirection::outgoing || !ret->getNoRipple())) - items.push_back(std::move(*ret)); - }); + forEachItem( + view, + accountID, + [&items, &accountID, &direction](std::shared_ptr const& sleCur) { + auto ret = T::makeItem(accountID, sleCur); + if (ret && (direction == LineDirection::outgoing || !ret->getNoRipple())) + items.push_back(std::move(*ret)); + }); // This list may be around for a while, so free up any unneeded // capacity items.shrink_to_fit(); @@ -55,7 +61,10 @@ getTrustLineItems(AccountID const& accountID, ReadView const& view, LineDirectio } // namespace detail std::vector -PathFindTrustLine::getItems(AccountID const& accountID, ReadView const& view, LineDirection direction) +PathFindTrustLine::getItems( + AccountID const& accountID, + ReadView const& view, + LineDirection direction) { return detail::getTrustLineItems(accountID, view, direction); } diff --git a/src/xrpld/app/paths/detail/AMMLiquidity.cpp b/src/xrpld/app/paths/detail/AMMLiquidity.cpp index ebbb51ce25..3ffc86d1ba 100644 --- a/src/xrpld/app/paths/detail/AMMLiquidity.cpp +++ b/src/xrpld/app/paths/detail/AMMLiquidity.cpp @@ -41,8 +41,10 @@ AMMLiquidity::generateFibSeqOffer(TAmounts const& balances { TAmounts cur{}; - cur.in = - toAmount(getIssue(balances.in), InitialFibSeqPct * initialBalances_.in, Number::rounding_mode::upward); + cur.in = toAmount( + getIssue(balances.in), + InitialFibSeqPct * initialBalances_.in, + Number::rounding_mode::upward); cur.out = swapAssetIn(initialBalances_, cur.in, tradingFee_); if (ammContext_.curIters() == 0) @@ -55,10 +57,14 @@ AMMLiquidity::generateFibSeqOffer(TAmounts const& balances 196418, 317811, 514229, 832040, 1346269}; // clang-format on - XRPL_ASSERT(!ammContext_.maxItersReached(), "xrpl::AMMLiquidity::generateFibSeqOffer : maximum iterations"); + XRPL_ASSERT( + !ammContext_.maxItersReached(), + "xrpl::AMMLiquidity::generateFibSeqOffer : maximum iterations"); cur.out = toAmount( - getIssue(balances.out), cur.out * fib[ammContext_.curIters() - 1], Number::rounding_mode::downward); + getIssue(balances.out), + cur.out * fib[ammContext_.curIters() - 1], + Number::rounding_mode::downward); // swapAssetOut() returns negative in this case if (cur.out >= balances.out) Throw("AMMLiquidity: generateFibSeqOffer exceeds the balance"); @@ -107,13 +113,15 @@ AMMLiquidity::maxOffer(TAmounts const& balances, Rules con auto const out = maxOut(balances.out, issueOut()); if (out <= TOut{0} || out >= balances.out) return std::nullopt; - return AMMOffer(*this, {swapAssetOut(balances, out, tradingFee_), out}, balances, Quality{balances}); + return AMMOffer( + *this, {swapAssetOut(balances, out, tradingFee_), out}, balances, Quality{balances}); } } template std::optional> -AMMLiquidity::getOffer(ReadView const& view, std::optional const& clobQuality) const +AMMLiquidity::getOffer(ReadView const& view, std::optional const& clobQuality) + const { // Can't generate more offers if multi-path. if (ammContext_.maxItersReached()) @@ -129,8 +137,8 @@ AMMLiquidity::getOffer(ReadView const& view, std::optional c } JLOG(j_.trace()) << "AMMLiquidity::getOffer balances " << to_string(initialBalances_.in) << " " - << to_string(initialBalances_.out) << " new balances " << to_string(balances.in) << " " - << to_string(balances.out); + << to_string(initialBalances_.out) << " new balances " + << to_string(balances.in) << " " << to_string(balances.out); // Can't generate AMM with a better quality than CLOB's // quality if AMM's Spot Price quality is less than CLOB quality or is @@ -140,8 +148,9 @@ AMMLiquidity::getOffer(ReadView const& view, std::optional c // to the requested clobQuality but not exactly and potentially SPQ may keep // on approaching clobQuality for many iterations. Checking for the quality // threshold prevents this scenario. - if (auto const spotPriceQ = Quality{balances}; - clobQuality && (spotPriceQ <= clobQuality || withinRelativeDistance(spotPriceQ, *clobQuality, Number(1, -7)))) + if (auto const spotPriceQ = Quality{balances}; clobQuality && + (spotPriceQ <= clobQuality || + withinRelativeDistance(spotPriceQ, *clobQuality, Number(1, -7)))) { JLOG(j_.trace()) << "AMMLiquidity::getOffer, higher clob quality"; return std::nullopt; @@ -166,7 +175,9 @@ AMMLiquidity::getOffer(ReadView const& view, std::optional c // nullopt if the pool is small. return maxOffer(balances, view.rules()); } - else if (auto const amounts = changeSpotPriceQuality(balances, *clobQuality, tradingFee_, view.rules(), j_)) + else if ( + auto const amounts = + changeSpotPriceQuality(balances, *clobQuality, tradingFee_, view.rules(), j_)) { return AMMOffer(*this, *amounts, balances, Quality{*amounts}); } @@ -196,13 +207,15 @@ AMMLiquidity::getOffer(ReadView const& view, std::optional c { if (offer->amount().in > beast::zero && offer->amount().out > beast::zero) { - JLOG(j_.trace()) << "AMMLiquidity::getOffer, created " << to_string(offer->amount().in) << "/" << issueIn_ - << " " << to_string(offer->amount().out) << "/" << issueOut_; + JLOG(j_.trace()) << "AMMLiquidity::getOffer, created " << to_string(offer->amount().in) + << "/" << issueIn_ << " " << to_string(offer->amount().out) << "/" + << issueOut_; return offer; } - JLOG(j_.debug()) << "AMMLiquidity::getOffer, no valid offer " << ammContext_.multiPath() << " " - << ammContext_.curIters() << " " << (clobQuality ? clobQuality->rate() : STAmount{}) << " " + JLOG(j_.debug()) << "AMMLiquidity::getOffer, no valid offer " << ammContext_.multiPath() + << " " << ammContext_.curIters() << " " + << (clobQuality ? clobQuality->rate() : STAmount{}) << " " << to_string(balances.in) << " " << to_string(balances.out); } diff --git a/src/xrpld/app/paths/detail/AMMOffer.cpp b/src/xrpld/app/paths/detail/AMMOffer.cpp index dd6b021689..4871d2251a 100644 --- a/src/xrpld/app/paths/detail/AMMOffer.cpp +++ b/src/xrpld/app/paths/detail/AMMOffer.cpp @@ -11,7 +11,11 @@ AMMOffer::AMMOffer( TAmounts const& amounts, TAmounts const& balances, Quality const& quality) - : ammLiquidity_(ammLiquidity), amounts_(amounts), balances_(balances), quality_(quality), consumed_(false) + : ammLiquidity_(ammLiquidity) + , amounts_(amounts) + , balances_(balances) + , quality_(quality) + , consumed_(false) { } @@ -54,7 +58,10 @@ AMMOffer::consume(ApplyView& view, TAmounts const& consume template TAmounts -AMMOffer::limitOut(TAmounts const& offerAmount, TOut const& limit, bool roundUp) const +AMMOffer::limitOut( + TAmounts const& offerAmount, + TOut const& limit, + bool roundUp) const { // Change the offer size proportionally to the original offer quality // to keep the strands quality order unchanged. The taker pays slightly @@ -76,12 +83,14 @@ AMMOffer::limitOut(TAmounts const& offerAmount, TOut const template TAmounts -AMMOffer::limitIn(TAmounts const& offerAmount, TIn const& limit, bool roundUp) const +AMMOffer::limitIn(TAmounts const& offerAmount, TIn const& limit, bool roundUp) + const { // See the comments above in limitOut(). if (ammLiquidity_.multiPath()) { - if (auto const& rules = getCurrentTransactionRules(); rules && rules->enabled(fixReducedOffersV2)) + if (auto const& rules = getCurrentTransactionRules(); + rules && rules->enabled(fixReducedOffersV2)) return quality().ceil_in_strict(offerAmount, limit, roundUp); return quality().ceil_in(offerAmount, limit); @@ -104,24 +113,27 @@ AMMOffer::checkInvariant(TAmounts const& consumed, beast:: { if (consumed.in > amounts_.in || consumed.out > amounts_.out) { - JLOG(j.error()) << "AMMOffer::checkInvariant failed: consumed " << to_string(consumed.in) << " " - << to_string(consumed.out) << " amounts " << to_string(amounts_.in) << " " - << to_string(amounts_.out); + JLOG(j.error()) << "AMMOffer::checkInvariant failed: consumed " << to_string(consumed.in) + << " " << to_string(consumed.out) << " amounts " << to_string(amounts_.in) + << " " << to_string(amounts_.out); return false; } Number const product = balances_.in * balances_.out; - auto const newBalances = TAmounts{balances_.in + consumed.in, balances_.out - consumed.out}; + auto const newBalances = + TAmounts{balances_.in + consumed.in, balances_.out - consumed.out}; Number const newProduct = newBalances.in * newBalances.out; if (newProduct >= product || withinRelativeDistance(product, newProduct, Number{1, -7})) return true; - JLOG(j.error()) << "AMMOffer::checkInvariant failed: balances " << to_string(balances_.in) << " " - << to_string(balances_.out) << " new balances " << to_string(newBalances.in) << " " - << to_string(newBalances.out) << " product/newProduct " << product << " " << newProduct << " diff " - << (product != Number{0} ? to_string((product - newProduct) / product) : "undefined"); + JLOG(j.error()) << "AMMOffer::checkInvariant failed: balances " << to_string(balances_.in) + << " " << to_string(balances_.out) << " new balances " + << to_string(newBalances.in) << " " << to_string(newBalances.out) + << " product/newProduct " << product << " " << newProduct << " diff " + << (product != Number{0} ? to_string((product - newProduct) / product) + : "undefined"); return false; } diff --git a/src/xrpld/app/paths/detail/BookStep.cpp b/src/xrpld/app/paths/detail/BookStep.cpp index b9c8aa4e67..4124fdfa30 100644 --- a/src/xrpld/app/paths/detail/BookStep.cpp +++ b/src/xrpld/app/paths/detail/BookStep.cpp @@ -1,9 +1,5 @@ -#include #include #include -#include -#include -#include #include #include @@ -14,6 +10,10 @@ #include #include #include +#include +#include +#include +#include #include @@ -128,10 +128,18 @@ public: offersUsed() const override; std::pair - revImp(PaymentSandbox& sb, ApplyView& afView, boost::container::flat_set& ofrsToRm, TOut const& out); + revImp( + PaymentSandbox& sb, + ApplyView& afView, + boost::container::flat_set& ofrsToRm, + TOut const& out); std::pair - fwdImp(PaymentSandbox& sb, ApplyView& afView, boost::container::flat_set& ofrsToRm, TIn const& in); + fwdImp( + PaymentSandbox& sb, + ApplyView& afView, + boost::container::flat_set& ofrsToRm, + TIn const& in); std::pair validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmount const& in) override; @@ -152,8 +160,8 @@ protected: { std::ostringstream ostr; ostr << name << ": " - << "\ninIss: " << book_.in.account << "\noutIss: " << book_.out.account << "\ninCur: " << book_.in.currency - << "\noutCur: " << book_.out.currency; + << "\ninIss: " << book_.in.account << "\noutIss: " << book_.out.account + << "\ninCur: " << book_.in.currency << "\noutCur: " << book_.out.currency; return ostr.str(); } @@ -180,7 +188,11 @@ private: // Return the unfunded and bad offers and the number of offers consumed. template std::pair, std::uint32_t> - forEachOffer(PaymentSandbox& sb, ApplyView& afView, DebtDirection prevStepDebtDir, Callback& callback) const; + forEachOffer( + PaymentSandbox& sb, + ApplyView& afView, + DebtDirection prevStepDebtDir, + Callback& callback) const; // Offer is either TOffer or AMMOffer template