diff --git a/.clang-tidy b/.clang-tidy index 069b62dc6..aa6a3c1db 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,165 +1,167 @@ --- Checks: "-*, - bugprone-argument-comment, - bugprone-assert-side-effect, - bugprone-bad-signal-to-kill-thread, - bugprone-bool-pointer-implicit-conversion, - bugprone-capturing-this-in-member-variable, - 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-misleading-setter-of-reference, - 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-unchecked-optional-access, - 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-use-enum-class, - cppcoreguidelines-virtual-class-destructor, - hicpp-ignored-remove-result, + bugprone-*, + -bugprone-assignment-in-if-condition, + -bugprone-bitwise-pointer-cast, + -bugprone-branch-clone, + -bugprone-command-processor, + -bugprone-copy-constructor-mutates-argument, + -bugprone-default-operator-new-on-overaligned-type, + -bugprone-easily-swappable-parameters, + -bugprone-exception-copy-constructor-throws, + -bugprone-exception-escape, + -bugprone-float-loop-counter, + -bugprone-forwarding-reference-overload, + -bugprone-implicit-widening-of-multiplication-result, + -bugprone-incorrect-enable-shared-from-this, + -bugprone-narrowing-conversions, + -bugprone-nondeterministic-pointer-iteration-order, + -bugprone-not-null-terminated-result, + -bugprone-random-generator-seed, + -bugprone-raw-memory-call-on-non-trivial-type, + -bugprone-std-namespace-modification, + -bugprone-tagged-union-member-count, + -bugprone-throwing-static-initialization, + -bugprone-unchecked-string-to-number-conversion, + -bugprone-unintended-char-ostream-output, + + cppcoreguidelines-*, + -cppcoreguidelines-avoid-c-arrays, + -cppcoreguidelines-avoid-capturing-lambda-coroutines, + -cppcoreguidelines-avoid-const-or-ref-data-members, + -cppcoreguidelines-avoid-do-while, + -cppcoreguidelines-avoid-goto, + -cppcoreguidelines-avoid-magic-numbers, + -cppcoreguidelines-avoid-non-const-global-variables, + -cppcoreguidelines-avoid-reference-coroutine-parameters, + -cppcoreguidelines-c-copy-assignment-signature, + -cppcoreguidelines-explicit-virtual-functions, + -cppcoreguidelines-interfaces-global-init, + -cppcoreguidelines-macro-to-enum, + -cppcoreguidelines-macro-usage, + -cppcoreguidelines-missing-std-forward, + -cppcoreguidelines-narrowing-conversions, + -cppcoreguidelines-no-malloc, + -cppcoreguidelines-noexcept-destructor, + -cppcoreguidelines-noexcept-move-operations, + -cppcoreguidelines-noexcept-swap, + -cppcoreguidelines-non-private-member-variables-in-classes, + -cppcoreguidelines-owning-memory, + -cppcoreguidelines-prefer-member-initializer, + -cppcoreguidelines-pro-bounds-array-to-pointer-decay, + -cppcoreguidelines-pro-bounds-avoid-unchecked-container-access, + -cppcoreguidelines-pro-bounds-constant-array-index, + -cppcoreguidelines-pro-bounds-pointer-arithmetic, + -cppcoreguidelines-pro-type-const-cast, + -cppcoreguidelines-pro-type-cstyle-cast, + -cppcoreguidelines-pro-type-reinterpret-cast, + -cppcoreguidelines-pro-type-union-access, + -cppcoreguidelines-pro-type-vararg, + -cppcoreguidelines-slicing, + -cppcoreguidelines-special-member-functions, + 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-nodiscard, - modernize-use-override, - modernize-use-ranges, - modernize-use-scoped-lock, - 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-ambiguous-smartptr-reset-call, - 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-identifier-naming, - readability-implicit-bool-conversion, - readability-inconsistent-declaration-parameter-name, - 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 + + misc-*, + -misc-anonymous-namespace-in-header, + -misc-confusable-identifiers, + -misc-coroutine-hostile-raii, + -misc-misleading-bidirectional, + -misc-misleading-identifier, + -misc-multiple-inheritance, + -misc-new-delete-overloads, + -misc-no-recursion, + -misc-non-copyable-objects, + -misc-non-private-member-variables-in-classes, + -misc-override-with-different-visibility, + -misc-predictable-rand, + -misc-unconventional-assign-operator, + -misc-uniqueptr-reset-release, + -misc-unused-parameters, + -misc-use-anonymous-namespace, + -misc-use-internal-linkage, + + modernize-*, + -modernize-avoid-bind, + -modernize-avoid-c-arrays, + -modernize-avoid-c-style-cast, + -modernize-avoid-setjmp-longjmp, + -modernize-avoid-variadic-functions, + -modernize-deprecated-ios-base-aliases, + -modernize-loop-convert, + -modernize-macro-to-enum, + -modernize-min-max-use-initializer-list, + -modernize-raw-string-literal, + -modernize-redundant-void-arg, + -modernize-replace-auto-ptr, + -modernize-replace-disallow-copy-and-assign-macro, + -modernize-replace-random-shuffle, + -modernize-return-braced-init-list, + -modernize-shrink-to-fit, + -modernize-unary-static-assert, + -modernize-use-auto, + -modernize-use-bool-literals, + -modernize-use-constraints, + -modernize-use-default-member-init, + -modernize-use-integer-sign-comparison, + -modernize-use-noexcept, + -modernize-use-nullptr, + -modernize-use-std-format, + -modernize-use-std-print, + -modernize-use-trailing-return-type, + -modernize-use-transparent-functors, + -modernize-use-uncaught-exceptions, + + performance-*, + -performance-avoid-endl, + -performance-enum-size, + -performance-inefficient-algorithm, + -performance-inefficient-string-concatenation, + -performance-no-int-to-ptr, + -performance-noexcept-destructor, + -performance-noexcept-move-constructor, + -performance-noexcept-swap, + -performance-type-promotion-in-math-fn, + -performance-unnecessary-copy-initialization, + -performance-unnecessary-value-param, + + readability-*, + -readability-avoid-const-params-in-decls, + -readability-avoid-unconditional-preprocessor-if, + -readability-container-data-pointer, + -readability-delete-null-pointer, + -readability-function-cognitive-complexity, + -readability-function-size, + -readability-identifier-length, + -readability-isolate-declaration, + -readability-magic-numbers, + -readability-misplaced-array-index, + -readability-named-parameter, + -readability-operators-representation, + -readability-qualified-auto, + -readability-redundant-access-specifiers, + -readability-redundant-control-flow, + -readability-redundant-function-ptr-dereference, + -readability-redundant-preprocessor, + -readability-redundant-smartptr-get, + -readability-redundant-string-cstr, + -readability-simplify-subscript-expr, + -readability-string-compare, + -readability-uniqueptr-delete-release, + -readability-uppercase-literal-suffix, + -readability-use-anyofallof, + -readability-use-concise-preprocessor-directives " +# --- +# bugprone-narrowing-conversions, # This will break a lot of code but we should enable it in the future because it can eliminate a lot of bugs +# misc-override-with-different-visibility, # Will be addressed in a future PR, but for now it generates too many warnings +# --- CheckOptions: 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' + 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;.*boost/.*fwd\.hpp' readability-braces-around-statements.ShortStatementLines: 2 readability-identifier-naming.MacroDefinitionCase: UPPER_CASE @@ -169,7 +171,7 @@ CheckOptions: readability-identifier-naming.EnumCase: CamelCase readability-identifier-naming.EnumConstantCase: CamelCase readability-identifier-naming.ScopedEnumConstantCase: CamelCase - readability-identifier-naming.GlobalConstantCase: UPPER_CASE + readability-identifier-naming.GlobalConstantCase: CamelCase readability-identifier-naming.GlobalConstantPrefix: "k" readability-identifier-naming.GlobalVariableCase: CamelCase readability-identifier-naming.GlobalVariablePrefix: "g" @@ -177,22 +179,23 @@ CheckOptions: readability-identifier-naming.ConstexprMethodCase: camelBack readability-identifier-naming.ClassMethodCase: camelBack readability-identifier-naming.ClassMemberCase: camelBack - readability-identifier-naming.ClassConstantCase: UPPER_CASE + readability-identifier-naming.ClassConstantCase: CamelCase readability-identifier-naming.ClassConstantPrefix: "k" - readability-identifier-naming.StaticConstantCase: UPPER_CASE + readability-identifier-naming.StaticConstantCase: CamelCase 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.StaticVariableCase: camelBack + readability-identifier-naming.ConstexprVariableCase: camelBack 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.PrivateMemberCase: camelBack readability-identifier-naming.PrivateMemberSuffix: _ + readability-identifier-naming.ProtectedMemberCase: camelBack readability-identifier-naming.ProtectedMemberSuffix: _ + readability-identifier-naming.PublicMemberCase: camelBack readability-identifier-naming.PublicMemberSuffix: "" readability-identifier-naming.FunctionIgnoredRegexp: ".*tag_invoke.*" diff --git a/.clangd b/.clangd index 87a9e010c..31f0bec5d 100644 --- a/.clangd +++ b/.clangd @@ -11,3 +11,4 @@ Diagnostics: - ".*ranges_lower_bound.h" - "time.h" - "stdlib.h" + - ".*boost/.*fwd.hpp" diff --git a/.gersemi/definitions.cmake b/.gersemi/definitions.cmake index 1e6de7884..ef974a6cc 100644 --- a/.gersemi/definitions.cmake +++ b/.gersemi/definitions.cmake @@ -17,3 +17,6 @@ endfunction() function(append_coverage_compiler_flags_to_target name mode) endfunction() + +function(patch_nix_binary target) +endfunction() diff --git a/.github/actions/build-clio/action.yml b/.github/actions/build-clio/action.yml index 6fa94eef2..a1eccf580 100644 --- a/.github/actions/build-clio/action.yml +++ b/.github/actions/build-clio/action.yml @@ -26,6 +26,6 @@ runs: run: | cd build cmake \ - --build . \ - --parallel "${{ steps.nproc.outputs.nproc }}" \ - --target ${CMAKE_TARGETS} + --build . \ + --parallel "${{ steps.nproc.outputs.nproc }}" \ + --target ${CMAKE_TARGETS} diff --git a/.github/actions/build-docker-image/action.yml b/.github/actions/build-docker-image/action.yml index c3ff74b7e..7b5e4b230 100644 --- a/.github/actions/build-docker-image/action.yml +++ b/.github/actions/build-docker-image/action.yml @@ -34,32 +34,32 @@ runs: steps: - name: Login to DockerHub if: ${{ inputs.push_image == 'true' && inputs.dockerhub_repo != '' }} - uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0 + uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4.4.0 with: username: ${{ env.DOCKERHUB_USER }} password: ${{ env.DOCKERHUB_PW }} - name: Login to GitHub Container Registry if: ${{ inputs.push_image == 'true' }} - uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0 + uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4.4.0 with: registry: ghcr.io username: ${{ github.repository_owner }} password: ${{ env.GITHUB_TOKEN }} - - uses: docker/setup-qemu-action@ce360397dd3f832beb865e1373c09c0e9f86d70a # v4.0.0 + - uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0 with: cache-image: false - - uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0 + - uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0 - - uses: docker/metadata-action@030e881283bb7a6894de51c315a6bfe6a94e05cf # v6.0.0 + - uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 id: meta with: images: ${{ inputs.images }} tags: ${{ inputs.tags }} - name: Build and push - uses: docker/build-push-action@bcafcacb16a39f128d818304e6c9c0c18556b85f # v7.1.0 + uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0 with: context: ${{ inputs.directory }} platforms: ${{ inputs.platforms }} diff --git a/.github/actions/build-identifier/action.yml b/.github/actions/build-identifier/action.yml new file mode 100644 index 000000000..7c085883a --- /dev/null +++ b/.github/actions/build-identifier/action.yml @@ -0,0 +1,53 @@ +name: Build identifier +description: Generate a unique build identifier and the ccache key derived from it + +inputs: + build_type: + description: Current build type (e.g. Release, Debug) + required: true + compiler: + description: Compiler used for the build (e.g. gcc, clang) + required: true + code_coverage: + description: Whether code coverage is on + required: true + sanitizers: + description: Sanitizer to enable, read by the 'sanitizers' conan profile (e.g. 'address', 'thread', 'undefinedbehavior') + required: true + +outputs: + build_identifier: + description: Unique identifier for the build configuration (without commit) + value: ${{ steps.build_identifier.outputs.build_identifier }} + cache_key: + description: ccache key, the build identifier suffixed with the common ancestor commit + value: ${{ steps.build_identifier.outputs.build_identifier }}-${{ steps.git_common_ancestor.outputs.commit }} + +runs: + using: composite + steps: + - name: Find common commit + id: git_common_ancestor + uses: ./.github/actions/git-common-ancestor + + - name: Build identifier + id: build_identifier + shell: bash + env: + RUNNER_OS: ${{ runner.os }} + BUILD_TYPE: ${{ inputs.build_type }} + COMPILER: ${{ inputs.compiler }} + CODE_COVERAGE: ${{ inputs.code_coverage }} + SANITIZERS: ${{ inputs.sanitizers }} + run: | + # Keep the legacy "__" layout so standard artifact + # names (e.g. clio_server_Linux_Release_gcc) stay backwards compatible. + # Sanitizer/coverage builds get extra suffixes and may differ from old names. + BUILD_IDENTIFIER="${RUNNER_OS}_${BUILD_TYPE}_${COMPILER}" + if [ "${CODE_COVERAGE}" == "true" ]; then + BUILD_IDENTIFIER+="_code_coverage" + fi + if [ -n "${SANITIZERS}" ]; then + BUILD_IDENTIFIER+="_${SANITIZERS}" + fi + echo "build_identifier=${BUILD_IDENTIFIER}" >>"${GITHUB_OUTPUT}" diff --git a/.github/actions/cache-key/action.yml b/.github/actions/cache-key/action.yml deleted file mode 100644 index 54b45692d..000000000 --- a/.github/actions/cache-key/action.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: Cache key -description: Generate cache key for ccache - -inputs: - conan_profile: - description: Conan profile name - required: true - build_type: - description: Current build type (e.g. Release, Debug) - required: true - default: Release - code_coverage: - description: Whether code coverage is on - required: true - default: "false" - -outputs: - key: - description: Generated cache key for ccache - value: ${{ steps.key_without_commit.outputs.key }}-${{ steps.git_common_ancestor.outputs.commit }} - restore_keys: - description: Cache restore keys for fallback - value: ${{ steps.key_without_commit.outputs.key }} - -runs: - using: composite - steps: - - name: Find common commit - id: git_common_ancestor - uses: ./.github/actions/git-common-ancestor - - - name: Set cache key without commit - id: key_without_commit - shell: bash - env: - RUNNER_OS: ${{ runner.os }} - BUILD_TYPE: ${{ inputs.build_type }} - CODE_COVERAGE: ${{ inputs.code_coverage == 'true' && '-code_coverage' || '' }} - CONAN_PROFILE: ${{ inputs.conan_profile }} - run: | - echo "key=clio-ccache-${RUNNER_OS}-${BUILD_TYPE}${CODE_COVERAGE}-${CONAN_PROFILE}-develop" >> "${GITHUB_OUTPUT}" diff --git a/.github/actions/cmake/action.yml b/.github/actions/cmake/action.yml index 96898d704..d3e7dabca 100644 --- a/.github/actions/cmake/action.yml +++ b/.github/actions/cmake/action.yml @@ -6,9 +6,6 @@ inputs: description: Build directory required: false default: "build" - conan_profile: - description: Conan profile name - required: true build_type: description: Build type for third-party libraries and clio. Could be 'Release', 'Debug' required: true @@ -25,10 +22,6 @@ inputs: description: Whether to enable code coverage required: true default: "false" - static: - description: Whether Clio is to be statically linked - required: true - default: "false" time_trace: description: Whether to enable compiler trace reports required: true @@ -50,15 +43,9 @@ runs: env: BUILD_DIR: "${{ inputs.build_dir }}" BUILD_TYPE: "${{ inputs.build_type }}" - SANITIZER_OPTION: |- - ${{ endsWith(inputs.conan_profile, '.asan') && '-Dsan=address' || - endsWith(inputs.conan_profile, '.tsan') && '-Dsan=thread' || - endsWith(inputs.conan_profile, '.ubsan') && '-Dsan=undefined' || - '' }} INTEGRATION_TESTS: "${{ inputs.integration_tests == 'true' && 'ON' || 'OFF' }}" BENCHMARK: "${{ inputs.benchmark == 'true' && 'ON' || 'OFF' }}" COVERAGE: "${{ inputs.code_coverage == 'true' && 'ON' || 'OFF' }}" - STATIC: "${{ inputs.static == 'true' && 'ON' || 'OFF' }}" TIME_TRACE: "${{ inputs.time_trace == 'true' && 'ON' || 'OFF' }}" PACKAGE: "${{ inputs.package == 'true' && 'ON' || 'OFF' }}" # GitHub creates a merge commit for a PR @@ -76,16 +63,14 @@ runs: FORCE_CLIO_VERSION: ${{ inputs.version }} run: | cmake \ - -B "${BUILD_DIR}" \ - -S . \ - -G Ninja \ - -DCMAKE_TOOLCHAIN_FILE:FILEPATH=build/generators/conan_toolchain.cmake \ - -DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \ - "${SANITIZER_OPTION}" \ - -Dtests=ON \ - -Dintegration_tests="${INTEGRATION_TESTS}" \ - -Dbenchmark="${BENCHMARK}" \ - -Dcoverage="${COVERAGE}" \ - -Dstatic="${STATIC}" \ - -Dtime_trace="${TIME_TRACE}" \ - -Dpackage="${PACKAGE}" + -B "${BUILD_DIR}" \ + -S . \ + -G Ninja \ + -DCMAKE_TOOLCHAIN_FILE:FILEPATH=build/generators/conan_toolchain.cmake \ + -DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \ + -Dtests=ON \ + -Dintegration_tests="${INTEGRATION_TESTS}" \ + -Dbenchmark="${BENCHMARK}" \ + -Dcoverage="${COVERAGE}" \ + -Dtime_trace="${TIME_TRACE}" \ + -Dpackage="${PACKAGE}" diff --git a/.github/actions/code-coverage/action.yml b/.github/actions/code-coverage/action.yml index aa16a6688..5612b1e07 100644 --- a/.github/actions/code-coverage/action.yml +++ b/.github/actions/code-coverage/action.yml @@ -15,13 +15,13 @@ runs: shell: bash run: | gcovr \ - -e benchmarks \ - -e tests \ - -e src/data/cassandra \ - -e src/data/CassandraBackend.hpp \ - -e 'src/data/BackendFactory.*' \ - --xml build/coverage_report.xml \ - -j8 --exclude-throw-branches + -e benchmarks \ + -e tests \ + -e src/data/cassandra \ + -e src/data/CassandraBackend.hpp \ + -e 'src/data/BackendFactory.*' \ + --xml build/coverage_report.xml \ + -j8 --exclude-throw-branches - name: Archive coverage report uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 diff --git a/.github/actions/conan/action.yml b/.github/actions/conan/action.yml index 897c3e548..4c930a59d 100644 --- a/.github/actions/conan/action.yml +++ b/.github/actions/conan/action.yml @@ -6,9 +6,6 @@ inputs: description: Build directory required: false default: "build" - conan_profile: - description: Conan profile name - required: true force_conan_source_build: description: Whether conan should build all dependencies from source required: true @@ -17,6 +14,10 @@ inputs: description: Build type for third-party libraries and clio. Could be 'Release', 'Debug' required: true default: "Release" + sanitizers: + description: Sanitizer to enable, read by the 'sanitizers' conan profile (e.g. 'address', 'thread', 'undefinedbehavior') + required: false + default: "" runs: using: composite @@ -27,11 +28,11 @@ runs: BUILD_DIR: "${{ inputs.build_dir }}" CONAN_BUILD_OPTION: "${{ inputs.force_conan_source_build == 'true' && '*' || 'missing' }}" BUILD_TYPE: "${{ inputs.build_type }}" - CONAN_PROFILE: "${{ inputs.conan_profile }}" + SANITIZERS: "${{ inputs.sanitizers }}" run: | conan \ - install . \ - -of "${BUILD_DIR}" \ - -b "${CONAN_BUILD_OPTION}" \ - -s "build_type=${BUILD_TYPE}" \ - --profile:all "${CONAN_PROFILE}" + install . \ + -of "${BUILD_DIR}" \ + -b "${CONAN_BUILD_OPTION}" \ + -s "build_type=${BUILD_TYPE}" \ + --profile:all ci diff --git a/.github/actions/git-common-ancestor/action.yml b/.github/actions/git-common-ancestor/action.yml index 1e7f16b58..54852b8e7 100644 --- a/.github/actions/git-common-ancestor/action.yml +++ b/.github/actions/git-common-ancestor/action.yml @@ -13,4 +13,4 @@ runs: id: find_common_ancestor shell: bash run: | - echo "commit=\"$(git merge-base --fork-point origin/develop)\"" >> $GITHUB_OUTPUT + echo "commit=\"$(git merge-base --fork-point origin/develop)\"" >>$GITHUB_OUTPUT diff --git a/.github/actions/set-compiler-env/action.yml b/.github/actions/set-compiler-env/action.yml new file mode 100644 index 000000000..a16dde2b3 --- /dev/null +++ b/.github/actions/set-compiler-env/action.yml @@ -0,0 +1,34 @@ +name: Set compiler environment +description: "Set CC and CXX environment variables for the given compiler." + +inputs: + compiler: + description: 'The compiler to use ("gcc" or "clang").' + required: true + +runs: + using: composite + + steps: + - name: Set CC and CXX for gcc + if: ${{ inputs.compiler == 'gcc' }} + shell: bash + run: | + echo "CC=gcc" >>"${GITHUB_ENV}" + echo "CXX=g++" >>"${GITHUB_ENV}" + + - name: Set CC and CXX for clang + if: ${{ inputs.compiler == 'clang' }} + shell: bash + run: | + echo "CC=clang" >>"${GITHUB_ENV}" + echo "CXX=clang++" >>"${GITHUB_ENV}" + + - name: Fail on unknown compiler + if: ${{ inputs.compiler != 'gcc' && inputs.compiler != 'clang' }} + shell: bash + env: + COMPILER: ${{ inputs.compiler }} + run: | + echo "Unknown compiler: $COMPILER" >&2 + exit 1 diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 6f8e2ae1c..727023a37 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,105 +1,21 @@ version: 2 updates: - package-ecosystem: github-actions - directory: / + directories: + - / + - .github/actions/build-clio/ + - .github/actions/build-docker-image/ + - .github/actions/build-identifier/ + - .github/actions/cmake/ + - .github/actions/code-coverage/ + - .github/actions/conan/ + - .github/actions/git-common-ancestor/ + - .github/actions/set-compiler-env/ schedule: interval: weekly day: monday time: "04:00" timezone: Etc/GMT - reviewers: - - XRPLF/clio-dev-team - commit-message: - prefix: "ci: [DEPENDABOT] " - target-branch: develop - - - package-ecosystem: github-actions - directory: .github/actions/build-clio/ - schedule: - interval: weekly - day: monday - time: "04:00" - timezone: Etc/GMT - reviewers: - - XRPLF/clio-dev-team - commit-message: - prefix: "ci: [DEPENDABOT] " - target-branch: develop - - - package-ecosystem: github-actions - directory: .github/actions/build-docker-image/ - schedule: - interval: weekly - day: monday - time: "04:00" - timezone: Etc/GMT - reviewers: - - XRPLF/clio-dev-team - commit-message: - prefix: "ci: [DEPENDABOT] " - target-branch: develop - - - package-ecosystem: github-actions - directory: .github/actions/cmake/ - schedule: - interval: weekly - day: monday - time: "04:00" - timezone: Etc/GMT - reviewers: - - XRPLF/clio-dev-team - commit-message: - prefix: "ci: [DEPENDABOT] " - target-branch: develop - - - package-ecosystem: github-actions - directory: .github/actions/code-coverage/ - schedule: - interval: weekly - day: monday - time: "04:00" - timezone: Etc/GMT - reviewers: - - XRPLF/clio-dev-team - commit-message: - prefix: "ci: [DEPENDABOT] " - target-branch: develop - - - package-ecosystem: github-actions - directory: .github/actions/conan/ - schedule: - interval: weekly - day: monday - time: "04:00" - timezone: Etc/GMT - reviewers: - - XRPLF/clio-dev-team - commit-message: - prefix: "ci: [DEPENDABOT] " - target-branch: develop - - - package-ecosystem: github-actions - directory: .github/actions/git-common-ancestor/ - schedule: - interval: weekly - day: monday - time: "04:00" - timezone: Etc/GMT - reviewers: - - XRPLF/clio-dev-team - commit-message: - prefix: "ci: [DEPENDABOT] " - target-branch: develop - - - package-ecosystem: github-actions - directory: .github/actions/cache-key/ - schedule: - interval: weekly - day: monday - time: "04:00" - timezone: Etc/GMT - reviewers: - - XRPLF/clio-dev-team commit-message: prefix: "ci: [DEPENDABOT] " target-branch: develop diff --git a/.github/scripts/conan/apple-clang-17.profile b/.github/scripts/conan/apple-clang-17.profile deleted file mode 100644 index 5c3d44c99..000000000 --- a/.github/scripts/conan/apple-clang-17.profile +++ /dev/null @@ -1,11 +0,0 @@ -[settings] -arch={{detect_api.detect_arch()}} -build_type=Release -compiler=apple-clang -compiler.cppstd=20 -compiler.libcxx=libc++ -compiler.version=17.0 -os=Macos - -[conf] -grpc/1.50.1:tools.build:cxxflags+=["-Wno-missing-template-arg-list-after-template-kw"] diff --git a/.github/scripts/conan/generate_matrix.py b/.github/scripts/conan/generate_matrix.py index 213ea23d3..7d0b30f28 100755 --- a/.github/scripts/conan/generate_matrix.py +++ b/.github/scripts/conan/generate_matrix.py @@ -3,17 +3,18 @@ import itertools import json LINUX_OS = ["heavy", "heavy-arm64"] -LINUX_CONTAINERS = [ - '{ "image": "ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696" }' -] +LINUX_CONTAINERS = ['{ "image": "ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b" }'] LINUX_COMPILERS = ["gcc", "clang"] -MACOS_OS = ["macos15"] +MACOS_OS = ["macos-26-apple-clang-21"] MACOS_CONTAINERS = [""] MACOS_COMPILERS = ["apple-clang"] BUILD_TYPES = ["Release", "Debug"] -SANITIZER_EXT = [".asan", ".tsan", ".ubsan", ""] + +# Values of the `SANITIZERS` environment variable read by the `sanitizers` conan +# profile. An empty string builds without any sanitizers. +SANITIZERS = ["address", "thread", "undefinedbehavior", ""] def generate_matrix(): @@ -23,13 +24,13 @@ def generate_matrix(): itertools.product(LINUX_OS, LINUX_CONTAINERS, LINUX_COMPILERS), itertools.product(MACOS_OS, MACOS_CONTAINERS, MACOS_COMPILERS), ): - for sanitizer_ext, build_type in itertools.product(SANITIZER_EXT, BUILD_TYPES): + for sanitizers, build_type in itertools.product(SANITIZERS, BUILD_TYPES): configurations.append( { "os": os, "container": container, "compiler": compiler, - "sanitizer_ext": sanitizer_ext, + "sanitizers": sanitizers, "build_type": build_type, } ) diff --git a/.github/scripts/conan/init.sh b/.github/scripts/conan/init.sh deleted file mode 100755 index dba73a6ec..000000000 --- a/.github/scripts/conan/init.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/bash - -set -ex - -CURRENT_DIR="$(cd "$(dirname "$0")" && pwd)" -REPO_DIR="$(cd "$CURRENT_DIR/../../../" && pwd)" - -CONAN_DIR="${CONAN_HOME:-$HOME/.conan2}" -PROFILES_DIR="$CONAN_DIR/profiles" - -# When developers' compilers are updated, these profiles might be different -if [[ -z "$CI" ]]; then - APPLE_CLANG_PROFILE="$CURRENT_DIR/apple-clang-17.profile" -else - APPLE_CLANG_PROFILE="$CURRENT_DIR/apple-clang-17.profile" -fi - -GCC_PROFILE="$REPO_DIR/docker/ci/conan/gcc.profile" -CLANG_PROFILE="$REPO_DIR/docker/ci/conan/clang.profile" - -SANITIZER_TEMPLATE_FILE="$REPO_DIR/docker/ci/conan/sanitizer_template.profile" - -rm -rf "$CONAN_DIR" - -conan remote add --index 0 xrplf https://conan.ripplex.io - -cp "$REPO_DIR/docker/ci/conan/global.conf" "$CONAN_DIR/global.conf" - -create_profile_with_sanitizers() { - profile_name="$1" - profile_source="$2" - - cp "$profile_source" "$PROFILES_DIR/$profile_name" - cp "$SANITIZER_TEMPLATE_FILE" "$PROFILES_DIR/$profile_name.asan" - cp "$SANITIZER_TEMPLATE_FILE" "$PROFILES_DIR/$profile_name.tsan" - cp "$SANITIZER_TEMPLATE_FILE" "$PROFILES_DIR/$profile_name.ubsan" -} - -mkdir -p "$PROFILES_DIR" - -if [[ "$(uname)" == "Darwin" ]]; then - create_profile_with_sanitizers "apple-clang" "$APPLE_CLANG_PROFILE" - echo "include(apple-clang)" >"$PROFILES_DIR/default" -else - create_profile_with_sanitizers "clang" "$CLANG_PROFILE" - create_profile_with_sanitizers "gcc" "$GCC_PROFILE" - echo "include(gcc)" >"$PROFILES_DIR/default" -fi diff --git a/.github/workflows/build-clio-docker-image.yml b/.github/workflows/build-clio-docker-image.yml index bad4f53f3..82d88ac8f 100644 --- a/.github/workflows/build-clio-docker-image.yml +++ b/.github/workflows/build-clio-docker-image.yml @@ -14,9 +14,9 @@ on: type: boolean description: Whether to strip clio binary default: true - publish_image: + push_image: type: boolean - description: Whether to publish docker image + description: Whether to push docker image required: true workflow_dispatch: @@ -43,12 +43,12 @@ defaults: shell: bash jobs: - build_and_publish_image: + build_and_push_image: name: Build and publish image runs-on: ubuntu-latest steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Download Clio binary from artifact if: ${{ inputs.artifact_name != null }} @@ -65,8 +65,8 @@ jobs: run: | wget "${BINARY_URL}" -P ./docker/clio/artifact/ if [ "$(sha256sum ./docker/clio/clio_server | awk '{print $1}')" != "${BINARY_SHA256}" ]; then - echo "Binary sha256 sum doesn't match" - exit 1 + echo "Binary sha256 sum doesn't match" + exit 1 fi - name: Unpack binary run: | @@ -74,9 +74,9 @@ jobs: cd docker/clio/artifact artifact=$(find . -type f) if [[ $artifact == *.zip ]]; then - unzip $artifact + unzip $artifact elif [[ $artifact == *.tar.gz ]]; then - tar -xvf $artifact + tar -xvf $artifact fi chmod +x ./clio_server mv ./clio_server ../ @@ -90,7 +90,7 @@ jobs: - name: Set GHCR_REPO id: set-ghcr-repo run: | - echo "GHCR_REPO=$(echo ghcr.io/${{ github.repository_owner }} | tr '[:upper:]' '[:lower:]')" >> ${GITHUB_OUTPUT} + echo "GHCR_REPO=$(echo ghcr.io/${{ github.repository_owner }} | tr '[:upper:]' '[:lower:]')" >>${GITHUB_OUTPUT} - name: Build Docker image uses: ./.github/actions/build-docker-image @@ -102,7 +102,7 @@ jobs: images: | ghcr.io/${{ steps.set-ghcr-repo.outputs.GHCR_REPO }}/clio ${{ github.repository_owner == 'XRPLF' && 'rippleci/clio' || '' }} - push_image: ${{ inputs.publish_image }} + push_image: ${{ inputs.push_image }} directory: docker/clio tags: ${{ inputs.tags }} platforms: linux/amd64 diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6e0a8c3e0..ce919f3c3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -45,30 +45,24 @@ jobs: fail-fast: false matrix: os: [heavy] - conan_profile: [gcc, clang] + compiler: [gcc, clang] build_type: [Release, Debug] - container: - [ - '{ "image": "ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696" }', - ] - static: [true] + container: ['{ "image": "ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b" }'] include: - - os: macos15 - conan_profile: apple-clang + - os: macos-26-apple-clang-21 + compiler: apple-clang build_type: Release container: "" - static: false uses: ./.github/workflows/reusable-build-test.yml with: runs_on: ${{ matrix.os }} container: ${{ matrix.container }} - conan_profile: ${{ matrix.conan_profile }} + compiler: ${{ matrix.compiler }} build_type: ${{ matrix.build_type }} download_ccache: true upload_ccache: true - static: ${{ matrix.static }} run_unit_tests: true run_integration_tests: false upload_clio_server: true @@ -79,13 +73,12 @@ jobs: uses: ./.github/workflows/reusable-build.yml with: runs_on: heavy - container: '{ "image": "ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696" }' - conan_profile: gcc + container: '{ "image": "ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b" }' + compiler: gcc build_type: Debug download_ccache: true upload_ccache: true code_coverage: true - static: true upload_clio_server: false targets: all analyze_build_time: false @@ -97,10 +90,10 @@ jobs: needs: build-and-test runs-on: heavy container: - image: ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696 + image: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: diff --git a/.github/workflows/check-libxrpl.yml b/.github/workflows/check-libxrpl.yml index b85e53adb..27cceb785 100644 --- a/.github/workflows/check-libxrpl.yml +++ b/.github/workflows/check-libxrpl.yml @@ -10,7 +10,7 @@ concurrency: cancel-in-progress: true env: - CONAN_PROFILE: gcc + COMPILER: gcc defaults: run: @@ -21,21 +21,29 @@ jobs: name: Build Clio / `libXRPL ${{ github.event.client_payload.version }}` runs-on: heavy container: - image: ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696 + image: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab + uses: XRPLF/actions/prepare-runner@e4b6449d55a61c002d7c3fdfa6c20f721ede0606 with: enable_ccache: false - name: Print build environment uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574 + - name: Set compiler environment + uses: ./.github/actions/set-compiler-env + with: + compiler: ${{ env.COMPILER }} + + - name: Setup conan + run: conan/init.sh + - name: Update libXRPL version requirement run: | sed -i.bak -E "s|'xrpl/[a-zA-Z0-9\\.\\-]+'|'xrpl/${{ github.event.client_payload.conan_ref }}'|g" conanfile.py @@ -43,17 +51,13 @@ jobs: - name: Update conan lockfile run: | - conan lock create . --profile:all ${{ env.CONAN_PROFILE }} + conan lock create . --profile:all ci - name: Run conan uses: ./.github/actions/conan - with: - conan_profile: ${{ env.CONAN_PROFILE }} - name: Run CMake uses: ./.github/actions/cmake - with: - conan_profile: ${{ env.CONAN_PROFILE }} - name: Build Clio uses: ./.github/actions/build-clio @@ -72,7 +76,7 @@ jobs: needs: build runs-on: heavy container: - image: ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696 + image: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b steps: - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 @@ -95,10 +99,10 @@ jobs: issues: write steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Create an issue - uses: XRPLF/actions/create-issue@fbcc16eb7f20dc3199eaf1aed0d3523a5ba9008c + uses: XRPLF/actions/create-issue@2b8bc36af85b88bca0dd7bfac2e2dc05f94ad712 with: title: "Proposed libXRPL check failed" body: > diff --git a/.github/workflows/check-pr-title.yml b/.github/workflows/check-pr-title.yml index 5eee18201..e519cb29d 100644 --- a/.github/workflows/check-pr-title.yml +++ b/.github/workflows/check-pr-title.yml @@ -7,4 +7,4 @@ on: jobs: check_title: - uses: XRPLF/actions/.github/workflows/check-pr-title.yml@a5d8dd35be543365e90a11358447130c8763871d + uses: XRPLF/actions/.github/workflows/check-pr-title.yml@cba1f0891650baf1a9c88624dc2d72573be2eb81 diff --git a/.github/workflows/clang-tidy.yml b/.github/workflows/clang-tidy.yml index 16dc15e24..2ec1644dd 100644 --- a/.github/workflows/clang-tidy.yml +++ b/.github/workflows/clang-tidy.yml @@ -28,12 +28,12 @@ env: BUILD_DIR: build BUILD_TYPE: Debug # Debug so that ASSERTS and such participate in clang-tidy check - OUTPUT_FILE: clang-tidy-output.txt - DIFF_FILE: clang-tidy-git-diff.txt - ISSUE_FILE: clang-tidy-issue.md + OUTPUT_FILE: /tmp/clang-tidy-output.txt + FILTERED_OUTPUT_FILE: /tmp/clang-tidy-filtered-output.txt + DIFF_FILE: /tmp/clang-tidy-git-diff.txt + ISSUE_FILE: /tmp/clang-tidy-issue.md - CONAN_PROFILE: clang - LLVM_TOOLS_VERSION: 21 + COMPILER: clang defaults: run: @@ -44,15 +44,15 @@ jobs: if: ${{ github.event_name == 'pull_request' }} permissions: contents: read - uses: XRPLF/actions/.github/workflows/determine-tidy-files.yml@12f5dbc98a2260259a66970e57fa4d26fb7f285c + uses: XRPLF/actions/.github/workflows/determine-tidy-files.yml@d041ac9f1fa9f07a4ba335eb4c1c82233fb3fef6 run-clang-tidy: name: Run clang tidy needs: [determine-files] - if: ${{ always() && !cancelled() && (github.event_name != 'pull_request' || needs.determine-files.outputs.cpp_changed_files != '' || needs.determine-files.outputs.clang_tidy_config_changed == 'true') }} + if: ${{ needs.determine-files.outputs.cpp_changed_files != '' || needs.determine-files.outputs.need_full_run == 'true' }} runs-on: heavy container: - image: ghcr.io/xrplf/clio-ci:f174b47f4909ae41b80406d836ab52adc39eacc6 + image: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b permissions: contents: write @@ -60,28 +60,34 @@ jobs: pull-requests: write steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab + uses: XRPLF/actions/prepare-runner@e4b6449d55a61c002d7c3fdfa6c20f721ede0606 with: enable_ccache: false - name: Print build environment uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574 + - name: Set compiler environment + uses: ./.github/actions/set-compiler-env + with: + compiler: ${{ env.COMPILER }} + + - name: Setup conan + run: conan/init.sh + - name: Run conan uses: ./.github/actions/conan with: build_dir: ${{ env.BUILD_DIR }} - conan_profile: ${{ env.CONAN_PROFILE }} build_type: ${{ env.BUILD_TYPE }} - name: Run CMake uses: ./.github/actions/cmake with: build_dir: ${{ env.BUILD_DIR }} - conan_profile: ${{ env.CONAN_PROFILE }} build_type: ${{ env.BUILD_TYPE }} - name: Get number of processors @@ -92,10 +98,10 @@ jobs: continue-on-error: true id: run_clang_tidy env: - TARGETS: ${{ (needs.determine-files.outputs.clang_tidy_config_changed != 'true' && github.event_name == 'pull_request') && needs.determine-files.outputs.cpp_changed_files || 'benchmarks src tests' }} + TARGETS: ${{ needs.determine-files.outputs.need_full_run != 'true' && needs.determine-files.outputs.cpp_changed_files || 'benchmarks src tests' }} run: | set -o pipefail - run-clang-tidy-${{ env.LLVM_TOOLS_VERSION }} -j ${{ steps.nproc.outputs.nproc }} -p "${BUILD_DIR}" -quiet -fix -allow-no-checks ${TARGETS} 2>&1 | tee "${OUTPUT_FILE}" + run-clang-tidy -j ${{ steps.nproc.outputs.nproc }} -p "${BUILD_DIR}" -quiet -fix -allow-no-checks ${TARGETS} 2>&1 | tee "${OUTPUT_FILE}" - name: Print errors if: ${{ steps.run_clang_tidy.outcome != 'success' }} @@ -137,7 +143,7 @@ jobs: - name: Write issue header if: ${{ steps.run_clang_tidy.outcome != 'success' }} run: | - cat > "${ISSUE_FILE}" <"${ISSUE_FILE}" < filtered-output.txt || true + # Extract lines containing 'error:', 'warning:', or 'note:' + grep -E '(error:|warning:|note:)' "${OUTPUT_FILE}" >"${FILTERED_OUTPUT_FILE}" || true - # If filtered output is empty, use original (might be a different error format) - if [ ! -s filtered-output.txt ]; then - cp "${OUTPUT_FILE}" filtered-output.txt - fi + # If filtered output is empty, use original (might be a different error format) + if [ ! -s "${FILTERED_OUTPUT_FILE}" ]; then + cp "${OUTPUT_FILE}" "${FILTERED_OUTPUT_FILE}" + fi - # Truncate if too large - head -c 60000 filtered-output.txt >> "${ISSUE_FILE}" - if [ "$(wc -c < filtered-output.txt)" -gt 60000 ]; then - echo "" >> "${ISSUE_FILE}" - echo "... (output truncated, see artifacts for full output)" >> "${ISSUE_FILE}" - fi + # Truncate if too large + head -c 60000 "${FILTERED_OUTPUT_FILE}" >>"${ISSUE_FILE}" + if [ "$(wc -c <"${FILTERED_OUTPUT_FILE}")" -gt 60000 ]; then + echo "" >>"${ISSUE_FILE}" + echo "... (output truncated, see artifacts for full output)" >>"${ISSUE_FILE}" + fi - rm filtered-output.txt + rm "${FILTERED_OUTPUT_FILE}" else - echo "No output file found" >> "${ISSUE_FILE}" + echo "No output file found" >>"${ISSUE_FILE}" fi - name: Append issue footer if: ${{ steps.run_clang_tidy.outcome != 'success' }} run: | - cat >> "${ISSUE_FILE}" <>"${ISSUE_FILE}" < Fixes #${{ steps.create_issue.outputs.issue_number }}. diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index fa328edef..bef4bf816 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -4,6 +4,18 @@ on: push: branches: [develop] workflow_dispatch: + pull_request: + branches: [release/*, develop] + paths: + - .github/workflows/docs.yml + + - CMakeLists.txt + - conanfile.py + - conan.lock + - "cmake/**" + - "docs/**" + - "src/**" + - "tests/**" concurrency: # Only cancel in-progress jobs or runs for the current workflow - matches against branch & tags @@ -18,16 +30,16 @@ jobs: build: runs-on: ubuntu-latest container: - image: ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696 + image: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b steps: - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: lfs: true - name: Prepare runner - uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab + uses: XRPLF/actions/prepare-runner@e4b6449d55a61c002d7c3fdfa6c20f721ede0606 with: enable_ccache: false @@ -46,6 +58,7 @@ jobs: run: cmake --build . --target docs - name: Setup Pages + if: ${{ github.repository == 'XRPLF/clio' && github.event_name == 'push' }} uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0 - name: Upload artifact @@ -55,6 +68,7 @@ jobs: name: docs-develop deploy: + if: ${{ github.repository == 'XRPLF/clio' && github.event_name == 'push' }} needs: build permissions: pages: write diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index fc104ec5d..9bb8b4176 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -37,7 +37,7 @@ jobs: - name: Get current date id: get_date run: | - echo "date=$(date +'%Y%m%d')" >> $GITHUB_OUTPUT + echo "date=$(date +'%Y%m%d')" >>$GITHUB_OUTPUT build-and-test: name: Build and Test @@ -47,33 +47,30 @@ jobs: fail-fast: false matrix: include: - - os: macos15 - conan_profile: apple-clang + - os: macos-26-apple-clang-21 + compiler: apple-clang build_type: Release - static: false - os: heavy - conan_profile: gcc + compiler: gcc build_type: Release - static: true - container: '{ "image": "ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696" }' + container: '{ "image": "ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b" }' - os: heavy - conan_profile: gcc + compiler: gcc build_type: Debug - static: true - container: '{ "image": "ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696" }' + container: '{ "image": "ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b" }' - os: heavy - conan_profile: gcc.ubsan + compiler: gcc + sanitizers: undefinedbehavior build_type: Release - static: false - container: '{ "image": "ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696" }' + container: '{ "image": "ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b" }' uses: ./.github/workflows/reusable-build-test.yml with: runs_on: ${{ matrix.os }} container: ${{ matrix.container }} - conan_profile: ${{ matrix.conan_profile }} + compiler: ${{ matrix.compiler }} + sanitizers: ${{ matrix.sanitizers }} build_type: ${{ matrix.build_type }} - static: ${{ matrix.static }} run_unit_tests: true run_integration_tests: true upload_clio_server: true @@ -88,13 +85,12 @@ jobs: uses: ./.github/workflows/reusable-build.yml with: runs_on: heavy - container: '{ "image": "ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696" }' - conan_profile: gcc + container: '{ "image": "ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b" }' + compiler: gcc build_type: Release download_ccache: false upload_ccache: false code_coverage: false - static: true upload_clio_server: false package: true version: nightly-${{ needs.get_date.outputs.date }} @@ -110,23 +106,20 @@ jobs: matrix: include: - os: heavy - conan_profile: clang - container: '{ "image": "ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696" }' - static: true - - os: macos15 - conan_profile: apple-clang + compiler: clang + container: '{ "image": "ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b" }' + - os: macos-26-apple-clang-21 + compiler: apple-clang container: "" - static: false uses: ./.github/workflows/reusable-build.yml with: runs_on: ${{ matrix.os }} container: ${{ matrix.container }} - conan_profile: ${{ matrix.conan_profile }} + compiler: ${{ matrix.compiler }} build_type: Release download_ccache: false upload_ccache: false code_coverage: false - static: ${{ matrix.static }} upload_clio_server: false targets: all analyze_build_time: true @@ -157,7 +150,7 @@ jobs: type=raw,value=${{ github.sha }} artifact_name: clio_server_Linux_Release_gcc strip_binary: true - publish_image: ${{ github.event_name != 'pull_request' }} + push_image: ${{ github.repository == 'XRPLF/clio' && github.event_name != 'pull_request' }} create_issue_on_failure: needs: [build-and-test, nightly_release, build_and_publish_docker_image] @@ -169,12 +162,12 @@ jobs: issues: write steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Create an issue - uses: XRPLF/actions/create-issue@fbcc16eb7f20dc3199eaf1aed0d3523a5ba9008c + uses: XRPLF/actions/create-issue@2b8bc36af85b88bca0dd7bfac2e2dc05f94ad712 with: title: "Nightly release failed 🌙" - body: "" + body: "Please check the nightly release workflow for details." labels: "bug" assignees: "godexsoft,kuznetsss,mathbunnyru" diff --git a/.github/workflows/pre-commit-autoupdate.yml b/.github/workflows/pre-commit-autoupdate.yml index 5d79fec76..08a2a391e 100644 --- a/.github/workflows/pre-commit-autoupdate.yml +++ b/.github/workflows/pre-commit-autoupdate.yml @@ -12,7 +12,7 @@ on: jobs: auto-update: - uses: XRPLF/actions/.github/workflows/pre-commit-autoupdate.yml@5e942d61bf32f7557a7c159cfac4712a687b3e3a + uses: XRPLF/actions/.github/workflows/pre-commit-autoupdate.yml@b929ad64a95f908dee04aa9f53d584cbe893595b with: sign_commit: true committer: "Clio CI " diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index 9e25304e1..8bbba3a27 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -8,7 +8,7 @@ on: jobs: run-hooks: - uses: XRPLF/actions/.github/workflows/pre-commit.yml@5e942d61bf32f7557a7c159cfac4712a687b3e3a + uses: XRPLF/actions/.github/workflows/pre-commit.yml@3ba08d6ddf114092891d48491fc2e26c3ba15552 with: runs_on: heavy - container: '{ "image": "ghcr.io/xrplf/clio-pre-commit:14342e087ceb8b593027198bf9ef06a43833c696" }' + container: '{ "image": "ghcr.io/xrplf/xrpld/pre-commit:sha-f56b79f" }' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 99bd26534..7c674ff43 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -21,23 +21,20 @@ jobs: fail-fast: false matrix: include: - - os: macos15 - conan_profile: apple-clang + - os: macos-26-apple-clang-21 + compiler: apple-clang build_type: Release - static: false - os: heavy - conan_profile: gcc + compiler: gcc build_type: Release - static: true - container: '{ "image": "ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696" }' + container: '{ "image": "ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b" }' uses: ./.github/workflows/reusable-build-test.yml with: runs_on: ${{ matrix.os }} container: ${{ matrix.container }} - conan_profile: ${{ matrix.conan_profile }} + compiler: ${{ matrix.compiler }} build_type: ${{ matrix.build_type }} - static: ${{ matrix.static }} run_unit_tests: true run_integration_tests: true upload_clio_server: true @@ -51,13 +48,12 @@ jobs: uses: ./.github/workflows/reusable-build.yml with: runs_on: heavy - container: '{ "image": "ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696" }' - conan_profile: gcc + container: '{ "image": "ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b" }' + compiler: gcc build_type: Release download_ccache: false upload_ccache: false code_coverage: false - static: true upload_clio_server: false package: true version: ${{ github.event_name == 'push' && github.ref_name || '' }} diff --git a/.github/workflows/reusable-build-test.yml b/.github/workflows/reusable-build-test.yml index d3cbe543d..41fb06b38 100644 --- a/.github/workflows/reusable-build-test.yml +++ b/.github/workflows/reusable-build-test.yml @@ -13,11 +13,17 @@ on: required: true type: string - conan_profile: - description: Conan profile to use + compiler: + description: 'Compiler to build with ("gcc", "clang" or "apple-clang")' required: true type: string + sanitizers: + description: 'Sanitizers to enable ("address", "thread", "undefinedbehavior" or empty)' + required: false + type: string + default: "" + build_type: description: Build type required: true @@ -35,12 +41,6 @@ on: type: boolean default: false - static: - description: Whether to build static binaries - required: true - type: boolean - default: true - run_unit_tests: description: Whether to run unit tests required: true @@ -81,12 +81,12 @@ jobs: with: runs_on: ${{ inputs.runs_on }} container: ${{ inputs.container }} - conan_profile: ${{ inputs.conan_profile }} + compiler: ${{ inputs.compiler }} + sanitizers: ${{ inputs.sanitizers }} build_type: ${{ inputs.build_type }} download_ccache: ${{ inputs.download_ccache }} upload_ccache: ${{ inputs.upload_ccache }} code_coverage: false - static: ${{ inputs.static }} upload_clio_server: ${{ inputs.upload_clio_server }} targets: ${{ inputs.targets }} analyze_build_time: false @@ -99,7 +99,8 @@ jobs: with: runs_on: ${{ inputs.runs_on }} container: ${{ inputs.container }} - conan_profile: ${{ inputs.conan_profile }} + compiler: ${{ inputs.compiler }} + sanitizers: ${{ inputs.sanitizers }} build_type: ${{ inputs.build_type }} run_unit_tests: ${{ inputs.run_unit_tests }} run_integration_tests: ${{ inputs.run_integration_tests }} diff --git a/.github/workflows/reusable-build.yml b/.github/workflows/reusable-build.yml index e4d994f8a..291055833 100644 --- a/.github/workflows/reusable-build.yml +++ b/.github/workflows/reusable-build.yml @@ -13,11 +13,17 @@ on: required: true type: string - conan_profile: - description: Conan profile to use + compiler: + description: 'Compiler to build with ("gcc", "clang" or "apple-clang")' required: true type: string + sanitizers: + description: 'Sanitizers to enable ("address", "thread", "undefinedbehavior" or empty)' + required: false + type: string + default: "" + build_type: description: Build type required: true @@ -40,11 +46,6 @@ on: required: true type: boolean - static: - description: Whether to build static binaries - required: true - type: boolean - upload_clio_server: description: Whether to upload clio_server required: true @@ -90,52 +91,56 @@ jobs: if: ${{ runner.os == 'macOS' }} uses: XRPLF/actions/cleanup-workspace@c7d9ce5ebb03c752a354889ecd870cadfc2b1cd4 - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab + uses: XRPLF/actions/prepare-runner@e4b6449d55a61c002d7c3fdfa6c20f721ede0606 with: enable_ccache: ${{ inputs.download_ccache }} - name: Print build environment uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574 - - name: Setup conan on macOS - if: ${{ runner.os == 'macOS' }} - run: ./.github/scripts/conan/init.sh - - - name: Generate cache key - uses: ./.github/actions/cache-key - id: cache_key + - name: Set compiler environment + if: ${{ runner.os == 'Linux' }} + uses: ./.github/actions/set-compiler-env + with: + compiler: ${{ inputs.compiler }} + + - name: Setup conan + run: conan/init.sh + + - name: Generate build identifier + uses: ./.github/actions/build-identifier + id: build_identifier with: - conan_profile: ${{ inputs.conan_profile }} build_type: ${{ inputs.build_type }} + compiler: ${{ inputs.compiler }} code_coverage: ${{ inputs.code_coverage }} + sanitizers: ${{ inputs.sanitizers }} - name: Restore ccache cache if: ${{ inputs.download_ccache && github.ref != 'refs/heads/develop' }} - uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ env.CCACHE_DIR }} - key: ${{ steps.cache_key.outputs.key }} + key: ${{ steps.build_identifier.outputs.cache_key }} restore-keys: | - ${{ steps.cache_key.outputs.restore_keys }} + ${{ steps.build_identifier.outputs.build_identifier }} - name: Run conan uses: ./.github/actions/conan with: - conan_profile: ${{ inputs.conan_profile }} build_type: ${{ inputs.build_type }} + sanitizers: ${{ inputs.sanitizers }} - name: Run CMake uses: ./.github/actions/cmake with: - conan_profile: ${{ inputs.conan_profile }} build_type: ${{ inputs.build_type }} code_coverage: ${{ inputs.code_coverage }} - static: ${{ inputs.static }} time_trace: ${{ inputs.analyze_build_time }} package: ${{ inputs.package }} version: ${{ inputs.version }} @@ -149,14 +154,14 @@ jobs: if: ${{ inputs.analyze_build_time }} run: | ClangBuildAnalyzer --all build/ build_time_report.bin - ClangBuildAnalyzer --analyze build_time_report.bin > build_time_report.txt + ClangBuildAnalyzer --analyze build_time_report.bin >build_time_report.txt cat build_time_report.txt - name: Upload build time analyze report if: ${{ inputs.analyze_build_time }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - name: build_time_report_${{ runner.os }}_${{ inputs.build_type }}_${{ inputs.conan_profile }} + name: build_time_report_${{ steps.build_identifier.outputs.build_identifier }} path: build_time_report.txt - name: Show ccache's statistics and zero it @@ -167,45 +172,45 @@ jobs: - name: Save ccache cache if: ${{ inputs.upload_ccache && github.ref == 'refs/heads/develop' }} - uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ env.CCACHE_DIR }} - key: ${{ steps.cache_key.outputs.key }} + key: ${{ steps.build_identifier.outputs.cache_key }} - name: Strip unit_tests - if: ${{ !endsWith(inputs.conan_profile, 'san') && !inputs.code_coverage && !inputs.analyze_build_time }} + if: ${{ inputs.sanitizers == '' && !inputs.code_coverage && !inputs.analyze_build_time }} run: strip build/clio_tests - name: Strip integration_tests - if: ${{ !endsWith(inputs.conan_profile, 'san') && !inputs.code_coverage && !inputs.analyze_build_time }} + if: ${{ inputs.sanitizers == '' && !inputs.code_coverage && !inputs.analyze_build_time }} run: strip build/clio_integration_tests - name: Upload clio_server if: ${{ inputs.upload_clio_server && !inputs.code_coverage && !inputs.analyze_build_time }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - name: clio_server_${{ runner.os }}_${{ inputs.build_type }}_${{ inputs.conan_profile }} + name: clio_server_${{ steps.build_identifier.outputs.build_identifier }} path: build/clio_server - name: Upload clio_tests if: ${{ !inputs.code_coverage && !inputs.analyze_build_time && !inputs.package }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - name: clio_tests_${{ runner.os }}_${{ inputs.build_type }}_${{ inputs.conan_profile }} + name: clio_tests_${{ steps.build_identifier.outputs.build_identifier }} path: build/clio_tests - name: Upload clio_integration_tests if: ${{ !inputs.code_coverage && !inputs.analyze_build_time && !inputs.package }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - name: clio_integration_tests_${{ runner.os }}_${{ inputs.build_type }}_${{ inputs.conan_profile }} + name: clio_integration_tests_${{ steps.build_identifier.outputs.build_identifier }} path: build/clio_integration_tests - name: Upload Clio Linux package if: ${{ inputs.package }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - name: clio_deb_package_${{ runner.os }}_${{ inputs.build_type }}_${{ inputs.conan_profile }} + name: clio_deb_package_${{ steps.build_identifier.outputs.build_identifier }} path: build/*.deb # This is run as part of the build job, because it requires the following: @@ -227,13 +232,13 @@ jobs: set -e EXPECTED_VERSION="clio-${INPUT_VERSION}" if [[ "${BUILD_TYPE}" == "Debug" ]]; then - EXPECTED_VERSION="${EXPECTED_VERSION}+DEBUG" + EXPECTED_VERSION="${EXPECTED_VERSION}+DEBUG" fi actual_version=$(./build/clio_server --version | head -n 1) if [[ "${actual_version}" != "${EXPECTED_VERSION}" ]]; then - echo "Expected version '${EXPECTED_VERSION}', but got '${actual_version}'" - exit 1 + echo "Expected version '${EXPECTED_VERSION}', but got '${actual_version}'" + exit 1 fi # `codecov/codecov-action` will rerun `gcov` if it's available and build directory is present diff --git a/.github/workflows/reusable-release.yml b/.github/workflows/reusable-release.yml index 80aacaacb..a3a3bac43 100644 --- a/.github/workflows/reusable-release.yml +++ b/.github/workflows/reusable-release.yml @@ -46,7 +46,7 @@ jobs: release: runs-on: heavy container: - image: ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696 + image: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b env: GH_REPO: ${{ github.repository }} GH_TOKEN: ${{ github.token }} @@ -55,12 +55,12 @@ jobs: contents: write steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab + uses: XRPLF/actions/prepare-runner@e4b6449d55a61c002d7c3fdfa6c20f721ede0606 with: enable_ccache: false @@ -81,9 +81,9 @@ jobs: env: RELEASE_HEADER: ${{ inputs.header }} run: | - echo "# Release notes" > "${RUNNER_TEMP}/release_notes.md" - echo "" >> "${RUNNER_TEMP}/release_notes.md" - printf '%s\n' "${RELEASE_HEADER}" >> "${RUNNER_TEMP}/release_notes.md" + echo "# Release notes" >"${RUNNER_TEMP}/release_notes.md" + echo "" >>"${RUNNER_TEMP}/release_notes.md" + printf '%s\n' "${RELEASE_HEADER}" >>"${RUNNER_TEMP}/release_notes.md" - name: Generate changelog if: ${{ inputs.generate_changelog }} @@ -91,7 +91,7 @@ jobs: LAST_TAG="$(gh release view --json tagName -q .tagName --repo XRPLF/clio)" LAST_TAG_COMMIT="$(git rev-parse $LAST_TAG)" BASE_COMMIT="$(git merge-base HEAD $LAST_TAG_COMMIT)" - git-cliff "${BASE_COMMIT}..HEAD" --ignore-tags "nightly|-b|-rc" >> "${RUNNER_TEMP}/release_notes.md" + git-cliff "${BASE_COMMIT}..HEAD" --ignore-tags "nightly|-b|-rc" >>"${RUNNER_TEMP}/release_notes.md" - name: Upload release notes uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -106,10 +106,10 @@ jobs: run: | RELEASES_TO_DELETE=$(gh release list --limit 50 --repo "${GH_REPO}" | grep -E "${DELETE_PATTERN}" | awk -F'\t' '{print $3}' || true) if [ -n "$RELEASES_TO_DELETE" ]; then - for RELEASE in $RELEASES_TO_DELETE; do - echo "Deleting release: $RELEASE" - gh release delete "$RELEASE" --repo "${GH_REPO}" --yes --cleanup-tag - done + for RELEASE in $RELEASES_TO_DELETE; do + echo "Deleting release: $RELEASE" + gh release delete "$RELEASE" --repo "${GH_REPO}" --yes --cleanup-tag + done fi - name: Publish release @@ -121,9 +121,9 @@ jobs: DRAFT_OPTION: ${{ inputs.draft && '--draft' || '' }} run: | gh release create "${RELEASE_VERSION}" \ - ${PRERELEASE_OPTION} \ - --title "${RELEASE_TITLE}" \ - --target "${GITHUB_SHA}" \ - ${DRAFT_OPTION} \ - --notes-file "${RUNNER_TEMP}/release_notes.md" \ - ./release_artifacts/clio_* + ${PRERELEASE_OPTION} \ + --title "${RELEASE_TITLE}" \ + --target "${GITHUB_SHA}" \ + ${DRAFT_OPTION} \ + --notes-file "${RUNNER_TEMP}/release_notes.md" \ + ./release_artifacts/clio_* diff --git a/.github/workflows/reusable-test.yml b/.github/workflows/reusable-test.yml index f635d59ad..c8f9c5cc1 100644 --- a/.github/workflows/reusable-test.yml +++ b/.github/workflows/reusable-test.yml @@ -13,11 +13,17 @@ on: required: true type: string - conan_profile: - description: Conan profile to use + compiler: + description: 'Compiler the binaries were built with ("gcc", "clang" or "apple-clang")' required: true type: string + sanitizers: + description: 'Sanitizers the binaries were built with ("address", "thread", "undefinedbehavior" or empty)' + required: false + type: string + default: "" + build_type: description: Build type required: true @@ -50,13 +56,23 @@ jobs: if: ${{ runner.os == 'macOS' }} uses: XRPLF/actions/cleanup-workspace@c7d9ce5ebb03c752a354889ecd870cadfc2b1cd4 - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 + - name: Generate build identifier + uses: ./.github/actions/build-identifier + id: build_identifier + with: + build_type: ${{ inputs.build_type }} + compiler: ${{ inputs.compiler }} + # code_coverage is run inside build environment + code_coverage: false + sanitizers: ${{ inputs.sanitizers }} + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - name: clio_tests_${{ runner.os }}_${{ inputs.build_type }}_${{ inputs.conan_profile }} + name: clio_tests_${{ steps.build_identifier.outputs.build_identifier }} - name: Make clio_tests executable run: chmod +x ./clio_tests @@ -67,11 +83,11 @@ jobs: run: ./clio_tests - name: Create an issue - if: ${{ steps.run_clio_tests.outcome == 'failure' && endsWith(inputs.conan_profile, 'san') }} - uses: XRPLF/actions/create-issue@fbcc16eb7f20dc3199eaf1aed0d3523a5ba9008c + if: ${{ steps.run_clio_tests.outcome == 'failure' && inputs.sanitizers != '' }} + uses: XRPLF/actions/create-issue@2b8bc36af85b88bca0dd7bfac2e2dc05f94ad712 with: - title: "[${{ inputs.conan_profile }}] reported issues" - body: "Clio tests failed one or more sanitizer checks when built with `${{ inputs.conan_profile }}`." + title: "[${{ inputs.compiler }} ${{ inputs.sanitizers }}] reported issues" + body: "Clio tests failed one or more sanitizers checks when built with `${{ inputs.compiler }}` and the `${{ inputs.sanitizers }}` sanitizers." labels: "bug" assignees: "godexsoft,kuznetsss,mathbunnyru" @@ -88,7 +104,7 @@ jobs: services: scylladb: - image: ${{ inputs.container != '' && 'scylladb/scylla' || '' }} + image: ${{ inputs.container != '' && 'scylladb/scylla:2026.1' || '' }} options: >- --health-cmd "cqlsh -e 'describe cluster'" --health-interval 10s @@ -100,6 +116,20 @@ jobs: if: ${{ runner.os == 'macOS' }} uses: XRPLF/actions/cleanup-workspace@c7d9ce5ebb03c752a354889ecd870cadfc2b1cd4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + + - name: Generate build identifier + uses: ./.github/actions/build-identifier + id: build_identifier + with: + build_type: ${{ inputs.build_type }} + compiler: ${{ inputs.compiler }} + # code_coverage is run inside build environment + code_coverage: false + sanitizers: ${{ inputs.sanitizers }} + - name: Delete and start colima (macOS) # This is a temporary workaround for colima issues on macOS runners if: ${{ runner.os == 'macOS' }} @@ -107,32 +137,38 @@ jobs: colima delete --force colima start + - name: Remove leftover scylladb container (macOS) + # A previous run that didn't clean up (e.g. a cancelled job) can leave the + # container behind, otherwise the name is still taken on the persistent runner. + if: ${{ runner.os == 'macOS' }} + run: docker rm --force scylladb || true + - name: Spin up scylladb (macOS) if: ${{ runner.os == 'macOS' }} timeout-minutes: 1 run: | docker run \ - --detach \ - --name scylladb \ - --health-cmd "cqlsh -e 'describe cluster'" \ - --health-interval 10s \ - --health-timeout 5s \ - --health-retries 5 \ - --publish 9042:9042 \ - --memory 16G \ - scylladb/scylla + --detach \ + --name scylladb \ + --health-cmd "cqlsh -e 'describe cluster'" \ + --health-interval 10s \ + --health-timeout 5s \ + --health-retries 5 \ + --publish 9042:9042 \ + --memory 16G \ + scylladb/scylla:2026.1 - name: Wait for scylladb container to be healthy (macOS) if: ${{ runner.os == 'macOS' }} timeout-minutes: 1 run: | until [ "$(docker inspect -f '{{.State.Health.Status}}' scylladb)" == "healthy" ]; do - sleep 1 + sleep 1 done - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - name: clio_integration_tests_${{ runner.os }}_${{ inputs.build_type }}_${{ inputs.conan_profile }} + name: clio_integration_tests_${{ steps.build_identifier.outputs.build_identifier }} - name: Run clio_integration_tests run: | diff --git a/.github/workflows/reusable-upload-coverage-report.yml b/.github/workflows/reusable-upload-coverage-report.yml index cb7f5878e..2ddc894f9 100644 --- a/.github/workflows/reusable-upload-coverage-report.yml +++ b/.github/workflows/reusable-upload-coverage-report.yml @@ -16,7 +16,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 @@ -27,8 +27,8 @@ jobs: path: build - name: Upload coverage report - if: ${{ hashFiles('build/coverage_report.xml') != '' }} - uses: codecov/codecov-action@57e3a136b779b570ffcdbf80b3bdc90e7fab3de2 # v6.0.0 + if: ${{ github.repository == 'XRPLF/clio' && hashFiles('build/coverage_report.xml') != '' }} + uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 with: files: build/coverage_report.xml fail_ci_if_error: true diff --git a/.github/workflows/sanitizers.yml b/.github/workflows/sanitizers.yml index 2e9a05216..937756789 100644 --- a/.github/workflows/sanitizers.yml +++ b/.github/workflows/sanitizers.yml @@ -19,7 +19,7 @@ on: - conanfile.py - conan.lock - "cmake/**" - # We don't run sanitizer on code change, because it takes too long + # We don't run sanitizers on code change, because it takes too long # - "src/**" # - "tests/**" @@ -36,18 +36,18 @@ jobs: fail-fast: false matrix: compiler: [gcc, clang] - sanitizer_ext: [.asan, .tsan, .ubsan] + sanitizers: [address, thread, undefinedbehavior] build_type: [Release, Debug] uses: ./.github/workflows/reusable-build-test.yml with: runs_on: heavy - container: '{ "image": "ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696" }' + container: '{ "image": "ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b" }' download_ccache: false upload_ccache: false - conan_profile: ${{ matrix.compiler }}${{ matrix.sanitizer_ext }} + compiler: ${{ matrix.compiler }} + sanitizers: ${{ matrix.sanitizers }} build_type: ${{ matrix.build_type }} - static: false run_unit_tests: true run_integration_tests: false upload_clio_server: false diff --git a/.github/workflows/update-docker-ci.yml b/.github/workflows/update-docker-ci.yml deleted file mode 100644 index b434b18a8..000000000 --- a/.github/workflows/update-docker-ci.yml +++ /dev/null @@ -1,364 +0,0 @@ -name: Update CI docker image - -on: - pull_request: - paths: - - .github/workflows/update-docker-ci.yml - - - ".github/actions/build-docker-image/**" - - - "docker/**" - - "!docker/clio/**" - - "!docker/develop/**" - push: - branches: [develop] - paths: - - .github/workflows/update-docker-ci.yml - - - ".github/actions/build-docker-image/**" - - - "docker/**" - - "!docker/clio/**" - - "!docker/develop/**" - workflow_dispatch: - -concurrency: - # Only matches runs for the current workflow - matches against branch & tags - group: ${{ github.workflow }}-${{ github.ref }} - # We want to execute all builds sequentially in develop - cancel-in-progress: false - -env: - CLANG_MAJOR_VERSION: 19 - GCC_MAJOR_VERSION: 15 - GCC_VERSION: 15.2.0 - -defaults: - run: - shell: bash - -jobs: - repo: - name: Calculate repo name - runs-on: ubuntu-latest - outputs: - GHCR_REPO: ${{ steps.set-ghcr-repo.outputs.GHCR_REPO }} - - steps: - - name: Set GHCR_REPO - id: set-ghcr-repo - run: | - echo "GHCR_REPO=$(echo ghcr.io/${{ github.repository_owner }} | tr '[:upper:]' '[:lower:]')" >> ${GITHUB_OUTPUT} - - gcc-amd64: - name: Build and push GCC docker image (amd64) - runs-on: heavy - needs: repo - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - - name: Get changed files - id: changed-files - uses: tj-actions/changed-files@9426d40962ed5378910ee2e21d5f8c6fcbf2dd96 # v47.0.6 - with: - files: "docker/compilers/gcc/**" - - - uses: ./.github/actions/build-docker-image - if: ${{ steps.changed-files.outputs.any_changed == 'true' }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - DOCKERHUB_USER: ${{ secrets.DOCKERHUB_USER }} - DOCKERHUB_PW: ${{ secrets.DOCKERHUB_PW }} - with: - images: | - ${{ needs.repo.outputs.GHCR_REPO }}/clio-gcc - ${{ github.repository_owner == 'XRPLF' && 'rippleci/clio_gcc' || '' }} - push_image: ${{ github.event_name != 'pull_request' }} - directory: docker/compilers/gcc - tags: | - type=raw,value=amd64-latest - type=raw,value=amd64-${{ env.GCC_MAJOR_VERSION }} - type=raw,value=amd64-${{ env.GCC_VERSION }} - type=raw,value=amd64-${{ github.sha }} - platforms: linux/amd64 - build_args: | - GCC_MAJOR_VERSION=${{ env.GCC_MAJOR_VERSION }} - GCC_VERSION=${{ env.GCC_VERSION }} - dockerhub_repo: ${{ github.repository_owner == 'XRPLF' && 'rippleci/clio_gcc' || '' }} - dockerhub_description: GCC compiler for XRPLF/clio. - - gcc-arm64: - name: Build and push GCC docker image (arm64) - runs-on: heavy-arm64 - needs: repo - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - - name: Get changed files - id: changed-files - uses: tj-actions/changed-files@9426d40962ed5378910ee2e21d5f8c6fcbf2dd96 # v47.0.6 - with: - files: "docker/compilers/gcc/**" - - - uses: ./.github/actions/build-docker-image - if: ${{ steps.changed-files.outputs.any_changed == 'true' }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - DOCKERHUB_USER: ${{ secrets.DOCKERHUB_USER }} - DOCKERHUB_PW: ${{ secrets.DOCKERHUB_PW }} - with: - images: | - ${{ needs.repo.outputs.GHCR_REPO }}/clio-gcc - ${{ github.repository_owner == 'XRPLF' && 'rippleci/clio_gcc' || '' }} - push_image: ${{ github.event_name != 'pull_request' }} - directory: docker/compilers/gcc - tags: | - type=raw,value=arm64-latest - type=raw,value=arm64-${{ env.GCC_MAJOR_VERSION }} - type=raw,value=arm64-${{ env.GCC_VERSION }} - type=raw,value=arm64-${{ github.sha }} - platforms: linux/arm64 - build_args: | - GCC_MAJOR_VERSION=${{ env.GCC_MAJOR_VERSION }} - GCC_VERSION=${{ env.GCC_VERSION }} - dockerhub_repo: ${{ github.repository_owner == 'XRPLF' && 'rippleci/clio_gcc' || '' }} - dockerhub_description: GCC compiler for XRPLF/clio. - - gcc-merge: - name: Merge and push multi-arch GCC docker image - runs-on: heavy - needs: [repo, gcc-amd64, gcc-arm64] - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - - name: Get changed files - id: changed-files - uses: tj-actions/changed-files@9426d40962ed5378910ee2e21d5f8c6fcbf2dd96 # v47.0.6 - with: - files: "docker/compilers/gcc/**" - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0 - - - name: Login to GitHub Container Registry - if: ${{ github.event_name != 'pull_request' }} - uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0 - with: - registry: ghcr.io - username: ${{ github.repository_owner }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Login to DockerHub - if: ${{ github.repository_owner == 'XRPLF' && github.event_name != 'pull_request' }} - uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0 - with: - username: ${{ secrets.DOCKERHUB_USER }} - password: ${{ secrets.DOCKERHUB_PW }} - - - name: Create and push multi-arch manifest - if: ${{ github.event_name != 'pull_request' && steps.changed-files.outputs.any_changed == 'true' }} - run: | - push_image() { - image=$1 - - docker buildx imagetools create \ - -t $image:latest \ - -t $image:${{ env.GCC_MAJOR_VERSION }} \ - -t $image:${{ env.GCC_VERSION }} \ - -t $image:${{ github.sha }} \ - $image:arm64-latest \ - $image:amd64-latest - } - push_image ${{ needs.repo.outputs.GHCR_REPO }}/clio-gcc - if [[ ${{ github.repository_owner }} == 'XRPLF' ]]; then - push_image rippleci/clio_clang - fi - - clang: - name: Build and push Clang docker image - runs-on: heavy - needs: repo - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - - name: Get changed files - id: changed-files - uses: tj-actions/changed-files@9426d40962ed5378910ee2e21d5f8c6fcbf2dd96 # v47.0.6 - with: - files: "docker/compilers/clang/**" - - - uses: ./.github/actions/build-docker-image - if: ${{ steps.changed-files.outputs.any_changed == 'true' }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - DOCKERHUB_USER: ${{ secrets.DOCKERHUB_USER }} - DOCKERHUB_PW: ${{ secrets.DOCKERHUB_PW }} - with: - images: | - ${{ needs.repo.outputs.GHCR_REPO }}/clio-clang - ${{ github.repository_owner == 'XRPLF' && 'rippleci/clio_clang' || '' }} - push_image: ${{ github.event_name != 'pull_request' }} - directory: docker/compilers/clang - tags: | - type=raw,value=latest - type=raw,value=${{ env.CLANG_MAJOR_VERSION }} - type=raw,value=${{ github.sha }} - platforms: linux/amd64,linux/arm64 - build_args: | - CLANG_MAJOR_VERSION=${{ env.CLANG_MAJOR_VERSION }} - dockerhub_repo: ${{ github.repository_owner == 'XRPLF' && 'rippleci/clio_clang' || '' }} - dockerhub_description: Clang compiler for XRPLF/clio. - - tools-amd64: - name: Build and push tools docker image (amd64) - runs-on: heavy - needs: [repo, gcc-merge] - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - - name: Get changed files - id: changed-files - uses: tj-actions/changed-files@9426d40962ed5378910ee2e21d5f8c6fcbf2dd96 # v47.0.6 - with: - files: "docker/tools/**" - - - uses: ./.github/actions/build-docker-image - if: ${{ steps.changed-files.outputs.any_changed == 'true' }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - images: | - ${{ needs.repo.outputs.GHCR_REPO }}/clio-tools - push_image: ${{ github.event_name != 'pull_request' }} - directory: docker/tools - tags: | - type=raw,value=amd64-latest - type=raw,value=amd64-${{ github.sha }} - platforms: linux/amd64 - build_args: | - GHCR_REPO=${{ needs.repo.outputs.GHCR_REPO }} - GCC_VERSION=${{ env.GCC_VERSION }} - - tools-arm64: - name: Build and push tools docker image (arm64) - runs-on: heavy-arm64 - needs: [repo, gcc-merge] - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - - name: Get changed files - id: changed-files - uses: tj-actions/changed-files@9426d40962ed5378910ee2e21d5f8c6fcbf2dd96 # v47.0.6 - with: - files: "docker/tools/**" - - - uses: ./.github/actions/build-docker-image - if: ${{ steps.changed-files.outputs.any_changed == 'true' }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - images: | - ${{ needs.repo.outputs.GHCR_REPO }}/clio-tools - push_image: ${{ github.event_name != 'pull_request' }} - directory: docker/tools - tags: | - type=raw,value=arm64-latest - type=raw,value=arm64-${{ github.sha }} - platforms: linux/arm64 - build_args: | - GHCR_REPO=${{ needs.repo.outputs.GHCR_REPO }} - GCC_VERSION=${{ env.GCC_VERSION }} - - tools-merge: - name: Merge and push multi-arch tools docker image - runs-on: heavy - needs: [repo, tools-amd64, tools-arm64] - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - - name: Get changed files - id: changed-files - uses: tj-actions/changed-files@9426d40962ed5378910ee2e21d5f8c6fcbf2dd96 # v47.0.6 - with: - files: "docker/tools/**" - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0 - - - name: Login to GitHub Container Registry - if: ${{ github.event_name != 'pull_request' }} - uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0 - with: - registry: ghcr.io - username: ${{ github.repository_owner }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Create and push multi-arch manifest - if: ${{ github.event_name != 'pull_request' && steps.changed-files.outputs.any_changed == 'true' }} - run: | - image=${{ needs.repo.outputs.GHCR_REPO }}/clio-tools - docker buildx imagetools create \ - -t $image:latest \ - -t $image:${{ github.sha }} \ - $image:arm64-latest \ - $image:amd64-latest - - pre-commit: - name: Build and push pre-commit docker image - runs-on: heavy - needs: [repo, tools-merge] - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - uses: ./.github/actions/build-docker-image - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - images: | - ${{ needs.repo.outputs.GHCR_REPO }}/clio-pre-commit - push_image: ${{ github.event_name != 'pull_request' }} - directory: docker/pre-commit - tags: | - type=raw,value=latest - type=raw,value=${{ github.sha }} - platforms: linux/amd64,linux/arm64 - build_args: | - GHCR_REPO=${{ needs.repo.outputs.GHCR_REPO }} - - ci: - name: Build and push CI docker image - runs-on: heavy - needs: [repo, gcc-merge, clang, tools-merge] - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - uses: ./.github/actions/build-docker-image - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - DOCKERHUB_USER: ${{ secrets.DOCKERHUB_USER }} - DOCKERHUB_PW: ${{ secrets.DOCKERHUB_PW }} - with: - images: | - ${{ needs.repo.outputs.GHCR_REPO }}/clio-ci - ${{ github.repository_owner == 'XRPLF' && 'rippleci/clio_ci' || '' }} - push_image: ${{ github.event_name != 'pull_request' }} - directory: docker/ci - tags: | - type=raw,value=latest - type=raw,value=gcc_${{ env.GCC_MAJOR_VERSION }}_clang_${{ env.CLANG_MAJOR_VERSION }} - type=raw,value=${{ github.sha }} - platforms: linux/amd64,linux/arm64 - build_args: | - GHCR_REPO=${{ needs.repo.outputs.GHCR_REPO }} - CLANG_MAJOR_VERSION=${{ env.CLANG_MAJOR_VERSION }} - GCC_MAJOR_VERSION=${{ env.GCC_MAJOR_VERSION }} - GCC_VERSION=${{ env.GCC_VERSION }} - dockerhub_repo: ${{ github.repository_owner == 'XRPLF' && 'rippleci/clio_ci' || '' }} - dockerhub_description: CI image for XRPLF/clio. diff --git a/.github/workflows/upload-conan-deps.yml b/.github/workflows/upload-conan-deps.yml index c8ea52ffe..ade3a3dc9 100644 --- a/.github/workflows/upload-conan-deps.yml +++ b/.github/workflows/upload-conan-deps.yml @@ -22,10 +22,10 @@ on: - .github/actions/conan/action.yml - ".github/scripts/conan/**" - - "!.github/scripts/conan/regenerate_lockfile.sh" - conanfile.py - conan.lock + - conan/profiles/** push: branches: [develop] paths: @@ -33,10 +33,10 @@ on: - .github/actions/conan/action.yml - ".github/scripts/conan/**" - - "!.github/scripts/conan/regenerate_lockfile.sh" - conanfile.py - conan.lock + - conan/profiles/** concurrency: group: ${{ github.workflow }}-${{ github.ref }} @@ -52,14 +52,14 @@ jobs: outputs: matrix: ${{ steps.set-matrix.outputs.matrix }} steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Calculate conan matrix id: set-matrix - run: .github/scripts/conan/generate_matrix.py >> "${GITHUB_OUTPUT}" + run: .github/scripts/conan/generate_matrix.py >>"${GITHUB_OUTPUT}" upload-conan-deps: - name: Build ${{ matrix.compiler }}${{ matrix.sanitizer_ext }} ${{ matrix.build_type }} + name: Build ${{ matrix.compiler }} ${{ matrix.sanitizers }} ${{ matrix.build_type }} needs: generate-matrix @@ -71,42 +71,48 @@ jobs: runs-on: ${{ matrix.os }} container: ${{ matrix.container != '' && fromJson(matrix.container) || null }} - env: - CONAN_PROFILE: ${{ matrix.compiler }}${{ matrix.sanitizer_ext }} - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab + uses: XRPLF/actions/prepare-runner@e4b6449d55a61c002d7c3fdfa6c20f721ede0606 with: enable_ccache: false - name: Print build environment uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574 - - name: Setup conan on macOS - if: ${{ runner.os == 'macOS' }} - run: ./.github/scripts/conan/init.sh + - name: Set compiler environment + if: ${{ runner.os == 'Linux' }} + uses: ./.github/actions/set-compiler-env + with: + compiler: ${{ matrix.compiler }} + + - name: Setup conan + run: conan/init.sh - name: Show conan profile - run: conan profile show --profile:all ${{ env.CONAN_PROFILE }} + env: + SANITIZERS: ${{ matrix.sanitizers }} + run: conan profile show --profile:all ci - name: Run conan uses: ./.github/actions/conan with: - conan_profile: ${{ env.CONAN_PROFILE }} + sanitizers: ${{ matrix.sanitizers }} # We check that everything builds fine from source on scheduled runs # But we do build and upload packages with build=missing by default force_conan_source_build: ${{ github.event_name == 'schedule' || github.event.inputs.force_source_build == 'true' }} build_type: ${{ matrix.build_type }} - - name: Login to Conan - if: ${{ github.repository_owner == 'XRPLF' && github.event_name != 'pull_request' }} - run: conan remote login -p ${{ secrets.CONAN_PASSWORD }} xrplf ${{ secrets.CONAN_USERNAME }} + - name: Log into Conan remote + if: ${{ github.repository == 'XRPLF/clio' && github.event_name != 'pull_request' }} + run: conan remote login -p ${{ secrets.NEXUS_REMOTE_PASSWORD }} xrplf ${{ secrets.NEXUS_REMOTE_USERNAME }} - name: Upload Conan packages - if: ${{ github.repository_owner == 'XRPLF' && github.event_name != 'pull_request' && github.event_name != 'schedule' }} + if: ${{ github.repository == 'XRPLF/clio' && github.event_name != 'pull_request' && github.event_name != 'schedule' }} env: FORCE_OPTION: ${{ github.event.inputs.force_upload == 'true' && '--force' || '' }} + CONAN_LOGIN_USERNAME_XRPLF: ${{ secrets.NEXUS_REMOTE_USERNAME }} + CONAN_PASSWORD_XRPLF: ${{ secrets.NEXUS_REMOTE_PASSWORD }} run: conan upload "*" -r=xrplf --confirm ${FORCE_OPTION} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 584c11b47..118e35ee6 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -29,12 +29,12 @@ repos: # Autoformat: YAML, JSON, Markdown, etc. - repo: https://github.com/rbubley/mirrors-prettier - rev: 515f543f5718ebfd6ce22e16708bb32c68ff96e1 # frozen: v3.8.3 + rev: 0ee178619d696787ca73d210cc191d720868c631 # frozen: v3.9.6 hooks: - id: prettier - repo: https://github.com/igorshubovych/markdownlint-cli - rev: e72a3ca1632f0b11a07d171449fe447a7ff6795e # frozen: v0.48.0 + rev: 5b5dddc4fb0f83c3ea1fc5616fa63e115dce83e0 # frozen: v0.49.1 hooks: - id: markdownlint-fix exclude: LICENSE.md @@ -49,7 +49,7 @@ repos: entry: hadolint/hadolint:v2.14.0 hadolint - repo: https://github.com/codespell-project/codespell - rev: 2ccb47ff45ad361a21071a7eedda4c37e6ae8c5a # frozen: v2.4.2 + rev: 57b21406f092110c18776e39b0bda50d37c945c8 # frozen: v2.4.3 hooks: - id: codespell args: @@ -59,7 +59,7 @@ repos: ] - repo: https://github.com/psf/black-pre-commit-mirror - rev: fa505ab9c3e0fedafe1709fd7ac2b5f8996c670d # frozen: 26.3.1 + rev: 4160603246a6b365d4a2af661c6d71b0a0f50478 # frozen: 26.5.1 hooks: - id: black @@ -67,7 +67,7 @@ repos: rev: 05c1426671b9237fb5e1444dd63aa5731bec0dfb # frozen: v3.13.1-1 hooks: - id: shfmt - args: ["-i", "4", "--write"] + args: [--write, --indent=4, --case-indent=true] # Running some C++ hooks before clang-format # to ensure that the style is consistent. @@ -93,15 +93,21 @@ repos: types: [c++] language: script + - id: fix-pragma-once + name: fix missing '#pragma once' declarations in header files + language: python + entry: ./pre-commit-hooks/fix_pragma_once.py + files: \.(h|hpp)$ + - repo: https://github.com/pre-commit/mirrors-clang-format - rev: 39233709be54124a7371a50cbfc5325bd4fb9d90 # frozen: v22.1.4 + rev: f4d7745e17a28aad7eed2f4874ca8d1568c11c4c # frozen: v22.1.8 hooks: - id: clang-format args: [--style=file] types: [c++] - repo: https://github.com/BlankSpruce/gersemi-pre-commit - rev: fc2d0aefdd73b719180177a2d4a7a56cef4d3ab6 # frozen: 0.27.2 + rev: e98930bdc210d3387007f9252d8c1694ea7e410f # frozen: 0.27.7 hooks: - id: gersemi diff --git a/CMakeLists.txt b/CMakeLists.txt index d6f725353..b68eca363 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,7 +16,6 @@ option(docs "Generate doxygen docs" FALSE) option(coverage "Build test coverage report" FALSE) option(package "Create distribution packages" FALSE) option(lint "Run clang-tidy checks during compilation" FALSE) -option(static "Statically linked Clio" FALSE) option(snapshot "Build snapshot tool" FALSE) option( time_trace @@ -25,10 +24,7 @@ option( ) # ========================================================================== # -set(san "" CACHE STRING "Add sanitizer instrumentation") set(CMAKE_EXPORT_COMPILE_COMMANDS TRUE) -set_property(CACHE san PROPERTY STRINGS ";undefined;memory;address;thread") -# ========================================================================== # set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH}) @@ -39,9 +35,36 @@ include(ClangTidy) include(Linker) add_library(clio_options INTERFACE) -target_compile_features(clio_options INTERFACE cxx_std_23) # Clio needs c++23 but deps can remain c++20 for now +target_compile_features(clio_options INTERFACE cxx_std_23) target_include_directories(clio_options INTERFACE ${CMAKE_SOURCE_DIR}/src) +if( + CMAKE_CXX_COMPILER_ID STREQUAL "Clang" + OR CMAKE_CXX_COMPILER_ID STREQUAL "GNU" +) + # Note: -static-libstdc++ can statically link both libstdc++ and libc++ + target_link_libraries( + clio_options + INTERFACE -static-libstdc++ -static-libgcc + ) +endif() + +# On aarch64, libatomic is required for atomic operations. It is not needed on x86_64. +# Linking it statically on Linux +if( + CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64" + AND CMAKE_SYSTEM_NAME STREQUAL "Linux" +) + target_link_options( + clio_options + INTERFACE -Wl,--push-state -Wl,-Bstatic -latomic -Wl,--pop-state + ) +endif() + +# Apply sanitizer instrumentation if requested and define SANITIZERS_ENABLED. +# Must come before the modules and subdirectories below that key off it. +include(Sanitizers) + if(verbose) set(CMAKE_VERBOSE_MAKEFILE TRUE) endif() @@ -49,7 +72,7 @@ endif() # Clio tweaks and checks include(CheckCompiler) include(Settings) -include(SourceLocation) +include(PatchNixBinary) # Clio deps include(deps/libxrpl) @@ -68,29 +91,6 @@ if(benchmark) add_subdirectory(benchmarks) endif() -# Enable selected sanitizer if enabled via `san` -if(san) - set(SUPPORTED_SANITIZERS "address" "thread" "memory" "undefined") - if(NOT san IN_LIST SUPPORTED_SANITIZERS) - message( - FATAL_ERROR - "Error: Unsupported sanitizer '${san}'. Supported values are: ${SUPPORTED_SANITIZERS}." - ) - endif() - - # Sanitizers recommend minimum of -O1 for reasonable performance so we enable it for debug builds - set(SAN_OPTIMIZATION_FLAG "") - if(CMAKE_BUILD_TYPE STREQUAL "Debug") - set(SAN_OPTIMIZATION_FLAG -O1) - endif() - target_compile_options( - clio_options - INTERFACE ${SAN_OPTIMIZATION_FLAG} ${SAN_FLAG} -fno-omit-frame-pointer - ) - - target_link_libraries(clio_options INTERFACE ${SAN_FLAG} ${SAN_LIB}) -endif() - # Generate `docs` target for doxygen documentation if enabled Note: use `make docs` to generate the documentation if(docs) add_subdirectory(docs) diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 000000000..f92cb8192 --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,4 @@ +# By default, anyone can review changes. + +# The CI tooling team should review changes to the CI configuration. +/.github/ @XRPLF/ci-tooling diff --git a/benchmarks/rpc/WorkQueueBenchmarks.cpp b/benchmarks/rpc/WorkQueueBenchmarks.cpp index 854ce8255..632ed4404 100644 --- a/benchmarks/rpc/WorkQueueBenchmarks.cpp +++ b/benchmarks/rpc/WorkQueueBenchmarks.cpp @@ -26,7 +26,7 @@ using namespace util::config; namespace { -auto const kCONFIG = ClioConfigDefinition{ +auto const kConfig = ClioConfigDefinition{ {"prometheus.compress_reply", ConfigValue{ConfigType::Boolean}.defaultValue(true)}, {"prometheus.enabled", ConfigValue{ConfigType::Boolean}.defaultValue(true)}, {"log.channels.[].channel", Array{ConfigValue{ConfigType::String}}}, @@ -48,10 +48,10 @@ auto const kCONFIG = ClioConfigDefinition{ void init() { - static std::once_flag kONCE; - std::call_once(kONCE, [] { - PrometheusService::init(kCONFIG); - (void)util::LogService::init(kCONFIG); + static std::once_flag kOnce; + std::call_once(kOnce, [] { + PrometheusService::init(kConfig); + (void)util::LogService::init(kConfig); }); } diff --git a/benchmarks/util/async/ExecutionContextBenchmarks.cpp b/benchmarks/util/async/ExecutionContextBenchmarks.cpp index fa93f3d16..6410de603 100644 --- a/benchmarks/util/async/ExecutionContextBenchmarks.cpp +++ b/benchmarks/util/async/ExecutionContextBenchmarks.cpp @@ -82,7 +82,7 @@ public: void run(std::size_t numThreads) { - using OpType = typename CtxType::template StoppableOperation; + using OpType = CtxType::template StoppableOperation; CtxType ctx{numThreads}; std::vector operations; @@ -169,11 +169,11 @@ public: static auto generateData() { - constexpr auto kTOTAL = 10'000; + constexpr auto kTotal = 10'000; std::vector data; - data.reserve(kTOTAL); + data.reserve(kTotal); util::MTRandomGenerator randomGenerator; - for (auto i = 0; i < kTOTAL; ++i) + for (auto i = 0; i < kTotal; ++i) data.push_back(randomGenerator.uniform(1, 100'000'000)); return data; diff --git a/benchmarks/util/log/LoggerBenchmark.cpp b/benchmarks/util/log/LoggerBenchmark.cpp index e175bf7ce..b8a519cdc 100644 --- a/benchmarks/util/log/LoggerBenchmark.cpp +++ b/benchmarks/util/log/LoggerBenchmark.cpp @@ -21,7 +21,7 @@ using namespace util; -static constexpr auto kLOG_FORMAT = "%Y-%m-%d %H:%M:%S.%f %^%3!l:%n%$ - %v"; +static constexpr auto kLogFormat = "%Y-%m-%d %H:%M:%S.%f %^%3!l:%n%$ - %v"; struct BenchmarkLoggingInitializer { [[nodiscard]] static std::shared_ptr @@ -32,7 +32,7 @@ struct BenchmarkLoggingInitializer { .logDir = logDir, .rotation = LogService::RotationParams{.sizeMB = sizeMB, .maxFiles = maxFiles}, }, - kLOG_FORMAT + kLogFormat ); } @@ -71,9 +71,9 @@ benchmarkConcurrentFileLogging(benchmark::State& state) state.PauseTiming(); std::filesystem::create_directories(logDir); - static constexpr size_t kQUEUE_SIZE = 8192; - static constexpr size_t kTHREAD_COUNT = 1; - spdlog::init_thread_pool(kQUEUE_SIZE, kTHREAD_COUNT); + static constexpr size_t kQueueSize = 8192; + static constexpr size_t kThreadCount = 1; + spdlog::init_thread_pool(kQueueSize, kThreadCount); auto fileSink = BenchmarkLoggingInitializer::createFileSink(logDir, 5, 25); diff --git a/cmake/CheckCompiler.cmake b/cmake/CheckCompiler.cmake index f0ce4e534..c333093ee 100644 --- a/cmake/CheckCompiler.cmake +++ b/cmake/CheckCompiler.cmake @@ -19,30 +19,3 @@ else() "Supported compilers: AppleClang 15+, Clang 16+, GCC 12+" ) endif() - -if(san) - string(TOLOWER ${san} san) - set(SAN_FLAG "-fsanitize=${san}") - set(SAN_LIB "") - if(is_gcc) - if(san STREQUAL "address") - set(SAN_LIB "asan") - elseif(san STREQUAL "thread") - set(SAN_LIB "tsan") - elseif(san STREQUAL "memory") - set(SAN_LIB "msan") - elseif(san STREQUAL "undefined") - set(SAN_LIB "ubsan") - endif() - endif() - set(_saved_CRL ${CMAKE_REQUIRED_LIBRARIES}) - set(CMAKE_REQUIRED_LIBRARIES "${SAN_FLAG};${SAN_LIB}") - check_cxx_compiler_flag(${SAN_FLAG} COMPILER_SUPPORTS_SAN) - set(CMAKE_REQUIRED_LIBRARIES ${_saved_CRL}) - if(NOT COMPILER_SUPPORTS_SAN) - message( - FATAL_ERROR - "${san} sanitizer does not seem to be supported by your compiler" - ) - endif() -endif() diff --git a/cmake/PatchNixBinary.cmake b/cmake/PatchNixBinary.cmake new file mode 100644 index 000000000..c6355fefc --- /dev/null +++ b/cmake/PatchNixBinary.cmake @@ -0,0 +1,55 @@ +#[===================================================================[ + Patch executables to run in non-Nix environments. + + The Nix-based CI image links binaries against an ELF interpreter (loader) + that lives in the Nix store, so the resulting binaries don't run elsewhere + (including once installed from the .deb package). `patch_nix_binary` adds a + POST_BUILD step that resets the interpreter to the system default loader and + drops the rpath. + + This is only active inside the Nix-based image, detected by the presence of + /tmp/loader-path.sh (shipped by that image, resolves the default loader). It + is skipped for sanitizer builds, whose runtime libraries are resolved through + the rpath. Everywhere else `patch_nix_binary` is a no-op. +#]===================================================================] + +include_guard(GLOBAL) + +# Provided by the Nix-based CI image; prints the system default ELF loader path. +set(_loader_path_script "/tmp/loader-path.sh") + +if( + CMAKE_SYSTEM_NAME STREQUAL "Linux" + AND NOT SANITIZERS_ENABLED + AND EXISTS "${_loader_path_script}" +) + execute_process( + COMMAND "${_loader_path_script}" + OUTPUT_VARIABLE DEFAULT_LOADER_PATH + OUTPUT_STRIP_TRAILING_WHITESPACE + COMMAND_ERROR_IS_FATAL ANY + ) + find_program(PATCHELF_COMMAND patchelf REQUIRED) + set(PATCH_NIX_BINARIES TRUE) + message( + STATUS + "Binaries will be patched to use loader '${DEFAULT_LOADER_PATH}'" + ) +else() + set(PATCH_NIX_BINARIES FALSE) +endif() + +function(patch_nix_binary target) + if(NOT PATCH_NIX_BINARIES) + return() + endif() + add_custom_command( + TARGET ${target} + POST_BUILD + COMMAND + "${PATCHELF_COMMAND}" --set-interpreter "${DEFAULT_LOADER_PATH}" + --remove-rpath "$" + COMMENT "Patching ${target}: set default loader, remove rpath" + VERBATIM + ) +endfunction() diff --git a/cmake/Sanitizers.cmake b/cmake/Sanitizers.cmake new file mode 100644 index 000000000..4d1f76710 --- /dev/null +++ b/cmake/Sanitizers.cmake @@ -0,0 +1,47 @@ +#[===================================================================[ + Apply sanitizer flags built by the Conan profile. + + Parsing, validation, and flag construction are performed in + conan/profiles/sanitizers. This module reads the following CMake variables + injected by the Conan toolchain via extra_variables: + + - SANITIZERS: The active sanitizers (e.g. "address"). + - SANITIZERS_COMPILER_FLAGS: Space-separated compiler flags. + - SANITIZERS_LINKER_FLAGS: Space-separated linker flags. + + It defines SANITIZERS_ENABLED for the rest of the build to key off, and + applies the flags to the 'clio_options' interface library. +#]===================================================================] + +include_guard(GLOBAL) + +if(NOT DEFINED SANITIZERS) + set(SANITIZERS_ENABLED FALSE) + return() +endif() +set(SANITIZERS_ENABLED TRUE) + +message(STATUS "=== Configuring sanitizers ===") +message(STATUS " SANITIZERS: ${SANITIZERS}") +message(STATUS " Compile flags: ${SANITIZERS_COMPILER_FLAGS}") +message(STATUS " Link flags: ${SANITIZERS_LINKER_FLAGS}") + +# Flags arrive as space-separated strings; split into CMake lists before use +separate_arguments( + sanitizers_compiler_flags + UNIX_COMMAND + "${SANITIZERS_COMPILER_FLAGS}" +) +separate_arguments( + sanitizers_linker_flags + UNIX_COMMAND + "${SANITIZERS_LINKER_FLAGS}" +) + +target_compile_options( + clio_options + INTERFACE + $<$:${sanitizers_compiler_flags}> + $<$:${sanitizers_compiler_flags}> +) +target_link_options(clio_options INTERFACE ${sanitizers_linker_flags}) diff --git a/cmake/Settings.cmake b/cmake/Settings.cmake index b31db9c21..e0311ad4f 100644 --- a/cmake/Settings.cmake +++ b/cmake/Settings.cmake @@ -40,7 +40,7 @@ if(is_appleclang) list(APPEND COMPILER_FLAGS -Wreorder-init-list) endif() -if(san) +if(SANITIZERS_ENABLED) # When building with sanitizers some compilers will actually produce extra warnings/errors. We don't want this yet, # at least not until we have fixed all runtime issues reported by the sanitizers. Once that is done we can start # removing some of these and trying to fix it in our codebase. We can never remove all of below because most of them @@ -85,3 +85,22 @@ target_compile_options(clio_options INTERFACE ${COMPILER_FLAGS}) # Add debug symbols for all builds, including Release. This is needed to get useful stack traces in production. target_compile_options(clio_options INTERFACE -g) + +# Keep -stdlib=libstdc++ off the compile commands, but preserve it for linking. +# +# Conan turns `compiler.libcxx=libstdc++` into `-stdlib=libstdc++` and puts it in CMAKE_CXX_FLAGS, which CMake passes to +# BOTH compile and link steps. On a normal Clang the compile step consumes it while choosing the C++ stdlib include +# paths. The Nixpkgs Clang wrapper (used by our CI image) supplies those paths itself (via -nostdinc++), so at compile +# time the flag is unused -> Clang errors under our -Werror. At link time the flag IS consumed (it selects the C++ +# runtime), so we move it there instead of dropping it entirely. +get_filename_component(_cxx_real "${CMAKE_CXX_COMPILER}" REALPATH) +if( + _cxx_real MATCHES "^/nix/store/" + AND CMAKE_SYSTEM_NAME STREQUAL "Linux" + AND is_clang + AND CMAKE_CXX_FLAGS MATCHES "stdlib=libstdc" +) + string(REPLACE "-stdlib=libstdc++" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") + string(STRIP "${CMAKE_CXX_FLAGS}" CMAKE_CXX_FLAGS) + add_link_options($<$:-stdlib=libstdc++>) +endif() diff --git a/cmake/deps/Boost.cmake b/cmake/deps/Boost.cmake index f4dd99e68..80b5c8e07 100644 --- a/cmake/deps/Boost.cmake +++ b/cmake/deps/Boost.cmake @@ -6,5 +6,5 @@ find_package( 1.82 REQUIRED CONFIG - COMPONENTS program_options coroutine system log log_setup + COMPONENTS program_options system log log_setup ) diff --git a/cmake/deps/OpenSSL.cmake b/cmake/deps/OpenSSL.cmake index c1831611f..e58ea406a 100644 --- a/cmake/deps/OpenSSL.cmake +++ b/cmake/deps/OpenSSL.cmake @@ -1,4 +1,4 @@ -find_package(OpenSSL 1.1.1 REQUIRED CONFIG) +find_package(OpenSSL 3 REQUIRED CONFIG) set_target_properties( OpenSSL::SSL diff --git a/cmake/deps/libbacktrace.cmake b/cmake/deps/libbacktrace.cmake index 3015d5781..0e81bd89a 100644 --- a/cmake/deps/libbacktrace.cmake +++ b/cmake/deps/libbacktrace.cmake @@ -1,4 +1,4 @@ -if("${san}" STREQUAL "") +if(NOT SANITIZERS_ENABLED) target_compile_definitions(clio_options INTERFACE BOOST_STACKTRACE_LINK) target_compile_definitions( clio_options diff --git a/cmake/pkg/postinst b/cmake/pkg/postinst index d10353d9b..6f802fdbe 100755 --- a/cmake/pkg/postinst +++ b/cmake/pkg/postinst @@ -10,36 +10,36 @@ CLIO_BIN="$CLIO_PREFIX/bin/${CLIO_EXECUTABLE}" CLIO_CONFIG="$CLIO_PREFIX/etc/config.json" case "$1" in -configure) - if ! id -u "$USER_NAME" >/dev/null 2>&1; then - # Users who should not have a home directory should have their home directory set to /nonexistent - # https://www.debian.org/doc/debian-policy/ch-opersys.html#non-existent-home-directories - useradd \ - --system \ - --home-dir /nonexistent \ - --no-create-home \ - --shell /usr/sbin/nologin \ - --comment "system user for ${CLIO_EXECUTABLE}" \ - --user-group \ - ${USER_NAME} - fi + configure) + if ! id -u "$USER_NAME" >/dev/null 2>&1; then + # Users who should not have a home directory should have their home directory set to /nonexistent + # https://www.debian.org/doc/debian-policy/ch-opersys.html#non-existent-home-directories + useradd \ + --system \ + --home-dir /nonexistent \ + --no-create-home \ + --shell /usr/sbin/nologin \ + --comment "system user for ${CLIO_EXECUTABLE}" \ + --user-group \ + ${USER_NAME} + fi - install -d -o "$USER_NAME" -g "$GROUP_NAME" /var/log/clio + install -d -o "$USER_NAME" -g "$GROUP_NAME" /var/log/clio - if [ -f "$CLIO_CONFIG" ]; then - chown "$USER_NAME:$GROUP_NAME" "$CLIO_CONFIG" - fi + if [ -f "$CLIO_CONFIG" ]; then + chown "$USER_NAME:$GROUP_NAME" "$CLIO_CONFIG" + fi - chown -R "$USER_NAME:$GROUP_NAME" "$CLIO_PREFIX" + chown -R "$USER_NAME:$GROUP_NAME" "$CLIO_PREFIX" - ln -sf "$CLIO_BIN" "/usr/bin/${CLIO_EXECUTABLE}" + ln -sf "$CLIO_BIN" "/usr/bin/${CLIO_EXECUTABLE}" - ;; -abort-upgrade | abort-remove | abort-deconfigure) ;; -*) - echo "postinst called with unknown argument \`$1'" >&2 - exit 1 - ;; + ;; + abort-upgrade | abort-remove | abort-deconfigure) ;; + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; esac exit 0 diff --git a/conan.lock b/conan.lock index b256432b2..bd8e7e0e6 100644 --- a/conan.lock +++ b/conan.lock @@ -1,61 +1,86 @@ { "version": "0.5", "requires": [ - "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1774439233.809", - "xxhash/0.8.3#681d36a0a6111fc56e5e45ea182c19cc%1765850149.987", - "xrpl/3.1.3#eabc6838b4553671bdde4b3aa1f8e3e6%1778495466.414", - "sqlite3/3.49.1#8631739a4c9b93bd3d6b753bac548a63%1765850149.926", - "spdlog/1.17.0#bcbaaf7147bda6ad24ffbd1ac3d7142c%1768312128.781", - "soci/4.0.3#fe32b9ad5eb47e79ab9e45a68f363945%1774450067.231", - "re2/20230301#ca3b241baec15bd31ea9187150e0b333%1765850148.103", - "rapidjson/cci.20220822#1b9d8c2256876a154172dc5cfbe447c6%1754325007.656", - "protobuf/3.21.12#44ee56c0a6eea0c19aeeaca680370b88%1764175361.456", - "openssl/1.1.1w#a8f0792d7c5121b954578a7149d23e03%1756223730.729", - "nudb/2.0.9#11149c73f8f2baff9a0198fe25971fc7%1775040983.408", - "minizip/1.2.13#9e87d57804bd372d6d1e32b1871517a3%1754325004.374", - "lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504%1765850143.914", - "libuv/1.46.0#dc28c1f653fa197f00db5b577a6f6011%1754325003.592", - "libiconv/1.17#1e65319e945f2d31941a9d28cc13c058%1765842973.492", - "libbacktrace/cci.20210118#a7691bfccd8caaf66309df196790a5a1%1765842973.03", - "libarchive/3.8.1#ffee18995c706e02bf96e7a2f7042e0d%1765850144.736", - "http_parser/2.9.4#98d91690d6fd021e9e624218a85d9d97%1754325001.385", - "gtest/1.17.0#5224b3b3ff3b4ce1133cbdd27d53ee7d%1768312129.152", - "grpc/1.50.1#02291451d1e17200293a409410d1c4e1%1756234248.958", - "fmt/12.1.0#50abab23274d56bb8f42c94b3b9a40c7%1763984116.926", - "doctest/2.4.11#a4211dfc329a16ba9f280f9574025659%1756234220.819", - "date/3.0.4#862e11e80030356b53c2c38599ceb32b%1765850143.772", - "cassandra-cpp-driver/2.17.0#bd3934138689482102c265d01288a316%1764175359.611", - "c-ares/1.34.6#545240bb1c40e2cacd4362d6b8967650%1774439234.681", - "bzip2/1.0.8#c470882369c2d95c5c77e970c0c7e321%1765850143.837", - "boost/1.83.0#91d8b1572534d2c334d6790e3c34d0c1%1764175359.61", - "benchmark/1.9.4#ce4403f7a24d3e1f907cd9da4b678be4%1754578869.672", - "abseil/20230802.1#90ba607d4ee8fb5fb157c3db540671fc%1764175359.429" + "zlib/1.3.2#1cb806da49011867778ffb6ac7190fcb%1782392402.122708", + "xxhash/0.8.3#681d36a0a6111fc56e5e45ea182c19cc%1782392402.420688", + "xrpl/3.3.0-rc1#526e843efce69a95339435869d2ec42c%1784212398.613288", + "sqlite3/3.53.0#324ada52333108388a9a6108bfa96734%1782392403.185447", + "spdlog/1.17.0#bcbaaf7147bda6ad24ffbd1ac3d7142c%1782736610.443882", + "soci/4.0.3#e726491a03468795453f7c83fc924a96%1782392402.679521", + "snappy/1.1.10#968fef506ff261592ec30c574d4a7809%1782307151.633168", + "secp256k1/0.7.1#b1f450b7f78a36fff75bb6934a356f3a%1782338841.3729", + "rocksdb/10.5.1#4a197eca381a3e5ae8adf8cffa5aacd0%1782392413.075713", + "re2/20251105#8579cfd0bda4daf0683f9e3898f964b4%1782392402.431897", + "rapidjson/cci.20220822#1b9d8c2256876a154172dc5cfbe447c6%1782736605.214886", + "protobuf/6.33.5#ff253ead763bd8d9904a52979cd21e81%1782392410.233933", + "openssl/3.6.3#f806de8933e3bf6f01016c6a888cee2e%1783945160.863288", + "nudb/2.0.9#11149c73f8f2baff9a0198fe25971fc7%1782392402.297166", + "mpt-crypto/0.4.0-rc4#ffdba12f2332357f0d8b0ae944cfff52%1784138702.932355", + "minizip/1.2.13#64dfec2ee447ab6c0c7eab967815a762%1782736605.272739", + "lz4/1.10.0#982d9b673900f665a1da109e09c17cab%1782392402.164188", + "libuv/1.46.0#e1a592bf7c0f37802889ca2c795fb26c%1782736605.776567", + "libiconv/1.17#9923bc6dc6f106646d6967e0039a5ada%1782392792.775744", + "libbacktrace/cci.20210118#a7691bfccd8caaf66309df196790a5a1%1782392402.420732", + "libarchive/3.8.7#c446109bd1f1d8ba7936c94189bc50e6%1782392403.066892", + "http_parser/2.9.4#98d91690d6fd021e9e624218a85d9d97%1782736605.237778", + "gtest/1.17.0#5224b3b3ff3b4ce1133cbdd27d53ee7d%1782392402.791979", + "grpc/1.81.1#f729f6d75992d20f9c72828e9142d62f%1783945160.094135", + "fmt/12.1.0#50abab23274d56bb8f42c94b3b9a40c7%1782736606.427131", + "ed25519/2015.03#ae761bdc52730a843f0809bdf6c1b1f6%1782307148.15562", + "date/3.0.4#862e11e80030356b53c2c38599ceb32b%1782392402.538492", + "cassandra-cpp-driver/2.17.0#bd3934138689482102c265d01288a316%1782736662.877646", + "c-ares/1.34.6#545240bb1c40e2cacd4362d6b8967650%1782392402.681654", + "bzip2/1.0.8#c470882369c2d95c5c77e970c0c7e321%1782392402.296732", + "boost/1.91.0#ea540ca2133d831b560036aa24dece3c%1782392419.475605", + "benchmark/1.9.5#b885dc73ad67b40a55d45684d1c88ad1%1782736613.864841", + "abseil/20250127.0#9ef01c1451a8340f9022e46238c0fbb6%1783945159.651047" ], "build_requires": [ - "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1774439233.809", - "protobuf/3.21.12#44ee56c0a6eea0c19aeeaca680370b88%1764175361.456", - "cmake/4.3.0#b939a42e98f593fb34d3a8c5cc860359%1774439249.183", - "cmake/3.31.11#f325c933f618a1fcebc1e1c0babfd1ba%1774439246.719", - "b2/5.4.2#ffd6084a119587e70f11cd45d1a386e2%1774439233.447" + "zlib/1.3.2#1cb806da49011867778ffb6ac7190fcb%1782392402.122708", + "protobuf/6.33.5#ff253ead763bd8d9904a52979cd21e81%1782392410.233933", + "cmake/4.3.3#840cf00ea09777e05c2050a50a82c722%1782392418.696091", + "b2/5.4.2#ffd6084a119587e70f11cd45d1a386e2%1782392402.624226", + "abseil/20250127.0#9ef01c1451a8340f9022e46238c0fbb6%1783945159.651047" ], "python_requires": [], "overrides": { - "protobuf/3.21.12#44ee56c0a6eea0c19aeeaca680370b88": [ + "openssl/3.6.3#f806de8933e3bf6f01016c6a888cee2e": [ null, - "protobuf/3.21.12" + "openssl/3.6.3#f806de8933e3bf6f01016c6a888cee2e" ], - "boost/1.83.0#91d8b1572534d2c334d6790e3c34d0c1": [ + "openssl/[>=1.1 <4]": [ + "openssl/3.6.3" + ], + "zlib/[>=1.2.11 <2]": [ + "zlib/1.3.2#1cb806da49011867778ffb6ac7190fcb" + ], + "zlib/1.3.2": [ null, - "boost/1.83.0#91d8b1572534d2c334d6790e3c34d0c1" + "zlib/1.3.2#1cb806da49011867778ffb6ac7190fcb" + ], + "boost/1.91.0": [ + "boost/1.91.0#ea540ca2133d831b560036aa24dece3c" + ], + "protobuf/[>=5.27.0 <7]": [ + "protobuf/6.33.5" ], "lz4/1.9.4": [ "lz4/1.10.0" ], "boost/[>=1.83.0 <1.91.0]": [ - "boost/1.83.0" + "boost/1.91.0" ], "sqlite3/[>=3.44 <4]": [ - "sqlite3/3.49.1" + "sqlite3/3.53.0" + ], + "boost/1.83.0": [ + "boost/1.91.0" + ], + "openssl/[>=3.5 <4]": [ + "openssl/3.6.3#f806de8933e3bf6f01016c6a888cee2e" + ], + "lz4/[>=1.9.4 <2]": [ + "lz4/1.10.0#982d9b673900f665a1da109e09c17cab" ] }, "config_requires": [] diff --git a/conan/global.conf b/conan/global.conf new file mode 100644 index 000000000..cc803dc80 --- /dev/null +++ b/conan/global.conf @@ -0,0 +1,7 @@ +# Global configuration for Conan. This is used to set the number of parallel +# downloads and uploads. +core:non_interactive=True +core.download:parallel={{ os.cpu_count() }} +core.upload:parallel={{ os.cpu_count() }} +tools.files.download:retry=5 +tools.files.download:retry_wait=10 diff --git a/conan/init.sh b/conan/init.sh new file mode 100755 index 000000000..107285424 --- /dev/null +++ b/conan/init.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +set -ex + +CURRENT_DIR="$(cd "$(dirname "$0")" && pwd)" +PROFILES_SRC_DIR="$CURRENT_DIR/profiles" + +CONAN_DIR="${CONAN_HOME:-$HOME/.conan2}" +PROFILES_DIR="$CONAN_DIR/profiles" + +rm -rf "$CONAN_DIR" + +conan remote add --index 0 --force xrplf https://conan.xrplf.org/repository/conan/ + +cp "$CURRENT_DIR/global.conf" "$CONAN_DIR/global.conf" + +mkdir -p "$PROFILES_DIR" + +# The compiler is selected via the `CC`/`CXX` environment variables (see +# `.github/actions/set-compiler-env`) and the sanitizers via the `SANITIZERS` +# environment variable. Builds always use the `ci` profile, which includes +# `sanitizers` and `default`. +cp "$PROFILES_SRC_DIR/default" "$PROFILES_DIR/default" +cp "$PROFILES_SRC_DIR/ci" "$PROFILES_DIR/ci" +cp "$PROFILES_SRC_DIR/sanitizers" "$PROFILES_DIR/sanitizers" diff --git a/conan/lockfile/apple-clang-21.profile b/conan/lockfile/apple-clang-21.profile new file mode 100644 index 000000000..f96434348 --- /dev/null +++ b/conan/lockfile/apple-clang-21.profile @@ -0,0 +1,8 @@ +[settings] +arch={{detect_api.detect_arch()}} +build_type=Release +compiler=apple-clang +compiler.cppstd=23 +compiler.libcxx=libc++ +compiler.version=21.0 +os=Macos diff --git a/.github/scripts/conan/regenerate_lockfile.sh b/conan/lockfile/regenerate.sh similarity index 82% rename from .github/scripts/conan/regenerate_lockfile.sh rename to conan/lockfile/regenerate.sh index 2024c80d6..4d46efe29 100755 --- a/.github/scripts/conan/regenerate_lockfile.sh +++ b/conan/lockfile/regenerate.sh @@ -14,7 +14,7 @@ export CONAN_HOME="$TEMP_DIR" # Ensure that the xrplf remote is the first to be consulted, so any recipes we # patched are used. We also add it there to not created huge diff when the # official Conan Center Index is updated. -conan remote add --force --index 0 xrplf https://conan.ripplex.io +conan remote add --force --index 0 xrplf https://conan.xrplf.org/repository/conan/ # Delete any existing lockfile. rm -f conan.lock @@ -22,4 +22,4 @@ rm -f conan.lock # Create a new lockfile that is compatible with macOS. # It should also work on Linux. conan lock create . \ - --profile:all=.github/scripts/conan/apple-clang-17.profile + --profile:all=./conan/lockfile/apple-clang-21.profile diff --git a/conan/profiles/ci b/conan/profiles/ci new file mode 100644 index 000000000..9422addfe --- /dev/null +++ b/conan/profiles/ci @@ -0,0 +1,8 @@ +{% set os = detect_api.detect_os() %} +include(sanitizers) + +[conf] +{% if os == "Linux" %} +user.package:libc_version=2.31 +tools.info.package_id:confs+=["user.package:libc_version"] +{% endif %} diff --git a/conan/profiles/default b/conan/profiles/default new file mode 100644 index 000000000..ae6e23c3c --- /dev/null +++ b/conan/profiles/default @@ -0,0 +1,27 @@ +{% set os = detect_api.detect_os() %} +{% set arch = detect_api.detect_arch() %} +{% set compiler, version, compiler_exe = detect_api.detect_default_compiler() %} +{% set compiler_version = version %} +{% if os == "Linux" %} +{% set compiler_version = detect_api.default_compiler_version(compiler, version) %} +{% endif %} + +[settings] +os={{ os }} +arch={{ arch }} +build_type=Debug +compiler={{ compiler }} +compiler.version={{ compiler_version }} +compiler.cppstd=23 +{% if os == "Windows" %} +compiler.runtime=static +{% else %} +compiler.libcxx={{ detect_api.detect_libcxx(compiler, version, compiler_exe) }} +{% endif %} + +[conf] +{# By default, Conan tries to reuse binaries built with different cppstd versions. #} +{# We want to avoid that to improve reproduceability, so we add the cppstd version to the package ID. #} +{# More info: https://docs.conan.io/2/reference/extensions/binary_compatibility.html #} +user.package:cppstd_version=23 +tools.info.package_id:confs+=["user.package:cppstd_version"] diff --git a/conan/profiles/sanitizers b/conan/profiles/sanitizers new file mode 100644 index 000000000..09e6aef02 --- /dev/null +++ b/conan/profiles/sanitizers @@ -0,0 +1,120 @@ +include(default) +{% set compiler, version, compiler_exe = detect_api.detect_default_compiler() %} +{% set arch = detect_api.detect_arch() %} +{% set sanitizers = os.getenv("SANITIZERS") %} + +{% if not sanitizers %} +{# Sanitizers not configured; no additional settings needed #} +{% else %} + +{% if compiler == "msvc" %} + {{ "Sanitizers are not supported on Windows/MSVC. Please unset the SANITIZERS environment variable." }} +{% endif %} + +{% set known_sanitizers = ["address", "thread", "undefinedbehavior"] %} +{% set provided_sanitizers = [] %} +{% for san in sanitizers.split(",") %} + {% set san = san.strip() %} + {% if san not in known_sanitizers %} + {{ "Unknown sanitizer in SANITIZERS: " ~ san }} + {% endif %} + {% set _ = provided_sanitizers.append(san) %} +{% endfor %} + +{% set enable_asan = "address" in provided_sanitizers %} +{% set enable_tsan = "thread" in provided_sanitizers %} +{% set enable_ubsan = "undefinedbehavior" in provided_sanitizers %} + +{% if enable_asan and enable_tsan %} + {{ "AddressSanitizer and ThreadSanitizer are incompatible and cannot be enabled simultaneously." }} +{% endif %} + +{% set sanitizer_types = [] %} +{% set defines = [] %} + +{% if enable_asan %} + {% set _ = sanitizer_types.append("address") %} + {% set _ = defines.append("BOOST_USE_ASAN") %} + {% set _ = defines.append("BOOST_USE_UCONTEXT") %} +{% elif enable_tsan %} + {% set _ = sanitizer_types.append("thread") %} + {% set _ = defines.append("BOOST_USE_TSAN") %} + {% set _ = defines.append("BOOST_USE_UCONTEXT") %} +{% endif %} + +{% if enable_ubsan %} + {% set _ = sanitizer_types.append("undefined") %} + {% set _ = sanitizer_types.append("float-divide-by-zero") %} + {# Clang supports additional UB checks beyond the GCC baseline #} + {% if compiler == "clang" or compiler == "apple-clang" %} + {% set _ = sanitizer_types.append("unsigned-integer-overflow") %} + {% endif %} +{% endif %} + +{# Frame pointer required for meaningful stack traces; -O1 for reasonable performance #} +{% set sanitizer_compiler_flags = ["-fno-omit-frame-pointer", "-O1"] %} + +{% if compiler == "gcc" %} + {# Suppress false positive warnings with GCC #} + {% set _ = sanitizer_compiler_flags.append("-Wno-stringop-overflow") %} + + {% set relocation_flags = [] %} + + {% if arch == "x86_64" and enable_asan %} + {# Large code model prevents relocation errors in instrumented ASAN binaries #} + {% set _ = sanitizer_compiler_flags.append("-mcmodel=large") %} + {% set _ = relocation_flags.append("-mcmodel=large") %} + {% elif enable_tsan %} + {# GCC doesn't support atomic_thread_fence with TSAN; suppress warnings #} + {% set _ = sanitizer_compiler_flags.append("-Wno-tsan") %} + {% if arch == "x86_64" %} + {# Medium code model for TSAN; large is incompatible #} + {% set _ = sanitizer_compiler_flags.append("-mcmodel=medium") %} + {% set _ = relocation_flags.append("-mcmodel=medium") %} + {% endif %} + {% endif %} + + {% set fsanitize = "-fsanitize=" ~ ",".join(sanitizer_types) %} + {% set _ = sanitizer_compiler_flags.append(fsanitize) %} + {% set _ = relocation_flags.append(fsanitize) %} + + {% set sanitizer_linker_flags = relocation_flags %} +{% elif compiler == "clang" or compiler == "apple-clang" %} + {% set fsanitize = "-fsanitize=" ~ ",".join(sanitizer_types) %} + {% set _ = sanitizer_compiler_flags.append(fsanitize) %} + + {% set sanitizer_linker_flags = [fsanitize] %} +{% endif %} + +[conf] +tools.build:defines+={{ defines }} +tools.build:cxxflags+={{ sanitizer_compiler_flags }} +tools.build:sharedlinkflags+={{ sanitizer_linker_flags }} +tools.build:exelinkflags+={{ sanitizer_linker_flags }} + +tools.info.package_id:confs+=["tools.build:cxxflags", "tools.build:exelinkflags", "tools.build:sharedlinkflags", "tools.build:defines"] + +# &: means "apply only to the consumer/root package" +&:tools.cmake.cmaketoolchain:extra_variables={"SANITIZERS": "{{ sanitizers }}", "SANITIZERS_COMPILER_FLAGS": "{{ sanitizer_compiler_flags | join(' ') }}", "SANITIZERS_LINKER_FLAGS": "{{ sanitizer_linker_flags | join(' ') }}"} + +[options] +{% if enable_asan %} + # Build Boost.Context with ucontext backend (not fcontext) so that + # ASAN fiber-switching annotations (__sanitizer_start/finish_switch_fiber) + # are compiled into the library. fcontext (assembly) has no ASAN support. + # define=BOOST_USE_ASAN=1 is critical: it must be defined when building + # Boost.Context itself so the ucontext backend compiles in the ASAN annotations. + boost/*:extra_b2_flags=context-impl=ucontext address-sanitizer=on define=BOOST_USE_ASAN=1 + boost/*:without_context=False + # Boost stacktrace fails to build with some sanitizers + boost/*:without_stacktrace=True +{% elif enable_tsan %} + # Build Boost.Context with ucontext backend for TSAN. fcontext (assembly) + # has no TSAN annotations, so without this the BOOST_USE_TSAN/BOOST_USE_UCONTEXT + # defines in [conf] would be ineffective. + boost/*:extra_b2_flags=context-impl=ucontext thread-sanitizer=on define=BOOST_USE_TSAN=1 + boost/*:without_context=False + boost/*:without_stacktrace=True +{% endif %} + +{% endif %} diff --git a/conanfile.py b/conanfile.py index ddfdeec4e..41d934095 100644 --- a/conanfile.py +++ b/conanfile.py @@ -1,6 +1,7 @@ -from conan import ConanFile from conan.tools.cmake import CMake, CMakeToolchain, cmake_layout +from conan import ConanFile + class ClioConan(ConanFile): name = "clio" @@ -14,13 +15,9 @@ class ClioConan(ConanFile): requires = [ "cassandra-cpp-driver/2.17.0", "fmt/12.1.0", - "grpc/1.50.1", "libbacktrace/cci.20210118", - "openssl/1.1.1w", - "protobuf/3.21.12", "spdlog/1.17.0", - "xrpl/3.1.3", - "zlib/1.3.1", + "xrpl/3.3.0-rc1", ] default_options = { @@ -35,16 +32,28 @@ class ClioConan(ConanFile): "protobuf/*:shared": False, "protobuf/*:with_zlib": True, "snappy/*:shared": False, - "xrpl/*:rocksdb": False, + "xrpl/*:rocksdb": True, # TODO: revert to false when includes are fixed in libxrpl "xrpl/*:tests": False, } exports_sources = ("CMakeLists.txt", "cmake/*", "src/*") def requirements(self): - self.requires("boost/1.83.0", force=True) self.requires("gtest/1.17.0") - self.requires("benchmark/1.9.4") + self.requires("benchmark/1.9.5") + # Clio's own code includes grpc () and openssl (via + # ) headers directly, but xrpl does not re-export them + # (only boost/date/xxhash are required with transitive_headers=True). + # So they must be direct requirements of clio to get their include dirs; + # the version pins match xrpl's, so this does not change any package_id. + self.requires("grpc/1.81.1") + self.requires("openssl/3.6.3", force=True) + # Pin the remaining transitive deps to the exact versions xrpl uses. + # override=True only sets the version when the package appears + # transitively (it does not make them direct deps), and matches xrpl's + # force=True boost pin that overrides nudb's `boost < 1.91.0` cap. + self.requires("boost/1.91.0", override=True) + self.requires("zlib/1.3.2", override=True) def configure(self): if self.settings.compiler == "apple-clang": diff --git a/docker/ci/Dockerfile b/docker/ci/Dockerfile deleted file mode 100644 index 72ba46b0f..000000000 --- a/docker/ci/Dockerfile +++ /dev/null @@ -1,132 +0,0 @@ -ARG GHCR_REPO=invalid -ARG CLANG_MAJOR_VERSION=invalid -ARG GCC_VERSION=invalid - -FROM ${GHCR_REPO}/clio-gcc:${GCC_VERSION} AS clio-gcc -FROM ${GHCR_REPO}/clio-tools:latest AS clio-tools - -FROM ${GHCR_REPO}/clio-clang:${CLANG_MAJOR_VERSION} - -ARG DEBIAN_FRONTEND=noninteractive - -SHELL ["/bin/bash", "-o", "pipefail", "-c"] - -# Using root by default is not very secure but github checkout action doesn't work with any other user -# https://github.com/actions/checkout/issues/956 -# And Github Actions doc recommends using root -# https://docs.github.com/en/actions/sharing-automations/creating-actions/dockerfile-support-for-github-actions#user - -# hadolint ignore=DL3002 -USER root -WORKDIR /root - -# Install common tools and dependencies -RUN apt-get update \ - && apt-get install -y --no-install-recommends --no-install-suggests \ - curl \ - dpkg-dev \ - file \ - git \ - git-lfs \ - gnupg \ - graphviz \ - jq \ - # libgmp, libmpfr and libncurses are gdb dependencies - libgmp-dev \ - libmpfr-dev \ - libncurses-dev \ - make \ - wget \ - zip \ - && apt-get clean \ - && rm -rf /var/lib/apt/lists/* - -# Install Python tools -RUN apt-get update \ - && apt-get install -y --no-install-recommends --no-install-suggests \ - python3 \ - python3-pip \ - && apt-get clean \ - && rm -rf /var/lib/apt/lists/* - -RUN pip install -q --no-cache-dir \ - # TODO: Remove this once we switch to newer Ubuntu base image - # lxml 6.0.0 is not compatible with our image - 'lxml<6.0.0' \ - cmake \ - conan==2.24.0 \ - gcovr \ - # We're adding pre-commit to this image as well, - # because clang-tidy workflow requires it - pre-commit - -# Install LLVM tools -ARG LLVM_TOOLS_VERSION=21 - -RUN echo "deb http://apt.llvm.org/focal/ llvm-toolchain-focal-${LLVM_TOOLS_VERSION} main" >> /etc/apt/sources.list \ - && wget --progress=dot:giga -O - https://apt.llvm.org/llvm-snapshot.gpg.key | apt-key add - - -RUN apt-get update \ - && apt-get install -y --no-install-recommends --no-install-suggests \ - clang-tidy-${LLVM_TOOLS_VERSION} \ - clang-tools-${LLVM_TOOLS_VERSION} \ - && apt-get clean \ - && rm -rf /var/lib/apt/lists/* - -ARG GCC_MAJOR_VERSION=invalid - -# Install custom-built gcc and make ldconfig aware of the new libstdc++ location (for gcc) -# Note: Clang is using libc++ instead -COPY --from=clio-gcc /gcc${GCC_MAJOR_VERSION}.deb / -RUN apt-get update \ - && apt-get install -y --no-install-recommends --no-install-suggests \ - binutils \ - libc6-dev \ - && apt-get clean \ - && rm -rf /var/lib/apt/lists/* \ - && dpkg -i /gcc${GCC_MAJOR_VERSION}.deb \ - && rm -rf /gcc${GCC_MAJOR_VERSION}.deb \ - && ldconfig - -# Rewire to use our custom-built gcc as default compiler -RUN update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-${GCC_MAJOR_VERSION} 100 \ - && update-alternatives --install /usr/bin/c++ c++ /usr/bin/g++-${GCC_MAJOR_VERSION} 100 \ - && update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-${GCC_MAJOR_VERSION} 100 \ - && update-alternatives --install /usr/bin/cc cc /usr/bin/gcc-${GCC_MAJOR_VERSION} 100 \ - && update-alternatives --install /usr/bin/gcov gcov /usr/bin/gcov-${GCC_MAJOR_VERSION} 100 \ - && update-alternatives --install /usr/bin/gcov-dump gcov-dump /usr/bin/gcov-dump-${GCC_MAJOR_VERSION} 100 \ - && update-alternatives --install /usr/bin/gcov-tool gcov-tool /usr/bin/gcov-tool-${GCC_MAJOR_VERSION} 100 - -COPY --from=clio-tools \ - /usr/local/bin/mold \ - /usr/local/bin/ld.mold \ - /usr/local/bin/ccache \ - /usr/local/bin/doxygen \ - /usr/local/bin/ClangBuildAnalyzer \ - /usr/local/bin/git-cliff \ - /usr/local/bin/gh \ - /usr/local/bin/gdb \ - /usr/local/bin/ninja \ - /usr/local/bin/ - -WORKDIR /root - -# Setup conan -RUN conan remote add --index 0 xrplf https://conan.ripplex.io - -WORKDIR /root/.conan2 -COPY conan/global.conf ./global.conf - -WORKDIR /root/.conan2/profiles - -COPY conan/clang.profile ./clang -COPY conan/sanitizer_template.profile ./clang.asan -COPY conan/sanitizer_template.profile ./clang.tsan -COPY conan/sanitizer_template.profile ./clang.ubsan - -COPY conan/gcc.profile ./gcc -COPY conan/sanitizer_template.profile ./gcc.asan -COPY conan/sanitizer_template.profile ./gcc.tsan -COPY conan/sanitizer_template.profile ./gcc.ubsan - -WORKDIR /root diff --git a/docker/ci/README.md b/docker/ci/README.md deleted file mode 100644 index b8a37a575..000000000 --- a/docker/ci/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# CI image for XRPLF/clio - -This image contains an environment to build [Clio](https://github.com/XRPLF/clio), check code and documentation. -It is used in [Clio Github Actions](https://github.com/XRPLF/clio/actions) but can also be used to compile Clio locally. - -The image is based on Ubuntu 20.04 and contains: - -- ccache 4.12.2 -- Clang 19 -- ClangBuildAnalyzer 1.6.0 -- Conan 2.24.0 -- Doxygen 1.16.1 -- GCC 15.2.0 -- GDB 17.1 -- gh 2.83.2 -- git-cliff 2.11.0 -- LLVM Tools 21 -- mold 2.40.4 -- Ninja 1.13.2 -- Python 3.8 -- and some other useful tools - -Conan is set up to build Clio without any additional steps. -There are two preset conan profiles: `clang` and `gcc` to use corresponding compiler. -`ASan`, `TSan` and `UBSan` sanitizer builds are enabled via conan profiles for each of the supported compilers. -These can be selected using the following pattern (all lowercase): `[compiler].[sanitizer]` (e.g. `--profile:all gcc.tsan`). diff --git a/docker/ci/conan/clang.profile b/docker/ci/conan/clang.profile deleted file mode 100644 index d142469c3..000000000 --- a/docker/ci/conan/clang.profile +++ /dev/null @@ -1,12 +0,0 @@ -[settings] -arch={{detect_api.detect_arch()}} -build_type=Release -compiler=clang -compiler.cppstd=20 -compiler.libcxx=libc++ -compiler.version=19 -os=Linux - -[conf] -tools.build:compiler_executables={"c": "/usr/bin/clang-19", "cpp": "/usr/bin/clang++-19"} -grpc/1.50.1:tools.build:cxxflags+=["-Wno-missing-template-arg-list-after-template-kw"] diff --git a/docker/ci/conan/gcc.profile b/docker/ci/conan/gcc.profile deleted file mode 100644 index 7224fc86b..000000000 --- a/docker/ci/conan/gcc.profile +++ /dev/null @@ -1,11 +0,0 @@ -[settings] -arch={{detect_api.detect_arch()}} -build_type=Release -compiler=gcc -compiler.cppstd=20 -compiler.libcxx=libstdc++11 -compiler.version=15 -os=Linux - -[conf] -tools.build:compiler_executables={"c": "/usr/bin/gcc-15", "cpp": "/usr/bin/g++-15"} diff --git a/docker/ci/conan/global.conf b/docker/ci/conan/global.conf deleted file mode 100644 index 8efc9de20..000000000 --- a/docker/ci/conan/global.conf +++ /dev/null @@ -1,2 +0,0 @@ -core.download:parallel={{os.cpu_count()}} -core.upload:parallel={{os.cpu_count()}} diff --git a/docker/ci/conan/sanitizer_template.profile b/docker/ci/conan/sanitizer_template.profile deleted file mode 100644 index 0df3aa04e..000000000 --- a/docker/ci/conan/sanitizer_template.profile +++ /dev/null @@ -1,37 +0,0 @@ -{% set compiler, sani = profile_name.split('.') %} - -{% set sanitizer_opt_map = {"asan": "address", "tsan": "thread", "ubsan": "undefined"} %} -{% set sanitizer = sanitizer_opt_map[sani] %} - -{% set sanitizer_b2_flags_map = { - "address": "context-impl=ucontext address-sanitizer=norecover", - "thread": "context-impl=ucontext thread-sanitizer=norecover", - "undefined": "undefined-sanitizer=norecover" -} %} -{% set sanitizer_b2_flags_str = sanitizer_b2_flags_map[sanitizer] %} - -{% set sanitizer_build_flags_str = "-fsanitize=" ~ sanitizer ~ " -g -O1 -fno-omit-frame-pointer" %} -{% set sanitizer_build_flags = sanitizer_build_flags_str.split(' ') %} -{% set sanitizer_link_flags_str = "-fsanitize=" ~ sanitizer %} -{% set sanitizer_link_flags = sanitizer_link_flags_str.split(' ') %} - -include({{ compiler }}) - -[options] -boost/*:extra_b2_flags="{{ sanitizer_b2_flags_str }}" -boost/*:without_context=False -boost/*:without_stacktrace=True - -[conf] -tools.build:cflags+={{ sanitizer_build_flags }} -tools.build:cxxflags+={{ sanitizer_build_flags }} -tools.build:exelinkflags+={{ sanitizer_link_flags }} -tools.build:sharedlinkflags+={{ sanitizer_link_flags }} - -{% if sanitizer == "address" %} - tools.build:defines+=["BOOST_USE_ASAN", "BOOST_USE_UCONTEXT"] -{% elif sanitizer == "thread" %} - tools.build:defines+=["BOOST_USE_TSAN", "BOOST_USE_UCONTEXT"] -{% endif %} - -tools.info.package_id:confs+=["tools.build:cflags", "tools.build:cxxflags", "tools.build:exelinkflags", "tools.build:sharedlinkflags", "tools.build:defines"] diff --git a/docker/clio/Dockerfile b/docker/clio/Dockerfile index f1a615b95..6a10f777a 100644 --- a/docker/clio/Dockerfile +++ b/docker/clio/Dockerfile @@ -1,11 +1,5 @@ FROM ubuntu:22.04 -RUN apt-get update \ - && apt-get install -y --no-install-recommends --no-install-suggests \ - libatomic1 \ - && apt-get clean \ - && rm -rf /var/lib/apt/lists/* - RUN groupadd -g 10001 clio \ && useradd -u 10000 -g 10001 -s /bin/bash clio diff --git a/docker/compilers/clang/Dockerfile b/docker/compilers/clang/Dockerfile deleted file mode 100644 index e9782c49f..000000000 --- a/docker/compilers/clang/Dockerfile +++ /dev/null @@ -1,32 +0,0 @@ -FROM ubuntu:20.04 - -ARG DEBIAN_FRONTEND=noninteractive - -SHELL ["/bin/bash", "-c"] - -# hadolint ignore=DL3002 -USER root -WORKDIR /root - -RUN apt-get update \ - && apt-get install -y --no-install-recommends --no-install-suggests \ - wget \ - software-properties-common \ - gnupg \ - && apt-get clean \ - && rm -rf /var/lib/apt/lists/* - -ARG CLANG_MAJOR_VERSION=invalid -# Bump this version to force rebuild of the image -ARG BUILD_VERSION=1 - -RUN wget --progress=dot:giga https://apt.llvm.org/llvm.sh \ - && chmod +x llvm.sh \ - && ./llvm.sh ${CLANG_MAJOR_VERSION} \ - && rm -rf llvm.sh \ - && apt-get update \ - && apt-get install -y --no-install-recommends --no-install-suggests \ - libc++-${CLANG_MAJOR_VERSION}-dev \ - libc++abi-${CLANG_MAJOR_VERSION}-dev \ - && apt-get clean \ - && rm -rf /var/lib/apt/lists/* diff --git a/docker/compilers/clang/README.md b/docker/compilers/clang/README.md deleted file mode 100644 index 6479791cb..000000000 --- a/docker/compilers/clang/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Clang compiler - -This image contains clang compiler to build . diff --git a/docker/compilers/gcc/Dockerfile b/docker/compilers/gcc/Dockerfile deleted file mode 100644 index ecaa22da9..000000000 --- a/docker/compilers/gcc/Dockerfile +++ /dev/null @@ -1,120 +0,0 @@ -ARG UBUNTU_VERSION=20.04 - -ARG GCC_MAJOR_VERSION=invalid - -FROM ubuntu:$UBUNTU_VERSION AS build - -ARG UBUNTU_VERSION - -ARG GCC_MAJOR_VERSION - -ARG BUILD_VERSION=0 - -ARG DEBIAN_FRONTEND=noninteractive -ARG TARGETARCH - -RUN apt-get update \ - && apt-get install -y --no-install-recommends --no-install-suggests \ - build-essential \ - file \ - flex \ - libz-dev \ - libzstd-dev \ - software-properties-common \ - wget \ - && apt-get clean \ - && rm -rf /var/lib/apt/lists/* - -ARG GCC_VERSION - -WORKDIR / -RUN wget --progress=dot:giga https://gcc.gnu.org/pub/gcc/releases/gcc-$GCC_VERSION/gcc-$GCC_VERSION.tar.gz \ - && tar xf gcc-$GCC_VERSION.tar.gz - -WORKDIR /gcc-$GCC_VERSION -RUN ./contrib/download_prerequisites - -# hadolint ignore=DL3059 -RUN mkdir /gcc-build -WORKDIR /gcc-build -RUN /gcc-$GCC_VERSION/configure \ - --with-pkgversion="clio-build-$BUILD_VERSION https://github.com/XRPLF/clio" \ - --enable-languages=c,c++ \ - --prefix=/usr \ - --with-gcc-major-version-only \ - --program-suffix=-${GCC_MAJOR_VERSION} \ - --enable-shared \ - --enable-linker-build-id \ - --libexecdir=/usr/lib \ - --without-included-gettext \ - --enable-threads=posix \ - --libdir=/usr/lib \ - --disable-nls \ - --enable-clocale=gnu \ - --enable-libstdcxx-backtrace=yes \ - --enable-libstdcxx-debug \ - --enable-libstdcxx-time=yes \ - --with-default-libstdcxx-abi=new \ - --enable-gnu-unique-object \ - --disable-vtable-verify \ - --enable-plugin \ - --enable-default-pie \ - --with-system-zlib \ - --enable-libphobos-checking=release \ - --with-target-system-zlib=auto \ - --disable-werror \ - --enable-cet \ - --disable-multilib \ - --without-cuda-driver \ - --enable-checking=release - -RUN make -j "$(nproc)" -RUN make install-strip DESTDIR=/gcc-$GCC_VERSION-$BUILD_VERSION-ubuntu-$UBUNTU_VERSION - -RUN export GDB_AUTOLOAD_DIR="/gcc-$GCC_VERSION-$BUILD_VERSION-ubuntu-$UBUNTU_VERSION/usr/share/gdb/auto-load/usr/lib64" \ - && mkdir -p "$GDB_AUTOLOAD_DIR" \ - && mv \ - /gcc-$GCC_VERSION-$BUILD_VERSION-ubuntu-$UBUNTU_VERSION/usr/lib64/libstdc++.so.*-gdb.py \ - $GDB_AUTOLOAD_DIR/ - -# Generate deb -WORKDIR / -COPY control.m4 / -COPY ld.so.conf /gcc-$GCC_VERSION-$BUILD_VERSION-ubuntu-$UBUNTU_VERSION/etc/ld.so.conf.d/1-gcc-${GCC_MAJOR_VERSION}.conf - -RUN mkdir /gcc-$GCC_VERSION-$BUILD_VERSION-ubuntu-$UBUNTU_VERSION/DEBIAN \ - && m4 \ - -P \ - -DUBUNTU_VERSION=$UBUNTU_VERSION \ - -DVERSION=$GCC_VERSION-$BUILD_VERSION \ - -DTARGETARCH=$TARGETARCH \ - control.m4 > /gcc-$GCC_VERSION-$BUILD_VERSION-ubuntu-$UBUNTU_VERSION/DEBIAN/control \ - && dpkg-deb \ - --build \ - --root-owner-group \ - /gcc-$GCC_VERSION-$BUILD_VERSION-ubuntu-$UBUNTU_VERSION \ - /gcc${GCC_MAJOR_VERSION}.deb - -# Create final image -FROM ubuntu:$UBUNTU_VERSION - -ARG GCC_MAJOR_VERSION - -COPY --from=build /gcc${GCC_MAJOR_VERSION}.deb / - -# Install gcc-${GCC_MAJOR_VERSION}, but also leave gcc${GCC_MAJOR_VERSION}.deb for others to copy if needed -RUN apt-get update \ - && apt-get install -y --no-install-recommends --no-install-suggests \ - binutils \ - libc6-dev \ - && apt-get clean \ - && rm -rf /var/lib/apt/lists/* \ - && dpkg -i /gcc${GCC_MAJOR_VERSION}.deb - -RUN update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-${GCC_MAJOR_VERSION} 100 \ - && update-alternatives --install /usr/bin/c++ c++ /usr/bin/g++-${GCC_MAJOR_VERSION} 100 \ - && update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-${GCC_MAJOR_VERSION} 100 \ - && update-alternatives --install /usr/bin/cc cc /usr/bin/gcc-${GCC_MAJOR_VERSION} 100 \ - && update-alternatives --install /usr/bin/gcov gcov /usr/bin/gcov-${GCC_MAJOR_VERSION} 100 \ - && update-alternatives --install /usr/bin/gcov-dump gcov-dump /usr/bin/gcov-dump-${GCC_MAJOR_VERSION} 100 \ - && update-alternatives --install /usr/bin/gcov-tool gcov-tool /usr/bin/gcov-tool-${GCC_MAJOR_VERSION} 100 diff --git a/docker/compilers/gcc/README.md b/docker/compilers/gcc/README.md deleted file mode 100644 index 5cc3a9cbf..000000000 --- a/docker/compilers/gcc/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# GCC compiler - -This image contains GCC compiler to build . diff --git a/docker/compilers/gcc/control.m4 b/docker/compilers/gcc/control.m4 deleted file mode 100644 index 896a735d0..000000000 --- a/docker/compilers/gcc/control.m4 +++ /dev/null @@ -1,7 +0,0 @@ -Package: gcc-15-ubuntu-UBUNTUVERSION -Version: VERSION -Architecture: TARGETARCH -Maintainer: Alex Kremer -Uploaders: Ayaz Salikhov -Description: GCC VERSION build for ubuntu UBUNTUVERSION -Depends: binutils, libc6-dev diff --git a/docker/compilers/gcc/ld.so.conf b/docker/compilers/gcc/ld.so.conf deleted file mode 100644 index 063e964a7..000000000 --- a/docker/compilers/gcc/ld.so.conf +++ /dev/null @@ -1,2 +0,0 @@ -# Path to the directory containing libstdc++.so.6 -/usr/lib64 diff --git a/docker/develop/compose.yaml b/docker/develop/compose.yaml index bd18473d8..e1b80722f 100644 --- a/docker/develop/compose.yaml +++ b/docker/develop/compose.yaml @@ -1,6 +1,6 @@ services: clio_develop: - image: ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696 + image: ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b volumes: - clio_develop_conan_data:/root/.conan2/p - clio_develop_ccache:/root/.ccache diff --git a/docker/develop/run b/docker/develop/run index 88518f14e..2c4cd12eb 100755 --- a/docker/develop/run +++ b/docker/develop/run @@ -41,26 +41,26 @@ EOF } case $1 in --h | --help) - print_help - ;; + -h | --help) + print_help + ;; --t | --terminal) - open_terminal - ;; + -t | --terminal) + open_terminal + ;; --s | --stop) - stop_container - ;; + -s | --stop) + stop_container + ;; --*) - echo "Unknown option: $1" - print_help - ;; + -*) + echo "Unknown option: $1" + print_help + ;; -*) - run "$@" - ;; + *) + run "$@" + ;; esac popd >/dev/null diff --git a/docker/tools/Dockerfile b/docker/tools/Dockerfile deleted file mode 100644 index 16196ea27..000000000 --- a/docker/tools/Dockerfile +++ /dev/null @@ -1,112 +0,0 @@ -ARG GHCR_REPO=invalid -ARG GCC_VERSION=invalid - -FROM ${GHCR_REPO}/clio-gcc:${GCC_VERSION} - -ARG DEBIAN_FRONTEND=noninteractive -ARG TARGETARCH - -SHELL ["/bin/bash", "-o", "pipefail", "-c"] - -ARG BUILD_VERSION=0 - -RUN apt-get update \ - && apt-get install -y --no-install-recommends --no-install-suggests \ - python3 \ - python3-pip \ - software-properties-common \ - wget \ - && pip3 install -q --no-cache-dir \ - cmake \ - && apt-get clean \ - && rm -rf /var/lib/apt/lists/* - -WORKDIR /tmp - -ARG NINJA_VERSION=1.13.2 - -RUN wget --progress=dot:giga "https://github.com/ninja-build/ninja/archive/refs/tags/v${NINJA_VERSION}.tar.gz" \ - && tar xf "v${NINJA_VERSION}.tar.gz" \ - && cd "ninja-${NINJA_VERSION}" \ - && ./configure.py --bootstrap \ - && mv ninja /usr/local/bin/ninja \ - && rm -rf /tmp/* /var/tmp/* - -ARG MOLD_VERSION=2.40.4 -RUN wget --progress=dot:giga "https://github.com/rui314/mold/archive/refs/tags/v${MOLD_VERSION}.tar.gz" \ - && tar xf "v${MOLD_VERSION}.tar.gz" \ - && cd "mold-${MOLD_VERSION}" \ - && mkdir build \ - && cd build \ - && cmake -GNinja -DCMAKE_BUILD_TYPE=Release .. \ - && ninja install \ - && rm -rf /tmp/* /var/tmp/* - -ARG CCACHE_VERSION=4.12.2 -RUN wget --progress=dot:giga "https://github.com/ccache/ccache/releases/download/v${CCACHE_VERSION}/ccache-${CCACHE_VERSION}.tar.gz" \ - && tar xf "ccache-${CCACHE_VERSION}.tar.gz" \ - && cd "ccache-${CCACHE_VERSION}" \ - && mkdir build \ - && cd build \ - && cmake -GNinja -DCMAKE_BUILD_TYPE=Release -DENABLE_TESTING=False .. \ - && ninja install \ - && rm -rf /tmp/* /var/tmp/* - -RUN apt-get update \ - && apt-get install -y --no-install-recommends --no-install-suggests \ - bison \ - flex \ - && apt-get clean \ - && rm -rf /var/lib/apt/lists/* - -ARG DOXYGEN_VERSION=1.16.1 -RUN wget --progress=dot:giga "https://github.com/doxygen/doxygen/releases/download/Release_${DOXYGEN_VERSION//./_}/doxygen-${DOXYGEN_VERSION}.src.tar.gz" \ - && tar xf "doxygen-${DOXYGEN_VERSION}.src.tar.gz" \ - && cd "doxygen-${DOXYGEN_VERSION}" \ - && mkdir build \ - && cd build \ - && cmake -GNinja -DCMAKE_BUILD_TYPE=Release .. \ - && ninja install \ - && rm -rf /tmp/* /var/tmp/* - -ARG CLANG_BUILD_ANALYZER_VERSION=1.6.0 -RUN wget --progress=dot:giga "https://github.com/aras-p/ClangBuildAnalyzer/archive/refs/tags/v${CLANG_BUILD_ANALYZER_VERSION}.tar.gz" \ - && tar xf "v${CLANG_BUILD_ANALYZER_VERSION}.tar.gz" \ - && cd "ClangBuildAnalyzer-${CLANG_BUILD_ANALYZER_VERSION}" \ - && mkdir build \ - && cd build \ - && cmake -GNinja -DCMAKE_BUILD_TYPE=Release .. \ - && ninja install \ - && rm -rf /tmp/* /var/tmp/* - -ARG GIT_CLIFF_VERSION=2.11.0 -RUN wget --progress=dot:giga "https://github.com/orhun/git-cliff/releases/download/v${GIT_CLIFF_VERSION}/git-cliff-${GIT_CLIFF_VERSION}-x86_64-unknown-linux-musl.tar.gz" \ - && tar xf git-cliff-${GIT_CLIFF_VERSION}-x86_64-unknown-linux-musl.tar.gz \ - && mv git-cliff-${GIT_CLIFF_VERSION}/git-cliff /usr/local/bin/git-cliff \ - && rm -rf /tmp/* /var/tmp/* - -ARG GH_VERSION=2.83.2 -RUN wget --progress=dot:giga "https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_${TARGETARCH}.tar.gz" \ - && tar xf gh_${GH_VERSION}_linux_${TARGETARCH}.tar.gz \ - && mv gh_${GH_VERSION}_linux_${TARGETARCH}/bin/gh /usr/local/bin/gh \ - && rm -rf /tmp/* /var/tmp/* - -RUN apt-get update \ - && apt-get install -y --no-install-recommends --no-install-suggests \ - libgmp-dev \ - libmpfr-dev \ - libncurses-dev \ - make \ - && apt-get clean \ - && rm -rf /var/lib/apt/lists/* - -ARG GDB_VERSION=17.1 -RUN wget --progress=dot:giga "https://sourceware.org/pub/gdb/releases/gdb-${GDB_VERSION}.tar.gz" \ - && tar xf "gdb-${GDB_VERSION}.tar.gz" \ - && cd "gdb-${GDB_VERSION}" \ - && ./configure --prefix=/usr/local \ - && make -j "$(nproc)" \ - && make install-gdb \ - && rm -rf /tmp/* /var/tmp/* - -WORKDIR /root diff --git a/docs/build-clio.md b/docs/build-clio.md index 81a43e006..cfaa79f7e 100644 --- a/docs/build-clio.md +++ b/docs/build-clio.md @@ -11,8 +11,8 @@ - [**Optional**] [GCovr](https://gcc.gnu.org/onlinedocs/gcc/Gcov.html): needed for code coverage generation - [**Optional**] [CCache](https://ccache.dev/): speeds up compilation if you are going to compile Clio often -We use our Docker image `ghcr.io/XRPLF/clio-ci` to build `Clio`, see [Building Clio with Docker](#building-clio-with-docker). -You can find information about exact compiler versions and tools in the [image's README](https://github.com/XRPLF/clio/blob/develop/docker/ci/README.md). +We use the Nix-based Docker image `ghcr.io/xrplf/xrpld/nix-ubuntu` to build `Clio`, see [Building Clio with Docker](#building-clio-with-docker). +This image is produced by [rippled](https://github.com/XRPLF/rippled) and ships the compilers and tools listed below. The following compiler version are guaranteed to work. Any compiler with lower version may not be able to build Clio: @@ -30,7 +30,7 @@ You can change it by using `$CONAN_HOME` env variable. [More info about Conan home](https://docs.conan.io/2/reference/environment.html#conan-home). > [!TIP] -> To setup Conan automatically, you can run `.github/scripts/conan/init.sh`. +> To setup Conan automatically, you can run `conan/init.sh`. > This will delete Conan home directory (if it exists), set up profiles and add Artifactory remote. The instruction below assumes that `$CONAN_HOME` is not set. @@ -90,7 +90,7 @@ core.upload:parallel={{os.cpu_count()}} Make sure artifactory is setup with Conan. ```sh -conan remote add --index 0 xrplf https://conan.ripplex.io +conan remote add --index 0 xrplf https://conan.xrplf.org/repository/conan/ ``` Now you should be able to download the prebuilt dependencies (including `xrpl` package) on supported platforms. @@ -104,7 +104,7 @@ It is implicitly used when running `conan` commands, you don't need to specify i You have to update this file every time you add a new dependency or change a revision or version of an existing dependency. -To update a lockfile, run from the repository root: `./.github/scripts/conan/regenerate_lockfile.sh` +To update a lockfile, run from the repository root: `./conan/lockfile/regenerate.sh` ## Building Clio @@ -175,7 +175,7 @@ Open the `index.html` file in your browser to see the documentation pages. It is also possible to build Clio using [Docker](https://www.docker.com/) if you don't want to install all the dependencies on your machine. ```sh -docker run -it ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696 +docker run -it ghcr.io/xrplf/xrpld/nix-ubuntu:sha-cb2642b git clone https://github.com/XRPLF/clio cd clio ``` diff --git a/docs/trouble_shooting.md b/docs/trouble_shooting.md index be524ed86..1c29806c9 100644 --- a/docs/trouble_shooting.md +++ b/docs/trouble_shooting.md @@ -13,7 +13,7 @@ If you see the error log message `Could not connect to Cassandra: No hosts avail If you would like to run a local ScyllaDB, you can call: ```sh -docker run --rm -p 9042:9042 --name clio-scylla -d scylladb/scylla +docker run --rm -p 9042:9042 --name clio-scylla -d scylladb/scylla:2026.1 ``` ## Check the server status of Clio diff --git a/pre-commit-hooks/fix_pragma_once.py b/pre-commit-hooks/fix_pragma_once.py new file mode 100755 index 000000000..08a505b6d --- /dev/null +++ b/pre-commit-hooks/fix_pragma_once.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 + +""" +Adds "#pragma once" to the top of header files that don't already have it. + +Usage: ./bin/pre-commit/fix_pragma_once.py ... +""" + +import sys +from pathlib import Path + +PRAGMA_ONCE = "#pragma once\n\n" + + +def fix_pragma_once(path: Path) -> bool: + original = path.read_text(encoding="utf-8") + if PRAGMA_ONCE not in original: + path.write_text(PRAGMA_ONCE + original, encoding="utf-8") + return False + return True + + +def main() -> int: + files = [Path(f) for f in sys.argv[1:]] + success = True + + for path in files: + success &= fix_pragma_once(path) + + return 0 if success else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pre-commit-hooks/verify-commits.sh b/pre-commit-hooks/verify-commits.sh index 70ddb4d24..57ef9ee9a 100755 --- a/pre-commit-hooks/verify-commits.sh +++ b/pre-commit-hooks/verify-commits.sh @@ -1,51 +1,56 @@ #!/bin/bash -# git for-each-ref refs/tags # see which tags are annotated and which are lightweight. Annotated tags are "tag" objects. -# # Set these so your commits and tags are always signed -# git config commit.gpgsign true -# git config tag.gpgsign true +# Annotated tags have object type "tag"; lightweight tags have type "commit". +# To inspect tags: git for-each-ref refs/tags +# +# To always sign commits and tags, configure: +# git config --global commit.gpgsign true +# git config --global tag.gpgsign true verify_commit_signed() { if git verify-commit HEAD &>/dev/null; then - : - # echo "HEAD commit seems signed..." + echo "HEAD commit is signed." else - echo "HEAD commit isn't signed!" + echo "HEAD commit is not signed!" exit 1 fi } -verify_tag() { - if git describe --exact-match --tags HEAD &>/dev/null; then - : # You might be ok to push - # echo "Tag is annotated." - return 0 +verify_tag_annotated() { + local version="$1" + # git cat-file -t returns "tag" for annotated tags, "commit" for lightweight. + if [[ "$(git cat-file -t "$version")" == "tag" ]]; then + echo "Tag '$version' is annotated." else - echo "Tag for [$version] not an annotated tag." + echo "Tag '$version' is not annotated!" + echo "Re-create it with: git tag -a -s -m \"$version\" \"$version\"" exit 1 fi } verify_tag_signed() { + local version="$1" if git verify-tag "$version" &>/dev/null; then - : # ok, I guess we'll let you push - # echo "Tag appears signed" - return 0 + echo "Tag '$version' is signed." else - echo "$version tag isn't signed" - echo "Sign it with [git tag -ams\"$version\" $version]" + echo "Tag '$version' is not signed!" + echo "Sign it with: git tag -a -s -m \"$version\" \"$version\"" exit 1 fi } -# Check some things if we're pushing a branch called "release/" -if echo "$PRE_COMMIT_REMOTE_BRANCH" | grep ^refs\/heads\/release\/ &>/dev/null; then - version=$(git tag --points-at HEAD) - echo "Looks like you're trying to push a $version release..." - echo "Making sure you've signed and tagged it." - if verify_commit_signed && verify_tag && verify_tag_signed; then - : # Ok, I guess you can push - else +# Enforce signing and annotated tags when pushing to a release branch. +if echo "$PRE_COMMIT_REMOTE_BRANCH" | grep -q "^refs/heads/release/"; then + # git describe --exact-match guarantees a single tag; git tag --points-at HEAD + # can return multiple newline-separated values, which breaks downstream commands. + version=$(git describe --exact-match --tags HEAD 2>/dev/null) + if [[ -z "$version" ]]; then + echo "No tag found at HEAD — cannot push an untagged release commit!" exit 1 fi + echo "Looks like you're trying to push a '$version' release..." + echo "Verifying the commit is signed and the tag is annotated and signed." + verify_commit_signed + verify_tag_annotated "$version" + verify_tag_signed "$version" fi diff --git a/src/app/CliArgs.cpp b/src/app/CliArgs.cpp index 8be2da557..379ae3853 100644 --- a/src/app/CliArgs.cpp +++ b/src/app/CliArgs.cpp @@ -28,7 +28,7 @@ CliArgs::parse(int argc, char const* argv[]) description.add_options() ("help,h", "Print help message and exit") ("version,v", "Print version and exit") - ("conf,c", po::value()->default_value(kDEFAULT_CONFIG_PATH), "Configuration file") + ("conf,c", po::value()->default_value(kDefaultConfigPath), "Configuration file") ("ng-web-server,w", "Use ng-web-server") ("migrate", po::value(), "Start migration helper") ("verify", "Checks the validity of config values") diff --git a/src/app/CliArgs.hpp b/src/app/CliArgs.hpp index 0f0c98499..d748c301d 100644 --- a/src/app/CliArgs.hpp +++ b/src/app/CliArgs.hpp @@ -16,31 +16,39 @@ public: /** * @brief Default configuration path. */ - static constexpr char kDEFAULT_CONFIG_PATH[] = "/etc/opt/clio/config.json"; + static constexpr char kDefaultConfigPath[] = "/etc/opt/clio/config.json"; /** * @brief An action parsed from the command line. */ class Action { public: - /** @brief Run action. */ + /** + * @brief Run action. + */ struct Run { std::string configPath; ///< Configuration file path. bool useNgWebServer; ///< Whether to use a ng web server }; - /** @brief Exit action. */ + /** + * @brief Exit action. + */ struct Exit { int exitCode; ///< Exit code. }; - /** @brief Migration action. */ + /** + * @brief Migration action. + */ struct Migrate { std::string configPath; MigrateSubCmd subCmd; }; - /** @brief Verify Config action. */ + /** + * @brief Verify Config action. + */ struct VerifyConfig { std::string configPath; }; diff --git a/src/app/ClioApplication.cpp b/src/app/ClioApplication.cpp index d1975952f..7b4eaf933 100644 --- a/src/app/ClioApplication.cpp +++ b/src/app/ClioApplication.cpp @@ -22,6 +22,7 @@ #include "util/build/Build.hpp" #include "util/config/ConfigDefinition.hpp" #include "util/log/Logger.hpp" +#include "util/requests/SslContext.hpp" #include "web/AdminVerificationStrategy.hpp" #include "web/RPCServerHandler.hpp" #include "web/Server.hpp" @@ -79,6 +80,13 @@ ClioApplication::ClioApplication(util::config::ClioConfigDefinition const& confi int ClioApplication::run(bool const useNgWebServer) { + if (auto const sslContext = util::requests::initClientSslContext(); + not sslContext.has_value()) { + LOG(util::LogService::fatal()) + << "Failed to create client SSL context: " << sslContext.error(); + return EXIT_FAILURE; + } + auto const threads = config_.get("io_threads"); LOG(util::LogService::info()) << "Number of io threads = " << threads; diff --git a/src/app/WebHandlers.cpp b/src/app/WebHandlers.cpp index 9c895891e..dce06c412 100644 --- a/src/app/WebHandlers.cpp +++ b/src/app/WebHandlers.cpp @@ -105,7 +105,7 @@ MetricsHandler::operator()( if (!postSuccessful) { return web::ng::Response{ boost::beast::http::status::too_many_requests, - rpc::makeError(rpc::RippledError::rpcTOO_BUSY), + rpc::makeError(rpc::RippledError::RpcTooBusy), request }; } @@ -125,7 +125,7 @@ HealthCheckHandler::operator()( boost::asio::yield_context ) { - static constexpr auto kHEALTH_CHECK_HTML = R"html( + static constexpr auto kHealthCheckHtml = R"html( Test page for Clio @@ -133,7 +133,7 @@ HealthCheckHandler::operator()( )html"; - return web::ng::Response{boost::beast::http::status::ok, kHEALTH_CHECK_HTML, request}; + return web::ng::Response{boost::beast::http::status::ok, kHealthCheckHtml, request}; } web::ng::Response @@ -144,7 +144,7 @@ CacheStateHandler::operator()( boost::asio::yield_context ) { - static constexpr auto kCACHE_CHECK_LOADED_HTML = R"html( + static constexpr auto kCacheCheckLoadedHtml = R"html( Cache state @@ -152,7 +152,7 @@ CacheStateHandler::operator()( )html"; - static constexpr auto kCACHE_CHECK_NOT_LOADED_HTML = R"html( + static constexpr auto kCacheCheckNotLoadedHtml = R"html( Cache state @@ -161,10 +161,10 @@ CacheStateHandler::operator()( )html"; if (cache_.get().isFull()) - return web::ng::Response{boost::beast::http::status::ok, kCACHE_CHECK_LOADED_HTML, request}; + return web::ng::Response{boost::beast::http::status::ok, kCacheCheckLoadedHtml, request}; return web::ng::Response{ - boost::beast::http::status::service_unavailable, kCACHE_CHECK_NOT_LOADED_HTML, request + boost::beast::http::status::service_unavailable, kCacheCheckNotLoadedHtml, request }; } diff --git a/src/app/WebHandlers.hpp b/src/app/WebHandlers.hpp index 20ee9a018..aba547a69 100644 --- a/src/app/WebHandlers.hpp +++ b/src/app/WebHandlers.hpp @@ -241,7 +241,7 @@ public: } catch (std::exception const&) { return web::ng::Response{ boost::beast::http::status::internal_server_error, - rpc::makeError(rpc::RippledError::rpcINTERNAL), + rpc::makeError(rpc::RippledError::RpcInternal), request }; } diff --git a/src/cluster/Backend.hpp b/src/cluster/Backend.hpp index d83643b73..ff04388a4 100644 --- a/src/cluster/Backend.hpp +++ b/src/cluster/Backend.hpp @@ -36,7 +36,8 @@ namespace cluster { */ class Backend { public: - /** @brief Type representing cluster data result - either a vector of nodes or an error message + /** + * @brief Type representing cluster data result - either a vector of nodes or an error message */ using ClusterData = std::expected, std::string>; @@ -119,7 +120,7 @@ public: * * @return The UUID of this node. */ - ClioNode::CUuid + [[nodiscard]] ClioNode::CUuid selfId() const; private: diff --git a/src/cluster/CacheLoaderDecider.hpp b/src/cluster/CacheLoaderDecider.hpp index 1a2780e65..45482ad1e 100644 --- a/src/cluster/CacheLoaderDecider.hpp +++ b/src/cluster/CacheLoaderDecider.hpp @@ -23,10 +23,14 @@ namespace cluster { * This ensures at most one node in the cluster loads the cache at a time. */ class CacheLoaderDecider { - /** @brief Thread pool for spawning asynchronous tasks */ + /** + * @brief Thread pool for spawning asynchronous tasks + */ boost::asio::thread_pool& ctx_; - /** @brief Interface for controlling cache loading permission of this node */ + /** + * @brief Interface for controlling cache loading permission of this node + */ std::unique_ptr cacheLoadingState_; public: diff --git a/src/cluster/ClioNode.cpp b/src/cluster/ClioNode.cpp index ab7b762d0..b12b5d6cb 100644 --- a/src/cluster/ClioNode.cpp +++ b/src/cluster/ClioNode.cpp @@ -22,12 +22,11 @@ namespace cluster { namespace { struct JsonFields { - static constexpr std::string_view const kUPDATE_TIME = "update_time"; - static constexpr std::string_view const kDB_ROLE = "db_role"; - static constexpr std::string_view const kETL_STARTED = "etl_started"; - static constexpr std::string_view const kCACHE_IS_FULL = "cache_is_full"; - static constexpr std::string_view const kCACHE_IS_CURRENTLY_LOADING = - "cache_is_currently_loading"; + static constexpr std::string_view const kUpdateTime = "update_time"; + static constexpr std::string_view const kDbRole = "db_role"; + static constexpr std::string_view const kEtlStarted = "etl_started"; + static constexpr std::string_view const kCacheIsFull = "cache_is_full"; + static constexpr std::string_view const kCacheIsCurrentlyLoading = "cache_is_currently_loading"; }; } // namespace @@ -67,11 +66,11 @@ void tag_invoke(boost::json::value_from_tag, boost::json::value& jv, ClioNode const& node) { jv = { - {JsonFields::kUPDATE_TIME, util::systemTpToUtcStr(node.updateTime, ClioNode::kTIME_FORMAT)}, - {JsonFields::kDB_ROLE, static_cast(node.dbRole)}, - {JsonFields::kETL_STARTED, node.etlStarted}, - {JsonFields::kCACHE_IS_FULL, node.cacheIsFull}, - {JsonFields::kCACHE_IS_CURRENTLY_LOADING, node.cacheIsCurrentlyLoading} + {JsonFields::kUpdateTime, util::systemTpToUtcStr(node.updateTime, ClioNode::kTimeFormat)}, + {JsonFields::kDbRole, static_cast(node.dbRole)}, + {JsonFields::kEtlStarted, node.etlStarted}, + {JsonFields::kCacheIsFull, node.cacheIsFull}, + {JsonFields::kCacheIsCurrentlyLoading, node.cacheIsCurrentlyLoading} }; } @@ -79,16 +78,16 @@ ClioNode tag_invoke(boost::json::value_to_tag, boost::json::value const& jv) { auto const& obj = jv.as_object(); - auto const& updateTimeStr = obj.at(JsonFields::kUPDATE_TIME).as_string(); + auto const& updateTimeStr = obj.at(JsonFields::kUpdateTime).as_string(); auto const updateTime = - util::systemTpFromUtcStr(std::string(updateTimeStr), ClioNode::kTIME_FORMAT); + util::systemTpFromUtcStr(std::string(updateTimeStr), ClioNode::kTimeFormat); if (!updateTime.has_value()) { throw std::runtime_error("Failed to parse update time"); } // Each field has a default value for backward compatibility auto dbRole = ClioNode::DbRole::Fallback; - if (auto const* v = obj.if_contains(JsonFields::kDB_ROLE)) { + if (auto const* v = obj.if_contains(JsonFields::kDbRole)) { auto const dbRoleValue = v->as_int64(); if (dbRoleValue > static_cast(ClioNode::DbRole::Max)) throw std::runtime_error("Invalid db_role value"); @@ -96,12 +95,11 @@ tag_invoke(boost::json::value_to_tag, boost::json::value const& jv) } auto const etlStarted = - obj.contains(JsonFields::kETL_STARTED) ? obj.at(JsonFields::kETL_STARTED).as_bool() : true; - auto const cacheIsFull = obj.contains(JsonFields::kCACHE_IS_FULL) - ? obj.at(JsonFields::kCACHE_IS_FULL).as_bool() - : true; - auto const cacheIsCurrentlyLoading = obj.contains(JsonFields::kCACHE_IS_CURRENTLY_LOADING) - ? obj.at(JsonFields::kCACHE_IS_CURRENTLY_LOADING).as_bool() + obj.contains(JsonFields::kEtlStarted) ? obj.at(JsonFields::kEtlStarted).as_bool() : true; + auto const cacheIsFull = + obj.contains(JsonFields::kCacheIsFull) ? obj.at(JsonFields::kCacheIsFull).as_bool() : true; + auto const cacheIsCurrentlyLoading = obj.contains(JsonFields::kCacheIsCurrentlyLoading) + ? obj.at(JsonFields::kCacheIsCurrentlyLoading).as_bool() : false; return ClioNode{ diff --git a/src/cluster/ClioNode.hpp b/src/cluster/ClioNode.hpp index 7bd36c34c..a74c4e7b4 100644 --- a/src/cluster/ClioNode.hpp +++ b/src/cluster/ClioNode.hpp @@ -19,7 +19,7 @@ struct ClioNode { /** * @brief The format of the time to store in the database. */ - static constexpr char const* kTIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"; + static constexpr char const* kTimeFormat = "%Y-%m-%dT%H:%M:%SZ"; /** * @brief Database role of a node in the cluster. diff --git a/src/cluster/ClusterCommunicationService.cpp b/src/cluster/ClusterCommunicationService.cpp index 0ad1320f7..dc30bb0cb 100644 --- a/src/cluster/ClusterCommunicationService.cpp +++ b/src/cluster/ClusterCommunicationService.cpp @@ -7,7 +7,6 @@ #include "util/config/ConfigDefinition.hpp" #include -#include #include #include diff --git a/src/cluster/ClusterCommunicationService.hpp b/src/cluster/ClusterCommunicationService.hpp index 052cbc355..685c73b56 100644 --- a/src/cluster/ClusterCommunicationService.hpp +++ b/src/cluster/ClusterCommunicationService.hpp @@ -36,8 +36,8 @@ class ClusterCommunicationService : public ClusterCommunicationServiceTag { CacheLoaderDecider cacheLoaderDecider_; public: - static constexpr std::chrono::milliseconds kDEFAULT_READ_INTERVAL{1000}; - static constexpr std::chrono::milliseconds kDEFAULT_WRITE_INTERVAL{1000}; + static constexpr std::chrono::milliseconds kDefaultReadInterval{1000}; + static constexpr std::chrono::milliseconds kDefaultWriteInterval{1000}; /** * @brief Construct a new Cluster Communication Service object. @@ -52,8 +52,8 @@ public: std::shared_ptr backend, std::unique_ptr writerState, std::unique_ptr cacheLoadingState, - std::chrono::steady_clock::duration readInterval = kDEFAULT_READ_INTERVAL, - std::chrono::steady_clock::duration writeInterval = kDEFAULT_WRITE_INTERVAL + std::chrono::steady_clock::duration readInterval = kDefaultReadInterval, + std::chrono::steady_clock::duration writeInterval = kDefaultWriteInterval ); ~ClusterCommunicationService() override; diff --git a/src/cluster/Metrics.hpp b/src/cluster/Metrics.hpp index aa4237afc..93673d2e3 100644 --- a/src/cluster/Metrics.hpp +++ b/src/cluster/Metrics.hpp @@ -18,14 +18,18 @@ namespace cluster { * - Health status of cluster communication */ class Metrics { - /** @brief Gauge tracking the total number of nodes visible in the cluster */ + /** + * @brief Gauge tracking the total number of nodes visible in the cluster + */ util::prometheus::GaugeInt& nodesInClusterMetric_ = PrometheusService::gaugeInt( "cluster_nodes_total_number", {}, "Total number of nodes this node can detect in the cluster." ); - /** @brief Boolean metric indicating whether cluster communication is healthy */ + /** + * @brief Boolean metric indicating whether cluster communication is healthy + */ util::prometheus::Bool isHealthy_ = PrometheusService::boolMetric( "cluster_communication_is_healthy", {}, diff --git a/src/cluster/WriterDecider.hpp b/src/cluster/WriterDecider.hpp index cfbc38483..616c09a05 100644 --- a/src/cluster/WriterDecider.hpp +++ b/src/cluster/WriterDecider.hpp @@ -63,13 +63,17 @@ namespace cluster { */ class WriterDecider { public: - static constexpr std::chrono::steady_clock::duration kRECOVERY_TIME = std::chrono::hours{1}; + static constexpr std::chrono::steady_clock::duration kRecoveryTime = std::chrono::hours{1}; private: - /** @brief Thread pool for spawning asynchronous tasks */ + /** + * @brief Thread pool for spawning asynchronous tasks + */ boost::asio::thread_pool& ctx_; - /** @brief Interface for controlling the writer state of this node */ + /** + * @brief Interface for controlling the writer state of this node + */ std::unique_ptr writerState_; /** @@ -90,12 +94,12 @@ public: * @param ctx Thread pool for executing asynchronous operations * @param writerState Writer state interface for controlling write operations * @param recoveryTime How long to wait in Fallback before attempting recovery - * (defaults to `kRECOVERY_TIME`; pass a short duration in tests) + * (defaults to `kRecoveryTime`; pass a short duration in tests) */ WriterDecider( boost::asio::thread_pool& ctx, std::unique_ptr writerState, - std::chrono::steady_clock::duration recoveryTime = kRECOVERY_TIME + std::chrono::steady_clock::duration recoveryTime = kRecoveryTime ); /** diff --git a/src/data/AmendmentCenter.cpp b/src/data/AmendmentCenter.cpp index 2a3051c81..a71d8d410 100644 --- a/src/data/AmendmentCenter.cpp +++ b/src/data/AmendmentCenter.cpp @@ -33,14 +33,14 @@ namespace { std::unordered_set& supportedAmendments() { - static std::unordered_set kAMENDMENTS = {}; - return kAMENDMENTS; + static std::unordered_set kAmendments = {}; + return kAmendments; } bool lookupAmendment( auto const& allAmendments, - std::vector const& ledgerAmendments, + std::vector const& ledgerAmendments, std::string_view name ) { @@ -80,7 +80,7 @@ operator std::string_view() const } AmendmentKey:: -operator ripple::uint256() const +operator xrpl::uint256() const { return Amendment::getAmendmentId(name); } @@ -92,14 +92,14 @@ AmendmentCenter::AmendmentCenter(std::shared_ptr const& namespace vs = std::views; rg::copy( - ripple::allAmendments() | vs::transform([&](auto const& p) { + xrpl::allAmendments() | vs::transform([&](auto const& p) { auto const& [name, support] = p; return Amendment{ .name = name, .feature = Amendment::getAmendmentId(name), - .isSupportedByXRPL = support != ripple::AmendmentSupport::Unsupported, + .isSupportedByXRPL = support != xrpl::AmendmentSupport::Unsupported, .isSupportedByClio = rg::contains(supportedAmendments(), name), - .isRetired = support == ripple::AmendmentSupport::Retired + .isRetired = support == xrpl::AmendmentSupport::Retired }; }), std::back_inserter(all_) @@ -207,26 +207,25 @@ AmendmentCenter::operator[](AmendmentKey const& key) const return getAmendment(key); } -ripple::uint256 +xrpl::uint256 Amendment::getAmendmentId(std::string_view name) { - return ripple::sha512Half(ripple::Slice(name.data(), name.size())); + return xrpl::sha512Half(xrpl::Slice(name.data(), name.size())); } -std::optional> +std::optional> AmendmentCenter::fetchAmendmentsList(boost::asio::yield_context yield, uint32_t seq) const { // the amendments should always be present on the ledger - auto const amendments = - backend_->fetchLedgerObject(ripple::keylet::amendments().key, seq, yield); + auto const amendments = backend_->fetchLedgerObject(xrpl::keylet::amendments().key, seq, yield); if (not amendments.has_value()) throw std::runtime_error("Amendments ledger object must be present in the database"); - ripple::SLE const amendmentsSLE{ - ripple::SerialIter{amendments->data(), amendments->size()}, ripple::keylet::amendments().key + xrpl::SLE const amendmentsSLE{ + xrpl::SerialIter{amendments->data(), amendments->size()}, xrpl::keylet::amendments().key }; - return amendmentsSLE[~ripple::sfAmendments]; + return amendmentsSLE[~xrpl::sfAmendments]; } } // namespace data diff --git a/src/data/AmendmentCenter.hpp b/src/data/AmendmentCenter.hpp index d23665cc5..bd13559fc 100644 --- a/src/data/AmendmentCenter.hpp +++ b/src/data/AmendmentCenter.hpp @@ -134,6 +134,17 @@ struct Amendments { REGISTER(fixIncludeKeyletFields); REGISTER(fixTokenEscrowV1); REGISTER(LendingProtocol); + REGISTER(MPTokensV2); + REGISTER(PermissionDelegationV1_1); + REGISTER(fixBatchInnerSigs); + REGISTER(fixCleanup3_1_3); + REGISTER(fixCleanup3_2_0); + // These amendments are added because of libxrpl 3.3.0, but they are not yet supported in Clio. + REGISTER(ConfidentialTransfer); + REGISTER(LendingProtocolV1_1); + REGISTER(BatchV1_1); + REGISTER(Sponsor); + REGISTER(fixCleanup3_3_0); // Obsolete but supported by libxrpl REGISTER(CryptoConditionsSuite); @@ -158,8 +169,6 @@ struct Amendments { REGISTER(fix1512); REGISTER(fix1523); REGISTER(fix1528); - REGISTER(fixBatchInnerSigs); - REGISTER(fixCleanup3_1_3); // NOLINTEND(readability-identifier-naming) /** @endcond */ }; @@ -263,7 +272,7 @@ public: operator[](AmendmentKey const& key) const final; private: - [[nodiscard]] std::optional> + [[nodiscard]] std::optional> fetchAmendmentsList(boost::asio::yield_context yield, uint32_t seq) const; }; diff --git a/src/data/BackendCounters.cpp b/src/data/BackendCounters.cpp index 8ce868e32..caed0253b 100644 --- a/src/data/BackendCounters.cpp +++ b/src/data/BackendCounters.cpp @@ -17,7 +17,7 @@ namespace data { namespace { -std::vector const kHISTOGRAM_BUCKETS{1, 2, 5, 10, 20, 50, 100, 200, 500, 700, 1000}; +std::vector const kHistogramBuckets{1, 2, 5, 10, 20, 50, 100, 200, 500, 700, 1000}; std::int64_t durationInMillisecondsSince(std::chrono::steady_clock::time_point const startTime) @@ -60,7 +60,7 @@ BackendCounters::BackendCounters() PrometheusService::histogramInt( "backend_duration_milliseconds_histogram", Labels({Label{"operation", "read"}}), - kHISTOGRAM_BUCKETS, + kHistogramBuckets, "The duration of backend read operations including retries" ) ) @@ -68,7 +68,7 @@ BackendCounters::BackendCounters() PrometheusService::histogramInt( "backend_duration_milliseconds_histogram", Labels({Label{"operation", "write"}}), - kHISTOGRAM_BUCKETS, + kHistogramBuckets, "The duration of backend write operations including retries" ) ) diff --git a/src/data/BackendInterface.cpp b/src/data/BackendInterface.cpp index a7cadee6f..d9e8dbe20 100644 --- a/src/data/BackendInterface.cpp +++ b/src/data/BackendInterface.cpp @@ -45,7 +45,7 @@ BackendInterface::finishWrites(std::uint32_t const ledgerSequence) void BackendInterface::writeLedgerObject(std::string&& key, std::uint32_t const seq, std::string&& blob) { - ASSERT(key.size() == sizeof(ripple::uint256), "Key must be 256 bits"); + ASSERT(key.size() == sizeof(xrpl::uint256), "Key must be 256 bits"); doWriteLedgerObject(std::move(key), seq, std::move(blob)); } @@ -58,14 +58,14 @@ BackendInterface::hardFetchLedgerRangeNoThrow() const // *** state data methods std::optional BackendInterface::fetchLedgerObject( - ripple::uint256 const& key, + xrpl::uint256 const& key, std::uint32_t const sequence, boost::asio::yield_context yield ) const { auto obj = cache_.get().get(key, sequence); if (obj) { - LOG(log_.trace()) << "Cache hit - " << ripple::strHex(key); + LOG(log_.trace()) << "Cache hit - " << xrpl::strHex(key); return obj; } @@ -80,7 +80,7 @@ BackendInterface::fetchLedgerObject( std::optional BackendInterface::fetchLedgerObjectSeq( - ripple::uint256 const& key, + xrpl::uint256 const& key, std::uint32_t const sequence, boost::asio::yield_context yield ) const @@ -93,14 +93,14 @@ BackendInterface::fetchLedgerObjectSeq( std::vector BackendInterface::fetchLedgerObjects( - std::vector const& keys, + std::vector const& keys, std::uint32_t const sequence, boost::asio::yield_context yield ) const { std::vector results; results.resize(keys.size()); - std::vector misses; + std::vector misses; for (size_t i = 0; i < keys.size(); ++i) { auto obj = cache_.get().get(keys[i], sequence); if (obj) { @@ -126,25 +126,25 @@ BackendInterface::fetchLedgerObjects( } // Fetches the successor to key/index -std::optional +std::optional BackendInterface::fetchSuccessorKey( - ripple::uint256 key, + xrpl::uint256 key, std::uint32_t const ledgerSequence, boost::asio::yield_context yield ) const { auto succ = cache_.get().getSuccessor(key, ledgerSequence); if (succ) { - LOG(log_.trace()) << "Cache hit - " << ripple::strHex(key); + LOG(log_.trace()) << "Cache hit - " << xrpl::strHex(key); } else { - LOG(log_.trace()) << "Cache miss - " << ripple::strHex(key); + LOG(log_.trace()) << "Cache miss - " << xrpl::strHex(key); } return succ ? succ->key : doFetchSuccessorKey(key, ledgerSequence, yield); } std::optional BackendInterface::fetchSuccessorObject( - ripple::uint256 key, + xrpl::uint256 key, std::uint32_t const ledgerSequence, boost::asio::yield_context yield ) const @@ -162,7 +162,7 @@ BackendInterface::fetchSuccessorObject( BookOffersPage BackendInterface::fetchBookOffers( - ripple::uint256 const& book, + xrpl::uint256 const& book, std::uint32_t const ledgerSequence, std::uint32_t const limit, boost::asio::yield_context yield @@ -171,9 +171,9 @@ BackendInterface::fetchBookOffers( // TODO try to speed this up. This can take a few seconds. The goal is // to get it down to a few hundred milliseconds. BookOffersPage page; - ripple::uint256 const bookEnd = ripple::getQualityNext(book); - ripple::uint256 uTipIndex = book; - std::vector keys; + xrpl::uint256 const bookEnd = xrpl::getQualityNext(book); + xrpl::uint256 uTipIndex = book; + std::vector keys; auto getMillis = [](auto diff) { return std::chrono::duration_cast(diff).count(); }; @@ -195,17 +195,17 @@ BackendInterface::fetchBookOffers( uTipIndex = offerDir->key; while (keys.size() < limit) { ++numPages; - ripple::STLedgerEntry const sle{ - ripple::SerialIter{offerDir->blob.data(), offerDir->blob.size()}, offerDir->key + xrpl::STLedgerEntry const sle{ + xrpl::SerialIter{offerDir->blob.data(), offerDir->blob.size()}, offerDir->key }; - auto indexes = sle.getFieldV256(ripple::sfIndexes); + auto indexes = sle.getFieldV256(xrpl::sfIndexes); keys.insert(keys.end(), indexes.begin(), indexes.end()); - auto next = sle.getFieldU64(ripple::sfIndexNext); + auto next = sle.getFieldU64(xrpl::sfIndexNext); if (next == 0u) { LOG(log_.trace()) << "Next is empty. breaking"; break; } - auto nextKey = ripple::keylet::page(uTipIndex, next); + auto nextKey = xrpl::keylet::page(uTipIndex, next); auto nextDir = fetchLedgerObject(nextKey.key, ledgerSequence, yield); ASSERT(nextDir.has_value(), "Next dir must exist"); // NOLINTBEGIN(bugprone-unchecked-optional-access) @@ -219,11 +219,11 @@ BackendInterface::fetchBookOffers( auto mid = std::chrono::system_clock::now(); auto objs = fetchLedgerObjects(keys, ledgerSequence, yield); for (size_t i = 0; i < keys.size() && i < limit; ++i) { - LOG(log_.trace()) << "Key = " << ripple::strHex(keys[i]) - << " blob = " << ripple::strHex(objs[i]) + LOG(log_.trace()) << "Key = " << xrpl::strHex(keys[i]) + << " blob = " << xrpl::strHex(objs[i]) << " ledgerSequence = " << ledgerSequence; ASSERT(!objs[i].empty(), "Ledger object can't be empty"); - page.offers.push_back({keys[i], objs[i]}); + page.offers.push_back({.key = keys[i], .blob = objs[i]}); } auto end = std::chrono::system_clock::now(); LOG(log_.debug()) << "Fetching " << std::to_string(keys.size()) << " offers took " @@ -236,7 +236,7 @@ BackendInterface::fetchBookOffers( << ". Fetching all objects took " << std::to_string(getMillis(end - mid)) << " milliseconds. total time = " << std::to_string(getMillis(end - begin)) << " milliseconds" - << " book = " << ripple::strHex(book); + << " book = " << xrpl::strHex(book); return page; } @@ -295,7 +295,7 @@ BackendInterface::setRange(uint32_t min, uint32_t max, bool force) LedgerPage BackendInterface::fetchLedgerPage( - std::optional const& cursor, + std::optional const& cursor, std::uint32_t const ledgerSequence, std::uint32_t const limit, bool outOfOrder, @@ -304,14 +304,14 @@ BackendInterface::fetchLedgerPage( { LedgerPage page; - std::vector keys; + std::vector keys; bool reachedEnd = false; while (keys.size() < limit && !reachedEnd) { - ripple::uint256 const& curCursor = [&]() { + xrpl::uint256 const& curCursor = [&]() { if (!keys.empty()) return keys.back(); - return (cursor ? *cursor : kFIRST_KEY); + return (cursor ? *cursor : kFirstKey); }(); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) @@ -328,13 +328,13 @@ BackendInterface::fetchLedgerPage( auto objects = fetchLedgerObjects(keys, ledgerSequence, yield); for (size_t i = 0; i < objects.size(); ++i) { if (!objects[i].empty()) { - page.objects.push_back({keys[i], std::move(objects[i])}); + page.objects.push_back({.key = keys[i], .blob = std::move(objects[i])}); } else if (!outOfOrder) { LOG(log_.error()) << "Deleted or non-existent object in successor table. key = " - << ripple::strHex(keys[i]) << " - seq = " << ledgerSequence; + << xrpl::strHex(keys[i]) << " - seq = " << ledgerSequence; std::stringstream msg; for (size_t j = 0; j < objects.size(); ++j) { - msg << " - " << ripple::strHex(keys[j]); + msg << " - " << xrpl::strHex(keys[j]); } LOG(log_.error()) << msg.str(); @@ -348,12 +348,12 @@ BackendInterface::fetchLedgerPage( return page; } -std::optional +std::optional BackendInterface::fetchFees(std::uint32_t const seq, boost::asio::yield_context yield) const { - ripple::Fees fees; + xrpl::Fees fees; - auto key = ripple::keylet::fees().key; + auto key = xrpl::keylet::feeSettings().key; auto bytes = fetchLedgerObject(key, seq, yield); if (!bytes) { @@ -361,17 +361,17 @@ BackendInterface::fetchFees(std::uint32_t const seq, boost::asio::yield_context return {}; } - ripple::SerialIter it(bytes->data(), bytes->size()); - ripple::SLE const sle{it, key}; + xrpl::SerialIter it(bytes->data(), bytes->size()); + xrpl::SLE const sle{it, key}; // XRPFees amendment introduced new fields for fees calculations. // New fields are set and the old fields are removed via `set_fees` tx. // Fallback to old fields if `set_fees` was not yet used to update the fields on this tx. auto hasNewFields = false; { - auto const baseFeeXRP = sle.at(~ripple::sfBaseFeeDrops); - auto const reserveBaseXRP = sle.at(~ripple::sfReserveBaseDrops); - auto const reserveIncrementXRP = sle.at(~ripple::sfReserveIncrementDrops); + auto const baseFeeXRP = sle.at(~xrpl::sfBaseFeeDrops); + auto const reserveBaseXRP = sle.at(~xrpl::sfReserveBaseDrops); + auto const reserveIncrementXRP = sle.at(~xrpl::sfReserveIncrementDrops); if (baseFeeXRP) fees.base = baseFeeXRP->xrp(); @@ -387,9 +387,9 @@ BackendInterface::fetchFees(std::uint32_t const seq, boost::asio::yield_context if (not hasNewFields) { // Fallback to old fields - auto const baseFee = sle.at(~ripple::sfBaseFee); - auto const reserveBase = sle.at(~ripple::sfReserveBase); - auto const reserveIncrement = sle.at(~ripple::sfReserveIncrement); + auto const baseFee = sle.at(~xrpl::sfBaseFee); + auto const reserveBase = sle.at(~xrpl::sfReserveBase); + auto const reserveIncrement = sle.at(~xrpl::sfReserveIncrement); if (baseFee) fees.base = baseFee.value(); diff --git a/src/data/BackendInterface.hpp b/src/data/BackendInterface.hpp index d677a2ee3..7d32f1220 100644 --- a/src/data/BackendInterface.hpp +++ b/src/data/BackendInterface.hpp @@ -49,7 +49,7 @@ public: } }; -static constexpr std::size_t kDEFAULT_WAIT_BETWEEN_RETRY = 500; +static constexpr std::size_t kDefaultWaitBetweenRetry = 500; /** * @brief A helper function that catches DatabaseTimeout exceptions and retries indefinitely. * @@ -60,7 +60,7 @@ static constexpr std::size_t kDEFAULT_WAIT_BETWEEN_RETRY = 500; */ template auto -retryOnTimeout(FnType func, size_t waitMs = kDEFAULT_WAIT_BETWEEN_RETRY) +retryOnTimeout(FnType func, size_t waitMs = kDefaultWaitBetweenRetry) { static util::Logger const log{"Backend"}; // NOLINT(readability-identifier-naming) @@ -87,7 +87,7 @@ synchronous(FnType&& func) { boost::asio::io_context ctx; - using R = typename boost::result_of::type; + using R = boost::result_of::type; if constexpr (!std::is_same_v) { R res; util::spawn(ctx, [_ = boost::asio::make_work_guard(ctx), &func, &res](auto yield) { @@ -178,9 +178,9 @@ public: * * @param sequence The sequence number to fetch for * @param yield The coroutine context - * @return The ripple::LedgerHeader if found; nullopt otherwise + * @return The xrpl::LedgerHeader if found; nullopt otherwise */ - virtual std::optional + virtual std::optional fetchLedgerBySequence(std::uint32_t sequence, boost::asio::yield_context yield) const = 0; /** @@ -188,10 +188,10 @@ public: * * @param hash The hash to fetch for * @param yield The coroutine context - * @return The ripple::LedgerHeader if found; nullopt otherwise + * @return The xrpl::LedgerHeader if found; nullopt otherwise */ - virtual std::optional - fetchLedgerByHash(ripple::uint256 const& hash, boost::asio::yield_context yield) const = 0; + virtual std::optional + fetchLedgerByHash(xrpl::uint256 const& hash, boost::asio::yield_context yield) const = 0; /** * @brief Fetches the latest ledger sequence. @@ -218,9 +218,9 @@ public: * @param pageSize The maximum number of accounts per page * @param seq The accounts need to exist for this sequence * @param yield The coroutine context - * @return A vector of ripple::uint256 representing the account roots + * @return A vector of xrpl::uint256 representing the account roots */ - virtual std::vector + virtual std::vector fetchAccountRoots( std::uint32_t number, std::uint32_t pageSize, @@ -262,7 +262,7 @@ public: * @param yield The coroutine context * @return Fees if fees are found; nullopt otherwise */ - std::optional + std::optional fetchFees(std::uint32_t seq, boost::asio::yield_context yield) const; /** @@ -273,7 +273,7 @@ public: * @return TransactionAndMetadata if transaction is found; nullopt otherwise */ virtual std::optional - fetchTransaction(ripple::uint256 const& hash, boost::asio::yield_context yield) const = 0; + fetchTransaction(xrpl::uint256 const& hash, boost::asio::yield_context yield) const = 0; /** * @brief Fetches multiple transactions. @@ -284,7 +284,7 @@ public: */ virtual std::vector fetchTransactions( - std::vector const& hashes, + std::vector const& hashes, boost::asio::yield_context yield ) const = 0; @@ -300,7 +300,7 @@ public: */ virtual TransactionsAndCursor fetchAccountTransactions( - ripple::AccountID const& account, + xrpl::AccountID const& account, std::uint32_t limit, bool forward, std::optional const& txnCursor, @@ -325,9 +325,9 @@ public: * * @param ledgerSequence The ledger sequence to fetch for * @param yield The coroutine context - * @return Hashes as ripple::uint256 in a vector + * @return Hashes as xrpl::uint256 in a vector */ - virtual std::vector + virtual std::vector fetchAllTransactionHashesInLedger( std::uint32_t ledgerSequence, boost::asio::yield_context yield @@ -343,7 +343,7 @@ public: */ virtual std::optional fetchNFT( - ripple::uint256 const& tokenID, + xrpl::uint256 const& tokenID, std::uint32_t ledgerSequence, boost::asio::yield_context yield ) const = 0; @@ -360,7 +360,7 @@ public: */ virtual TransactionsAndCursor fetchNFTTransactions( - ripple::uint256 const& tokenID, + xrpl::uint256 const& tokenID, std::uint32_t limit, bool forward, std::optional const& cursorIn, @@ -381,11 +381,11 @@ public: */ virtual NFTsAndCursor fetchNFTsByIssuer( - ripple::AccountID const& issuer, + xrpl::AccountID const& issuer, std::optional const& taxon, std::uint32_t ledgerSequence, std::uint32_t limit, - std::optional const& cursorIn, + std::optional const& cursorIn, boost::asio::yield_context yield ) const = 0; @@ -401,13 +401,67 @@ public: */ virtual MPTHoldersAndCursor fetchMPTHolders( - ripple::uint192 const& mptID, + xrpl::uint192 const& mptID, std::uint32_t const limit, - std::optional const& cursorIn, + std::optional const& cursorIn, std::uint32_t const ledgerSequence, boost::asio::yield_context yield ) const = 0; + /** + * @brief Fetches transactions for a particular MPTokenIssuance ID. + * + * Returns one page of transactions for this issuance, newest-first (or oldest-first when + * @p forward is set). Each row of the mptoken_issuance_transactions table holds only a + * transaction hash and its ledger position, not the transaction itself or its type. So the + * query cannot filter by type. When a type filter is requested, the handler looks up each full + * transaction by hash and drops rows whose type does not match, the same way account_tx does. + * + * @param mptIssuanceID The 24-byte MPTokenIssuance ID. + * @param limit The maximum number of transactions per result page. + * @param forward Whether to fetch the page forwards or backwards from the given cursor. + * @param cursorIn The cursor to resume fetching from. + * @param yield The coroutine context. + * @return Results and a cursor to resume from. + */ + virtual TransactionsAndCursor + fetchMPTokenIssuanceTransactions( + xrpl::uint192 const& mptIssuanceID, + std::uint32_t limit, + bool forward, + std::optional const& cursorIn, + boost::asio::yield_context yield + ) const = 0; + + /** + * @brief Fetches transactions for a particular MPTokenIssuance ID involving a particular + * account. + * + * Returns one page of transactions for this issuance and account, newest-first (or oldest-first + * when @p forward is set). Each row of the account_mptoken_issuance_transactions table holds + * only a transaction hash and its ledger position, not the transaction itself or its type. So + * the query cannot filter by type. When a type filter is requested, the handler looks up each + * full transaction by hash and drops rows whose type does not match, the same way account_tx + * does. + * + * @param mptIssuanceID The 24-byte MPTokenIssuance ID. + * @param account The account that must be affected by the transaction. + * @param limit The maximum number of transactions per result page. + * @param forward Whether to fetch the page forwards or backwards from the given cursor. + * @param cursorIn The cursor to resume fetching from. + * @param yield The coroutine context. + * @return Results and a cursor to resume from. + */ + virtual TransactionsAndCursor + fetchAccountMPTokenIssuanceTransactions( + xrpl::uint192 const& mptIssuanceID, + xrpl::AccountID const& account, + std::uint32_t limit, + bool forward, + std::optional const& cursorIn, + boost::asio::yield_context yield + ) const = 0; + /** * @brief Fetches a specific ledger object. * @@ -421,7 +475,7 @@ public: */ std::optional fetchLedgerObject( - ripple::uint256 const& key, + xrpl::uint256 const& key, std::uint32_t sequence, boost::asio::yield_context yield ) const; @@ -438,7 +492,7 @@ public: */ std::optional fetchLedgerObjectSeq( - ripple::uint256 const& key, + xrpl::uint256 const& key, std::uint32_t sequence, boost::asio::yield_context yield ) const; @@ -457,7 +511,7 @@ public: */ std::vector fetchLedgerObjects( - std::vector const& keys, + std::vector const& keys, std::uint32_t sequence, boost::asio::yield_context yield ) const; @@ -472,7 +526,7 @@ public: */ virtual std::optional doFetchLedgerObject( - ripple::uint256 const& key, + xrpl::uint256 const& key, std::uint32_t sequence, boost::asio::yield_context yield ) const = 0; @@ -487,7 +541,7 @@ public: */ virtual std::optional doFetchLedgerObjectSeq( - ripple::uint256 const& key, + xrpl::uint256 const& key, std::uint32_t sequence, boost::asio::yield_context yield ) const = 0; @@ -502,7 +556,7 @@ public: */ virtual std::vector doFetchLedgerObjects( - std::vector const& keys, + std::vector const& keys, std::uint32_t sequence, boost::asio::yield_context yield ) const = 0; @@ -529,7 +583,7 @@ public: */ LedgerPage fetchLedgerPage( - std::optional const& cursor, + std::optional const& cursor, std::uint32_t ledgerSequence, std::uint32_t limit, bool outOfOrder, @@ -546,7 +600,7 @@ public: */ std::optional fetchSuccessorObject( - ripple::uint256 key, + xrpl::uint256 key, std::uint32_t ledgerSequence, boost::asio::yield_context yield ) const; @@ -563,9 +617,9 @@ public: * @param yield The coroutine context * @return The successor key on success; nullopt otherwise */ - std::optional + std::optional fetchSuccessorKey( - ripple::uint256 key, + xrpl::uint256 key, std::uint32_t ledgerSequence, boost::asio::yield_context yield ) const; @@ -578,9 +632,9 @@ public: * @param yield The coroutine context * @return The successor on success; nullopt otherwise */ - virtual std::optional + virtual std::optional doFetchSuccessorKey( - ripple::uint256 key, + xrpl::uint256 key, std::uint32_t ledgerSequence, boost::asio::yield_context yield ) const = 0; @@ -596,7 +650,7 @@ public: */ BookOffersPage fetchBookOffers( - ripple::uint256 const& book, + xrpl::uint256 const& book, std::uint32_t ledgerSequence, std::uint32_t limit, boost::asio::yield_context yield @@ -615,7 +669,9 @@ public: boost::asio::yield_context yield ) const = 0; - /** @brief Return type for fetchClioNodesData() method */ + /** + * @brief Return type for fetchClioNodesData() method + */ using ClioNodesDataFetchResult = std::expected>, std::string>; @@ -663,7 +719,7 @@ public: * @param blob r-value string serialization of ledger header. */ virtual void - writeLedger(ripple::LedgerHeader const& ledgerHeader, std::string&& blob) = 0; + writeLedger(xrpl::LedgerHeader const& ledgerHeader, std::string&& blob) = 0; /** * @brief Writes a new ledger object. @@ -725,6 +781,28 @@ public: virtual void writeNFTTransactions(std::vector const& data) = 0; + /** + * @brief Write MPTokenIssuance transaction index rows to the `mptoken_issuance_transactions` + * table. + * + * @param data A vector of MPTokenIssuanceTransactionsData objects. + */ + virtual void + writeMPTokenIssuanceTransactions(std::vector const& data) = 0; + + /** + * @brief Write MPTokenIssuance transaction index rows to the + * `account_mptoken_issuance_transactions` table. + * + * One row is written per affected account in each record. + * + * @param data A vector of MPTokenIssuanceTransactionsData objects. + */ + virtual void + writeAccountMPTokenIssuanceTransactions( + std::vector const& data + ) = 0; + /** * @brief Write accounts that started holding onto a MPT. * diff --git a/src/data/CassandraBackend.hpp b/src/data/CassandraBackend.hpp index 4c75ea4b0..bfad3a8f4 100644 --- a/src/data/CassandraBackend.hpp +++ b/src/data/CassandraBackend.hpp @@ -72,7 +72,7 @@ public: */ using DefaultCassandraFamily::DefaultCassandraFamily; - /* + /** * @brief Move constructor is deleted because handle_ is shared by reference with executor */ BasicCassandraBackend(BasicCassandraBackend&&) = delete; @@ -101,11 +101,11 @@ public: [[nodiscard]] NFTsAndCursor fetchNFTsByIssuer( - ripple::AccountID const& issuer, + xrpl::AccountID const& issuer, std::optional const& taxon, std::uint32_t const ledgerSequence, std::uint32_t const limit, - std::optional const& cursorIn, + std::optional const& cursorIn, boost::asio::yield_context yield ) const override { @@ -115,7 +115,7 @@ public: if (taxon.has_value()) { auto r = schema_->selectNFTIDsByIssuerTaxon.bind(issuer); r.bindAt(1, *taxon); - r.bindAt(2, cursorIn.value_or(ripple::uint256(0))); + r.bindAt(2, cursorIn.value_or(xrpl::uint256(0))); r.bindAt(3, Limit{limit}); return r; } @@ -124,9 +124,8 @@ public: r.bindAt( 1, std::make_tuple( - cursorIn.has_value() ? ripple::nft::toUInt32(ripple::nft::getTaxon(*cursorIn)) - : 0, - cursorIn.value_or(ripple::uint256(0)) + cursorIn.has_value() ? xrpl::nft::toUInt32(xrpl::nft::getTaxon(*cursorIn)) : 0, + cursorIn.value_or(xrpl::uint256(0)) ) ); r.bindAt(2, Limit{limit}); @@ -142,8 +141,8 @@ public: return {}; } - std::vector nftIDs; - for (auto const [nftID] : extract(idQueryResults)) + std::vector nftIDs; + for (auto const [nftID] : extract(idQueryResults)) nftIDs.push_back(nftID); if (nftIDs.empty()) @@ -177,11 +176,11 @@ public: auto const nftUris = executor_.readEach(yield, selectNFTURIStatements); for (auto i = 0u; i < nftIDs.size(); i++) { - if (auto const maybeRow = nftInfos[i].template get(); + if (auto const maybeRow = nftInfos[i].template get(); maybeRow.has_value()) { auto [seq, owner, isBurned] = *maybeRow; NFT nft(nftIDs[i], seq, owner, isBurned); - if (auto const maybeUri = nftUris[i].template get(); + if (auto const maybeUri = nftUris[i].template get(); maybeUri.has_value()) nft.uri = *maybeUri; ret.nfts.push_back(nft); @@ -190,7 +189,7 @@ public: return ret; } - [[nodiscard]] std::vector + [[nodiscard]] std::vector fetchAccountRoots( std::uint32_t number, std::uint32_t pageSize, @@ -198,8 +197,8 @@ public: boost::asio::yield_context yield ) const override { - std::vector liveAccounts; - std::optional lastItem; + std::vector liveAccounts; + std::optional lastItem; while (liveAccounts.size() < number) { Statement const statement = lastItem @@ -214,9 +213,9 @@ public: break; } // The results should not contain duplicates, we just filter out deleted accounts - std::vector fullAccounts; - for (auto [account] : extract(results)) { - fullAccounts.push_back(ripple::keylet::account(account).key); + std::vector fullAccounts; + for (auto [account] : extract(results)) { + fullAccounts.push_back(xrpl::keylet::account(account).key); lastItem = account; } auto const objs = this->doFetchLedgerObjects(fullAccounts, seq, yield); diff --git a/src/data/DBHelpers.hpp b/src/data/DBHelpers.hpp index ee5c71c5f..3b65e9eeb 100644 --- a/src/data/DBHelpers.hpp +++ b/src/data/DBHelpers.hpp @@ -24,10 +24,10 @@ * @brief Struct used to keep track of what to write to account_transactions/account_tx tables. */ struct AccountTransactionsData { - boost::container::flat_set accounts; + boost::container::flat_set accounts; std::uint32_t ledgerSequence{}; std::uint32_t transactionIndex{}; - ripple::uint256 txHash; + xrpl::uint256 txHash; /** * @brief Construct a new AccountTransactionsData object @@ -35,7 +35,7 @@ struct AccountTransactionsData { * @param meta The transaction metadata * @param txHash The transaction hash */ - AccountTransactionsData(ripple::TxMeta const& meta, ripple::uint256 const& txHash) + AccountTransactionsData(xrpl::TxMeta const& meta, xrpl::uint256 const& txHash) : accounts(meta.getAffectedAccounts()) , ledgerSequence(meta.getLgrSeq()) , transactionIndex(meta.getIndex()) @@ -52,10 +52,10 @@ struct AccountTransactionsData { * Gets written to nf_token_transactions table and the like. */ struct NFTTransactionsData { - ripple::uint256 tokenID; + xrpl::uint256 tokenID; std::uint32_t ledgerSequence; std::uint32_t transactionIndex; - ripple::uint256 txHash; + xrpl::uint256 txHash; /** * @brief Construct a new NFTTransactionsData object @@ -65,9 +65,9 @@ struct NFTTransactionsData { * @param txHash The transaction hash */ NFTTransactionsData( - ripple::uint256 const& tokenID, - ripple::TxMeta const& meta, - ripple::uint256 const& txHash + xrpl::uint256 const& tokenID, + xrpl::TxMeta const& meta, + xrpl::uint256 const& txHash ) : tokenID(tokenID) , ledgerSequence(meta.getLgrSeq()) @@ -91,11 +91,11 @@ struct NFTTransactionsData { * objects. */ struct NFTsData { - ripple::uint256 tokenID; + xrpl::uint256 tokenID; std::uint32_t ledgerSequence; std::optional transactionIndex; - ripple::AccountID owner; - std::optional uri; + xrpl::AccountID owner; + std::optional uri; bool isBurned = false; bool onlyUriChanged = false; // Whether only the URI was changed @@ -113,10 +113,10 @@ struct NFTsData { * @param meta The transaction metadata */ NFTsData( - ripple::uint256 const& tokenID, - ripple::AccountID const& owner, - ripple::Blob const& uri, - ripple::TxMeta const& meta + xrpl::uint256 const& tokenID, + xrpl::AccountID const& owner, + xrpl::Blob const& uri, + xrpl::TxMeta const& meta ) : tokenID(tokenID) , ledgerSequence(meta.getLgrSeq()) @@ -137,9 +137,9 @@ struct NFTsData { * @param isBurned Whether the NFT is burned */ NFTsData( - ripple::uint256 const& tokenID, - ripple::AccountID const& owner, - ripple::TxMeta const& meta, + xrpl::uint256 const& tokenID, + xrpl::AccountID const& owner, + xrpl::TxMeta const& meta, bool isBurned ) : tokenID(tokenID) @@ -164,10 +164,10 @@ struct NFTsData { * @param uri The URI */ NFTsData( - ripple::uint256 const& tokenID, + xrpl::uint256 const& tokenID, std::uint32_t const ledgerSequence, - ripple::AccountID const& owner, - ripple::Blob const& uri + xrpl::AccountID const& owner, + xrpl::Blob const& uri ) : tokenID(tokenID), ledgerSequence(ledgerSequence), owner(owner), uri(uri) { @@ -181,7 +181,7 @@ struct NFTsData { * @param uri The new URI * */ - NFTsData(ripple::uint256 const& tokenID, ripple::TxMeta const& meta, ripple::Blob const& uri) + NFTsData(xrpl::uint256 const& tokenID, xrpl::TxMeta const& meta, xrpl::Blob const& uri) : tokenID(tokenID) , ledgerSequence(meta.getLgrSeq()) , transactionIndex(meta.getIndex()) @@ -195,8 +195,25 @@ struct NFTsData { * @brief Represents an MPT and holder pair */ struct MPTHolderData { - ripple::uint192 mptID; - ripple::AccountID holder; + xrpl::uint192 mptID; + xrpl::AccountID holder; +}; + +/** + * @brief Represents a transaction link for an MPTokenIssuance. + * + * @note Writing one of these records inserts into two tables: + * mptoken_issuance_transactions and account_mptoken_issuance_transactions. + */ +struct MPTokenIssuanceTransactionsData { + xrpl::uint192 mptIssuanceID; + boost::container::flat_set accounts; + std::uint32_t ledgerSequence{}; + std::uint32_t transactionIndex{}; + xrpl::uint256 txHash; + + bool + operator==(MPTokenIssuanceTransactionsData const&) const = default; }; /** @@ -209,13 +226,13 @@ template inline bool isDirNode(T const& object) { - static constexpr auto kMIN_SIZE_REQUIRED = 3; - if (std::size(object) < kMIN_SIZE_REQUIRED) + static constexpr auto kMinSizeRequired = 3; + if (std::size(object) < kMinSizeRequired) return false; - static constexpr short kDIR_NODE_SPACE_KEY = 0x0064; + static constexpr short kDirNodeSpaceKey = 0x0064; short const spaceKey = (object.data()[1] << 8) | object.data()[2]; - return spaceKey == kDIR_NODE_SPACE_KEY; + return spaceKey == kDirNodeSpaceKey; } /** @@ -232,42 +249,44 @@ isBookDir(T const& key, R const& object) if (!isDirNode(object)) return false; - ripple::STLedgerEntry const sle{ripple::SerialIter{object.data(), object.size()}, key}; - return !sle[~ripple::sfOwner].has_value(); + xrpl::STLedgerEntry const sle{xrpl::SerialIter{object.data(), object.size()}, key}; + return !sle[~xrpl::sfOwner].has_value(); } /** * @brief Get the book base. * * @param key The key to get the book base out of - * @return Book base as ripple::uint256 + * @return Book base as xrpl::uint256 */ template -inline ripple::uint256 +inline xrpl::uint256 getBookBase(T const& key) { - static constexpr size_t kEY_SIZE = 24; + static constexpr size_t kEySize = 24; - ASSERT(key.size() == ripple::uint256::size(), "Invalid key size {}", key.size()); + ASSERT(key.size() == xrpl::uint256::size(), "Invalid key size {}", key.size()); - ripple::uint256 ret; - for (size_t i = 0; i < kEY_SIZE; ++i) + xrpl::uint256 ret; + for (size_t i = 0; i < kEySize; ++i) ret.data()[i] = key.data()[i]; return ret; } /** - * @brief Stringify a ripple::uint256. + * @brief Stringify a xrpl::uint256. * * @param input The input value * @return The input value as a string */ inline std::string -uint256ToString(ripple::uint256 const& input) +uint256ToString(xrpl::uint256 const& input) { - return {reinterpret_cast(input.data()), ripple::uint256::size()}; + return {reinterpret_cast(input.data()), xrpl::uint256::size()}; } -/** @brief The ripple epoch start timestamp. Midnight on 1st January 2000. */ -static constexpr std::uint32_t kRIPPLE_EPOCH_START = 946684800; +/** + * @brief The ripple epoch start timestamp. Midnight on 1st January 2000. + */ +static constexpr std::uint32_t kRippleEpochStart = 946684800; diff --git a/src/data/KeyspaceBackend.hpp b/src/data/KeyspaceBackend.hpp index 07fe364c6..bde01a933 100644 --- a/src/data/KeyspaceBackend.hpp +++ b/src/data/KeyspaceBackend.hpp @@ -104,23 +104,23 @@ public: [[nodiscard]] NFTsAndCursor fetchNFTsByIssuer( - ripple::AccountID const& issuer, + xrpl::AccountID const& issuer, std::optional const& taxon, std::uint32_t const ledgerSequence, std::uint32_t const limit, - std::optional const& cursorIn, + std::optional const& cursorIn, boost::asio::yield_context yield ) const override { - std::vector nftIDs; + std::vector nftIDs; if (taxon.has_value()) { // Keyspace and ScyllaDB uses the same logic for taxon-filtered queries nftIDs = fetchNFTIDsByTaxon(issuer, *taxon, limit, cursorIn, yield); } else { // Amazon Keyspaces Workflow for non-taxon queries auto const startTaxon = - cursorIn.has_value() ? ripple::nft::toUInt32(ripple::nft::getTaxon(*cursorIn)) : 0; - auto const startTokenID = cursorIn.value_or(ripple::uint256(0)); + cursorIn.has_value() ? xrpl::nft::toUInt32(xrpl::nft::getTaxon(*cursorIn)) : 0; + auto const startTokenID = cursorIn.value_or(xrpl::uint256(0)); Statement const firstQuery = schema_->selectNFTIDsByIssuerTaxon.bind(issuer); firstQuery.bindAt(1, startTaxon); @@ -129,7 +129,7 @@ public: auto const firstRes = executor_.read(yield, firstQuery); if (firstRes.has_value()) { - for (auto const [nftID] : extract(*firstRes)) + for (auto const [nftID] : extract(*firstRes)) nftIDs.push_back(nftID); } @@ -141,7 +141,7 @@ public: auto const secondRes = executor_.read(yield, secondQuery); if (secondRes.has_value()) { - for (auto const [nftID] : extract(*secondRes)) + for (auto const [nftID] : extract(*secondRes)) nftIDs.push_back(nftID); } } @@ -160,9 +160,9 @@ public: * @param pageSize The maximum number of accounts per page. * @param seq The accounts need to exist at this ledger sequence. * @param yield The coroutine context. - * @return A vector of ripple::uint256 representing the account root hashes. + * @return A vector of xrpl::uint256 representing the account root hashes. */ - [[nodiscard]] std::vector + [[nodiscard]] std::vector fetchAccountRoots( [[maybe_unused]] std::uint32_t number, [[maybe_unused]] std::uint32_t pageSize, @@ -175,42 +175,42 @@ public: } private: - [[nodiscard]] std::vector + [[nodiscard]] std::vector fetchNFTIDsByTaxon( - ripple::AccountID const& issuer, + xrpl::AccountID const& issuer, std::uint32_t const taxon, std::uint32_t const limit, - std::optional const& cursorIn, + std::optional const& cursorIn, boost::asio::yield_context yield ) const { - std::vector nftIDs; + std::vector nftIDs; Statement const statement = schema_->selectNFTIDsByIssuerTaxon.bind(issuer); statement.bindAt(1, taxon); - statement.bindAt(2, cursorIn.value_or(ripple::uint256(0))); + statement.bindAt(2, cursorIn.value_or(xrpl::uint256(0))); statement.bindAt(3, Limit{limit}); auto const res = executor_.read(yield, statement); if (res.has_value() && res->hasRows()) { - for (auto const [nftID] : extract(*res)) + for (auto const [nftID] : extract(*res)) nftIDs.push_back(nftID); } return nftIDs; } - [[nodiscard]] std::vector + [[nodiscard]] std::vector fetchNFTIDsWithoutTaxon( - ripple::AccountID const& issuer, + xrpl::AccountID const& issuer, std::uint32_t const limit, - std::optional const& cursorIn, + std::optional const& cursorIn, boost::asio::yield_context yield ) const { - std::vector nftIDs; + std::vector nftIDs; auto const startTaxon = - cursorIn.has_value() ? ripple::nft::toUInt32(ripple::nft::getTaxon(*cursorIn)) : 0; - auto const startTokenID = cursorIn.value_or(ripple::uint256(0)); + cursorIn.has_value() ? xrpl::nft::toUInt32(xrpl::nft::getTaxon(*cursorIn)) : 0; + auto const startTokenID = cursorIn.value_or(xrpl::uint256(0)); Statement firstQuery = schema_->selectNFTIDsByIssuerTaxon.bind(issuer); firstQuery.bindAt(1, startTaxon); @@ -219,7 +219,7 @@ private: auto const firstRes = executor_.read(yield, firstQuery); if (firstRes.has_value()) { - for (auto const [nftID] : extract(*firstRes)) + for (auto const [nftID] : extract(*firstRes)) nftIDs.push_back(nftID); } @@ -231,7 +231,7 @@ private: auto const secondRes = executor_.read(yield, secondQuery); if (secondRes.has_value()) { - for (auto const [nftID] : extract(*secondRes)) + for (auto const [nftID] : extract(*secondRes)) nftIDs.push_back(nftID); } } @@ -244,7 +244,7 @@ private: */ [[nodiscard]] NFTsAndCursor populateNFTsAndCreateCursor( - std::vector const& nftIDs, + std::vector const& nftIDs, std::uint32_t const ledgerSequence, std::uint32_t const limit, boost::asio::yield_context yield @@ -283,11 +283,11 @@ private: // Combine the results into final NFT objects. for (auto i = 0u; i < nftIDs.size(); ++i) { - if (auto const maybeRow = nftInfos[i].template get(); + if (auto const maybeRow = nftInfos[i].template get(); maybeRow.has_value()) { auto [seq, owner, isBurned] = *maybeRow; NFT nft(nftIDs[i], seq, owner, isBurned); - if (auto const maybeUri = nftUris[i].template get(); + if (auto const maybeUri = nftUris[i].template get(); maybeUri.has_value()) nft.uri = *maybeUri; ret.nfts.push_back(nft); diff --git a/src/data/LedgerCache.cpp b/src/data/LedgerCache.cpp index 02678218d..fa40d0ba0 100644 --- a/src/data/LedgerCache.cpp +++ b/src/data/LedgerCache.cpp @@ -112,7 +112,7 @@ LedgerCache::update(std::vector const& objs, uint32_t seq) } std::optional -LedgerCache::getSuccessor(ripple::uint256 const& key, uint32_t seq) const +LedgerCache::getSuccessor(xrpl::uint256 const& key, uint32_t seq) const { if (disabled_ or not full_) return {}; @@ -129,7 +129,7 @@ LedgerCache::getSuccessor(ripple::uint256 const& key, uint32_t seq) const } std::optional -LedgerCache::getPredecessor(ripple::uint256 const& key, uint32_t seq) const +LedgerCache::getPredecessor(xrpl::uint256 const& key, uint32_t seq) const { if (disabled_ or not full_) return {}; @@ -145,7 +145,7 @@ LedgerCache::getPredecessor(ripple::uint256 const& key, uint32_t seq) const } std::optional -LedgerCache::get(ripple::uint256 const& key, uint32_t seq) const +LedgerCache::get(xrpl::uint256 const& key, uint32_t seq) const { if (disabled_) return {}; @@ -164,7 +164,7 @@ LedgerCache::get(ripple::uint256 const& key, uint32_t seq) const } std::optional -LedgerCache::getDeleted(ripple::uint256 const& key, uint32_t seq) const +LedgerCache::getDeleted(xrpl::uint256 const& key, uint32_t seq) const { if (disabled_) return std::nullopt; diff --git a/src/data/LedgerCache.hpp b/src/data/LedgerCache.hpp index 0c4cae298..f6cf764fb 100644 --- a/src/data/LedgerCache.hpp +++ b/src/data/LedgerCache.hpp @@ -29,13 +29,15 @@ namespace data { */ class LedgerCache : public LedgerCacheInterface { public: - /** @brief An entry of the cache */ + /** + * @brief An entry of the cache + */ struct CacheEntry { uint32_t seq = 0; Blob blob; }; - using CacheMap = std::map; + using CacheMap = std::map; private: // counters for fetchLedgerObject(s) hit rate @@ -95,7 +97,7 @@ private: // temporary set to prevent background thread from writing already deleted data. not used when // cache is full - std::unordered_set> deletes_; + std::unordered_set> deletes_; public: void @@ -105,16 +107,16 @@ public: update(std::vector const& objs, uint32_t seq) override; std::optional - get(ripple::uint256 const& key, uint32_t seq) const override; + get(xrpl::uint256 const& key, uint32_t seq) const override; std::optional - getDeleted(ripple::uint256 const& key, uint32_t seq) const override; + getDeleted(xrpl::uint256 const& key, uint32_t seq) const override; std::optional - getSuccessor(ripple::uint256 const& key, uint32_t seq) const override; + getSuccessor(xrpl::uint256 const& key, uint32_t seq) const override; std::optional - getPredecessor(ripple::uint256 const& key, uint32_t seq) const override; + getPredecessor(xrpl::uint256 const& key, uint32_t seq) const override; void setDisabled() override; diff --git a/src/data/LedgerCacheInterface.hpp b/src/data/LedgerCacheInterface.hpp index 6e9126784..19b7d1acb 100644 --- a/src/data/LedgerCacheInterface.hpp +++ b/src/data/LedgerCacheInterface.hpp @@ -56,7 +56,7 @@ public: * @return If found in cache, will return the cached Blob; otherwise nullopt is returned */ [[nodiscard]] virtual std::optional - get(ripple::uint256 const& key, uint32_t seq) const = 0; + get(xrpl::uint256 const& key, uint32_t seq) const = 0; /** * @brief Fetch a recently deleted object by its key and sequence number. @@ -66,7 +66,7 @@ public: * @return If found in deleted cache, will return the cached Blob; otherwise nullopt is returned */ [[nodiscard]] virtual std::optional - getDeleted(ripple::uint256 const& key, uint32_t seq) const = 0; + getDeleted(xrpl::uint256 const& key, uint32_t seq) const = 0; /** * @brief Gets a cached successor. @@ -78,7 +78,7 @@ public: * @return If found in cache, will return the cached successor; otherwise nullopt is returned */ [[nodiscard]] virtual std::optional - getSuccessor(ripple::uint256 const& key, uint32_t seq) const = 0; + getSuccessor(xrpl::uint256 const& key, uint32_t seq) const = 0; /** * @brief Gets a cached predcessor. @@ -90,7 +90,7 @@ public: * @return If found in cache, will return the cached predcessor; otherwise nullopt is returned */ [[nodiscard]] virtual std::optional - getPredecessor(ripple::uint256 const& key, uint32_t seq) const = 0; + getPredecessor(xrpl::uint256 const& key, uint32_t seq) const = 0; /** * @brief Disables the cache. diff --git a/src/data/LedgerCacheLoadingState.hpp b/src/data/LedgerCacheLoadingState.hpp index c77ce974f..49e6d0af5 100644 --- a/src/data/LedgerCacheLoadingState.hpp +++ b/src/data/LedgerCacheLoadingState.hpp @@ -73,23 +73,33 @@ public: */ explicit LedgerCacheLoadingState(LedgerCacheInterface const& cache); - /** @copydoc LedgerCacheLoadingStateInterface::allowLoading() */ + /** + * @copydoc LedgerCacheLoadingStateInterface::allowLoading() + */ void allowLoading() override; - /** @copydoc LedgerCacheLoadingStateInterface::isLoadingAllowed() */ + /** + * @copydoc LedgerCacheLoadingStateInterface::isLoadingAllowed() + */ [[nodiscard]] bool isLoadingAllowed() const override; - /** @copydoc LedgerCacheLoadingStateInterface::waitForLoadingAllowed() */ + /** + * @copydoc LedgerCacheLoadingStateInterface::waitForLoadingAllowed() + */ void waitForLoadingAllowed() const override; - /** @copydoc LedgerCacheLoadingStateInterface::isCurrentlyLoading() */ + /** + * @copydoc LedgerCacheLoadingStateInterface::isCurrentlyLoading() + */ [[nodiscard]] bool isCurrentlyLoading() const override; - /** @copydoc LedgerCacheLoadingStateInterface::clone() */ + /** + * @copydoc LedgerCacheLoadingStateInterface::clone() + */ [[nodiscard]] std::unique_ptr clone() const override; }; diff --git a/src/data/LedgerHeaderCache.hpp b/src/data/LedgerHeaderCache.hpp index 65707a7f7..cb79ad9cd 100644 --- a/src/data/LedgerHeaderCache.hpp +++ b/src/data/LedgerHeaderCache.hpp @@ -11,7 +11,7 @@ namespace data { /** - * @brief A simple cache holding one `ripple::LedgerHeader` to reduce DB lookups. + * @brief A simple cache holding one `xrpl::LedgerHeader` to reduce DB lookups. * * Used internally by backend implementations. When a ledger header is * fetched via `FetchLedgerBySeq` (often triggered by RPC commands), @@ -27,7 +27,7 @@ public: * @brief Struct to store ledger header cache entry and the sequence it belongs to */ struct CacheEntry { - ripple::LedgerHeader ledger; + xrpl::LedgerHeader ledger; uint32_t seq{}; /** diff --git a/src/data/Types.hpp b/src/data/Types.hpp index fa3ad7b7f..90a37094e 100644 --- a/src/data/Types.hpp +++ b/src/data/Types.hpp @@ -20,7 +20,7 @@ using Blob = std::vector; * @brief Represents an object in the ledger. */ struct LedgerObject { - ripple::uint256 key; + xrpl::uint256 key; Blob blob; bool @@ -32,7 +32,7 @@ struct LedgerObject { */ struct LedgerPage { std::vector objects; - std::optional cursor; + std::optional cursor; }; /** @@ -40,7 +40,7 @@ struct LedgerPage { */ struct BookOffersPage { std::vector offers; - std::optional cursor; + std::optional cursor; }; /** @@ -159,9 +159,9 @@ struct TransactionsAndCursor { * @brief Represents a NFToken. */ struct NFT { - ripple::uint256 tokenID; + xrpl::uint256 tokenID; std::uint32_t ledgerSequence{}; - ripple::AccountID owner; + xrpl::AccountID owner; Blob uri; bool isBurned{}; @@ -176,9 +176,9 @@ struct NFT { * @param uri The URI * @param isBurned Whether the token is burned */ - NFT(ripple::uint256 const& tokenID, + NFT(xrpl::uint256 const& tokenID, std::uint32_t ledgerSequence, - ripple::AccountID const& owner, + xrpl::AccountID const& owner, Blob uri, bool isBurned) : tokenID{tokenID} @@ -197,9 +197,9 @@ struct NFT { * @param owner The owner * @param isBurned Whether the token is burned */ - NFT(ripple::uint256 const& tokenID, + NFT(xrpl::uint256 const& tokenID, std::uint32_t ledgerSequence, - ripple::AccountID const& owner, + xrpl::AccountID const& owner, bool isBurned) : NFT(tokenID, ledgerSequence, owner, {}, isBurned) { @@ -226,7 +226,7 @@ struct NFT { */ struct NFTsAndCursor { std::vector nfts; - std::optional cursor; + std::optional cursor; }; /** @@ -234,7 +234,7 @@ struct NFTsAndCursor { */ struct MPTHoldersAndCursor { std::vector mptokens; - std::optional cursor; + std::optional cursor; }; /** @@ -253,7 +253,7 @@ struct LedgerRange { */ struct Amendment { std::string name; - ripple::uint256 feature; + xrpl::uint256 feature; bool isSupportedByXRPL = false; bool isSupportedByClio = false; bool isRetired = false; @@ -264,7 +264,7 @@ struct Amendment { * @param name The name of the amendment * @return The amendment Id as uint256 */ - static ripple::uint256 + static xrpl::uint256 getAmendmentId(std::string_view const name); /** @@ -294,14 +294,20 @@ struct AmendmentKey { { } - /** @brief Conversion to string */ + /** + * @brief Conversion to string + */ operator std::string const&() const; - /** @brief Conversion to string_view */ + /** + * @brief Conversion to string_view + */ operator std::string_view() const; - /** @brief Conversion to uint256 */ - operator ripple::uint256() const; + /** + * @brief Conversion to uint256 + */ + operator xrpl::uint256() const; /** * @brief Comparison operators @@ -312,14 +318,12 @@ struct AmendmentKey { operator<=>(AmendmentKey const& other) const = default; }; -constexpr ripple::uint256 kFIRST_KEY{ +constexpr xrpl::uint256 kFirstKey{ "0000000000000000000000000000000000000000000000000000000000000000" }; -constexpr ripple::uint256 kLAST_KEY{ +constexpr xrpl::uint256 kLastKey{ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" }; -constexpr ripple::uint256 kHI192{ - "0000000000000000000000000000000000000000000000001111111111111111" -}; +constexpr xrpl::uint256 kHi192{"0000000000000000000000000000000000000000000000001111111111111111"}; } // namespace data diff --git a/src/data/cassandra/CassandraBackendFamily.hpp b/src/data/cassandra/CassandraBackendFamily.hpp index 50166ac48..3d0aa01f3 100644 --- a/src/data/cassandra/CassandraBackendFamily.hpp +++ b/src/data/cassandra/CassandraBackendFamily.hpp @@ -77,6 +77,13 @@ protected: // TODO: move to interface level mutable FetchLedgerCacheType ledgerCache_{}; + static constexpr std::size_t kTransactionCursorBindIndex = 1; + static constexpr std::size_t kTransactionLimitBindIndex = 2; + static constexpr std::size_t kMPTokenIssuanceTxCursorBindIndex = 1; + static constexpr std::size_t kMPTokenIssuanceTxLimitBindIndex = 2; + static constexpr std::size_t kAccountMPTokenIssuanceTxCursorBindIndex = 2; + static constexpr std::size_t kAccountMPTokenIssuanceTxLimitBindIndex = 3; + public: /** * @brief Create a new cassandra/scylla backend instance. @@ -127,14 +134,14 @@ public: LOG(log_.info()) << "Created (revamped) CassandraBackend"; } - /* + /** * @brief Move constructor is deleted because handle_ is shared by reference with executor */ CassandraBackendFamily(CassandraBackendFamily&&) = delete; TransactionsAndCursor fetchAccountTransactions( - ripple::AccountID const& account, + xrpl::AccountID const& account, std::uint32_t const limit, bool forward, std::optional const& txnCursor, @@ -154,22 +161,24 @@ public: auto cursor = txnCursor; if (cursor) { - statement.bindAt(1, cursor->asTuple()); - LOG(log_.debug()) << "account = " << ripple::strHex(account) + statement.bindAt(kTransactionCursorBindIndex, cursor->asTuple()); + LOG(log_.debug()) << "account = " << xrpl::strHex(account) << " tuple = " << cursor->ledgerSequence << cursor->transactionIndex; } else { auto const seq = forward ? rng->minSequence : rng->maxSequence; auto const placeHolder = forward ? 0u : std::numeric_limits::max(); - statement.bindAt(1, std::make_tuple(placeHolder, placeHolder)); - LOG(log_.debug()) << "account = " << ripple::strHex(account) << " idx = " << seq + statement.bindAt( + kTransactionCursorBindIndex, std::make_tuple(placeHolder, placeHolder) + ); + LOG(log_.debug()) << "account = " << xrpl::strHex(account) << " idx = " << seq << " tuple = " << placeHolder; } // FIXME: Limit is a hack to support uint32_t properly for the time // being. Should be removed later and schema updated to use proper // types. - statement.bindAt(2, Limit{limit}); + statement.bindAt(kTransactionLimitBindIndex, Limit{limit}); auto const res = executor_.read(yield, statement); auto const& results = res.value(); if (not results.hasRows()) { @@ -177,12 +186,11 @@ public: return {}; } - std::vector hashes = {}; + std::vector hashes = {}; auto numRows = results.numRows(); LOG(log_.info()) << "num_rows = " << numRows; - for (auto [hash, data] : - extract>(results)) { + for (auto [hash, data] : extract>(results)) { hashes.push_back(hash); if (--numRows == 0) { LOG(log_.debug()) << "Setting cursor"; @@ -208,7 +216,7 @@ public: } void - writeLedger(ripple::LedgerHeader const& ledgerHeader, std::string&& blob) override + writeLedger(xrpl::LedgerHeader const& ledgerHeader, std::string&& blob) override { executor_.write(schema_->insertLedgerHeader, ledgerHeader.seq, std::move(blob)); @@ -237,7 +245,7 @@ public: return std::nullopt; } - std::optional + std::optional fetchLedgerBySequence( std::uint32_t const sequence, boost::asio::yield_context yield @@ -251,7 +259,7 @@ public: if (auto const& result = res.value(); result) { if (auto const maybeValue = result.template get>(); maybeValue) { - auto const header = util::deserializeHeader(ripple::makeSlice(*maybeValue)); + auto const header = util::deserializeHeader(xrpl::makeSlice(*maybeValue)); ledgerCache_.put(FetchLedgerCache::CacheEntry{header, sequence}); return header; } @@ -268,8 +276,8 @@ public: return std::nullopt; } - std::optional - fetchLedgerByHash(ripple::uint256 const& hash, boost::asio::yield_context yield) const override + std::optional + fetchLedgerByHash(xrpl::uint256 const& hash, boost::asio::yield_context yield) const override { if (auto const res = executor_.read(yield, schema_->selectLedgerByHash, hash); res) { if (auto const& result = res.value(); result) { @@ -336,7 +344,7 @@ public: return fetchTransactions(hashes, yield); } - std::vector + std::vector fetchAllTransactionHashesInLedger( std::uint32_t const ledgerSequence, boost::asio::yield_context yield @@ -358,8 +366,8 @@ public: return {}; } - std::vector hashes; - for (auto [hash] : extract(result)) + std::vector hashes; + for (auto [hash] : extract(result)) hashes.push_back(std::move(hash)); auto end = std::chrono::system_clock::now(); @@ -375,7 +383,7 @@ public: std::optional fetchNFT( - ripple::uint256 const& tokenID, + xrpl::uint256 const& tokenID, std::uint32_t const ledgerSequence, boost::asio::yield_context yield ) const override @@ -384,8 +392,7 @@ public: if (not res) return std::nullopt; - if (auto const maybeRow = res->template get(); - maybeRow) { + if (auto const maybeRow = res->template get(); maybeRow) { auto [seq, owner, isBurned] = *maybeRow; auto result = std::make_optional(tokenID, seq, owner, isBurned); @@ -402,7 +409,7 @@ public: // one. auto uriRes = executor_.read(yield, schema_->selectNFTURI, tokenID, ledgerSequence); if (uriRes) { - if (auto const maybeUri = uriRes->template get(); maybeUri) + if (auto const maybeUri = uriRes->template get(); maybeUri) result->uri = *maybeUri; } @@ -415,7 +422,7 @@ public: TransactionsAndCursor fetchNFTTransactions( - ripple::uint256 const& tokenID, + xrpl::uint256 const& tokenID, std::uint32_t const limit, bool const forward, std::optional const& cursorIn, @@ -435,19 +442,21 @@ public: auto cursor = cursorIn; if (cursor) { - statement.bindAt(1, cursor->asTuple()); - LOG(log_.debug()) << "token_id = " << ripple::strHex(tokenID) + statement.bindAt(kTransactionCursorBindIndex, cursor->asTuple()); + LOG(log_.debug()) << "token_id = " << xrpl::strHex(tokenID) << " tuple = " << cursor->ledgerSequence << cursor->transactionIndex; } else { auto const seq = forward ? rng->minSequence : rng->maxSequence; auto const placeHolder = forward ? 0 : std::numeric_limits::max(); - statement.bindAt(1, std::make_tuple(placeHolder, placeHolder)); - LOG(log_.debug()) << "token_id = " << ripple::strHex(tokenID) << " idx = " << seq + statement.bindAt( + kTransactionCursorBindIndex, std::make_tuple(placeHolder, placeHolder) + ); + LOG(log_.debug()) << "token_id = " << xrpl::strHex(tokenID) << " idx = " << seq << " tuple = " << placeHolder; } - statement.bindAt(2, Limit{limit}); + statement.bindAt(kTransactionLimitBindIndex, Limit{limit}); auto const res = executor_.read(yield, statement); auto const& results = res.value(); @@ -456,12 +465,11 @@ public: return {}; } - std::vector hashes = {}; + std::vector hashes = {}; auto numRows = results.numRows(); LOG(log_.info()) << "num_rows = " << numRows; - for (auto [hash, data] : - extract>(results)) { + for (auto [hash, data] : extract>(results)) { hashes.push_back(hash); if (--numRows == 0) { LOG(log_.debug()) << "Setting cursor"; @@ -485,11 +493,64 @@ public: return {txns, {}}; } + TransactionsAndCursor + fetchMPTokenIssuanceTransactions( + xrpl::uint192 const& mptIssuanceID, + std::uint32_t const limit, + bool const forward, + std::optional const& cursorIn, + boost::asio::yield_context yield + ) const override + { + auto const statement = [this, forward, &mptIssuanceID]() { + if (forward) + return schema_->selectMPTokenIssuanceTxForward.bind(mptIssuanceID); + + return schema_->selectMPTokenIssuanceTx.bind(mptIssuanceID); + }(); + return fetchMPTokenIssuanceTransactionsImpl( + statement, + kMPTokenIssuanceTxCursorBindIndex, + kMPTokenIssuanceTxLimitBindIndex, + limit, + forward, + cursorIn, + yield + ); + } + + TransactionsAndCursor + fetchAccountMPTokenIssuanceTransactions( + xrpl::uint192 const& mptIssuanceID, + xrpl::AccountID const& account, + std::uint32_t const limit, + bool const forward, + std::optional const& cursorIn, + boost::asio::yield_context yield + ) const override + { + auto const statement = [this, forward, &mptIssuanceID, &account]() { + if (forward) + return schema_->selectAccountMPTokenIssuanceTxForward.bind(mptIssuanceID, account); + + return schema_->selectAccountMPTokenIssuanceTx.bind(mptIssuanceID, account); + }(); + return fetchMPTokenIssuanceTransactionsImpl( + statement, + kAccountMPTokenIssuanceTxCursorBindIndex, + kAccountMPTokenIssuanceTxLimitBindIndex, + limit, + forward, + cursorIn, + yield + ); + } + MPTHoldersAndCursor fetchMPTHolders( - ripple::uint192 const& mptID, + xrpl::uint192 const& mptID, std::uint32_t const limit, - std::optional const& cursorIn, + std::optional const& cursorIn, std::uint32_t const ledgerSequence, boost::asio::yield_context yield ) const override @@ -498,7 +559,7 @@ public: yield, schema_->selectMPTHolders, mptID, - cursorIn.value_or(ripple::AccountID(0)), + cursorIn.value_or(xrpl::AccountID(0)), Limit{limit} ); @@ -508,10 +569,10 @@ public: return {}; } - std::vector mptKeys; - std::optional cursor; - for (auto const [holder] : extract(holderResults)) { - mptKeys.push_back(ripple::keylet::mptoken(mptID, holder).key); + std::vector mptKeys; + std::optional cursor; + for (auto const [holder] : extract(holderResults)) { + mptKeys.push_back(xrpl::keylet::mptoken(mptID, holder).key); cursor = holder; } @@ -532,13 +593,13 @@ public: std::optional doFetchLedgerObject( - ripple::uint256 const& key, + xrpl::uint256 const& key, std::uint32_t const sequence, boost::asio::yield_context yield ) const override { LOG(log_.debug()) << "Fetching ledger object for seq " << sequence - << ", key = " << ripple::to_string(key); + << ", key = " << xrpl::to_string(key); if (auto const res = executor_.read(yield, schema_->selectObject, key, sequence); res) { if (auto const result = res->template get(); result) { if (result->size()) @@ -555,13 +616,13 @@ public: std::optional doFetchLedgerObjectSeq( - ripple::uint256 const& key, + xrpl::uint256 const& key, std::uint32_t const sequence, boost::asio::yield_context yield ) const override { LOG(log_.debug()) << "Fetching ledger object for seq " << sequence - << ", key = " << ripple::to_string(key); + << ", key = " << xrpl::to_string(key); if (auto const res = executor_.read(yield, schema_->selectObject, key, sequence); res) { if (auto const result = res->template get(); result) { auto [_, seq] = *result; @@ -576,7 +637,7 @@ public: } std::optional - fetchTransaction(ripple::uint256 const& hash, boost::asio::yield_context yield) const override + fetchTransaction(xrpl::uint256 const& hash, boost::asio::yield_context yield) const override { if (auto const res = executor_.read(yield, schema_->selectTransaction, hash); res) { if (auto const maybeValue = res->template get(); @@ -593,17 +654,17 @@ public: return std::nullopt; } - std::optional + std::optional doFetchSuccessorKey( - ripple::uint256 key, + xrpl::uint256 key, std::uint32_t const ledgerSequence, boost::asio::yield_context yield ) const override { if (auto const res = executor_.read(yield, schema_->selectSuccessor, key, ledgerSequence); res) { - if (auto const result = res->template get(); result) { - if (*result == kLAST_KEY) + if (auto const result = res->template get(); result) { + if (*result == kLastKey) return std::nullopt; return result; } @@ -618,7 +679,7 @@ public: std::vector fetchTransactions( - std::vector const& hashes, + std::vector const& hashes, boost::asio::yield_context yield ) const override { @@ -664,7 +725,7 @@ public: std::vector doFetchLedgerObjects( - std::vector const& keys, + std::vector const& keys, std::uint32_t const sequence, boost::asio::yield_context yield ) const override @@ -713,7 +774,7 @@ public: ) const override { auto const [keys, timeDiff] = - util::timed([this, &ledgerSequence, yield]() -> std::vector { + util::timed([this, &ledgerSequence, yield]() -> std::vector { auto const res = executor_.read(yield, schema_->selectDiff, ledgerSequence); if (not res) { LOG(log_.error()) << "Could not fetch ledger diff: " << res.error() @@ -728,8 +789,8 @@ public: return {}; } - std::vector resultKeys; - for (auto [key] : extract(results)) + std::vector resultKeys; + for (auto [key] : extract(results)) resultKeys.push_back(key); return resultKeys; @@ -877,6 +938,55 @@ public: executor_.write(std::move(statements)); } + void + writeMPTokenIssuanceTransactions( + std::vector const& data + ) override + { + std::vector statements; + statements.reserve(data.size()); + + std::ranges::transform(data, std::back_inserter(statements), [this](auto const& record) { + return schema_->insertMPTokenIssuanceTx.bind( + record.mptIssuanceID, + std::make_tuple(record.ledgerSequence, record.transactionIndex), + record.txHash + ); + }); + + executor_.write(std::move(statements)); + } + + void + writeAccountMPTokenIssuanceTransactions( + std::vector const& data + ) override + { + std::size_t numStatements = 0u; + for (auto const& record : data) + numStatements += record.accounts.size(); + + std::vector statements; + statements.reserve(numStatements); + + for (auto const& record : data) { + std::ranges::transform( + record.accounts, + std::back_inserter(statements), + [this, &record](auto const& account) { + return schema_->insertAccountMPTokenIssuanceTx.bind( + record.mptIssuanceID, + account, + std::make_tuple(record.ledgerSequence, record.transactionIndex), + record.txHash + ); + } + ); + } + + executor_.write(std::move(statements)); + } + void writeTransaction( std::string&& hash, @@ -918,8 +1028,8 @@ public: // to record the URI and link to the issuer_nf_tokens table. if (record.uri) { statements.push_back(schema_->insertIssuerNFT.bind( - ripple::nft::getIssuer(record.tokenID), - static_cast(ripple::nft::getTaxon(record.tokenID)), + xrpl::nft::getIssuer(record.tokenID), + static_cast(xrpl::nft::getTaxon(record.tokenID)), record.tokenID )); statements.push_back(schema_->insertNFTURI.bind( @@ -1016,6 +1126,86 @@ protected: return true; } + + /** + * @brief Shared implementation of the two MPTokenIssuance transaction-index fetchers. + * + * @note The forward path queries with an inclusive seq_idx >=, + * so the returned cursor's transaction index is advanced + * by one to avoid re-reading the last row on the next page. + * + * @param statement The statement already bound with the partition-key columns. + * @param cursorIdx The bind index for the `seq_idx` cursor tuple. + * @param limitIdx The bind index for the `LIMIT`. + * @param limit The maximum number of transactions per result page. + * @param forward Whether the page is fetched forwards or backwards. + * @param cursorIn The cursor to resume fetching from. + * @param yield The coroutine context. + * @return Results and a cursor to resume from. + */ + TransactionsAndCursor + fetchMPTokenIssuanceTransactionsImpl( + Statement const& statement, + std::size_t const cursorIdx, + std::size_t const limitIdx, + std::uint32_t const limit, + bool const forward, + std::optional const& cursorIn, + boost::asio::yield_context yield + ) const + { + auto rng = fetchLedgerRange(); + if (!rng) + return {.txns = {}, .cursor = {}}; + + auto cursor = cursorIn; + if (cursor.has_value()) { + statement.bindAt(cursorIdx, cursor->asTuple()); + } else { + // Forward uses the nft_history-style inclusive lower bound; reverse starts just past + // the latest validated ledger so its exclusive `<` query includes that ledger's rows. + auto const ledgerSequence = forward ? rng->minSequence : rng->maxSequence; + auto const transactionIndex = forward ? 0u : std::numeric_limits::max(); + statement.bindAt(cursorIdx, std::make_tuple(ledgerSequence, transactionIndex)); + } + + statement.bindAt(limitIdx, Limit{limit}); + + auto const res = executor_.read(yield, statement); + auto const& results = res.value(); + if (not results.hasRows()) { + LOG(log_.debug()) << "No rows returned"; + return {}; + } + + std::vector hashes = {}; + auto numRows = results.numRows(); + + for (auto const& [hash, data] : + extract>(results)) { + hashes.push_back(hash); + + if (--numRows == 0) { + LOG(log_.debug()) << "Setting cursor"; + cursor = data; + + // forward queries by ledger/tx sequence `>=` + // so we have to advance the index by one + if (forward) + ++cursor->transactionIndex; + } + } + + auto txns = fetchTransactions(hashes, yield); + LOG(log_.debug()) << "MPTokenIssuance Txns = " << txns.size(); + + if (txns.size() == limit) { + LOG(log_.debug()) << "Returning cursor"; + return {std::move(txns), cursor}; + } + + return {std::move(txns), {}}; + } }; } // namespace data::cassandra diff --git a/src/data/cassandra/Schema.hpp b/src/data/cassandra/Schema.hpp index 8725ee302..eda31318a 100644 --- a/src/data/cassandra/Schema.hpp +++ b/src/data/cassandra/Schema.hpp @@ -278,9 +278,42 @@ public: R"( CREATE TABLE IF NOT EXISTS {} ( - mpt_id blob, - holder blob, - PRIMARY KEY (mpt_id, holder) + mptoken_issuance_id blob, + seq_idx tuple, + hash blob, + PRIMARY KEY (mptoken_issuance_id, seq_idx) + ) + WITH CLUSTERING ORDER BY (seq_idx DESC) + )", + qualifiedTableName(settingsProvider_.get(), "mptoken_issuance_transactions") + ) + ); + + statements.emplace_back( + fmt::format( + R"( + CREATE TABLE IF NOT EXISTS {} + ( + mptoken_issuance_id blob, + account blob, + seq_idx tuple, + hash blob, + PRIMARY KEY ((mptoken_issuance_id, account), seq_idx) + ) + WITH CLUSTERING ORDER BY (seq_idx DESC) + )", + qualifiedTableName(settingsProvider_.get(), "account_mptoken_issuance_transactions") + ) + ); + + statements.emplace_back( + fmt::format( + R"( + CREATE TABLE IF NOT EXISTS {} + ( + mpt_id blob, + holder blob, + PRIMARY KEY (mpt_id, holder) ) WITH CLUSTERING ORDER BY (holder ASC) )", @@ -474,6 +507,34 @@ public: ); }(); + PreparedStatement insertMPTokenIssuanceTx = [this]() { + return handle_.get().prepare( + fmt::format( + R"( + INSERT INTO {} + (mptoken_issuance_id, seq_idx, hash) + VALUES (?, ?, ?) + )", + qualifiedTableName(settingsProvider_.get(), "mptoken_issuance_transactions") + ) + ); + }(); + + PreparedStatement insertAccountMPTokenIssuanceTx = [this]() { + return handle_.get().prepare( + fmt::format( + R"( + INSERT INTO {} + (mptoken_issuance_id, account, seq_idx, hash) + VALUES (?, ?, ?, ?) + )", + qualifiedTableName( + settingsProvider_.get(), "account_mptoken_issuance_transactions" + ) + ) + ); + }(); + PreparedStatement insertMPTHolder = [this]() { return handle_.get().prepare( fmt::format( @@ -740,6 +801,76 @@ public: ); }(); + PreparedStatement selectMPTokenIssuanceTx = [this]() { + return handle_.get().prepare( + fmt::format( + R"( + SELECT hash, seq_idx + FROM {} + WHERE mptoken_issuance_id = ? + AND seq_idx < ? + ORDER BY seq_idx DESC + LIMIT ? + )", + qualifiedTableName(settingsProvider_.get(), "mptoken_issuance_transactions") + ) + ); + }(); + + PreparedStatement selectMPTokenIssuanceTxForward = [this]() { + return handle_.get().prepare( + fmt::format( + R"( + SELECT hash, seq_idx + FROM {} + WHERE mptoken_issuance_id = ? + AND seq_idx >= ? + ORDER BY seq_idx ASC + LIMIT ? + )", + qualifiedTableName(settingsProvider_.get(), "mptoken_issuance_transactions") + ) + ); + }(); + + PreparedStatement selectAccountMPTokenIssuanceTx = [this]() { + return handle_.get().prepare( + fmt::format( + R"( + SELECT hash, seq_idx + FROM {} + WHERE mptoken_issuance_id = ? + AND account = ? + AND seq_idx < ? + ORDER BY seq_idx DESC + LIMIT ? + )", + qualifiedTableName( + settingsProvider_.get(), "account_mptoken_issuance_transactions" + ) + ) + ); + }(); + + PreparedStatement selectAccountMPTokenIssuanceTxForward = [this]() { + return handle_.get().prepare( + fmt::format( + R"( + SELECT hash, seq_idx + FROM {} + WHERE mptoken_issuance_id = ? + AND account = ? + AND seq_idx >= ? + ORDER BY seq_idx ASC + LIMIT ? + )", + qualifiedTableName( + settingsProvider_.get(), "account_mptoken_issuance_transactions" + ) + ) + ); + }(); + PreparedStatement selectNFTIDsByIssuerTaxon = [this]() { return handle_.get().prepare( fmt::format( diff --git a/src/data/cassandra/SettingsProvider.cpp b/src/data/cassandra/SettingsProvider.cpp index c9f461d96..d0f57eaa3 100644 --- a/src/data/cassandra/SettingsProvider.cpp +++ b/src/data/cassandra/SettingsProvider.cpp @@ -90,13 +90,13 @@ SettingsProvider::parseSettings() const if (config_.getValueView("connect_timeout").hasValue()) { auto const connectTimeoutSecond = config_.get("connect_timeout"); settings.connectionTimeout = - std::chrono::milliseconds{connectTimeoutSecond * util::kMILLISECONDS_PER_SECOND}; + std::chrono::milliseconds{connectTimeoutSecond * util::kMillisecondsPerSecond}; } if (config_.getValueView("request_timeout").hasValue()) { auto const requestTimeoutSecond = config_.get("request_timeout"); settings.requestTimeout = - std::chrono::milliseconds{requestTimeoutSecond * util::kMILLISECONDS_PER_SECOND}; + std::chrono::milliseconds{requestTimeoutSecond * util::kMillisecondsPerSecond}; } settings.certificate = parseOptionalCertificate(); diff --git a/src/data/cassandra/impl/AsyncExecutor.hpp b/src/data/cassandra/impl/AsyncExecutor.hpp index 7748811fa..53e0e860e 100644 --- a/src/data/cassandra/impl/AsyncExecutor.hpp +++ b/src/data/cassandra/impl/AsyncExecutor.hpp @@ -35,7 +35,7 @@ template < SomeRetryPolicy RetryPolicyType = ExponentialBackoffRetryPolicy> class AsyncExecutor : public std::enable_shared_from_this< AsyncExecutor> { - using FutureWithCallbackType = typename HandleType::FutureWithCallbackType; + using FutureWithCallbackType = HandleType::FutureWithCallbackType; using CallbackType = std::function; using RetryCallbackType = std::function; diff --git a/src/data/cassandra/impl/Batch.cpp b/src/data/cassandra/impl/Batch.cpp index aa52d5dad..e186aefb6 100644 --- a/src/data/cassandra/impl/Batch.cpp +++ b/src/data/cassandra/impl/Batch.cpp @@ -12,7 +12,7 @@ #include namespace { -constexpr auto kBATCH_DELETER = [](CassBatch* ptr) { cass_batch_free(ptr); }; +constexpr auto kBatchDeleter = [](CassBatch* ptr) { cass_batch_free(ptr); }; } // namespace namespace data::cassandra::impl { @@ -29,7 +29,7 @@ namespace data::cassandra::impl { * https://docs.datastax.com/en/developer/cpp-driver-dse/1.10/features/basics/batches/index.html */ Batch::Batch(std::vector const& statements) - : ManagedObject{cass_batch_new(CASS_BATCH_TYPE_UNLOGGED), kBATCH_DELETER} + : ManagedObject{cass_batch_new(CASS_BATCH_TYPE_UNLOGGED), kBatchDeleter} { cass_batch_set_is_idempotent(*this, cass_true); diff --git a/src/data/cassandra/impl/Cluster.cpp b/src/data/cassandra/impl/Cluster.cpp index c75c42d3a..904e9f4d0 100644 --- a/src/data/cassandra/impl/Cluster.cpp +++ b/src/data/cassandra/impl/Cluster.cpp @@ -14,13 +14,13 @@ namespace { -constexpr auto kCLUSTER_DELETER = [](CassCluster* ptr) { cass_cluster_free(ptr); }; +constexpr auto kClusterDeleter = [](CassCluster* ptr) { cass_cluster_free(ptr); }; }; // namespace namespace data::cassandra::impl { -Cluster::Cluster(Settings const& settings) : ManagedObject{cass_cluster_new(), kCLUSTER_DELETER} +Cluster::Cluster(Settings const& settings) : ManagedObject{cass_cluster_new(), kClusterDeleter} { using std::to_string; diff --git a/src/data/cassandra/impl/Cluster.hpp b/src/data/cassandra/impl/Cluster.hpp index 7d445d1d2..cf6bd9668 100644 --- a/src/data/cassandra/impl/Cluster.hpp +++ b/src/data/cassandra/impl/Cluster.hpp @@ -35,11 +35,11 @@ providerFromString(std::string const& provider) * @brief Bundles all cassandra settings in one place. */ struct Settings { - static constexpr std::size_t kDEFAULT_CONNECTION_TIMEOUT = 10000; - static constexpr uint32_t kDEFAULT_MAX_WRITE_REQUESTS_OUTSTANDING = 10'000; - static constexpr uint32_t kDEFAULT_MAX_READ_REQUESTS_OUTSTANDING = 100'000; - static constexpr std::size_t kDEFAULT_BATCH_SIZE = 20; - static constexpr Provider kDEFAULT_PROVIDER = Provider::Cassandra; + static constexpr std::size_t kDefaultConnectionTimeout = 10000; + static constexpr uint32_t kDefaultMaxWriteRequestsOutstanding = 10'000; + static constexpr uint32_t kDefaultMaxReadRequestsOutstanding = 100'000; + static constexpr std::size_t kDefaultBatchSize = 20; + static constexpr Provider kDefaultProvider = Provider::Cassandra; /** * @brief Represents the configuration of contact points for cassandra. @@ -56,50 +56,78 @@ struct Settings { std::string bundle; // no meaningful default }; - /** @brief Enables or disables cassandra driver logger */ + /** + * @brief Enables or disables cassandra driver logger + */ bool enableLog = false; - /** @brief Connect timeout specified in milliseconds */ + /** + * @brief Connect timeout specified in milliseconds + */ std::chrono::milliseconds connectionTimeout = - std::chrono::milliseconds{kDEFAULT_CONNECTION_TIMEOUT}; + std::chrono::milliseconds{kDefaultConnectionTimeout}; - /** @brief Request timeout specified in milliseconds */ + /** + * @brief Request timeout specified in milliseconds + */ std::chrono::milliseconds requestTimeout = std::chrono::milliseconds{0}; // no timeout at all - /** @brief Connection information; either ContactPoints or SecureConnectionBundle */ + /** + * @brief Connection information; either ContactPoints or SecureConnectionBundle + */ std::variant connectionInfo = ContactPoints{}; - /** @brief The number of threads for the driver to pool */ + /** + * @brief The number of threads for the driver to pool + */ uint32_t threads = std::thread::hardware_concurrency(); - /** @brief The maximum number of outstanding write requests at any given moment */ - uint32_t maxWriteRequestsOutstanding = kDEFAULT_MAX_WRITE_REQUESTS_OUTSTANDING; + /** + * @brief The maximum number of outstanding write requests at any given moment + */ + uint32_t maxWriteRequestsOutstanding = kDefaultMaxWriteRequestsOutstanding; - /** @brief The maximum number of outstanding read requests at any given moment */ - uint32_t maxReadRequestsOutstanding = kDEFAULT_MAX_READ_REQUESTS_OUTSTANDING; + /** + * @brief The maximum number of outstanding read requests at any given moment + */ + uint32_t maxReadRequestsOutstanding = kDefaultMaxReadRequestsOutstanding; - /** @brief The number of connection per host to always have active */ + /** + * @brief The number of connection per host to always have active + */ uint32_t coreConnectionsPerHost = 3u; - /** @brief Size of batches when writing */ - std::size_t writeBatchSize = kDEFAULT_BATCH_SIZE; + /** + * @brief Size of batches when writing + */ + std::size_t writeBatchSize = kDefaultBatchSize; - /** @brief Provider to know if we are using scylladb or keyspace */ - Provider provider = kDEFAULT_PROVIDER; + /** + * @brief Provider to know if we are using scylladb or keyspace + */ + Provider provider = kDefaultProvider; - /** @brief Size of the IO queue */ + /** + * @brief Size of the IO queue + */ std::optional queueSizeIO = std::nullopt; // NOLINT(readability-redundant-member-init) - /** @brief SSL certificate */ + /** + * @brief SSL certificate + */ std::optional certificate = std::nullopt; // NOLINT(readability-redundant-member-init) - /** @brief Username/login */ + /** + * @brief Username/login + */ std::optional username = std::nullopt; // NOLINT(readability-redundant-member-init) - /** @brief Password to match the `username` */ + /** + * @brief Password to match the `username` + */ std::optional password = std::nullopt; // NOLINT(readability-redundant-member-init) diff --git a/src/data/cassandra/impl/Collection.hpp b/src/data/cassandra/impl/Collection.hpp index 8ee404dbb..8847936c4 100644 --- a/src/data/cassandra/impl/Collection.hpp +++ b/src/data/cassandra/impl/Collection.hpp @@ -14,7 +14,7 @@ namespace data::cassandra::impl { class Collection : public ManagedObject { - static constexpr auto kDELETER = [](CassCollection* ptr) { cass_collection_free(ptr); }; + static constexpr auto kDeleter = [](CassCollection* ptr) { cass_collection_free(ptr); }; static void throwErrorIfNeeded(CassError const rc, std::string_view const label) @@ -30,7 +30,7 @@ public: template explicit Collection(std::vector const& value) - : ManagedObject{cass_collection_new(CASS_COLLECTION_TYPE_LIST, value.size()), kDELETER} + : ManagedObject{cass_collection_new(CASS_COLLECTION_TYPE_LIST, value.size()), kDeleter} { bind(value); } @@ -58,14 +58,14 @@ public: } void - append(ripple::uint256 const& value) const + append(xrpl::uint256 const& value) const { auto const rc = cass_collection_append_bytes( *this, static_cast(static_cast(value.data())), - ripple::uint256::size() + xrpl::uint256::size() ); - throwErrorIfNeeded(rc, "Bind ripple::uint256"); + throwErrorIfNeeded(rc, "Bind xrpl::uint256"); } }; } // namespace data::cassandra::impl diff --git a/src/data/cassandra/impl/ExecutionStrategy.hpp b/src/data/cassandra/impl/ExecutionStrategy.hpp index fb874c277..e8907a5f9 100644 --- a/src/data/cassandra/impl/ExecutionStrategy.hpp +++ b/src/data/cassandra/impl/ExecutionStrategy.hpp @@ -65,15 +65,15 @@ class DefaultExecutionStrategy { std::reference_wrapper handle_; std::thread thread_; - typename BackendCountersType::PtrType counters_; + BackendCountersType::PtrType counters_; public: - using ResultOrErrorType = typename HandleType::ResultOrErrorType; - using StatementType = typename HandleType::StatementType; - using PreparedStatementType = typename HandleType::PreparedStatementType; - using FutureType = typename HandleType::FutureType; - using FutureWithCallbackType = typename HandleType::FutureWithCallbackType; - using ResultType = typename HandleType::ResultType; + using ResultOrErrorType = HandleType::ResultOrErrorType; + using StatementType = HandleType::StatementType; + using PreparedStatementType = HandleType::PreparedStatementType; + using FutureType = HandleType::FutureType; + using FutureWithCallbackType = HandleType::FutureWithCallbackType; + using ResultType = HandleType::ResultType; using CompletionTokenType = boost::asio::yield_context; /** @@ -83,7 +83,7 @@ public: DefaultExecutionStrategy( Settings const& settings, HandleType const& handle, - typename BackendCountersType::PtrType counters = BackendCountersType::make() + BackendCountersType::PtrType counters = BackendCountersType::make() ) : maxWriteRequestsOutstanding_{settings.maxWriteRequestsOutstanding} , maxReadRequestsOutstanding_{settings.maxReadRequestsOutstanding} @@ -119,7 +119,7 @@ public: /** * @return true if outstanding read requests allowance is exhausted; false otherwise */ - bool + [[nodiscard]] bool isTooBusy() const { bool const result = numReadRequestsOutstanding_ >= maxReadRequestsOutstanding_; @@ -169,7 +169,7 @@ public: * * @param preparedStatement Statement to prepare and execute * @param args Args to bind to the prepared statement - * @throw DatabaseTimeout on timeout + * @throws DatabaseTimeout on timeout */ template void @@ -185,7 +185,7 @@ public: * Retries forever with retry policy specified by @ref AsyncExecutor * * @param statement Statement to execute - * @throw DatabaseTimeout on timeout + * @throws DatabaseTimeout on timeout */ void write(StatementType&& statement) @@ -215,7 +215,7 @@ public: * Retries forever with retry policy specified by @ref AsyncExecutor. * * @param statements Vector of statements to execute as a batch - * @throw DatabaseTimeout on timeout + * @throws DatabaseTimeout on timeout */ void write(std::vector&& statements) @@ -254,7 +254,7 @@ public: * Retries forever with retry policy specified by @ref AsyncExecutor. * * @param statements Vector of statements to execute - * @throw DatabaseTimeout on timeout + * @throws DatabaseTimeout on timeout */ void writeEach(std::vector&& statements) @@ -272,7 +272,7 @@ public: * @param token Completion token (yield_context) * @param preparedStatement Statement to prepare and execute * @param args Args to bind to the prepared statement - * @throw DatabaseTimeout on timeout + * @throws DatabaseTimeout on timeout * @return ResultType or error wrapped in Expected */ template @@ -289,7 +289,7 @@ public: * * @param token Completion token (yield_context) * @param statements Statements to execute in a batch - * @throw DatabaseTimeout on timeout + * @throws DatabaseTimeout on timeout * @return ResultType or error wrapped in Expected */ [[maybe_unused]] ResultOrErrorType @@ -346,7 +346,7 @@ public: * * @param token Completion token (yield_context) * @param statement Statement to execute - * @throw DatabaseTimeout on timeout + * @throws DatabaseTimeout on timeout * @return ResultType or error wrapped in Expected */ [[maybe_unused]] ResultOrErrorType @@ -402,7 +402,7 @@ public: * * @param token Completion token (yield_context) * @param statements Statements to execute - * @throw DatabaseTimeout on db error + * @throws DatabaseTimeout on db error * @return Vector of results */ std::vector @@ -495,7 +495,7 @@ public: /** * @brief Get statistics about the backend. */ - boost::json::object + [[nodiscard]] boost::json::object stats() const { return counters_->report(); @@ -536,13 +536,13 @@ private: } } - bool + [[nodiscard]] bool canAddWriteRequest() const { return numWriteRequestsOutstanding_ < maxWriteRequestsOutstanding_; } - bool + [[nodiscard]] bool finishedAllWriteRequests() const { return numWriteRequestsOutstanding_ == 0; diff --git a/src/data/cassandra/impl/Future.cpp b/src/data/cassandra/impl/Future.cpp index a86ef5645..813499efb 100644 --- a/src/data/cassandra/impl/Future.cpp +++ b/src/data/cassandra/impl/Future.cpp @@ -13,12 +13,12 @@ #include namespace { -constexpr auto kFUTURE_DELETER = [](CassFuture* ptr) { cass_future_free(ptr); }; +constexpr auto kFutureDeleter = [](CassFuture* ptr) { cass_future_free(ptr); }; } // namespace namespace data::cassandra::impl { -/* implicit */ Future::Future(CassFuture* ptr) : ManagedObject{ptr, kFUTURE_DELETER} +/* implicit */ Future::Future(CassFuture* ptr) : ManagedObject{ptr, kFutureDeleter} { } diff --git a/src/data/cassandra/impl/Future.hpp b/src/data/cassandra/impl/Future.hpp index 4dbe1a5aa..4e42b95e3 100644 --- a/src/data/cassandra/impl/Future.hpp +++ b/src/data/cassandra/impl/Future.hpp @@ -33,7 +33,9 @@ public: FutureWithCallback(FutureWithCallback&&) = default; private: - /** Wrapped in a unique_ptr so it can survive std::move :/ */ + /** + * Wrapped in a unique_ptr so it can survive std::move :/ + */ FnPtrType cb_; }; diff --git a/src/data/cassandra/impl/Result.cpp b/src/data/cassandra/impl/Result.cpp index dcfeaf3d2..e5ffb6619 100644 --- a/src/data/cassandra/impl/Result.cpp +++ b/src/data/cassandra/impl/Result.cpp @@ -7,13 +7,13 @@ #include namespace { -constexpr auto kRESULT_DELETER = [](CassResult const* ptr) { cass_result_free(ptr); }; -constexpr auto kRESULT_ITERATOR_DELETER = [](CassIterator* ptr) { cass_iterator_free(ptr); }; +constexpr auto kResultDeleter = [](CassResult const* ptr) { cass_result_free(ptr); }; +constexpr auto kResultIteratorDeleter = [](CassIterator* ptr) { cass_iterator_free(ptr); }; } // namespace namespace data::cassandra::impl { -/* implicit */ Result::Result(CassResult const* ptr) : ManagedObject{ptr, kRESULT_DELETER} +/* implicit */ Result::Result(CassResult const* ptr) : ManagedObject{ptr, kResultDeleter} { } @@ -30,7 +30,7 @@ Result::hasRows() const } /* implicit */ ResultIterator::ResultIterator(CassIterator* ptr) - : ManagedObject{ptr, kRESULT_ITERATOR_DELETER}, hasMore_{cass_iterator_next(ptr) != 0u} + : ManagedObject{ptr, kResultIteratorDeleter}, hasMore_{cass_iterator_next(ptr) != 0u} { } diff --git a/src/data/cassandra/impl/Result.hpp b/src/data/cassandra/impl/Result.hpp index 4e422bc3d..75a1b61a8 100644 --- a/src/data/cassandra/impl/Result.hpp +++ b/src/data/cassandra/impl/Result.hpp @@ -43,18 +43,18 @@ extractColumn(CassRow const* row, std::size_t idx) using UintTupleType = std::tuple; using UCharVectorType = std::vector; - if constexpr (std::is_same_v) { + if constexpr (std::is_same_v) { cass_byte_t const* buf = nullptr; std::size_t bufSize = 0; auto const rc = cass_value_get_bytes(cass_row_get_column(row, idx), &buf, &bufSize); - throwErrorIfNeeded(rc, "Extract ripple::uint256"); - output = ripple::uint256::fromVoid(buf); - } else if constexpr (std::is_same_v) { + throwErrorIfNeeded(rc, "Extract xrpl::uint256"); + output = xrpl::uint256::fromVoid(buf); + } else if constexpr (std::is_same_v) { cass_byte_t const* buf = nullptr; std::size_t bufSize = 0; auto const rc = cass_value_get_bytes(cass_row_get_column(row, idx), &buf, &bufSize); - throwErrorIfNeeded(rc, "Extract ripple::AccountID"); - output = ripple::AccountID::fromVoid(buf); + throwErrorIfNeeded(rc, "Extract xrpl::AccountID"); + output = xrpl::AccountID::fromVoid(buf); } else if constexpr (std::is_same_v) { cass_byte_t const* buf = nullptr; std::size_t bufSize = 0; diff --git a/src/data/cassandra/impl/Session.hpp b/src/data/cassandra/impl/Session.hpp index 013667020..313500403 100644 --- a/src/data/cassandra/impl/Session.hpp +++ b/src/data/cassandra/impl/Session.hpp @@ -7,10 +7,10 @@ namespace data::cassandra::impl { class Session : public ManagedObject { - static constexpr auto kDELETER = [](CassSession* ptr) { cass_session_free(ptr); }; + static constexpr auto kDeleter = [](CassSession* ptr) { cass_session_free(ptr); }; public: - Session() : ManagedObject{cass_session_new(), kDELETER} + Session() : ManagedObject{cass_session_new(), kDeleter} { } }; diff --git a/src/data/cassandra/impl/SslContext.cpp b/src/data/cassandra/impl/SslContext.cpp index 92232bf21..5e6addafe 100644 --- a/src/data/cassandra/impl/SslContext.cpp +++ b/src/data/cassandra/impl/SslContext.cpp @@ -8,13 +8,13 @@ #include namespace { -constexpr auto kCONTEXT_DELETER = [](CassSsl* ptr) { cass_ssl_free(ptr); }; +constexpr auto kContextDeleter = [](CassSsl* ptr) { cass_ssl_free(ptr); }; } // namespace namespace data::cassandra::impl { SslContext::SslContext(std::string const& certificate) - : ManagedObject{cass_ssl_new(), kCONTEXT_DELETER} + : ManagedObject{cass_ssl_new(), kContextDeleter} { cass_ssl_set_verify_flags(*this, CASS_SSL_VERIFY_NONE); if (auto const rc = cass_ssl_add_trusted_cert(*this, certificate.c_str()); rc != CASS_OK) { diff --git a/src/data/cassandra/impl/Statement.hpp b/src/data/cassandra/impl/Statement.hpp index d70aeb65c..99fd6ab04 100644 --- a/src/data/cassandra/impl/Statement.hpp +++ b/src/data/cassandra/impl/Statement.hpp @@ -26,7 +26,7 @@ namespace data::cassandra::impl { class Statement : public ManagedObject { - static constexpr auto kDELETER = [](CassStatement* ptr) { cass_statement_free(ptr); }; + static constexpr auto kDeleter = [](CassStatement* ptr) { cass_statement_free(ptr); }; public: /** @@ -37,7 +37,7 @@ public: */ template explicit Statement(std::string_view query, Args&&... args) - : ManagedObject{cass_statement_new_n(query.data(), query.size(), sizeof...(args)), kDELETER} + : ManagedObject{cass_statement_new_n(query.data(), query.size(), sizeof...(args)), kDeleter} { // TODO: figure out how to set consistency level in config // NOTE: Keyspace doesn't support QUORUM at write level @@ -46,7 +46,7 @@ public: bind(std::forward(args)...); } - /* implicit */ Statement(CassStatement* ptr) : ManagedObject{ptr, kDELETER} + /* implicit */ Statement(CassStatement* ptr) : ManagedObject{ptr, kDeleter} { // cass_statement_set_consistency(*this, CASS_CONSISTENCY_LOCAL_QUORUM); cass_statement_set_is_idempotent(*this, cass_true); @@ -93,18 +93,17 @@ public: using DecayedType = std::decay_t; using UCharVectorType = std::vector; using UintTupleType = std::tuple; - using UintByteTupleType = std::tuple; - using ByteVectorType = std::vector; + using UintByteTupleType = std::tuple; + using ByteVectorType = std::vector; if constexpr ( - std::is_same_v || - std::is_same_v + std::is_same_v || std::is_same_v ) { auto const rc = bindBytes(value.data(), value.size()); - throwErrorIfNeeded(rc, "Bind ripple::base_uint"); - } else if constexpr (std::is_same_v) { + throwErrorIfNeeded(rc, "Bind xrpl::base_uint"); + } else if constexpr (std::is_same_v) { auto const rc = bindBytes(value.data(), value.size()); - throwErrorIfNeeded(rc, "Bind ripple::AccountID"); + throwErrorIfNeeded(rc, "Bind xrpl::AccountID"); } else if constexpr (std::is_same_v) { auto const rc = bindBytes(value.data(), value.size()); throwErrorIfNeeded(rc, "Bind vector"); @@ -122,7 +121,7 @@ public: std::is_same_v ) { auto const rc = cass_statement_bind_tuple(*this, idx, Tuple{std::forward(value)}); - throwErrorIfNeeded(rc, "Bind tuple or "); + throwErrorIfNeeded(rc, "Bind tuple or "); } else if constexpr (std::is_same_v) { auto const rc = cass_statement_bind_collection(*this, idx, Collection{std::forward(value)}); @@ -157,10 +156,10 @@ public: * This is used to produce Statement objects that can be executed. */ class PreparedStatement : public ManagedObject { - static constexpr auto kDELETER = [](CassPrepared const* ptr) { cass_prepared_free(ptr); }; + static constexpr auto kDeleter = [](CassPrepared const* ptr) { cass_prepared_free(ptr); }; public: - /* implicit */ PreparedStatement(CassPrepared const* ptr) : ManagedObject{ptr, kDELETER} + /* implicit */ PreparedStatement(CassPrepared const* ptr) : ManagedObject{ptr, kDeleter} { } diff --git a/src/data/cassandra/impl/Tuple.cpp b/src/data/cassandra/impl/Tuple.cpp index b4caa94a0..12cea9ae2 100644 --- a/src/data/cassandra/impl/Tuple.cpp +++ b/src/data/cassandra/impl/Tuple.cpp @@ -5,18 +5,18 @@ #include namespace { -constexpr auto kTUPLE_DELETER = [](CassTuple* ptr) { cass_tuple_free(ptr); }; -constexpr auto kTUPLE_ITERATOR_DELETER = [](CassIterator* ptr) { cass_iterator_free(ptr); }; +constexpr auto kTupleDeleter = [](CassTuple* ptr) { cass_tuple_free(ptr); }; +constexpr auto kTupleIteratorDeleter = [](CassIterator* ptr) { cass_iterator_free(ptr); }; } // namespace namespace data::cassandra::impl { -/* implicit */ Tuple::Tuple(CassTuple* ptr) : ManagedObject{ptr, kTUPLE_DELETER} +/* implicit */ Tuple::Tuple(CassTuple* ptr) : ManagedObject{ptr, kTupleDeleter} { } /* implicit */ TupleIterator::TupleIterator(CassIterator* ptr) - : ManagedObject{ptr, kTUPLE_ITERATOR_DELETER} + : ManagedObject{ptr, kTupleIteratorDeleter} { } diff --git a/src/data/cassandra/impl/Tuple.hpp b/src/data/cassandra/impl/Tuple.hpp index 8f04ababa..bee2399e2 100644 --- a/src/data/cassandra/impl/Tuple.hpp +++ b/src/data/cassandra/impl/Tuple.hpp @@ -18,14 +18,14 @@ namespace data::cassandra::impl { class Tuple : public ManagedObject { - static constexpr auto kDELETER = [](CassTuple* ptr) { cass_tuple_free(ptr); }; + static constexpr auto kDeleter = [](CassTuple* ptr) { cass_tuple_free(ptr); }; public: /* implicit */ Tuple(CassTuple* ptr); template explicit Tuple(std::tuple&& value) - : ManagedObject{cass_tuple_new(std::tuple_size>{}), kDELETER} + : ManagedObject{cass_tuple_new(std::tuple_size>{}), kDeleter} { std::apply(std::bind_front(&Tuple::bind, this), std::move(value)); } @@ -62,14 +62,14 @@ public: else if constexpr (std::is_convertible_v) { auto const rc = cass_tuple_set_int64(*this, idx, std::forward(value)); throwErrorIfNeeded(rc, "Bind int64"); - } else if constexpr (std::is_same_v) { + } else if constexpr (std::is_same_v) { auto const rc = cass_tuple_set_bytes( *this, idx, static_cast(static_cast(value.data())), value.size() ); - throwErrorIfNeeded(rc, "Bind ripple::uint256"); + throwErrorIfNeeded(rc, "Bind xrpl::uint256"); } else { // type not supported for binding static_assert(util::Unsupported); diff --git a/src/data/impl/InputFile.cpp b/src/data/impl/InputFile.cpp index a3e9905a8..bb6b28760 100644 --- a/src/data/impl/InputFile.cpp +++ b/src/data/impl/InputFile.cpp @@ -29,7 +29,7 @@ InputFile::readRaw(char* data, size_t size) return not file_.fail(); } -ripple::uint256 +xrpl::uint256 InputFile::hash() const { auto sum = shasum_; diff --git a/src/data/impl/InputFile.hpp b/src/data/impl/InputFile.hpp index d35e3d093..d4b9e6ec4 100644 --- a/src/data/impl/InputFile.hpp +++ b/src/data/impl/InputFile.hpp @@ -32,7 +32,7 @@ public: bool readRaw(char* data, size_t size); - ripple::uint256 + xrpl::uint256 hash() const; }; } // namespace data::impl diff --git a/src/data/impl/LedgerCacheFile.cpp b/src/data/impl/LedgerCacheFile.cpp index 3abfe045a..a44c1b83d 100644 --- a/src/data/impl/LedgerCacheFile.cpp +++ b/src/data/impl/LedgerCacheFile.cpp @@ -17,17 +17,17 @@ namespace data::impl { -using Hash = ripple::uint256; +using Hash = xrpl::uint256; using Separator = std::array; -static constexpr Separator kSEPARATOR = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; +static constexpr Separator kSeparator = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; namespace { -std::expected, std::string> +std::expected, std::string> readCacheEntry(InputFile& file, size_t i) { - ripple::uint256 key; - if (not file.readRaw(reinterpret_cast(key.data()), ripple::base_uint<256>::bytes)) { + xrpl::uint256 key; + if (not file.readRaw(reinterpret_cast(key.data()), xrpl::BaseUInt<256>::kBytes)) { return std::unexpected(fmt::format("Failed to read key at index {}", i)); } @@ -78,25 +78,25 @@ LedgerCacheFile::write(DataView dataView) .deletedSize = dataView.deleted.size() }; file.write(header); - file.write(kSEPARATOR); + file.write(kSeparator); for (auto const& [k, v] : dataView.map) { - file.write(k.data(), decltype(k)::bytes); + file.write(k.data(), decltype(k)::kBytes); file.write(v.seq); file.write(v.blob.size()); file.writeRaw(reinterpret_cast(v.blob.data()), v.blob.size()); } - file.write(kSEPARATOR); + file.write(kSeparator); for (auto const& [k, v] : dataView.deleted) { - file.write(k.data(), decltype(k)::bytes); + file.write(k.data(), decltype(k)::kBytes); file.write(v.seq); file.write(v.blob.size()); file.writeRaw(reinterpret_cast(v.blob.data()), v.blob.size()); } - file.write(kSEPARATOR); + file.write(kSeparator); auto const hash = file.hash(); - file.write(hash.data(), decltype(hash)::bytes); + file.write(hash.data(), decltype(hash)::kBytes); // flush internal buffer explicitly before renaming if (auto const expectedSuccess = file.close(); not expectedSuccess.has_value()) { @@ -129,9 +129,9 @@ LedgerCacheFile::read(uint32_t minLatestSequence) if (not file.read(header)) { return std::unexpected{"Error reading cache header"}; } - if (header.version != kVERSION) { + if (header.version != kVersion) { return std::unexpected{fmt::format( - "Cache has wrong version: expected {} found {}", kVERSION, header.version + "Cache has wrong version: expected {} found {}", kVersion, header.version )}; } if (header.latestSeq < minLatestSequence) { @@ -185,9 +185,9 @@ LedgerCacheFile::read(uint32_t minLatestSequence) } auto const dataHash = file.hash(); - ripple::uint256 hashFromFile{}; + xrpl::uint256 hashFromFile{}; if (not file.readRaw( - reinterpret_cast(hashFromFile.data()), decltype(hashFromFile)::bytes + reinterpret_cast(hashFromFile.data()), decltype(hashFromFile)::kBytes )) { return std::unexpected{"Error reading hash"}; } diff --git a/src/data/impl/LedgerCacheFile.hpp b/src/data/impl/LedgerCacheFile.hpp index 2b1652aee..45b0ae669 100644 --- a/src/data/impl/LedgerCacheFile.hpp +++ b/src/data/impl/LedgerCacheFile.hpp @@ -17,14 +17,14 @@ namespace data::impl { class LedgerCacheFile { public: struct Header { - uint32_t version = kVERSION; + uint32_t version = kVersion; uint32_t latestSeq{}; uint64_t mapSize{}; uint64_t deletedSize{}; }; private: - static constexpr uint32_t kVERSION = 1; + static constexpr uint32_t kVersion = 1; std::string path_; diff --git a/src/data/impl/OutputFile.cpp b/src/data/impl/OutputFile.cpp index 2ae06911e..9ab50b1f3 100644 --- a/src/data/impl/OutputFile.cpp +++ b/src/data/impl/OutputFile.cpp @@ -34,7 +34,7 @@ OutputFile::writeToFile(char const* data, size_t size) shasum_.update(data, size); } -ripple::uint256 +xrpl::uint256 OutputFile::hash() const { auto sum = shasum_; diff --git a/src/data/impl/OutputFile.hpp b/src/data/impl/OutputFile.hpp index 25d4dd130..99ad8f3bb 100644 --- a/src/data/impl/OutputFile.hpp +++ b/src/data/impl/OutputFile.hpp @@ -39,7 +39,7 @@ public: void writeRaw(char const* data, size_t size); - ripple::uint256 + xrpl::uint256 hash() const; std::expected diff --git a/src/etl/CacheLoaderSettings.hpp b/src/etl/CacheLoaderSettings.hpp index 224d142a1..2207a0ae2 100644 --- a/src/etl/CacheLoaderSettings.hpp +++ b/src/etl/CacheLoaderSettings.hpp @@ -13,43 +13,52 @@ namespace etl { * @brief Settings for the cache loader */ struct CacheLoaderSettings { - /** @brief Ways to load the cache */ + /** + * @brief Ways to load the cache + */ enum class LoadStyle { ASYNC, SYNC, NONE }; - /** @brief Settings for cache file operations */ + /** + * @brief Settings for cache file operations + */ struct CacheFileSettings { std::string - path; /**< path to the file to load cache from on start and save cache to on shutdown */ - uint32_t maxAge = 5000; /**< max difference between latest sequence in cache file and DB */ + path; ///< path to the file to load cache from on start and save cache to on shutdown + uint32_t maxAge = 5000; ///< max difference between latest sequence in cache file and DB auto operator<=>(CacheFileSettings const&) const = default; }; - size_t numCacheDiffs = 32; /**< number of diffs to use to generate cursors */ - size_t numCacheMarkers = 48; /**< number of markers to use at one time to traverse the ledger */ - size_t cachePageFetchSize = - 512; /**< number of ledger objects to fetch concurrently per marker */ - size_t numThreads = 2; /**< number of threads to use for loading cache */ - size_t numCacheCursorsFromDiff = 0; /**< number of cursors to fetch from diff */ - size_t numCacheCursorsFromAccount = 0; /**< number of cursors to fetch from account_tx */ + size_t numCacheDiffs = 32; ///< number of diffs to use to generate cursors + size_t numCacheMarkers = 48; ///< number of markers to use at one time to traverse the ledger + size_t cachePageFetchSize = 512; ///< number of ledger objects to fetch concurrently per marker + size_t numThreads = 2; ///< number of threads to use for loading cache + size_t numCacheCursorsFromDiff = 0; ///< number of cursors to fetch from diff + size_t numCacheCursorsFromAccount = 0; ///< number of cursors to fetch from account_tx - LoadStyle loadStyle = LoadStyle::ASYNC; /**< how to load the cache */ + LoadStyle loadStyle = LoadStyle::ASYNC; ///< how to load the cache std::optional - cacheFileSettings; /**< optional settings for cache file operations */ + cacheFileSettings; ///< optional settings for cache file operations auto operator<=>(CacheLoaderSettings const&) const = default; - /** @returns True if the load style is SYNC; false otherwise */ + /** + * @return True if the load style is SYNC; false otherwise + */ [[nodiscard]] bool isSync() const; - /** @returns True if the load style is ASYNC; false otherwise */ + /** + * @return True if the load style is ASYNC; false otherwise + */ [[nodiscard]] bool isAsync() const; - /** @returns True if the cache is disabled; false otherwise */ + /** + * @return True if the cache is disabled; false otherwise + */ [[nodiscard]] bool isDisabled() const; }; @@ -58,7 +67,7 @@ struct CacheLoaderSettings { * @brief Create a CacheLoaderSettings object from a Config object * * @param config The configuration object - * @returns The CacheLoaderSettings object + * @return The CacheLoaderSettings object */ [[nodiscard]] CacheLoaderSettings makeCacheLoaderSettings(util::config::ClioConfigDefinition const& config); diff --git a/src/etl/ETLHelpers.cpp b/src/etl/ETLHelpers.cpp index 43781b673..d1743c7c4 100644 --- a/src/etl/ETLHelpers.cpp +++ b/src/etl/ETLHelpers.cpp @@ -8,16 +8,16 @@ #include namespace etl { -std::vector +std::vector getMarkers(size_t numMarkers) { ASSERT(numMarkers <= 256, "Number of markers must be <= 256. Got: {}", numMarkers); unsigned char const incr = 256 / numMarkers; - std::vector markers; + std::vector markers; markers.reserve(numMarkers); - ripple::uint256 base{0}; + xrpl::uint256 base{0}; for (size_t i = 0; i < numMarkers; ++i) { markers.push_back(base); base.data()[0] += incr; diff --git a/src/etl/ETLHelpers.hpp b/src/etl/ETLHelpers.hpp index a70d70266..0b660638c 100644 --- a/src/etl/ETLHelpers.hpp +++ b/src/etl/ETLHelpers.hpp @@ -130,7 +130,7 @@ public: * @param numMarkers Total markers to partition for * @return The markers */ -std::vector +std::vector getMarkers(size_t numMarkers); } // namespace etl diff --git a/src/etl/ETLService.cpp b/src/etl/ETLService.cpp index 721c4fe33..af1c63d85 100644 --- a/src/etl/ETLService.cpp +++ b/src/etl/ETLService.cpp @@ -72,13 +72,13 @@ ETLService::makeETLService( std::shared_ptr ret; auto fetcher = std::make_shared(backend, balancer); - auto extractor = std::make_shared(fetcher); + auto amendmentBlockHandler = std::make_shared(ctx, *state); + auto extractor = std::make_shared(fetcher, amendmentBlockHandler); auto publisher = std::make_shared(ctx, backend, subscriptions, *state); auto cacheLoader = std::make_shared>( config, backend, backend->cache(), std::move(cacheLoadingState) ); auto cacheUpdater = std::make_shared(backend->cache()); - auto amendmentBlockHandler = std::make_shared(ctx, *state); auto monitorProvider = std::make_shared(); backend->setCorruptionDetector(CorruptionDetector{*state, backend->cache()}); @@ -298,7 +298,7 @@ ETLService::loadInitialLedgerIfNeeded() auto [ledger, timeDiff] = ::util::timed>([this, seq]() { return extractor_->extractLedgerOnly(seq).and_then( - [this, seq](auto&& data) -> std::optional { + [this, seq](auto&& data) -> std::optional { // TODO: loadInitialLedger in balancer should be called fetchEdgeKeys or // similar auto res = balancer_->loadInitialLedger(seq, *initialLoadObserver_); diff --git a/src/etl/ETLService.hpp b/src/etl/ETLService.hpp index 0303943bc..125922035 100644 --- a/src/etl/ETLService.hpp +++ b/src/etl/ETLService.hpp @@ -179,19 +179,19 @@ public: void stop() override; - boost::json::object + [[nodiscard]] boost::json::object getInfo() const override; - bool + [[nodiscard]] bool isAmendmentBlocked() const override; - bool + [[nodiscard]] bool isCorruptionDetected() const override; - std::optional + [[nodiscard]] std::optional getETLState() const override; - std::uint32_t + [[nodiscard]] std::uint32_t lastCloseAgeSeconds() const override; private: diff --git a/src/etl/LoadBalancer.cpp b/src/etl/LoadBalancer.cpp index 50f8fb14e..9bb14b777 100644 --- a/src/etl/LoadBalancer.cpp +++ b/src/etl/LoadBalancer.cpp @@ -277,7 +277,7 @@ LoadBalancer::forwardToRippled( auto const cmd = boost::json::value_to(request.at("command")); if (shouldUseCache(isAdmin)) { // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - if (auto cachedResponse = forwardingCache_->get(cmd); cachedResponse) { + if (auto cachedResponse = forwardingCache_->get(cmd, request); cachedResponse) { forwardingCounters_.cacheHit.get() += 1; return *std::move(cachedResponse); } @@ -289,7 +289,7 @@ LoadBalancer::forwardToRippled( auto numAttempts = 0u; - auto xUserValue = isAdmin ? kADMIN_FORWARDING_X_USER_VALUE : kUSER_FORWARDING_X_USER_VALUE; + auto xUserValue = isAdmin ? kAdminForwardingXUserValue : kUserForwardingXUserValue; std::optional response; rpc::ClioError error = rpc::ClioError::EtlConnectionError; @@ -311,8 +311,10 @@ LoadBalancer::forwardToRippled( } if (response) { - if (shouldUseCache(isAdmin) and not response->contains("error")) - forwardingCache_->put(cmd, *response); // NOLINT(bugprone-unchecked-optional-access) + if (shouldUseCache(isAdmin) and not response->contains("error")) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + forwardingCache_->put(cmd, request, *response); + } return *std::move(response); } diff --git a/src/etl/LoadBalancer.hpp b/src/etl/LoadBalancer.hpp index 30896f68e..8fb9a3681 100644 --- a/src/etl/LoadBalancer.hpp +++ b/src/etl/LoadBalancer.hpp @@ -63,7 +63,7 @@ public: using OptionalGetLedgerResponseType = std::optional; private: - static constexpr std::uint32_t kDEFAULT_DOWNLOAD_RANGES = 16; + static constexpr std::uint32_t kDefaultDownloadRanges = 16; util::Logger log_{"ETL"}; // Forwarding cache must be destroyed after sources because sources have a callback to @@ -75,7 +75,7 @@ private: std::vector sources_; std::optional etlState_; - std::uint32_t downloadRanges_ = kDEFAULT_DOWNLOAD_RANGES; /*< The number of markers to use when + std::uint32_t downloadRanges_ = kDefaultDownloadRanges; /*< The number of markers to use when downloading initial ledger */ struct ForwardingCounters { @@ -95,12 +95,12 @@ public: /** * @brief Value for the X-User header when forwarding admin requests */ - static constexpr std::string_view kADMIN_FORWARDING_X_USER_VALUE = "clio_admin"; + static constexpr std::string_view kAdminForwardingXUserValue = "clio_admin"; /** * @brief Value for the X-User header when forwarding user requests */ - static constexpr std::string_view kUSER_FORWARDING_X_USER_VALUE = "clio_user"; + static constexpr std::string_view kUserForwardingXUserValue = "clio_user"; /** * @brief Create an instance of the load balancer. diff --git a/src/etl/LoaderInterface.hpp b/src/etl/LoaderInterface.hpp index e10e2d1c3..bcbb047ea 100644 --- a/src/etl/LoaderInterface.hpp +++ b/src/etl/LoaderInterface.hpp @@ -36,7 +36,7 @@ struct LoaderInterface { * @param data The data to load * @return Optional ledger header */ - [[nodiscard]] virtual std::optional + [[nodiscard]] virtual std::optional loadInitialLedger(model::LedgerData const& data) = 0; }; diff --git a/src/etl/MPTHelpers.cpp b/src/etl/MPTHelpers.cpp index b56daf457..975dc6b7f 100644 --- a/src/etl/MPTHelpers.cpp +++ b/src/etl/MPTHelpers.cpp @@ -1,55 +1,158 @@ #include "data/DBHelpers.hpp" #include "util/Assert.hpp" -#include -#include -#include +#include #include +#include #include +#include #include +#include +#include +#include #include #include +#include #include #include -#include +#include #include #include +#include namespace etl { -/** - * @brief Get the MPToken created from a transaction - * - * @param txMeta Transaction metadata - * @return MPT and holder account pair - */ -std::optional -getMPTokenAuthorize(ripple::TxMeta const& txMeta) +std::vector +getMPTHolderFromTx(xrpl::TxMeta const& txMeta, xrpl::STTx const&) { - for (ripple::STObject const& node : txMeta.getNodes()) { - if (node.getFieldU16(ripple::sfLedgerEntryType) != ripple::ltMPTOKEN) - continue; - - if (node.getFName() == ripple::sfCreatedNode) { - auto const& newMPT = node.peekAtField(ripple::sfNewFields).downcast(); - return MPTHolderData{ - .mptID = newMPT[ripple::sfMPTokenIssuanceID], - .holder = newMPT.getAccountID(ripple::sfAccount) - }; - } - } - return {}; -} - -std::optional -getMPTHolderFromTx(ripple::TxMeta const& txMeta, ripple::STTx const& sttx) -{ - if (txMeta.getResultTER() != ripple::tesSUCCESS || - sttx.getTxnType() != ripple::TxType::ttMPTOKEN_AUTHORIZE) + if (txMeta.getResultTER() != xrpl::tesSUCCESS) return {}; - return getMPTokenAuthorize(txMeta); + std::vector holders; + + for (xrpl::STObject const& node : txMeta.getNodes()) { + if (node.getFieldU16(xrpl::sfLedgerEntryType) != xrpl::ltMPTOKEN) + continue; + + if (node.getFName() == xrpl::sfCreatedNode) { + auto const& newMPT = node.peekAtField(xrpl::sfNewFields).downcast(); + holders.push_back( + MPTHolderData{ + .mptID = newMPT[xrpl::sfMPTokenIssuanceID], + .holder = newMPT.getAccountID(xrpl::sfAccount) + } + ); + } + } + + return holders; +} + +namespace { + +using MPTokenIssuanceIDs = boost::container::flat_set; + +/** + * @brief Derive the MPTokenIssuanceID from an affected node in transaction metadata. + * + * @param node An entry of the metadata's AffectedNodes array. + * @return The 192-bit issuance ID if the node is an MPTokenIssuance or MPToken object. + */ +std::optional +getMPTokenIssuanceIDFromNode(xrpl::STObject const& node) +{ + auto const entryType = node.getFieldU16(xrpl::sfLedgerEntryType); + if (entryType != xrpl::ltMPTOKEN && entryType != xrpl::ltMPTOKEN_ISSUANCE) + return std::nullopt; + + auto const& fieldsName = + node.getFName() == xrpl::sfCreatedNode ? xrpl::sfNewFields : xrpl::sfFinalFields; + if (not node.isFieldPresent(fieldsName)) + return std::nullopt; + + auto const& fields = node.peekAtField(fieldsName).downcast(); + + if (entryType == xrpl::ltMPTOKEN) { + if (not fields.isFieldPresent(xrpl::sfMPTokenIssuanceID)) + return std::nullopt; + + return fields[xrpl::sfMPTokenIssuanceID]; + } + + // MPTokenIssuance objects carry no sfMPTokenIssuanceID, and the node's ledger key is a + // one-way hash that does not embed the ID, so reconstruct it from sfSequence and sfIssuer + if (not fields.isFieldPresent(xrpl::sfSequence) || not fields.isFieldPresent(xrpl::sfIssuer)) + return std::nullopt; + + return xrpl::makeMptID( + fields.getFieldU32(xrpl::sfSequence), fields.getAccountID(xrpl::sfIssuer) + ); +} + +void +addMPTokenIssuanceIDsFromTx(MPTokenIssuanceIDs& issuanceIDs, xrpl::STTx const& sttx) +{ + if (sttx.isFieldPresent(xrpl::sfMPTokenIssuanceID)) + issuanceIDs.insert(sttx.getFieldH192(xrpl::sfMPTokenIssuanceID)); + + for (xrpl::STBase const& field : sttx) { + switch (field.getSType()) { + case xrpl::STI_AMOUNT: { + auto const& amount = field.downcast(); + if (amount.holds()) + issuanceIDs.insert(amount.get().getMptID()); + break; + } + case xrpl::STI_ISSUE: { + auto const& issue = field.downcast(); + if (issue.holds()) + issuanceIDs.insert(issue.value().get().getMptID()); + break; + } + default: + break; + } + } +} + +} // namespace + +std::vector +getMPTokenIssuanceTxsFromTx(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx) +{ + // Collect each distinct issuance only once per transaction; the same set of affected accounts + // is attached to every record produced below. + MPTokenIssuanceIDs issuanceIDs; + + if (txMeta.getResultTER() == xrpl::tesSUCCESS) { + for (auto const& node : txMeta.getNodes()) { + if (auto const issuanceID = getMPTokenIssuanceIDFromNode(node); issuanceID.has_value()) + issuanceIDs.insert(*issuanceID); + } + } + + addMPTokenIssuanceIDsFromTx(issuanceIDs, sttx); + + if (issuanceIDs.empty()) + return {}; + + auto const accounts = txMeta.getAffectedAccounts(); + + std::vector result; + result.reserve(issuanceIDs.size()); + for (auto const& issuanceID : issuanceIDs) { + result.push_back( + MPTokenIssuanceTransactionsData{ + .mptIssuanceID = issuanceID, + .accounts = accounts, + .ledgerSequence = txMeta.getLgrSeq(), + .transactionIndex = txMeta.getIndex(), + .txHash = sttx.getTransactionID() + } + ); + } + return result; } std::optional @@ -57,19 +160,19 @@ getMPTHolderFromObj(std::string const& key, std::string const& blob) { // https://github.com/XRPLF/XRPL-Standards/tree/master/XLS-0033-multi-purpose-tokens#2121-mptoken-ledger-identifier ASSERT( - key.size() == ripple::uint256::size(), + key.size() == xrpl::uint256::size(), "The size of the key is expected to fit uint256 exactly" ); - ripple::STLedgerEntry const sle = ripple::STLedgerEntry( - ripple::SerialIter{blob.data(), blob.size()}, ripple::uint256::fromVoid(key.data()) + xrpl::STLedgerEntry const sle = xrpl::STLedgerEntry( + xrpl::SerialIter{blob.data(), blob.size()}, xrpl::uint256::fromVoid(key.data()) ); - if (sle.getFieldU16(ripple::sfLedgerEntryType) != ripple::ltMPTOKEN) - return {}; + if (sle.getFieldU16(xrpl::sfLedgerEntryType) != xrpl::ltMPTOKEN) + return std::nullopt; - auto const mptIssuanceID = sle[ripple::sfMPTokenIssuanceID]; - auto const holder = sle.getAccountID(ripple::sfAccount); + auto const mptIssuanceID = sle[xrpl::sfMPTokenIssuanceID]; + auto const holder = sle.getAccountID(xrpl::sfAccount); return MPTHolderData{.mptID = mptIssuanceID, .holder = holder}; } diff --git a/src/etl/MPTHelpers.hpp b/src/etl/MPTHelpers.hpp index dc9e30a0a..cdc3405ad 100644 --- a/src/etl/MPTHelpers.hpp +++ b/src/etl/MPTHelpers.hpp @@ -3,8 +3,12 @@ #include "data/DBHelpers.hpp" -#include -#include +#include +#include + +#include +#include +#include namespace etl { @@ -13,10 +17,11 @@ namespace etl { * * @param txMeta Transaction metadata * @param sttx The transaction - * @return The MPTIssuanceID and holder pair as a optional + * @return The MPTIssuanceID and holder pairs created by the transaction; empty if the transaction + * failed or created no MPToken. */ -std::optional -getMPTHolderFromTx(ripple::TxMeta const& txMeta, ripple::STTx const& sttx); +std::vector +getMPTHolderFromTx(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx); /** * @brief Pull MPT data from ledger object via loadInitialLedger. @@ -28,4 +33,22 @@ getMPTHolderFromTx(ripple::TxMeta const& txMeta, ripple::STTx const& sttx); std::optional getMPTHolderFromObj(std::string const& key, std::string const& blob); +/** + * @brief Pull MPT issuance transaction index data from a transaction. + * + * @note This scans the transaction's metadata for affected MPTokenIssuance/MPToken ledger objects + * and transaction fields for attached MPTokenIssuanceID/MPT issue references. It produces one + * record per distinct issuance, each carrying the full set of affected accounts. Transaction fields + * are scanned so failed transactions that carry an issuance reference are indexed even when + * metadata has no affected MPT objects. Used by live ETL and reused by the historical backfill + * migrator. + * + * @param txMeta Transaction metadata. + * @param sttx The transaction. + * @return One record per distinct MPT issuance referenced by metadata or transaction fields; empty + * if no MPT issuance reference is found. + */ +std::vector +getMPTokenIssuanceTxsFromTx(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx); + } // namespace etl diff --git a/src/etl/Models.hpp b/src/etl/Models.hpp index 401181ecf..6df7f5932 100644 --- a/src/etl/Models.hpp +++ b/src/etl/Models.hpp @@ -28,10 +28,10 @@ namespace etl::model { * incoming transactions by the Registry for its `onTransaction` and `onInitialTransaction` hooks. * It's a compilation error to list the same transaction type more than once. */ -template +template requires(util::hasNoDuplicates(Types...)) struct Spec { - static constexpr bool kSPEC_TAG = true; + static constexpr bool kSpecTag = true; /** * @brief Checks if the transaction type was requested. @@ -40,7 +40,7 @@ struct Spec { * @return true if the transaction was requested; false otherwise */ [[nodiscard]] static constexpr bool - wants(ripple::TxType type) noexcept + wants(xrpl::TxType type) noexcept { return ((Types == type) || ...); } @@ -54,13 +54,13 @@ struct Transaction { std::string metaRaw; // unpacked blob and meta - ripple::STTx sttx; - ripple::TxMeta meta; + xrpl::STTx sttx; + xrpl::TxMeta meta; // commonly used stuff - ripple::uint256 id; + xrpl::uint256 id; std::string key; // key is the above id as a string of 32 characters - ripple::TxType type; + xrpl::TxType type; /** * @brief Compares Transaction objects to each other without considering sttx and meta fields @@ -94,9 +94,9 @@ struct Object { Deleted = 3, }; - ripple::uint256 key; + xrpl::uint256 key; std::string keyRaw; - ripple::Blob data; + xrpl::Blob data; std::string dataRaw; std::string successor; std::string predecessor; @@ -127,7 +127,7 @@ struct LedgerData { std::optional> successors; std::optional> edgeKeys; - ripple::LedgerHeader header; + xrpl::LedgerHeader header; std::string rawHeader; uint32_t seq; @@ -140,8 +140,8 @@ struct LedgerData { operator==(LedgerData const& other) const { auto const serialized = [](auto const& hdr) { - ripple::Serializer ser; - ripple::addRaw(hdr, ser); + xrpl::Serializer ser; + xrpl::addRaw(hdr, ser); return ser.getString(); }; diff --git a/src/etl/MonitorInterface.hpp b/src/etl/MonitorInterface.hpp index 953dfa8c0..c095abecb 100644 --- a/src/etl/MonitorInterface.hpp +++ b/src/etl/MonitorInterface.hpp @@ -16,7 +16,7 @@ namespace etl { */ class MonitorInterface { public: - static constexpr auto kDEFAULT_REPEAT_INTERVAL = std::chrono::seconds{1}; + static constexpr auto kDefaultRepeatInterval = std::chrono::seconds{1}; using NewSequenceSignalType = boost::signals2::signal; using DbStalledSignalType = boost::signals2::signal; @@ -61,7 +61,7 @@ public: * @param repeatInterval The interval between attempts to check the database for new ledgers */ virtual void - run(std::chrono::steady_clock::duration repeatInterval = kDEFAULT_REPEAT_INTERVAL) = 0; + run(std::chrono::steady_clock::duration repeatInterval = kDefaultRepeatInterval) = 0; /** * @brief Stops the monitor service diff --git a/src/etl/MonitorProviderInterface.hpp b/src/etl/MonitorProviderInterface.hpp index 3f6c029c8..7a5050db0 100644 --- a/src/etl/MonitorProviderInterface.hpp +++ b/src/etl/MonitorProviderInterface.hpp @@ -18,7 +18,7 @@ struct MonitorProviderInterface { /** * @brief The time Monitor should wait before reporting absence of updates to the database */ - static constexpr auto kDEFAULT_DB_STALLED_REPORT_DELAY = std::chrono::seconds{10}; + static constexpr auto kDefaultDbStalledReportDelay = std::chrono::seconds{10}; virtual ~MonitorProviderInterface() = default; @@ -38,7 +38,7 @@ struct MonitorProviderInterface { std::shared_ptr backend, std::shared_ptr validatedLedgers, uint32_t startSequence, - std::chrono::steady_clock::duration dbStalledReportDelay = kDEFAULT_DB_STALLED_REPORT_DELAY + std::chrono::steady_clock::duration dbStalledReportDelay = kDefaultDbStalledReportDelay ) = 0; }; diff --git a/src/etl/NFTHelpers.cpp b/src/etl/NFTHelpers.cpp index cd14ef4a6..6b885efe5 100644 --- a/src/etl/NFTHelpers.cpp +++ b/src/etl/NFTHelpers.cpp @@ -30,50 +30,50 @@ namespace etl { std::pair, std::optional> -getNftokenModifyData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx) +getNftokenModifyData(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx) { - auto const tokenID = sttx.getFieldH256(ripple::sfNFTokenID); + auto const tokenID = sttx.getFieldH256(xrpl::sfNFTokenID); // note: sfURI is optional, if it is absent, we will update the uri as empty string return { {NFTTransactionsData( - sttx.getFieldH256(ripple::sfNFTokenID), txMeta, sttx.getTransactionID() + sttx.getFieldH256(xrpl::sfNFTokenID), txMeta, sttx.getTransactionID() )}, - NFTsData(tokenID, txMeta, sttx.getFieldVL(ripple::sfURI)) + NFTsData(tokenID, txMeta, sttx.getFieldVL(xrpl::sfURI)) }; } std::pair, std::optional> -getNFTokenMintData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx) +getNFTokenMintData(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx) { // To find the minted token ID, we put all tokenIDs referenced in the // metadata from prior to the tx application into one vector, then all // tokenIDs referenced in the metadata from after the tx application into // another, then find the one tokenID that was added by this tx // application. - std::vector prevIDs; - std::vector finalIDs; + std::vector prevIDs; + std::vector finalIDs; // The owner is not necessarily the issuer, if using authorized minter // flow. Determine owner from the ledger object ID of the NFTokenPages // that were changed. - std::optional owner; + std::optional owner; - for (ripple::STObject const& node : txMeta.getNodes()) { - if (node.getFieldU16(ripple::sfLedgerEntryType) != ripple::ltNFTOKEN_PAGE) + for (xrpl::STObject const& node : txMeta.getNodes()) { + if (node.getFieldU16(xrpl::sfLedgerEntryType) != xrpl::ltNFTOKEN_PAGE) continue; if (!owner) - owner = ripple::AccountID::fromVoid(node.getFieldH256(ripple::sfLedgerIndex).data()); + owner = xrpl::AccountID::fromVoid(node.getFieldH256(xrpl::sfLedgerIndex).data()); - if (node.getFName() == ripple::sfCreatedNode) { - ripple::STArray const& toAddNFTs = node.peekAtField(ripple::sfNewFields) - .downcast() - .getFieldArray(ripple::sfNFTokens); + if (node.getFName() == xrpl::sfCreatedNode) { + xrpl::STArray const& toAddNFTs = node.peekAtField(xrpl::sfNewFields) + .downcast() + .getFieldArray(xrpl::sfNFTokens); std::ranges::transform( toAddNFTs, std::back_inserter(finalIDs), - [](ripple::STObject const& nft) { return nft.getFieldH256(ripple::sfNFTokenID); } + [](xrpl::STObject const& nft) { return nft.getFieldH256(xrpl::sfNFTokenID); } ); } // Else it's modified, as there should never be a deleted NFToken page @@ -88,27 +88,27 @@ getNFTokenMintData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx) // 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. - ripple::STObject const& previousFields = - node.peekAtField(ripple::sfPreviousFields).downcast(); - if (!previousFields.isFieldPresent(ripple::sfNFTokens)) + xrpl::STObject const& previousFields = + node.peekAtField(xrpl::sfPreviousFields).downcast(); + if (!previousFields.isFieldPresent(xrpl::sfNFTokens)) continue; - ripple::STArray const& toAddNFTs = previousFields.getFieldArray(ripple::sfNFTokens); + xrpl::STArray const& toAddNFTs = previousFields.getFieldArray(xrpl::sfNFTokens); std::ranges::transform( toAddNFTs, std::back_inserter(prevIDs), - [](ripple::STObject const& nft) { return nft.getFieldH256(ripple::sfNFTokenID); } + [](xrpl::STObject const& nft) { return nft.getFieldH256(xrpl::sfNFTokenID); } ); - ripple::STArray const& toAddFinalNFTs = node.peekAtField(ripple::sfFinalFields) - .downcast() - .getFieldArray(ripple::sfNFTokens); + xrpl::STArray const& toAddFinalNFTs = node.peekAtField(xrpl::sfFinalFields) + .downcast() + .getFieldArray(xrpl::sfNFTokens); std::ranges::transform( toAddFinalNFTs, std::back_inserter(finalIDs), - [](ripple::STObject const& nft) { return nft.getFieldH256(ripple::sfNFTokenID); } + [](xrpl::STObject const& nft) { return nft.getFieldH256(xrpl::sfNFTokenID); } ); } } @@ -130,14 +130,14 @@ getNFTokenMintData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx) return { {NFTTransactionsData(*finalMismatch, txMeta, sttx.getTransactionID())}, - NFTsData(*finalMismatch, *owner, sttx.getFieldVL(ripple::sfURI), txMeta) + NFTsData(*finalMismatch, *owner, sttx.getFieldVL(xrpl::sfURI), txMeta) }; } std::pair, std::optional> -getNFTokenBurnData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx) +getNFTokenBurnData(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx) { - ripple::uint256 const tokenID = sttx.getFieldH256(ripple::sfNFTokenID); + xrpl::uint256 const tokenID = sttx.getFieldH256(xrpl::sfNFTokenID); std::vector const txs = { NFTTransactionsData(tokenID, txMeta, sttx.getTransactionID()) }; @@ -145,9 +145,9 @@ getNFTokenBurnData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx) // Determine who owned the token when it was burned by finding an // NFTokenPage that was deleted or modified that contains this // tokenID. - for (ripple::STObject const& node : txMeta.getNodes()) { - if (node.getFieldU16(ripple::sfLedgerEntryType) != ripple::ltNFTOKEN_PAGE || - node.getFName() == ripple::sfCreatedNode) + for (xrpl::STObject const& node : txMeta.getNodes()) { + if (node.getFieldU16(xrpl::sfLedgerEntryType) != xrpl::ltNFTOKEN_PAGE || + node.getFName() == xrpl::sfCreatedNode) continue; // NFT burn can result in an NFTokenPage being modified to no longer @@ -158,25 +158,25 @@ getNFTokenBurnData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx) // deleted. In this case, we need to look in the PreviousFields. // Otherwise, the page was not modified prior to deleting and we // need to look in the FinalFields. - std::optional prevNFTs; + std::optional prevNFTs; - if (node.isFieldPresent(ripple::sfPreviousFields)) { - ripple::STObject const& previousFields = - node.peekAtField(ripple::sfPreviousFields).downcast(); - if (previousFields.isFieldPresent(ripple::sfNFTokens)) - prevNFTs = previousFields.getFieldArray(ripple::sfNFTokens); - } else if (node.getFName() == ripple::sfDeletedNode) { - prevNFTs = node.peekAtField(ripple::sfFinalFields) - .downcast() - .getFieldArray(ripple::sfNFTokens); + if (node.isFieldPresent(xrpl::sfPreviousFields)) { + xrpl::STObject const& previousFields = + node.peekAtField(xrpl::sfPreviousFields).downcast(); + if (previousFields.isFieldPresent(xrpl::sfNFTokens)) + prevNFTs = previousFields.getFieldArray(xrpl::sfNFTokens); + } else if (node.getFName() == xrpl::sfDeletedNode) { + prevNFTs = node.peekAtField(xrpl::sfFinalFields) + .downcast() + .getFieldArray(xrpl::sfNFTokens); } if (!prevNFTs) continue; auto const nft = std::find_if( - prevNFTs->begin(), prevNFTs->end(), [&tokenID](ripple::STObject const& candidate) { - return candidate.getFieldH256(ripple::sfNFTokenID) == tokenID; + prevNFTs->begin(), prevNFTs->end(), [&tokenID](xrpl::STObject const& candidate) { + return candidate.getFieldH256(xrpl::sfNFTokenID) == tokenID; } ); if (nft != prevNFTs->end()) { @@ -184,7 +184,7 @@ getNFTokenBurnData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx) txs, NFTsData( tokenID, - ripple::AccountID::fromVoid(node.getFieldH256(ripple::sfLedgerIndex).data()), + xrpl::AccountID::fromVoid(node.getFieldH256(xrpl::sfLedgerIndex).data()), txMeta, true ) @@ -198,18 +198,18 @@ getNFTokenBurnData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx) } std::pair, std::optional> -getNFTokenAcceptOfferData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx) +getNFTokenAcceptOfferData(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx) { // If we have the buy offer from this tx, we can determine the owner // more easily by just looking at the owner of the accepted NFTokenOffer // object. - if (sttx.isFieldPresent(ripple::sfNFTokenBuyOffer)) { + if (sttx.isFieldPresent(xrpl::sfNFTokenBuyOffer)) { auto const affectedBuyOffer = std::find_if( txMeta.getNodes().begin(), txMeta.getNodes().end(), - [&sttx](ripple::STObject const& node) { - return node.getFieldH256(ripple::sfLedgerIndex) == - sttx.getFieldH256(ripple::sfNFTokenBuyOffer); + [&sttx](xrpl::STObject const& node) { + return node.getFieldH256(xrpl::sfLedgerIndex) == + sttx.getFieldH256(xrpl::sfNFTokenBuyOffer); } ); if (affectedBuyOffer == txMeta.getNodes().end()) { @@ -218,13 +218,13 @@ getNFTokenAcceptOfferData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx throw std::runtime_error(msg.str()); } - ripple::uint256 const tokenID = affectedBuyOffer->peekAtField(ripple::sfFinalFields) - .downcast() - .getFieldH256(ripple::sfNFTokenID); + xrpl::uint256 const tokenID = affectedBuyOffer->peekAtField(xrpl::sfFinalFields) + .downcast() + .getFieldH256(xrpl::sfNFTokenID); - ripple::AccountID const owner = affectedBuyOffer->peekAtField(ripple::sfFinalFields) - .downcast() - .getAccountID(ripple::sfOwner); + xrpl::AccountID const owner = affectedBuyOffer->peekAtField(xrpl::sfFinalFields) + .downcast() + .getAccountID(xrpl::sfOwner); return { {NFTTransactionsData(tokenID, txMeta, sttx.getTransactionID())}, NFTsData(tokenID, owner, txMeta, false) @@ -233,9 +233,9 @@ getNFTokenAcceptOfferData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx // Otherwise we have to infer the new owner from the affected nodes. auto const affectedSellOffer = std::find_if( - txMeta.getNodes().begin(), txMeta.getNodes().end(), [&sttx](ripple::STObject const& node) { - return node.getFieldH256(ripple::sfLedgerIndex) == - sttx.getFieldH256(ripple::sfNFTokenSellOffer); + txMeta.getNodes().begin(), txMeta.getNodes().end(), [&sttx](xrpl::STObject const& node) { + return node.getFieldH256(xrpl::sfLedgerIndex) == + sttx.getFieldH256(xrpl::sfNFTokenSellOffer); } ); if (affectedSellOffer == txMeta.getNodes().end()) { @@ -244,37 +244,37 @@ getNFTokenAcceptOfferData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx throw std::runtime_error(msg.str()); } - ripple::uint256 const tokenID = affectedSellOffer->peekAtField(ripple::sfFinalFields) - .downcast() - .getFieldH256(ripple::sfNFTokenID); + xrpl::uint256 const tokenID = affectedSellOffer->peekAtField(xrpl::sfFinalFields) + .downcast() + .getFieldH256(xrpl::sfNFTokenID); - ripple::AccountID const seller = affectedSellOffer->peekAtField(ripple::sfFinalFields) - .downcast() - .getAccountID(ripple::sfOwner); + xrpl::AccountID const seller = affectedSellOffer->peekAtField(xrpl::sfFinalFields) + .downcast() + .getAccountID(xrpl::sfOwner); - for (ripple::STObject const& node : txMeta.getNodes()) { - if (node.getFieldU16(ripple::sfLedgerEntryType) != ripple::ltNFTOKEN_PAGE || - node.getFName() == ripple::sfDeletedNode) + for (xrpl::STObject const& node : txMeta.getNodes()) { + if (node.getFieldU16(xrpl::sfLedgerEntryType) != xrpl::ltNFTOKEN_PAGE || + node.getFName() == xrpl::sfDeletedNode) continue; - ripple::AccountID const nodeOwner = - ripple::AccountID::fromVoid(node.getFieldH256(ripple::sfLedgerIndex).data()); + xrpl::AccountID const nodeOwner = + xrpl::AccountID::fromVoid(node.getFieldH256(xrpl::sfLedgerIndex).data()); if (nodeOwner == seller) continue; - ripple::STArray const& nfts = [&node] { - if (node.getFName() == ripple::sfCreatedNode) { - return node.peekAtField(ripple::sfNewFields) - .downcast() - .getFieldArray(ripple::sfNFTokens); + xrpl::STArray const& nfts = [&node] { + if (node.getFName() == xrpl::sfCreatedNode) { + return node.peekAtField(xrpl::sfNewFields) + .downcast() + .getFieldArray(xrpl::sfNFTokens); } - return node.peekAtField(ripple::sfFinalFields) - .downcast() - .getFieldArray(ripple::sfNFTokens); + return node.peekAtField(xrpl::sfFinalFields) + .downcast() + .getFieldArray(xrpl::sfNFTokens); }(); - auto const nft = std::ranges::find_if(nfts, [&tokenID](ripple::STObject const& candidate) { - return candidate.getFieldH256(ripple::sfNFTokenID) == tokenID; + auto const nft = std::ranges::find_if(nfts, [&tokenID](xrpl::STObject const& candidate) { + return candidate.getFieldH256(xrpl::sfNFTokenID) == tokenID; }); if (nft != nfts.end()) { return { @@ -294,16 +294,16 @@ getNFTokenAcceptOfferData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx // transaction using this feature. This transaction also never returns an // NFTsData because it does not change the state of an NFT itself. std::pair, std::optional> -getNFTokenCancelOfferData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx) +getNFTokenCancelOfferData(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx) { std::vector txs; - for (ripple::STObject const& node : txMeta.getNodes()) { - if (node.getFieldU16(ripple::sfLedgerEntryType) != ripple::ltNFTOKEN_OFFER) + for (xrpl::STObject const& node : txMeta.getNodes()) { + if (node.getFieldU16(xrpl::sfLedgerEntryType) != xrpl::ltNFTOKEN_OFFER) continue; - ripple::uint256 const tokenID = node.peekAtField(ripple::sfFinalFields) - .downcast() - .getFieldH256(ripple::sfNFTokenID); + xrpl::uint256 const tokenID = node.peekAtField(xrpl::sfFinalFields) + .downcast() + .getFieldH256(xrpl::sfNFTokenID); txs.emplace_back(tokenID, txMeta, sttx.getTransactionID()); } @@ -322,39 +322,39 @@ getNFTokenCancelOfferData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx // This transaction never returns an NFTokensData because it does not // change the state of an NFT itself. std::pair, std::optional> -getNFTokenCreateOfferData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx) +getNFTokenCreateOfferData(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx) { return { {NFTTransactionsData( - sttx.getFieldH256(ripple::sfNFTokenID), txMeta, sttx.getTransactionID() + sttx.getFieldH256(xrpl::sfNFTokenID), txMeta, sttx.getTransactionID() )}, {} }; } std::pair, std::optional> -getNFTDataFromTx(ripple::TxMeta const& txMeta, ripple::STTx const& sttx) +getNFTDataFromTx(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx) { - if (txMeta.getResultTER() != ripple::tesSUCCESS) + if (txMeta.getResultTER() != xrpl::tesSUCCESS) return {{}, {}}; switch (sttx.getTxnType()) { - case ripple::TxType::ttNFTOKEN_MINT: + case xrpl::TxType::ttNFTOKEN_MINT: return getNFTokenMintData(txMeta, sttx); - case ripple::TxType::ttNFTOKEN_BURN: + case xrpl::TxType::ttNFTOKEN_BURN: return getNFTokenBurnData(txMeta, sttx); - case ripple::TxType::ttNFTOKEN_ACCEPT_OFFER: + case xrpl::TxType::ttNFTOKEN_ACCEPT_OFFER: return getNFTokenAcceptOfferData(txMeta, sttx); - case ripple::TxType::ttNFTOKEN_CANCEL_OFFER: + case xrpl::TxType::ttNFTOKEN_CANCEL_OFFER: return getNFTokenCancelOfferData(txMeta, sttx); - case ripple::TxType::ttNFTOKEN_CREATE_OFFER: + case xrpl::TxType::ttNFTOKEN_CREATE_OFFER: return getNFTokenCreateOfferData(txMeta, sttx); - case ripple::TxType::ttNFTOKEN_MODIFY: + case xrpl::TxType::ttNFTOKEN_MODIFY: return getNftokenModifyData(txMeta, sttx); default: @@ -367,23 +367,23 @@ getNFTDataFromObj(std::uint32_t const seq, std::string const& key, std::string c { // https://github.com/XRPLF/XRPL-Standards/tree/master/XLS-0020-non-fungible-tokens#tokenpage-id-format ASSERT( - key.size() == ripple::uint256::size(), + key.size() == xrpl::uint256::size(), "The size of the key (token) is expected to fit uint256 exactly" ); - auto const sle = ripple::STLedgerEntry( - ripple::SerialIter{blob.data(), blob.size()}, ripple::uint256::fromVoid(key.data()) + auto const sle = xrpl::STLedgerEntry( + xrpl::SerialIter{blob.data(), blob.size()}, xrpl::uint256::fromVoid(key.data()) ); - if (sle.getFieldU16(ripple::sfLedgerEntryType) != ripple::ltNFTOKEN_PAGE) + if (sle.getFieldU16(xrpl::sfLedgerEntryType) != xrpl::ltNFTOKEN_PAGE) return {}; - auto const owner = ripple::AccountID::fromVoid(key.data()); + auto const owner = xrpl::AccountID::fromVoid(key.data()); std::vector nfts; - for (ripple::STObject const& node : sle.getFieldArray(ripple::sfNFTokens)) { + for (xrpl::STObject const& node : sle.getFieldArray(xrpl::sfNFTokens)) { nfts.emplace_back( - node.getFieldH256(ripple::sfNFTokenID), seq, owner, node.getFieldVL(ripple::sfURI) + node.getFieldH256(xrpl::sfNFTokenID), seq, owner, node.getFieldVL(xrpl::sfURI) ); } diff --git a/src/etl/NFTHelpers.hpp b/src/etl/NFTHelpers.hpp index c06ee2af5..9686c5a87 100644 --- a/src/etl/NFTHelpers.hpp +++ b/src/etl/NFTHelpers.hpp @@ -22,7 +22,7 @@ namespace etl { * @return NFT URI change data as a pair of transactions and optional NFTsData */ std::pair, std::optional> -getNftokenModifyData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx); +getNftokenModifyData(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx); /** * @brief Get the NFT Token mint data from a transaction @@ -32,7 +32,7 @@ getNftokenModifyData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx); * @return NFT Token mint data as a pair of transactions and optional NFTsData */ std::pair, std::optional> -getNFTokenMintData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx); +getNFTokenMintData(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx); /** * @brief Get the NFT Token burn data from a transaction @@ -42,7 +42,7 @@ getNFTokenMintData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx); * @return NFT Token burn data as a pair of transactions and optional NFTsData */ std::pair, std::optional> -getNFTokenBurnData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx); +getNFTokenBurnData(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx); /** * @brief Get the NFT Token accept offer data from a transaction @@ -52,7 +52,7 @@ getNFTokenBurnData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx); * @return NFT Token accept offer data as a pair of transactions and optional NFTsData */ std::pair, std::optional> -getNFTokenAcceptOfferData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx); +getNFTokenAcceptOfferData(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx); /** * @brief Get the NFT Token cancel offer data from a transaction @@ -62,7 +62,7 @@ getNFTokenAcceptOfferData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx * @return NFT Token cancel offer data as a pair of transactions and optional NFTsData */ std::pair, std::optional> -getNFTokenCancelOfferData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx); +getNFTokenCancelOfferData(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx); /** * @brief Get the NFT Token create offer data from a transaction @@ -72,7 +72,7 @@ getNFTokenCancelOfferData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx * @return NFT Token create offer data as a pair of transactions and optional NFTsData */ std::pair, std::optional> -getNFTokenCreateOfferData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx); +getNFTokenCreateOfferData(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx); /** * @brief Pull NFT data from TX via ETLService. @@ -82,7 +82,7 @@ getNFTokenCreateOfferData(ripple::TxMeta const& txMeta, ripple::STTx const& sttx * @return NFT transactions data as a pair of transactions and optional NFTsData */ std::pair, std::optional> -getNFTDataFromTx(ripple::TxMeta const& txMeta, ripple::STTx const& sttx); +getNFTDataFromTx(xrpl::TxMeta const& txMeta, xrpl::STTx const& sttx); /** * @brief Pull NFT data from ledger object via loadInitialLedger. @@ -97,9 +97,9 @@ getNFTDataFromObj(std::uint32_t seq, std::string const& key, std::string const& /** * @brief Get the unique NFTs data from a vector of NFTsData happening in the same ledger. For - example, if a NFT has + * example, if a NFT has * both accept offer and burn happening in the same ledger,we only keep the final state of the NFT. - + * * @param nfts The NFTs data to filter, happening in the same ledger * @return The unique NFTs data */ diff --git a/src/etl/RegistryInterface.hpp b/src/etl/RegistryInterface.hpp index 4c740d355..3cf4c9712 100644 --- a/src/etl/RegistryInterface.hpp +++ b/src/etl/RegistryInterface.hpp @@ -40,11 +40,11 @@ namespace etl { * @code{.cpp} * struct Ext { * using spec = etl::model::Spec< - * ripple::TxType::ttNFTOKEN_BURN, - * ripple::TxType::ttNFTOKEN_ACCEPT_OFFER, - * ripple::TxType::ttNFTOKEN_CREATE_OFFER, - * ripple::TxType::ttNFTOKEN_CANCEL_OFFER, - * ripple::TxType::ttNFTOKEN_MINT>; + * xrpl::TxType::ttNFTOKEN_BURN, + * xrpl::TxType::ttNFTOKEN_ACCEPT_OFFER, + * xrpl::TxType::ttNFTOKEN_CREATE_OFFER, + * xrpl::TxType::ttNFTOKEN_CANCEL_OFFER, + * xrpl::TxType::ttNFTOKEN_MINT>; * * static void * onInitialTransaction(uint32_t, etl::model::Transaction const&); diff --git a/src/etl/Source.hpp b/src/etl/Source.hpp index db0ed9f0e..ca7acb9b8 100644 --- a/src/etl/Source.hpp +++ b/src/etl/Source.hpp @@ -77,7 +77,9 @@ public: [[nodiscard]] virtual boost::json::object toJson() const = 0; - /** @return String representation of the source (for debug) */ + /** + * @return String representation of the source (for debug) + */ [[nodiscard]] virtual std::string toString() const = 0; diff --git a/src/etl/SystemState.hpp b/src/etl/SystemState.hpp index 7b82d26da..88e8f6a28 100644 --- a/src/etl/SystemState.hpp +++ b/src/etl/SystemState.hpp @@ -44,14 +44,18 @@ struct SystemState { "Whether the process is in strict read-only mode" ); - /** @brief Whether the process is writing to the database. */ + /** + * @brief Whether the process is writing to the database. + */ util::prometheus::Bool isWriting = PrometheusService::boolMetric( "etl_writing", util::prometheus::Labels{}, "Whether the process is writing to the database" ); - /** @brief Shows whether ETL started monitor and ready to become a writer if needed */ + /** + * @brief Shows whether ETL started monitor and ready to become a writer if needed + */ std::atomic_bool etlStarted{false}; /** @@ -61,8 +65,8 @@ struct SystemState { * across components. */ enum class WriteCommand { - StartWriting, /**< Request to attempt taking over as the ETL writer */ - StopWriting /**< Request to give up the ETL writer role (e.g., due to write conflict) */ + StartWriting, ///< Request to attempt taking over as the ETL writer + StopWriting ///< Request to give up the ETL writer role (e.g., due to write conflict) }; /** diff --git a/src/etl/WriterState.hpp b/src/etl/WriterState.hpp index 0cb8f083e..6e90a5e41 100644 --- a/src/etl/WriterState.hpp +++ b/src/etl/WriterState.hpp @@ -144,8 +144,7 @@ public: */ class WriterState : public WriterStateInterface { private: - std::shared_ptr - systemState_; /**< @brief Shared system state for ETL coordination */ + std::shared_ptr systemState_; ///< @brief Shared system state for ETL coordination std::reference_wrapper cache_; /** @@ -216,19 +215,27 @@ public: [[nodiscard]] bool isFallback() const override; - /** @copydoc WriterStateInterface::isFallbackRecovery */ + /** + * @copydoc WriterStateInterface::isFallbackRecovery + */ [[nodiscard]] bool isFallbackRecovery() const override; - /** @copydoc WriterStateInterface::setFallbackRecovery */ + /** + * @copydoc WriterStateInterface::setFallbackRecovery + */ void setFallbackRecovery(bool newValue) override; - /** @copydoc WriterStateInterface::isEtlStarted */ + /** + * @copydoc WriterStateInterface::isEtlStarted + */ [[nodiscard]] bool isEtlStarted() const override; - /** @copydoc WriterStateInterface::isCacheFull */ + /** + * @copydoc WriterStateInterface::isCacheFull + */ [[nodiscard]] bool isCacheFull() const override; diff --git a/src/etl/impl/AmendmentBlockHandler.cpp b/src/etl/impl/AmendmentBlockHandler.cpp index b200b2f33..f2fda30e1 100644 --- a/src/etl/impl/AmendmentBlockHandler.cpp +++ b/src/etl/impl/AmendmentBlockHandler.cpp @@ -11,15 +11,14 @@ namespace etl::impl { -AmendmentBlockHandler::ActionType const AmendmentBlockHandler::kDEFAULT_AMENDMENT_BLOCK_ACTION = - []() { - static util::Logger const log{"ETL"}; // NOLINT(readability-identifier-naming) - LOG( - log.fatal() - ) << "Can't process new ledgers: The current ETL source is not compatible with the version " - "of " - << "the libxrpl Clio is currently using. Please upgrade Clio to a newer version."; - }; +AmendmentBlockHandler::ActionType const AmendmentBlockHandler::kDefaultAmendmentBlockAction = []() { + static util::Logger const log{"ETL"}; // NOLINT(readability-identifier-naming) + LOG( + log.fatal() + ) << "Can't process new ledgers: The current ETL source is not compatible with the version " + "of " + << "the libxrpl Clio is currently using. Please upgrade Clio to a newer version."; +}; AmendmentBlockHandler::AmendmentBlockHandler( util::async::AnyExecutionContext ctx, @@ -40,16 +39,18 @@ void AmendmentBlockHandler::notifyAmendmentBlocked() { state_.get().isAmendmentBlocked = true; - if (not operation_.has_value()) - operation_.emplace(ctx_.executeRepeatedly(interval_, action_)); + + if (auto operation = operation_.lock(); not operation->has_value()) + operation->emplace(ctx_.executeRepeatedly(interval_, action_)); } void AmendmentBlockHandler::stop() { - if (operation_.has_value()) { - operation_->abort(); - operation_.reset(); + auto lock = operation_.lock(); + if (auto& operation = *lock; operation.has_value()) { + operation->abort(); + operation.reset(); } } diff --git a/src/etl/impl/AmendmentBlockHandler.hpp b/src/etl/impl/AmendmentBlockHandler.hpp index cedc78f98..f1c6b31dd 100644 --- a/src/etl/impl/AmendmentBlockHandler.hpp +++ b/src/etl/impl/AmendmentBlockHandler.hpp @@ -2,6 +2,7 @@ #include "etl/AmendmentBlockHandlerInterface.hpp" #include "etl/SystemState.hpp" +#include "util/Mutex.hpp" #include "util/async/AnyExecutionContext.hpp" #include "util/async/AnyOperation.hpp" @@ -18,23 +19,24 @@ namespace etl::impl { class AmendmentBlockHandler : public AmendmentBlockHandlerInterface { public: using ActionType = std::function; + using OperationType = std::optional>; private: std::reference_wrapper state_; std::chrono::steady_clock::duration interval_; util::async::AnyExecutionContext ctx_; - std::optional> operation_; + util::Mutex operation_; ActionType action_; public: - static ActionType const kDEFAULT_AMENDMENT_BLOCK_ACTION; + static ActionType const kDefaultAmendmentBlockAction; AmendmentBlockHandler( util::async::AnyExecutionContext ctx, SystemState& state, std::chrono::steady_clock::duration interval = std::chrono::seconds{1}, - ActionType action = kDEFAULT_AMENDMENT_BLOCK_ACTION + ActionType action = kDefaultAmendmentBlockAction ); ~AmendmentBlockHandler() override; diff --git a/src/etl/impl/AsyncGrpcCall.cpp b/src/etl/impl/AsyncGrpcCall.cpp index 839044d65..83d204728 100644 --- a/src/etl/impl/AsyncGrpcCall.cpp +++ b/src/etl/impl/AsyncGrpcCall.cpp @@ -26,22 +26,22 @@ namespace etl::impl { AsyncGrpcCall::AsyncGrpcCall( uint32_t seq, - ripple::uint256 const& marker, - std::optional const& nextMarker + xrpl::uint256 const& marker, + std::optional const& nextMarker ) { request_.set_user("ETL"); request_.mutable_ledger()->set_sequence(seq); if (marker.isNonZero()) - request_.set_marker(marker.data(), ripple::uint256::size()); + request_.set_marker(marker.data(), xrpl::uint256::size()); nextPrefix_ = nextMarker ? nextMarker->data()[0] : 0x00; auto const prefix = marker.data()[0]; - LOG(log_.debug()) << "Setting up AsyncGrpcCall. marker = " << ripple::strHex(marker) - << ". prefix = " << ripple::strHex(std::string(1, prefix)) - << ". nextPrefix_ = " << ripple::strHex(std::string(1, nextPrefix_)); + LOG(log_.debug()) << "Setting up AsyncGrpcCall. marker = " << xrpl::strHex(marker) + << ". prefix = " << xrpl::strHex(std::string(1, prefix)) + << ". nextPrefix_ = " << xrpl::strHex(std::string(1, nextPrefix_)); ASSERT( nextPrefix_ > prefix or nextPrefix_ == 0x00, @@ -142,7 +142,7 @@ std::string AsyncGrpcCall::getMarkerPrefix() { return next_->marker().empty() ? std::string{} - : ripple::strHex(std::string{next_->marker().data()[0]}); + : xrpl::strHex(std::string{next_->marker().data()[0]}); } // this is used to generate edgeKeys - keys that were the last one in the onInitialObjects list diff --git a/src/etl/impl/AsyncGrpcCall.hpp b/src/etl/impl/AsyncGrpcCall.hpp index 47d942455..85a891d3b 100644 --- a/src/etl/impl/AsyncGrpcCall.hpp +++ b/src/etl/impl/AsyncGrpcCall.hpp @@ -42,8 +42,8 @@ private: public: AsyncGrpcCall( uint32_t seq, - ripple::uint256 const& marker, - std::optional const& nextMarker + xrpl::uint256 const& marker, + std::optional const& nextMarker ); static std::vector diff --git a/src/etl/impl/BaseCursorProvider.hpp b/src/etl/impl/BaseCursorProvider.hpp index 4edb467e5..6b07887cb 100644 --- a/src/etl/impl/BaseCursorProvider.hpp +++ b/src/etl/impl/BaseCursorProvider.hpp @@ -7,8 +7,8 @@ namespace etl::impl { struct CursorPair { - ripple::uint256 start; - ripple::uint256 end; + xrpl::uint256 start; + xrpl::uint256 end; }; struct BaseCursorProvider { diff --git a/src/etl/impl/CacheLoader.hpp b/src/etl/impl/CacheLoader.hpp index 2641cdf0a..de36ac570 100644 --- a/src/etl/impl/CacheLoader.hpp +++ b/src/etl/impl/CacheLoader.hpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -18,12 +19,17 @@ #include #include #include +#include #include #include +#include #include #include +#include #include +struct CacheLoaderImplTests; + namespace etl::impl { template @@ -98,49 +104,78 @@ private: spawnWorker(uint32_t const seq, size_t cachePageFetchSize) { return ctx_.execute([this, seq, cachePageFetchSize](auto token) { - while (not token.isStopRequested() and not cache_.get().isDisabled()) { - auto cursor = queue_.tryPop(); - if (not cursor.has_value()) { - return; // queue is empty - } - - auto [start, end] = *cursor; - LOG(log_.debug()) << "Starting a cursor: " << ripple::strHex(start); - - while (not token.isStopRequested() and not cache_.get().isDisabled()) { - auto res = - data::retryOnTimeout([this, seq, cachePageFetchSize, &start, token]() { - return backend_->fetchLedgerPage( - start, seq, cachePageFetchSize, false, token - ); - }); - - cache_.get().update(res.objects, seq, true); - - if (not res.cursor or res.cursor > end) { - if (--remaining_ <= 0) { - auto endTime = std::chrono::steady_clock::now(); - auto duration = std::chrono::duration_cast( - endTime - startTime_ - ); - - LOG(log_.info()) - << "Finished loading cache. Cache size = " << cache_.get().size() - << ". Took " << duration.count() << " seconds"; - - cache_.get().setFull(); - } else { - LOG(log_.debug()) << "Finished a cursor. Remaining = " << remaining_; - } - - break; // pick up the next cursor if available - } - - start = *std::move(res.cursor); - } - } + runGuarded([this, seq, cachePageFetchSize, token] { + loadCacheFromCursors(token, seq, cachePageFetchSize); + }); }); } + + template + void + runGuarded(Work&& work) + { + std::optional failure; + try { + std::forward(work)(); + } catch (std::exception const& e) { + failure = fmt::format("Cache loading failed: {}", e.what()); + } catch (...) { + failure = "Cache loading failed with an unknown (non-std) error"; + } + + if (failure.has_value()) { + LOG(log_.error()) << *failure + << "; disabling cache and continuing without it (reads will be " + "served from the database)."; + cache_.get().setDisabled(); + } + } + + template + void + loadCacheFromCursors(TokenType token, uint32_t const seq, size_t cachePageFetchSize) + { + while (not token.isStopRequested() and not cache_.get().isDisabled()) { + auto cursor = queue_.tryPop(); + if (not cursor.has_value()) { + return; // queue is empty + } + + auto [start, end] = *cursor; + LOG(log_.debug()) << "Starting a cursor: " << xrpl::strHex(start); + + while (not token.isStopRequested() and not cache_.get().isDisabled()) { + auto res = data::retryOnTimeout([this, seq, cachePageFetchSize, &start, token]() { + return backend_->fetchLedgerPage(start, seq, cachePageFetchSize, false, token); + }); + + cache_.get().update(res.objects, seq, true); + + if (not res.cursor or res.cursor > end) { + if (--remaining_ <= 0) { + auto endTime = std::chrono::steady_clock::now(); + auto duration = + std::chrono::duration_cast(endTime - startTime_); + + LOG(log_.info()) + << "Finished loading cache. Cache size = " << cache_.get().size() + << ". Took " << duration.count() << " seconds"; + + cache_.get().setFull(); + } else { + LOG(log_.debug()) << "Finished a cursor. Remaining = " << remaining_; + } + + break; // pick up the next cursor if available + } + + start = *std::move(res.cursor); + } + } + } + + // Grants tests access to the private guard/loading members above. + friend struct ::CacheLoaderImplTests; }; } // namespace etl::impl diff --git a/src/etl/impl/CursorFromAccountProvider.hpp b/src/etl/impl/CursorFromAccountProvider.hpp index 19eed1475..6fbe46777 100644 --- a/src/etl/impl/CursorFromAccountProvider.hpp +++ b/src/etl/impl/CursorFromAccountProvider.hpp @@ -43,10 +43,10 @@ public: }(); rg::sort(accountRoots); - std::vector cursors{data::kFIRST_KEY}; + std::vector cursors{data::kFirstKey}; rg::copy(accountRoots.begin(), accountRoots.end(), std::back_inserter(cursors)); rg::sort(cursors); - cursors.push_back(data::kLAST_KEY); + cursors.push_back(data::kLastKey); std::vector pairs; pairs.reserve(cursors.size()); diff --git a/src/etl/impl/CursorFromDiffProvider.hpp b/src/etl/impl/CursorFromDiffProvider.hpp index 538809a09..a6cabdf8a 100644 --- a/src/etl/impl/CursorFromDiffProvider.hpp +++ b/src/etl/impl/CursorFromDiffProvider.hpp @@ -43,8 +43,8 @@ public: auto const range = backend_->fetchLedgerRange(); ASSERT(range.has_value(), "Ledger range is not available when cache is loading"); - std::set liveCursors; - std::set deletedCursors; + std::set liveCursors; + std::set deletedCursors; auto i = 0; // NOLINTNEXTLINE(bugprone-unchecked-optional-access) while (liveCursors.size() < numCursors_ and seq - i >= range->minSequence) { @@ -67,13 +67,13 @@ public: ); } - std::vector cursors{data::kFIRST_KEY}; + std::vector cursors{data::kFirstKey}; rg::copy( liveCursors | vs::take(std::min(liveCursors.size(), numCursors_)), std::back_inserter(cursors) ); rg::sort(cursors); - cursors.push_back(data::kLAST_KEY); + cursors.push_back(data::kLastKey); std::vector pairs; pairs.reserve(cursors.size()); diff --git a/src/etl/impl/CursorFromFixDiffNumProvider.hpp b/src/etl/impl/CursorFromFixDiffNumProvider.hpp index f3cdcac1c..fdf2ed24b 100644 --- a/src/etl/impl/CursorFromFixDiffNumProvider.hpp +++ b/src/etl/impl/CursorFromFixDiffNumProvider.hpp @@ -57,14 +57,14 @@ public: rg::unique(diffs, [](auto const& a, auto const& b) { return a.key == b.key; }); diffs.erase(removalCursor, last); - std::vector cursors{data::kFIRST_KEY}; + std::vector cursors{data::kFirstKey}; rg::copy( diffs // | vs::filter([](auto const& obj) { return not obj.blob.empty(); }) // | vs::transform([](auto const& obj) { return obj.key; }), std::back_inserter(cursors) ); - cursors.push_back(data::kLAST_KEY); // last pair should cover the remaining range + cursors.push_back(data::kLastKey); // last pair should cover the remaining range std::vector pairs; pairs.reserve(cursors.size()); diff --git a/src/etl/impl/Extraction.cpp b/src/etl/impl/Extraction.cpp index 93256a22a..608e14507 100644 --- a/src/etl/impl/Extraction.cpp +++ b/src/etl/impl/Extraction.cpp @@ -2,7 +2,6 @@ #include "data/DBHelpers.hpp" #include "data/Types.hpp" -#include "etl/LedgerFetcherInterface.hpp" #include "etl/Models.hpp" #include "etl/impl/LedgerFetcher.hpp" #include "util/Assert.hpp" @@ -10,6 +9,7 @@ #include "util/Profiler.hpp" #include "util/log/Logger.hpp" +#include #include #include #include @@ -18,12 +18,11 @@ #include #include -#include #include #include -#include #include #include +#include #include #include #include @@ -57,9 +56,10 @@ model::Transaction extractTx(PBTxType tx, uint32_t seq) { auto raw = std::move(*tx.mutable_transaction_blob()); - ripple::SerialIter it{raw.data(), raw.size()}; - ripple::STTx const sttx{it}; - ripple::TxMeta meta{sttx.getTransactionID(), seq, tx.metadata_blob()}; + xrpl::SerialIter it{raw.data(), raw.size()}; + xrpl::STTx const sttx{it}; + auto const& metaBlob = tx.metadata_blob(); + xrpl::TxMeta meta{sttx.getTransactionID(), seq, xrpl::Blob{metaBlob.begin(), metaBlob.end()}}; return { .raw = std::move(raw), @@ -92,7 +92,7 @@ extractTxs(PBTxListType transactions, uint32_t seq) model::Object extractObj(PBObjType obj) { - auto const key = ripple::uint256::fromVoidChecked(obj.key()); + auto const key = xrpl::uint256::fromVoidChecked(obj.key()); ASSERT(key.has_value(), "Failed to deserialize key from void"); if (!key) return {}; @@ -108,8 +108,8 @@ extractObj(PBObjType obj) .keyRaw = std::move(*obj.mutable_key()), .data = {obj.mutable_data()->begin(), obj.mutable_data()->end()}, .dataRaw = std::move(*obj.mutable_data()), - .successor = valueOr(obj.successor(), uint256ToString(data::kFIRST_KEY)), - .predecessor = valueOr(obj.predecessor(), uint256ToString(data::kLAST_KEY)), + .successor = valueOr(obj.successor(), uint256ToString(data::kFirstKey)), + .predecessor = valueOr(obj.predecessor(), uint256ToString(data::kLastKey)), .type = extractModType(obj.mod_type()), }; } @@ -164,7 +164,7 @@ auto Extractor::unpack() { return [](auto&& data) { - auto header = ::util::deserializeHeader(ripple::makeSlice(data.ledger_header())); + auto header = ::util::deserializeHeader(xrpl::makeSlice(data.ledger_header())); return std::make_optional({ .transactions = extractTxs( @@ -180,19 +180,36 @@ Extractor::unpack() }; } +std::optional +Extractor::guardedUnpack(std::optional&& response, uint32_t seq) +{ + try { + return std::move(response).and_then(unpack()); + } catch (std::runtime_error const& e) { + LOG(log_.fatal()) << "Failed to extract/deserialize ledger " << seq + << " - the network likely has an amendment this Clio does not support: " + << e.what(); + amendmentBlockHandler_->notifyAmendmentBlocked(); + return std::nullopt; + } +} + std::optional Extractor::extractLedgerWithDiff(uint32_t seq) { LOG(log_.debug()) << "Extracting DIFF " << seq; auto const [batch, time] = ::util::timed>([this, seq] { - return fetcher_->fetchDataAndDiff(seq).and_then(unpack()); + return guardedUnpack(fetcher_->fetchDataAndDiff(seq), seq); }); - LOG(log_.debug()) << "Extracted and Transformed diff for " << seq << " in " << time << "ms"; + if (batch.has_value()) { + LOG(log_.debug()) << "Extracted and transformed diff for " << seq << " in " << time << "ms"; + } else { + LOG(log_.debug()) << "Did not produce diff for " << seq << " (no data) after " << time + << "ms"; + } - // can be nullopt. this means that either the server is stopping or another node took over ETL - // writing. return batch; } @@ -202,14 +219,17 @@ Extractor::extractLedgerOnly(uint32_t seq) LOG(log_.debug()) << "Extracting FULL " << seq; auto const [batch, time] = ::util::timed>([this, seq] { - return fetcher_->fetchData(seq).and_then(unpack()); + return guardedUnpack(fetcher_->fetchData(seq), seq); }); - LOG(log_.debug()) << "Extracted and Transformed full ledger for " << seq << " in " << time - << "ms"; + if (batch.has_value()) { + LOG(log_.debug()) << "Extracted and transformed full ledger " << seq << " in " << time + << "ms"; + } else { + LOG(log_.debug()) << "Did not produce full ledger " << seq << " (no data) after " << time + << "ms"; + } - // can be nullopt. this means that either the server is stopping or another node took over ETL - // writing. return batch; } diff --git a/src/etl/impl/Extraction.hpp b/src/etl/impl/Extraction.hpp index 04735cc09..e354e592a 100644 --- a/src/etl/impl/Extraction.hpp +++ b/src/etl/impl/Extraction.hpp @@ -1,5 +1,6 @@ #pragma once +#include "etl/AmendmentBlockHandlerInterface.hpp" #include "etl/ExtractorInterface.hpp" #include "etl/LedgerFetcherInterface.hpp" #include "etl/Models.hpp" @@ -59,6 +60,7 @@ maybeExtractSuccessors(PBLedgerResponseType const& data); // fetches the data in gRPC and transforms to local representation class Extractor : public ExtractorInterface { std::shared_ptr fetcher_; + std::shared_ptr amendmentBlockHandler_; util::Logger log_{"ETL"}; @@ -66,8 +68,15 @@ private: [[nodiscard]] static auto unpack(); + [[nodiscard]] std::optional + guardedUnpack(std::optional&& response, uint32_t seq); + public: - Extractor(std::shared_ptr fetcher) : fetcher_(std::move(fetcher)) + Extractor( + std::shared_ptr fetcher, + std::shared_ptr amendmentBlockHandler + ) + : fetcher_(std::move(fetcher)), amendmentBlockHandler_(std::move(amendmentBlockHandler)) { } diff --git a/src/etl/impl/ForwardingSource.hpp b/src/etl/impl/ForwardingSource.hpp index 05d2dee80..3806b9b71 100644 --- a/src/etl/impl/ForwardingSource.hpp +++ b/src/etl/impl/ForwardingSource.hpp @@ -20,14 +20,14 @@ class ForwardingSource { util::requests::WsConnectionBuilder connectionBuilder_; std::chrono::steady_clock::duration forwardingTimeout_; - static constexpr std::chrono::seconds kCONNECTION_TIMEOUT{3}; + static constexpr std::chrono::seconds kConnectionTimeout{3}; public: ForwardingSource( std::string ip, std::string wsPort, std::chrono::steady_clock::duration forwardingTimeout, - std::chrono::steady_clock::duration connTimeout = ForwardingSource::kCONNECTION_TIMEOUT + std::chrono::steady_clock::duration connTimeout = ForwardingSource::kConnectionTimeout ); /** diff --git a/src/etl/impl/GrpcSource.cpp b/src/etl/impl/GrpcSource.cpp index 849eb517c..fc2bb8e3b 100644 --- a/src/etl/impl/GrpcSource.cpp +++ b/src/etl/impl/GrpcSource.cpp @@ -58,13 +58,12 @@ GrpcSource::GrpcSource( try { grpc::ChannelArguments chArgs; chArgs.SetMaxReceiveMessageSize(-1); - chArgs.SetInt(GRPC_ARG_KEEPALIVE_TIME_MS, kKEEPALIVE_PING_INTERVAL_MS); - chArgs.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, kKEEPALIVE_TIMEOUT_MS); + chArgs.SetInt(GRPC_ARG_KEEPALIVE_TIME_MS, kKeepalivePingIntervalMs); + chArgs.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, kKeepaliveTimeoutMs); chArgs.SetInt( - GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, - static_cast(kKEEPALIVE_PERMIT_WITHOUT_CALLS) + GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, static_cast(kKeepalivePermitWithoutCalls) ); - chArgs.SetInt(GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA, kMAX_PINGS_WITHOUT_DATA); + chArgs.SetInt(GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA, kMaxPingsWithoutData); stub_ = org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub( grpc::CreateCustomChannel( diff --git a/src/etl/impl/GrpcSource.hpp b/src/etl/impl/GrpcSource.hpp index d3065ed6d..65ae90282 100644 --- a/src/etl/impl/GrpcSource.hpp +++ b/src/etl/impl/GrpcSource.hpp @@ -24,18 +24,18 @@ class GrpcSource { std::unique_ptr initialLoadShouldStop_; std::chrono::system_clock::duration deadline_; - static constexpr auto kKEEPALIVE_PING_INTERVAL_MS = 10000; - static constexpr auto kKEEPALIVE_TIMEOUT_MS = 5000; - static constexpr auto kKEEPALIVE_PERMIT_WITHOUT_CALLS = - true; // Allow keepalive pings when no calls - static constexpr auto kMAX_PINGS_WITHOUT_DATA = 0; // No limit - static constexpr auto kDEADLINE = std::chrono::seconds(30); + static constexpr auto kKeepalivePingIntervalMs = 10000; + static constexpr auto kKeepaliveTimeoutMs = 5000; + static constexpr auto kKeepalivePermitWithoutCalls = + true; // Allow keepalive pings when no calls + static constexpr auto kMaxPingsWithoutData = 0; // No limit + static constexpr auto kDeadline = std::chrono::seconds(30); public: GrpcSource( std::string const& ip, std::string const& grpcPort, - std::chrono::system_clock::duration deadline = kDEADLINE + std::chrono::system_clock::duration deadline = kDeadline ); /** diff --git a/src/etl/impl/LedgerPublisher.hpp b/src/etl/impl/LedgerPublisher.hpp index 1fac36f4d..4e191c6cf 100644 --- a/src/etl/impl/LedgerPublisher.hpp +++ b/src/etl/impl/LedgerPublisher.hpp @@ -65,7 +65,7 @@ class LedgerPublisher : public LedgerPublisherInterface { std::shared_ptr subscriptions_; std::reference_wrapper state_; // shared state for ETL - util::Mutex, std::shared_mutex> lastCloseTime_; + util::Mutex, std::shared_mutex> lastCloseTime_; std::reference_wrapper lastPublishSeconds_ = PrometheusService::counterInt( @@ -157,7 +157,7 @@ public: * @param lgrInfo the ledger to publish */ void - publish(ripple::LedgerHeader const& lgrInfo) + publish(xrpl::LedgerHeader const& lgrInfo) { publishStrand_.submit([this, lgrInfo = lgrInfo] { LOG(log_.info()) << "Publishing ledger " << std::to_string(lgrInfo.seq); @@ -167,9 +167,9 @@ public: // if the ledger closed over MAX_LEDGER_AGE_SECONDS ago, assume we are still catching up // and don't publish - static constexpr std::uint32_t kMAX_LEDGER_AGE_SECONDS = 600; - if (age < kMAX_LEDGER_AGE_SECONDS) { - std::optional fees = + static constexpr std::uint32_t kMaxLedgerAgeSeconds = 600; + if (age < kMaxLedgerAgeSeconds) { + std::optional fees = data::synchronousAndRetryOnTimeout([&](auto yield) { return backend_->fetchFees(lgrInfo.seq, yield); }); @@ -188,12 +188,12 @@ public: // order with transaction index std::ranges::sort(transactions, [](auto const& t1, auto const& t2) { - ripple::SerialIter iter1{t1.metadata.data(), t1.metadata.size()}; - ripple::STObject const object1(iter1, ripple::sfMetadata); - ripple::SerialIter iter2{t2.metadata.data(), t2.metadata.size()}; - ripple::STObject const object2(iter2, ripple::sfMetadata); - return object1.getFieldU32(ripple::sfTransactionIndex) < - object2.getFieldU32(ripple::sfTransactionIndex); + xrpl::SerialIter iter1{t1.metadata.data(), t1.metadata.size()}; + xrpl::STObject const object1(iter1, xrpl::sfMetadata); + xrpl::SerialIter iter2{t2.metadata.data(), t2.metadata.size()}; + xrpl::STObject const object2(iter2, xrpl::sfMetadata); + return object1.getFieldU32(xrpl::sfTransactionIndex) < + object2.getFieldU32(xrpl::sfTransactionIndex); }); for (auto const& txAndMeta : transactions) @@ -246,9 +246,9 @@ public: std::chrono::system_clock::now().time_since_epoch() ) .count(); - if (now < (kRIPPLE_EPOCH_START + closeTime)) + if (now < (kRippleEpochStart + closeTime)) return 0; - return now - (kRIPPLE_EPOCH_START + closeTime); + return now - (kRippleEpochStart + closeTime); } /** @@ -275,7 +275,7 @@ public: private: void - setLastClose(std::chrono::time_point lastCloseTime) + setLastClose(std::chrono::time_point lastCloseTime) { auto closeTime = lastCloseTime_.lock(); *closeTime = lastCloseTime; diff --git a/src/etl/impl/Loading.cpp b/src/etl/impl/Loading.cpp index 74738b127..f319a64f8 100644 --- a/src/etl/impl/Loading.cpp +++ b/src/etl/impl/Loading.cpp @@ -83,8 +83,8 @@ Loader::onInitialLoadGotMoreObjects( std::optional lastKey ) { - static constexpr std::size_t kLOG_STRIDE = 1000u; - static auto kINITIAL_LOAD_START_TIME = std::chrono::steady_clock::now(); + static constexpr std::size_t kLogStride = 1000u; + static auto kInitialLoadStartTime = std::chrono::steady_clock::now(); try { LOG(log_.trace()) << "On initial load: got more objects for seq " << seq @@ -99,12 +99,12 @@ Loader::onInitialLoadGotMoreObjects( initialLoadWrittenObjects_ += data.size(); ++initialLoadWrites_; - if (initialLoadWrites_ % kLOG_STRIDE == 0u && initialLoadWrites_ != 0u) { + if (initialLoadWrites_ % kLogStride == 0u && initialLoadWrites_ != 0u) { auto elapsedSinceStart = std::chrono::duration_cast( - std::chrono::steady_clock::now() - kINITIAL_LOAD_START_TIME + std::chrono::steady_clock::now() - kInitialLoadStartTime ); auto elapsedSeconds = - elapsedSinceStart.count() / static_cast(util::kMILLISECONDS_PER_SECOND); + elapsedSinceStart.count() / static_cast(util::kMillisecondsPerSecond); auto objectsPerSecond = elapsedSeconds > 0.0 ? static_cast(initialLoadWrittenObjects_) / elapsedSeconds : 0.0; @@ -120,7 +120,7 @@ Loader::onInitialLoadGotMoreObjects( } } -std::optional +std::optional Loader::loadInitialLedger(model::LedgerData const& data) { try { diff --git a/src/etl/impl/Loading.hpp b/src/etl/impl/Loading.hpp index 3870165a9..0096b9225 100644 --- a/src/etl/impl/Loading.hpp +++ b/src/etl/impl/Loading.hpp @@ -67,7 +67,7 @@ public: std::optional lastKey ) override; - std::optional + std::optional loadInitialLedger(model::LedgerData const& data) override; }; diff --git a/src/etl/impl/Monitor.cpp b/src/etl/impl/Monitor.cpp index b89c3650e..229731dda 100644 --- a/src/etl/impl/Monitor.cpp +++ b/src/etl/impl/Monitor.cpp @@ -10,7 +10,6 @@ #include #include -#include #include #include #include diff --git a/src/etl/impl/Registry.hpp b/src/etl/impl/Registry.hpp index cdad01dce..26d46e07b 100644 --- a/src/etl/impl/Registry.hpp +++ b/src/etl/impl/Registry.hpp @@ -57,7 +57,7 @@ concept HasInitialObjectHook = requires(T p) { }; template -concept ContainsSpec = std::decay_t::spec::kSPEC_TAG; +concept ContainsSpec = std::decay_t::spec::kSpecTag; template concept ContainsValidHook = diff --git a/src/etl/impl/Scheduling.hpp b/src/etl/impl/Scheduling.hpp index 22a3157c2..87aeb757a 100644 --- a/src/etl/impl/Scheduling.hpp +++ b/src/etl/impl/Scheduling.hpp @@ -49,11 +49,11 @@ public: [[nodiscard]] std::optional next() override { - static constexpr auto kMAX = std::numeric_limits::max(); + static constexpr auto kMax = std::numeric_limits::max(); uint32_t currentSeq = seq_; if (ledgers_.get().getMostRecent() >= currentSeq) { - while (currentSeq < maxSeq_.value_or(kMAX)) { + while (currentSeq < maxSeq_.value_or(kMax)) { if (seq_.compare_exchange_weak( currentSeq, currentSeq + 1u, std::memory_order_acq_rel )) { diff --git a/src/etl/impl/SourceImpl.hpp b/src/etl/impl/SourceImpl.hpp index 371e3784e..211c65d11 100644 --- a/src/etl/impl/SourceImpl.hpp +++ b/src/etl/impl/SourceImpl.hpp @@ -143,7 +143,9 @@ public: return res; } - /** @return String representation of the source (for debug) */ + /** + * @return String representation of the source (for debug) + */ [[nodiscard]] std::string toString() const final { diff --git a/src/etl/impl/SubscriptionSource.cpp b/src/etl/impl/SubscriptionSource.cpp index d8618df9c..833d3ac04 100644 --- a/src/etl/impl/SubscriptionSource.cpp +++ b/src/etl/impl/SubscriptionSource.cpp @@ -58,7 +58,7 @@ SubscriptionSource::SubscriptionSource( , subscriptions_(std::move(subscriptions)) , strand_(boost::asio::make_strand(ioContext)) , wsTimeout_(wsTimeout) - , retry_(util::makeRetryExponentialBackoff(retryDelay, kRETRY_MAX_DELAY, strand_)) + , retry_(util::makeRetryExponentialBackoff(retryDelay, kRetryMaxDelay, strand_)) , onConnect_(std::move(onConnect)) , onDisconnect_(std::move(onDisconnect)) , onLedgerClosed_(std::move(onLedgerClosed)) @@ -198,9 +198,9 @@ SubscriptionSource::handleMessage(std::string const& message) auto const object = raw.as_object(); uint32_t ledgerIndex = 0; - static constexpr auto kJS_LEDGER_CLOSED = "ledgerClosed"; - static constexpr auto kJS_VALIDATION_RECEIVED = "validationReceived"; - static constexpr auto kJS_MANIFEST_RECEIVED = "manifestReceived"; + static constexpr auto kJsLedgerClosed = "ledgerClosed"; + static constexpr auto kJsValidationReceived = "validationReceived"; + static constexpr auto kJsManifestReceived = "manifestReceived"; if (object.contains(JS(result))) { auto const& result = object.at(JS(result)).as_object(); @@ -215,7 +215,7 @@ SubscriptionSource::handleMessage(std::string const& message) LOG(log_.debug()) << "Received a message on ledger subscription stream. Message: " << object; - } else if (object.contains(JS(type)) && object.at(JS(type)) == kJS_LEDGER_CLOSED) { + } else if (object.contains(JS(type)) && object.at(JS(type)) == kJsLedgerClosed) { LOG(log_.debug()) << "Received a message of type 'ledgerClosed' on ledger subscription " "stream. Message: " << object; @@ -239,12 +239,12 @@ SubscriptionSource::handleMessage(std::string const& message) LOG(log_.debug()) << "Forwarding proposed transaction: " << object; subscriptions_->forwardProposedTransaction(object); } else if ( - object.contains(JS(type)) && object.at(JS(type)) == kJS_VALIDATION_RECEIVED + object.contains(JS(type)) && object.at(JS(type)) == kJsValidationReceived ) { LOG(log_.debug()) << "Forwarding validation: " << object; subscriptions_->forwardValidation(object); } else if ( - object.contains(JS(type)) && object.at(JS(type)) == kJS_MANIFEST_RECEIVED + object.contains(JS(type)) && object.at(JS(type)) == kJsManifestReceived ) { LOG(log_.debug()) << "Forwarding manifest: " << object; subscriptions_->forwardManifest(object); @@ -358,12 +358,12 @@ SubscriptionSource::setValidatedRange(std::string range) std::string const& SubscriptionSource::getSubscribeCommandJson() { - static boost::json::object const kJSON_VALUE{ + static boost::json::object const kJsonValue{ {"command", "subscribe"}, {"streams", {"ledger", "manifests", "validations", "transactions_proposed"}}, }; - static std::string const kJSON_STRING = boost::json::serialize(kJSON_VALUE); - return kJSON_STRING; + static std::string const kJsonString = boost::json::serialize(kJsonValue); + return kJsonString; } } // namespace etl::impl diff --git a/src/etl/impl/SubscriptionSource.hpp b/src/etl/impl/SubscriptionSource.hpp index 021ce3d72..1e35181fe 100644 --- a/src/etl/impl/SubscriptionSource.hpp +++ b/src/etl/impl/SubscriptionSource.hpp @@ -74,9 +74,9 @@ private: util::StopHelper stopHelper_; - static constexpr std::chrono::seconds kWS_TIMEOUT{30}; - static constexpr std::chrono::seconds kRETRY_MAX_DELAY{30}; - static constexpr std::chrono::seconds kRETRY_DELAY{1}; + static constexpr std::chrono::seconds kWsTimeout{30}; + static constexpr std::chrono::seconds kRetryMaxDelay{30}; + static constexpr std::chrono::seconds kRetryDelay{1}; public: /** @@ -104,8 +104,8 @@ public: OnConnectHook onConnect, OnDisconnectHook onDisconnect, OnLedgerClosedHook onLedgerClosed, - std::chrono::steady_clock::duration const wsTimeout = SubscriptionSource::kWS_TIMEOUT, - std::chrono::steady_clock::duration const retryDelay = SubscriptionSource::kRETRY_DELAY + std::chrono::steady_clock::duration const wsTimeout = SubscriptionSource::kWsTimeout, + std::chrono::steady_clock::duration const retryDelay = SubscriptionSource::kRetryDelay ); /** diff --git a/src/etl/impl/TaskManager.cpp b/src/etl/impl/TaskManager.cpp index 2bbc4d80e..bde4bd51a 100644 --- a/src/etl/impl/TaskManager.cpp +++ b/src/etl/impl/TaskManager.cpp @@ -40,7 +40,7 @@ TaskManager::TaskManager( , extractor_(extractor) , loader_(loader) , monitor_(monitor) - , queue_({.startSeq = startSeq, .increment = 1u, .limit = kQUEUE_SIZE_LIMIT}) + , queue_({.startSeq = startSeq, .increment = 1u, .limit = kQueueSizeLimit}) { } @@ -70,8 +70,8 @@ TaskManager::spawnExtractor(TaskQueue& queue) { // TODO https://github.com/XRPLF/clio/issues/2838: the approach should be changed to a reactive // one instead - static constexpr auto kDELAY_BETWEEN_ATTEMPTS = std::chrono::milliseconds{10u}; - static constexpr auto kDELAY_BETWEEN_ENQUEUE_ATTEMPTS = std::chrono::milliseconds{1u}; + static constexpr auto kDelayBetweenAttempts = std::chrono::milliseconds{10u}; + static constexpr auto kDelayBetweenEnqueueAttempts = std::chrono::milliseconds{1u}; return ctx_.execute([this, &queue](auto stopRequested) { while (not stopRequested) { @@ -81,7 +81,7 @@ TaskManager::spawnExtractor(TaskQueue& queue) LOG(log_.debug()) << "Adding data after extracting diff"; while (not queue.enqueue(*maybeBatch)) { // TODO (https://github.com/XRPLF/clio/issues/1852) - std::this_thread::sleep_for(kDELAY_BETWEEN_ENQUEUE_ATTEMPTS); + std::this_thread::sleep_for(kDelayBetweenEnqueueAttempts); if (stopRequested) break; @@ -89,7 +89,7 @@ TaskManager::spawnExtractor(TaskQueue& queue) } } else { // TODO (https://github.com/XRPLF/clio/issues/1852) - std::this_thread::sleep_for(kDELAY_BETWEEN_ATTEMPTS); + std::this_thread::sleep_for(kDelayBetweenAttempts); } } @@ -130,7 +130,7 @@ TaskManager::spawnLoader(TaskQueue& queue) if (shouldExitOnError) break; - auto const seconds = nanos / util::kNANO_PER_SECOND; + auto const seconds = nanos / util::kNanoPerSecond; auto const txnCount = data->transactions.size(); auto const objCount = data->objects.size(); diff --git a/src/etl/impl/TaskManager.hpp b/src/etl/impl/TaskManager.hpp index da8f2aaba..0ff85885d 100644 --- a/src/etl/impl/TaskManager.hpp +++ b/src/etl/impl/TaskManager.hpp @@ -23,7 +23,7 @@ namespace etl::impl { class TaskManager : public TaskManagerInterface { - static constexpr auto kQUEUE_SIZE_LIMIT = 2048uz; + static constexpr auto kQueueSizeLimit = 2048uz; util::async::AnyExecutionContext ctx_; std::shared_ptr schedulers_; diff --git a/src/etl/impl/ext/MPT.cpp b/src/etl/impl/ext/MPT.cpp index 343afca9f..dd07654ab 100644 --- a/src/etl/impl/ext/MPT.cpp +++ b/src/etl/impl/ext/MPT.cpp @@ -8,7 +8,9 @@ #include +#include #include +#include #include #include #include @@ -25,13 +27,13 @@ MPTExt::onLedgerData(model::LedgerData const& data) { LOG(log_.trace()) << "got TXS cnt = " << data.transactions.size() << "; OBJS size = " << data.objects.size(); - writeMPTHoldersFromTransactions(data); + writeMPTDataFromTransactions(data); } void MPTExt::onInitialObject(uint32_t, model::Object const& obj) { - LOG(log_.trace()) << "got initial object with key: " << ripple::strHex(obj.key); + LOG(log_.trace()) << "got initial object with key: " << xrpl::strHex(obj.key); if (auto const mptHolder = getMPTHolderFromObj(obj.keyRaw, obj.dataRaw); mptHolder.has_value()) backend_->writeMPTHolders({*mptHolder}); } @@ -40,21 +42,50 @@ void MPTExt::onInitialData(model::LedgerData const& data) { LOG(log_.trace()) << "got initial TXS cnt = " << data.transactions.size(); - writeMPTHoldersFromTransactions(data); + writeMPTDataFromTransactions(data); } void -MPTExt::writeMPTHoldersFromTransactions(model::LedgerData const& data) +MPTExt::writeMPTDataFromTransactions(model::LedgerData const& data) { std::vector holders; + std::vector issuanceTxs; + std::size_t indexRowsWritten = 0; + static constexpr std::size_t kIndexRowsPerTxWarningThreshold = 1000; for (auto const& tx : data.transactions) { - if (auto const mptHolder = getMPTHolderFromTx(tx.meta, tx.sttx); mptHolder.has_value()) - holders.push_back(*mptHolder); + auto const mptHolders = getMPTHolderFromTx(tx.meta, tx.sttx); + holders.append_range(mptHolders); + + auto txIndexData = getMPTokenIssuanceTxsFromTx(tx.meta, tx.sttx); + + std::size_t txIndexRows = 0; + for (auto const& record : txIndexData) + txIndexRows += 1 + record.accounts.size(); + + if (txIndexRows > kIndexRowsPerTxWarningThreshold) { + LOG(log_.warn()) << "MPT issuance tx index fanout of " << txIndexRows + << " rows exceeds the expected bound of " + << kIndexRowsPerTxWarningThreshold << " for tx " + << xrpl::strHex(tx.id); + } + + indexRowsWritten += txIndexRows; + issuanceTxs.insert( + issuanceTxs.end(), + std::make_move_iterator(txIndexData.begin()), + std::make_move_iterator(txIndexData.end()) + ); } if (not holders.empty()) backend_->writeMPTHolders(holders); + + if (not issuanceTxs.empty()) { + backend_->writeMPTokenIssuanceTransactions(issuanceTxs); + backend_->writeAccountMPTokenIssuanceTransactions(issuanceTxs); + issuanceTxIndexRowsWritten_.get() += static_cast(indexRowsWritten); + } } } // namespace etl::impl diff --git a/src/etl/impl/ext/MPT.hpp b/src/etl/impl/ext/MPT.hpp index 2f0c3719b..9af3e8559 100644 --- a/src/etl/impl/ext/MPT.hpp +++ b/src/etl/impl/ext/MPT.hpp @@ -3,6 +3,8 @@ #include "data/BackendInterface.hpp" #include "etl/Models.hpp" #include "util/log/Logger.hpp" +#include "util/prometheus/Counter.hpp" +#include "util/prometheus/Prometheus.hpp" #include #include @@ -10,6 +12,7 @@ #include #include +#include #include namespace etl::impl { @@ -18,6 +21,13 @@ class MPTExt { std::shared_ptr backend_; util::Logger log_{"ETL"}; + std::reference_wrapper issuanceTxIndexRowsWritten_ = + PrometheusService::counterInt( + "etl_mpt_issuance_tx_index_rows_written_total", + {}, + "Total number of MPT issuance transaction index rows written by ETL" + ); + public: explicit MPTExt(std::shared_ptr backend); @@ -32,7 +42,7 @@ public: private: void - writeMPTHoldersFromTransactions(model::LedgerData const& data); + writeMPTDataFromTransactions(model::LedgerData const& data); }; } // namespace etl::impl diff --git a/src/etl/impl/ext/Successor.cpp b/src/etl/impl/ext/Successor.cpp index 5bb012141..3a5481250 100644 --- a/src/etl/impl/ext/Successor.cpp +++ b/src/etl/impl/ext/Successor.cpp @@ -86,7 +86,7 @@ SuccessorExt::writeIncludedSuccessor(uint32_t seq, model::BookSuccessor const& s { auto firstBook = succ.firstBook; if (firstBook.empty()) - firstBook = uint256ToString(data::kLAST_KEY); + firstBook = uint256ToString(data::kLastKey); backend_->writeSuccessor(auto{succ.bookBase}, seq, std::move(firstBook)); } @@ -116,10 +116,10 @@ SuccessorExt::updateSuccessorFromCache(uint32_t seq, model::Object const& obj) c { auto const lb = cache_.get() .getPredecessor(obj.key, seq) - .value_or(data::LedgerObject{.key = data::kFIRST_KEY, .blob = {}}); + .value_or(data::LedgerObject{.key = data::kFirstKey, .blob = {}}); auto const ub = cache_.get() .getSuccessor(obj.key, seq) - .value_or(data::LedgerObject{.key = data::kLAST_KEY, .blob = {}}); + .value_or(data::LedgerObject{.key = data::kLastKey, .blob = {}}); auto checkBookBase = false; auto const isDeleted = obj.data.empty(); @@ -133,7 +133,7 @@ SuccessorExt::updateSuccessorFromCache(uint32_t seq, model::Object const& obj) c if (isDeleted) { auto const old = cache_.get().getDeleted(obj.key, seq - 1); - ASSERT(old.has_value(), "Deleted object {} must be in cache", ripple::strHex(obj.key)); + ASSERT(old.has_value(), "Deleted object {} must be in cache", xrpl::strHex(obj.key)); checkBookBase = isBookDir(obj.key, *old); // NOLINT(bugprone-unchecked-optional-access) } else { @@ -161,7 +161,7 @@ void SuccessorExt::updateBookSuccessor( std::optional const& maybeSuccessor, auto seq, - ripple::uint256 const& bookBase + xrpl::uint256 const& bookBase ) const { if (maybeSuccessor.has_value()) { @@ -169,16 +169,16 @@ SuccessorExt::updateBookSuccessor( uint256ToString(bookBase), seq, uint256ToString(maybeSuccessor->key) ); } else { - backend_->writeSuccessor(uint256ToString(bookBase), seq, uint256ToString(data::kLAST_KEY)); + backend_->writeSuccessor(uint256ToString(bookBase), seq, uint256ToString(data::kLastKey)); } } void SuccessorExt::writeSuccessors(uint32_t seq) const { - ripple::uint256 prev = data::kFIRST_KEY; + xrpl::uint256 prev = data::kFirstKey; while (auto cur = cache_.get().getSuccessor(prev, seq)) { - if (prev == data::kFIRST_KEY) + if (prev == data::kFirstKey) backend_->writeSuccessor(uint256ToString(prev), seq, uint256ToString(cur->key)); if (isBookDir(cur->key, cur->blob)) { @@ -187,9 +187,7 @@ SuccessorExt::writeSuccessors(uint32_t seq) const // make sure the base is not an actual object if (not cache_.get().get(base, seq)) { auto succ = cache_.get().getSuccessor(base, seq); - ASSERT( - succ.has_value(), "Book base {} must have a successor", ripple::strHex(base) - ); + ASSERT(succ.has_value(), "Book base {} must have a successor", xrpl::strHex(base)); if (succ->key == cur->key) // NOLINT(bugprone-unchecked-optional-access) backend_->writeSuccessor(uint256ToString(base), seq, uint256ToString(cur->key)); @@ -199,7 +197,7 @@ SuccessorExt::writeSuccessors(uint32_t seq) const prev = cur->key; } - backend_->writeSuccessor(uint256ToString(prev), seq, uint256ToString(data::kLAST_KEY)); + backend_->writeSuccessor(uint256ToString(prev), seq, uint256ToString(data::kLastKey)); } void @@ -207,7 +205,7 @@ SuccessorExt::writeEdgeKeys(std::uint32_t seq, auto const& edgeKeys) const { for (auto const& key : edgeKeys) { // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - auto succ = cache_.get().getSuccessor(*ripple::uint256::fromVoidChecked(key), seq); + auto succ = cache_.get().getSuccessor(*xrpl::uint256::fromVoidChecked(key), seq); if (succ) backend_->writeSuccessor(auto{key}, seq, uint256ToString(succ->key)); } diff --git a/src/etl/impl/ext/Successor.hpp b/src/etl/impl/ext/Successor.hpp index 7cc317af9..dbac88587 100644 --- a/src/etl/impl/ext/Successor.hpp +++ b/src/etl/impl/ext/Successor.hpp @@ -54,7 +54,7 @@ private: updateBookSuccessor( std::optional const& maybeSuccessor, auto seq, - ripple::uint256 const& bookBase + xrpl::uint256 const& bookBase ) const; void diff --git a/src/feed/SubscriptionManager.cpp b/src/feed/SubscriptionManager.cpp index d7893bb07..eeeba9f51 100644 --- a/src/feed/SubscriptionManager.cpp +++ b/src/feed/SubscriptionManager.cpp @@ -29,7 +29,7 @@ SubscriptionManager::unsubBookChanges(SubscriberSharedPtr const& subscriber) void SubscriptionManager::pubBookChanges( - ripple::LedgerHeader const& lgrInfo, + xrpl::LedgerHeader const& lgrInfo, std::vector const& transactions ) { @@ -55,7 +55,7 @@ SubscriptionManager::unsubProposedTransactions(SubscriberSharedPtr const& subscr void SubscriptionManager::subProposedAccount( - ripple::AccountID const& account, + xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber ) { @@ -68,7 +68,7 @@ SubscriptionManager::subProposedAccount( void SubscriptionManager::unsubProposedAccount( - ripple::AccountID const& account, + xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber ) { @@ -99,8 +99,8 @@ SubscriptionManager::unsubLedger(SubscriberSharedPtr const& subscriber) void SubscriptionManager::pubLedger( - ripple::LedgerHeader const& lgrInfo, - ripple::Fees const& fees, + xrpl::LedgerHeader const& lgrInfo, + xrpl::Fees const& fees, std::string const& ledgerRange, std::uint32_t const txnCount ) @@ -158,7 +158,7 @@ SubscriptionManager::unsubTransactions(SubscriberSharedPtr const& subscriber) void SubscriptionManager::subAccount( - ripple::AccountID const& account, + xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber ) { @@ -167,7 +167,7 @@ SubscriptionManager::subAccount( void SubscriptionManager::unsubAccount( - ripple::AccountID const& account, + xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber ) { @@ -175,13 +175,13 @@ SubscriptionManager::unsubAccount( } void -SubscriptionManager::subBook(ripple::Book const& book, SubscriberSharedPtr const& subscriber) +SubscriptionManager::subBook(xrpl::Book const& book, SubscriberSharedPtr const& subscriber) { transactionFeed_.sub(book, subscriber); } void -SubscriptionManager::unsubBook(ripple::Book const& book, SubscriberSharedPtr const& subscriber) +SubscriptionManager::unsubBook(xrpl::Book const& book, SubscriberSharedPtr const& subscriber) { transactionFeed_.unsub(book, subscriber); } @@ -189,7 +189,7 @@ SubscriptionManager::unsubBook(ripple::Book const& book, SubscriberSharedPtr con void SubscriptionManager::pubTransaction( data::TransactionAndMetadata const& txMeta, - ripple::LedgerHeader const& lgrInfo + xrpl::LedgerHeader const& lgrInfo ) { transactionFeed_.pub(txMeta, lgrInfo, backend_, amendmentCenter_, networkID_); diff --git a/src/feed/SubscriptionManager.hpp b/src/feed/SubscriptionManager.hpp index 5b4cdb79b..f7db99606 100644 --- a/src/feed/SubscriptionManager.hpp +++ b/src/feed/SubscriptionManager.hpp @@ -143,7 +143,7 @@ public: */ void pubBookChanges( - ripple::LedgerHeader const& lgrInfo, + xrpl::LedgerHeader const& lgrInfo, std::vector const& transactions ) final; @@ -168,10 +168,7 @@ public: * @param subscriber */ void - subProposedAccount( - ripple::AccountID const& account, - SubscriberSharedPtr const& subscriber - ) final; + subProposedAccount(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber) final; /** * @brief Unsubscribe to the proposed transactions feed for particular account. @@ -180,7 +177,7 @@ public: */ void unsubProposedAccount( - ripple::AccountID const& account, + xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber ) final; @@ -216,8 +213,8 @@ public: */ void pubLedger( - ripple::LedgerHeader const& lgrInfo, - ripple::Fees const& fees, + xrpl::LedgerHeader const& lgrInfo, + xrpl::Fees const& fees, std::string const& ledgerRange, std::uint32_t txnCount ) final; @@ -285,7 +282,7 @@ public: * @param subscriber */ void - subAccount(ripple::AccountID const& account, SubscriberSharedPtr const& subscriber) final; + subAccount(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber) final; /** * @brief Unsubscribe to the transactions feed for particular account. @@ -293,7 +290,7 @@ public: * @param subscriber The subscriber to unsubscribe */ void - unsubAccount(ripple::AccountID const& account, SubscriberSharedPtr const& subscriber) final; + unsubAccount(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber) final; /** * @brief Subscribe to the transactions feed, only receive feed when particular order book is @@ -302,7 +299,7 @@ public: * @param subscriber */ void - subBook(ripple::Book const& book, SubscriberSharedPtr const& subscriber) final; + subBook(xrpl::Book const& book, SubscriberSharedPtr const& subscriber) final; /** * @brief Unsubscribe to the transactions feed for particular order book. @@ -310,7 +307,7 @@ public: * @param subscriber */ void - unsubBook(ripple::Book const& book, SubscriberSharedPtr const& subscriber) final; + unsubBook(xrpl::Book const& book, SubscriberSharedPtr const& subscriber) final; /** * @brief Forward the transactions feed. @@ -320,7 +317,7 @@ public: void pubTransaction( data::TransactionAndMetadata const& txMeta, - ripple::LedgerHeader const& lgrInfo + xrpl::LedgerHeader const& lgrInfo ) final; /** diff --git a/src/feed/SubscriptionManagerInterface.hpp b/src/feed/SubscriptionManagerInterface.hpp index 2d07586e2..422f63946 100644 --- a/src/feed/SubscriptionManagerInterface.hpp +++ b/src/feed/SubscriptionManagerInterface.hpp @@ -53,7 +53,7 @@ public: */ virtual void pubBookChanges( - ripple::LedgerHeader const& lgrInfo, + xrpl::LedgerHeader const& lgrInfo, std::vector const& transactions ) = 0; @@ -78,7 +78,7 @@ public: * @param subscriber */ virtual void - subProposedAccount(ripple::AccountID const& account, SubscriberSharedPtr const& subscriber) = 0; + subProposedAccount(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber) = 0; /** * @brief Unsubscribe to the proposed transactions feed for particular account. @@ -86,10 +86,7 @@ public: * @param subscriber */ virtual void - unsubProposedAccount( - ripple::AccountID const& account, - SubscriberSharedPtr const& subscriber - ) = 0; + unsubProposedAccount(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber) = 0; /** * @brief Forward the proposed transactions feed. @@ -124,8 +121,8 @@ public: */ virtual void pubLedger( - ripple::LedgerHeader const& lgrInfo, - ripple::Fees const& fees, + xrpl::LedgerHeader const& lgrInfo, + xrpl::Fees const& fees, std::string const& ledgerRange, std::uint32_t txnCount ) = 0; @@ -193,7 +190,7 @@ public: * @param subscriber */ virtual void - subAccount(ripple::AccountID const& account, SubscriberSharedPtr const& subscriber) = 0; + subAccount(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber) = 0; /** * @brief Unsubscribe to the transactions feed for particular account. @@ -201,7 +198,7 @@ public: * @param subscriber The subscriber to unsubscribe */ virtual void - unsubAccount(ripple::AccountID const& account, SubscriberSharedPtr const& subscriber) = 0; + unsubAccount(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber) = 0; /** * @brief Subscribe to the transactions feed, only receive feed when particular order book is @@ -210,7 +207,7 @@ public: * @param subscriber */ virtual void - subBook(ripple::Book const& book, SubscriberSharedPtr const& subscriber) = 0; + subBook(xrpl::Book const& book, SubscriberSharedPtr const& subscriber) = 0; /** * @brief Unsubscribe to the transactions feed for particular order book. @@ -218,7 +215,7 @@ public: * @param subscriber */ virtual void - unsubBook(ripple::Book const& book, SubscriberSharedPtr const& subscriber) = 0; + unsubBook(xrpl::Book const& book, SubscriberSharedPtr const& subscriber) = 0; /** * @brief Forward the transactions feed. @@ -228,7 +225,7 @@ public: virtual void pubTransaction( data::TransactionAndMetadata const& txMeta, - ripple::LedgerHeader const& lgrInfo + xrpl::LedgerHeader const& lgrInfo ) = 0; /** diff --git a/src/feed/impl/BookChangesFeed.hpp b/src/feed/impl/BookChangesFeed.hpp index 87f0cc239..bff965f72 100644 --- a/src/feed/impl/BookChangesFeed.hpp +++ b/src/feed/impl/BookChangesFeed.hpp @@ -31,7 +31,7 @@ struct BookChangesFeed : public SingleFeedBase { * @param transactions The transactions that were included in the ledger. */ void - pub(ripple::LedgerHeader const& lgrInfo, + pub(xrpl::LedgerHeader const& lgrInfo, std::vector const& transactions) { SingleFeedBase::pub(boost::json::serialize(rpc::computeBookChanges(lgrInfo, transactions))); diff --git a/src/feed/impl/LedgerFeed.cpp b/src/feed/impl/LedgerFeed.cpp index 3454f66b4..3fe0172f4 100644 --- a/src/feed/impl/LedgerFeed.cpp +++ b/src/feed/impl/LedgerFeed.cpp @@ -22,8 +22,8 @@ namespace feed::impl { boost::json::object LedgerFeed::makeLedgerPubMessage( - ripple::LedgerHeader const& lgrInfo, - ripple::Fees const& fees, + xrpl::LedgerHeader const& lgrInfo, + xrpl::Fees const& fees, std::string const& ledgerRange, uint32_t const txnCount, uint32_t const networkID @@ -80,8 +80,8 @@ LedgerFeed::sub( void LedgerFeed::pub( - ripple::LedgerHeader const& lgrInfo, - ripple::Fees const& fees, + xrpl::LedgerHeader const& lgrInfo, + xrpl::Fees const& fees, std::string const& ledgerRange, uint32_t const txnCount, uint32_t const networkID diff --git a/src/feed/impl/LedgerFeed.hpp b/src/feed/impl/LedgerFeed.hpp index 9aa97bc3b..d66e72164 100644 --- a/src/feed/impl/LedgerFeed.hpp +++ b/src/feed/impl/LedgerFeed.hpp @@ -59,8 +59,8 @@ public: * @param networkID The network ID. */ void - pub(ripple::LedgerHeader const& lgrInfo, - ripple::Fees const& fees, + pub(xrpl::LedgerHeader const& lgrInfo, + xrpl::Fees const& fees, std::string const& ledgerRange, uint32_t txnCount, uint32_t networkID); @@ -68,8 +68,8 @@ public: private: static boost::json::object makeLedgerPubMessage( - ripple::LedgerHeader const& lgrInfo, - ripple::Fees const& fees, + xrpl::LedgerHeader const& lgrInfo, + xrpl::Fees const& fees, std::string const& ledgerRange, uint32_t txnCount, uint32_t networkID diff --git a/src/feed/impl/ProposedTransactionFeed.cpp b/src/feed/impl/ProposedTransactionFeed.cpp index 1b2d65412..db1194822 100644 --- a/src/feed/impl/ProposedTransactionFeed.cpp +++ b/src/feed/impl/ProposedTransactionFeed.cpp @@ -52,10 +52,7 @@ ProposedTransactionFeed::sub(SubscriberSharedPtr const& subscriber) } void -ProposedTransactionFeed::sub( - ripple::AccountID const& account, - SubscriberSharedPtr const& subscriber -) +ProposedTransactionFeed::sub(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber) { auto const added = accountSignal_.connectTrackableSlot( subscriber, account, ProposedTransactionSlot(*this, subscriber) @@ -78,7 +75,7 @@ ProposedTransactionFeed::unsub(SubscriberSharedPtr const& subscriber) void ProposedTransactionFeed::unsub( - ripple::AccountID const& account, + xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber ) { @@ -114,8 +111,7 @@ ProposedTransactionFeed::pub(boost::json::object const& receivedTxJson) auto const transaction = receivedTxJson.at(JS(transaction)).as_object(); auto const accounts = rpc::getAccountsFromTransaction(transaction); - auto affectedAccounts = - std::unordered_set(accounts.cbegin(), accounts.cend()); + auto affectedAccounts = std::unordered_set(accounts.cbegin(), accounts.cend()); [[maybe_unused]] auto task = strand_.execute([this, allVersionMsgs, affectedAccounts = std::move(affectedAccounts)]() { @@ -154,7 +150,7 @@ ProposedTransactionFeed::unsubInternal(SubscriberPtr subscriber) } void -ProposedTransactionFeed::unsubInternal(ripple::AccountID const& account, SubscriberPtr subscriber) +ProposedTransactionFeed::unsubInternal(xrpl::AccountID const& account, SubscriberPtr subscriber) { if (accountSignal_.disconnect(subscriber, account)) { LOG(logger_.info()) << subscriber->tag() << "Unsubscribed accounts_proposed " << account; diff --git a/src/feed/impl/ProposedTransactionFeed.hpp b/src/feed/impl/ProposedTransactionFeed.hpp index 517b0cdb8..d2b989529 100644 --- a/src/feed/impl/ProposedTransactionFeed.hpp +++ b/src/feed/impl/ProposedTransactionFeed.hpp @@ -62,7 +62,7 @@ class ProposedTransactionFeed { std::reference_wrapper subAllCount_; std::reference_wrapper subAccountCount_; - TrackableSignalMap accountSignal_; + TrackableSignalMap accountSignal_; TrackableSignal signal_; public: @@ -98,7 +98,7 @@ public: * @param account The account to watch. */ void - sub(ripple::AccountID const& account, SubscriberSharedPtr const& subscriber); + sub(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber); /** * @brief Unsubscribe to the proposed transaction feed. @@ -113,7 +113,7 @@ public: * @param account The account to unsubscribe. */ void - unsub(ripple::AccountID const& account, SubscriberSharedPtr const& subscriber); + unsub(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber); /** * @brief Publishes the proposed transaction feed. @@ -139,6 +139,6 @@ private: unsubInternal(SubscriberPtr subscriber); void - unsubInternal(ripple::AccountID const& account, SubscriberPtr subscriber); + unsubInternal(xrpl::AccountID const& account, SubscriberPtr subscriber); }; } // namespace feed::impl diff --git a/src/feed/impl/TransactionFeed.cpp b/src/feed/impl/TransactionFeed.cpp index 563450d9a..f8e60ed94 100644 --- a/src/feed/impl/TransactionFeed.cpp +++ b/src/feed/impl/TransactionFeed.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -68,7 +69,7 @@ TransactionFeed::sub(SubscriberSharedPtr const& subscriber) } void -TransactionFeed::sub(ripple::AccountID const& account, SubscriberSharedPtr const& subscriber) +TransactionFeed::sub(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber) { auto const added = accountSignal_.connectTrackableSlot( subscriber, account, TransactionSlot(*this, subscriber) @@ -95,10 +96,7 @@ TransactionFeed::subProposed(SubscriberSharedPtr const& subscriber) } void -TransactionFeed::subProposed( - ripple::AccountID const& account, - SubscriberSharedPtr const& subscriber -) +TransactionFeed::subProposed(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber) { auto const added = accountProposedSignal_.connectTrackableSlot( subscriber, account, TransactionSlot(*this, subscriber) @@ -111,7 +109,7 @@ TransactionFeed::subProposed( } void -TransactionFeed::sub(ripple::Book const& book, SubscriberSharedPtr const& subscriber) +TransactionFeed::sub(xrpl::Book const& book, SubscriberSharedPtr const& subscriber) { auto const added = bookSignal_.connectTrackableSlot(subscriber, book, TransactionSlot(*this, subscriber)); @@ -131,7 +129,7 @@ TransactionFeed::unsub(SubscriberSharedPtr const& subscriber) } void -TransactionFeed::unsub(ripple::AccountID const& account, SubscriberSharedPtr const& subscriber) +TransactionFeed::unsub(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber) { unsubInternal(account, subscriber.get()); } @@ -144,7 +142,7 @@ TransactionFeed::unsubProposed(SubscriberSharedPtr const& subscriber) void TransactionFeed::unsubProposed( - ripple::AccountID const& account, + xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber ) { @@ -152,7 +150,7 @@ TransactionFeed::unsubProposed( } void -TransactionFeed::unsub(ripple::Book const& book, SubscriberSharedPtr const& subscriber) +TransactionFeed::unsub(xrpl::Book const& book, SubscriberSharedPtr const& subscriber) { unsubInternal(book, subscriber.get()); } @@ -178,7 +176,7 @@ TransactionFeed::bookSubCount() const void TransactionFeed::pub( data::TransactionAndMetadata const& txMeta, - ripple::LedgerHeader const& lgrInfo, + xrpl::LedgerHeader const& lgrInfo, std::shared_ptr const& backend, std::shared_ptr const& amendmentCenter, uint32_t const networkID @@ -186,12 +184,12 @@ TransactionFeed::pub( { auto [tx, meta] = rpc::deserializeTxPlusMeta(txMeta, lgrInfo.seq); - std::optional ownerFunds; + std::optional ownerFunds; - if (tx->getTxnType() == ripple::ttOFFER_CREATE) { - auto const account = tx->getAccountID(ripple::sfAccount); - auto const amount = tx->getFieldAmount(ripple::sfTakerGets); - if (account != amount.issue().account) { + if (tx->getTxnType() == xrpl::ttOFFER_CREATE) { + auto const account = tx->getAccountID(xrpl::sfAccount); + auto const amount = tx->getFieldAmount(xrpl::sfTakerGets); + if (account != amount.get().account) { auto fetchFundsSynchronous = [&]() { data::synchronous([&](boost::asio::yield_context yield) { ownerFunds = rpc::accountFunds( @@ -215,8 +213,8 @@ TransactionFeed::pub( rpc::insertDeliverMaxAlias(txnPubobj, version); rpc::insertMPTIssuanceID(txnPubobj, tx, metaPubobj, meta); - Json::Value nftJson; - ripple::RPC::insertNFTSyntheticInJson(nftJson, tx, *meta); + json::Value nftJson; + xrpl::RPC::insertNFTSyntheticInJson(nftJson, tx, *meta); auto const nftBoostJson = rpc::toBoostJson(nftJson).as_object(); if (nftBoostJson.contains(JS(meta)) && nftBoostJson.at(JS(meta)).is_object()) { auto& metaObjInPub = pubObj.at(JS(meta)).as_object(); @@ -240,10 +238,10 @@ TransactionFeed::pub( pubObj[JS(type)] = "transaction"; pubObj[JS(validated)] = true; pubObj[JS(status)] = "closed"; - pubObj[JS(close_time_iso)] = ripple::to_string_iso(lgrInfo.closeTime); + pubObj[JS(close_time_iso)] = xrpl::toStringIso(lgrInfo.closeTime); pubObj[JS(ledger_index)] = lgrInfo.seq; - pubObj[JS(ledger_hash)] = ripple::strHex(lgrInfo.hash); + pubObj[JS(ledger_hash)] = xrpl::strHex(lgrInfo.hash); if (version >= 2u) { if (pubObj[txKey].as_object().contains(JS(hash))) { pubObj[JS(hash)] = pubObj[txKey].as_object()[JS(hash)]; @@ -255,7 +253,7 @@ TransactionFeed::pub( pubObj[JS(engine_result_code)] = meta->getResult(); std::string token; std::string human; - ripple::transResultInfo(meta->getResultTER(), token, human); + xrpl::transResultInfo(meta->getResultTER(), token, human); pubObj[JS(engine_result)] = token; pubObj[JS(engine_result_message)] = human; @@ -270,36 +268,36 @@ TransactionFeed::pub( ); auto const affectedAccountsFlat = meta->getAffectedAccounts(); - auto affectedAccounts = std::unordered_set( + auto affectedAccounts = std::unordered_set( affectedAccountsFlat.cbegin(), affectedAccountsFlat.cend() ); - std::unordered_set affectedBooks; + std::unordered_set affectedBooks; for (auto const& node : meta->getNodes()) { - if (node.getFieldU16(ripple::sfLedgerEntryType) == ripple::ltOFFER) { - ripple::SField const* field = nullptr; + if (node.getFieldU16(xrpl::sfLedgerEntryType) == xrpl::ltOFFER) { + xrpl::SField const* field = nullptr; // We need a field that contains the TakerGets and TakerPays // parameters. - if (node.getFName() == ripple::sfModifiedNode) { - field = &ripple::sfPreviousFields; - } else if (node.getFName() == ripple::sfCreatedNode) { - field = &ripple::sfNewFields; - } else if (node.getFName() == ripple::sfDeletedNode) { - field = &ripple::sfFinalFields; + if (node.getFName() == xrpl::sfModifiedNode) { + field = &xrpl::sfPreviousFields; + } else if (node.getFName() == xrpl::sfCreatedNode) { + field = &xrpl::sfNewFields; + } else if (node.getFName() == xrpl::sfDeletedNode) { + field = &xrpl::sfFinalFields; } if (field != nullptr) { - auto const data = dynamic_cast(node.peekAtPField(*field)); + auto const data = dynamic_cast(node.peekAtPField(*field)); - if ((data != nullptr) && data->isFieldPresent(ripple::sfTakerPays) && - data->isFieldPresent(ripple::sfTakerGets)) { + if ((data != nullptr) && data->isFieldPresent(xrpl::sfTakerPays) && + data->isFieldPresent(xrpl::sfTakerGets)) { // determine the OrderBook - ripple::Book const book{ - data->getFieldAmount(ripple::sfTakerGets).issue(), - data->getFieldAmount(ripple::sfTakerPays).issue(), - (*data)[~ripple::sfDomainID] + xrpl::Book const book{ + data->getFieldAmount(xrpl::sfTakerGets).get(), + data->getFieldAmount(xrpl::sfTakerPays).get(), + (*data)[~xrpl::sfDomainID] }; if (!affectedBooks.contains(book)) { affectedBooks.insert(book); @@ -345,7 +343,7 @@ TransactionFeed::unsubInternal(SubscriberPtr subscriber) } void -TransactionFeed::unsubInternal(ripple::AccountID const& account, SubscriberPtr subscriber) +TransactionFeed::unsubInternal(xrpl::AccountID const& account, SubscriberPtr subscriber) { if (accountSignal_.disconnect(subscriber, account)) { LOG(logger_.info()) << subscriber->tag() << "Unsubscribed account " << account; @@ -360,13 +358,13 @@ TransactionFeed::unsubProposedInternal(SubscriberPtr subscriber) } void -TransactionFeed::unsubProposedInternal(ripple::AccountID const& account, SubscriberPtr subscriber) +TransactionFeed::unsubProposedInternal(xrpl::AccountID const& account, SubscriberPtr subscriber) { accountProposedSignal_.disconnect(subscriber, account); } void -TransactionFeed::unsubInternal(ripple::Book const& book, SubscriberPtr subscriber) +TransactionFeed::unsubInternal(xrpl::Book const& book, SubscriberPtr subscriber) { if (bookSignal_.disconnect(subscriber, book)) { LOG(logger_.info()) << subscriber->tag() << "Unsubscribed book " << book; diff --git a/src/feed/impl/TransactionFeed.hpp b/src/feed/impl/TransactionFeed.hpp index d55bc0d01..e1740ca56 100644 --- a/src/feed/impl/TransactionFeed.hpp +++ b/src/feed/impl/TransactionFeed.hpp @@ -54,14 +54,14 @@ class TransactionFeed { std::reference_wrapper subAccountCount_; std::reference_wrapper subBookCount_; - TrackableSignalMap const&> + TrackableSignalMap const&> accountSignal_; - TrackableSignalMap const&> + TrackableSignalMap const&> bookSignal_; TrackableSignal const&> signal_; // Signals for proposed tx subscribers - TrackableSignalMap const&> + TrackableSignalMap const&> accountProposedSignal_; TrackableSignal const&> txProposedSignal_; @@ -100,7 +100,7 @@ public: * @param account The account to watch. */ void - sub(ripple::AccountID const& account, SubscriberSharedPtr const& subscriber); + sub(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber); /** * @brief Subscribe to the transaction feed, only receive the feed when particular order book is @@ -109,7 +109,7 @@ public: * @param book The order book to watch. */ void - sub(ripple::Book const& book, SubscriberSharedPtr const& subscriber); + sub(xrpl::Book const& book, SubscriberSharedPtr const& subscriber); /** * @brief Subscribe to the transaction feed for proposed transaction stream. @@ -125,7 +125,7 @@ public: * @param account The account to watch. */ void - subProposed(ripple::AccountID const& account, SubscriberSharedPtr const& subscriber); + subProposed(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber); /** * @brief Unsubscribe to the transaction feed. @@ -140,7 +140,7 @@ public: * @param account The account to unsubscribe. */ void - unsub(ripple::AccountID const& account, SubscriberSharedPtr const& subscriber); + unsub(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber); /** * @brief Unsubscribe to the transaction feed for proposed transaction stream. @@ -155,7 +155,7 @@ public: * @param account The account to unsubscribe. */ void - unsubProposed(ripple::AccountID const& account, SubscriberSharedPtr const& subscriber); + unsubProposed(xrpl::AccountID const& account, SubscriberSharedPtr const& subscriber); /** * @brief Unsubscribe to the transaction feed for particular order book. @@ -163,7 +163,7 @@ public: * @param book The book to unsubscribe. */ void - unsub(ripple::Book const& book, SubscriberSharedPtr const& subscriber); + unsub(xrpl::Book const& book, SubscriberSharedPtr const& subscriber); /** * @brief Publishes the transaction feed. @@ -174,7 +174,7 @@ public: */ void pub(data::TransactionAndMetadata const& txMeta, - ripple::LedgerHeader const& lgrInfo, + xrpl::LedgerHeader const& lgrInfo, std::shared_ptr const& backend, std::shared_ptr const& amendmentCenter, uint32_t networkID); @@ -202,15 +202,15 @@ private: unsubInternal(SubscriberPtr subscriber); void - unsubInternal(ripple::AccountID const& account, SubscriberPtr subscriber); + unsubInternal(xrpl::AccountID const& account, SubscriberPtr subscriber); void unsubProposedInternal(SubscriberPtr subscriber); void - unsubProposedInternal(ripple::AccountID const& account, SubscriberPtr subscriber); + unsubProposedInternal(xrpl::AccountID const& account, SubscriberPtr subscriber); void - unsubInternal(ripple::Book const& book, SubscriberPtr subscriber); + unsubInternal(xrpl::Book const& book, SubscriberPtr subscriber); }; } // namespace feed::impl diff --git a/src/main/CMakeLists.txt b/src/main/CMakeLists.txt index 6ef5b0bc0..202dd2428 100644 --- a/src/main/CMakeLists.txt +++ b/src/main/CMakeLists.txt @@ -3,21 +3,9 @@ add_executable(clio_server) target_sources(clio_server PRIVATE Main.cpp) target_link_libraries(clio_server PRIVATE clio_app) -if(static) - if(san) - message(FATAL_ERROR "Static linkage not allowed when using sanitizers") - elseif(is_appleclang) - message(FATAL_ERROR "Static linkage not supported on AppleClang") - else() - target_link_options( - # Note: -static-libstdc++ can statically link both libstdc++ and libc++ - clio_server - PRIVATE -static-libstdc++ -static-libgcc - ) - endif() -endif() - set_target_properties( clio_server PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} ) + +patch_nix_binary(clio_server) diff --git a/src/migration/MigratiorStatus.hpp b/src/migration/MigratiorStatus.hpp index b36c8d079..821d6bb1a 100644 --- a/src/migration/MigratiorStatus.hpp +++ b/src/migration/MigratiorStatus.hpp @@ -62,7 +62,7 @@ public: private: static constexpr std::array(Status::NumStatuses)> - kSTATUS_STR_MAP = {"Migrated", "NotMigrated", "NotKnown"}; + kStatusStrMap = {"Migrated", "NotMigrated", "NotKnown"}; Status status_; }; diff --git a/src/migration/MigratorStatus.cpp b/src/migration/MigratorStatus.cpp index ff0b96a50..8d916b6fb 100644 --- a/src/migration/MigratorStatus.cpp +++ b/src/migration/MigratorStatus.cpp @@ -20,14 +20,14 @@ MigratorStatus::operator==(Status const& other) const std::string MigratorStatus::toString() const { - return kSTATUS_STR_MAP[static_cast(status_)]; + return kStatusStrMap[static_cast(status_)]; } MigratorStatus MigratorStatus::fromString(std::string const& statusStr) { - for (std::size_t i = 0; i < kSTATUS_STR_MAP.size(); ++i) { - if (statusStr == kSTATUS_STR_MAP[i]) { + for (std::size_t i = 0; i < kStatusStrMap.size(); ++i) { + if (statusStr == kStatusStrMap[i]) { return MigratorStatus(static_cast(i)); } } diff --git a/src/migration/README.md b/src/migration/README.md index 93ace4197..580b53433 100644 --- a/src/migration/README.md +++ b/src/migration/README.md @@ -34,11 +34,11 @@ A migrator satisfies the `MigratorSpec`(impl/Spec.hpp) concept. It contains: -- A `kNAME` which will be used to identify the migrator. User will refer this migrator in command-line tool by this name. The name needs to be different with other migrators, otherwise a compilation error will be raised. +- A `kName` which will be used to identify the migrator. User will refer this migrator in command-line tool by this name. The name needs to be different with other migrators, otherwise a compilation error will be raised. -- A `kDESCRIPTION` which is the detail information of the migrator. +- A `kDescription` which is the detail information of the migrator. -- An optional `kCAN_BLOCK_CLIO` which indicates whether the migrator can block the Clio server. If it's absent, the migrator can't block server. If there is a blocking migrator not completed, the Clio server will fail to start. +- An optional `kCanBlockClio` which indicates whether the migrator can block the Clio server. If it's absent, the migrator can't block server. If there is a blocking migrator not completed, the Clio server will fail to start. - A static function `runMigration`, it will be called when user run `--migrate name`. It accepts two parameters: backend, which provides the DB operations interface, and cfg, which provides migration-related configuration. Each migrator can have its own configuration under `.migration` session. @@ -63,8 +63,8 @@ If you need to do full scan against other table, you can follow below steps: - Describe the table which needs full scan in a struct. It has to satisfy the `TableSpec`(cassandra/Spec.hpp) concept, containing static member: - Tuple type `Row`, it's the type of each field in a row. The order of types should match what database will return in a row. Key types should come first, followed by other field types sorted in alphabetical order. - - `kPARTITION_KEY`, it's the name of the partition key of the table. - - `kTABLE_NAME` + - `kPartitionKey`, it's the name of the partition key of the table. + - `kTableName` - Inherent from `FullTableScannerAdapterBase`. - Implement `onRowRead`, its parameter is the `Row` we defined. It's the callback function when a row is read. diff --git a/src/migration/cassandra/CassandraMigrationBackend.hpp b/src/migration/cassandra/CassandraMigrationBackend.hpp index 2930b8de9..33a15f474 100644 --- a/src/migration/cassandra/CassandraMigrationBackend.hpp +++ b/src/migration/cassandra/CassandraMigrationBackend.hpp @@ -60,24 +60,24 @@ public: ) { LOG(log_.debug()) << "Travsering token range: " << start << " - " << end - << " ; table: " << TableDesc::kTABLE_NAME; + << " ; table: " << TableDesc::kTableName; // for each table we only have one prepared statement - static auto kSTATEMENT_PREPARED = migrationSchema_.getPreparedFullScanStatement( - handle_, TableDesc::kTABLE_NAME, TableDesc::kPARTITION_KEY + static auto kStatementPrepared = migrationSchema_.getPreparedFullScanStatement( + handle_, TableDesc::kTableName, TableDesc::kPartitionKey ); - auto const statement = kSTATEMENT_PREPARED.bind(start, end); + auto const statement = kStatementPrepared.bind(start, end); auto const res = this->executor_.read(yield, statement); if (not res) { - LOG(log_.error()) << "Could not fetch data from table: " << TableDesc::kTABLE_NAME + LOG(log_.error()) << "Could not fetch data from table: " << TableDesc::kTableName << " range: " << start << " - " << end << ";" << res.error(); return; } auto const& results = res.value(); if (not results.hasRows()) { - LOG(log_.debug()) << "No rows returned - table: " << TableDesc::kTABLE_NAME + LOG(log_.debug()) << "No rows returned - table: " << TableDesc::kTableName << " range: " << start << " - " << end; return; } diff --git a/src/migration/cassandra/impl/CassandraMigrationSchema.hpp b/src/migration/cassandra/impl/CassandraMigrationSchema.hpp index 7ec85ee19..eb1bbb9f9 100644 --- a/src/migration/cassandra/impl/CassandraMigrationSchema.hpp +++ b/src/migration/cassandra/impl/CassandraMigrationSchema.hpp @@ -71,7 +71,7 @@ public: data::cassandra::PreparedStatement const& getPreparedInsertMigratedMigrator(data::cassandra::Handle const& handler) { - static auto kPREPARED = handler.prepare( + static auto kPrepared = handler.prepare( fmt::format( R"( INSERT INTO {} @@ -83,7 +83,7 @@ public: ) ) ); - return kPREPARED; + return kPrepared; } }; } // namespace migration::cassandra::impl diff --git a/src/migration/cassandra/impl/FullTableScanner.hpp b/src/migration/cassandra/impl/FullTableScanner.hpp index aba604f61..9cb0e39af 100644 --- a/src/migration/cassandra/impl/FullTableScanner.hpp +++ b/src/migration/cassandra/impl/FullTableScanner.hpp @@ -123,10 +123,10 @@ public: * @brief The full table scanner settings. */ struct FullTableScannerSettings { - std::uint32_t ctxThreadsNum; /**< number of threads used in the execution context */ - std::uint32_t jobsNum; /**< number of coroutines to run, it is the number of concurrent - database reads */ - std::uint32_t cursorsPerJob; /**< number of cursors per coroutine */ + std::uint32_t ctxThreadsNum; ///< number of threads used in the execution context + std::uint32_t jobsNum; ///< number of coroutines to run, it is the number of concurrent + ///< database reads + std::uint32_t cursorsPerJob; ///< number of cursors per coroutine }; /** diff --git a/src/migration/cassandra/impl/ObjectsAdapter.cpp b/src/migration/cassandra/impl/ObjectsAdapter.cpp index e95c29c80..47904a7da 100644 --- a/src/migration/cassandra/impl/ObjectsAdapter.cpp +++ b/src/migration/cassandra/impl/ObjectsAdapter.cpp @@ -17,7 +17,7 @@ ObjectsAdapter::onRowRead(TableObjectsDesc::Row const& row) onStateRead_(ledgerSeq, std::nullopt); return; } - ripple::SLE sle{ripple::SerialIter{blob.data(), blob.size()}, key}; + xrpl::SLE sle{xrpl::SerialIter{blob.data(), blob.size()}, key}; onStateRead_(ledgerSeq, std::make_optional(std::move(sle))); } diff --git a/src/migration/cassandra/impl/ObjectsAdapter.hpp b/src/migration/cassandra/impl/ObjectsAdapter.hpp index c8db88e66..e8938128b 100644 --- a/src/migration/cassandra/impl/ObjectsAdapter.hpp +++ b/src/migration/cassandra/impl/ObjectsAdapter.hpp @@ -22,9 +22,9 @@ namespace migration::cassandra::impl { * @brief The description of the objects table. It has to be a TableSpec. */ struct TableObjectsDesc { - using Row = std::tuple; - static constexpr char const* kPARTITION_KEY = "key"; - static constexpr char const* kTABLE_NAME = "objects"; + using Row = std::tuple; + static constexpr char const* kPartitionKey = "key"; + static constexpr char const* kTableName = "objects"; }; /** @@ -33,7 +33,7 @@ struct TableObjectsDesc { */ class ObjectsAdapter : public impl::FullTableScannerAdapterBase { public: - using OnStateRead = std::function)>; + using OnStateRead = std::function)>; /** * @brief Construct a new Objects Adapter object diff --git a/src/migration/cassandra/impl/Spec.hpp b/src/migration/cassandra/impl/Spec.hpp index 9daa12bc9..6e6426347 100644 --- a/src/migration/cassandra/impl/Spec.hpp +++ b/src/migration/cassandra/impl/Spec.hpp @@ -16,7 +16,7 @@ concept TableSpec = requires { requires std::tuple_size_v >= 0; // Ensures 'row' is a tuple // Check that static constexpr members 'partitionKey' and 'tableName' exist - { T::kPARTITION_KEY } -> std::convertible_to; - { T::kTABLE_NAME } -> std::convertible_to; + { T::kPartitionKey } -> std::convertible_to; + { T::kTableName } -> std::convertible_to; }; } // namespace migration::cassandra::impl diff --git a/src/migration/cassandra/impl/TransactionsAdapter.cpp b/src/migration/cassandra/impl/TransactionsAdapter.cpp index 7e2da4d82..b1c69c1f9 100644 --- a/src/migration/cassandra/impl/TransactionsAdapter.cpp +++ b/src/migration/cassandra/impl/TransactionsAdapter.cpp @@ -11,9 +11,9 @@ TransactionsAdapter::onRowRead(TableTransactionsDesc::Row const& row) { auto const& [txHash, date, ledgerSeq, metaBlob, txBlob] = row; - ripple::SerialIter it{txBlob.data(), txBlob.size()}; - ripple::STTx const sttx{it}; - ripple::TxMeta const txMeta{sttx.getTransactionID(), ledgerSeq, metaBlob}; + xrpl::SerialIter it{txBlob.data(), txBlob.size()}; + xrpl::STTx const sttx{it}; + xrpl::TxMeta const txMeta{sttx.getTransactionID(), ledgerSeq, metaBlob}; onTransactionRead_(sttx, txMeta); } } // namespace migration::cassandra::impl diff --git a/src/migration/cassandra/impl/TransactionsAdapter.hpp b/src/migration/cassandra/impl/TransactionsAdapter.hpp index 928e25862..bbb0b5a54 100644 --- a/src/migration/cassandra/impl/TransactionsAdapter.hpp +++ b/src/migration/cassandra/impl/TransactionsAdapter.hpp @@ -22,10 +22,9 @@ namespace migration::cassandra::impl { */ struct TableTransactionsDesc { // hash, date, ledger_seq, metadata, transaction - using Row = - std::tuple; - static constexpr char const* kPARTITION_KEY = "hash"; - static constexpr char const* kTABLE_NAME = "transactions"; + using Row = std::tuple; + static constexpr char const* kPartitionKey = "hash"; + static constexpr char const* kTableName = "transactions"; }; /** @@ -34,7 +33,7 @@ struct TableTransactionsDesc { */ class TransactionsAdapter : public impl::FullTableScannerAdapterBase { public: - using OnTransactionRead = std::function; + using OnTransactionRead = std::function; /** * @brief Construct a new Transactions Adapter object diff --git a/src/migration/impl/MigratorsRegister.hpp b/src/migration/impl/MigratorsRegister.hpp index 4f02910dc..b447e99dd 100644 --- a/src/migration/impl/MigratorsRegister.hpp +++ b/src/migration/impl/MigratorsRegister.hpp @@ -34,7 +34,7 @@ concept BackendMatchAllMigrators = (MigrationBackend && . template concept HasCanBlockClio = requires(T t) { - { t.kCAN_BLOCK_CLIO }; + { t.kCanBlockClio }; }; /** @@ -57,7 +57,7 @@ class MigratorsRegister { void callMigration(std::string const& name, util::config::ObjectView const& config) { - if (name == Migrator::kNAME) { + if (name == Migrator::kName) { LOG(log_.info()) << "Running migration: " << name; Migrator::runMigration(backend_, config); backend_->writeMigratorStatus( @@ -71,16 +71,16 @@ class MigratorsRegister { static constexpr std::string_view getDescriptionIfMatch(std::string_view targetName) { - return (T::kNAME == targetName) ? T::kDESCRIPTION : ""; + return (T::kName == targetName) ? T::kDescription : ""; } template static constexpr bool canBlockClioHelper(std::string_view targetName) { - if (targetName == First::kNAME) { + if (targetName == First::kName) { if constexpr (HasCanBlockClio) { - return First::kCAN_BLOCK_CLIO; + return First::kCanBlockClio; } return false; } @@ -168,7 +168,7 @@ public: [[nodiscard]] constexpr auto getMigratorNames() const { - return std::array{MigratorType::kNAME...}; + return std::array{MigratorType::kName...}; } /** diff --git a/src/migration/impl/Spec.hpp b/src/migration/impl/Spec.hpp index b41c9b7eb..28aafeeb9 100644 --- a/src/migration/impl/Spec.hpp +++ b/src/migration/impl/Spec.hpp @@ -15,11 +15,11 @@ namespace migration::impl { template concept MigratorSpec = requires(std::shared_ptr const& backend, util::config::ObjectView const& cfg) { - // Check that 'kNAME' exists and is a string - { T::kNAME } -> std::convertible_to; + // Check that 'kName' exists and is a string + { T::kName } -> std::convertible_to; - // Check that 'kDESCRIPTION' exists and is a string - { T::kDESCRIPTION } -> std::convertible_to; + // Check that 'kDescription' exists and is a string + { T::kDescription } -> std::convertible_to; // Check that the migrator specifies the backend type it supports typename T::Backend; diff --git a/src/rpc/AMMHelpers.cpp b/src/rpc/AMMHelpers.cpp index 2bffede1c..3dc6fcb58 100644 --- a/src/rpc/AMMHelpers.cpp +++ b/src/rpc/AMMHelpers.cpp @@ -10,21 +10,20 @@ #include #include #include -#include #include #include namespace rpc { -std::pair +std::pair getAmmPoolHolds( BackendInterface const& backend, data::AmendmentCenterInterface const& amendmentCenter, std::uint32_t sequence, - ripple::AccountID const& ammAccountID, - ripple::Issue const& issue1, - ripple::Issue const& issue2, + xrpl::AccountID const& ammAccountID, + xrpl::Issue const& issue1, + xrpl::Issue const& issue2, bool freezeHandling, boost::asio::yield_context yield ) @@ -52,39 +51,39 @@ getAmmPoolHolds( return std::make_pair(assetInBalance, assetOutBalance); } -ripple::STAmount +xrpl::STAmount getAmmLpHolds( BackendInterface const& backend, std::uint32_t sequence, - ripple::Currency const& cur1, - ripple::Currency const& cur2, - ripple::AccountID const& ammAccount, - ripple::AccountID const& lpAccount, + xrpl::Issue const& iss1, + xrpl::Issue const& iss2, + xrpl::AccountID const& ammAccount, + xrpl::AccountID const& lpAccount, boost::asio::yield_context yield ) { - auto const lptCurrency = ammLPTCurrency(cur1, cur2); + auto const lptCurrency = ammLPTCurrency(iss1, iss2); // not using accountHolds because we don't need to check if the associated tokens of the LP are // frozen return ammAccountHolds(backend, sequence, lpAccount, lptCurrency, ammAccount, true, yield); } -ripple::STAmount +xrpl::STAmount getAmmLpHolds( BackendInterface const& backend, std::uint32_t sequence, - ripple::SLE const& ammSle, - ripple::AccountID const& lpAccount, + xrpl::SLE const& ammSle, + xrpl::AccountID const& lpAccount, boost::asio::yield_context yield ) { return getAmmLpHolds( backend, sequence, - ammSle[ripple::sfAsset].get().currency, - ammSle[ripple::sfAsset2].get().currency, - ammSle[ripple::sfAccount], + ammSle[xrpl::sfAsset].get(), + ammSle[xrpl::sfAsset2].get(), + ammSle[xrpl::sfAccount], lpAccount, yield ); diff --git a/src/rpc/AMMHelpers.hpp b/src/rpc/AMMHelpers.hpp index 11857200c..02d6f8077 100644 --- a/src/rpc/AMMHelpers.hpp +++ b/src/rpc/AMMHelpers.hpp @@ -28,14 +28,14 @@ namespace rpc { * @param yield The coroutine context * @return The balances of the amm asset pair */ -std::pair +std::pair getAmmPoolHolds( BackendInterface const& backend, data::AmendmentCenterInterface const& amendmentCenter, std::uint32_t sequence, - ripple::AccountID const& ammAccountID, - ripple::Issue const& issue1, - ripple::Issue const& issue2, + xrpl::AccountID const& ammAccountID, + xrpl::Issue const& issue1, + xrpl::Issue const& issue2, bool freezeHandling, boost::asio::yield_context yield ); @@ -45,21 +45,21 @@ getAmmPoolHolds( * * @param backend The backend to use * @param sequence The sequence number to use - * @param cur1 The first currency - * @param cur2 The second currency + * @param iss1 The first issue + * @param iss2 The second issue * @param ammAccount The amm account * @param lpAccount The lp account * @param yield The coroutine context * @return The lp token balance */ -ripple::STAmount +xrpl::STAmount getAmmLpHolds( BackendInterface const& backend, std::uint32_t sequence, - ripple::Currency const& cur1, - ripple::Currency const& cur2, - ripple::AccountID const& ammAccount, - ripple::AccountID const& lpAccount, + xrpl::Issue const& iss1, + xrpl::Issue const& iss2, + xrpl::AccountID const& ammAccount, + xrpl::AccountID const& lpAccount, boost::asio::yield_context yield ); @@ -73,12 +73,12 @@ getAmmLpHolds( * @param yield The coroutine context * @return The lp token balance */ -ripple::STAmount +xrpl::STAmount getAmmLpHolds( BackendInterface const& backend, std::uint32_t sequence, - ripple::SLE const& ammSle, - ripple::AccountID const& lpAccount, + xrpl::SLE const& ammSle, + xrpl::AccountID const& lpAccount, boost::asio::yield_context yield ); diff --git a/src/rpc/BookChangesHelper.hpp b/src/rpc/BookChangesHelper.hpp index bc496a775..3eb1afeb4 100644 --- a/src/rpc/BookChangesHelper.hpp +++ b/src/rpc/BookChangesHelper.hpp @@ -37,13 +37,13 @@ namespace rpc { * @brief Represents an entry in the book_changes' changes array. */ struct BookChange { - ripple::STAmount sideAVolume; - ripple::STAmount sideBVolume; - ripple::STAmount highRate; - ripple::STAmount lowRate; - ripple::STAmount openRate; - ripple::STAmount closeRate; - std::optional domain; + xrpl::STAmount sideAVolume; + xrpl::STAmount sideBVolume; + xrpl::STAmount highRate; + xrpl::STAmount lowRate; + xrpl::STAmount openRate; + xrpl::STAmount closeRate; + std::optional domain; }; /** @@ -90,59 +90,59 @@ private: private: void - handleAffectedNode(ripple::STObject const& node) + handleAffectedNode(xrpl::STObject const& node) { auto const& metaType = node.getFName(); - auto const nodeType = node.getFieldU16(ripple::sfLedgerEntryType); + auto const nodeType = node.getFieldU16(xrpl::sfLedgerEntryType); - // we only care about ripple::ltOFFER objects being modified or + // we only care about xrpl::ltOFFER objects being modified or // deleted - if (nodeType != ripple::ltOFFER || metaType == ripple::sfCreatedNode) + if (nodeType != xrpl::ltOFFER || metaType == xrpl::sfCreatedNode) return; // if either FF or PF are missing we can't compute // but generally these are cancelled rather than crossed // so skipping them is consistent - if (!node.isFieldPresent(ripple::sfFinalFields) || - !node.isFieldPresent(ripple::sfPreviousFields)) + if (!node.isFieldPresent(xrpl::sfFinalFields) || + !node.isFieldPresent(xrpl::sfPreviousFields)) return; auto const& finalFields = - node.peekAtField(ripple::sfFinalFields).downcast(); + node.peekAtField(xrpl::sfFinalFields).downcast(); auto const& previousFields = - node.peekAtField(ripple::sfPreviousFields).downcast(); + node.peekAtField(xrpl::sfPreviousFields).downcast(); // defensive case that should never be hit - if (!finalFields.isFieldPresent(ripple::sfTakerGets) || - !finalFields.isFieldPresent(ripple::sfTakerPays) || - !previousFields.isFieldPresent(ripple::sfTakerGets) || - !previousFields.isFieldPresent(ripple::sfTakerPays)) + if (!finalFields.isFieldPresent(xrpl::sfTakerGets) || + !finalFields.isFieldPresent(xrpl::sfTakerPays) || + !previousFields.isFieldPresent(xrpl::sfTakerGets) || + !previousFields.isFieldPresent(xrpl::sfTakerPays)) return; // filter out any offers deleted by explicit offer cancels - if (metaType == ripple::sfDeletedNode && offerCancel_ && - finalFields.getFieldU32(ripple::sfSequence) == *offerCancel_) + if (metaType == xrpl::sfDeletedNode && offerCancel_ && + finalFields.getFieldU32(xrpl::sfSequence) == *offerCancel_) return; // compute the difference in gets and pays actually // affected onto the offer - auto const deltaGets = finalFields.getFieldAmount(ripple::sfTakerGets) - - previousFields.getFieldAmount(ripple::sfTakerGets); - auto const deltaPays = finalFields.getFieldAmount(ripple::sfTakerPays) - - previousFields.getFieldAmount(ripple::sfTakerPays); + auto const deltaGets = finalFields.getFieldAmount(xrpl::sfTakerGets) - + previousFields.getFieldAmount(xrpl::sfTakerGets); + auto const deltaPays = finalFields.getFieldAmount(xrpl::sfTakerPays) - + previousFields.getFieldAmount(xrpl::sfTakerPays); - transformAndStore(deltaGets, deltaPays, finalFields[~ripple::sfDomainID]); + transformAndStore(deltaGets, deltaPays, finalFields[~xrpl::sfDomainID]); } void transformAndStore( - ripple::STAmount const& deltaGets, - ripple::STAmount const& deltaPays, - std::optional const& domain + xrpl::STAmount const& deltaGets, + xrpl::STAmount const& deltaPays, + std::optional const& domain ) { - auto const g = to_string(deltaGets.issue()); - auto const p = to_string(deltaPays.issue()); + auto const g = to_string(deltaGets.get()); + auto const p = to_string(deltaPays.get()); auto const noswap = [&]() { if (isXRP(deltaGets)) @@ -154,15 +154,15 @@ private: auto second = noswap ? deltaPays : deltaGets; // defensively programmed, should (probably) never happen - if (second == beast::zero) + if (second == beast::kZero) return; - auto const rate = divide(first, second, ripple::noIssue()); + auto const rate = divide(first, second, xrpl::noIssue()); - if (first < beast::zero) + if (first < beast::kZero) first = -first; - if (second < beast::zero) + if (second < beast::kZero) second = -second; auto const key = noswap ? (g + '|' + p) : (p + '|' + g); @@ -197,24 +197,24 @@ private: handleBookChange(data::TransactionAndMetadata const& blob) { auto const [tx, meta] = rpc::deserializeTxPlusMeta(blob); - if (!tx || !meta || !tx->isFieldPresent(ripple::sfTransactionType)) + if (!tx || !meta || !tx->isFieldPresent(xrpl::sfTransactionType)) return; offerCancel_ = shouldCancelOffer(tx); - for (auto const& node : meta->getFieldArray(ripple::sfAffectedNodes)) + for (auto const& node : meta->getFieldArray(xrpl::sfAffectedNodes)) handleAffectedNode(node); } static std::optional - shouldCancelOffer(std::shared_ptr const& tx) + shouldCancelOffer(std::shared_ptr const& tx) { - switch (tx->getFieldU16(ripple::sfTransactionType)) { + switch (tx->getFieldU16(xrpl::sfTransactionType)) { // in future if any other ways emerge to cancel an offer // this switch makes them easy to add - case ripple::ttOFFER_CANCEL: - case ripple::ttOFFER_CREATE: - if (tx->isFieldPresent(ripple::sfOfferSequence)) - return tx->getFieldU32(ripple::sfOfferSequence); + case xrpl::ttOFFER_CANCEL: + case xrpl::ttOFFER_CREATE: + if (tx->isFieldPresent(xrpl::sfOfferSequence)) + return tx->getFieldU32(xrpl::sfOfferSequence); [[fallthrough]]; default: return std::nullopt; @@ -232,12 +232,12 @@ private: inline void tag_invoke(boost::json::value_from_tag, boost::json::value& jv, BookChange const& change) { - auto amountStr = [](ripple::STAmount const& amount) -> std::string { + auto amountStr = [](xrpl::STAmount const& amount) -> std::string { return isXRP(amount) ? to_string(amount.xrp()) : to_string(amount.iou()); }; - auto currencyStr = [](ripple::STAmount const& amount) -> std::string { - return isXRP(amount) ? "XRP_drops" : to_string(amount.issue()); + auto currencyStr = [](xrpl::STAmount const& amount) -> std::string { + return isXRP(amount) ? "XRP_drops" : to_string(amount.get()); }; jv = { @@ -252,7 +252,7 @@ tag_invoke(boost::json::value_from_tag, boost::json::value& jv, BookChange const }; if (change.domain.has_value()) - jv.as_object()[JS(domain)] = ripple::to_string(*change.domain); + jv.as_object()[JS(domain)] = xrpl::to_string(*change.domain); } /** @@ -264,7 +264,7 @@ tag_invoke(boost::json::value_from_tag, boost::json::value& jv, BookChange const */ [[nodiscard]] boost::json::object computeBookChanges( - ripple::LedgerHeader const& lgrInfo, + xrpl::LedgerHeader const& lgrInfo, std::vector const& transactions ); diff --git a/src/rpc/CMakeLists.txt b/src/rpc/CMakeLists.txt index a23ed71af..9691de44d 100644 --- a/src/rpc/CMakeLists.txt +++ b/src/rpc/CMakeLists.txt @@ -58,4 +58,4 @@ target_sources( handlers/VaultInfo.cpp ) -target_link_libraries(clio_rpc PRIVATE clio_util) +target_link_libraries(clio_rpc PUBLIC clio_util clio_data) diff --git a/src/rpc/Counters.hpp b/src/rpc/Counters.hpp index 641c6ecb3..c76d44597 100644 --- a/src/rpc/Counters.hpp +++ b/src/rpc/Counters.hpp @@ -116,23 +116,33 @@ public: void rpcFailedToForward(std::string const& method); - /** @brief Increments the global too busy counter. */ + /** + * @brief Increments the global too busy counter. + */ void onTooBusy(); - /** @brief Increments the global not ready counter. */ + /** + * @brief Increments the global not ready counter. + */ void onNotReady(); - /** @brief Increments the global bad syntax counter. */ + /** + * @brief Increments the global bad syntax counter. + */ void onBadSyntax(); - /** @brief Increments the global unknown command/method counter. */ + /** + * @brief Increments the global unknown command/method counter. + */ void onUnknownCommand(); - /** @brief Increments the global internal error counter. */ + /** + * @brief Increments the global internal error counter. + */ void onInternalError(); @@ -145,11 +155,15 @@ public: void recordLedgerRequest(boost::json::object const& params, std::uint32_t currentLedgerSequence); - /** @return Uptime of this instance in seconds. */ + /** + * @return Uptime of this instance in seconds. + */ std::chrono::seconds uptime() const; - /** @return A JSON report with current state of all counters for every method. */ + /** + * @return A JSON report with current state of all counters for every method. + */ boost::json::object report() const; }; diff --git a/src/rpc/CredentialHelpers.cpp b/src/rpc/CredentialHelpers.cpp index ca1cce187..2601cb03e 100644 --- a/src/rpc/CredentialHelpers.cpp +++ b/src/rpc/CredentialHelpers.cpp @@ -34,36 +34,36 @@ namespace rpc::credentials { bool -checkExpired(ripple::SLE const& sleCred, ripple::LedgerHeader const& ledger) +checkExpired(xrpl::SLE const& sleCred, xrpl::LedgerHeader const& ledger) { - if (sleCred.isFieldPresent(ripple::sfExpiration)) { - std::uint32_t const exp = sleCred.getFieldU32(ripple::sfExpiration); + if (sleCred.isFieldPresent(xrpl::sfExpiration)) { + std::uint32_t const exp = sleCred.getFieldU32(xrpl::sfExpiration); std::uint32_t const now = ledger.parentCloseTime.time_since_epoch().count(); return now > exp; } return false; } -std::set> -createAuthCredentials(ripple::STArray const& in) +std::set> +createAuthCredentials(xrpl::STArray const& in) { - std::set> out; + std::set> out; for (auto const& cred : in) - out.insert({cred[ripple::sfIssuer], cred[ripple::sfCredentialType]}); + out.insert({cred[xrpl::sfIssuer], cred[xrpl::sfCredentialType]}); return out; } -ripple::STArray +xrpl::STArray parseAuthorizeCredentials(boost::json::array const& jv) { - ripple::STArray arr; + xrpl::STArray arr; for (auto const& jo : jv) { ASSERT( jo.at(JS(issuer)).is_string(), "issuer must be string, should already be checked in AuthorizeCredentialValidator" ); - auto const issuer = ripple::parseBase58( + auto const issuer = xrpl::parseBase58( static_cast(jo.at(JS(issuer)).as_string()) ); ASSERT( @@ -77,18 +77,18 @@ parseAuthorizeCredentials(boost::json::array const& jv) "AuthorizeCredentialValidator" ); auto const credentialType = - ripple::strUnHex(static_cast(jo.at(JS(credential_type)).as_string())); + xrpl::strUnHex(static_cast(jo.at(JS(credential_type)).as_string())); ASSERT( credentialType.has_value(), "credential_type must be present, should already be checked in " "AuthorizeCredentialValidator." ); - auto credential = ripple::STObject::makeInnerObject(ripple::sfCredential); + auto credential = xrpl::STObject::makeInnerObject(xrpl::sfCredential); // NOLINTBEGIN(bugprone-unchecked-optional-access) - credential.setAccountID(ripple::sfIssuer, *issuer); - credential.setFieldVL(ripple::sfCredentialType, *credentialType); + credential.setAccountID(xrpl::sfIssuer, *issuer); + credential.setFieldVL(xrpl::sfCredentialType, *credentialType); // NOLINTEND(bugprone-unchecked-optional-access) arr.push_back(std::move(credential)); @@ -97,16 +97,16 @@ parseAuthorizeCredentials(boost::json::array const& jv) return arr; } -std::expected +std::expected fetchCredentialArray( std::optional const& credID, - ripple::AccountID const& srcAcc, + xrpl::AccountID const& srcAcc, BackendInterface const& backend, - ripple::LedgerHeader const& info, + xrpl::LedgerHeader const& info, boost::asio::yield_context const& yield ) { - ripple::STArray authCreds; + xrpl::STArray authCreds; std::unordered_set elems; for (auto const& elem : *credID) { // NOLINT(bugprone-unchecked-optional-access) ASSERT( @@ -114,41 +114,39 @@ fetchCredentialArray( ); if (elems.contains(elem.as_string())) - return Error{Status{RippledError::rpcBAD_CREDENTIALS, "duplicates in credentials."}}; + return Error{Status{RippledError::RpcBadCredentials, "duplicates in credentials."}}; elems.insert(elem.as_string()); - ripple::uint256 credHash; + xrpl::uint256 credHash; ASSERT( credHash.parseHex(boost::json::value_to(elem)), "should already be checked in validators.hpp that elem is a uint256 hex" ); - auto const credKeylet = ripple::keylet::credential(credHash).key; + auto const credKeylet = xrpl::keylet::credential(credHash).key; auto const credLedgerObject = backend.fetchLedgerObject(credKeylet, info.seq, yield); if (!credLedgerObject) - return Error{Status{RippledError::rpcBAD_CREDENTIALS, "credentials don't exist."}}; + return Error{Status{RippledError::RpcBadCredentials, "credentials don't exist."}}; - auto credIt = ripple::SerialIter{credLedgerObject->data(), credLedgerObject->size()}; - auto const sleCred = ripple::SLE{credIt, credKeylet}; + auto credIt = xrpl::SerialIter{credLedgerObject->data(), credLedgerObject->size()}; + auto const sleCred = xrpl::SLE{credIt, credKeylet}; - if ((sleCred.getType() != ripple::ltCREDENTIAL) || - ((sleCred.getFieldU32(ripple::sfFlags) & ripple::lsfAccepted) == 0u)) - return Error{Status{RippledError::rpcBAD_CREDENTIALS, "credentials aren't accepted"}}; + if ((sleCred.getType() != xrpl::ltCREDENTIAL) || + ((sleCred.getFieldU32(xrpl::sfFlags) & xrpl::lsfAccepted) == 0u)) + return Error{Status{RippledError::RpcBadCredentials, "credentials aren't accepted"}}; if (credentials::checkExpired(sleCred, info)) - return Error{Status{RippledError::rpcBAD_CREDENTIALS, "credentials are expired"}}; + return Error{Status{RippledError::RpcBadCredentials, "credentials are expired"}}; - if (sleCred.getAccountID(ripple::sfSubject) != srcAcc) { + if (sleCred.getAccountID(xrpl::sfSubject) != srcAcc) { return Error{Status{ - RippledError::rpcBAD_CREDENTIALS, "credentials don't belong to the root account" + RippledError::RpcBadCredentials, "credentials don't belong to the root account" }}; } - auto credential = ripple::STObject::makeInnerObject(ripple::sfCredential); - credential.setAccountID(ripple::sfIssuer, sleCred.getAccountID(ripple::sfIssuer)); - credential.setFieldVL( - ripple::sfCredentialType, sleCred.getFieldVL(ripple::sfCredentialType) - ); + auto credential = xrpl::STObject::makeInnerObject(xrpl::sfCredential); + credential.setAccountID(xrpl::sfIssuer, sleCred.getAccountID(xrpl::sfIssuer)); + credential.setFieldVL(xrpl::sfCredentialType, sleCred.getFieldVL(xrpl::sfCredentialType)); authCreds.push_back(std::move(credential)); } diff --git a/src/rpc/CredentialHelpers.hpp b/src/rpc/CredentialHelpers.hpp index 2091181de..1cf27e652 100644 --- a/src/rpc/CredentialHelpers.hpp +++ b/src/rpc/CredentialHelpers.hpp @@ -28,7 +28,7 @@ namespace rpc::credentials { * @return true if credential not expired, false otherwise */ bool -checkExpired(ripple::SLE const& sleCred, ripple::LedgerHeader const& ledger); +checkExpired(xrpl::SLE const& sleCred, xrpl::LedgerHeader const& ledger); /** * @brief Creates authentication credential field (which is a set of pairs of AccountID and @@ -37,8 +37,8 @@ checkExpired(ripple::SLE const& sleCred, ripple::LedgerHeader const& ledger); * @param in The array of Credential objects to check * @return Auth Credential array */ -std::set> -createAuthCredentials(ripple::STArray const& in); +std::set> +createAuthCredentials(xrpl::STArray const& in); /** * @brief Parses each credential object and makes sure the credential type and values are correct @@ -46,7 +46,7 @@ createAuthCredentials(ripple::STArray const& in); * @param jv The boost json array of credentials to parse * @return Array of credentials after parsing */ -ripple::STArray +xrpl::STArray parseAuthorizeCredentials(boost::json::array const& jv); /** @@ -59,12 +59,12 @@ parseAuthorizeCredentials(boost::json::array const& jv); * @param yield The coroutine context * @return Array of credential objects, error if failed otherwise */ -std::expected +std::expected fetchCredentialArray( std::optional const& credID, - ripple::AccountID const& srcAcc, + xrpl::AccountID const& srcAcc, BackendInterface const& backend, - ripple::LedgerHeader const& info, + xrpl::LedgerHeader const& info, boost::asio::yield_context const& yield ); diff --git a/src/rpc/Errors.cpp b/src/rpc/Errors.cpp index 393d77aae..f8ec37cfa 100644 --- a/src/rpc/Errors.cpp +++ b/src/rpc/Errors.cpp @@ -34,7 +34,7 @@ operator<<(std::ostream& stream, Status const& status) if (!status.message.empty()) { stream << ", Message: " << status.message; } else { - stream << ", Message: " << ripple::RPC::get_error_info(err).message; + stream << ", Message: " << xrpl::RPC::getErrorInfo(err).message; } }, [&stream, &status](ClioError err) { @@ -60,7 +60,7 @@ operator<<(std::ostream& stream, Status const& status) WarningInfo const& getWarningInfo(WarningCode code) { - static constexpr WarningInfo kINFOS[]{ + static constexpr WarningInfo kInfos[]{ {WarningCode::WarnUnknown, "Unknown warning"}, {WarningCode::WarnRpcClio, "This is a clio server. clio only serves validated data. If you want to talk to rippled, " @@ -74,7 +74,7 @@ getWarningInfo(WarningCode code) }; auto matchByCode = [code](auto const& info) { return info.code == code; }; - if (auto it = ranges::find_if(kINFOS, matchByCode); it != end(kINFOS)) + if (auto it = ranges::find_if(kInfos, matchByCode); it != end(kInfos)) return *it; throw(out_of_range("Invalid WarningCode")); @@ -93,7 +93,7 @@ makeWarning(WarningCode code) ClioErrorInfo const& getErrorInfo(ClioError code) { - static constexpr ClioErrorInfo kINFOS[]{ + static constexpr ClioErrorInfo kInfos[]{ {.code = ClioError::RpcMalformedCurrency, .error = "malformedCurrency", .message = "Malformed currency."}, @@ -150,7 +150,7 @@ getErrorInfo(ClioError code) }; auto matchByCode = [code](auto const& info) { return info.code == code; }; - if (auto it = ranges::find_if(kINFOS, matchByCode); it != end(kINFOS)) + if (auto it = ranges::find_if(kInfos, matchByCode); it != end(kInfos)) return *it; throw(out_of_range("Invalid error code")); @@ -164,11 +164,11 @@ makeError( ) { boost::json::object json; - auto const& info = ripple::RPC::get_error_info(err); + auto const& info = xrpl::RPC::getErrorInfo(err); - json["error"] = customError.value_or(info.token.c_str()).data(); + json["error"] = customError.value_or(info.token.cStr()).data(); json["error_code"] = static_cast(err); - json["error_message"] = customMessage.value_or(info.message.c_str()).data(); + json["error_message"] = customMessage.value_or(info.message.cStr()).data(); json["status"] = "error"; json["type"] = "response"; @@ -204,7 +204,7 @@ makeError(Status const& status) auto res = visit( util::OverloadSet{ [&status, &wrapOptional](RippledError err) { - if (err == ripple::rpcUNKNOWN) { + if (err == xrpl::RpcUnknown) { return boost::json::object{ {"error", status.message}, {"type", "response"}, {"status", "error"} }; diff --git a/src/rpc/Errors.hpp b/src/rpc/Errors.hpp index 5da04323e..8f69d8157 100644 --- a/src/rpc/Errors.hpp +++ b/src/rpc/Errors.hpp @@ -13,7 +13,9 @@ namespace rpc { -/** @brief Custom clio RPC Errors. */ +/** + * @brief Custom clio RPC Errors. + */ enum class ClioError { // normal clio errors start with 5000 RpcMalformedCurrency = 5000, @@ -24,7 +26,7 @@ enum class ClioError { RpcFieldNotFoundTransaction = 5006, RpcMalformedOracleDocumentId = 5007, RpcMalformedAuthorizedCredentials = 5008, - // NOTE: RpcEntryNotFound is replaced with RippledError::rpcENTRY_NOT_FOUND + // NOTE: RpcEntryNotFound is replaced with RippledError::RpcEntryNotFound // RpcEntryNotFound = 5009, // special system errors start with 6000 @@ -43,15 +45,19 @@ enum class ClioError { EtlInvalidResponse = 7003, }; -/** @brief Holds info about a particular @ref ClioError. */ +/** + * @brief Holds info about a particular @ref ClioError. + */ struct ClioErrorInfo { ClioError const code; std::string_view const error; std::string_view const message; }; -/** @brief Clio uses compatible Rippled error codes for most RPC errors. */ -using RippledError = ripple::error_code_i; +/** + * @brief Clio uses compatible Rippled error codes for most RPC errors. + */ +using RippledError = xrpl::ErrorCodeI; /** * @brief Clio operates on a combination of Rippled and Custom Clio error codes. @@ -61,9 +67,11 @@ using RippledError = ripple::error_code_i; */ using CombinedError = std::variant; -/** @brief A status returned from any RPC handler. */ +/** + * @brief A status returned from any RPC handler. + */ struct Status { - CombinedError code = RippledError::rpcSUCCESS; + CombinedError code = RippledError::RpcSuccess; std::string error; std::string message; std::optional extraInfo; @@ -94,7 +102,7 @@ struct Status { * * @param message The message */ - explicit Status(std::string message) : code(ripple::rpcUNKNOWN), message(std::move(message)) + explicit Status(std::string message) : code(xrpl::RpcUnknown), message(std::move(message)) { } @@ -131,7 +139,7 @@ struct Status { operator bool() const { if (auto err = std::get_if(&code)) - return *err != RippledError::rpcSUCCESS; + return *err != RippledError::RpcSuccess; return true; } @@ -177,7 +185,9 @@ struct Status { operator<<(std::ostream& stream, Status const& status); }; -/** @brief Warning codes that can be returned by clio. */ +/** + * @brief Warning codes that can be returned by clio. + */ // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) enum WarningCode { WarnUnknown = -1, @@ -187,7 +197,9 @@ enum WarningCode { WarnRpcDeprecated = 2004 }; -/** @brief Holds information about a clio warning. */ +/** + * @brief Holds information about a clio warning. + */ struct WarningInfo { constexpr WarningInfo() = default; @@ -205,7 +217,9 @@ struct WarningInfo { std::string_view const message = "unknown warning"; }; -/** @brief Invalid parameters error. */ +/** + * @brief Invalid parameters error. + */ class InvalidParamsError : public std::exception { std::string msg_; @@ -231,7 +245,9 @@ public: } }; -/** @brief Account not found error. */ +/** + * @brief Account not found error. + */ class AccountNotFoundError : public std::exception { std::string account_; @@ -257,7 +273,9 @@ public: } }; -/** @brief A globally available @ref rpc::Status that represents a successful state. */ +/** + * @brief A globally available @ref rpc::Status that represents a successful state. + */ static Status gOk; /** diff --git a/src/rpc/Factories.cpp b/src/rpc/Factories.cpp index 2dbc78cba..6badd0147 100644 --- a/src/rpc/Factories.cpp +++ b/src/rpc/Factories.cpp @@ -83,7 +83,7 @@ makeHttpContext( if (command == "subscribe" || command == "unsubscribe") { return Error{ - {RippledError::rpcBAD_SYNTAX, + {RippledError::RpcBadSyntax, "Subscribe and unsubscribe are only allowed for websocket."} }; } diff --git a/src/rpc/JS.hpp b/src/rpc/JS.hpp index ceb733d18..ec89f88ce 100644 --- a/src/rpc/JS.hpp +++ b/src/rpc/JS.hpp @@ -2,11 +2,17 @@ #include -/** @brief Helper macro for borrowing from ripple::jss static (J)son (S)trings. */ -#define JS(x) ripple::jss::x.c_str() +/** + * @brief Helper macro for borrowing from xrpl::jss static (J)son (S)trings. + */ +#define JS(x) xrpl::jss::x.cStr() -/** @brief Access the lower case copy of a static (J)son (S)tring. */ +/** + * @brief Access the lower case copy of a static (J)son (S)tring. + */ #define JSL(x) util::toLower(JS(x)) -/** @brief Provides access to (SF)ield name (S)trings. */ -#define SFS(x) ripple::x.jsonName.c_str() +/** + * @brief Provides access to (SF)ield name (S)trings. + */ +#define SFS(x) xrpl::x.jsonName.cStr() diff --git a/src/rpc/RPCCenter.cpp b/src/rpc/RPCCenter.cpp index 0ed3ff875..8280ded91 100644 --- a/src/rpc/RPCCenter.cpp +++ b/src/rpc/RPCCenter.cpp @@ -10,7 +10,7 @@ namespace { std::unordered_set const& handledRpcs() { - static std::unordered_set const kHANDLED_RPCS = { + static std::unordered_set const kHandledRpcs = { // clang-format off "account_channels", "account_currencies", @@ -52,13 +52,13 @@ handledRpcs() "version", // clang-format on }; - return kHANDLED_RPCS; + return kHandledRpcs; } std::unordered_set const& forwardedRpcs() { - static std::unordered_set const kFORWARDED_RPCS = { + static std::unordered_set const kForwardedRpcs = { "server_definitions", "server_state", "submit", @@ -73,7 +73,7 @@ forwardedRpcs() "simulate", "batch" }; - return kFORWARDED_RPCS; + return kForwardedRpcs; } } // namespace diff --git a/src/rpc/RPCEngine.hpp b/src/rpc/RPCEngine.hpp index a3e970d30..c6380ba9f 100644 --- a/src/rpc/RPCEngine.hpp +++ b/src/rpc/RPCEngine.hpp @@ -135,26 +135,26 @@ public: if (forwardingProxy_.shouldForward(ctx)) { // Disallow forwarding of the admin api, only user api is allowed for security reasons. if (isAdminCmd(ctx.method, ctx.params)) - return Result{Status{RippledError::rpcNO_PERMISSION}}; + return Result{Status{RippledError::RpcNoPermission}}; return forwardingProxy_.forward(ctx); } if (not ctx.isAdmin and responseCache_) { - if (auto res = responseCache_->get(ctx.method); res.has_value()) + if (auto res = responseCache_->get(ctx.method, ctx.params); res.has_value()) return Result{*std::move(res)}; } if (backend_->isTooBusy()) { LOG(log_.error()) << "Database is too busy. Rejecting request"; notifyTooBusy(); // TODO: should we add ctx.method if we have it? - return Result{Status{RippledError::rpcTOO_BUSY}}; + return Result{Status{RippledError::RpcTooBusy}}; } auto const method = handlerProvider_->getHandler(ctx.method); if (!method) { notifyUnknownCommand(); - return Result{Status{RippledError::rpcUNKNOWN_COMMAND}}; + return Result{Status{RippledError::RpcUnknownCommand}}; } try { @@ -174,7 +174,7 @@ public: if (not v) { notifyErrored(ctx.method); } else if (not ctx.isAdmin and responseCache_) { - responseCache_->put(ctx.method, v.result->as_object()); + responseCache_->put(ctx.method, ctx.params, v.result->as_object()); } return Result{std::move(v)}; @@ -182,12 +182,12 @@ public: LOG(log_.error()) << "Database timeout"; notifyTooBusy(); - return Result{Status{RippledError::rpcTOO_BUSY}}; + return Result{Status{RippledError::RpcTooBusy}}; } catch (std::exception const& ex) { LOG(log_.error()) << ctx.tag() << "Caught exception: " << ex.what(); notifyInternalError(); - return Result{Status{RippledError::rpcINTERNAL}}; + return Result{Status{RippledError::RpcInternal}}; } } @@ -333,13 +333,13 @@ private: if (backend_->isTooBusy()) { LOG(log_.error()) << "Database is too busy. Rejecting request"; notifyTooBusy(); // TODO: should we add ctx.method if we have it? - return Result{Status{RippledError::rpcTOO_BUSY}}; + return Result{Status{RippledError::RpcTooBusy}}; } auto const method = handlerProvider_->getHandler(ctx.method); if (!method) { notifyUnknownCommand(); - return Result{Status{RippledError::rpcUNKNOWN_COMMAND}}; + return Result{Status{RippledError::RpcUnknownCommand}}; } try { @@ -365,12 +365,12 @@ private: LOG(log_.error()) << "Database timeout"; notifyTooBusy(); - return Result{Status{RippledError::rpcTOO_BUSY}}; + return Result{Status{RippledError::RpcTooBusy}}; } catch (std::exception const& ex) { LOG(log_.error()) << ctx.tag() << "Caught exception: " << ex.what(); notifyInternalError(); - return Result{Status{RippledError::rpcINTERNAL}}; + return Result{Status{RippledError::RpcInternal}}; } } }; diff --git a/src/rpc/RPCHelpers.cpp b/src/rpc/RPCHelpers.cpp index 5a389f7e2..9b3600588 100644 --- a/src/rpc/RPCHelpers.cpp +++ b/src/rpc/RPCHelpers.cpp @@ -16,7 +16,6 @@ #include #include -#include #include #include #include @@ -88,7 +87,7 @@ namespace rpc { std::optional parseAccountCursor(std::optional jsonCursor) { - ripple::uint256 cursorIndex = beast::zero; + xrpl::uint256 cursorIndex = beast::kZero; std::uint64_t startHint = 0; if (!jsonCursor) @@ -116,17 +115,17 @@ parseAccountCursor(std::optional jsonCursor) return AccountCursor({.index = cursorIndex, .hint = startHint}); } -std::optional +std::optional getDeliveredAmount( - std::shared_ptr const& txn, - std::shared_ptr const& meta, + std::shared_ptr const& txn, + std::shared_ptr const& meta, std::uint32_t const ledgerSequence, uint32_t date ) { - if (meta->hasDeliveredAmount()) - return meta->getDeliveredAmount(); - if (txn->isFieldPresent(ripple::sfAmount)) { + if (auto const delivered = meta->getDeliveredAmount(); delivered.has_value()) + return delivered; + if (txn->isFieldPresent(xrpl::sfAmount)) { // Ledger 4594095 is the first ledger in which the DeliveredAmount field // was present when a partial payment was made and its absence indicates // that the amount delivered is listed in the Amount field. @@ -135,11 +134,10 @@ getDeliveredAmount( // then its absence indicates that the amount delivered is listed in the // Amount field. DeliveredAmount went live January 24, 2014. // 446000000 is in Feb 2014, well after DeliveredAmount went live - static constexpr std::uint32_t kFIRST_LEDGER_WITH_DELIVERED_AMOUNT = 4594095; - static constexpr std::uint32_t kDELIVERED_AMOUNT_LIVE_DATE = 446000000; - if (ledgerSequence >= kFIRST_LEDGER_WITH_DELIVERED_AMOUNT || - date > kDELIVERED_AMOUNT_LIVE_DATE) { - return txn->getFieldAmount(ripple::sfAmount); + static constexpr std::uint32_t kFirstLedgerWithDeliveredAmount = 4594095; + static constexpr std::uint32_t kDeliveredAmountLiveDate = 446000000; + if (ledgerSequence >= kFirstLedgerWithDeliveredAmount || date > kDeliveredAmountLiveDate) { + return txn->getFieldAmount(xrpl::sfAmount); } } return {}; @@ -147,55 +145,54 @@ getDeliveredAmount( bool canHaveDeliveredAmount( - std::shared_ptr const& txn, - std::shared_ptr const& meta + std::shared_ptr const& txn, + std::shared_ptr const& meta ) { - ripple::TxType const tt{txn->getTxnType()}; - if (tt != ripple::ttPAYMENT && tt != ripple::ttCHECK_CASH && tt != ripple::ttACCOUNT_DELETE) + xrpl::TxType const tt{txn->getTxnType()}; + if (tt != xrpl::ttPAYMENT && tt != xrpl::ttCHECK_CASH && tt != xrpl::ttACCOUNT_DELETE) return false; - return meta->getResultTER() == ripple::tesSUCCESS; + return meta->getResultTER() == xrpl::tesSUCCESS; } -std::optional +std::optional accountFromStringStrict(std::string const& account) { - auto blob = ripple::strUnHex(account); + auto blob = xrpl::strUnHex(account); - std::optional publicKey = {}; - if (blob && ripple::publicKeyType(ripple::makeSlice(*blob))) { - publicKey = ripple::PublicKey(ripple::Slice{blob->data(), blob->size()}); + std::optional publicKey = {}; + if (blob && xrpl::publicKeyType(xrpl::makeSlice(*blob))) { + publicKey = xrpl::PublicKey(xrpl::Slice{blob->data(), blob->size()}); } else { publicKey = - util::parseBase58Wrapper(ripple::TokenType::AccountPublic, account); + util::parseBase58Wrapper(xrpl::TokenType::AccountPublic, account); } - std::optional result; + std::optional result; if (publicKey) { - result = ripple::calcAccountID(*publicKey); + result = xrpl::calcAccountID(*publicKey); } else { - result = util::parseBase58Wrapper(account); + result = util::parseBase58Wrapper(account); } return result; } -std::pair, std::shared_ptr> +std::pair, std::shared_ptr> deserializeTxPlusMeta(data::TransactionAndMetadata const& blobs) { static util::Logger const log{"RPC"}; // NOLINT(readability-identifier-naming) try { - std::pair, std::shared_ptr> - result; + std::pair, std::shared_ptr> result; { - ripple::SerialIter s{blobs.transaction.data(), blobs.transaction.size()}; - result.first = std::make_shared(s); + xrpl::SerialIter s{blobs.transaction.data(), blobs.transaction.size()}; + result.first = std::make_shared(s); } { - ripple::SerialIter s{blobs.metadata.data(), blobs.metadata.size()}; - result.second = std::make_shared(s, ripple::sfMetadata); + xrpl::SerialIter s{blobs.metadata.data(), blobs.metadata.size()}; + result.second = std::make_shared(s, xrpl::sfMetadata); } return result; } catch (std::exception const& e) { @@ -211,22 +208,22 @@ deserializeTxPlusMeta(data::TransactionAndMetadata const& blobs) } } -std::pair, std::shared_ptr> +std::pair, std::shared_ptr> deserializeTxPlusMeta(data::TransactionAndMetadata const& blobs, std::uint32_t seq) { auto [tx, meta] = deserializeTxPlusMeta(blobs); - std::shared_ptr const m = - std::make_shared(tx->getTransactionID(), seq, *meta); + std::shared_ptr const m = + std::make_shared(tx->getTransactionID(), seq, *meta); return {tx, m}; } boost::json::object -toJson(ripple::STBase const& obj) +toJson(xrpl::STBase const& obj) { boost::json::value value = - boost::json::parse(obj.getJson(ripple::JsonOptions::none).toStyledString()); + boost::json::parse(obj.getJson(xrpl::JsonOptions::Values::None).toStyledString()); return value.as_object(); } @@ -240,15 +237,15 @@ toExpandedJson( ) { auto [txn, meta] = deserializeTxPlusMeta(blobs, blobs.ledgerSequence); - auto txnJson = toJson(*txn); - auto metaJson = toJson(*meta); + auto txnJson = rpc::toJson(*txn); + auto metaJson = rpc::toJson(*meta); insertDeliveredAmount(metaJson, txn, meta, blobs.date); insertDeliverMaxAlias(txnJson, apiVersion); insertMPTIssuanceID(txnJson, txn, metaJson, meta); if (nftEnabled == NFTokenjson::ENABLE) { - Json::Value nftJson; - ripple::RPC::insertNFTSyntheticInJson(nftJson, txn, *meta); + json::Value nftJson; + xrpl::RPC::insertNFTSyntheticInJson(nftJson, txn, *meta); // if there is no nft fields, the nftJson will be {"meta":null} auto const nftBoostJson = toBoostJson(nftJson).as_object(); if (nftBoostJson.contains(JS(meta)) and nftBoostJson.at(JS(meta)).is_object()) { @@ -270,15 +267,15 @@ toExpandedJson( std::optional encodeCTID(uint32_t ledgerSeq, uint16_t txnIndex, uint16_t networkId) noexcept { - static constexpr uint32_t kMAX_LEDGER_SEQ = 0x0FFF'FFFF; - static constexpr uint32_t kMAX_TXN_INDEX = 0xFFFF; - static constexpr uint32_t kMAX_NETWORK_ID = 0xFFFF; + static constexpr uint32_t kMaxLedgerSeq = 0x0FFF'FFFF; + static constexpr uint32_t kMaxTxnIndex = 0xFFFF; + static constexpr uint32_t kMaxNetworkId = 0xFFFF; - if (ledgerSeq > kMAX_LEDGER_SEQ || txnIndex > kMAX_TXN_INDEX || networkId > kMAX_NETWORK_ID) + if (ledgerSeq > kMaxLedgerSeq || txnIndex > kMaxTxnIndex || networkId > kMaxNetworkId) return {}; - static constexpr uint64_t kCTID_PREFIX = 0xC000'0000; - uint64_t const ctidValue = ((kCTID_PREFIX + static_cast(ledgerSeq)) << 32) + + static constexpr uint64_t kCtidPrefix = 0xC000'0000; + uint64_t const ctidValue = ((kCtidPrefix + static_cast(ledgerSeq)) << 32) + (static_cast(txnIndex) << 16) + networkId; return {fmt::format("{:016X}", ctidValue)}; @@ -287,15 +284,15 @@ encodeCTID(uint32_t ledgerSeq, uint16_t txnIndex, uint16_t networkId) noexcept bool insertDeliveredAmount( boost::json::object& metaJson, - std::shared_ptr const& txn, - std::shared_ptr const& meta, + std::shared_ptr const& txn, + std::shared_ptr const& meta, uint32_t date ) { if (canHaveDeliveredAmount(txn, meta)) { if (auto amt = getDeliveredAmount(txn, meta, meta->getLgrSeq(), date)) { metaJson["delivered_amount"] = - toBoostJson(amt->getJson(ripple::JsonOptions::include_date)); + toBoostJson(amt->getJson(xrpl::JsonOptions::Values::IncludeDate)); } else { metaJson["delivered_amount"] = "unavailable"; } @@ -310,18 +307,18 @@ insertDeliveredAmount( * @param meta The metadata * @return The mpt_issuance_id or std::nullopt if not available */ -static std::optional -getMPTIssuanceID(std::shared_ptr const& meta) +static std::optional +getMPTIssuanceID(std::shared_ptr const& meta) { - ripple::TxMeta const& transactionMeta = *meta; + xrpl::TxMeta const& transactionMeta = *meta; - for (ripple::STObject const& node : transactionMeta.getNodes()) { - if (node.getFieldU16(ripple::sfLedgerEntryType) != ripple::ltMPTOKEN_ISSUANCE || - node.getFName() != ripple::sfCreatedNode) + for (xrpl::STObject const& node : transactionMeta.getNodes()) { + if (node.getFieldU16(xrpl::sfLedgerEntryType) != xrpl::ltMPTOKEN_ISSUANCE || + node.getFName() != xrpl::sfCreatedNode) continue; - auto const& mptNode = node.peekAtField(ripple::sfNewFields).downcast(); - return ripple::makeMptID(mptNode[ripple::sfSequence], mptNode[ripple::sfIssuer]); + auto const& mptNode = node.peekAtField(xrpl::sfNewFields).downcast(); + return xrpl::makeMptID(mptNode[xrpl::sfSequence], mptNode[xrpl::sfIssuer]); } return {}; @@ -336,22 +333,22 @@ getMPTIssuanceID(std::shared_ptr const& meta) */ static bool canHaveMPTIssuanceID( - std::shared_ptr const& txn, - std::shared_ptr const& meta + std::shared_ptr const& txn, + std::shared_ptr const& meta ) { - if (txn->getTxnType() != ripple::ttMPTOKEN_ISSUANCE_CREATE) + if (txn->getTxnType() != xrpl::ttMPTOKEN_ISSUANCE_CREATE) return false; - return (meta->getResultTER() == ripple::tesSUCCESS); + return (meta->getResultTER() == xrpl::tesSUCCESS); } bool insertMPTIssuanceID( boost::json::object& txnJson, - std::shared_ptr const& txn, + std::shared_ptr const& txn, boost::json::object& metaJson, - std::shared_ptr const& meta + std::shared_ptr const& meta ) { if (!canHaveMPTIssuanceID(txn, meta)) @@ -366,9 +363,9 @@ insertMPTIssuanceID( // Otherwise, add it to txn json if (txnJson.contains(JS(TransactionType)) && txnJson.at(JS(TransactionType)).is_string() and txnJson.at(JS(TransactionType)).as_string() == JS(MPTokenIssuanceCreate)) { - metaJson[JS(mpt_issuance_id)] = ripple::to_string(*id); + metaJson[JS(mpt_issuance_id)] = xrpl::to_string(*id); } else { - txnJson[JS(mpt_issuance_id)] = ripple::to_string(*id); + txnJson[JS(mpt_issuance_id)] = xrpl::to_string(*id); } return true; @@ -386,16 +383,16 @@ insertDeliverMaxAlias(boost::json::object& txJson, std::uint32_t const apiVersio } boost::json::object -toJson(ripple::TxMeta const& meta) +toJson(xrpl::TxMeta const& meta) { boost::json::value value = - boost::json::parse(meta.getJson(ripple::JsonOptions::none).toStyledString()); + boost::json::parse(meta.getJson(xrpl::JsonOptions::Values::None).toStyledString()); return value.as_object(); } boost::json::value -toBoostJson(Json::Value const& value) +toBoostJson(json::Value const& value) { boost::json::value boostValue = boost::json::parse(value.toStyledString()); @@ -403,13 +400,13 @@ toBoostJson(Json::Value const& value) } boost::json::object -toJson(ripple::SLE const& sle) +toJson(xrpl::SLE const& sle) { boost::json::value value = - boost::json::parse(sle.getJson(ripple::JsonOptions::none).toStyledString()); - if (sle.getType() == ripple::ltACCOUNT_ROOT) { - if (sle.isFieldPresent(ripple::sfEmailHash)) { - auto const& hash = sle.getFieldH128(ripple::sfEmailHash); + boost::json::parse(sle.getJson(xrpl::JsonOptions::Values::None).toStyledString()); + if (sle.getType() == xrpl::ltACCOUNT_ROOT) { + if (sle.isFieldPresent(xrpl::sfEmailHash)) { + auto const& hash = sle.getFieldH128(xrpl::sfEmailHash); std::string md5 = strHex(hash); boost::algorithm::to_lower(md5); value.as_object()["urlgravatar"] = @@ -420,23 +417,23 @@ toJson(ripple::SLE const& sle) } boost::json::object -toJson(ripple::LedgerHeader const& lgrInfo, bool const binary, std::uint32_t const apiVersion) +toJson(xrpl::LedgerHeader const& lgrInfo, bool const binary, std::uint32_t const apiVersion) { boost::json::object header; if (binary) { - header[JS(ledger_data)] = ripple::strHex(ledgerHeaderToBlob(lgrInfo)); + header[JS(ledger_data)] = xrpl::strHex(ledgerHeaderToBlob(lgrInfo)); } else { - header[JS(account_hash)] = ripple::strHex(lgrInfo.accountHash); + header[JS(account_hash)] = xrpl::strHex(lgrInfo.accountHash); header[JS(close_flags)] = lgrInfo.closeFlags; header[JS(close_time)] = lgrInfo.closeTime.time_since_epoch().count(); - header[JS(close_time_human)] = ripple::to_string(lgrInfo.closeTime); + header[JS(close_time_human)] = xrpl::to_string(lgrInfo.closeTime); header[JS(close_time_resolution)] = lgrInfo.closeTimeResolution.count(); - header[JS(close_time_iso)] = ripple::to_string_iso(lgrInfo.closeTime); - header[JS(ledger_hash)] = ripple::strHex(lgrInfo.hash); + header[JS(close_time_iso)] = xrpl::toStringIso(lgrInfo.closeTime); + header[JS(ledger_hash)] = xrpl::strHex(lgrInfo.hash); header[JS(parent_close_time)] = lgrInfo.parentCloseTime.time_since_epoch().count(); - header[JS(parent_hash)] = ripple::strHex(lgrInfo.parentHash); - header[JS(total_coins)] = ripple::to_string(lgrInfo.drops); - header[JS(transaction_hash)] = ripple::strHex(lgrInfo.txHash); + header[JS(parent_hash)] = xrpl::strHex(lgrInfo.parentHash); + header[JS(total_coins)] = xrpl::to_string(lgrInfo.drops); + header[JS(transaction_hash)] = xrpl::strHex(lgrInfo.txHash); if (apiVersion < 2u) { header[JS(ledger_index)] = std::to_string(lgrInfo.seq); @@ -461,7 +458,7 @@ parseStringAsUInt(std::string const& value) return index; } -std::expected +std::expected ledgerHeaderFromRequest( std::shared_ptr const& backend, web::Context const& ctx @@ -471,16 +468,16 @@ ledgerHeaderFromRequest( if (!hashValue.is_null()) { if (!hashValue.is_string()) - return std::unexpected{Status{RippledError::rpcINVALID_PARAMS, "ledgerHashNotString"}}; + return std::unexpected{Status{RippledError::RpcInvalidParams, "ledgerHashNotString"}}; - ripple::uint256 ledgerHash; + xrpl::uint256 ledgerHash; if (!ledgerHash.parseHex(boost::json::value_to(hashValue))) - return std::unexpected{Status{RippledError::rpcINVALID_PARAMS, "ledgerHashMalformed"}}; + return std::unexpected{Status{RippledError::RpcInvalidParams, "ledgerHashMalformed"}}; auto lgrInfo = backend->fetchLedgerByHash(ledgerHash, ctx.yield); if (!lgrInfo || lgrInfo->seq > ctx.range.maxSequence) - return std::unexpected{Status{RippledError::rpcLGR_NOT_FOUND, "ledgerNotFound"}}; + return std::unexpected{Status{RippledError::RpcLgrNotFound, "ledgerNotFound"}}; return *lgrInfo; } @@ -504,18 +501,18 @@ ledgerHeaderFromRequest( } if (!ledgerSequence) - return std::unexpected{Status{RippledError::rpcINVALID_PARAMS, "ledgerIndexMalformed"}}; + return std::unexpected{Status{RippledError::RpcInvalidParams, "ledgerIndexMalformed"}}; auto lgrInfo = backend->fetchLedgerBySequence(*ledgerSequence, ctx.yield); if (!lgrInfo || lgrInfo->seq > ctx.range.maxSequence) - return std::unexpected{Status{RippledError::rpcLGR_NOT_FOUND, "ledgerNotFound"}}; + return std::unexpected{Status{RippledError::RpcLgrNotFound, "ledgerNotFound"}}; return *lgrInfo; } // extract ledgerHeaderFromRequest's parameter from context -std::expected +std::expected getLedgerHeaderFromHashOrSeq( BackendInterface const& backend, boost::asio::yield_context yield, @@ -524,12 +521,12 @@ getLedgerHeaderFromHashOrSeq( uint32_t maxSeq ) { - std::optional lgrInfo; - auto const err = std::unexpected{Status{RippledError::rpcLGR_NOT_FOUND, "ledgerNotFound"}}; + std::optional lgrInfo; + auto const err = std::unexpected{Status{RippledError::RpcLgrNotFound, "ledgerNotFound"}}; if (ledgerHash) { // invoke uint256's constructor to parse the hex string , instead of // copying buffer - ripple::uint256 const ledgerHash256{std::string_view(*ledgerHash)}; + xrpl::uint256 const ledgerHash256{std::string_view(*ledgerHash)}; lgrInfo = backend.fetchLedgerByHash(ledgerHash256, yield); if (!lgrInfo || lgrInfo->seq > maxSeq) return err; @@ -549,9 +546,9 @@ getLedgerHeaderFromHashOrSeq( } std::vector -ledgerHeaderToBlob(ripple::LedgerHeader const& info, bool includeHash) +ledgerHeaderToBlob(xrpl::LedgerHeader const& info, bool includeHash) { - ripple::Serializer s; + xrpl::Serializer s; s.add32(info.seq); s.add64(info.drops.drops()); s.addBitString(info.parentHash); @@ -567,20 +564,20 @@ ledgerHeaderToBlob(ripple::LedgerHeader const& info, bool includeHash) } std::uint64_t -getStartHint(ripple::SLE const& sle, ripple::AccountID const& accountID) +getStartHint(xrpl::SLE const& sle, xrpl::AccountID const& accountID) { - if (sle.getType() == ripple::ltRIPPLE_STATE) { - if (sle.getFieldAmount(ripple::sfLowLimit).getIssuer() == accountID) { - return sle.getFieldU64(ripple::sfLowNode); + if (sle.getType() == xrpl::ltRIPPLE_STATE) { + if (sle.getFieldAmount(xrpl::sfLowLimit).getIssuer() == accountID) { + return sle.getFieldU64(xrpl::sfLowNode); } - if (sle.getFieldAmount(ripple::sfHighLimit).getIssuer() == accountID) - return sle.getFieldU64(ripple::sfHighNode); + if (sle.getFieldAmount(xrpl::sfHighLimit).getIssuer() == accountID) + return sle.getFieldU64(xrpl::sfHighNode); } - if (!sle.isFieldPresent(ripple::sfOwnerNode)) + if (!sle.isFieldPresent(xrpl::sfOwnerNode)) return 0; - return sle.getFieldU64(ripple::sfOwnerNode); + return sle.getFieldU64(xrpl::sfOwnerNode); } // traverse account's nfts @@ -590,80 +587,80 @@ std::expected traverseNFTObjects( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& accountID, - ripple::uint256 nextPage, + xrpl::AccountID const& accountID, + xrpl::uint256 nextPage, std::uint32_t limit, boost::asio::yield_context yield, - std::function atOwnedNode + std::function atOwnedNode ) { - auto const firstNFTPage = ripple::keylet::nftpage_min(accountID); - auto const lastNFTPage = ripple::keylet::nftpage_max(accountID); + auto const firstNFTPage = xrpl::keylet::nftokenPageMin(accountID); + auto const lastNFTPage = xrpl::keylet::nftokenPageMax(accountID); // check if nextPage is valid - if (nextPage != beast::zero and firstNFTPage.key != (nextPage & ~ripple::nft::pageMask)) - return std::unexpected{Status{RippledError::rpcINVALID_PARAMS, "Invalid marker."}}; + if (nextPage != beast::kZero and firstNFTPage.key != (nextPage & ~xrpl::nft::kPageMask)) + return std::unexpected{Status{RippledError::RpcInvalidParams, "Invalid marker."}}; // no marker, start from the last page - ripple::uint256 const currentPage = nextPage == beast::zero ? lastNFTPage.key : nextPage; + xrpl::uint256 const currentPage = nextPage == beast::kZero ? lastNFTPage.key : nextPage; // read the current page auto page = backend.fetchLedgerObject(currentPage, sequence, yield); if (!page) { - if (nextPage == beast::zero) { // no nft objects in lastNFTPage - return AccountCursor{.index = beast::zero, .hint = 0}; + if (nextPage == beast::kZero) { // no nft objects in lastNFTPage + return AccountCursor{.index = beast::kZero, .hint = 0}; } // marker is in the right range, but still invalid - return std::unexpected{Status{RippledError::rpcINVALID_PARAMS, "Invalid marker."}}; + return std::unexpected{Status{RippledError::RpcInvalidParams, "Invalid marker."}}; } // the object exists and the key is in right range, must be nft page - ripple::SLE pageSLE{ripple::SerialIter{page->data(), page->size()}, currentPage}; + xrpl::SLE pageSLE{xrpl::SerialIter{page->data(), page->size()}, currentPage}; auto count = 0u; // traverse the nft page linked list until the start of the list or reach the limit while (true) { - auto const nftPreviousPage = pageSLE.getFieldH256(ripple::sfPreviousPageMin); + auto const nftPreviousPage = pageSLE.getFieldH256(xrpl::sfPreviousPageMin); atOwnedNode(std::move(pageSLE)); count++; - if (count == limit or nftPreviousPage == beast::zero) + if (count == limit or nftPreviousPage == beast::kZero) return AccountCursor{.index = nftPreviousPage, .hint = count}; page = backend.fetchLedgerObject(nftPreviousPage, sequence, yield); if (!page) break; - pageSLE = ripple::SLE{ripple::SerialIter{page->data(), page->size()}, nftPreviousPage}; + pageSLE = xrpl::SLE{xrpl::SerialIter{page->data(), page->size()}, nftPreviousPage}; } - return AccountCursor{.index = beast::zero, .hint = 0}; + return AccountCursor{.index = beast::kZero, .hint = 0}; } std::expected traverseOwnedNodes( BackendInterface const& backend, - ripple::AccountID const& accountID, + xrpl::AccountID const& accountID, std::uint32_t sequence, std::uint32_t limit, std::optional jsonCursor, boost::asio::yield_context yield, - std::function atOwnedNode, + std::function atOwnedNode, bool nftIncluded ) { auto const maybeCursor = parseAccountCursor(jsonCursor); if (!maybeCursor) - return std::unexpected{Status{RippledError::rpcINVALID_PARAMS, "Malformed cursor."}}; + return std::unexpected{Status{RippledError::RpcInvalidParams, "Malformed cursor."}}; // the format is checked in RPC framework level auto [hexCursor, startHint] = *maybeCursor; auto const isNftMarkerNonZero = - startHint == std::numeric_limits::max() and hexCursor != beast::zero; + startHint == std::numeric_limits::max() and hexCursor != beast::kZero; auto const isNftMarkerZero = - startHint == std::numeric_limits::max() and hexCursor == beast::zero; + startHint == std::numeric_limits::max() and hexCursor == beast::kZero; // if we need to traverse nft objects and this is the first request -> traverse nft objects // if we need to traverse nft objects and the marker is still in nft page -> traverse nft // objects if we need to traverse nft objects and the marker is still in nft page but next page @@ -687,18 +684,18 @@ traverseOwnedNodes( // adjust limit ,continue traversing owned nodes limit -= nftsCount; - hexCursor = beast::zero; + hexCursor = beast::kZero; startHint = 0; } else if (nftIncluded and isNftMarkerZero) { // the last request happen to fetch all the nft, adjust marker to continue traversing owned // nodes - hexCursor = beast::zero; + hexCursor = beast::kZero; startHint = 0; } return traverseOwnedNodes( backend, - ripple::keylet::ownerDir(accountID), + xrpl::keylet::ownerDir(accountID), hexCursor, startHint, sequence, @@ -711,46 +708,46 @@ traverseOwnedNodes( std::expected traverseOwnedNodes( BackendInterface const& backend, - ripple::Keylet const& owner, - ripple::uint256 const& hexMarker, + xrpl::Keylet const& owner, + xrpl::uint256 const& hexMarker, std::uint32_t const startHint, std::uint32_t sequence, std::uint32_t limit, boost::asio::yield_context yield, - std::function atOwnedNode + std::function atOwnedNode ) { - auto cursor = AccountCursor({.index = beast::zero, .hint = 0}); + auto cursor = AccountCursor({.index = beast::kZero, .hint = 0}); auto const rootIndex = owner; auto currentIndex = rootIndex; // track the current page we are accessing, will return it as the next hint auto currentPage = startHint; - std::vector keys; + std::vector keys; // Only reserve 2048 nodes when fetching all owned ledger objects. If there // are more, then keys will allocate more memory, which is suboptimal, but // should only occur occasionally. - static constexpr std::uint32_t kMIN_NODES = 2048; - keys.reserve(std::min(kMIN_NODES, limit)); + static constexpr std::uint32_t kMinNodes = 2048; + keys.reserve(std::min(kMinNodes, limit)); auto start = std::chrono::system_clock::now(); // If startAfter is not zero try jumping to that page using the hint if (hexMarker.isNonZero()) { - auto const hintIndex = ripple::keylet::page(rootIndex, startHint); + auto const hintIndex = xrpl::keylet::page(rootIndex, startHint); auto hintDir = backend.fetchLedgerObject(hintIndex.key, sequence, yield); if (!hintDir) - return std::unexpected{Status(ripple::rpcINVALID_PARAMS, "Invalid marker.")}; + return std::unexpected{Status(xrpl::RpcInvalidParams, "Invalid marker.")}; - ripple::SerialIter hintDirIt{hintDir->data(), hintDir->size()}; - ripple::SLE const hintDirSle{hintDirIt, hintIndex.key}; + xrpl::SerialIter hintDirIt{hintDir->data(), hintDir->size()}; + xrpl::SLE const hintDirSle{hintDirIt, hintIndex.key}; - if (auto const& indexes = hintDirSle.getFieldV256(ripple::sfIndexes); + if (auto const& indexes = hintDirSle.getFieldV256(xrpl::sfIndexes); std::ranges::find(indexes, hexMarker) == std::end(indexes)) { // the index specified by marker is not in the page specified by marker - return std::unexpected{Status(ripple::rpcINVALID_PARAMS, "Invalid marker.")}; + return std::unexpected{Status(xrpl::RpcInvalidParams, "Invalid marker.")}; } currentIndex = hintIndex; @@ -760,14 +757,14 @@ traverseOwnedNodes( if (!ownerDir) { return std::unexpected{ - Status(ripple::rpcINVALID_PARAMS, "Owner directory not found.") + Status(xrpl::RpcInvalidParams, "Owner directory not found.") }; } - ripple::SerialIter ownedDirIt{ownerDir->data(), ownerDir->size()}; - ripple::SLE const ownedDirSle{ownedDirIt, currentIndex.key}; + xrpl::SerialIter ownedDirIt{ownerDir->data(), ownerDir->size()}; + xrpl::SLE const ownedDirSle{ownedDirIt, currentIndex.key}; - for (auto const& key : ownedDirSle.getFieldV256(ripple::sfIndexes)) { + for (auto const& key : ownedDirSle.getFieldV256(xrpl::sfIndexes)) { if (!found) { if (key == hexMarker) found = true; @@ -785,11 +782,11 @@ traverseOwnedNodes( break; } // the next page - auto const uNodeNext = ownedDirSle.getFieldU64(ripple::sfIndexNext); + auto const uNodeNext = ownedDirSle.getFieldU64(xrpl::sfIndexNext); if (uNodeNext == 0) break; - currentIndex = ripple::keylet::page(rootIndex, uNodeNext); + currentIndex = xrpl::keylet::page(rootIndex, uNodeNext); currentPage = uNodeNext; } } else { @@ -799,10 +796,10 @@ traverseOwnedNodes( if (!ownerDir) break; - ripple::SerialIter ownedDirIt{ownerDir->data(), ownerDir->size()}; - ripple::SLE const ownedDirSle{ownedDirIt, currentIndex.key}; + xrpl::SerialIter ownedDirIt{ownerDir->data(), ownerDir->size()}; + xrpl::SLE const ownedDirSle{ownedDirIt, currentIndex.key}; - for (auto const& key : ownedDirSle.getFieldV256(ripple::sfIndexes)) { + for (auto const& key : ownedDirSle.getFieldV256(xrpl::sfIndexes)) { keys.push_back(key); if (--limit == 0) @@ -814,11 +811,11 @@ traverseOwnedNodes( break; } - auto const uNodeNext = ownedDirSle.getFieldU64(ripple::sfIndexNext); + auto const uNodeNext = ownedDirSle.getFieldU64(xrpl::sfIndexNext); if (uNodeNext == 0) break; - currentIndex = ripple::keylet::page(rootIndex, uNodeNext); + currentIndex = xrpl::keylet::page(rootIndex, uNodeNext); currentPage = uNodeNext; } } @@ -838,35 +835,35 @@ traverseOwnedNodes( LOG(log.debug()) << "Time loading owned entries: " << timeDiff << " milliseconds"; for (auto i = 0u; i < objects.size(); ++i) { - ripple::SerialIter it{objects[i].data(), objects[i].size()}; - atOwnedNode(ripple::SLE{it, keys[i]}); + xrpl::SerialIter it{objects[i].data(), objects[i].size()}; + atOwnedNode(xrpl::SLE{it, keys[i]}); } if (limit == 0) return cursor; - return AccountCursor({.index = beast::zero, .hint = 0}); + return AccountCursor({.index = beast::kZero, .hint = 0}); } -std::shared_ptr +std::shared_ptr read( std::shared_ptr const& backend, - ripple::Keylet const& keylet, - ripple::LedgerHeader const& lgrInfo, + xrpl::Keylet const& keylet, + xrpl::LedgerHeader const& lgrInfo, web::Context const& context ) { if (auto const blob = backend->fetchLedgerObject(keylet.key, lgrInfo.seq, context.yield); blob) { - return std::make_shared( - ripple::SerialIter{blob->data(), blob->size()}, keylet.key + return std::make_shared( + xrpl::SerialIter{blob->data(), blob->size()}, keylet.key ); } return nullptr; } -std::optional +std::optional parseRippleLibSeed(boost::json::value const& value) { // ripple-lib encodes seed used to generate an Ed25519 wallet in a @@ -875,29 +872,28 @@ parseRippleLibSeed(boost::json::value const& value) if (!value.is_string()) return {}; - auto const result = ripple::decodeBase58Token( - boost::json::value_to(value), ripple::TokenType::None - ); + auto const result = + xrpl::decodeBase58Token(boost::json::value_to(value), xrpl::TokenType::None); - static constexpr std::size_t kSEED_SIZE = 18; - static constexpr std::array kSEED_PREFIX = {0xE1, 0x4B}; - if (result.size() == kSEED_SIZE && static_cast(result[0]) == kSEED_PREFIX[0] && - static_cast(result[1]) == kSEED_PREFIX[1]) - return ripple::Seed(ripple::makeSlice(result.substr(2))); + static constexpr std::size_t kSeedSize = 18; + static constexpr std::array kSeedPrefix = {0xE1, 0x4B}; + if (result.size() == kSeedSize && static_cast(result[0]) == kSeedPrefix[0] && + static_cast(result[1]) == kSeedPrefix[1]) + return xrpl::Seed(xrpl::makeSlice(result.substr(2))); return {}; } -std::vector +std::vector getAccountsFromTransaction(boost::json::object const& transaction) { - std::vector accounts = {}; + std::vector accounts = {}; for (auto const& [key, value] : transaction) { if (value.is_object()) { auto inObject = getAccountsFromTransaction(value.as_object()); accounts.insert(accounts.end(), inObject.begin(), inObject.end()); } else if (value.is_string()) { - auto const account = util::parseBase58Wrapper( + auto const account = util::parseBase58Wrapper( boost::json::value_to(value) ); if (account) { @@ -913,30 +909,30 @@ bool isGlobalFrozen( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& issuer, + xrpl::AccountID const& issuer, boost::asio::yield_context yield ) { - if (ripple::isXRP(issuer)) + if (xrpl::isXRP(issuer)) return false; - auto key = ripple::keylet::account(issuer).key; + auto key = xrpl::keylet::account(issuer).key; auto blob = backend.fetchLedgerObject(key, sequence, yield); if (!blob) return false; - ripple::SerialIter it{blob->data(), blob->size()}; - ripple::SLE const sle{it, key}; + xrpl::SerialIter it{blob->data(), blob->size()}; + xrpl::SLE const sle{it, key}; - return sle.isFlag(ripple::lsfGlobalFreeze); + return sle.isFlag(xrpl::lsfGlobalFreeze); } bool fetchAndCheckAnyFlagsExists( BackendInterface const& backend, std::uint32_t sequence, - ripple::Keylet const& keylet, + xrpl::Keylet const& keylet, std::vector const& flags, boost::asio::yield_context yield ) @@ -946,8 +942,8 @@ fetchAndCheckAnyFlagsExists( if (!blob) return false; - ripple::SerialIter it{blob->data(), blob->size()}; - ripple::SLE const sle{it, keylet.key}; + xrpl::SerialIter it{blob->data(), blob->size()}; + xrpl::SLE const sle{it, keylet.key}; return std::ranges::any_of(flags, [sle](std::uint32_t flag) { return sle.isFlag(flag); }); } @@ -956,27 +952,27 @@ bool isFrozen( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& account, - ripple::Currency const& currency, - ripple::AccountID const& issuer, + xrpl::AccountID const& account, + xrpl::Currency const& currency, + xrpl::AccountID const& issuer, boost::asio::yield_context yield ) { - if (ripple::isXRP(currency)) + if (xrpl::isXRP(currency)) return false; if (fetchAndCheckAnyFlagsExists( - backend, sequence, ripple::keylet::account(issuer), {ripple::lsfGlobalFreeze}, yield + backend, sequence, xrpl::keylet::account(issuer), {xrpl::lsfGlobalFreeze}, yield )) return true; - auto const trustLineKeylet = ripple::keylet::line(account, issuer, currency); + auto const trustLineKeylet = xrpl::keylet::trustLine(account, issuer, currency); return issuer != account && fetchAndCheckAnyFlagsExists( backend, sequence, trustLineKeylet, - {(issuer > account) ? ripple::lsfHighFreeze : ripple::lsfLowFreeze}, + {(issuer > account) ? xrpl::lsfHighFreeze : xrpl::lsfLowFreeze}, yield ); } @@ -985,26 +981,22 @@ bool isDeepFrozen( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& account, - ripple::Currency const& currency, - ripple::AccountID const& issuer, + xrpl::AccountID const& account, + xrpl::Currency const& currency, + xrpl::AccountID const& issuer, boost::asio::yield_context yield ) { - if (ripple::isXRP(currency)) + if (xrpl::isXRP(currency)) return false; if (issuer == account) return false; - auto const trustLineKeylet = ripple::keylet::line(account, issuer, currency); + auto const trustLineKeylet = xrpl::keylet::trustLine(account, issuer, currency); return fetchAndCheckAnyFlagsExists( - backend, - sequence, - trustLineKeylet, - {ripple::lsfHighDeepFreeze, ripple::lsfLowDeepFreeze}, - yield + backend, sequence, trustLineKeylet, {xrpl::lsfHighDeepFreeze, xrpl::lsfLowDeepFreeze}, yield ); } @@ -1012,9 +1004,9 @@ bool isLPTokenFrozen( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& account, - ripple::Issue const& asset, - ripple::Issue const& asset2, + xrpl::AccountID const& account, + xrpl::Issue const& asset, + xrpl::Issue const& asset2, boost::asio::yield_context yield ) { @@ -1022,33 +1014,40 @@ isLPTokenFrozen( isFrozen(backend, sequence, account, asset2.currency, asset2.account, yield); } -ripple::XRPAmount +xrpl::XRPAmount xrpLiquid( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& id, + xrpl::AccountID const& id, boost::asio::yield_context yield ) { - auto const key = ripple::keylet::account(id).key; + auto const key = xrpl::keylet::account(id).key; auto blob = backend.fetchLedgerObject(key, sequence, yield); if (!blob) - return beast::zero; + return beast::kZero; - ripple::SerialIter it{blob->data(), blob->size()}; - ripple::SLE const sle{it, key}; + xrpl::SerialIter it{blob->data(), blob->size()}; + xrpl::SLE const sle{it, key}; - std::uint32_t const ownerCount = sle.getFieldU32(ripple::sfOwnerCount); + std::uint32_t const ownerCount = sle.getFieldU32(xrpl::sfOwnerCount); - auto balance = sle.getFieldAmount(ripple::sfBalance); + // A sponsored account pays no base reserve of its own, and an account pays one extra base + // reserve for every account it sponsors. Before the Sponsor amendment activates neither field + // is ever set, so this evaluates to 1 and matches the previous behaviour. + std::uint32_t const accountCount = (sle.isFieldPresent(xrpl::sfSponsor) ? 0 : 1) + + sle.getFieldU32(xrpl::sfSponsoringAccountCount); - ripple::STAmount const amount = [&]() { + auto balance = sle.getFieldAmount(xrpl::sfBalance); + + xrpl::STAmount const amount = [&]() { // AMM doesn't require the reserves - if ((sle.getFlags() & ripple::lsfAMMNode) != 0u) + if ((sle.getFlags() & xrpl::lsfAMMNode) != 0u) return balance; - auto const reserve = backend.fetchFees(sequence, yield)->accountReserve(ownerCount); - ripple::STAmount amount = balance - reserve; + auto const reserve = + backend.fetchFees(sequence, yield)->accountReserve(ownerCount, accountCount); + xrpl::STAmount amount = balance - reserve; if (balance < reserve) amount.clear(); return amount; @@ -1057,13 +1056,13 @@ xrpLiquid( return amount.xrp(); } -ripple::STAmount +xrpl::STAmount accountFunds( BackendInterface const& backend, data::AmendmentCenterInterface const& amendmentCenter, std::uint32_t const sequence, - ripple::STAmount const& amount, - ripple::AccountID const& id, + xrpl::STAmount const& amount, + xrpl::AccountID const& id, boost::asio::yield_context yield ) { @@ -1076,79 +1075,79 @@ accountFunds( amendmentCenter, sequence, id, - amount.getCurrency(), + amount.get().currency, amount.getIssuer(), true, yield ); } -ripple::STAmount +xrpl::STAmount ammAccountHolds( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& account, - ripple::Currency const& currency, - ripple::AccountID const& issuer, + xrpl::AccountID const& account, + xrpl::Currency const& currency, + xrpl::AccountID const& issuer, bool const zeroIfFrozen, boost::asio::yield_context yield ) { - ripple::STAmount amount; - ASSERT(!ripple::isXRP(currency), "LPToken currency can never be XRP"); - if (ripple::isXRP(currency)) + xrpl::STAmount amount; + ASSERT(!xrpl::isXRP(currency), "LPToken currency can never be XRP"); + if (xrpl::isXRP(currency)) return {xrpLiquid(backend, sequence, account, yield)}; - auto const key = ripple::keylet::line(account, issuer, currency).key; + auto const key = xrpl::keylet::trustLine(account, issuer, currency).key; auto const blob = backend.fetchLedgerObject(key, sequence, yield); if (!blob) { - amount.setIssue(ripple::Issue(currency, issuer)); + amount.setIssue(xrpl::Issue(currency, issuer)); amount.clear(); return amount; } - ripple::SerialIter it{blob->data(), blob->size()}; - ripple::SLE const sle{it, key}; + xrpl::SerialIter it{blob->data(), blob->size()}; + xrpl::SLE const sle{it, key}; if (zeroIfFrozen && (isFrozen(backend, sequence, account, currency, issuer, yield) || isDeepFrozen(backend, sequence, account, currency, issuer, yield))) { - amount.setIssue(ripple::Issue(currency, issuer)); + amount.setIssue(xrpl::Issue(currency, issuer)); amount.clear(); } else { - amount = sle.getFieldAmount(ripple::sfBalance); + amount = sle.getFieldAmount(xrpl::sfBalance); if (account > issuer) { // Put balance in account terms. amount.negate(); } - amount.setIssuer(issuer); + amount.setIssue(xrpl::Issue{amount.get().currency, issuer}); } return amount; } -ripple::STAmount +xrpl::STAmount accountHolds( BackendInterface const& backend, data::AmendmentCenterInterface const& amendmentCenter, std::uint32_t sequence, - ripple::AccountID const& account, - ripple::Currency const& currency, - ripple::AccountID const& issuer, + xrpl::AccountID const& account, + xrpl::Currency const& currency, + xrpl::AccountID const& issuer, bool const zeroIfFrozen, boost::asio::yield_context yield ) { - ripple::STAmount amount; - if (ripple::isXRP(currency)) + xrpl::STAmount amount; + if (xrpl::isXRP(currency)) return {xrpLiquid(backend, sequence, account, yield)}; - auto const key = ripple::keylet::line(account, issuer, currency).key; + auto const key = xrpl::keylet::trustLine(account, issuer, currency).key; auto const blob = backend.fetchLedgerObject(key, sequence, yield); if (!blob) { - amount.setIssue(ripple::Issue(currency, issuer)); + amount.setIssue(xrpl::Issue(currency, issuer)); amount.clear(); return amount; } @@ -1164,35 +1163,35 @@ accountHolds( yield, data::Amendments::fixFrozenLPTokenTransfer, sequence )) { auto const issuerBlob = - backend.fetchLedgerObject(ripple::keylet::account(issuer).key, sequence, yield); + backend.fetchLedgerObject(xrpl::keylet::account(issuer).key, sequence, yield); if (!issuerBlob) return false; - ripple::SLE const issuerSle{ - ripple::SerialIter{issuerBlob->data(), issuerBlob->size()}, - ripple::keylet::account(issuer).key + xrpl::SLE const issuerSle{ + xrpl::SerialIter{issuerBlob->data(), issuerBlob->size()}, + xrpl::keylet::account(issuer).key }; // if the issuer is an amm account, then currency is lptoken, so we will need to check // if the assets in the pool are frozen as well - if (issuerSle.isFieldPresent(ripple::sfAMMID)) { - auto const ammKeylet = ripple::keylet::amm(issuerSle[ripple::sfAMMID]); + if (issuerSle.isFieldPresent(xrpl::sfAMMID)) { + auto const ammKeylet = xrpl::keylet::amm(issuerSle[xrpl::sfAMMID]); auto const ammBlob = backend.fetchLedgerObject(ammKeylet.key, sequence, yield); if (!ammBlob) return false; - ripple::SLE const ammSle{ - ripple::SerialIter{ammBlob->data(), ammBlob->size()}, ammKeylet.key + xrpl::SLE const ammSle{ + xrpl::SerialIter{ammBlob->data(), ammBlob->size()}, ammKeylet.key }; return !isLPTokenFrozen( backend, sequence, account, - ammSle[ripple::sfAsset].get(), - ammSle[ripple::sfAsset2].get(), + ammSle[xrpl::sfAsset].get(), + ammSle[xrpl::sfAsset2].get(), yield ); } @@ -1202,50 +1201,50 @@ accountHolds( }(); if (allowBalance) { - ripple::SerialIter it{blob->data(), blob->size()}; - ripple::SLE const sle{it, key}; + xrpl::SerialIter it{blob->data(), blob->size()}; + xrpl::SLE const sle{it, key}; - amount = sle.getFieldAmount(ripple::sfBalance); + amount = sle.getFieldAmount(xrpl::sfBalance); if (account > issuer) { // Put balance in account terms. amount.negate(); } - amount.setIssuer(issuer); + amount.setIssue(xrpl::Issue{amount.get().currency, issuer}); } else { - amount.setIssue(ripple::Issue(currency, issuer)); + amount.setIssue(xrpl::Issue(currency, issuer)); amount.clear(); } return amount; } -ripple::Rate +xrpl::Rate transferRate( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& issuer, + xrpl::AccountID const& issuer, boost::asio::yield_context yield ) { - auto key = ripple::keylet::account(issuer).key; + auto key = xrpl::keylet::account(issuer).key; auto blob = backend.fetchLedgerObject(key, sequence, yield); if (blob) { - ripple::SerialIter it{blob->data(), blob->size()}; - ripple::SLE const sle{it, key}; + xrpl::SerialIter it{blob->data(), blob->size()}; + xrpl::SLE const sle{it, key}; - if (sle.isFieldPresent(ripple::sfTransferRate)) - return ripple::Rate{sle.getFieldU32(ripple::sfTransferRate)}; + if (sle.isFieldPresent(xrpl::sfTransferRate)) + return xrpl::Rate{sle.getFieldU32(xrpl::sfTransferRate)}; } - return ripple::parityRate; + return xrpl::kParityRate; } boost::json::array postProcessOrderBook( std::vector const& offers, - ripple::Book const& book, - ripple::AccountID const& takerID, + xrpl::Book const& book, + xrpl::AccountID const& takerID, data::BackendInterface const& backend, data::AmendmentCenterInterface const& amendmentCenter, std::uint32_t const ledgerSequence, @@ -1254,26 +1253,27 @@ postProcessOrderBook( { boost::json::array jsonOffers; - std::map umBalance; + std::map umBalance; - bool const globalFreeze = isGlobalFrozen(backend, ledgerSequence, book.out.account, yield) || - isGlobalFrozen(backend, ledgerSequence, book.in.account, yield); + bool const globalFreeze = + isGlobalFrozen(backend, ledgerSequence, book.out.getIssuer(), yield) || + isGlobalFrozen(backend, ledgerSequence, book.in.getIssuer(), yield); - auto rate = transferRate(backend, ledgerSequence, book.out.account, yield); + auto rate = transferRate(backend, ledgerSequence, book.out.getIssuer(), yield); for (auto const& obj : offers) { try { - ripple::SerialIter it{obj.blob.data(), obj.blob.size()}; - ripple::SLE const offer{it, obj.key}; - ripple::uint256 const bookDir = offer.getFieldH256(ripple::sfBookDirectory); + xrpl::SerialIter it{obj.blob.data(), obj.blob.size()}; + xrpl::SLE const offer{it, obj.key}; + xrpl::uint256 const bookDir = offer.getFieldH256(xrpl::sfBookDirectory); - auto const uOfferOwnerID = offer.getAccountID(ripple::sfAccount); - auto const& saTakerGets = offer.getFieldAmount(ripple::sfTakerGets); - auto const& saTakerPays = offer.getFieldAmount(ripple::sfTakerPays); - ripple::STAmount saOwnerFunds; + auto const uOfferOwnerID = offer.getAccountID(xrpl::sfAccount); + auto const& saTakerGets = offer.getFieldAmount(xrpl::sfTakerGets); + auto const& saTakerPays = offer.getFieldAmount(xrpl::sfTakerPays); + xrpl::STAmount saOwnerFunds; bool firstOwnerOffer = true; - if (book.out.account == uOfferOwnerID) { + if (book.out.getIssuer() == uOfferOwnerID) { // If an offer is selling issuer's own IOUs, it is fully // funded. saOwnerFunds = saTakerGets; @@ -1294,34 +1294,34 @@ postProcessOrderBook( amendmentCenter, ledgerSequence, uOfferOwnerID, - book.out.currency, - book.out.account, + book.out.get().currency, + book.out.getIssuer(), true, yield ); - if (saOwnerFunds < beast::zero) + if (saOwnerFunds < beast::kZero) saOwnerFunds.clear(); } } boost::json::object offerJson = toJson(offer); - ripple::STAmount saTakerGetsFunded; - ripple::STAmount saOwnerFundsLimit = saOwnerFunds; - ripple::Rate offerRate = ripple::parityRate; - ripple::STAmount const dirRate = ripple::amountFromQuality(getQuality(bookDir)); + xrpl::STAmount saTakerGetsFunded; + xrpl::STAmount saOwnerFundsLimit = saOwnerFunds; + xrpl::Rate offerRate = xrpl::kParityRate; + xrpl::STAmount const dirRate = xrpl::amountFromQuality(getQuality(bookDir)); - if (rate != ripple::parityRate + if (rate != xrpl::kParityRate // Have a transfer fee. - && takerID != book.out.account + && takerID != book.out.getIssuer() // Not taking offers of own IOUs. - && book.out.account != uOfferOwnerID) + && book.out.getIssuer() != uOfferOwnerID) // Offer owner not issuing ownfunds { // Need to charge a transfer fee to offer owner. offerRate = rate; - saOwnerFundsLimit = ripple::divide(saOwnerFunds, offerRate); + saOwnerFundsLimit = xrpl::divide(saOwnerFunds, offerRate); } if (saOwnerFundsLimit >= saTakerGets) { @@ -1330,19 +1330,19 @@ postProcessOrderBook( } else { saTakerGetsFunded = saOwnerFundsLimit; offerJson["taker_gets_funded"] = - toBoostJson(saTakerGetsFunded.getJson(ripple::JsonOptions::none)); + toBoostJson(saTakerGetsFunded.getJson(xrpl::JsonOptions::Values::None)); offerJson["taker_pays_funded"] = toBoostJson( std::min( saTakerPays, - ripple::multiply(saTakerGetsFunded, dirRate, saTakerPays.issue()) + xrpl::multiply(saTakerGetsFunded, dirRate, saTakerPays.get()) ) - .getJson(ripple::JsonOptions::none) + .getJson(xrpl::JsonOptions::Values::None) ); } - ripple::STAmount const saOwnerPays = (ripple::parityRate == offerRate) + xrpl::STAmount const saOwnerPays = (xrpl::kParityRate == offerRate) ? saTakerGetsFunded - : std::min(saOwnerFunds, ripple::multiply(saTakerGetsFunded, offerRate)); + : std::min(saOwnerFunds, xrpl::multiply(saTakerGetsFunded, offerRate)); umBalance[uOfferOwnerID] = saOwnerFunds - saOwnerPays; @@ -1361,234 +1361,230 @@ postProcessOrderBook( } // get book via currency type -std::expected +std::expected parseBook( - ripple::Currency pays, - ripple::AccountID payIssuer, - ripple::Currency gets, - ripple::AccountID getIssuer, + xrpl::Currency pays, + xrpl::AccountID payIssuer, + xrpl::Currency gets, + xrpl::AccountID getIssuer, std::optional const& domain ) { if (isXRP(pays) && !isXRP(payIssuer)) { return std::unexpected{Status{ - RippledError::rpcSRC_ISR_MALFORMED, + RippledError::RpcSrcIsrMalformed, "Unneeded field 'taker_pays.issuer' for XRP currency specification." }}; } if (!isXRP(pays) && isXRP(payIssuer)) { return std::unexpected{Status{ - RippledError::rpcSRC_ISR_MALFORMED, + RippledError::RpcSrcIsrMalformed, "Invalid field 'taker_pays.issuer', expected non-XRP issuer." }}; } - if (ripple::isXRP(gets) && !ripple::isXRP(getIssuer)) { + if (xrpl::isXRP(gets) && !xrpl::isXRP(getIssuer)) { return std::unexpected{Status{ - RippledError::rpcDST_ISR_MALFORMED, + RippledError::RpcDstIsrMalformed, "Unneeded field 'taker_gets.issuer' for XRP currency specification." }}; } - if (!ripple::isXRP(gets) && ripple::isXRP(getIssuer)) { + if (!xrpl::isXRP(gets) && xrpl::isXRP(getIssuer)) { return std::unexpected{Status{ - RippledError::rpcDST_ISR_MALFORMED, + RippledError::RpcDstIsrMalformed, "Invalid field 'taker_gets.issuer', expected non-XRP issuer." }}; } if (pays == gets && payIssuer == getIssuer) - return std::unexpected{Status{RippledError::rpcBAD_MARKET, "badMarket"}}; + return std::unexpected{Status{RippledError::RpcBadMarket, "badMarket"}}; - std::optional domainID = std::nullopt; + std::optional domainID = std::nullopt; if (domain.has_value()) { - ripple::uint256 dom; + xrpl::uint256 dom; if (!dom.parseHex(*domain)) - return std::unexpected{Status{RippledError::rpcDOMAIN_MALFORMED}}; + return std::unexpected{Status{RippledError::RpcDomainMalformed}}; domainID = dom; } - return ripple::Book{{pays, payIssuer}, {gets, getIssuer}, domainID}; + return xrpl::Book{xrpl::Issue{pays, payIssuer}, xrpl::Issue{gets, getIssuer}, domainID}; } -std::expected +std::expected parseBook(boost::json::object const& request) { if (!request.contains("taker_pays")) { return std::unexpected{ - Status{RippledError::rpcINVALID_PARAMS, "Missing field 'taker_pays'"} + Status{RippledError::RpcInvalidParams, "Missing field 'taker_pays'"} }; } if (!request.contains("taker_gets")) { return std::unexpected{ - Status{RippledError::rpcINVALID_PARAMS, "Missing field 'taker_gets'"} + Status{RippledError::RpcInvalidParams, "Missing field 'taker_gets'"} }; } if (!request.at("taker_pays").is_object()) { return std::unexpected{ - Status{RippledError::rpcINVALID_PARAMS, "Field 'taker_pays' is not an object"} + Status{RippledError::RpcInvalidParams, "Field 'taker_pays' is not an object"} }; } if (!request.at("taker_gets").is_object()) { return std::unexpected{ - Status{RippledError::rpcINVALID_PARAMS, "Field 'taker_gets' is not an object"} + Status{RippledError::RpcInvalidParams, "Field 'taker_gets' is not an object"} }; } auto takerPays = request.at("taker_pays").as_object(); if (!takerPays.contains("currency")) - return std::unexpected{Status{RippledError::rpcSRC_CUR_MALFORMED}}; + return std::unexpected{Status{RippledError::RpcSrcCurMalformed}}; if (!takerPays.at("currency").is_string()) - return std::unexpected{Status{RippledError::rpcSRC_CUR_MALFORMED}}; + return std::unexpected{Status{RippledError::RpcSrcCurMalformed}}; auto takerGets = request.at("taker_gets").as_object(); if (!takerGets.contains("currency")) - return std::unexpected{Status{RippledError::rpcDST_AMT_MALFORMED}}; + return std::unexpected{Status{RippledError::RpcDstAmtMalformed}}; if (!takerGets.at("currency").is_string()) { return std::unexpected{Status{ - RippledError::rpcDST_AMT_MALFORMED, + RippledError::RpcDstAmtMalformed, }}; } if (request.contains("domain") && !request.at("domain").is_string()) - return std::unexpected{Status{RippledError::rpcDOMAIN_MALFORMED}}; + return std::unexpected{Status{RippledError::RpcDomainMalformed}}; - ripple::Currency payCurrency; - if (!ripple::to_currency( + xrpl::Currency payCurrency; + if (!xrpl::toCurrency( payCurrency, boost::json::value_to(takerPays.at("currency")) )) - return std::unexpected{Status{RippledError::rpcSRC_CUR_MALFORMED}}; + return std::unexpected{Status{RippledError::RpcSrcCurMalformed}}; - ripple::Currency getCurrency; - if (!ripple::to_currency( - getCurrency, boost::json::value_to(takerGets["currency"]) - )) - return std::unexpected{Status{RippledError::rpcDST_AMT_MALFORMED}}; + xrpl::Currency getCurrency; + if (!xrpl::toCurrency(getCurrency, boost::json::value_to(takerGets["currency"]))) + return std::unexpected{Status{RippledError::RpcDstAmtMalformed}}; - ripple::AccountID payIssuer; + xrpl::AccountID payIssuer; if (takerPays.contains("issuer")) { if (!takerPays.at("issuer").is_string()) { return std::unexpected{ - Status{RippledError::rpcINVALID_PARAMS, "takerPaysIssuerNotString"} + Status{RippledError::RpcInvalidParams, "takerPaysIssuerNotString"} }; } - if (!ripple::to_issuer( - payIssuer, boost::json::value_to(takerPays.at("issuer")) - )) - return std::unexpected{Status{RippledError::rpcSRC_ISR_MALFORMED}}; + if (!xrpl::toIssuer(payIssuer, boost::json::value_to(takerPays.at("issuer")))) + return std::unexpected{Status{RippledError::RpcSrcIsrMalformed}}; - if (payIssuer == ripple::noAccount()) - return std::unexpected{Status{RippledError::rpcSRC_ISR_MALFORMED}}; + if (payIssuer == xrpl::noAccount()) + return std::unexpected{Status{RippledError::RpcSrcIsrMalformed}}; } else { - payIssuer = ripple::xrpAccount(); + payIssuer = xrpl::xrpAccount(); } if (isXRP(payCurrency) && !isXRP(payIssuer)) { return std::unexpected{Status{ - RippledError::rpcSRC_ISR_MALFORMED, + RippledError::RpcSrcIsrMalformed, "Unneeded field 'taker_pays.issuer' for XRP currency specification." }}; } if (!isXRP(payCurrency) && isXRP(payIssuer)) { return std::unexpected{Status{ - RippledError::rpcSRC_ISR_MALFORMED, + RippledError::RpcSrcIsrMalformed, "Invalid field 'taker_pays.issuer', expected non-XRP issuer." }}; } if ((!isXRP(payCurrency)) && (!takerPays.contains("issuer"))) { - return std::unexpected{ - Status{RippledError::rpcSRC_ISR_MALFORMED, "Missing non-XRP issuer."} - }; + return std::unexpected{Status{RippledError::RpcSrcIsrMalformed, "Missing non-XRP issuer."}}; } - ripple::AccountID getIssuer; + xrpl::AccountID getIssuer; if (takerGets.contains("issuer")) { if (!takerGets["issuer"].is_string()) { return std::unexpected{ - Status{RippledError::rpcINVALID_PARAMS, "taker_gets.issuer should be string"} + Status{RippledError::RpcInvalidParams, "taker_gets.issuer should be string"} }; } - if (!ripple::to_issuer( + if (!xrpl::toIssuer( getIssuer, boost::json::value_to(takerGets.at("issuer")) )) { return std::unexpected{Status{ - RippledError::rpcDST_ISR_MALFORMED, "Invalid field 'taker_gets.issuer', bad issuer." + RippledError::RpcDstIsrMalformed, "Invalid field 'taker_gets.issuer', bad issuer." }}; } - if (getIssuer == ripple::noAccount()) { + if (getIssuer == xrpl::noAccount()) { return std::unexpected{Status{ - RippledError::rpcDST_ISR_MALFORMED, + RippledError::RpcDstIsrMalformed, "Invalid field 'taker_gets.issuer', bad issuer account one." }}; } } else { - getIssuer = ripple::xrpAccount(); + getIssuer = xrpl::xrpAccount(); } - if (ripple::isXRP(getCurrency) && !ripple::isXRP(getIssuer)) { + if (xrpl::isXRP(getCurrency) && !xrpl::isXRP(getIssuer)) { return std::unexpected{Status{ - RippledError::rpcDST_ISR_MALFORMED, + RippledError::RpcDstIsrMalformed, "Unneeded field 'taker_gets.issuer' for XRP currency specification." }}; } - if (!ripple::isXRP(getCurrency) && ripple::isXRP(getIssuer)) { + if (!xrpl::isXRP(getCurrency) && xrpl::isXRP(getIssuer)) { return std::unexpected{Status{ - RippledError::rpcDST_ISR_MALFORMED, + RippledError::RpcDstIsrMalformed, "Invalid field 'taker_gets.issuer', expected non-XRP issuer." }}; } if (payCurrency == getCurrency && payIssuer == getIssuer) - return std::unexpected{Status{RippledError::rpcBAD_MARKET, "badMarket"}}; + return std::unexpected{Status{RippledError::RpcBadMarket, "badMarket"}}; - std::optional domainID; + std::optional domainID; if (request.contains("domain")) { - ripple::uint256 dom; + xrpl::uint256 dom; if (!dom.parseHex(boost::json::value_to(request.at("domain")))) - return std::unexpected{Status{RippledError::rpcDOMAIN_MALFORMED}}; + return std::unexpected{Status{RippledError::RpcDomainMalformed}}; domainID = dom; } - return ripple::Book{{payCurrency, payIssuer}, {getCurrency, getIssuer}, domainID}; + return xrpl::Book{ + xrpl::Issue{payCurrency, payIssuer}, xrpl::Issue{getCurrency, getIssuer}, domainID + }; } -std::expected +std::expected parseTaker(boost::json::value const& taker) { - std::optional takerID = {}; + std::optional takerID = {}; if (!taker.is_string()) - return std::unexpected{Status{RippledError::rpcINVALID_PARAMS, "takerNotString"}}; + return std::unexpected{Status{RippledError::RpcInvalidParams, "takerNotString"}}; takerID = accountFromStringStrict(boost::json::value_to(taker)); if (!takerID) - return std::unexpected{Status{RippledError::rpcBAD_ISSUER, "invalidTakerAccount"}}; + return std::unexpected{Status{RippledError::RpcBadIssuer, "invalidTakerAccount"}}; return *takerID; } -ripple::Issue +xrpl::Issue parseIssue(boost::json::object const& issue) { - Json::Value jv; + json::Value jv; if (issue.contains(JS(issuer)) && issue.at(JS(issuer)).is_string()) jv["issuer"] = boost::json::value_to(issue.at(JS(issuer))); if (issue.contains(JS(currency)) && issue.at(JS(currency)).is_string()) jv["currency"] = boost::json::value_to(issue.at(JS(currency))); - return ripple::issueFromJson(jv); + return xrpl::issueFromJson(jv); } bool @@ -1609,8 +1605,8 @@ isAdminCmd(std::string const& method, boost::json::object const& request) { if (method == JS(ledger)) { auto const requestStr = boost::json::serialize(request); - Json::Value jv; - Json::Reader{}.parse(requestStr, jv); + json::Value jv; + json::Reader{}.parse(requestStr, jv); // rippled considers string/non-zero int/non-empty array/ non-empty json as true. // Use rippled's API asBool to get the same result. // https://github.com/XRPLF/rippled/issues/5119 @@ -1631,18 +1627,18 @@ isAdminCmd(std::string const& method, boost::json::object const& request) return false; } -std::expected +std::expected getNFTID(boost::json::object const& request) { if (!request.contains(JS(nft_id))) - return std::unexpected{Status{RippledError::rpcINVALID_PARAMS, "missingTokenID"}}; + return std::unexpected{Status{RippledError::RpcInvalidParams, "missingTokenID"}}; if (!request.at(JS(nft_id)).is_string()) - return std::unexpected{Status{RippledError::rpcINVALID_PARAMS, "tokenIDNotString"}}; + return std::unexpected{Status{RippledError::RpcInvalidParams, "tokenIDNotString"}}; - ripple::uint256 tokenid; + xrpl::uint256 tokenid; if (!tokenid.parseHex(boost::json::value_to(request.at(JS(nft_id))))) - return std::unexpected{Status{RippledError::rpcINVALID_PARAMS, "malformedTokenID"}}; + return std::unexpected{Status{RippledError::RpcInvalidParams, "malformedTokenID"}}; return tokenid; } @@ -1652,8 +1648,8 @@ toJsonWithBinaryTx(data::TransactionAndMetadata const& txnPlusMeta, std::uint32_ { boost::json::object obj{}; auto const metaKey = apiVersion > 1 ? JS(meta_blob) : JS(meta); - obj[metaKey] = ripple::strHex(txnPlusMeta.metadata); - obj[JS(tx_blob)] = ripple::strHex(txnPlusMeta.transaction); + obj[metaKey] = xrpl::strHex(txnPlusMeta.metadata); + obj[JS(tx_blob)] = xrpl::strHex(txnPlusMeta.transaction); return obj; } diff --git a/src/rpc/RPCHelpers.hpp b/src/rpc/RPCHelpers.hpp index 231513c35..5fbeac1c1 100644 --- a/src/rpc/RPCHelpers.hpp +++ b/src/rpc/RPCHelpers.hpp @@ -21,7 +21,6 @@ #include #include #include -#include #include #include #include @@ -65,16 +64,18 @@ namespace rpc { -/** @brief Enum for NFT json manipulation */ +/** + * @brief Enum for NFT json manipulation + */ enum class NFTokenjson { ENABLE, DISABLE }; /** - * @brief Get a ripple::AccountID from its string representation + * @brief Get a xrpl::AccountID from its string representation * * @param account The string representation of the account * @return The account ID or std::nullopt if the string is not a valid account */ -std::optional +std::optional accountFromStringStrict(std::string const& account); /** @@ -85,7 +86,7 @@ accountFromStringStrict(std::string const& account); * @return true if the SLE is owned by the account */ bool -isOwnedByAccount(ripple::SLE const& sle, ripple::AccountID const& accountID); +isOwnedByAccount(xrpl::SLE const& sle, xrpl::AccountID const& accountID); /** * @brief Get the start hint for the account @@ -95,7 +96,7 @@ isOwnedByAccount(ripple::SLE const& sle, ripple::AccountID const& accountID); * @return The start hint */ std::uint64_t -getStartHint(ripple::SLE const& sle, ripple::AccountID const& accountID); +getStartHint(xrpl::SLE const& sle, xrpl::AccountID const& accountID); /** * @brief Parse the account cursor from the JSON @@ -113,7 +114,7 @@ parseAccountCursor(std::optional jsonCursor); * @param blobs The TransactionAndMetadata to deserialize * @return The deserialized objects */ -std::pair, std::shared_ptr> +std::pair, std::shared_ptr> deserializeTxPlusMeta(data::TransactionAndMetadata const& blobs); // TODO this function should probably be in a different file and namespace @@ -124,7 +125,7 @@ deserializeTxPlusMeta(data::TransactionAndMetadata const& blobs); * @param seq The sequence number to set * @return The deserialized objects */ -std::pair, std::shared_ptr> +std::pair, std::shared_ptr> deserializeTxPlusMeta(data::TransactionAndMetadata const& blobs, std::uint32_t seq); /** @@ -175,8 +176,8 @@ insertDeliverMaxAlias(boost::json::object& txJson, std::uint32_t apiVersion); bool insertDeliveredAmount( boost::json::object& metaJson, - std::shared_ptr const& txn, - std::shared_ptr const& meta, + std::shared_ptr const& txn, + std::shared_ptr const& meta, uint32_t date ); @@ -195,9 +196,9 @@ insertDeliveredAmount( bool insertMPTIssuanceID( boost::json::object& txnJson, - std::shared_ptr const& txn, + std::shared_ptr const& txn, boost::json::object& metaJson, - std::shared_ptr const& meta + std::shared_ptr const& meta ); /** @@ -207,7 +208,7 @@ insertMPTIssuanceID( * @return The JSON object */ boost::json::object -toJson(ripple::STBase const& obj); +toJson(xrpl::STBase const& obj); /** * @brief Convert SLE to JSON @@ -216,7 +217,7 @@ toJson(ripple::STBase const& obj); * @return The JSON object */ boost::json::object -toJson(ripple::SLE const& sle); +toJson(xrpl::SLE const& sle); /** * @brief Convert a LedgerHeader to JSON object. @@ -227,7 +228,7 @@ toJson(ripple::SLE const& sle); * @return The JSON object. */ boost::json::object -toJson(ripple::LedgerHeader const& info, bool binary, std::uint32_t apiVersion); +toJson(xrpl::LedgerHeader const& info, bool binary, std::uint32_t apiVersion); /** * @brief Convert a TxMeta to JSON object. @@ -236,9 +237,9 @@ toJson(ripple::LedgerHeader const& info, bool binary, std::uint32_t apiVersion); * @return The JSON object. */ boost::json::object -toJson(ripple::TxMeta const& meta); +toJson(xrpl::TxMeta const& meta); -using RippledJson = Json::Value; +using RippledJson = json::Value; /** * @brief Convert a RippledJson to boost::json::value @@ -260,8 +261,8 @@ toBoostJson(RippledJson const& value); */ boost::json::object generatePubLedgerMessage( - ripple::LedgerHeader const& lgrInfo, - ripple::Fees const& fees, + xrpl::LedgerHeader const& lgrInfo, + xrpl::Fees const& fees, std::string const& ledgerRange, std::uint32_t txnCount ); @@ -273,7 +274,7 @@ generatePubLedgerMessage( * @param ctx The context of the request * @return The ledger info or an error status */ -std::expected +std::expected ledgerHeaderFromRequest( std::shared_ptr const& backend, web::Context const& ctx @@ -289,7 +290,7 @@ ledgerHeaderFromRequest( * @param maxSeq The maximum sequence to search * @return The ledger info or an error status */ -std::expected +std::expected getLedgerHeaderFromHashOrSeq( BackendInterface const& backend, boost::asio::yield_context yield, @@ -314,13 +315,13 @@ getLedgerHeaderFromHashOrSeq( std::expected traverseOwnedNodes( BackendInterface const& backend, - ripple::Keylet const& owner, - ripple::uint256 const& hexMarker, + xrpl::Keylet const& owner, + xrpl::uint256 const& hexMarker, std::uint32_t startHint, std::uint32_t sequence, std::uint32_t limit, boost::asio::yield_context yield, - std::function atOwnedNode + std::function atOwnedNode ); /** @@ -341,12 +342,12 @@ traverseOwnedNodes( std::expected traverseOwnedNodes( BackendInterface const& backend, - ripple::AccountID const& accountID, + xrpl::AccountID const& accountID, std::uint32_t sequence, std::uint32_t limit, std::optional jsonCursor, boost::asio::yield_context yield, - std::function atOwnedNode, + std::function atOwnedNode, bool nftIncluded = false ); @@ -359,11 +360,11 @@ traverseOwnedNodes( * @param context The context of the request * @return The SLE or nullptr if not found */ -std::shared_ptr +std::shared_ptr read( std::shared_ptr const& backend, - ripple::Keylet const& keylet, - ripple::LedgerHeader const& lgrInfo, + xrpl::Keylet const& keylet, + xrpl::LedgerHeader const& lgrInfo, web::Context const& context ); @@ -373,7 +374,7 @@ read( * @param transaction The transaction * @return A vector of accounts associated with the transaction */ -std::vector +std::vector getAccountsFromTransaction(boost::json::object const& transaction); /** @@ -384,7 +385,7 @@ getAccountsFromTransaction(boost::json::object const& transaction); * @return The blob */ std::vector -ledgerHeaderToBlob(ripple::LedgerHeader const& info, bool includeHash = false); +ledgerHeaderToBlob(xrpl::LedgerHeader const& info, bool includeHash = false); /** * @brief Whether global frozen is set @@ -399,7 +400,7 @@ bool isGlobalFrozen( BackendInterface const& backend, std::uint32_t seq, - ripple::AccountID const& issuer, + xrpl::AccountID const& issuer, boost::asio::yield_context yield ); @@ -418,9 +419,9 @@ bool isFrozen( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& account, - ripple::Currency const& currency, - ripple::AccountID const& issuer, + xrpl::AccountID const& account, + xrpl::Currency const& currency, + xrpl::AccountID const& issuer, boost::asio::yield_context yield ); @@ -438,7 +439,7 @@ bool fetchAndCheckAnyFlagsExists( BackendInterface const& backend, std::uint32_t sequence, - ripple::Keylet const& keylet, + xrpl::Keylet const& keylet, std::vector const& flags, boost::asio::yield_context yield ); @@ -461,9 +462,9 @@ bool isDeepFrozen( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& account, - ripple::Currency const& currency, - ripple::AccountID const& issuer, + xrpl::AccountID const& account, + xrpl::Currency const& currency, + xrpl::AccountID const& issuer, boost::asio::yield_context yield ); @@ -482,9 +483,9 @@ bool isLPTokenFrozen( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& account, - ripple::Issue const& asset, - ripple::Issue const& asset2, + xrpl::AccountID const& account, + xrpl::Issue const& asset, + xrpl::Issue const& asset2, boost::asio::yield_context yield ); @@ -499,13 +500,13 @@ isLPTokenFrozen( * @param yield The coroutine context * @return The account funds */ -ripple::STAmount +xrpl::STAmount accountFunds( BackendInterface const& backend, data::AmendmentCenterInterface const& amendmentCenter, std::uint32_t sequence, - ripple::STAmount const& amount, - ripple::AccountID const& id, + xrpl::STAmount const& amount, + xrpl::AccountID const& id, boost::asio::yield_context yield ); @@ -522,14 +523,14 @@ accountFunds( * @param yield The coroutine context * @return The amount account holds */ -ripple::STAmount +xrpl::STAmount accountHolds( BackendInterface const& backend, data::AmendmentCenterInterface const& amendmentCenter, std::uint32_t sequence, - ripple::AccountID const& account, - ripple::Currency const& currency, - ripple::AccountID const& issuer, + xrpl::AccountID const& account, + xrpl::Currency const& currency, + xrpl::AccountID const& issuer, bool zeroIfFrozen, boost::asio::yield_context yield ); @@ -546,13 +547,13 @@ accountHolds( * @param yield The coroutine context * @return The amount account holds */ -ripple::STAmount +xrpl::STAmount ammAccountHolds( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& account, - ripple::Currency const& currency, - ripple::AccountID const& issuer, + xrpl::AccountID const& account, + xrpl::Currency const& currency, + xrpl::AccountID const& issuer, bool const zeroIfFrozen, boost::asio::yield_context yield ); @@ -566,11 +567,11 @@ ammAccountHolds( * @param yield The coroutine context * @return The transfer rate */ -ripple::Rate +xrpl::Rate transferRate( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& issuer, + xrpl::AccountID const& issuer, boost::asio::yield_context yield ); @@ -583,11 +584,11 @@ transferRate( * @param yield The coroutine context * @return The XRP liquidity */ -ripple::XRPAmount +xrpl::XRPAmount xrpLiquid( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& id, + xrpl::AccountID const& id, boost::asio::yield_context yield ); @@ -606,8 +607,8 @@ xrpLiquid( boost::json::array postProcessOrderBook( std::vector const& offers, - ripple::Book const& book, - ripple::AccountID const& takerID, + xrpl::Book const& book, + xrpl::AccountID const& takerID, data::BackendInterface const& backend, data::AmendmentCenterInterface const& amendmentCenter, std::uint32_t ledgerSequence, @@ -624,12 +625,12 @@ postProcessOrderBook( * @param domain The domain * @return The book or an error status */ -std::expected +std::expected parseBook( - ripple::Currency pays, - ripple::AccountID payIssuer, - ripple::Currency gets, - ripple::AccountID getIssuer, + xrpl::Currency pays, + xrpl::AccountID payIssuer, + xrpl::Currency gets, + xrpl::AccountID getIssuer, std::optional const& domain ); @@ -639,7 +640,7 @@ parseBook( * @param request The request * @return The book or an error status */ -std::expected +std::expected parseBook(boost::json::object const& request); /** @@ -648,17 +649,17 @@ parseBook(boost::json::object const& request); * @param taker The taker as json * @return The taker account or an error status */ -std::expected +std::expected parseTaker(boost::json::value const& taker); /** - * @brief Parse the json object into a ripple::Issue object. + * @brief Parse the json object into a xrpl::Issue object. * @param issue The json object to parse. The accepted format is { "currency" : "USD", "issuer" : * "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59" } or {"currency" : "XRP"} - * @return The ripple::Issue object. - * @exception raise Json::error exception if the json object is not in the accepted format. + * @return The xrpl::Issue object. + * @exception raise json::error exception if the json object is not in the accepted format. */ -ripple::Issue +xrpl::Issue parseIssue(boost::json::object const& issue); /** @@ -685,7 +686,7 @@ isAdminCmd(std::string const& method, boost::json::object const& request); * @param request The request * @return The NFTID or an error status */ -std::expected +std::expected getNFTID(boost::json::object const& request); /** @@ -713,8 +714,8 @@ decodeCTID(T const ctid) noexcept auto const getCTID64 = [](T const ctid) noexcept -> std::optional { if constexpr (std::is_convertible_v) { std::string const ctidString(ctid); - static constexpr std::size_t kCTID_STRING_LENGTH = 16; - if (ctidString.length() != kCTID_STRING_LENGTH) + static constexpr std::size_t kCtidStringLength = 16; + if (ctidString.length() != kCtidStringLength) return {}; if (!boost::regex_match(ctidString, boost::regex("^[0-9A-F]+$"))) @@ -731,10 +732,10 @@ decodeCTID(T const ctid) noexcept auto const ctidValue = getCTID64(ctid).value_or(0); - static constexpr uint64_t kCTID_PREFIX = 0xC000'0000'0000'0000ULL; - static constexpr uint64_t kCTID_PREFIX_MASK = 0xF000'0000'0000'0000ULL; + static constexpr uint64_t kCtidPrefix = 0xC000'0000'0000'0000ULL; + static constexpr uint64_t kCtidPrefixMask = 0xF000'0000'0000'0000ULL; - if ((ctidValue & kCTID_PREFIX_MASK) != kCTID_PREFIX) + if ((ctidValue & kCtidPrefixMask) != kCtidPrefix) return {}; uint32_t const ledgerSeq = (ctidValue >> 32) & 0xFFFF'FFFUL; @@ -762,7 +763,7 @@ logDuration( using boost::json::serialize; static util::Logger const log{"RPC"}; // NOLINT(readability-identifier-naming) - static constexpr std::int64_t kDURATION_ERROR_THRESHOLD_SECONDS = 10; + static constexpr std::int64_t kDurationErrorThresholdSeconds = 10; auto const millis = std::chrono::duration_cast(dur).count(); auto const seconds = std::chrono::duration_cast(dur).count(); @@ -772,12 +773,13 @@ logDuration( serialize(util::removeSecret(request)) ); - if (seconds > kDURATION_ERROR_THRESHOLD_SECONDS) { + if (seconds > kDurationErrorThresholdSeconds) { LOG(log.error()) << tag << msg; } else if (seconds > 1) { LOG(log.warn()) << tag << msg; - } else + } else { LOG(log.info()) << tag << msg; + } } /** @@ -786,7 +788,7 @@ logDuration( * @param value JSON value to parse from * @return The parsed seed if successful; std::nullopt otherwise */ -std::optional +std::optional parseRippleLibSeed(boost::json::value const& value); /** @@ -805,11 +807,11 @@ std::expected traverseNFTObjects( BackendInterface const& backend, std::uint32_t sequence, - ripple::AccountID const& accountID, - ripple::uint256 nextPage, + xrpl::AccountID const& accountID, + xrpl::uint256 nextPage, std::uint32_t limit, boost::asio::yield_context yield, - std::function atOwnedNode + std::function atOwnedNode ); /** @@ -830,8 +832,8 @@ parseStringAsUInt(std::string const& value); // TODO: move to string utils or s */ bool canHaveDeliveredAmount( - std::shared_ptr const& txn, - std::shared_ptr const& meta + std::shared_ptr const& txn, + std::shared_ptr const& meta ); /** @@ -843,10 +845,10 @@ canHaveDeliveredAmount( * @param date The date of the ledger * @return The delivered amount or std::nullopt if not available */ -std::optional +std::optional getDeliveredAmount( - std::shared_ptr const& txn, - std::shared_ptr const& meta, + std::shared_ptr const& txn, + std::shared_ptr const& meta, std::uint32_t ledgerSequence, uint32_t date ); diff --git a/src/rpc/WorkQueue.cpp b/src/rpc/WorkQueue.cpp index 89a72872d..02dc8e4ad 100644 --- a/src/rpc/WorkQueue.cpp +++ b/src/rpc/WorkQueue.cpp @@ -62,7 +62,7 @@ WorkQueue::WorkQueue(DontStartProcessingTag, std::uint32_t numWorkers, uint32_t } WorkQueue::WorkQueue(std::uint32_t numWorkers, uint32_t maxSize) - : WorkQueue(kDONT_START_PROCESSING_TAG, numWorkers, maxSize) + : WorkQueue(kDontStartProcessingTag, numWorkers, maxSize) { startProcessing(); } diff --git a/src/rpc/WorkQueue.hpp b/src/rpc/WorkQueue.hpp index 8a6483275..bf99f2e5f 100644 --- a/src/rpc/WorkQueue.hpp +++ b/src/rpc/WorkQueue.hpp @@ -90,7 +90,7 @@ private: [[nodiscard]] std::optional popNext() { - if (not high.empty() and (highPriorityCounter < kTAKE_HIGH_PRIO or normal.empty())) { + if (not high.empty() and (highPriorityCounter < kTakeHighPrio or normal.empty())) { auto taskWithTimestamp = std::move(high.front()); high.pop(); ++highPriorityCounter; @@ -109,7 +109,7 @@ private: }; private: - static constexpr auto kTAKE_HIGH_PRIO = 4uz; + static constexpr auto kTakeHighPrio = 4uz; // these are cumulative for the lifetime of the process std::reference_wrapper queued_; @@ -143,7 +143,7 @@ private: public: struct DontStartProcessingTag {}; - static constexpr DontStartProcessingTag kDONT_START_PROCESSING_TAG = {}; + static constexpr DontStartProcessingTag kDontStartProcessingTag = {}; /** * @brief Create an instance of the work queue. diff --git a/src/rpc/common/APIVersion.hpp b/src/rpc/common/APIVersion.hpp index faca665a4..bbf65b48f 100644 --- a/src/rpc/common/APIVersion.hpp +++ b/src/rpc/common/APIVersion.hpp @@ -11,17 +11,17 @@ namespace rpc { /** * @brief Default API version to use if no version is specified by clients */ -static constexpr uint32_t kAPI_VERSION_DEFAULT = 1u; +static constexpr uint32_t kApiVersionDefault = 1u; /** * @brief Minimum API version supported by this build */ -static constexpr uint32_t kAPI_VERSION_MIN = 1u; +static constexpr uint32_t kApiVersionMin = 1u; /** * @brief Maximum API version supported by this build */ -static constexpr uint32_t kAPI_VERSION_MAX = 3u; +static constexpr uint32_t kApiVersionMax = 3u; /** * @brief A baseclass for API version helper diff --git a/src/rpc/common/Concepts.hpp b/src/rpc/common/Concepts.hpp index 9f6dc3855..c455b2ded 100644 --- a/src/rpc/common/Concepts.hpp +++ b/src/rpc/common/Concepts.hpp @@ -51,7 +51,7 @@ concept SomeProcessor = (SomeRequirement or SomeModifier); */ template concept SomeContextProcessWithInput = - requires(T a, typename T::Input const& in, typename T::Output out, Context const& ctx) { + requires(T a, T::Input const& in, T::Output out, Context const& ctx) { { a.process(in, ctx) } -> std::same_as>; }; @@ -59,7 +59,7 @@ concept SomeContextProcessWithInput = * @brief A process function that expects no Input but does take a Context. */ template -concept SomeContextProcessWithoutInput = requires(T a, typename T::Output out, Context const& ctx) { +concept SomeContextProcessWithoutInput = requires(T a, T::Output out, Context const& ctx) { { a.process(ctx) } -> std::same_as>; }; diff --git a/src/rpc/common/MetaProcessors.cpp b/src/rpc/common/MetaProcessors.cpp index d4a3aa94f..a5ab8cc7c 100644 --- a/src/rpc/common/MetaProcessors.cpp +++ b/src/rpc/common/MetaProcessors.cpp @@ -36,11 +36,11 @@ ValidateArrayAt::verify(boost::json::value& value, std::string_view key) const return {}; // ignore. field does not exist, let 'required' fail instead if (not value.as_object().at(key).is_array()) - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; auto& arr = value.as_object().at(key).as_array(); if (idx_ >= arr.size()) - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; auto& res = arr.at(idx_); for (auto const& spec : specs_) { diff --git a/src/rpc/common/Modifiers.hpp b/src/rpc/common/Modifiers.hpp index 33262cf67..0b621220b 100644 --- a/src/rpc/common/Modifiers.hpp +++ b/src/rpc/common/Modifiers.hpp @@ -109,13 +109,13 @@ struct ToNumber final { return {}; // ignore for non-string types auto const strInt = boost::json::value_to(value.as_object().at(key)); - if (strInt.find('.') != std::string::npos) - return Error{Status{RippledError::rpcINVALID_PARAMS}}; // maybe a float + if (strInt.contains('.')) + return Error{Status{RippledError::RpcInvalidParams}}; // maybe a float try { value.as_object()[key] = std::stoi(strInt); } catch (std::exception& e) { - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; } return {}; } diff --git a/src/rpc/common/Specs.hpp b/src/rpc/common/Specs.hpp index 36da6b0c6..f3996da37 100644 --- a/src/rpc/common/Specs.hpp +++ b/src/rpc/common/Specs.hpp @@ -32,7 +32,7 @@ struct FieldSpec final { : processor_{ impl::makeFieldProcessor(key, std::forward(processors)...) } - , checker_{impl::kEMPTY_FIELD_CHECKER} + , checker_{impl::kEmptyFieldChecker} { } @@ -45,7 +45,7 @@ struct FieldSpec final { */ template FieldSpec(std::string const& key, Checks&&... checks) - : processor_{impl::kEMPTY_FIELD_PROCESSOR} + : processor_{impl::kEmptyFieldProcessor} , checker_{impl::makeFieldChecker(key, std::forward(checks)...)} { } diff --git a/src/rpc/common/Types.hpp b/src/rpc/common/Types.hpp index 159f19c6b..d2798c1e9 100644 --- a/src/rpc/common/Types.hpp +++ b/src/rpc/common/Types.hpp @@ -149,7 +149,7 @@ struct Result { * @brief A cursor object used to traverse nodes owned by an account. */ struct AccountCursor { - ripple::uint256 index; + xrpl::uint256 index; std::uint32_t hint{}; /** @@ -160,7 +160,7 @@ struct AccountCursor { [[nodiscard]] std::string toString() const { - return ripple::strHex(index) + "," + std::to_string(hint); + return xrpl::strHex(index) + "," + std::to_string(hint); } /** diff --git a/src/rpc/common/Validators.cpp b/src/rpc/common/Validators.cpp index a745bf342..9be9275a3 100644 --- a/src/rpc/common/Validators.cpp +++ b/src/rpc/common/Validators.cpp @@ -20,7 +20,6 @@ #include #include -#include #include #include #include @@ -34,7 +33,7 @@ Required::verify(boost::json::value const& value, std::string_view key) { if (not value.is_object() or not value.as_object().contains(key)) { return Error{Status{ - RippledError::rpcINVALID_PARAMS, "Required field '" + std::string{key} + "' missing" + RippledError::RpcInvalidParams, "Required field '" + std::string{key} + "' missing" }}; } @@ -50,12 +49,12 @@ TimeFormatValidator::verify(boost::json::value const& value, std::string_view ke return {}; // ignore. field does not exist, let 'required' fail instead if (not value.as_object().at(key).is_string()) - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; auto const ret = util::systemTpFromUtcStr(value_to(value.as_object().at(key)), format_); if (!ret) - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; return {}; } @@ -80,22 +79,22 @@ checkIsU32Numeric(std::string_view sv) CustomValidator CustomValidators::uint160HexStringValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { - return makeHexStringValidator(value, key); + return makeHexStringValidator(value, key); }}; CustomValidator CustomValidators::uint192HexStringValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { - return makeHexStringValidator(value, key); + return makeHexStringValidator(value, key); }}; CustomValidator CustomValidators::uint256HexStringValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { - return makeHexStringValidator(value, key); + return makeHexStringValidator(value, key); }}; CustomValidator CustomValidators::ledgerIndexValidator = CustomValidator{[](boost::json::value const& value, std::string_view /* key */) -> MaybeError { - auto err = Error{Status{RippledError::rpcINVALID_PARAMS, "ledgerIndexMalformed"}}; + auto err = Error{Status{RippledError::RpcInvalidParams, "ledgerIndexMalformed"}}; if (!value.is_string() && !(value.is_uint64() || value.is_int64())) return err; @@ -111,15 +110,15 @@ CustomValidator CustomValidators::ledgerTypeValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_string()) { return Error{Status{ - RippledError::rpcINVALID_PARAMS, fmt::format("Invalid field '{}', not string.", key) + RippledError::RpcInvalidParams, fmt::format("Invalid field '{}', not string.", key) }}; } auto const type = util::LedgerTypes::getLedgerEntryTypeFromStr(boost::json::value_to(value)); - if (type == ripple::ltANY) { + if (type == xrpl::ltANY) { return Error{ - Status{RippledError::rpcINVALID_PARAMS, fmt::format("Invalid field '{}'.", key)} + Status{RippledError::RpcInvalidParams, fmt::format("Invalid field '{}'.", key)} }; } @@ -129,12 +128,12 @@ CustomValidator CustomValidators::ledgerTypeValidator = CustomValidator CustomValidators::accountValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_string()) - return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotString"}}; + return Error{Status{RippledError::RpcInvalidParams, std::string(key) + "NotString"}}; // TODO: we are using accountFromStringStrict from RPCHelpers, after we // remove all old handler, this function can be moved to here if (!accountFromStringStrict(boost::json::value_to(value))) - return Error{Status{RippledError::rpcACT_MALFORMED, std::string(key) + "Malformed"}}; + return Error{Status{RippledError::RpcActMalformed, std::string(key) + "Malformed"}}; return MaybeError{}; }}; @@ -142,10 +141,10 @@ CustomValidator CustomValidators::accountValidator = CustomValidator CustomValidators::accountBase58Validator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_string()) - return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotString"}}; + return Error{Status{RippledError::RpcInvalidParams, std::string(key) + "NotString"}}; auto const account = - util::parseBase58Wrapper(boost::json::value_to(value)); + util::parseBase58Wrapper(boost::json::value_to(value)); if (!account || account->isZero()) return Error{Status{ClioError::RpcMalformedAddress}}; @@ -155,13 +154,13 @@ CustomValidator CustomValidators::accountBase58Validator = CustomValidator CustomValidators::accountMarkerValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_string()) - return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotString"}}; + return Error{Status{RippledError::RpcInvalidParams, std::string(key) + "NotString"}}; // TODO: we are using parseAccountCursor from RPCHelpers, after we // remove all old handler, this function can be moved to here if (!parseAccountCursor(boost::json::value_to(value))) { // align with the current error message - return Error{Status{RippledError::rpcINVALID_PARAMS, "Malformed cursor."}}; + return Error{Status{RippledError::RpcInvalidParams, "Malformed cursor."}}; } return MaybeError{}; @@ -171,16 +170,16 @@ CustomValidator CustomValidators::accountTypeValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_string()) { return Error{Status{ - RippledError::rpcINVALID_PARAMS, fmt::format("Invalid field '{}', not string.", key) + RippledError::RpcInvalidParams, fmt::format("Invalid field '{}', not string.", key) }}; } auto const type = util::LedgerTypes::getAccountOwnedLedgerTypeFromStr( boost::json::value_to(value) ); - if (type == ripple::ltANY) { + if (type == xrpl::ltANY) { return Error{ - Status{RippledError::rpcINVALID_PARAMS, fmt::format("Invalid field '{}'.", key)} + Status{RippledError::RpcInvalidParams, fmt::format("Invalid field '{}'.", key)} }; } @@ -190,14 +189,14 @@ CustomValidator CustomValidators::accountTypeValidator = CustomValidator CustomValidators::currencyValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_string()) - return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotString"}}; + return Error{Status{RippledError::RpcInvalidParams, std::string(key) + "NotString"}}; auto const currencyStr = boost::json::value_to(value); if (currencyStr.empty()) - return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "IsEmpty"}}; + return Error{Status{RippledError::RpcInvalidParams, std::string(key) + "IsEmpty"}}; - ripple::Currency currency; - if (!ripple::to_currency(currency, currencyStr)) + xrpl::Currency currency; + if (!xrpl::toCurrency(currency, currencyStr)) return Error{Status{ClioError::RpcMalformedCurrency, "malformedCurrency"}}; return MaybeError{}; @@ -206,20 +205,20 @@ CustomValidator CustomValidators::currencyValidator = CustomValidator CustomValidators::issuerValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_string()) - return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotString"}}; + return Error{Status{RippledError::RpcInvalidParams, std::string(key) + "NotString"}}; - ripple::AccountID issuer; + xrpl::AccountID issuer; // TODO: need to align with the error - if (!ripple::to_issuer(issuer, boost::json::value_to(value))) { + if (!xrpl::toIssuer(issuer, boost::json::value_to(value))) { return Error{Status{ - RippledError::rpcINVALID_PARAMS, fmt::format("Invalid field '{}', bad issuer.", key) + RippledError::RpcInvalidParams, fmt::format("Invalid field '{}', bad issuer.", key) }}; } - if (issuer == ripple::noAccount()) { + if (issuer == xrpl::noAccount()) { return Error{Status{ - RippledError::rpcINVALID_PARAMS, + RippledError::RpcInvalidParams, fmt::format("Invalid field '{}', bad issuer account one.", key) }}; } @@ -230,9 +229,9 @@ CustomValidator CustomValidators::issuerValidator = CustomValidator CustomValidators::subscribeStreamValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_array()) - return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotArray"}}; + return Error{Status{RippledError::RpcInvalidParams, std::string(key) + "NotArray"}}; - static std::unordered_set const kVALID_STREAMS = { + static std::unordered_set const kValidStreams = { "ledger", "transactions", "transactions_proposed", @@ -241,18 +240,18 @@ CustomValidator CustomValidators::subscribeStreamValidator = "validations" }; - static std::unordered_set const kNOT_SUPPORT_STREAMS = { + static std::unordered_set const kNotSupportStreams = { "peer_status", "consensus", "server" }; for (auto const& v : value.as_array()) { if (!v.is_string()) - return Error{Status{RippledError::rpcINVALID_PARAMS, "streamNotString"}}; + return Error{Status{RippledError::RpcInvalidParams, "streamNotString"}}; - if (kNOT_SUPPORT_STREAMS.contains(boost::json::value_to(v))) - return Error{Status{RippledError::rpcNOT_SUPPORTED}}; + if (kNotSupportStreams.contains(boost::json::value_to(v))) + return Error{Status{RippledError::RpcNotSupported}}; - if (not kVALID_STREAMS.contains(boost::json::value_to(v))) - return Error{Status{RippledError::rpcSTREAM_MALFORMED}}; + if (not kValidStreams.contains(boost::json::value_to(v))) + return Error{Status{RippledError::RpcStreamMalformed}}; } return MaybeError{}; @@ -261,10 +260,10 @@ CustomValidator CustomValidators::subscribeStreamValidator = CustomValidator CustomValidators::subscribeAccountsValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_array()) - return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotArray"}}; + return Error{Status{RippledError::RpcInvalidParams, std::string(key) + "NotArray"}}; if (value.as_array().empty()) - return Error{Status{RippledError::rpcACT_MALFORMED, std::string(key) + " malformed."}}; + return Error{Status{RippledError::RpcActMalformed, std::string(key) + " malformed."}}; for (auto const& v : value.as_array()) { auto obj = boost::json::object(); @@ -282,7 +281,7 @@ CustomValidator CustomValidators::subscribeAccountsValidator = CustomValidator CustomValidators::currencyIssueValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (not value.is_object()) - return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotObject"}}; + return Error{Status{RippledError::RpcInvalidParams, std::string(key) + "NotObject"}}; try { parseIssue(value.as_object()); @@ -301,7 +300,7 @@ CustomValidator CustomValidators::credentialTypeValidator = }}; } - auto const& credTypeHex = ripple::strViewUnHex(value.as_string()); + auto const& credTypeHex = xrpl::strUnHex(value.as_string()); if (!credTypeHex.has_value()) { return Error{Status{ ClioError::RpcMalformedAuthorizedCredentials, std::string(key) + " NotHexString" @@ -314,7 +313,7 @@ CustomValidator CustomValidators::credentialTypeValidator = }; } - if (credTypeHex->size() > ripple::maxCredentialTypeLength) { + if (credTypeHex->size() > xrpl::kMaxCredentialTypeLength) { return Error{Status{ ClioError::RpcMalformedAuthorizedCredentials, std::string(key) + " greater than max length" @@ -337,12 +336,12 @@ CustomValidator CustomValidators::authorizeCredentialValidator = }}; } - if (authCred.size() > ripple::maxCredentialsArraySize) { + if (authCred.size() > xrpl::kMaxCredentialsArraySize) { return Error{Status{ ClioError::RpcMalformedAuthorizedCredentials, fmt::format( "Max {} number of credentials in authorized_credentials array", - ripple::maxCredentialsArraySize + xrpl::kMaxCredentialsArraySize ) }}; } diff --git a/src/rpc/common/Validators.hpp b/src/rpc/common/Validators.hpp index c4e053d88..5c5cccbc3 100644 --- a/src/rpc/common/Validators.hpp +++ b/src/rpc/common/Validators.hpp @@ -69,7 +69,7 @@ public: * * @param value The JSON value representing the outer object * @param key The key used to retrieve the tested value from the outer object - * @return `RippledError::rpcNOT_SUPPORTED` if the value matched; otherwise no error is returned + * @return `RippledError::RpcNotSupported` if the value matched; otherwise no error is returned */ [[nodiscard]] MaybeError verify(boost::json::value const& value, std::string_view key) const @@ -79,7 +79,7 @@ public: auto const res = value_to(value.as_object().at(key)); if (value_ == res) { return Error{Status{ - RippledError::rpcNOT_SUPPORTED, + RippledError::RpcNotSupported, fmt::format("Not supported field '{}'s value '{}'", std::string{key}, res) }}; } @@ -99,7 +99,7 @@ public: * * @param value The JSON value representing the outer object * @param key The key used to retrieve the tested value from the outer object - * @return `RippledError::rpcNOT_SUPPORTED` if the field is found; otherwise no error is + * @return `RippledError::RpcNotSupported` if the field is found; otherwise no error is * returned */ [[nodiscard]] static MaybeError @@ -107,7 +107,7 @@ public: { if (value.is_object() and value.as_object().contains(key)) { return Error{Status{ - RippledError::rpcNOT_SUPPORTED, "Not supported field '" + std::string{key} + '\'' + RippledError::RpcNotSupported, "Not supported field '" + std::string{key} + '\'' }}; } @@ -133,7 +133,7 @@ struct Type final { * * @param value The JSON value representing the outer object * @param key The key used to retrieve the tested value from the outer object - * @return `RippledError::rpcINVALID_PARAMS` if validation failed; otherwise no error is + * @return `RippledError::RpcInvalidParams` if validation failed; otherwise no error is * returned */ [[nodiscard]] MaybeError @@ -146,7 +146,7 @@ struct Type final { auto const convertible = (checkTypeAndClamp(res) || ...); if (not convertible) - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; return {}; } @@ -176,7 +176,7 @@ public: * * @param value The JSON value representing the outer object * @param key The key used to retrieve the tested value from the outer object - * @return `RippledError::rpcINVALID_PARAMS` if validation failed; otherwise no error is + * @return `RippledError::RpcInvalidParams` if validation failed; otherwise no error is * returned */ [[nodiscard]] MaybeError @@ -192,7 +192,7 @@ public: // TODO: may want a way to make this code more generic (e.g. use a free // function that can be overridden for this comparison) if (res < min_ || res > max_) - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; return {}; } @@ -220,7 +220,7 @@ public: * * @param value The JSON value representing the outer object * @param key The key used to retrieve the tested value from the outer object - * @return `RippledError::rpcINVALID_PARAMS` if validation failed; otherwise no error is + * @return `RippledError::RpcInvalidParams` if validation failed; otherwise no error is * returned */ [[nodiscard]] MaybeError @@ -234,7 +234,7 @@ public: auto const res = value_to(value.as_object().at(key)); if (res < min_) - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; return {}; } @@ -262,7 +262,7 @@ public: * * @param value The JSON value representing the outer object * @param key The key used to retrieve the tested value from the outer object - * @return `RippledError::rpcINVALID_PARAMS` if validation failed; otherwise no error is + * @return `RippledError::RpcInvalidParams` if validation failed; otherwise no error is * returned */ [[nodiscard]] MaybeError @@ -276,7 +276,7 @@ public: auto const res = value_to(value.as_object().at(key)); if (res > max_) - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; return {}; } @@ -303,7 +303,7 @@ public: * * @param value The JSON value representing the outer object * @param key The key used to retrieve the tested value from the outer object - * @return `RippledError::rpcINVALID_PARAMS` if validation failed; otherwise no error is + * @return `RippledError::RpcInvalidParams` if validation failed; otherwise no error is * returned */ [[nodiscard]] MaybeError @@ -332,7 +332,7 @@ public: * * @param value The JSON value representing the outer object * @param key The key used to retrieve the tested value from the outer object - * @return `RippledError::rpcINVALID_PARAMS` if validation failed; otherwise no error is + * @return `RippledError::RpcInvalidParams` if validation failed; otherwise no error is * returned */ [[nodiscard]] MaybeError @@ -345,7 +345,7 @@ public: auto const res = value_to(value.as_object().at(key)); if (res != original_) - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; return {}; } @@ -389,7 +389,7 @@ public: * * @param value The JSON value representing the outer object * @param key The key used to retrieve the tested value from the outer object - * @return `RippledError::rpcINVALID_PARAMS` if validation failed; otherwise no error is + * @return `RippledError::RpcInvalidParams` if validation failed; otherwise no error is * returned */ [[nodiscard]] MaybeError @@ -403,7 +403,7 @@ public: auto const res = value_to(value.as_object().at(key)); if (std::find(std::begin(options_), std::end(options_), res) == std::end(options_)) { return Error{ - Status{RippledError::rpcINVALID_PARAMS, fmt::format("Invalid field '{}'.", key)} + Status{RippledError::RpcInvalidParams, fmt::format("Invalid field '{}'.", key)} }; } @@ -460,18 +460,18 @@ checkIsU32Numeric(std::string_view sv); template requires( - std::is_same_v || std::is_same_v || - std::is_same_v + std::is_same_v || std::is_same_v || + std::is_same_v ) MaybeError makeHexStringValidator(boost::json::value const& value, std::string_view key) { if (!value.is_string()) - return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotString"}}; + return Error{Status{RippledError::RpcInvalidParams, std::string(key) + "NotString"}}; HexType parsedInt; if (!parsedInt.parseHex(value.as_string().c_str())) - return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "Malformed"}}; + return Error{Status{RippledError::RpcInvalidParams, std::string(key) + "Malformed"}}; return MaybeError{}; } @@ -574,7 +574,7 @@ struct CustomValidators final { static CustomValidator subscribeAccountsValidator; /** - * @brief Validates an asset (ripple::Issue). + * @brief Validates an asset (xrpl::Issue). * * Used by amm_info. */ @@ -605,7 +605,7 @@ struct Hex256ItemType final { * * @param value the value to verify * @param key The key used to retrieve the tested value from the outer object - * @return `RippledError::rpcINVALID_PARAMS` if validation failed; otherwise no error is + * @return `RippledError::RpcInvalidParams` if validation failed; otherwise no error is * returned */ [[nodiscard]] static MaybeError @@ -618,10 +618,10 @@ struct Hex256ItemType final { // loop through each item in the array and make sure it is uint256 hex string for (auto const& elem : res.as_array()) { - ripple::uint256 num; + xrpl::uint256 num; if (!elem.is_string() || !num.parseHex(elem.as_string())) { return Error{ - Status{RippledError::rpcINVALID_PARAMS, "Item is not a valid uint256 type."} + Status{RippledError::RpcInvalidParams, "Item is not a valid uint256 type."} }; } } diff --git a/src/rpc/common/impl/APIVersionParser.hpp b/src/rpc/common/impl/APIVersionParser.hpp index 4edbf4cf7..88cbce838 100644 --- a/src/rpc/common/impl/APIVersionParser.hpp +++ b/src/rpc/common/impl/APIVersionParser.hpp @@ -21,9 +21,9 @@ class ProductionAPIVersionParser : public APIVersionParser { public: ProductionAPIVersionParser( - uint32_t defaultVersion = kAPI_VERSION_DEFAULT, - uint32_t minVersion = kAPI_VERSION_MIN, - uint32_t maxVersion = kAPI_VERSION_MAX + uint32_t defaultVersion = kApiVersionDefault, + uint32_t minVersion = kApiVersionMin, + uint32_t maxVersion = kApiVersionMax ); ProductionAPIVersionParser(util::config::ObjectView const& config); diff --git a/src/rpc/common/impl/Factories.hpp b/src/rpc/common/impl/Factories.hpp index b0b107984..9980178fd 100644 --- a/src/rpc/common/impl/Factories.hpp +++ b/src/rpc/common/impl/Factories.hpp @@ -20,7 +20,7 @@ namespace rpc::impl { using FieldSpecProcessor = std::function; -static FieldSpecProcessor const kEMPTY_FIELD_PROCESSOR = [](boost::json::value&) -> MaybeError { +static FieldSpecProcessor const kEmptyFieldProcessor = [](boost::json::value&) -> MaybeError { return {}; }; @@ -60,7 +60,7 @@ makeFieldProcessor(std::string const& key, Processors&&... procs) using FieldChecker = std::function; -static FieldChecker const kEMPTY_FIELD_CHECKER = [](boost::json::value const&) -> check::Warnings { +static FieldChecker const kEmptyFieldChecker = [](boost::json::value const&) -> check::Warnings { return {}; }; diff --git a/src/rpc/common/impl/ForwardingProxy.hpp b/src/rpc/common/impl/ForwardingProxy.hpp index 29d06d727..ee29ec013 100644 --- a/src/rpc/common/impl/ForwardingProxy.hpp +++ b/src/rpc/common/impl/ForwardingProxy.hpp @@ -115,9 +115,9 @@ private: [[nodiscard]] bool isForcedForward(web::Context const& ctx) const { - static constexpr auto kFORCE_FORWARD = "force_forward"; - return ctx.isAdmin and ctx.params.contains(kFORCE_FORWARD) and - ctx.params.at(kFORCE_FORWARD).is_bool() and ctx.params.at(kFORCE_FORWARD).as_bool(); + static constexpr auto kForceForward = "force_forward"; + return ctx.isAdmin and ctx.params.contains(kForceForward) and + ctx.params.at(kForceForward).is_bool() and ctx.params.at(kForceForward).as_bool(); } }; diff --git a/src/rpc/handlers/AMMInfo.cpp b/src/rpc/handlers/AMMInfo.cpp index 08c19082b..3eb8f3002 100644 --- a/src/rpc/handlers/AMMInfo.cpp +++ b/src/rpc/handlers/AMMInfo.cpp @@ -43,15 +43,15 @@ namespace { std::string -toIso8601(ripple::NetClock::time_point tp) +toIso8601(xrpl::NetClock::time_point tp) { using namespace std::chrono; - static constexpr auto kRIPPLE_EPOCH_OFFSET = seconds{kRIPPLE_EPOCH_START}; + static constexpr auto kRippleEpochOffset = seconds{kRippleEpochStart}; return date::format( "%Y-%Om-%dT%H:%M:%OS%z", date::sys_time( - system_clock::time_point{tp.time_since_epoch() + kRIPPLE_EPOCH_OFFSET} + system_clock::time_point{tp.time_since_epoch() + kRippleEpochOffset} ) ); }; @@ -63,19 +63,19 @@ namespace rpc { AMMInfoHandler::Result AMMInfoHandler::process(AMMInfoHandler::Input const& input, Context const& ctx) const { - using namespace ripple; + using namespace xrpl; auto const hasInvalidParams = [&input] { // no asset/asset2 can be specified if amm account is specified if (input.ammAccount) - return input.issue1 != ripple::noIssue() || input.issue2 != ripple::noIssue(); + return input.issue1 != xrpl::noIssue() || input.issue2 != xrpl::noIssue(); // both assets must be specified when amm account is not specified - return input.issue1 == ripple::noIssue() || input.issue2 == ripple::noIssue(); + return input.issue1 == xrpl::noIssue() || input.issue2 == xrpl::noIssue(); }(); if (hasInvalidParams) - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "AMMInfo's ledger range must be available"); @@ -96,23 +96,23 @@ AMMInfoHandler::process(AMMInfoHandler::Input const& input, Context const& ctx) if (input.accountID) { auto keylet = keylet::account(*input.accountID); if (not sharedPtrBackend_->fetchLedgerObject(keylet.key, lgrInfo.seq, ctx.yield)) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; } - ripple::uint256 ammID; + xrpl::uint256 ammID; if (input.ammAccount) { auto const accountKeylet = keylet::account(*input.ammAccount); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject(accountKeylet.key, lgrInfo.seq, ctx.yield); if (not accountLedgerObject) - return Error{Status{RippledError::rpcACT_MALFORMED}}; - ripple::STLedgerEntry const sle{ - ripple::SerialIter{accountLedgerObject->data(), accountLedgerObject->size()}, + return Error{Status{RippledError::RpcActMalformed}}; + xrpl::STLedgerEntry const sle{ + xrpl::SerialIter{accountLedgerObject->data(), accountLedgerObject->size()}, accountKeylet.key }; - if (not sle.isFieldPresent(ripple::sfAMMID)) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; - ammID = sle.getFieldH256(ripple::sfAMMID); + if (not sle.isFieldPresent(xrpl::sfAMMID)) + return Error{Status{RippledError::RpcActNotFound}}; + ammID = sle.getFieldH256(xrpl::sfAMMID); } auto issue1 = input.issue1; @@ -122,7 +122,7 @@ AMMInfoHandler::process(AMMInfoHandler::Input const& input, Context const& ctx) sharedPtrBackend_->fetchLedgerObject(ammKeylet.key, lgrInfo.seq, ctx.yield); if (not ammBlob) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; auto const amm = SLE{SerialIter{ammBlob->data(), ammBlob->size()}, ammKeylet.key}; auto const ammAccountID = amm.getAccountID(sfAccount); @@ -130,12 +130,12 @@ AMMInfoHandler::process(AMMInfoHandler::Input const& input, Context const& ctx) keylet::account(ammAccountID).key, lgrInfo.seq, ctx.yield ); if (not accBlob) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; // If the issue1 and issue2 are not specified, we need to get them from the AMM. // Otherwise we preserve the mapping of asset1 -> issue1 and asset2 -> issue2 as requested by // the user. - if (issue1 == ripple::noIssue() and issue2 == ripple::noIssue()) { + if (issue1 == xrpl::noIssue() and issue2 == xrpl::noIssue()) { issue1 = amm[sfAsset].get(); issue2 = amm[sfAsset2].get(); } @@ -156,10 +156,10 @@ AMMInfoHandler::process(AMMInfoHandler::Input const& input, Context const& ctx) Output response; response.ledgerIndex = lgrInfo.seq; - response.ledgerHash = ripple::strHex(lgrInfo.hash); - response.amount1 = toBoostJson(asset1Balance.getJson(JsonOptions::none)); - response.amount2 = toBoostJson(asset2Balance.getJson(JsonOptions::none)); - response.lpToken = toBoostJson(lptAMMBalance.getJson(JsonOptions::none)); + response.ledgerHash = xrpl::strHex(lgrInfo.hash); + response.amount1 = toBoostJson(asset1Balance.getJson(JsonOptions::Values::None)); + response.amount2 = toBoostJson(asset2Balance.getJson(JsonOptions::Values::None)); + response.lpToken = toBoostJson(lptAMMBalance.getJson(JsonOptions::Values::None)); response.tradingFee = amm[sfTradingFee]; response.ammAccount = to_string(ammAccountID); @@ -181,8 +181,9 @@ AMMInfoHandler::process(AMMInfoHandler::Input const& input, Context const& ctx) auto const timeSlot = ammAuctionTimeSlot(lgrInfo.parentCloseTime.time_since_epoch().count(), auctionSlot); - auction[JS(time_interval)] = timeSlot ? *timeSlot : AUCTION_SLOT_TIME_INTERVALS; - auction[JS(price)] = toBoostJson(auctionSlot[sfPrice].getJson(JsonOptions::none)); + auction[JS(time_interval)] = timeSlot ? *timeSlot : xrpl::kAuctionSlotTimeIntervals; + auction[JS(price)] = + toBoostJson(auctionSlot[sfPrice].getJson(JsonOptions::Values::None)); auction[JS(discounted_fee)] = auctionSlot[sfDiscountedFee]; auction[JS(account)] = to_string(auctionSlot.getAccountID(sfAccount)); auction[JS(expiration)] = @@ -230,62 +231,62 @@ AMMInfoHandler::process(AMMInfoHandler::Input const& input, Context const& ctx) RpcSpecConstRef AMMInfoHandler::spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kSTRING_ISSUE_VALIDATOR = validation::CustomValidator{ + static auto const kStringIssueValidator = validation::CustomValidator{ [](boost::json::value const& value, std::string_view key) -> MaybeError { if (not value.is_string()) { return Error{ - Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotString"} + Status{RippledError::RpcInvalidParams, std::string(key) + "NotString"} }; } try { - ripple::issueFromJson(boost::json::value_to(value)); + xrpl::issueFromJson(boost::json::value_to(value)); } catch (std::runtime_error const&) { - return Error{Status{RippledError::rpcISSUE_MALFORMED}}; + return Error{Status{RippledError::RpcIssueMalformed}}; } return MaybeError{}; } }; - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(asset), meta::WithCustomError{ validation::Type{}, - Status(RippledError::rpcISSUE_MALFORMED) + Status(RippledError::RpcIssueMalformed) }, - meta::IfType{kSTRING_ISSUE_VALIDATOR}, + meta::IfType{kStringIssueValidator}, meta::IfType{ meta::WithCustomError{ validation::CustomValidators::currencyIssueValidator, - Status(RippledError::rpcISSUE_MALFORMED) + Status(RippledError::RpcIssueMalformed) }, }}, {JS(asset2), meta::WithCustomError{ validation::Type{}, - Status(RippledError::rpcISSUE_MALFORMED) + Status(RippledError::RpcIssueMalformed) }, - meta::IfType{kSTRING_ISSUE_VALIDATOR}, + meta::IfType{kStringIssueValidator}, meta::IfType{ meta::WithCustomError{ validation::CustomValidators::currencyIssueValidator, - Status(RippledError::rpcISSUE_MALFORMED) + Status(RippledError::RpcIssueMalformed) }, }}, {JS(amm_account), meta::WithCustomError{ - validation::CustomValidators::accountValidator, Status(RippledError::rpcACT_MALFORMED) + validation::CustomValidators::accountValidator, Status(RippledError::RpcActMalformed) }}, {JS(account), meta::WithCustomError{ - validation::CustomValidators::accountValidator, Status(RippledError::rpcACT_MALFORMED) + validation::CustomValidators::accountValidator, Status(RippledError::RpcActMalformed) }}, }; - return kRPC_SPEC; + return kRpcSpec; } void diff --git a/src/rpc/handlers/AMMInfo.hpp b/src/rpc/handlers/AMMInfo.hpp index ce3d3d733..abcfea87c 100644 --- a/src/rpc/handlers/AMMInfo.hpp +++ b/src/rpc/handlers/AMMInfo.hpp @@ -51,10 +51,10 @@ public: * @brief A struct to hold the input data for the command */ struct Input { - std::optional accountID; - std::optional ammAccount; - ripple::Issue issue1 = ripple::noIssue(); - ripple::Issue issue2 = ripple::noIssue(); + std::optional accountID; + std::optional ammAccount; + xrpl::Issue issue1 = xrpl::noIssue(); + xrpl::Issue issue2 = xrpl::noIssue(); std::optional ledgerHash; std::optional ledgerIndex; }; diff --git a/src/rpc/handlers/AccountChannels.cpp b/src/rpc/handlers/AccountChannels.cpp index 5fe65856e..c977be248 100644 --- a/src/rpc/handlers/AccountChannels.cpp +++ b/src/rpc/handlers/AccountChannels.cpp @@ -34,33 +34,33 @@ namespace rpc { void AccountChannelsHandler::addChannel( std::vector& jsonChannels, - ripple::SLE const& channelSle + xrpl::SLE const& channelSle ) { ChannelResponse channel; - channel.channelID = ripple::to_string(channelSle.key()); - channel.account = ripple::to_string(channelSle.getAccountID(ripple::sfAccount)); - channel.accountDestination = ripple::to_string(channelSle.getAccountID(ripple::sfDestination)); - channel.amount = channelSle[ripple::sfAmount].getText(); - channel.balance = channelSle[ripple::sfBalance].getText(); - channel.settleDelay = channelSle[ripple::sfSettleDelay]; + channel.channelID = xrpl::to_string(channelSle.key()); + channel.account = xrpl::to_string(channelSle.getAccountID(xrpl::sfAccount)); + channel.accountDestination = xrpl::to_string(channelSle.getAccountID(xrpl::sfDestination)); + channel.amount = channelSle[xrpl::sfAmount].getText(); + channel.balance = channelSle[xrpl::sfBalance].getText(); + channel.settleDelay = channelSle[xrpl::sfSettleDelay]; - if (publicKeyType(channelSle[ripple::sfPublicKey])) { - ripple::PublicKey const pk(channelSle[ripple::sfPublicKey]); - channel.publicKey = toBase58(ripple::TokenType::AccountPublic, pk); + if (publicKeyType(channelSle[xrpl::sfPublicKey])) { + xrpl::PublicKey const pk(channelSle[xrpl::sfPublicKey]); + channel.publicKey = toBase58(xrpl::TokenType::AccountPublic, pk); channel.publicKeyHex = strHex(pk); } - if (auto const& v = channelSle[~ripple::sfExpiration]) + if (auto const& v = channelSle[~xrpl::sfExpiration]) channel.expiration = v; - if (auto const& v = channelSle[~ripple::sfCancelAfter]) + if (auto const& v = channelSle[~xrpl::sfCancelAfter]) channel.cancelAfter = v; - if (auto const& v = channelSle[~ripple::sfSourceTag]) + if (auto const& v = channelSle[~xrpl::sfSourceTag]) channel.sourceTag = v; - if (auto const& v = channelSle[~ripple::sfDestinationTag]) + if (auto const& v = channelSle[~xrpl::sfDestinationTag]) channel.destinationTag = v; jsonChannels.push_back(channel); @@ -89,23 +89,22 @@ AccountChannelsHandler::process( auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::keylet::account(*accountID).key, + xrpl::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield ); if (!accountLedgerObject) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; auto const destAccountID = input.destinationAccount ? accountFromStringStrict(*input.destinationAccount) - : std::optional{}; + : std::optional{}; Output response; - auto const addToResponse = [&](ripple::SLE const sle) { - if (sle.getType() == ripple::ltPAYCHAN && - sle.getAccountID(ripple::sfAccount) == accountID && - (!destAccountID || *destAccountID == sle.getAccountID(ripple::sfDestination))) { + auto const addToResponse = [&](xrpl::SLE const sle) { + if (sle.getType() == xrpl::ltPAYCHAN && sle.getAccountID(xrpl::sfAccount) == accountID && + (!destAccountID || *destAccountID == sle.getAccountID(xrpl::sfDestination))) { addChannel(response.channels, sle); } @@ -127,7 +126,7 @@ AccountChannelsHandler::process( response.account = input.account; response.limit = input.limit; - response.ledgerHash = ripple::strHex(lgrInfo.hash); + response.ledgerHash = xrpl::strHex(lgrInfo.hash); response.ledgerIndex = lgrInfo.seq; auto const nextMarker = *expectedNext; diff --git a/src/rpc/handlers/AccountChannels.hpp b/src/rpc/handlers/AccountChannels.hpp index 07a197f64..f3b72d2c3 100644 --- a/src/rpc/handlers/AccountChannels.hpp +++ b/src/rpc/handlers/AccountChannels.hpp @@ -32,9 +32,9 @@ class AccountChannelsHandler { std::shared_ptr const sharedPtrBackend_; public: - static constexpr auto kLIMIT_MIN = 10; - static constexpr auto kLIMIT_MAX = 400; - static constexpr auto kLIMIT_DEFAULT = 200; + static constexpr auto kLimitMin = 10; + static constexpr auto kLimitMax = 400; + static constexpr auto kLimitDefault = 200; /** * @brief A struct to hold data for one channel response @@ -78,7 +78,7 @@ public: std::optional destinationAccount; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = kLIMIT_DEFAULT; + uint32_t limit = kLimitDefault; std::optional marker; }; @@ -103,7 +103,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, {JS(destination_account), validation::Type{}, @@ -112,12 +112,12 @@ public: {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + modifiers::Clamp{kLimitMin, kLimitMax}}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(marker), validation::CustomValidators::accountMarkerValidator}, }; - return kRPC_SPEC; + return kRpcSpec; } /** @@ -132,7 +132,7 @@ public: private: static void - addChannel(std::vector& jsonChannels, ripple::SLE const& channelSle); + addChannel(std::vector& jsonChannels, xrpl::SLE const& channelSle); /** * @brief Convert the Output to a JSON object diff --git a/src/rpc/handlers/AccountCurrencies.cpp b/src/rpc/handlers/AccountCurrencies.cpp index fa5ae30a0..beceda730 100644 --- a/src/rpc/handlers/AccountCurrencies.cpp +++ b/src/rpc/handlers/AccountCurrencies.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -48,19 +49,19 @@ AccountCurrenciesHandler::process( auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::keylet::account(*accountID).key, + xrpl::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield ); if (!accountLedgerObject) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; Output response; - auto const addToResponse = [&](ripple::SLE const sle) { - if (sle.getType() == ripple::ltRIPPLE_STATE) { - auto balance = sle.getFieldAmount(ripple::sfBalance); - auto const lowLimit = sle.getFieldAmount(ripple::sfLowLimit); - auto const highLimit = sle.getFieldAmount(ripple::sfHighLimit); + auto const addToResponse = [&](xrpl::SLE const sle) { + if (sle.getType() == xrpl::ltRIPPLE_STATE) { + auto balance = sle.getFieldAmount(xrpl::sfBalance); + auto const lowLimit = sle.getFieldAmount(xrpl::sfLowLimit); + auto const highLimit = sle.getFieldAmount(xrpl::sfHighLimit); bool const viewLowest = (lowLimit.getIssuer() == accountID); auto const lineLimit = viewLowest ? lowLimit : highLimit; auto const lineLimitPeer = !viewLowest ? lowLimit : highLimit; @@ -68,11 +69,17 @@ AccountCurrenciesHandler::process( if (!viewLowest) balance.negate(); - if (balance < lineLimit) - response.receiveCurrencies.insert(ripple::to_string(balance.getCurrency())); + if (balance < lineLimit) { + response.receiveCurrencies.insert( + xrpl::to_string(balance.get().currency) + ); + } - if ((-balance) < lineLimitPeer) - response.sendCurrencies.insert(ripple::to_string(balance.getCurrency())); + if ((-balance) < lineLimitPeer) { + response.sendCurrencies.insert( + xrpl::to_string(balance.get().currency) + ); + } } return true; @@ -89,7 +96,7 @@ AccountCurrenciesHandler::process( addToResponse ); - response.ledgerHash = ripple::strHex(lgrInfo.hash); + response.ledgerHash = xrpl::strHex(lgrInfo.hash); response.ledgerIndex = lgrInfo.seq; return response; diff --git a/src/rpc/handlers/AccountCurrencies.hpp b/src/rpc/handlers/AccountCurrencies.hpp index 91ca3a053..f8e4441f2 100644 --- a/src/rpc/handlers/AccountCurrencies.hpp +++ b/src/rpc/handlers/AccountCurrencies.hpp @@ -72,7 +72,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, @@ -80,7 +80,7 @@ public: {JS(strict), check::Deprecated{}} }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/rpc/handlers/AccountInfo.cpp b/src/rpc/handlers/AccountInfo.cpp index ad2470dbc..16d02f484 100644 --- a/src/rpc/handlers/AccountInfo.cpp +++ b/src/rpc/handlers/AccountInfo.cpp @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include #include @@ -40,7 +40,7 @@ AccountInfoHandler::process(AccountInfoHandler::Input const& input, Context cons if (!input.account && !input.ident) { return Error{ - Status{RippledError::rpcINVALID_PARAMS, ripple::RPC::missing_field_message(JS(account))} + Status{RippledError::RpcInvalidParams, xrpl::RPC::missingFieldMessage(JS(account))} }; } @@ -61,20 +61,20 @@ AccountInfoHandler::process(AccountInfoHandler::Input const& input, Context cons auto const accountStr = input.account.value_or(input.ident.value_or("")); auto const accountID = accountFromStringStrict(accountStr); auto const accountKeylet = - ripple::keylet::account(*accountID); // NOLINT(bugprone-unchecked-optional-access) + xrpl::keylet::account(*accountID); // NOLINT(bugprone-unchecked-optional-access) auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject(accountKeylet.key, lgrInfo.seq, ctx.yield); if (!accountLedgerObject) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; - ripple::STLedgerEntry const sle{ - ripple::SerialIter{accountLedgerObject->data(), accountLedgerObject->size()}, + xrpl::STLedgerEntry const sle{ + xrpl::SerialIter{accountLedgerObject->data(), accountLedgerObject->size()}, accountKeylet.key }; if (!accountKeylet.check(sle)) - return Error{Status{RippledError::rpcDB_DESERIALIZATION}}; + return Error{Status{RippledError::RpcDbDeserialization}}; auto isEnabled = [this, &ctx, seq = lgrInfo.seq](auto key) { return amendmentCenter_->isEnabled(ctx.yield, key, seq); @@ -86,7 +86,7 @@ AccountInfoHandler::process(AccountInfoHandler::Input const& input, Context cons Output out{ .ledgerIndex = lgrInfo.seq, - .ledgerHash = ripple::strHex(lgrInfo.hash), + .ledgerHash = xrpl::strHex(lgrInfo.hash), .accountData = sle, .isDisallowIncomingEnabled = isDisallowIncomingEnabled, .isClawbackEnabled = isClawbackEnabled, @@ -100,21 +100,21 @@ AccountInfoHandler::process(AccountInfoHandler::Input const& input, Context cons // We put the SignerList in an array because of an anticipated // future when we support multiple signer lists on one account. auto const signersKey = - ripple::keylet::signers(*accountID); // NOLINT(bugprone-unchecked-optional-access) + xrpl::keylet::signerList(*accountID); // NOLINT(bugprone-unchecked-optional-access) // This code will need to be revisited if in the future we // support multiple SignerLists on one account. auto const signers = sharedPtrBackend_->fetchLedgerObject(signersKey.key, lgrInfo.seq, ctx.yield); - out.signerLists = std::vector(); + out.signerLists = std::vector(); if (signers) { - ripple::STLedgerEntry const sleSigners{ - ripple::SerialIter{signers->data(), signers->size()}, signersKey.key + xrpl::STLedgerEntry const sleSigners{ + xrpl::SerialIter{signers->data(), signers->size()}, signersKey.key }; if (!signersKey.check(sleSigners)) - return Error{Status{RippledError::rpcDB_DESERIALIZATION}}; + return Error{Status{RippledError::RpcDbDeserialization}}; out.signerLists->push_back(sleSigners); } @@ -137,34 +137,34 @@ tag_invoke( {JS(validated), output.validated}, }; - std::vector> lsFlags{{ - {"defaultRipple", ripple::lsfDefaultRipple}, - {"depositAuth", ripple::lsfDepositAuth}, - {"disableMasterKey", ripple::lsfDisableMaster}, - {"disallowIncomingXRP", ripple::lsfDisallowXRP}, - {"globalFreeze", ripple::lsfGlobalFreeze}, - {"noFreeze", ripple::lsfNoFreeze}, - {"passwordSpent", ripple::lsfPasswordSpent}, - {"requireAuthorization", ripple::lsfRequireAuth}, - {"requireDestinationTag", ripple::lsfRequireDestTag}, + std::vector> lsFlags{{ + {"defaultRipple", xrpl::lsfDefaultRipple}, + {"depositAuth", xrpl::lsfDepositAuth}, + {"disableMasterKey", xrpl::lsfDisableMaster}, + {"disallowIncomingXRP", xrpl::lsfDisallowXRP}, + {"globalFreeze", xrpl::lsfGlobalFreeze}, + {"noFreeze", xrpl::lsfNoFreeze}, + {"passwordSpent", xrpl::lsfPasswordSpent}, + {"requireAuthorization", xrpl::lsfRequireAuth}, + {"requireDestinationTag", xrpl::lsfRequireDestTag}, }}; if (output.isDisallowIncomingEnabled) { - std::vector> const + std::vector> const disallowIncomingFlags = { - {"disallowIncomingNFTokenOffer", ripple::lsfDisallowIncomingNFTokenOffer}, - {"disallowIncomingCheck", ripple::lsfDisallowIncomingCheck}, - {"disallowIncomingPayChan", ripple::lsfDisallowIncomingPayChan}, - {"disallowIncomingTrustline", ripple::lsfDisallowIncomingTrustline}, + {"disallowIncomingNFTokenOffer", xrpl::lsfDisallowIncomingNFTokenOffer}, + {"disallowIncomingCheck", xrpl::lsfDisallowIncomingCheck}, + {"disallowIncomingPayChan", xrpl::lsfDisallowIncomingPayChan}, + {"disallowIncomingTrustline", xrpl::lsfDisallowIncomingTrustline}, }; lsFlags.insert(lsFlags.end(), disallowIncomingFlags.begin(), disallowIncomingFlags.end()); } if (output.isClawbackEnabled) - lsFlags.emplace_back("allowTrustLineClawback", ripple::lsfAllowTrustLineClawback); + lsFlags.emplace_back("allowTrustLineClawback", xrpl::lsfAllowTrustLineClawback); if (output.isTokenEscrowEnabled) - lsFlags.emplace_back("allowTrustLineLocking", ripple::lsfAllowTrustLineLocking); + lsFlags.emplace_back("allowTrustLineLocking", xrpl::lsfAllowTrustLineLocking); boost::json::object acctFlags; for (auto const& lsf : lsFlags) @@ -172,7 +172,7 @@ tag_invoke( jv.as_object()[JS(account_flags)] = std::move(acctFlags); - auto const pseudoFields = ripple::getPseudoAccountFields(); + auto const pseudoFields = xrpl::getPseudoAccountFields(); for (auto const& pseudoField : pseudoFields) { if (output.accountData.isFieldPresent(*pseudoField)) { std::string_view name = pseudoField->fieldName; diff --git a/src/rpc/handlers/AccountInfo.hpp b/src/rpc/handlers/AccountInfo.hpp index 84e3c3e51..091859b0e 100644 --- a/src/rpc/handlers/AccountInfo.hpp +++ b/src/rpc/handlers/AccountInfo.hpp @@ -39,12 +39,12 @@ public: struct Output { uint32_t ledgerIndex; std::string ledgerHash; - ripple::STLedgerEntry accountData; + xrpl::STLedgerEntry accountData; bool isDisallowIncomingEnabled = false; bool isClawbackEnabled = false; bool isTokenEscrowEnabled = false; uint32_t apiVersion; - std::optional> signerLists; + std::optional> signerLists; // validated should be sent via framework bool validated = true; }; @@ -88,7 +88,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC_V1 = RpcSpec{ + static auto const kRpcSpecV1 = RpcSpec{ {JS(account), validation::CustomValidators::accountValidator}, {JS(ident), validation::CustomValidators::accountValidator}, {JS(ident), check::Deprecated{}}, @@ -98,10 +98,10 @@ public: {JS(strict), check::Deprecated{}} }; - static auto const kRPC_SPEC = - RpcSpec{kRPC_SPEC_V1, {{JS(signer_lists), validation::Type{}}}}; + static auto const kRpcSpec = + RpcSpec{kRpcSpecV1, {{JS(signer_lists), validation::Type{}}}}; - return apiVersion == 1 ? kRPC_SPEC_V1 : kRPC_SPEC; + return apiVersion == 1 ? kRpcSpecV1 : kRpcSpec; } /** diff --git a/src/rpc/handlers/AccountLines.cpp b/src/rpc/handlers/AccountLines.cpp index 352c84158..8d0bacee6 100644 --- a/src/rpc/handlers/AccountLines.cpp +++ b/src/rpc/handlers/AccountLines.cpp @@ -33,21 +33,21 @@ namespace rpc { void AccountLinesHandler::addLine( std::vector& lines, - ripple::SLE const& lineSle, - ripple::AccountID const& account, - std::optional const& peerAccount + xrpl::SLE const& lineSle, + xrpl::AccountID const& account, + std::optional const& peerAccount ) { - auto const flags = lineSle.getFieldU32(ripple::sfFlags); - auto const lowLimit = lineSle.getFieldAmount(ripple::sfLowLimit); - auto const highLimit = lineSle.getFieldAmount(ripple::sfHighLimit); + auto const flags = lineSle.getFieldU32(xrpl::sfFlags); + auto const lowLimit = lineSle.getFieldAmount(xrpl::sfLowLimit); + auto const highLimit = lineSle.getFieldAmount(xrpl::sfHighLimit); auto const lowID = lowLimit.getIssuer(); auto const highID = highLimit.getIssuer(); - auto const lowQualityIn = lineSle.getFieldU32(ripple::sfLowQualityIn); - auto const lowQualityOut = lineSle.getFieldU32(ripple::sfLowQualityOut); - auto const highQualityIn = lineSle.getFieldU32(ripple::sfHighQualityIn); - auto const highQualityOut = lineSle.getFieldU32(ripple::sfHighQualityOut); - auto balance = lineSle.getFieldAmount(ripple::sfBalance); + auto const lowQualityIn = lineSle.getFieldU32(xrpl::sfLowQualityIn); + auto const lowQualityOut = lineSle.getFieldU32(xrpl::sfLowQualityOut); + auto const highQualityIn = lineSle.getFieldU32(xrpl::sfHighQualityIn); + auto const highQualityOut = lineSle.getFieldU32(xrpl::sfHighQualityOut); + auto balance = lineSle.getFieldAmount(xrpl::sfBalance); auto const viewLowest = (lowID == account); auto const lineLimit = viewLowest ? lowLimit : highLimit; @@ -62,30 +62,29 @@ AccountLinesHandler::addLine( if (not viewLowest) balance.negate(); - bool const lineAuth = (flags & (viewLowest ? ripple::lsfLowAuth : ripple::lsfHighAuth)) != 0u; + bool const lineAuth = (flags & (viewLowest ? xrpl::lsfLowAuth : xrpl::lsfHighAuth)) != 0u; bool const lineAuthPeer = - (flags & (not viewLowest ? ripple::lsfLowAuth : ripple::lsfHighAuth)) != 0u; + (flags & (not viewLowest ? xrpl::lsfLowAuth : xrpl::lsfHighAuth)) != 0u; bool const lineNoRipple = - (flags & (viewLowest ? ripple::lsfLowNoRipple : ripple::lsfHighNoRipple)) != 0u; + (flags & (viewLowest ? xrpl::lsfLowNoRipple : xrpl::lsfHighNoRipple)) != 0u; bool const lineNoRipplePeer = - (flags & (not viewLowest ? ripple::lsfLowNoRipple : ripple::lsfHighNoRipple)) != 0u; - bool const lineFreeze = - (flags & (viewLowest ? ripple::lsfLowFreeze : ripple::lsfHighFreeze)) != 0u; + (flags & (not viewLowest ? xrpl::lsfLowNoRipple : xrpl::lsfHighNoRipple)) != 0u; + bool const lineFreeze = (flags & (viewLowest ? xrpl::lsfLowFreeze : xrpl::lsfHighFreeze)) != 0u; bool const lineFreezePeer = - (flags & (not viewLowest ? ripple::lsfLowFreeze : ripple::lsfHighFreeze)) != 0u; + (flags & (not viewLowest ? xrpl::lsfLowFreeze : xrpl::lsfHighFreeze)) != 0u; bool const lineDeepFreeze = - (flags & (viewLowest ? ripple::lsfLowDeepFreeze : ripple::lsfHighDeepFreeze)) != 0u; + (flags & (viewLowest ? xrpl::lsfLowDeepFreeze : xrpl::lsfHighDeepFreeze)) != 0u; bool const lineDeepFreezePeer = - (flags & (not viewLowest ? ripple::lsfLowDeepFreeze : ripple::lsfHighDeepFreeze)) != 0u; + (flags & (not viewLowest ? xrpl::lsfLowDeepFreeze : xrpl::lsfHighDeepFreeze)) != 0u; - ripple::STAmount const& saBalance = balance; - ripple::STAmount const& saLimit = lineLimit; - ripple::STAmount const& saLimitPeer = lineLimitPeer; + xrpl::STAmount const& saBalance = balance; + xrpl::STAmount const& saLimit = lineLimit; + xrpl::STAmount const& saLimitPeer = lineLimitPeer; LineResponse line; - line.account = ripple::to_string(lineAccountIDPeer); + line.account = xrpl::to_string(lineAccountIDPeer); line.balance = saBalance.getText(); - line.currency = ripple::to_string(saBalance.issue().currency); + line.currency = xrpl::to_string(saBalance.get().currency); line.limit = saLimit.getText(); line.limitPeer = saLimitPeer.getText(); line.qualityIn = lineQualityIn; @@ -138,28 +137,28 @@ AccountLinesHandler::process(AccountLinesHandler::Input const& input, Context co auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::keylet::account(*accountID).key, + xrpl::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield ); if (not accountLedgerObject) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; auto const peerAccountID = - input.peer ? accountFromStringStrict(*(input.peer)) : std::optional{}; + input.peer ? accountFromStringStrict(*(input.peer)) : std::optional{}; Output response; response.lines.reserve(input.limit); - auto const addToResponse = [&](ripple::SLE const sle) { - if (sle.getType() == ripple::ltRIPPLE_STATE) { + auto const addToResponse = [&](xrpl::SLE const sle) { + if (sle.getType() == xrpl::ltRIPPLE_STATE) { auto ignore = false; if (input.ignoreDefault) { - if (sle.getFieldAmount(ripple::sfLowLimit).getIssuer() == accountID) { - ignore = ((sle.getFieldU32(ripple::sfFlags) & ripple::lsfLowReserve) == 0u); + if (sle.getFieldAmount(xrpl::sfLowLimit).getIssuer() == accountID) { + ignore = ((sle.getFieldU32(xrpl::sfFlags) & xrpl::lsfLowReserve) == 0u); } else { - ignore = ((sle.getFieldU32(ripple::sfFlags) & ripple::lsfHighReserve) == 0u); + ignore = ((sle.getFieldU32(xrpl::sfFlags) & xrpl::lsfHighReserve) == 0u); } } @@ -186,7 +185,7 @@ AccountLinesHandler::process(AccountLinesHandler::Input const& input, Context co response.account = input.account; response.limit = input.limit; // not documented, // https://github.com/XRPLF/xrpl-dev-portal/issues/1838 - response.ledgerHash = ripple::strHex(lgrInfo.hash); + response.ledgerHash = xrpl::strHex(lgrInfo.hash); response.ledgerIndex = lgrInfo.seq; if (nextMarker.isNonZero()) diff --git a/src/rpc/handlers/AccountLines.hpp b/src/rpc/handlers/AccountLines.hpp index 0cd3384e0..5bfd3cc12 100644 --- a/src/rpc/handlers/AccountLines.hpp +++ b/src/rpc/handlers/AccountLines.hpp @@ -36,9 +36,9 @@ class AccountLinesHandler { std::shared_ptr const sharedPtrBackend_; public: - static constexpr auto kLIMIT_MIN = 10; - static constexpr auto kLIMIT_MAX = 400; - static constexpr auto kLIMIT_DEFAULT = 200; + static constexpr auto kLimitMin = 10; + static constexpr auto kLimitMax = 400; + static constexpr auto kLimitDefault = 200; /** * @brief A struct to hold data for one line response @@ -84,7 +84,7 @@ public: std::optional peer; bool ignoreDefault = false; // TODO: document // https://github.com/XRPLF/xrpl-dev-portal/issues/1839 - uint32_t limit = kLIMIT_DEFAULT; + uint32_t limit = kLimitDefault; std::optional marker; }; @@ -109,31 +109,31 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(account), validation::Required{}, meta::WithCustomError{ validation::CustomValidators::accountValidator, - Status(RippledError::rpcACT_MALFORMED) + Status(RippledError::RpcActMalformed) }}, {JS(peer), meta::WithCustomError{ validation::CustomValidators::accountValidator, - Status(RippledError::rpcACT_MALFORMED) + Status(RippledError::RpcActMalformed) }}, {JS(ignore_default), validation::Type{}}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + modifiers::Clamp{kLimitMin, kLimitMax}}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(marker), validation::CustomValidators::accountMarkerValidator}, {JS(ledger), check::Deprecated{}}, {"peer_index", check::Deprecated{}}, }; - return kRPC_SPEC; + return kRpcSpec; } /** @@ -150,9 +150,9 @@ private: static void addLine( std::vector& lines, - ripple::SLE const& lineSle, - ripple::AccountID const& account, - std::optional const& peerAccount + xrpl::SLE const& lineSle, + xrpl::AccountID const& account, + std::optional const& peerAccount ); private: diff --git a/src/rpc/handlers/AccountMPTokenIssuances.cpp b/src/rpc/handlers/AccountMPTokenIssuances.cpp index 671ba38db..14413dc48 100644 --- a/src/rpc/handlers/AccountMPTokenIssuances.cpp +++ b/src/rpc/handlers/AccountMPTokenIssuances.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -31,68 +32,68 @@ namespace rpc { void AccountMPTokenIssuancesHandler::addMPTokenIssuance( std::vector& issuances, - ripple::SLE const& sle, - ripple::AccountID const& account + xrpl::SLE const& sle, + xrpl::AccountID const& account ) { MPTokenIssuanceResponse issuance; - issuance.MPTokenIssuanceID = ripple::strHex(sle.key()); - issuance.issuer = ripple::to_string(account); - issuance.sequence = sle.getFieldU32(ripple::sfSequence); - auto const flags = sle.getFieldU32(ripple::sfFlags); + issuance.mpTokenIssuanceId = xrpl::strHex(sle.key()); + issuance.issuer = xrpl::to_string(account); + issuance.sequence = sle.getFieldU32(xrpl::sfSequence); + auto const flags = sle.getFieldU32(xrpl::sfFlags); auto const setFlag = [&](std::optional& field, std::uint32_t mask) { if ((flags & mask) != 0u) field = true; }; - setFlag(issuance.mptLocked, ripple::lsfMPTLocked); - setFlag(issuance.mptCanLock, ripple::lsfMPTCanLock); - setFlag(issuance.mptRequireAuth, ripple::lsfMPTRequireAuth); - setFlag(issuance.mptCanEscrow, ripple::lsfMPTCanEscrow); - setFlag(issuance.mptCanTrade, ripple::lsfMPTCanTrade); - setFlag(issuance.mptCanTransfer, ripple::lsfMPTCanTransfer); - setFlag(issuance.mptCanClawback, ripple::lsfMPTCanClawback); + setFlag(issuance.mptLocked, xrpl::lsfMPTLocked); + setFlag(issuance.mptCanLock, xrpl::lsfMPTCanLock); + setFlag(issuance.mptRequireAuth, xrpl::lsfMPTRequireAuth); + setFlag(issuance.mptCanEscrow, xrpl::lsfMPTCanEscrow); + setFlag(issuance.mptCanTrade, xrpl::lsfMPTCanTrade); + setFlag(issuance.mptCanTransfer, xrpl::lsfMPTCanTransfer); + setFlag(issuance.mptCanClawback, xrpl::lsfMPTCanClawback); - if (sle.isFieldPresent(ripple::sfMutableFlags)) { - auto const mutableFlags = sle.getFieldU32(ripple::sfMutableFlags); + if (sle.isFieldPresent(xrpl::sfMutableFlags)) { + auto const mutableFlags = sle.getFieldU32(xrpl::sfMutableFlags); auto const setMutableFlag = [&](std::optional& field, std::uint32_t mask) { if ((mutableFlags & mask) != 0u) field = true; }; - setMutableFlag(issuance.mptCanMutateCanLock, ripple::lsmfMPTCanMutateCanLock); - setMutableFlag(issuance.mptCanMutateRequireAuth, ripple::lsmfMPTCanMutateRequireAuth); - setMutableFlag(issuance.mptCanMutateCanEscrow, ripple::lsmfMPTCanMutateCanEscrow); - setMutableFlag(issuance.mptCanMutateCanTrade, ripple::lsmfMPTCanMutateCanTrade); - setMutableFlag(issuance.mptCanMutateCanTransfer, ripple::lsmfMPTCanMutateCanTransfer); - setMutableFlag(issuance.mptCanMutateCanClawback, ripple::lsmfMPTCanMutateCanClawback); - setMutableFlag(issuance.mptCanMutateMetadata, ripple::lsmfMPTCanMutateMetadata); - setMutableFlag(issuance.mptCanMutateTransferFee, ripple::lsmfMPTCanMutateTransferFee); + setMutableFlag(issuance.mptCanMutateCanLock, xrpl::lsmfMPTCanEnableCanLock); + setMutableFlag(issuance.mptCanMutateRequireAuth, xrpl::lsmfMPTCanEnableRequireAuth); + setMutableFlag(issuance.mptCanMutateCanEscrow, xrpl::lsmfMPTCanEnableCanEscrow); + setMutableFlag(issuance.mptCanMutateCanTrade, xrpl::lsmfMPTCanEnableCanTrade); + setMutableFlag(issuance.mptCanMutateCanTransfer, xrpl::lsmfMPTCanEnableCanTransfer); + setMutableFlag(issuance.mptCanMutateCanClawback, xrpl::lsmfMPTCanEnableCanClawback); + setMutableFlag(issuance.mptCanMutateMetadata, xrpl::lsmfMPTCanMutateMetadata); + setMutableFlag(issuance.mptCanMutateTransferFee, xrpl::lsmfMPTCanMutateTransferFee); } - if (sle.isFieldPresent(ripple::sfTransferFee)) - issuance.transferFee = sle.getFieldU16(ripple::sfTransferFee); + if (sle.isFieldPresent(xrpl::sfTransferFee)) + issuance.transferFee = sle.getFieldU16(xrpl::sfTransferFee); - if (sle.isFieldPresent(ripple::sfAssetScale)) - issuance.assetScale = sle.getFieldU8(ripple::sfAssetScale); + if (sle.isFieldPresent(xrpl::sfAssetScale)) + issuance.assetScale = sle.getFieldU8(xrpl::sfAssetScale); - if (sle.isFieldPresent(ripple::sfMaximumAmount)) - issuance.maximumAmount = sle.getFieldU64(ripple::sfMaximumAmount); + if (sle.isFieldPresent(xrpl::sfMaximumAmount)) + issuance.maximumAmount = sle.getFieldU64(xrpl::sfMaximumAmount); - if (sle.isFieldPresent(ripple::sfOutstandingAmount)) - issuance.outstandingAmount = sle.getFieldU64(ripple::sfOutstandingAmount); + if (sle.isFieldPresent(xrpl::sfOutstandingAmount)) + issuance.outstandingAmount = sle.getFieldU64(xrpl::sfOutstandingAmount); - if (sle.isFieldPresent(ripple::sfLockedAmount)) - issuance.lockedAmount = sle.getFieldU64(ripple::sfLockedAmount); + if (sle.isFieldPresent(xrpl::sfLockedAmount)) + issuance.lockedAmount = sle.getFieldU64(xrpl::sfLockedAmount); - if (sle.isFieldPresent(ripple::sfMPTokenMetadata)) - issuance.mptokenMetadata = ripple::strHex(sle.getFieldVL(ripple::sfMPTokenMetadata)); + if (sle.isFieldPresent(xrpl::sfMPTokenMetadata)) + issuance.mptokenMetadata = xrpl::strHex(sle.getFieldVL(xrpl::sfMPTokenMetadata)); - if (sle.isFieldPresent(ripple::sfDomainID)) - issuance.domainID = ripple::strHex(sle.getFieldH256(ripple::sfDomainID)); + if (sle.isFieldPresent(xrpl::sfDomainID)) + issuance.domainID = xrpl::strHex(sle.getFieldH256(xrpl::sfDomainID)); issuances.push_back(issuance); } @@ -120,19 +121,19 @@ AccountMPTokenIssuancesHandler::process( auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::keylet::account(*accountID).key, + xrpl::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield ); if (not accountLedgerObject.has_value()) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; Output response; response.issuances.reserve(input.limit); - auto const addToResponse = [&](ripple::SLE const& sle) { - if (sle.getType() == ripple::ltMPTOKEN_ISSUANCE) { + auto const addToResponse = [&](xrpl::SLE const& sle) { + if (sle.getType() == xrpl::ltMPTOKEN_ISSUANCE) { addMPTokenIssuance(response.issuances, sle, *accountID); } }; @@ -155,7 +156,7 @@ AccountMPTokenIssuancesHandler::process( response.account = input.account; response.limit = input.limit; - response.ledgerHash = ripple::strHex(lgrInfo.hash); + response.ledgerHash = xrpl::strHex(lgrInfo.hash); response.ledgerIndex = lgrInfo.seq; if (nextMarker.isNonZero()) @@ -225,7 +226,7 @@ tag_invoke( ) { auto obj = boost::json::object{ - {JS(mpt_issuance_id), issuance.MPTokenIssuanceID}, + {JS(mpt_issuance_id), issuance.mpTokenIssuanceId}, {JS(issuer), issuance.issuer}, {JS(sequence), issuance.sequence}, }; @@ -236,11 +237,23 @@ tag_invoke( } }; + // UInt64 amount fields must be serialized as base-10 strings (matching rippled's + // STUInt64::getJson) so that JSON parsers using IEEE-754 doubles do not silently lose + // precision for values greater than 2^53. + auto const setUint64IfPresent = + [&](boost::json::string_view field, xrpl::SField const& sField, auto const& value) { + if (value.has_value()) { + obj[field] = toBoostJson( + xrpl::STUInt64{sField, *value}.getJson(xrpl::JsonOptions::Values::None) + ); + } + }; + setIfPresent("transfer_fee", issuance.transferFee); setIfPresent("asset_scale", issuance.assetScale); - setIfPresent("maximum_amount", issuance.maximumAmount); - setIfPresent("outstanding_amount", issuance.outstandingAmount); - setIfPresent("locked_amount", issuance.lockedAmount); + setUint64IfPresent("maximum_amount", xrpl::sfMaximumAmount, issuance.maximumAmount); + setUint64IfPresent("outstanding_amount", xrpl::sfOutstandingAmount, issuance.outstandingAmount); + setUint64IfPresent("locked_amount", xrpl::sfLockedAmount, issuance.lockedAmount); setIfPresent("mptoken_metadata", issuance.mptokenMetadata); setIfPresent("domain_id", issuance.domainID); diff --git a/src/rpc/handlers/AccountMPTokenIssuances.hpp b/src/rpc/handlers/AccountMPTokenIssuances.hpp index 53ec3c5bf..1ba32f7e4 100644 --- a/src/rpc/handlers/AccountMPTokenIssuances.hpp +++ b/src/rpc/handlers/AccountMPTokenIssuances.hpp @@ -34,15 +34,15 @@ class AccountMPTokenIssuancesHandler { std::shared_ptr sharedPtrBackend_; public: - static constexpr auto kLIMIT_MIN = 10; - static constexpr auto kLIMIT_MAX = 400; - static constexpr auto kLIMIT_DEFAULT = 200; + static constexpr auto kLimitMin = 10; + static constexpr auto kLimitMax = 400; + static constexpr auto kLimitDefault = 200; /** * @brief A struct to hold data for one MPTokenIssuance response. */ struct MPTokenIssuanceResponse { - std::string MPTokenIssuanceID; + std::string mpTokenIssuanceId; std::string issuer; uint32_t sequence{}; @@ -93,7 +93,7 @@ public: std::string account; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = kLIMIT_DEFAULT; + uint32_t limit = kLimitDefault; std::optional marker; }; @@ -118,24 +118,24 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(account), validation::Required{}, meta::WithCustomError{ validation::CustomValidators::accountValidator, - Status(RippledError::rpcACT_MALFORMED) + Status(RippledError::RpcActMalformed) }}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + modifiers::Clamp{kLimitMin, kLimitMax}}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(marker), validation::CustomValidators::accountMarkerValidator}, {JS(ledger), check::Deprecated{}}, }; - return kRPC_SPEC; + return kRpcSpec; } /** @@ -152,8 +152,8 @@ private: static void addMPTokenIssuance( std::vector& issuances, - ripple::SLE const& sle, - ripple::AccountID const& account + xrpl::SLE const& sle, + xrpl::AccountID const& account ); private: diff --git a/src/rpc/handlers/AccountMPTokens.cpp b/src/rpc/handlers/AccountMPTokens.cpp index ddec96c9e..6978ea389 100644 --- a/src/rpc/handlers/AccountMPTokens.cpp +++ b/src/rpc/handlers/AccountMPTokens.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -30,26 +31,26 @@ namespace rpc { void -AccountMPTokensHandler::addMPToken(std::vector& mpts, ripple::SLE const& sle) +AccountMPTokensHandler::addMPToken(std::vector& mpts, xrpl::SLE const& sle) { MPTokenResponse token{}; - auto const flags = sle.getFieldU32(ripple::sfFlags); + auto const flags = sle.getFieldU32(xrpl::sfFlags); - token.MPTokenID = ripple::strHex(sle.key()); - token.account = ripple::to_string(sle.getAccountID(ripple::sfAccount)); - token.MPTokenIssuanceID = ripple::strHex(sle.getFieldH192(ripple::sfMPTokenIssuanceID)); - token.MPTAmount = sle.getFieldU64(ripple::sfMPTAmount); + token.mpTokenId = xrpl::strHex(sle.key()); + token.account = xrpl::to_string(sle.getAccountID(xrpl::sfAccount)); + token.mpTokenIssuanceId = xrpl::strHex(sle.getFieldH192(xrpl::sfMPTokenIssuanceID)); + token.mptAmount = sle.getFieldU64(xrpl::sfMPTAmount); - if (sle.isFieldPresent(ripple::sfLockedAmount)) - token.lockedAmount = sle.getFieldU64(ripple::sfLockedAmount); + if (sle.isFieldPresent(xrpl::sfLockedAmount)) + token.lockedAmount = sle.getFieldU64(xrpl::sfLockedAmount); auto const setFlag = [&](std::optional& field, std::uint32_t mask) { if ((flags & mask) != 0u) field = true; }; - setFlag(token.mptLocked, ripple::lsfMPTLocked); - setFlag(token.mptAuthorized, ripple::lsfMPTAuthorized); + setFlag(token.mptLocked, xrpl::lsfMPTLocked); + setFlag(token.mptAuthorized, xrpl::lsfMPTAuthorized); mpts.push_back(token); } @@ -77,19 +78,19 @@ AccountMPTokensHandler::process( auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::keylet::account(*accountID).key, + xrpl::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield ); if (not accountLedgerObject.has_value()) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; Output response; response.mpts.reserve(input.limit); - auto const addToResponse = [&](ripple::SLE const& sle) { - if (sle.getType() == ripple::ltMPTOKEN) { + auto const addToResponse = [&](xrpl::SLE const& sle) { + if (sle.getType() == xrpl::ltMPTOKEN) { addMPToken(response.mpts, sle); } }; @@ -112,7 +113,7 @@ AccountMPTokensHandler::process( response.account = input.account; response.limit = input.limit; - response.ledgerHash = ripple::strHex(lgrInfo.hash); + response.ledgerHash = xrpl::strHex(lgrInfo.hash); response.ledgerIndex = lgrInfo.seq; if (nextMarker.isNonZero()) @@ -176,20 +177,29 @@ tag_invoke( AccountMPTokensHandler::MPTokenResponse const& mptoken ) { - auto obj = boost::json::object{ - {"mpt_id", mptoken.MPTokenID}, - {JS(account), mptoken.account}, - {JS(mpt_issuance_id), mptoken.MPTokenIssuanceID}, - {JS(mpt_amount), mptoken.MPTAmount}, + // UInt64 amount fields must be serialized as base-10 strings (matching rippled's + // STUInt64::getJson) so that JSON parsers using IEEE-754 doubles do not silently lose + // precision for values greater than 2^53. + auto const uint64ToString = [](xrpl::SField const& field, std::uint64_t value) { + return toBoostJson(xrpl::STUInt64{field, value}.getJson(xrpl::JsonOptions::Values::None)); }; + auto obj = boost::json::object{ + {"mpt_id", mptoken.mpTokenId}, + {JS(account), mptoken.account}, + {JS(mpt_issuance_id), mptoken.mpTokenIssuanceId}, + {JS(mpt_amount), uint64ToString(xrpl::sfMPTAmount, mptoken.mptAmount)}, + }; + + if (mptoken.lockedAmount.has_value()) + obj["locked_amount"] = uint64ToString(xrpl::sfLockedAmount, *mptoken.lockedAmount); + auto const setIfPresent = [&](boost::json::string_view field, auto const& value) { if (value.has_value()) { obj[field] = *value; } }; - setIfPresent("locked_amount", mptoken.lockedAmount); setIfPresent("mpt_locked", mptoken.mptLocked); setIfPresent("mpt_authorized", mptoken.mptAuthorized); diff --git a/src/rpc/handlers/AccountMPTokens.hpp b/src/rpc/handlers/AccountMPTokens.hpp index 92338b37f..c7d3a5246 100644 --- a/src/rpc/handlers/AccountMPTokens.hpp +++ b/src/rpc/handlers/AccountMPTokens.hpp @@ -33,18 +33,18 @@ class AccountMPTokensHandler { std::shared_ptr sharedPtrBackend_; public: - static constexpr auto kLIMIT_MIN = 10; - static constexpr auto kLIMIT_MAX = 400; - static constexpr auto kLIMIT_DEFAULT = 200; + static constexpr auto kLimitMin = 10; + static constexpr auto kLimitMax = 400; + static constexpr auto kLimitDefault = 200; /** * @brief A struct to hold data for one MPToken response. */ struct MPTokenResponse { - std::string MPTokenID; + std::string mpTokenId; std::string account; - std::string MPTokenIssuanceID; - uint64_t MPTAmount{}; + std::string mpTokenIssuanceId; + uint64_t mptAmount{}; std::optional lockedAmount; std::optional mptLocked; @@ -71,7 +71,7 @@ public: std::string account; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = kLIMIT_DEFAULT; + uint32_t limit = kLimitDefault; std::optional marker; }; @@ -96,24 +96,24 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(account), validation::Required{}, meta::WithCustomError{ validation::CustomValidators::accountValidator, - Status(RippledError::rpcACT_MALFORMED) + Status(RippledError::RpcActMalformed) }}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + modifiers::Clamp{kLimitMin, kLimitMax}}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(marker), validation::CustomValidators::accountMarkerValidator}, {JS(ledger), check::Deprecated{}}, }; - return kRPC_SPEC; + return kRpcSpec; } /** @@ -128,7 +128,7 @@ public: private: static void - addMPToken(std::vector& mpts, ripple::SLE const& sle); + addMPToken(std::vector& mpts, xrpl::SLE const& sle); private: /** diff --git a/src/rpc/handlers/AccountNFTs.cpp b/src/rpc/handlers/AccountNFTs.cpp index 2ad1ab842..96b7f9582 100644 --- a/src/rpc/handlers/AccountNFTs.cpp +++ b/src/rpc/handlers/AccountNFTs.cpp @@ -50,69 +50,69 @@ AccountNFTsHandler::process(AccountNFTsHandler::Input const& input, Context cons auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::keylet::account(*accountID).key, + xrpl::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield ); if (!accountLedgerObject) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; auto response = Output{}; response.account = input.account; response.limit = input.limit; - response.ledgerHash = ripple::strHex(lgrInfo.hash); + response.ledgerHash = xrpl::strHex(lgrInfo.hash); response.ledgerIndex = lgrInfo.seq; // if a marker was passed, start at the page specified in marker. Else, start at the max page - auto const pageKey = input.marker ? ripple::uint256{input.marker->c_str()} + auto const pageKey = input.marker ? xrpl::uint256{input.marker->c_str()} // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - : ripple::keylet::nftpage_max(*accountID).key; + : xrpl::keylet::nftokenPageMax(*accountID).key; auto const blob = sharedPtrBackend_->fetchLedgerObject(pageKey, lgrInfo.seq, ctx.yield); if (!blob) { if (input.marker.has_value()) { return Error{Status{ - RippledError::rpcINVALID_PARAMS, "Marker field does not match any valid Page ID" + RippledError::RpcInvalidParams, "Marker field does not match any valid Page ID" }}; } return response; } - std::optional page{ - ripple::SLE{ripple::SerialIter{blob->data(), blob->size()}, pageKey} + std::optional page{ + xrpl::SLE{xrpl::SerialIter{blob->data(), blob->size()}, pageKey} }; - if (page->getType() != ripple::ltNFTOKEN_PAGE) { + if (page->getType() != xrpl::ltNFTOKEN_PAGE) { return Error{ - Status{RippledError::rpcINVALID_PARAMS, "Marker matches Page ID from another Account"} + Status{RippledError::RpcInvalidParams, "Marker matches Page ID from another Account"} }; } auto numPages = 0u; while (page) { - auto const arr = page->getFieldArray(ripple::sfNFTokens); + auto const arr = page->getFieldArray(xrpl::sfNFTokens); for (auto const& nft : arr) { - auto const nftokenID = nft[ripple::sfNFTokenID]; + auto const nftokenID = nft[xrpl::sfNFTokenID]; - response.nfts.push_back(toBoostJson(nft.getJson(ripple::JsonOptions::none))); + response.nfts.push_back(toBoostJson(nft.getJson(xrpl::JsonOptions::Values::None))); auto& obj = response.nfts.back().as_object(); // Pull out the components of the nft ID. - obj[SFS(sfFlags)] = ripple::nft::getFlags(nftokenID); - obj[SFS(sfIssuer)] = to_string(ripple::nft::getIssuer(nftokenID)); - obj[SFS(sfNFTokenTaxon)] = ripple::nft::toUInt32(ripple::nft::getTaxon(nftokenID)); - obj[JS(nft_serial)] = ripple::nft::getSerial(nftokenID); + obj[SFS(sfFlags)] = xrpl::nft::getFlags(nftokenID); + obj[SFS(sfIssuer)] = to_string(xrpl::nft::getIssuer(nftokenID)); + obj[SFS(sfNFTokenTaxon)] = xrpl::nft::toUInt32(xrpl::nft::getTaxon(nftokenID)); + obj[JS(nft_serial)] = xrpl::nft::getSequence(nftokenID); - if (std::uint16_t const xferFee = {ripple::nft::getTransferFee(nftokenID)}) + if (std::uint16_t const xferFee = {xrpl::nft::getTransferFee(nftokenID)}) obj[SFS(sfTransferFee)] = xferFee; } ++numPages; - if (auto const npm = (*page)[~ripple::sfPreviousPageMin]) { - auto const nextKey = ripple::Keylet(ripple::ltNFTOKEN_PAGE, *npm); + if (auto const npm = (*page)[~xrpl::sfPreviousPageMin]) { + auto const nextKey = xrpl::Keylet(xrpl::ltNFTOKEN_PAGE, *npm); if (numPages == input.limit) { response.marker = to_string(nextKey.key); return response; @@ -122,7 +122,7 @@ AccountNFTsHandler::process(AccountNFTsHandler::Input const& input, Context cons sharedPtrBackend_->fetchLedgerObject(nextKey.key, lgrInfo.seq, ctx.yield); page.emplace( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::SLE{ripple::SerialIter{nextBlob->data(), nextBlob->size()}, nextKey.key} + xrpl::SLE{xrpl::SerialIter{nextBlob->data(), nextBlob->size()}, nextKey.key} ); } else { page.reset(); diff --git a/src/rpc/handlers/AccountNFTs.hpp b/src/rpc/handlers/AccountNFTs.hpp index 79b10a6c1..dcea64578 100644 --- a/src/rpc/handlers/AccountNFTs.hpp +++ b/src/rpc/handlers/AccountNFTs.hpp @@ -28,9 +28,9 @@ class AccountNFTsHandler { std::shared_ptr sharedPtrBackend_; public: - static constexpr auto kLIMIT_MIN = 20; - static constexpr auto kLIMIT_MAX = 400; - static constexpr auto kLIMIT_DEFAULT = 100; + static constexpr auto kLimitMin = 20; + static constexpr auto kLimitMax = 400; + static constexpr auto kLimitDefault = 100; /** * @brief A struct to hold the output data of the command @@ -53,7 +53,7 @@ public: std::string account; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = kLIMIT_DEFAULT; // Limit the number of token pages to retrieve. [20,400] + uint32_t limit = kLimitDefault; // Limit the number of token pages to retrieve. [20,400] std::optional marker; }; @@ -78,7 +78,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, @@ -86,10 +86,10 @@ public: {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + modifiers::Clamp{kLimitMin, kLimitMax}}, }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/rpc/handlers/AccountObjects.cpp b/src/rpc/handlers/AccountObjects.cpp index ed0dcae85..183ebd4e1 100644 --- a/src/rpc/handlers/AccountObjects.cpp +++ b/src/rpc/handlers/AccountObjects.cpp @@ -51,15 +51,15 @@ AccountObjectsHandler::process(AccountObjectsHandler::Input const& input, Contex auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::keylet::account(*accountID).key, + xrpl::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield ); if (!accountLedgerObject) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; - auto typeFilter = std::optional>{}; + auto typeFilter = std::optional>{}; if (input.deletionBlockersOnly) { typeFilter.emplace(); @@ -73,12 +73,12 @@ AccountObjectsHandler::process(AccountObjectsHandler::Input const& input, Contex typeFilter->push_back(type); } } else { - if (input.type && input.type != ripple::ltANY) + if (input.type && input.type != xrpl::ltANY) typeFilter = {*input.type}; } Output response; - auto const addToResponse = [&](ripple::SLE&& sle) { + auto const addToResponse = [&](xrpl::SLE&& sle) { if (not typeFilter or std::find(std::begin(*typeFilter), std::end(*typeFilter), sle.getType()) != std::end(*typeFilter)) { @@ -101,7 +101,7 @@ AccountObjectsHandler::process(AccountObjectsHandler::Input const& input, Contex if (not expectedNext.has_value()) return Error{expectedNext.error()}; - response.ledgerHash = ripple::strHex(lgrInfo.hash); + response.ledgerHash = xrpl::strHex(lgrInfo.hash); response.ledgerIndex = lgrInfo.seq; response.limit = input.limit; response.account = input.account; diff --git a/src/rpc/handlers/AccountObjects.hpp b/src/rpc/handlers/AccountObjects.hpp index 5271d3f3a..da51a4391 100644 --- a/src/rpc/handlers/AccountObjects.hpp +++ b/src/rpc/handlers/AccountObjects.hpp @@ -34,9 +34,9 @@ class AccountObjectsHandler { std::shared_ptr sharedPtrBackend_; public: - static constexpr auto kLIMIT_MIN = 10; - static constexpr auto kLIMIT_MAX = 400; - static constexpr auto kLIMIT_DEFAULT = 200; + static constexpr auto kLimitMin = 10; + static constexpr auto kLimitMax = 400; + static constexpr auto kLimitDefault = 200; /** * @brief A struct to hold the output data of the command @@ -47,7 +47,7 @@ public: uint32_t ledgerIndex{}; std::optional marker; uint32_t limit{}; - std::vector accountObjects; + std::vector accountObjects; bool validated = true; }; @@ -58,9 +58,9 @@ public: std::string account; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = kLIMIT_DEFAULT; // [10,400] + uint32_t limit = kLimitDefault; // [10,400] std::optional marker; - std::optional type; + std::optional type; bool deletionBlockersOnly = false; }; @@ -85,20 +85,20 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp(kLIMIT_MIN, kLIMIT_MAX)}, + modifiers::Clamp(kLimitMin, kLimitMax)}, {JS(type), validation::CustomValidators::accountTypeValidator}, {JS(marker), validation::CustomValidators::accountMarkerValidator}, {JS(deletion_blockers_only), validation::Type{}}, }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/rpc/handlers/AccountOffers.cpp b/src/rpc/handlers/AccountOffers.cpp index a5531d810..09abb815d 100644 --- a/src/rpc/handlers/AccountOffers.cpp +++ b/src/rpc/handlers/AccountOffers.cpp @@ -29,20 +29,20 @@ namespace rpc { void -AccountOffersHandler::addOffer(std::vector& offers, ripple::SLE const& offerSle) +AccountOffersHandler::addOffer(std::vector& offers, xrpl::SLE const& offerSle) { auto offer = AccountOffersHandler::Offer(); - offer.takerPays = offerSle.getFieldAmount(ripple::sfTakerPays); - offer.takerGets = offerSle.getFieldAmount(ripple::sfTakerGets); - offer.seq = offerSle.getFieldU32(ripple::sfSequence); - offer.flags = offerSle.getFieldU32(ripple::sfFlags); + offer.takerPays = offerSle.getFieldAmount(xrpl::sfTakerPays); + offer.takerGets = offerSle.getFieldAmount(xrpl::sfTakerGets); + offer.seq = offerSle.getFieldU32(xrpl::sfSequence); + offer.flags = offerSle.getFieldU32(xrpl::sfFlags); - auto const quality = getQuality(offerSle.getFieldH256(ripple::sfBookDirectory)); - auto const rate = ripple::amountFromQuality(quality); + auto const quality = getQuality(offerSle.getFieldH256(xrpl::sfBookDirectory)); + auto const rate = xrpl::amountFromQuality(quality); offer.quality = rate.getText(); - if (offerSle.isFieldPresent(ripple::sfExpiration)) - offer.expiration = offerSle.getFieldU32(ripple::sfExpiration); + if (offerSle.isFieldPresent(xrpl::sfExpiration)) + offer.expiration = offerSle.getFieldU32(xrpl::sfExpiration); offers.push_back(offer); }; @@ -67,21 +67,21 @@ AccountOffersHandler::process(AccountOffersHandler::Input const& input, Context auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::keylet::account(*accountID).key, + xrpl::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield ); if (!accountLedgerObject) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; Output response; - response.account = ripple::to_string(*accountID); // NOLINT(bugprone-unchecked-optional-access) - response.ledgerHash = ripple::strHex(lgrInfo.hash); + response.account = xrpl::to_string(*accountID); // NOLINT(bugprone-unchecked-optional-access) + response.ledgerHash = xrpl::strHex(lgrInfo.hash); response.ledgerIndex = lgrInfo.seq; - auto const addToResponse = [&](ripple::SLE const sle) { - if (sle.getType() == ripple::ltOFFER) + auto const addToResponse = [&](xrpl::SLE const sle) { + if (sle.getType() == xrpl::ltOFFER) addOffer(response.offers, sle); return true; @@ -145,13 +145,13 @@ tag_invoke( if (offer.expiration) jsonObject[JS(expiration)] = *offer.expiration; - auto const convertAmount = [&](char const* field, ripple::STAmount const& amount) { + auto const convertAmount = [&](char const* field, xrpl::STAmount const& amount) { if (amount.native()) { jsonObject[field] = amount.getText(); } else { jsonObject[field] = { - {JS(currency), ripple::to_string(amount.getCurrency())}, - {JS(issuer), ripple::to_string(amount.getIssuer())}, + {JS(currency), xrpl::to_string(amount.get().currency)}, + {JS(issuer), xrpl::to_string(amount.getIssuer())}, {JS(value), amount.getText()}, }; } diff --git a/src/rpc/handlers/AccountOffers.hpp b/src/rpc/handlers/AccountOffers.hpp index a4bb11719..990f02b0f 100644 --- a/src/rpc/handlers/AccountOffers.hpp +++ b/src/rpc/handlers/AccountOffers.hpp @@ -31,9 +31,9 @@ class AccountOffersHandler { std::shared_ptr sharedPtrBackend_; public: - static constexpr auto kLIMIT_MIN = 10; - static constexpr auto kLIMIT_MAX = 400; - static constexpr auto kLIMIT_DEFAULT = 200; + static constexpr auto kLimitMin = 10; + static constexpr auto kLimitMax = 400; + static constexpr auto kLimitDefault = 200; /** * @brief A struct to hold data for one offer response @@ -41,8 +41,8 @@ public: struct Offer { uint32_t flags{}; uint32_t seq{}; - ripple::STAmount takerGets; - ripple::STAmount takerPays; + xrpl::STAmount takerGets; + xrpl::STAmount takerPays; std::string quality; std::optional expiration; }; @@ -67,7 +67,7 @@ public: std::string account; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = kLIMIT_DEFAULT; + uint32_t limit = kLimitDefault; std::optional marker; }; @@ -92,7 +92,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, @@ -100,12 +100,12 @@ public: {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + modifiers::Clamp{kLimitMin, kLimitMax}}, {JS(ledger), check::Deprecated{}}, {JS(strict), check::Deprecated{}}, }; - return kRPC_SPEC; + return kRpcSpec; } /** @@ -120,7 +120,7 @@ public: private: static void - addOffer(std::vector& offers, ripple::SLE const& offerSle); + addOffer(std::vector& offers, xrpl::SLE const& offerSle); /** * @brief Convert the Output to a JSON object diff --git a/src/rpc/handlers/AccountTx.cpp b/src/rpc/handlers/AccountTx.cpp index 70f52217f..720529438 100644 --- a/src/rpc/handlers/AccountTx.cpp +++ b/src/rpc/handlers/AccountTx.cpp @@ -46,7 +46,7 @@ AccountTxHandler::process(AccountTxHandler::Input const& input, Context const& c range->maxSequence || // NOLINT(bugprone-unchecked-optional-access) input.ledgerIndexMin < range->minSequence)) { // NOLINT(bugprone-unchecked-optional-access) - return Error{Status{RippledError::rpcLGR_IDX_MALFORMED, "ledgerSeqMinOutOfRange"}}; + return Error{Status{RippledError::RpcLgrIdxMalformed, "ledgerSeqMinOutOfRange"}}; } if (static_cast(*input.ledgerIndexMin) > minIndex) @@ -59,7 +59,7 @@ AccountTxHandler::process(AccountTxHandler::Input const& input, Context const& c range->maxSequence || // NOLINT(bugprone-unchecked-optional-access) input.ledgerIndexMax < range->minSequence)) { // NOLINT(bugprone-unchecked-optional-access) - return Error{Status{RippledError::rpcLGR_IDX_MALFORMED, "ledgerSeqMaxOutOfRange"}}; + return Error{Status{RippledError::RpcLgrIdxMalformed, "ledgerSeqMaxOutOfRange"}}; } if (static_cast(*input.ledgerIndexMax) < maxIndex) @@ -68,16 +68,14 @@ AccountTxHandler::process(AccountTxHandler::Input const& input, Context const& c if (minIndex > maxIndex) { if (ctx.apiVersion == 1u) - return Error{Status{RippledError::rpcLGR_IDXS_INVALID}}; + return Error{Status{RippledError::RpcLgrIdxsInvalid}}; - return Error{Status{RippledError::rpcINVALID_LGR_RANGE}}; + return Error{Status{RippledError::RpcInvalidLgrRange}}; } if (input.ledgerHash || input.ledgerIndex || input.usingValidatedLedger) { if (ctx.apiVersion > 1u && (input.ledgerIndexMax || input.ledgerIndexMin)) { - return Error{ - Status{RippledError::rpcINVALID_PARAMS, "containsLedgerSpecifierAndRange"} - }; + return Error{Status{RippledError::RpcInvalidParams, "containsLedgerSpecifierAndRange"}}; } if (!input.ledgerIndexMax && !input.ledgerIndexMin) { @@ -113,7 +111,7 @@ AccountTxHandler::process(AccountTxHandler::Input const& input, Context const& c } } - auto const limit = input.limit.value_or(kLIMIT_DEFAULT); + auto const limit = input.limit.value_or(kLimitDefault); auto const accountID = accountFromStringStrict(input.account); auto const [txnsAndCursor, timeDiff] = util::timed([&]() { return sharedPtrBackend_->fetchAccountTransactions( @@ -188,8 +186,8 @@ AccountTxHandler::process(AccountTxHandler::Input const& input, Context const& c txnPlusMeta.ledgerSequence, ctx.yield ); ledgerHeader) { - obj[JS(ledger_hash)] = ripple::strHex(ledgerHeader->hash); - obj[JS(close_time_iso)] = ripple::to_string_iso(ledgerHeader->closeTime); + obj[JS(ledger_hash)] = xrpl::strHex(ledgerHeader->hash); + obj[JS(close_time_iso)] = xrpl::toStringIso(ledgerHeader->closeTime); } } obj[JS(validated)] = true; @@ -205,7 +203,7 @@ AccountTxHandler::process(AccountTxHandler::Input const& input, Context const& c } response.limit = input.limit; - response.account = ripple::to_string(*accountID); // NOLINT(bugprone-unchecked-optional-access) + response.account = xrpl::to_string(*accountID); // NOLINT(bugprone-unchecked-optional-access) response.ledgerIndexMin = minIndex; response.ledgerIndexMax = maxIndex; diff --git a/src/rpc/handlers/AccountTx.hpp b/src/rpc/handlers/AccountTx.hpp index 10df1a3a6..d21cf5814 100644 --- a/src/rpc/handlers/AccountTx.hpp +++ b/src/rpc/handlers/AccountTx.hpp @@ -41,9 +41,9 @@ class AccountTxHandler { std::shared_ptr etl_; public: - static constexpr auto kLIMIT_MIN = 1; - static constexpr auto kLIMIT_MAX = 1000; - static constexpr auto kLIMIT_DEFAULT = 200; + static constexpr auto kLimitMin = 1; + static constexpr auto kLimitMax = 1000; + static constexpr auto kLimitDefault = 200; /** * @brief A struct to hold the marker data @@ -113,7 +113,7 @@ public: spec([[maybe_unused]] uint32_t apiVersion) { auto const& typesKeysInLowercase = util::getTxTypesInLowercase(); - static auto const kRPC_SPEC_FOR_V1 = RpcSpec{ + static auto const kRpcSpecForV1 = RpcSpec{ {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, @@ -123,11 +123,11 @@ public: {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + modifiers::Clamp{kLimitMin, kLimitMax}}, {JS(marker), meta::WithCustomError{ validation::Type{}, - Status{RippledError::rpcINVALID_PARAMS, "invalidMarker"}, + Status{RippledError::RpcInvalidParams, "invalidMarker"}, }, meta::Section{ {JS(ledger), validation::Required{}, validation::Type{}}, @@ -143,15 +143,15 @@ public: }, }; - static auto const kRPC_SPEC = RpcSpec{ - kRPC_SPEC_FOR_V1, + static auto const kRpcSpec = RpcSpec{ + kRpcSpecForV1, { {JS(binary), validation::Type{}}, {JS(forward), validation::Type{}}, } }; - return apiVersion == 1 ? kRPC_SPEC_FOR_V1 : kRPC_SPEC; + return apiVersion == 1 ? kRpcSpecForV1 : kRpcSpec; } /** diff --git a/src/rpc/handlers/BookChanges.cpp b/src/rpc/handlers/BookChanges.cpp index d9012f6cf..70d561543 100644 --- a/src/rpc/handlers/BookChanges.cpp +++ b/src/rpc/handlers/BookChanges.cpp @@ -45,7 +45,7 @@ BookChangesHandler::process(BookChangesHandler::Input const& input, Context cons Output response; response.bookChanges = BookChanges::compute(transactions); - response.ledgerHash = ripple::strHex(lgrInfo.hash); + response.ledgerHash = xrpl::strHex(lgrInfo.hash); response.ledgerIndex = lgrInfo.seq; response.ledgerTime = lgrInfo.closeTime.time_since_epoch().count(); @@ -91,7 +91,7 @@ tag_invoke(boost::json::value_to_tag, boost::json::va [[nodiscard]] boost::json::object computeBookChanges( - ripple::LedgerHeader const& lgrInfo, + xrpl::LedgerHeader const& lgrInfo, std::vector const& transactions ) { diff --git a/src/rpc/handlers/BookChanges.hpp b/src/rpc/handlers/BookChanges.hpp index 5abf22e93..e82c5a0ce 100644 --- a/src/rpc/handlers/BookChanges.hpp +++ b/src/rpc/handlers/BookChanges.hpp @@ -70,12 +70,12 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/rpc/handlers/BookOffers.cpp b/src/rpc/handlers/BookOffers.cpp index 3522ac5e9..af8b72f94 100644 --- a/src/rpc/handlers/BookOffers.cpp +++ b/src/rpc/handlers/BookOffers.cpp @@ -56,12 +56,12 @@ BookOffersHandler::process(Input const& input, Context const& ctx) const sharedPtrBackend_->fetchBookOffers(bookKey, lgrInfo.seq, input.limit, ctx.yield); auto output = BookOffersHandler::Output{}; - output.ledgerHash = ripple::strHex(lgrInfo.hash); + output.ledgerHash = xrpl::strHex(lgrInfo.hash); output.ledgerIndex = lgrInfo.seq; output.offers = postProcessOrderBook( offers, book, - input.taker ? *(input.taker) : beast::zero, + input.taker ? *(input.taker) : beast::kZero, *sharedPtrBackend_, *amendmentCenter_, lgrInfo.seq, @@ -91,24 +91,24 @@ tag_invoke(boost::json::value_to_tag, boost::json::val auto input = BookOffersHandler::Input{}; auto const& jsonObject = jv.as_object(); - ripple::to_currency( + xrpl::toCurrency( input.getsCurrency, boost::json::value_to(jv.at(JS(taker_gets)).as_object().at(JS(currency))) ); - ripple::to_currency( + xrpl::toCurrency( input.paysCurrency, boost::json::value_to(jv.at(JS(taker_pays)).as_object().at(JS(currency))) ); if (jv.at(JS(taker_gets)).as_object().contains(JS(issuer))) { - ripple::to_issuer( + xrpl::toIssuer( input.getsID, boost::json::value_to(jv.at(JS(taker_gets)).as_object().at(JS(issuer))) ); } if (jv.at(JS(taker_pays)).as_object().contains(JS(issuer))) { - ripple::to_issuer( + xrpl::toIssuer( input.paysID, boost::json::value_to(jv.at(JS(taker_pays)).as_object().at(JS(issuer))) ); diff --git a/src/rpc/handlers/BookOffers.hpp b/src/rpc/handlers/BookOffers.hpp index b974d6420..8d0937279 100644 --- a/src/rpc/handlers/BookOffers.hpp +++ b/src/rpc/handlers/BookOffers.hpp @@ -37,9 +37,9 @@ class BookOffersHandler { std::shared_ptr amendmentCenter_; public: - static constexpr auto kLIMIT_MIN = 1; - static constexpr auto kLIMIT_MAX = 100; - static constexpr auto kLIMIT_DEFAULT = 60; + static constexpr auto kLimitMin = 1; + static constexpr auto kLimitMax = 100; + static constexpr auto kLimitDefault = 60; /** * @brief A struct to hold the output data of the command @@ -60,13 +60,13 @@ public: struct Input { std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = kLIMIT_DEFAULT; - std::optional taker; - ripple::Currency paysCurrency; - ripple::Currency getsCurrency; + uint32_t limit = kLimitDefault; + std::optional taker; + xrpl::Currency paysCurrency; + xrpl::Currency getsCurrency; // accountID will be filled by input converter, if no issuer is given, will use XRP issuer - ripple::AccountID paysID = ripple::xrpAccount(); - ripple::AccountID getsID = ripple::xrpAccount(); + xrpl::AccountID paysID = xrpl::xrpAccount(); + xrpl::AccountID getsID = xrpl::xrpAccount(); std::optional domain; }; @@ -95,7 +95,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(taker_gets), validation::Required{}, validation::Type{}, @@ -104,12 +104,12 @@ public: validation::Required{}, meta::WithCustomError{ validation::CustomValidators::currencyValidator, - Status(RippledError::rpcDST_AMT_MALFORMED) + Status(RippledError::RpcDstAmtMalformed) }}, {JS(issuer), meta::WithCustomError{ validation::CustomValidators::issuerValidator, - Status(RippledError::rpcDST_ISR_MALFORMED) + Status(RippledError::RpcDstIsrMalformed) }} }}, {JS(taker_pays), @@ -120,38 +120,38 @@ public: validation::Required{}, meta::WithCustomError{ validation::CustomValidators::currencyValidator, - Status(RippledError::rpcSRC_CUR_MALFORMED) + Status(RippledError::RpcSrcCurMalformed) }}, {JS(issuer), meta::WithCustomError{ validation::CustomValidators::issuerValidator, - Status(RippledError::rpcSRC_ISR_MALFORMED) + Status(RippledError::RpcSrcIsrMalformed) }} }}, // return INVALID_PARAMS if account format is wrong for "taker" {JS(taker), meta::WithCustomError{ validation::CustomValidators::accountValidator, - Status(RippledError::rpcINVALID_PARAMS, "Invalid field 'taker'.") + Status(RippledError::RpcInvalidParams, "Invalid field 'taker'.") }}, {JS(domain), meta::WithCustomError{ validation::Type{}, - Status(RippledError::rpcDOMAIN_MALFORMED, "Unable to parse domain.") + Status(RippledError::RpcDomainMalformed, "Unable to parse domain.") }, meta::WithCustomError{ validation::CustomValidators::uint256HexStringValidator, - Status(RippledError::rpcDOMAIN_MALFORMED, "Unable to parse domain.") + Status(RippledError::RpcDomainMalformed, "Unable to parse domain.") }}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + modifiers::Clamp{kLimitMin, kLimitMax}}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/rpc/handlers/DepositAuthorized.cpp b/src/rpc/handlers/DepositAuthorized.cpp index 15bb3ba23..e07fb503d 100644 --- a/src/rpc/handlers/DepositAuthorized.cpp +++ b/src/rpc/handlers/DepositAuthorized.cpp @@ -24,7 +24,6 @@ #include #include -#include #include #include @@ -56,40 +55,40 @@ DepositAuthorizedHandler::process( auto const srcAccountLedgerObject = sharedPtrBackend_->fetchLedgerObject( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::keylet::account(*sourceAccountID).key, + xrpl::keylet::account(*sourceAccountID).key, lgrInfo.seq, ctx.yield ); if (!srcAccountLedgerObject) - return Error{Status{RippledError::rpcSRC_ACT_NOT_FOUND, "source_accountNotFound"}}; + return Error{Status{RippledError::RpcSrcActNotFound, "source_accountNotFound"}}; // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - auto const dstKeylet = ripple::keylet::account(*destinationAccountID).key; + auto const dstKeylet = xrpl::keylet::account(*destinationAccountID).key; auto const dstAccountLedgerObject = sharedPtrBackend_->fetchLedgerObject(dstKeylet, lgrInfo.seq, ctx.yield); if (!dstAccountLedgerObject) - return Error{Status{RippledError::rpcDST_ACT_NOT_FOUND, "destination_accountNotFound"}}; + return Error{Status{RippledError::RpcDstActNotFound, "destination_accountNotFound"}}; Output response; - auto it = ripple::SerialIter{dstAccountLedgerObject->data(), dstAccountLedgerObject->size()}; - auto const sleDest = ripple::SLE{it, dstKeylet}; + auto it = xrpl::SerialIter{dstAccountLedgerObject->data(), dstAccountLedgerObject->size()}; + auto const sleDest = xrpl::SLE{it, dstKeylet}; bool const reqAuth = - sleDest.isFlag(ripple::lsfDepositAuth) && (sourceAccountID != destinationAccountID); + sleDest.isFlag(xrpl::lsfDepositAuth) && (sourceAccountID != destinationAccountID); auto const& creds = input.credentials; bool const credentialsPresent = creds.has_value(); - ripple::STArray authCreds; + xrpl::STArray authCreds; if (credentialsPresent) { if (creds->empty()) { return Error{ - Status{RippledError::rpcINVALID_PARAMS, "credential array has no elements."} + Status{RippledError::RpcInvalidParams, "credential array has no elements."} }; } - if (creds->size() > ripple::maxCredentialsArraySize) { - return Error{Status{RippledError::rpcINVALID_PARAMS, "credential array too long."}}; + if (creds->size() > xrpl::kMaxCredentialsArraySize) { + return Error{Status{RippledError::RpcInvalidParams, "credential array too long."}}; } auto const credArray = credentials::fetchCredentialArray( input.credentials, @@ -108,7 +107,7 @@ DepositAuthorizedHandler::process( bool depositAuthorized = true; if (reqAuth) { - ripple::uint256 hashKey; + xrpl::uint256 hashKey; if (credentialsPresent) { auto const sortedAuthCreds = credentials::createAuthCredentials(authCreds); ASSERT( @@ -117,10 +116,10 @@ DepositAuthorizedHandler::process( ); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - hashKey = ripple::keylet::depositPreauth(*destinationAccountID, sortedAuthCreds).key; + hashKey = xrpl::keylet::depositPreauth(*destinationAccountID, sortedAuthCreds).key; } else { // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - hashKey = ripple::keylet::depositPreauth(*destinationAccountID, *sourceAccountID).key; + hashKey = xrpl::keylet::depositPreauth(*destinationAccountID, *sourceAccountID).key; } depositAuthorized = @@ -129,7 +128,7 @@ DepositAuthorizedHandler::process( response.sourceAccount = input.sourceAccount; response.destinationAccount = input.destinationAccount; - response.ledgerHash = ripple::strHex(lgrInfo.hash); + response.ledgerHash = xrpl::strHex(lgrInfo.hash); response.ledgerIndex = lgrInfo.seq; response.depositAuthorized = depositAuthorized; if (credentialsPresent) diff --git a/src/rpc/handlers/DepositAuthorized.hpp b/src/rpc/handlers/DepositAuthorized.hpp index a0db152d2..20999738c 100644 --- a/src/rpc/handlers/DepositAuthorized.hpp +++ b/src/rpc/handlers/DepositAuthorized.hpp @@ -81,7 +81,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(source_account), validation::Required{}, validation::CustomValidators::accountValidator}, @@ -93,7 +93,7 @@ public: {JS(credentials), validation::Type{}, validation::Hex256ItemType()} }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/rpc/handlers/Feature.cpp b/src/rpc/handlers/Feature.cpp index e3098e994..f9821e5e9 100644 --- a/src/rpc/handlers/Feature.cpp +++ b/src/rpc/handlers/Feature.cpp @@ -56,7 +56,7 @@ FeatureHandler::process(FeatureHandler::Input const& input, Context const& ctx) auto searchPredicate = [search = input.feature](auto const& feature) { if (search) { - return ripple::to_string(feature.feature) == *search or feature.name == *search; + return xrpl::to_string(feature.feature) == *search or feature.name == *search; } return true; }; @@ -66,14 +66,14 @@ FeatureHandler::process(FeatureHandler::Input const& input, Context const& ctx) all | vs::filter(searchPredicate), std::back_inserter(filtered), [&](auto const& feature) { return Output::Feature{ .name = feature.name, - .key = ripple::to_string(feature.feature), + .key = xrpl::to_string(feature.feature), .supported = feature.isSupportedByClio and feature.isSupportedByXRPL, }; } ); if (filtered.empty()) - return Error{Status{RippledError::rpcBAD_FEATURE}}; + return Error{Status{RippledError::RpcBadFeature}}; std::vector names; rg::transform(filtered, std::back_inserter(names), [](auto const& feature) { @@ -93,7 +93,7 @@ FeatureHandler::process(FeatureHandler::Input const& input, Context const& ctx) return Output{ .features = std::move(features), - .ledgerHash = ripple::strHex(lgrInfo.hash), + .ledgerHash = xrpl::strHex(lgrInfo.hash), .ledgerIndex = lgrInfo.seq, .inlineResult = input.feature.has_value() }; @@ -102,20 +102,20 @@ FeatureHandler::process(FeatureHandler::Input const& input, Context const& ctx) RpcSpecConstRef FeatureHandler::spec([[maybe_unused]] uint32_t apiVersion) { - static RpcSpec const kRPC_SPEC = { + static RpcSpec const kRpcSpec = { {JS(feature), validation::Type{}}, {JS(vetoed), meta::WithCustomError{ validation::NotSupported{}, Status( - RippledError::rpcNO_PERMISSION, + RippledError::RpcNoPermission, "The admin portion of feature API is not available through Clio." ) }}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, }; - return kRPC_SPEC; + return kRpcSpec; } void diff --git a/src/rpc/handlers/GatewayBalances.cpp b/src/rpc/handlers/GatewayBalances.cpp index 6509382ad..e9585d2be 100644 --- a/src/rpc/handlers/GatewayBalances.cpp +++ b/src/rpc/handlers/GatewayBalances.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -62,21 +63,21 @@ GatewayBalancesHandler::process( auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::keylet::account(*accountID).key, + xrpl::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield ); if (!accountLedgerObject) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; auto output = GatewayBalancesHandler::Output{}; - auto addEscrow = [&](ripple::SLE const& sle) { - if (sle.getType() == ripple::ltESCROW) { - auto const& escrow = sle.getFieldAmount(ripple::sfAmount); - auto& lockedBalance = output.locked[escrow.getCurrency()]; - if (lockedBalance == beast::zero) { + auto addEscrow = [&](xrpl::SLE const& sle) { + if (sle.getType() == xrpl::ltESCROW) { + auto const& escrow = sle.getFieldAmount(xrpl::sfAmount); + auto& lockedBalance = output.locked[escrow.get().currency]; + if (lockedBalance == beast::kZero) { // This is needed to set the currency code correctly lockedBalance = escrow; } else { @@ -87,28 +88,28 @@ GatewayBalancesHandler::process( // On overflow return the largest valid STAmount. // Very large sums of STAmount are approximations // anyway. - lockedBalance = ripple::STAmount( - lockedBalance.issue(), - ripple::STAmount::cMaxValue, - ripple::STAmount::cMaxOffset + lockedBalance = xrpl::STAmount( + lockedBalance.get(), + xrpl::STAmount::kMaxValue, + xrpl::STAmount::kMaxOffset ); } } } }; - auto const addToResponse = [&](ripple::SLE const sle) { + auto const addToResponse = [&](xrpl::SLE const sle) { addEscrow(sle); - if (sle.getType() == ripple::ltRIPPLE_STATE) { - ripple::STAmount balance = sle.getFieldAmount(ripple::sfBalance); - auto const lowLimit = sle.getFieldAmount(ripple::sfLowLimit); - auto const highLimit = sle.getFieldAmount(ripple::sfHighLimit); + if (sle.getType() == xrpl::ltRIPPLE_STATE) { + xrpl::STAmount balance = sle.getFieldAmount(xrpl::sfBalance); + auto const lowLimit = sle.getFieldAmount(xrpl::sfLowLimit); + auto const highLimit = sle.getFieldAmount(xrpl::sfHighLimit); auto const lowID = lowLimit.getIssuer(); auto const highID = highLimit.getIssuer(); auto const viewLowest = (lowLimit.getIssuer() == accountID); - auto const flags = sle.getFieldU32(ripple::sfFlags); - auto const freeze = flags & (viewLowest ? ripple::lsfLowFreeze : ripple::lsfHighFreeze); + auto const flags = sle.getFieldU32(xrpl::sfFlags); + auto const freeze = flags & (viewLowest ? xrpl::lsfLowFreeze : xrpl::lsfHighFreeze); if (!viewLowest) balance.negate(); @@ -133,16 +134,18 @@ GatewayBalancesHandler::process( output.frozenBalances[peer].push_back(-balance); } else { // normal negative balance, obligation to customer - auto& bal = output.sums[balance.getCurrency()]; - if (bal == beast::zero) { + auto& bal = output.sums[balance.get().currency]; + if (bal == beast::kZero) { // This is needed to set the currency code correctly bal = -balance; } else { try { bal -= balance; } catch (std::runtime_error const& e) { - bal = ripple::STAmount( - bal.issue(), ripple::STAmount::cMaxValue, ripple::STAmount::cMaxOffset + bal = xrpl::STAmount( + bal.get(), + xrpl::STAmount::kMaxValue, + xrpl::STAmount::kMaxOffset ); } } @@ -167,7 +170,7 @@ GatewayBalancesHandler::process( return Error{ret.error()}; output.accountID = input.account; - output.ledgerHash = ripple::strHex(lgrInfo.hash); + output.ledgerHash = xrpl::strHex(lgrInfo.hash); output.ledgerIndex = lgrInfo.seq; return output; @@ -184,31 +187,30 @@ tag_invoke( if (!output.sums.empty()) { boost::json::object obligations; for (auto const& [k, v] : output.sums) - obligations[ripple::to_string(k)] = v.getText(); + obligations[xrpl::to_string(k)] = v.getText(); obj[JS(obligations)] = std::move(obligations); } - auto const toJson = - [](std::map> const& balances) { - boost::json::object balancesObj; + auto const toJson = [](std::map> const& balances) { + boost::json::object balancesObj; - if (not balances.empty()) { - for (auto const& [accId, accBalances] : balances) { - boost::json::array arr; - for (auto const& balance : accBalances) { - boost::json::object entry; - entry[JS(currency)] = ripple::to_string(balance.issue().currency); - entry[JS(value)] = balance.getText(); - arr.push_back(std::move(entry)); - } - - balancesObj[ripple::to_string(accId)] = std::move(arr); + if (not balances.empty()) { + for (auto const& [accId, accBalances] : balances) { + boost::json::array arr; + for (auto const& balance : accBalances) { + boost::json::object entry; + entry[JS(currency)] = xrpl::to_string(balance.get().currency); + entry[JS(value)] = balance.getText(); + arr.push_back(std::move(entry)); } - } - return balancesObj; - }; + balancesObj[xrpl::to_string(accId)] = std::move(arr); + } + } + + return balancesObj; + }; if (auto balances = toJson(output.hotBalances); !balances.empty()) obj[JS(balances)] = balances; @@ -224,7 +226,7 @@ tag_invoke( if (!output.locked.empty()) { boost::json::object lockedObj; for (auto const& [currency, amount] : output.locked) { - lockedObj[ripple::to_string(currency)] = amount.getText(); + lockedObj[xrpl::to_string(currency)] = amount.getText(); } obj[JS(locked)] = std::move(lockedObj); } diff --git a/src/rpc/handlers/GatewayBalances.hpp b/src/rpc/handlers/GatewayBalances.hpp index df5c1f668..65b6e4405 100644 --- a/src/rpc/handlers/GatewayBalances.hpp +++ b/src/rpc/handlers/GatewayBalances.hpp @@ -50,11 +50,11 @@ public: uint32_t ledgerIndex; std::string accountID; bool overflow = false; - std::map sums; - std::map> hotBalances; - std::map> assets; - std::map> frozenBalances; - std::map locked; + std::map sums; + std::map> hotBalances; + std::map> assets; + std::map> frozenBalances; + std::map locked; // validated should be sent via framework bool validated = true; }; @@ -64,7 +64,7 @@ public: */ struct Input { std::string account; - std::set hotWallets; + std::set hotWallets; std::optional ledgerHash; std::optional ledgerIndex; }; @@ -99,18 +99,17 @@ public: // wallet needs to be an valid accountID or public key auto const wallets = value.is_array() ? value.as_array() : boost::json::array{value}; - auto const getAccountID = - [](auto const& j) -> std::optional { + auto const getAccountID = [](auto const& j) -> std::optional { if (j.is_string()) { - auto const pk = util::parseBase58Wrapper( - ripple::TokenType::AccountPublic, + auto const pk = util::parseBase58Wrapper( + xrpl::TokenType::AccountPublic, boost::json::value_to(j) ); if (pk) - return ripple::calcAccountID(*pk); + return xrpl::calcAccountID(*pk); - return util::parseBase58Wrapper( + return util::parseBase58Wrapper( boost::json::value_to(j) ); } @@ -128,20 +127,19 @@ public: }; }; - static auto const kSPEC_COMMON = RpcSpec{ + static auto const kSpecCommon = RpcSpec{ {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator} }; - static auto const kSPEC_V1 = RpcSpec{ - kSPEC_COMMON, {{JS(hotwallet), getHotWalletValidator(ripple::rpcINVALID_HOTWALLET)}} - }; - static auto const kSPEC_V2 = RpcSpec{ - kSPEC_COMMON, {{JS(hotwallet), getHotWalletValidator(ripple::rpcINVALID_PARAMS)}} + static auto const kSpecV1 = RpcSpec{ + kSpecCommon, {{JS(hotwallet), getHotWalletValidator(xrpl::RpcInvalidHotwallet)}} }; + static auto const kSpecV2 = + RpcSpec{kSpecCommon, {{JS(hotwallet), getHotWalletValidator(xrpl::RpcInvalidParams)}}}; - return apiVersion == 1 ? kSPEC_V1 : kSPEC_V2; + return apiVersion == 1 ? kSpecV1 : kSpecV2; } /** diff --git a/src/rpc/handlers/GetAggregatePrice.cpp b/src/rpc/handlers/GetAggregatePrice.cpp index 44cdc464f..0b8cc519a 100644 --- a/src/rpc/handlers/GetAggregatePrice.cpp +++ b/src/rpc/handlers/GetAggregatePrice.cpp @@ -64,47 +64,46 @@ GetAggregatePriceHandler::process( // sorted descending by lastUpdateTime, ascending by AssetPrice using TimestampPricesBiMap = boost::bimaps::bimap< boost::bimaps::multiset_of>, - boost::bimaps::multiset_of>; + boost::bimaps::multiset_of>; TimestampPricesBiMap timestampPricesBiMap; for (auto const& oracle : input.oracles) { - auto const oracleIndex = ripple::keylet::oracle(oracle.account, oracle.documentId).key; + auto const oracleIndex = xrpl::keylet::oracle(oracle.account, oracle.documentId).key; auto const oracleObject = sharedPtrBackend_->fetchLedgerObject(oracleIndex, lgrInfo.seq, ctx.yield); if (not oracleObject) continue; - ripple::STLedgerEntry const oracleSle{ - ripple::SerialIter{oracleObject->data(), oracleObject->size()}, oracleIndex + xrpl::STLedgerEntry const oracleSle{ + xrpl::SerialIter{oracleObject->data(), oracleObject->size()}, oracleIndex }; tracebackOracleObject(ctx.yield, oracleSle, [&](auto const& node) { - auto const& series = node.getFieldArray(ripple::sfPriceDataSeries); + auto const& series = node.getFieldArray(xrpl::sfPriceDataSeries); // Find the token pair entry with the price if (auto const iter = std::find_if( series.begin(), series.end(), - [&](ripple::STObject const& o) -> bool { - return o.getFieldCurrency(ripple::sfBaseAsset).getText() == + [&](xrpl::STObject const& o) -> bool { + return o.getFieldCurrency(xrpl::sfBaseAsset).getText() == input.baseAsset and - o.getFieldCurrency(ripple::sfQuoteAsset).getText() == - input.quoteAsset and - o.isFieldPresent(ripple::sfAssetPrice); + o.getFieldCurrency(xrpl::sfQuoteAsset).getText() == input.quoteAsset and + o.isFieldPresent(xrpl::sfAssetPrice); } ); iter != series.end()) { - auto const price = iter->getFieldU64(ripple::sfAssetPrice); + auto const price = iter->getFieldU64(xrpl::sfAssetPrice); // Asset price is after scale, so we need to get the negative of the scale - auto const scale = iter->isFieldPresent(ripple::sfScale) - ? -static_cast(iter->getFieldU8(ripple::sfScale)) + auto const scale = iter->isFieldPresent(xrpl::sfScale) + ? -static_cast(iter->getFieldU8(xrpl::sfScale)) : 0; timestampPricesBiMap.insert( TimestampPricesBiMap::value_type( - node.getFieldU32(ripple::sfLastUpdateTime), - ripple::STAmount{ripple::noIssue(), price, scale} + node.getFieldU32(xrpl::sfLastUpdateTime), + xrpl::STAmount{xrpl::noIssue(), price, scale} ) ); return true; @@ -114,14 +113,14 @@ GetAggregatePriceHandler::process( } if (timestampPricesBiMap.empty()) - return Error{Status{ripple::rpcOBJECT_NOT_FOUND}}; + return Error{Status{xrpl::RpcObjectNotFound}}; auto const latestTime = timestampPricesBiMap.left.begin()->first; Output out{ .time = latestTime, .trimStats = std::nullopt, - .ledgerHash = ripple::to_string(lgrInfo.hash), + .ledgerHash = xrpl::to_string(lgrInfo.hash), .ledgerIndex = lgrInfo.seq, .median = "" }; @@ -141,15 +140,15 @@ GetAggregatePriceHandler::process( auto const getStats = [](TimestampPricesBiMap::right_const_iterator begin, TimestampPricesBiMap::right_const_iterator end) -> Stats { - ripple::STAmount avg{ripple::noIssue(), 0, 0}; - ripple::Number sd{0}; + xrpl::STAmount avg{xrpl::noIssue(), 0, 0}; + xrpl::Number sd{0}; std::uint16_t const size = std::distance(begin, end); - avg = std::accumulate(begin, end, avg, [&](ripple::STAmount const& acc, auto const& it) { + avg = std::accumulate(begin, end, avg, [&](xrpl::STAmount const& acc, auto const& it) { return acc + it.first; }); - avg = divide(avg, ripple::STAmount{ripple::noIssue(), size, 0}, ripple::noIssue()); + avg = divide(avg, xrpl::STAmount{xrpl::noIssue(), size, 0}, xrpl::noIssue()); if (size > 1) { - sd = std::accumulate(begin, end, sd, [&](ripple::Number const& acc, auto const& it) { + sd = std::accumulate(begin, end, sd, [&](xrpl::Number const& acc, auto const& it) { return acc + ((it.first - avg) * (it.first - avg)); }); sd = root2(sd / (size - 1)); @@ -178,11 +177,11 @@ GetAggregatePriceHandler::process( auto const median = [&, size = out.extireStats.size]() { auto const middle = size / 2; if ((size % 2) == 0) { - static ripple::STAmount const kTWO{ripple::noIssue(), 2, 0}; + static xrpl::STAmount const kTwo{xrpl::noIssue(), 2, 0}; auto it = itAdvance(timestampPricesBiMap.right.begin(), middle - 1); auto const& a1 = it->first; auto const& a2 = (++it)->first; - return divide(a1 + a2, kTWO, ripple::noIssue()); + return divide(a1 + a2, kTwo, xrpl::noIssue()); } return itAdvance(timestampPricesBiMap.right.begin(), middle)->first; }(); @@ -194,14 +193,14 @@ GetAggregatePriceHandler::process( void GetAggregatePriceHandler::tracebackOracleObject( boost::asio::yield_context yield, - ripple::STObject const& oracleObject, - std::function const& callback + xrpl::STObject const& oracleObject, + std::function const& callback ) const { - static constexpr auto kHISTORY_MAX = 3; + static constexpr auto kHistoryMax = 3; - std::optional optOracleObject = oracleObject; - std::optional optCurrentObject = optOracleObject; + std::optional optOracleObject = oracleObject; + std::optional optCurrentObject = optOracleObject; bool isNew = false; bool noOracleFound = false; @@ -216,10 +215,10 @@ GetAggregatePriceHandler::tracebackOracleObject( if (callback(*optOracleObject) or isNew) return; - if (++history > kHISTORY_MAX) + if (++history > kHistoryMax) return; - auto const prevTxIndex = optCurrentObject->getFieldH256(ripple::sfPreviousTxnID); + auto const prevTxIndex = optCurrentObject->getFieldH256(xrpl::sfPreviousTxnID); auto const prevTx = sharedPtrBackend_->fetchTransaction(prevTxIndex, yield); if (not prevTx) @@ -228,13 +227,13 @@ GetAggregatePriceHandler::tracebackOracleObject( noOracleFound = true; auto const [_, meta] = deserializeTxPlusMeta(*prevTx); - for (ripple::STObject const& node : meta->getFieldArray(ripple::sfAffectedNodes)) { - if (node.getFieldU16(ripple::sfLedgerEntryType) != ripple::ltORACLE) { + for (xrpl::STObject const& node : meta->getFieldArray(xrpl::sfAffectedNodes)) { + if (node.getFieldU16(xrpl::sfLedgerEntryType) != xrpl::ltORACLE) { continue; } noOracleFound = false; optCurrentObject = node; - isNew = node.isFieldPresent(ripple::sfNewFields); + isNew = node.isFieldPresent(xrpl::sfNewFields); // if a meta is for the new and this is the first // look-up then it's the meta for the tx that // created the current object; i.e. there is no @@ -243,8 +242,8 @@ GetAggregatePriceHandler::tracebackOracleObject( return; optOracleObject = isNew - ? dynamic_cast(node.peekAtField(ripple::sfNewFields)) - : dynamic_cast(node.peekAtField(ripple::sfFinalFields)); + ? dynamic_cast(node.peekAtField(xrpl::sfNewFields)) + : dynamic_cast(node.peekAtField(xrpl::sfFinalFields)); break; } @@ -273,7 +272,7 @@ tag_invoke(boost::json::value_to_tag, boost::js oracle.as_object().at(JS(oracle_document_id)) ), // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - .account = *util::parseBase58Wrapper( + .account = *util::parseBase58Wrapper( boost::json::value_to(oracle.as_object().at(JS(account))) ) } @@ -306,7 +305,7 @@ tag_invoke( {JS(entire_set), boost::json::object{ {JS(mean), output.extireStats.avg.getText()}, - {JS(standard_deviation), ripple::to_string(output.extireStats.sd)}, + {JS(standard_deviation), xrpl::to_string(output.extireStats.sd)}, {JS(size), output.extireStats.size} }}, {JS(median), output.median} @@ -315,7 +314,7 @@ tag_invoke( if (output.trimStats) { jv.as_object()[JS(trimmed_set)] = boost::json::object{ {JS(mean), output.trimStats->avg.getText()}, - {JS(standard_deviation), ripple::to_string(output.trimStats->sd)}, + {JS(standard_deviation), xrpl::to_string(output.trimStats->sd)}, {JS(size), output.trimStats->size} }; } diff --git a/src/rpc/handlers/GetAggregatePrice.hpp b/src/rpc/handlers/GetAggregatePrice.hpp index 2b4157c10..fcadeb3e5 100644 --- a/src/rpc/handlers/GetAggregatePrice.hpp +++ b/src/rpc/handlers/GetAggregatePrice.hpp @@ -39,9 +39,9 @@ public: * @brief A struct to hold the statistics */ struct Stats { - ripple::STAmount avg{}; // NOLINT(readability-redundant-member-init) + xrpl::STAmount avg{}; // NOLINT(readability-redundant-member-init) // standard deviation - ripple::Number sd{}; // NOLINT(readability-redundant-member-init) + xrpl::Number sd{}; // NOLINT(readability-redundant-member-init) uint32_t size{0}; }; @@ -63,7 +63,7 @@ public: */ struct Oracle { std::uint32_t documentId{0}; - ripple::AccountID account; + xrpl::AccountID account; }; /** @@ -100,19 +100,19 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static constexpr auto kORACLES_MAX = 200; + static constexpr auto kOraclesMax = 200; - static auto const kORACLES_VALIDATOR = modifiers::CustomModifier{ + static auto const kOraclesValidator = modifiers::CustomModifier{ [](boost::json::value& value, std::string_view) -> MaybeError { if (!value.is_array() or value.as_array().empty() or - value.as_array().size() > kORACLES_MAX) - return Error{Status{RippledError::rpcORACLE_MALFORMED}}; + value.as_array().size() > kOraclesMax) + return Error{Status{RippledError::RpcOracleMalformed}}; for (auto& oracle : value.as_array()) { if (!oracle.is_object() or !oracle.as_object().contains(JS(oracle_document_id)) or !oracle.as_object().contains(JS(account))) - return Error{Status{RippledError::rpcORACLE_MALFORMED}}; + return Error{Status{RippledError::RpcOracleMalformed}}; auto maybeError = validation::Type{}.verify( oracle, JS(oracle_document_id) @@ -128,14 +128,14 @@ public: oracle.as_object(), JS(account) ); if (!maybeError) - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; }; return MaybeError{}; } }; - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, // validate quoteAsset and base_asset in accordance to the currency code found in XRPL @@ -147,15 +147,15 @@ public: validation::Required{}, meta::WithCustomError{ validation::CustomValidators::currencyValidator, - Status(RippledError::rpcINVALID_PARAMS) + Status(RippledError::RpcInvalidParams) }}, {JS(quote_asset), validation::Required{}, meta::WithCustomError{ validation::CustomValidators::currencyValidator, - Status(RippledError::rpcINVALID_PARAMS) + Status(RippledError::RpcInvalidParams) }}, - {JS(oracles), validation::Required{}, kORACLES_VALIDATOR}, + {JS(oracles), validation::Required{}, kOraclesValidator}, // note: Unlike `rippled`, Clio only supports UInt as input, no string, no `null`, etc. {JS(time_threshold), validation::Type{}}, { @@ -165,7 +165,7 @@ public: } }; - return kRPC_SPEC; + return kRpcSpec; } /** @@ -181,14 +181,15 @@ public: private: /** * @brief Calls callback on the oracle ledger entry - If the oracle entry does not contains the price pair, search up to three previous metadata - objects. Stops early if the callback returns true. + * + * If the oracle entry does not contains the price pair, search up to three previous metadata + * objects. Stops early if the callback returns true. */ void tracebackOracleObject( boost::asio::yield_context yield, - ripple::STObject const& oracleObject, - std::function const& callback + xrpl::STObject const& oracleObject, + std::function const& callback ) const; /** diff --git a/src/rpc/handlers/Ledger.cpp b/src/rpc/handlers/Ledger.cpp index 7e3f0d2ff..9c3eee428 100644 --- a/src/rpc/handlers/Ledger.cpp +++ b/src/rpc/handlers/Ledger.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -67,7 +68,7 @@ LedgerHandler::process(LedgerHandler::Input const& input, Context const& ctx) co return toJsonWithBinaryTx(tx, ctx.apiVersion); }; - auto const isoTimeStr = ripple::to_string_iso(lgrInfo.closeTime); + auto const isoTimeStr = xrpl::toStringIso(lgrInfo.closeTime); auto const expandTxJsonV2 = [&](data::TransactionAndMetadata const& tx) { auto [txn, meta] = toExpandedJson(tx, ctx.apiVersion); @@ -82,7 +83,7 @@ LedgerHandler::process(LedgerHandler::Input const& input, Context const& ctx) co } entry[JS(close_time_iso)] = isoTimeStr; - entry[JS(ledger_hash)] = ripple::strHex(lgrInfo.hash); + entry[JS(ledger_hash)] = xrpl::strHex(lgrInfo.hash); if (txn.contains(JS(hash))) { entry[JS(hash)] = txn.at(JS(hash)); txn.erase(JS(hash)); @@ -109,10 +110,10 @@ LedgerHandler::process(LedgerHandler::Input const& input, Context const& ctx) co if (input.ownerFunds) { // check the type of tx auto const [tx, meta] = rpc::deserializeTxPlusMeta(obj); - if (tx and tx->isFieldPresent(ripple::sfTransactionType) and - tx->getTxnType() == ripple::ttOFFER_CREATE) { - auto const account = tx->getAccountID(ripple::sfAccount); - auto const amount = tx->getFieldAmount(ripple::sfTakerGets); + if (tx and tx->isFieldPresent(xrpl::sfTransactionType) and + tx->getTxnType() == xrpl::ttOFFER_CREATE) { + auto const account = tx->getAccountID(xrpl::sfAccount); + auto const amount = tx->getFieldAmount(xrpl::sfTakerGets); // If the offer create is not self funded then add the // owner balance @@ -122,7 +123,7 @@ LedgerHandler::process(LedgerHandler::Input const& input, Context const& ctx) co *amendmentCenter_, lgrInfo.seq, account, - amount.getCurrency(), + amount.template get().currency, amount.getIssuer(), false, // fhIGNORE_FREEZE from rippled ctx.yield @@ -141,7 +142,7 @@ LedgerHandler::process(LedgerHandler::Input const& input, Context const& ctx) co std::move_iterator(hashes.begin()), std::move_iterator(hashes.end()), std::back_inserter(jsonTxs), - [](auto hash) { return boost::json::string(ripple::strHex(hash)); } + [](auto hash) { return boost::json::string(xrpl::strHex(hash)); } ); } } @@ -154,13 +155,13 @@ LedgerHandler::process(LedgerHandler::Input const& input, Context const& ctx) co for (auto const& obj : diff) { boost::json::object entry; - entry["object_id"] = ripple::strHex(obj.key); + entry["object_id"] = xrpl::strHex(obj.key); if (input.binary) { - entry["object"] = ripple::strHex(obj.blob); + entry["object"] = xrpl::strHex(obj.blob); } else if (!obj.blob.empty()) { - ripple::STLedgerEntry const sle{ - ripple::SerialIter{obj.blob.data(), obj.blob.size()}, obj.key + xrpl::STLedgerEntry const sle{ + xrpl::SerialIter{obj.blob.data(), obj.blob.size()}, obj.key }; entry["object"] = toJson(sle); } else { @@ -171,7 +172,7 @@ LedgerHandler::process(LedgerHandler::Input const& input, Context const& ctx) co } } - output.ledgerHash = ripple::strHex(lgrInfo.hash); + output.ledgerHash = xrpl::strHex(lgrInfo.hash); output.ledgerIndex = lgrInfo.seq; return output; diff --git a/src/rpc/handlers/Ledger.hpp b/src/rpc/handlers/Ledger.hpp index ae446cd00..7a06ef626 100644 --- a/src/rpc/handlers/Ledger.hpp +++ b/src/rpc/handlers/Ledger.hpp @@ -93,7 +93,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(full), validation::Type{}, validation::NotSupported{true}}, {JS(full), check::Deprecated{}}, {JS(accounts), validation::Type{}, validation::NotSupported{true}}, @@ -110,7 +110,7 @@ public: {JS(type), check::Deprecated{}}, }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/rpc/handlers/LedgerData.cpp b/src/rpc/handlers/LedgerData.cpp index 109a96633..9a05caa40 100644 --- a/src/rpc/handlers/LedgerData.cpp +++ b/src/rpc/handlers/LedgerData.cpp @@ -38,10 +38,10 @@ LedgerDataHandler::process(Input const& input, Context const& ctx) const { // marker must be int if outOfOrder is true if (input.outOfOrder && input.marker) - return Error{Status{RippledError::rpcINVALID_PARAMS, "outOfOrderMarkerNotInt"}}; + return Error{Status{RippledError::RpcInvalidParams, "outOfOrderMarkerNotInt"}}; if (!input.outOfOrder && input.diffMarker) - return Error{Status{RippledError::rpcINVALID_PARAMS, "markerNotString"}}; + return Error{Status{RippledError::RpcInvalidParams, "markerNotString"}}; auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "LedgerData's ledger range must be available"); @@ -67,10 +67,10 @@ LedgerDataHandler::process(Input const& input, Context const& ctx) const } else { if (input.marker && !sharedPtrBackend_->fetchLedgerObject(*(input.marker), lgrInfo.seq, ctx.yield)) - return Error{Status{RippledError::rpcINVALID_PARAMS, "markerDoesNotExist"}}; + return Error{Status{RippledError::RpcInvalidParams, "markerDoesNotExist"}}; } - output.ledgerHash = ripple::strHex(lgrInfo.hash); + output.ledgerHash = xrpl::strHex(lgrInfo.hash); output.ledgerIndex = lgrInfo.seq; auto const start = std::chrono::system_clock::now(); @@ -79,7 +79,7 @@ LedgerDataHandler::process(Input const& input, Context const& ctx) const if (input.diffMarker) { // keep the same logic as previous implementation auto diff = sharedPtrBackend_->fetchLedgerDiff(*(input.diffMarker), ctx.yield); - std::vector keys; + std::vector keys; for (auto& [key, object] : diff) { if (object.empty()) @@ -91,7 +91,7 @@ LedgerDataHandler::process(Input const& input, Context const& ctx) const for (size_t i = 0; i < objs.size(); ++i) { auto& obj = objs[i]; if (!obj.empty()) - results.push_back({keys[i], std::move(obj)}); + results.push_back({.key = keys[i], .blob = std::move(obj)}); } if (*(input.diffMarker) > lgrInfo.seq) @@ -101,7 +101,7 @@ LedgerDataHandler::process(Input const& input, Context const& ctx) const // framework can not handler the check right now, adjust the value here auto const limit = std::min( input.limit, - input.binary ? LedgerDataHandler::kLIMIT_BINARY : LedgerDataHandler::kLIMIT_JSON + input.binary ? LedgerDataHandler::kLimitBinary : LedgerDataHandler::kLimitJson ); auto page = sharedPtrBackend_->fetchLedgerPage( input.marker, lgrInfo.seq, limit, input.outOfOrder, ctx.yield @@ -109,7 +109,7 @@ LedgerDataHandler::process(Input const& input, Context const& ctx) const results = std::move(page.objects); if (page.cursor) { - output.marker = ripple::strHex(*(page.cursor)); + output.marker = xrpl::strHex(*(page.cursor)); } else if (input.outOfOrder) { output.diffMarker = range->maxSequence; // NOLINT(bugprone-unchecked-optional-access) } @@ -123,14 +123,14 @@ LedgerDataHandler::process(Input const& input, Context const& ctx) const output.states.reserve(results.size()); for (auto const& [key, object] : results) { - ripple::STLedgerEntry const sle{ripple::SerialIter{object.data(), object.size()}, key}; + xrpl::STLedgerEntry const sle{xrpl::SerialIter{object.data(), object.size()}, key}; // note the filter is after limit is applied, same as rippled - if (input.type == ripple::LedgerEntryType::ltANY || sle.getType() == input.type) { + if (input.type == xrpl::LedgerEntryType::ltANY || sle.getType() == input.type) { if (input.binary) { boost::json::object entry; - entry[JS(data)] = ripple::serializeHex(sle); - entry[JS(index)] = ripple::to_string(sle.key()); + entry[JS(data)] = xrpl::serializeHex(sle); + entry[JS(index)] = xrpl::to_string(sle.key()); output.states.push_back(std::move(entry)); } else { output.states.push_back(toJson(sle)); @@ -187,7 +187,7 @@ tag_invoke(boost::json::value_to_tag, boost::json::val if (jsonObject.contains(JS(binary))) { input.binary = jsonObject.at(JS(binary)).as_bool(); input.limit = - input.binary ? LedgerDataHandler::kLIMIT_BINARY : LedgerDataHandler::kLIMIT_JSON; + input.binary ? LedgerDataHandler::kLimitBinary : LedgerDataHandler::kLimitJson; } if (jsonObject.contains(JS(limit))) @@ -198,9 +198,8 @@ tag_invoke(boost::json::value_to_tag, boost::json::val if (jsonObject.contains(JS(marker))) { if (jsonObject.at(JS(marker)).is_string()) { - input.marker = ripple::uint256{ - boost::json::value_to(jsonObject.at(JS(marker))).data() - }; + input.marker = + xrpl::uint256{boost::json::value_to(jsonObject.at(JS(marker))).data()}; } else { input.diffMarker = util::integralValueAs(jsonObject.at(JS(marker))); } diff --git a/src/rpc/handlers/LedgerData.hpp b/src/rpc/handlers/LedgerData.hpp index d053f7e3d..f6f434b7f 100644 --- a/src/rpc/handlers/LedgerData.hpp +++ b/src/rpc/handlers/LedgerData.hpp @@ -37,8 +37,8 @@ class LedgerDataHandler { public: // constants - static constexpr uint32_t kLIMIT_BINARY = 2048; - static constexpr uint32_t kLIMIT_JSON = 256; + static constexpr uint32_t kLimitBinary = 2048; + static constexpr uint32_t kLimitJson = 256; /** * @brief A struct to hold the output data of the command @@ -64,11 +64,11 @@ public: std::optional ledgerHash; std::optional ledgerIndex; bool binary = false; - uint32_t limit = LedgerDataHandler::kLIMIT_JSON; // max 256 for json ; 2048 for binary - std::optional marker; + uint32_t limit = LedgerDataHandler::kLimitJson; // max 256 for json ; 2048 for binary + std::optional marker; std::optional diffMarker; bool outOfOrder = false; - ripple::LedgerEntryType type = ripple::LedgerEntryType::ltANY; + xrpl::LedgerEntryType type = xrpl::LedgerEntryType::ltANY; }; using Result = HandlerReturnType; @@ -92,7 +92,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(binary), validation::Type{}}, {"out_of_order", validation::Type{}}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, @@ -104,7 +104,7 @@ public: {JS(type), validation::CustomValidators::ledgerTypeValidator}, {JS(ledger), check::Deprecated{}}, }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/rpc/handlers/LedgerEntry.cpp b/src/rpc/handlers/LedgerEntry.cpp index f07a85ad2..20982b628 100644 --- a/src/rpc/handlers/LedgerEntry.cpp +++ b/src/rpc/handlers/LedgerEntry.cpp @@ -42,21 +42,21 @@ namespace rpc { LedgerEntryHandler::Result LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context const& ctx) const { - ripple::uint256 key; + xrpl::uint256 key; if (input.index) { - key = ripple::uint256{std::string_view(*(input.index))}; + key = xrpl::uint256{std::string_view(*(input.index))}; if (key.isZero()) - return Error{Status{RippledError::rpcENTRY_NOT_FOUND}}; + return Error{Status{RippledError::RpcEntryNotFound}}; } else if (input.accountRoot) { - key = ripple::keylet::account( + key = xrpl::keylet::account( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - *util::parseBase58Wrapper(*(input.accountRoot)) + *util::parseBase58Wrapper(*(input.accountRoot)) ) .key; } else if (input.did) { // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - key = ripple::keylet::did(*util::parseBase58Wrapper(*(input.did))).key; + key = xrpl::keylet::did(*util::parseBase58Wrapper(*(input.did))).key; } else if (input.directory) { auto const expectedkey = composeKeyFromDirectory(*input.directory); if (!expectedkey.has_value()) @@ -64,41 +64,40 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons key = expectedkey.value(); // std::expected, not optional } else if (input.offer) { - auto const id = util::parseBase58Wrapper( + auto const id = util::parseBase58Wrapper( boost::json::value_to(input.offer->at(JS(account))) ); // NOLINTBEGIN(bugprone-unchecked-optional-access) - key = ripple::keylet::offer( - *id, boost::json::value_to(input.offer->at(JS(seq))) - ) - .key; + key = + xrpl::keylet::offer(*id, boost::json::value_to(input.offer->at(JS(seq)))) + .key; // NOLINTEND(bugprone-unchecked-optional-access) } else if (input.rippleStateAccount) { auto const id1 = - util::parseBase58Wrapper(boost::json::value_to( + util::parseBase58Wrapper(boost::json::value_to( input.rippleStateAccount->at(JS(accounts)).as_array().at(0) )); auto const id2 = - util::parseBase58Wrapper(boost::json::value_to( + util::parseBase58Wrapper(boost::json::value_to( input.rippleStateAccount->at(JS(accounts)).as_array().at(1) )); - auto const currency = ripple::to_currency( + auto const currency = xrpl::toCurrency( boost::json::value_to(input.rippleStateAccount->at(JS(currency))) ); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - key = ripple::keylet::line(*id1, *id2, currency).key; + key = xrpl::keylet::trustLine(*id1, *id2, currency).key; } else if (input.escrow) { - auto const id = util::parseBase58Wrapper( + auto const id = util::parseBase58Wrapper( boost::json::value_to(input.escrow->at(JS(owner))) ); key = // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::keylet::escrow(*id, util::integralValueAs(input.escrow->at(JS(seq)))) + xrpl::keylet::escrow(*id, util::integralValueAs(input.escrow->at(JS(seq)))) .key; } else if (input.depositPreauth) { - auto const owner = util::parseBase58Wrapper( + auto const owner = util::parseBase58Wrapper( boost::json::value_to(input.depositPreauth->at(JS(owner))) ); // Only one of authorize or authorized_credentials MUST exist; @@ -111,11 +110,11 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons } if (input.depositPreauth->contains(JS(authorized))) { - auto const authorized = util::parseBase58Wrapper( + auto const authorized = util::parseBase58Wrapper( boost::json::value_to(input.depositPreauth->at(JS(authorized))) ); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - key = ripple::keylet::depositPreauth(*owner, *authorized).key; + key = xrpl::keylet::depositPreauth(*owner, *authorized).key; } else { auto const authorizedCredentials = rpc::credentials::parseAuthorizeCredentials( input.depositPreauth->at(JS(authorized_credentials)).as_array() @@ -129,14 +128,14 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons } // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - key = ripple::keylet::depositPreauth(*owner, authCreds).key; + key = xrpl::keylet::depositPreauth(*owner, authCreds).key; } } else if (input.ticket) { - auto const id = util::parseBase58Wrapper( + auto const id = util::parseBase58Wrapper( boost::json::value_to(input.ticket->at(JS(account))) ); - key = ripple::getTicketIndex( + key = xrpl::getTicketIndex( *id, // NOLINT(bugprone-unchecked-optional-access) util::integralValueAs(input.ticket->at(JS(ticket_seq))) ); @@ -144,17 +143,17 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons auto const getIssuerFromJson = [](auto const& assetJson) { // the field check has been done in validator auto const currency = - ripple::to_currency(boost::json::value_to(assetJson.at(JS(currency)))); - if (ripple::isXRP(currency)) { - return ripple::xrpIssue(); + xrpl::toCurrency(boost::json::value_to(assetJson.at(JS(currency)))); + if (xrpl::isXRP(currency)) { + return xrpl::xrpIssue(); } - auto const issuer = util::parseBase58Wrapper( + auto const issuer = util::parseBase58Wrapper( boost::json::value_to(assetJson.at(JS(issuer))) ); - return ripple::Issue{currency, *issuer}; + return xrpl::Issue{currency, *issuer}; }; - key = ripple::keylet::amm( + key = xrpl::keylet::amm( getIssuerFromJson(input.amm->at(JS(asset))), getIssuerFromJson(input.amm->at(JS(asset2))) ) @@ -165,18 +164,18 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons if (input.bridgeAccount) { auto const bridgeAccount = - util::parseBase58Wrapper(*(input.bridgeAccount)); + util::parseBase58Wrapper(*(input.bridgeAccount)); auto const chainType = - ripple::STXChainBridge::srcChain(bridgeAccount == input.bridge->lockingChainDoor()); + xrpl::STXChainBridge::srcChain(bridgeAccount == input.bridge->lockingChainDoor()); if (bridgeAccount != input.bridge->door(chainType)) return Error{Status{ClioError::RpcMalformedRequest}}; - key = ripple::keylet::bridge(input.bridge->value(), chainType).key; + key = xrpl::keylet::bridge(input.bridge->value(), chainType).key; } else if (input.chainClaimId) { - key = ripple::keylet::xChainClaimID(input.bridge->value(), *input.chainClaimId).key; + key = xrpl::keylet::xChainClaimID(input.bridge->value(), *input.chainClaimId).key; } else { - key = ripple::keylet::xChainCreateAccountClaimID( + key = xrpl::keylet::xChainCreateAccountClaimID( input.bridge->value(), *input.createAccountClaimId ) .key; @@ -186,58 +185,58 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons } else if (input.credential) { key = *input.credential; } else if (input.mptIssuance) { - auto const mptIssuanceID = ripple::uint192{std::string_view(*(input.mptIssuance))}; - key = ripple::keylet::mptIssuance(mptIssuanceID).key; + auto const mptIssuanceID = xrpl::uint192{std::string_view(*(input.mptIssuance))}; + key = xrpl::keylet::mptokenIssuance(mptIssuanceID).key; } else if (input.mptoken) { - auto const holder = ripple::parseBase58( + auto const holder = xrpl::parseBase58( boost::json::value_to(input.mptoken->at(JS(account))) ); - auto const mptIssuanceID = ripple::uint192{std::string_view( + auto const mptIssuanceID = xrpl::uint192{std::string_view( boost::json::value_to(input.mptoken->at(JS(mpt_issuance_id))) )}; // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - key = ripple::keylet::mptoken(mptIssuanceID, *holder).key; + key = xrpl::keylet::mptoken(mptIssuanceID, *holder).key; } else if (input.permissionedDomain) { - auto const account = ripple::parseBase58( + auto const account = xrpl::parseBase58( boost::json::value_to(input.permissionedDomain->at(JS(account))) ); auto const seq = util::integralValueAs(input.permissionedDomain->at(JS(seq))); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - key = ripple::keylet::permissionedDomain(*account, seq).key; + key = xrpl::keylet::permissionedDomain(*account, seq).key; } else if (input.vault) { - auto const account = ripple::parseBase58( + auto const account = xrpl::parseBase58( boost::json::value_to(input.vault->at(JS(owner))) ); auto const seq = util::integralValueAs(input.vault->at(JS(seq))); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - key = ripple::keylet::vault(*account, seq).key; + key = xrpl::keylet::vault(*account, seq).key; } else if (input.loanBroker) { - auto const account = ripple::parseBase58( + auto const account = xrpl::parseBase58( boost::json::value_to(input.loanBroker->at(JS(owner))) ); auto const seq = util::integralValueAs(input.loanBroker->at(JS(seq))); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - key = ripple::keylet::loanbroker(*account, seq).key; + key = xrpl::keylet::loanBroker(*account, seq).key; } else if (input.loan) { - auto const id = ripple::uint256{ + auto const id = xrpl::uint256{ boost::json::value_to(input.loan->at(JS(loan_broker_id))).data() }; auto const seq = util::integralValueAs(input.loan->at(JS(loan_seq))); - key = ripple::keylet::loan(id, seq).key; + key = xrpl::keylet::loan(id, seq).key; } else if (input.delegate) { - auto const account = ripple::parseBase58( + auto const account = xrpl::parseBase58( boost::json::value_to(input.delegate->at(JS(account))) ); - auto const authorize = ripple::parseBase58( + auto const authorize = xrpl::parseBase58( boost::json::value_to(input.delegate->at(JS(authorize))) ); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - key = ripple::keylet::delegate(*account, *authorize).key; + key = xrpl::keylet::delegate(*account, *authorize).key; } else { // Must specify 1 of the following fields to indicate what type if (ctx.apiVersion == 1) return Error{Status{ClioError::RpcUnknownOption}}; - return Error{Status{RippledError::rpcINVALID_PARAMS, "No ledger_entry params provided."}}; + return Error{Status{RippledError::RpcInvalidParams, "No ledger_entry params provided."}}; } // check ledger exists @@ -260,30 +259,30 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons if (!ledgerObject || ledgerObject->empty()) { if (not input.includeDeleted) - return Error{Status{RippledError::rpcENTRY_NOT_FOUND}}; + return Error{Status{RippledError::RpcEntryNotFound}}; auto const deletedSeq = sharedPtrBackend_->fetchLedgerObjectSeq(key, lgrInfo.seq, ctx.yield); if (!deletedSeq) - return Error{Status{RippledError::rpcENTRY_NOT_FOUND}}; + return Error{Status{RippledError::RpcEntryNotFound}}; ledgerObject = sharedPtrBackend_->fetchLedgerObject(key, *deletedSeq - 1, ctx.yield); if (!ledgerObject || ledgerObject->empty()) - return Error{Status{RippledError::rpcENTRY_NOT_FOUND}}; + return Error{Status{RippledError::RpcEntryNotFound}}; output.deletedLedgerIndex = deletedSeq; } - ripple::STLedgerEntry const sle{ - ripple::SerialIter{ledgerObject->data(), ledgerObject->size()}, key + xrpl::STLedgerEntry const sle{ + xrpl::SerialIter{ledgerObject->data(), ledgerObject->size()}, key }; - if (input.expectedType != ripple::ltANY && sle.getType() != input.expectedType) - return Error{Status{RippledError::rpcUNEXPECTED_LEDGER_TYPE}}; + if (input.expectedType != xrpl::ltANY && sle.getType() != input.expectedType) + return Error{Status{RippledError::RpcUnexpectedLedgerType}}; - output.index = ripple::strHex(key); + output.index = xrpl::strHex(key); output.ledgerIndex = lgrInfo.seq; - output.ledgerHash = ripple::strHex(lgrInfo.hash); + output.ledgerHash = xrpl::strHex(lgrInfo.hash); if (input.binary) { - output.nodeBinary = ripple::strHex(*ledgerObject); + output.nodeBinary = xrpl::strHex(*ledgerObject); } else { output.node = toJson(sle); } @@ -291,36 +290,36 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons return output; } -std::expected +std::expected LedgerEntryHandler::composeKeyFromDirectory(boost::json::object const& directory) noexcept { // can not specify both dir_root and owner. if (directory.contains(JS(dir_root)) && directory.contains(JS(owner))) { return std::unexpected{ - Status{RippledError::rpcINVALID_PARAMS, "mayNotSpecifyBothDirRootAndOwner"} + Status{RippledError::RpcInvalidParams, "mayNotSpecifyBothDirRootAndOwner"} }; } // at least one should available if (!(directory.contains(JS(dir_root)) || directory.contains(JS(owner)))) - return std::unexpected{Status{RippledError::rpcINVALID_PARAMS, "missingOwnerOrDirRoot"}}; + return std::unexpected{Status{RippledError::RpcInvalidParams, "missingOwnerOrDirRoot"}}; uint64_t const subIndex = directory.contains(JS(sub_index)) ? boost::json::value_to(directory.at(JS(sub_index))) : 0; if (directory.contains(JS(dir_root))) { - ripple::uint256 const uDirRoot{ + xrpl::uint256 const uDirRoot{ boost::json::value_to(directory.at(JS(dir_root))).data() }; - return ripple::keylet::page(uDirRoot, subIndex).key; + return xrpl::keylet::page(uDirRoot, subIndex).key; } - auto const ownerID = util::parseBase58Wrapper( + auto const ownerID = util::parseBase58Wrapper( boost::json::value_to(directory.at(JS(owner))) ); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - return ripple::keylet::page(ripple::keylet::ownerDir(*ownerID), subIndex).key; + return xrpl::keylet::page(xrpl::keylet::ownerDir(*ownerID), subIndex).key; } void @@ -368,88 +367,84 @@ tag_invoke(boost::json::value_to_tag, boost::json::va input.binary = jv.at(JS(binary)).as_bool(); // check all the potential index - static auto const kINDEX_FIELD_TYPE_MAP = - std::unordered_map{ - {JS(index), ripple::ltANY}, - {JS(directory), ripple::ltDIR_NODE}, - {JS(offer), ripple::ltOFFER}, - {JS(check), ripple::ltCHECK}, - {JS(escrow), ripple::ltESCROW}, - {JS(payment_channel), ripple::ltPAYCHAN}, - {JS(deposit_preauth), ripple::ltDEPOSIT_PREAUTH}, - {JS(ticket), ripple::ltTICKET}, - {JS(nft_page), ripple::ltNFTOKEN_PAGE}, - {JS(amm), ripple::ltAMM}, - {JS(xchain_owned_create_account_claim_id), - ripple::ltXCHAIN_OWNED_CREATE_ACCOUNT_CLAIM_ID}, - {JS(xchain_owned_claim_id), ripple::ltXCHAIN_OWNED_CLAIM_ID}, - {JS(oracle), ripple::ltORACLE}, - {JS(credential), ripple::ltCREDENTIAL}, - {JS(mptoken), ripple::ltMPTOKEN}, - {JS(permissioned_domain), ripple::ltPERMISSIONED_DOMAIN}, - {JS(vault), ripple::ltVAULT}, - {JS(loan_broker), ripple::ltLOAN_BROKER}, - {JS(loan), ripple::ltLOAN}, - {JS(delegate), ripple::ltDELEGATE}, - {JS(amendments), ripple::ltAMENDMENTS}, - {JS(fee), ripple::ltFEE_SETTINGS}, - {JS(hashes), ripple::ltLEDGER_HASHES}, - {JS(nft_offer), ripple::ltNFTOKEN_OFFER}, - {JS(nunl), ripple::ltNEGATIVE_UNL}, - {JS(signer_list), ripple::ltSIGNER_LIST}, - }; + static auto const kIndexFieldTypeMap = std::unordered_map{ + {JS(index), xrpl::ltANY}, + {JS(directory), xrpl::ltDIR_NODE}, + {JS(offer), xrpl::ltOFFER}, + {JS(check), xrpl::ltCHECK}, + {JS(escrow), xrpl::ltESCROW}, + {JS(payment_channel), xrpl::ltPAYCHAN}, + {JS(deposit_preauth), xrpl::ltDEPOSIT_PREAUTH}, + {JS(ticket), xrpl::ltTICKET}, + {JS(nft_page), xrpl::ltNFTOKEN_PAGE}, + {JS(amm), xrpl::ltAMM}, + {JS(xchain_owned_create_account_claim_id), xrpl::ltXCHAIN_OWNED_CREATE_ACCOUNT_CLAIM_ID}, + {JS(xchain_owned_claim_id), xrpl::ltXCHAIN_OWNED_CLAIM_ID}, + {JS(oracle), xrpl::ltORACLE}, + {JS(credential), xrpl::ltCREDENTIAL}, + {JS(mptoken), xrpl::ltMPTOKEN}, + {JS(permissioned_domain), xrpl::ltPERMISSIONED_DOMAIN}, + {JS(vault), xrpl::ltVAULT}, + {JS(loan_broker), xrpl::ltLOAN_BROKER}, + {JS(loan), xrpl::ltLOAN}, + {JS(delegate), xrpl::ltDELEGATE}, + {JS(amendments), xrpl::ltAMENDMENTS}, + {JS(fee), xrpl::ltFEE_SETTINGS}, + {JS(hashes), xrpl::ltLEDGER_HASHES}, + {JS(nft_offer), xrpl::ltNFTOKEN_OFFER}, + {JS(nunl), xrpl::ltNEGATIVE_UNL}, + {JS(signer_list), xrpl::ltSIGNER_LIST}, + }; auto const parseBridgeFromJson = [](boost::json::value const& bridgeJson) { auto const lockingDoor = - *util::parseBase58Wrapper(boost::json::value_to( - bridgeJson.at(ripple::sfLockingChainDoor.getJsonName().c_str()) + *util::parseBase58Wrapper(boost::json::value_to( + bridgeJson.at(xrpl::sfLockingChainDoor.getJsonName().cStr()) )); auto const issuingDoor = - *util::parseBase58Wrapper(boost::json::value_to( - bridgeJson.at(ripple::sfIssuingChainDoor.getJsonName().c_str()) + *util::parseBase58Wrapper(boost::json::value_to( + bridgeJson.at(xrpl::sfIssuingChainDoor.getJsonName().cStr()) )); - auto const lockingIssue = parseIssue( - bridgeJson.at(ripple::sfLockingChainIssue.getJsonName().c_str()).as_object() - ); - auto const issuingIssue = parseIssue( - bridgeJson.at(ripple::sfIssuingChainIssue.getJsonName().c_str()).as_object() - ); + auto const lockingIssue = + parseIssue(bridgeJson.at(xrpl::sfLockingChainIssue.getJsonName().cStr()).as_object()); + auto const issuingIssue = + parseIssue(bridgeJson.at(xrpl::sfIssuingChainIssue.getJsonName().cStr()).as_object()); - return ripple::STXChainBridge{lockingDoor, lockingIssue, issuingDoor, issuingIssue}; + return xrpl::STXChainBridge{lockingDoor, lockingIssue, issuingDoor, issuingIssue}; }; auto const parseOracleFromJson = [](boost::json::value const& json) { - auto const account = util::parseBase58Wrapper( + auto const account = util::parseBase58Wrapper( boost::json::value_to(json.at(JS(account))) ); auto const documentId = boost::json::value_to(json.at(JS(oracle_document_id))); - return ripple::keylet::oracle(*account, documentId).key; + return xrpl::keylet::oracle(*account, documentId).key; }; auto const parseCredentialFromJson = [](boost::json::value const& json) { - auto const subject = util::parseBase58Wrapper( + auto const subject = util::parseBase58Wrapper( boost::json::value_to(json.at(JS(subject))) ); - auto const issuer = util::parseBase58Wrapper( + auto const issuer = util::parseBase58Wrapper( boost::json::value_to(json.at(JS(issuer))) ); auto const credType = - ripple::strUnHex(boost::json::value_to(json.at(JS(credential_type)))); + xrpl::strUnHex(boost::json::value_to(json.at(JS(credential_type)))); - return ripple::keylet::credential( - *subject, *issuer, ripple::Slice(credType->data(), credType->size()) + return xrpl::keylet::credential( + *subject, *issuer, xrpl::Slice(credType->data(), credType->size()) ) .key; }; auto const indexFieldType = - std::ranges::find_if(kINDEX_FIELD_TYPE_MAP, [&jsonObject](auto const& pair) { + std::ranges::find_if(kIndexFieldTypeMap, [&jsonObject](auto const& pair) { auto const& [field, _] = pair; return jsonObject.contains(field) && jsonObject.at(field).is_string(); }); - if (indexFieldType != kINDEX_FIELD_TYPE_MAP.end()) { + if (indexFieldType != kIndexFieldTypeMap.end()) { input.index = boost::json::value_to(jv.at(indexFieldType->first)); input.expectedType = indexFieldType->second; } diff --git a/src/rpc/handlers/LedgerEntry.hpp b/src/rpc/handlers/LedgerEntry.hpp index 293926468..8c5b0702e 100644 --- a/src/rpc/handlers/LedgerEntry.hpp +++ b/src/rpc/handlers/LedgerEntry.hpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include @@ -69,7 +70,7 @@ public: std::optional index; // index can be extracted from payment_channel, check, escrow, offer // etc, expectedType is used to save the type of index - ripple::LedgerEntryType expectedType = ripple::ltANY; + xrpl::LedgerEntryType expectedType = xrpl::ltANY; // account id to address account root object std::optional accountRoot; // account id to address did object @@ -89,12 +90,12 @@ public: std::optional vault; std::optional loanBroker; std::optional loan; - std::optional bridge; + std::optional bridge; std::optional bridgeAccount; std::optional chainClaimId; std::optional createAccountClaimId; - std::optional oracleNode; - std::optional credential; + std::optional oracleNode; + std::optional credential; std::optional delegate; bool includeDeleted = false; }; @@ -123,18 +124,18 @@ public: // Validator only works in this handler // The accounts array must have two different elements // Each element must be a valid address - static auto const kRIPPLE_STATE_ACCOUNTS_CHECK = validation::CustomValidator{ + static auto const kRippleStateAccountsCheck = validation::CustomValidator{ [](boost::json::value const& value, std::string_view /* key */) -> MaybeError { if (!value.is_array() || value.as_array().size() != 2 || !value.as_array()[0].is_string() || !value.as_array()[1].is_string() || value.as_array()[0].as_string() == value.as_array()[1].as_string()) { - return Error{Status{RippledError::rpcINVALID_PARAMS, "malformedAccounts"}}; + return Error{Status{RippledError::RpcInvalidParams, "malformedAccounts"}}; } - auto const id1 = util::parseBase58Wrapper( + auto const id1 = util::parseBase58Wrapper( boost::json::value_to(value.as_array()[0]) ); - auto const id2 = util::parseBase58Wrapper( + auto const id2 = util::parseBase58Wrapper( boost::json::value_to(value.as_array()[1]) ); @@ -145,44 +146,44 @@ public: } }; - static auto const kMALFORMED_REQUEST_HEX_STRING_VALIDATOR = meta::WithCustomError{ + static auto const kMalformedRequestHexStringValidator = meta::WithCustomError{ validation::CustomValidators::uint256HexStringValidator, Status(ClioError::RpcMalformedRequest) }; - static auto const kMALFORMED_REQUEST_INT_VALIDATOR = meta::WithCustomError{ + static auto const kMalformedRequestIntValidator = meta::WithCustomError{ validation::Type{}, Status(ClioError::RpcMalformedRequest) }; - static auto const kBRIDGE_JSON_VALIDATOR = meta::WithCustomError{ + static auto const kBridgeJsonValidator = meta::WithCustomError{ meta::IfType{meta::Section{ - {ripple::sfLockingChainDoor.getJsonName().c_str(), + {xrpl::sfLockingChainDoor.getJsonName().cStr(), validation::Required{}, validation::CustomValidators::accountBase58Validator}, - {ripple::sfIssuingChainDoor.getJsonName().c_str(), + {xrpl::sfIssuingChainDoor.getJsonName().cStr(), validation::Required{}, validation::CustomValidators::accountBase58Validator}, - {ripple::sfLockingChainIssue.getJsonName().c_str(), + {xrpl::sfLockingChainIssue.getJsonName().cStr(), validation::Required{}, validation::CustomValidators::currencyIssueValidator}, - {ripple::sfIssuingChainIssue.getJsonName().c_str(), + {xrpl::sfIssuingChainIssue.getJsonName().cStr(), validation::Required{}, validation::CustomValidators::currencyIssueValidator}, }}, Status(ClioError::RpcMalformedRequest) }; - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(binary), validation::Type{}}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, - {JS(index), kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + {JS(index), kMalformedRequestHexStringValidator}, {JS(account_root), validation::CustomValidators::accountBase58Validator}, {JS(did), validation::CustomValidators::accountBase58Validator}, - {JS(check), kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + {JS(check), kMalformedRequestHexStringValidator}, {JS(deposit_preauth), validation::Type{}, - meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + meta::IfType{kMalformedRequestHexStringValidator}, meta::IfType{ meta::Section{ {JS(owner), @@ -198,15 +199,15 @@ public: }}, {JS(directory), validation::Type{}, - meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + meta::IfType{kMalformedRequestHexStringValidator}, meta::IfType{meta::Section{ {JS(owner), validation::CustomValidators::accountBase58Validator}, {JS(dir_root), validation::CustomValidators::uint256HexStringValidator}, - {JS(sub_index), kMALFORMED_REQUEST_INT_VALIDATOR} + {JS(sub_index), kMalformedRequestIntValidator} }}}, {JS(escrow), validation::Type{}, - meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + meta::IfType{kMalformedRequestHexStringValidator}, meta::IfType{ meta::Section{ {JS(owner), @@ -215,44 +216,44 @@ public: validation::CustomValidators::accountBase58Validator, Status(ClioError::RpcMalformedOwner) }}, - {JS(seq), validation::Required{}, kMALFORMED_REQUEST_INT_VALIDATOR}, + {JS(seq), validation::Required{}, kMalformedRequestIntValidator}, }, }}, {JS(offer), validation::Type{}, - meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + meta::IfType{kMalformedRequestHexStringValidator}, meta::IfType{ meta::Section{ {JS(account), validation::Required{}, validation::CustomValidators::accountBase58Validator}, - {JS(seq), validation::Required{}, kMALFORMED_REQUEST_INT_VALIDATOR}, + {JS(seq), validation::Required{}, kMalformedRequestIntValidator}, }, }}, - {JS(payment_channel), kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + {JS(payment_channel), kMalformedRequestHexStringValidator}, {JS(ripple_state), validation::Type{}, meta::Section{ - {JS(accounts), validation::Required{}, kRIPPLE_STATE_ACCOUNTS_CHECK}, + {JS(accounts), validation::Required{}, kRippleStateAccountsCheck}, {JS(currency), validation::Required{}, validation::CustomValidators::currencyValidator}, }}, {JS(ticket), validation::Type{}, - meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + meta::IfType{kMalformedRequestHexStringValidator}, meta::IfType{ meta::Section{ {JS(account), validation::Required{}, validation::CustomValidators::accountBase58Validator}, - {JS(ticket_seq), validation::Required{}, kMALFORMED_REQUEST_INT_VALIDATOR}, + {JS(ticket_seq), validation::Required{}, kMalformedRequestIntValidator}, }, }}, - {JS(nft_page), kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + {JS(nft_page), kMalformedRequestHexStringValidator}, {JS(amm), validation::Type{}, - meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + meta::IfType{kMalformedRequestHexStringValidator}, meta::IfType{ meta::Section{ {JS(asset), @@ -279,7 +280,7 @@ public: meta::WithCustomError{ validation::Type{}, Status(ClioError::RpcMalformedRequest) }, - kBRIDGE_JSON_VALIDATOR}, + kBridgeJsonValidator}, {JS(bridge_account), meta::WithCustomError{ validation::CustomValidators::accountBase58Validator, @@ -290,8 +291,8 @@ public: validation::Type{}, Status(ClioError::RpcMalformedRequest) }, - meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, - kBRIDGE_JSON_VALIDATOR, + meta::IfType{kMalformedRequestHexStringValidator}, + kBridgeJsonValidator, meta::WithCustomError{ meta::IfType{meta::Section{ {JS(xchain_owned_claim_id), @@ -305,8 +306,8 @@ public: validation::Type{}, Status(ClioError::RpcMalformedRequest) }, - meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, - kBRIDGE_JSON_VALIDATOR, + meta::IfType{kMalformedRequestHexStringValidator}, + kBridgeJsonValidator, meta::WithCustomError{ meta::IfType{meta::Section{ {JS(xchain_owned_create_account_claim_id), @@ -321,7 +322,7 @@ public: Status(ClioError::RpcMalformedRequest) }, meta::IfType{meta::WithCustomError{ - kMALFORMED_REQUEST_HEX_STRING_VALIDATOR, Status(ClioError::RpcMalformedAddress) + kMalformedRequestHexStringValidator, Status(ClioError::RpcMalformedAddress) }}, meta::IfType{meta::Section{ {JS(account), @@ -352,7 +353,7 @@ public: Status(ClioError::RpcMalformedRequest) }, meta::IfType{meta::WithCustomError{ - kMALFORMED_REQUEST_HEX_STRING_VALIDATOR, Status(ClioError::RpcMalformedAddress) + kMalformedRequestHexStringValidator, Status(ClioError::RpcMalformedAddress) }}, meta::IfType{meta::Section{ {JS(subject), @@ -391,7 +392,7 @@ public: validation::Type{}, Status(ClioError::RpcMalformedRequest) }, - meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + meta::IfType{kMalformedRequestHexStringValidator}, meta::IfType{ meta::Section{ { @@ -421,7 +422,7 @@ public: validation::Type{}, Status(ClioError::RpcMalformedRequest) }, - meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + meta::IfType{kMalformedRequestHexStringValidator}, meta::IfType{meta::Section{ {JS(seq), meta::WithCustomError{ @@ -446,7 +447,7 @@ public: validation::Type{}, Status(ClioError::RpcMalformedRequest) }, - meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + meta::IfType{kMalformedRequestHexStringValidator}, meta::IfType{meta::Section{ {JS(seq), meta::WithCustomError{ @@ -471,7 +472,7 @@ public: validation::Type{}, Status(ClioError::RpcMalformedRequest) }, - meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + meta::IfType{kMalformedRequestHexStringValidator}, meta::IfType{meta::Section{ {JS(seq), meta::WithCustomError{ @@ -496,7 +497,7 @@ public: validation::Type{}, Status(ClioError::RpcMalformedRequest) }, - meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + meta::IfType{kMalformedRequestHexStringValidator}, meta::IfType{meta::Section{ {JS(loan_seq), meta::WithCustomError{ @@ -521,7 +522,7 @@ public: validation::Type{}, Status(ClioError::RpcMalformedRequest) }, - meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + meta::IfType{kMalformedRequestHexStringValidator}, meta::IfType{meta::Section{ {JS(account), meta::WithCustomError{ @@ -540,17 +541,17 @@ public: Status(ClioError::RpcMalformedAddress) }} }}}, - {JS(amendments), kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, - {JS(fee), kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, - {JS(hashes), kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, - {JS(nft_offer), kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, - {JS(nunl), kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, - {JS(signer_list), kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + {JS(amendments), kMalformedRequestHexStringValidator}, + {JS(fee), kMalformedRequestHexStringValidator}, + {JS(hashes), kMalformedRequestHexStringValidator}, + {JS(nft_offer), kMalformedRequestHexStringValidator}, + {JS(nunl), kMalformedRequestHexStringValidator}, + {JS(signer_list), kMalformedRequestHexStringValidator}, {JS(ledger), check::Deprecated{}}, {"include_deleted", validation::Type{}}, }; - return kRPC_SPEC; + return kRpcSpec; } /** @@ -566,7 +567,7 @@ public: private: // dir_root and owner can not be both empty or filled at the same time // This function will return an error if this is the case - static std::expected + static std::expected composeKeyFromDirectory(boost::json::object const& directory) noexcept; /** diff --git a/src/rpc/handlers/LedgerIndex.cpp b/src/rpc/handlers/LedgerIndex.cpp index 293de1ae4..0315b242b 100644 --- a/src/rpc/handlers/LedgerIndex.cpp +++ b/src/rpc/handlers/LedgerIndex.cpp @@ -32,8 +32,8 @@ LedgerIndexHandler::process(LedgerIndexHandler::Input const& input, Context cons auto const ledger = sharedPtrBackend_->fetchLedgerBySequence(index, ctx.yield); return Output{ .ledgerIndex = index, - .ledgerHash = ripple::strHex(ledger->hash), - .closeTimeIso = ripple::to_string_iso(ledger->closeTime) + .ledgerHash = xrpl::strHex(ledger->hash), + .closeTimeIso = xrpl::toStringIso(ledger->closeTime) }; }; @@ -42,7 +42,7 @@ LedgerIndexHandler::process(LedgerIndexHandler::Input const& input, Context cons return fillOutputByIndex(maxIndex); auto const convertISOTimeStrToTicks = [](std::string const& isoTimeStr) { - auto const systemTime = util::systemTpFromUtcStr(isoTimeStr, kDATE_FORMAT); + auto const systemTime = util::systemTpFromUtcStr(isoTimeStr, kDateFormat); // systemTime must be valid after validation passed return systemTime->time_since_epoch().count(); }; @@ -57,7 +57,7 @@ LedgerIndexHandler::process(LedgerIndexHandler::Input const& input, Context cons // If the given date is earlier than the first valid ledger, return lgrNotFound if (earlierThan(minIndex)) - return Error{Status{RippledError::rpcLGR_NOT_FOUND, "ledgerNotInRange"}}; + return Error{Status{RippledError::RpcLgrNotFound, "ledgerNotInRange"}}; auto const view = std::ranges::iota_view{minIndex, maxIndex + 1}; diff --git a/src/rpc/handlers/LedgerIndex.hpp b/src/rpc/handlers/LedgerIndex.hpp index c79a34c29..682fadc0e 100644 --- a/src/rpc/handlers/LedgerIndex.hpp +++ b/src/rpc/handlers/LedgerIndex.hpp @@ -1,4 +1,5 @@ #pragma once + #include "data/BackendInterface.hpp" #include "rpc/JS.hpp" #include "rpc/common/Specs.hpp" @@ -22,7 +23,7 @@ namespace rpc { */ class LedgerIndexHandler { std::shared_ptr sharedPtrBackend_; - static constexpr auto kDATE_FORMAT = "%Y-%m-%dT%TZ"; + static constexpr auto kDateFormat = "%Y-%m-%dT%TZ"; public: /** @@ -62,12 +63,12 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(date), validation::Type{}, - validation::TimeFormatValidator{kDATE_FORMAT}}, + validation::TimeFormatValidator{kDateFormat}}, }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/rpc/handlers/MPTHolders.cpp b/src/rpc/handlers/MPTHolders.cpp index 2fdbebd73..12037f28a 100644 --- a/src/rpc/handlers/MPTHolders.cpp +++ b/src/rpc/handlers/MPTHolders.cpp @@ -11,20 +11,20 @@ #include #include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include +#include #include #include #include -using namespace ripple; +using namespace xrpl; namespace rpc { @@ -45,18 +45,18 @@ MPTHoldersHandler::process(MPTHoldersHandler::Input const& input, Context const& return Error{expectedLgrInfo.error()}; auto const& lgrInfo = *expectedLgrInfo; - auto const limit = input.limit.value_or(MPTHoldersHandler::kLIMIT_DEFAULT); - auto const mptID = ripple::uint192{input.mptID.c_str()}; + auto const limit = input.limit.value_or(MPTHoldersHandler::kLimitDefault); + auto const mptID = xrpl::uint192{input.mptID.c_str()}; auto const issuanceLedgerObject = sharedPtrBackend_->fetchLedgerObject( - ripple::keylet::mptIssuance(mptID).key, lgrInfo.seq, ctx.yield + xrpl::keylet::mptokenIssuance(mptID).key, lgrInfo.seq, ctx.yield ); if (!issuanceLedgerObject) - return Error{Status{RippledError::rpcOBJECT_NOT_FOUND, "objectNotFound"}}; + return Error{Status{RippledError::RpcObjectNotFound, "objectNotFound"}}; - std::optional cursor; + std::optional cursor; if (input.marker) - cursor = ripple::AccountID{input.marker->c_str()}; + cursor = xrpl::AccountID{input.marker->c_str()}; auto const dbResponse = sharedPtrBackend_->fetchMPTHolders(mptID, limit, cursor, lgrInfo.seq, ctx.yield); @@ -67,20 +67,20 @@ MPTHoldersHandler::process(MPTHoldersHandler::Input const& input, Context const& boost::json::array const mpts; for (auto const& mpt : dbResponse.mptokens) { - ripple::STLedgerEntry const sle{ - ripple::SerialIter{mpt.data(), mpt.size()}, keylet::mptIssuance(mptID).key + xrpl::STLedgerEntry const sle{ + xrpl::SerialIter{mpt.data(), mpt.size()}, keylet::mptokenIssuance(mptID).key }; boost::json::object mptJson; - mptJson[JS(account)] = toBase58(sle[ripple::sfAccount]); + mptJson[JS(account)] = toBase58(sle[xrpl::sfAccount]); mptJson[JS(flags)] = sle.getFlags(); mptJson["mpt_amount"] = toBoostJson( - ripple::STUInt64{ripple::sfMPTAmount, sle[ripple::sfMPTAmount]}.getJson( - JsonOptions::none + xrpl::STUInt64{xrpl::sfMPTAmount, sle[xrpl::sfMPTAmount]}.getJson( + JsonOptions::Values::None ) ); mptJson["mptoken_index"] = - ripple::to_string(ripple::keylet::mptoken(mptID, sle[ripple::sfAccount]).key); + xrpl::to_string(xrpl::keylet::mptoken(mptID, sle[xrpl::sfAccount]).key); output.mpts.push_back(mptJson); } diff --git a/src/rpc/handlers/MPTHolders.hpp b/src/rpc/handlers/MPTHolders.hpp index 22c302f84..daed106ed 100644 --- a/src/rpc/handlers/MPTHolders.hpp +++ b/src/rpc/handlers/MPTHolders.hpp @@ -27,9 +27,9 @@ class MPTHoldersHandler { std::shared_ptr sharedPtrBackend_; public: - static constexpr auto kLIMIT_MIN = 1; - static constexpr auto kLIMIT_MAX = 100; - static constexpr auto kLIMIT_DEFAULT = 50; + static constexpr auto kLimitMin = 1; + static constexpr auto kLimitMax = 100; + static constexpr auto kLimitDefault = 50; /** * @brief A struct to hold the output data of the command @@ -75,7 +75,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(mpt_issuance_id), validation::Required{}, validation::CustomValidators::uint192HexStringValidator}, @@ -84,11 +84,11 @@ public: {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + modifiers::Clamp{kLimitMin, kLimitMax}}, {JS(marker), validation::CustomValidators::uint160HexStringValidator}, }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/rpc/handlers/NFTBuyOffers.cpp b/src/rpc/handlers/NFTBuyOffers.cpp index 404525878..481c26da0 100644 --- a/src/rpc/handlers/NFTBuyOffers.cpp +++ b/src/rpc/handlers/NFTBuyOffers.cpp @@ -5,7 +5,7 @@ #include #include -using namespace ripple; +using namespace xrpl; namespace rpc { @@ -13,7 +13,7 @@ NFTBuyOffersHandler::Result NFTBuyOffersHandler::process(NFTBuyOffersHandler::Input const& input, Context const& ctx) const { auto const tokenID = uint256{input.nftID.c_str()}; - auto const directory = keylet::nft_buys(tokenID); + auto const directory = keylet::nftBuys(tokenID); return iterateOfferDirectory(input, tokenID, directory, ctx.yield); } diff --git a/src/rpc/handlers/NFTHistory.cpp b/src/rpc/handlers/NFTHistory.cpp index 8699f99aa..51a1f1791 100644 --- a/src/rpc/handlers/NFTHistory.cpp +++ b/src/rpc/handlers/NFTHistory.cpp @@ -42,7 +42,7 @@ NFTHistoryHandler::process(NFTHistoryHandler::Input const& input, Context const& if (input.ledgerIndexMin) { // NOLINTBEGIN(bugprone-unchecked-optional-access) if (range->maxSequence < input.ledgerIndexMin || range->minSequence > input.ledgerIndexMin) - return Error{Status{RippledError::rpcLGR_IDX_MALFORMED, "ledgerSeqMinOutOfRange"}}; + return Error{Status{RippledError::RpcLgrIdxMalformed, "ledgerSeqMinOutOfRange"}}; // NOLINTEND(bugprone-unchecked-optional-access) minIndex = *input.ledgerIndexMin; @@ -51,21 +51,19 @@ NFTHistoryHandler::process(NFTHistoryHandler::Input const& input, Context const& if (input.ledgerIndexMax) { // NOLINTBEGIN(bugprone-unchecked-optional-access) if (range->maxSequence < input.ledgerIndexMax || range->minSequence > input.ledgerIndexMax) - return Error{Status{RippledError::rpcLGR_IDX_MALFORMED, "ledgerSeqMaxOutOfRange"}}; + return Error{Status{RippledError::RpcLgrIdxMalformed, "ledgerSeqMaxOutOfRange"}}; // NOLINTEND(bugprone-unchecked-optional-access) maxIndex = *input.ledgerIndexMax; } if (minIndex > maxIndex) - return Error{Status{RippledError::rpcLGR_IDXS_INVALID}}; + return Error{Status{RippledError::RpcLgrIdxsInvalid}}; if (input.ledgerHash || input.ledgerIndex) { // rippled does not have this check if (input.ledgerIndexMax || input.ledgerIndexMin) { - return Error{ - Status{RippledError::rpcINVALID_PARAMS, "containsLedgerSpecifierAndRange"} - }; + return Error{Status{RippledError::RpcInvalidParams, "containsLedgerSpecifierAndRange"}}; } auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( @@ -95,8 +93,8 @@ NFTHistoryHandler::process(NFTHistoryHandler::Input const& input, Context const& } } - auto const limit = input.limit.value_or(kLIMIT_DEFAULT); - auto const tokenID = ripple::uint256{input.nftID.c_str()}; + auto const limit = input.limit.value_or(kLimitDefault); + auto const tokenID = xrpl::uint256{input.nftID.c_str()}; auto const [txnsAndCursor, timeDiff] = util::timed([&]() { return sharedPtrBackend_->fetchNFTTransactions( @@ -143,8 +141,8 @@ NFTHistoryHandler::process(NFTHistoryHandler::Input const& input, Context const& txnPlusMeta.ledgerSequence, ctx.yield ); lgrInfo) { - obj[JS(close_time_iso)] = ripple::to_string_iso(lgrInfo->closeTime); - obj[JS(ledger_hash)] = ripple::strHex(lgrInfo->hash); + obj[JS(close_time_iso)] = xrpl::toStringIso(lgrInfo->closeTime); + obj[JS(ledger_hash)] = xrpl::strHex(lgrInfo->hash); } } } else { @@ -158,7 +156,7 @@ NFTHistoryHandler::process(NFTHistoryHandler::Input const& input, Context const& } response.limit = input.limit; - response.nftID = ripple::to_string(tokenID); + response.nftID = xrpl::to_string(tokenID); response.ledgerIndexMin = minIndex; response.ledgerIndexMax = maxIndex; diff --git a/src/rpc/handlers/NFTHistory.hpp b/src/rpc/handlers/NFTHistory.hpp index 8cc982cc3..a4eba808d 100644 --- a/src/rpc/handlers/NFTHistory.hpp +++ b/src/rpc/handlers/NFTHistory.hpp @@ -35,9 +35,9 @@ class NFTHistoryHandler { std::shared_ptr sharedPtrBackend_; public: - static constexpr auto kLIMIT_MIN = 1; - static constexpr auto kLIMIT_MAX = 100; - static constexpr auto kLIMIT_DEFAULT = 50; + static constexpr auto kLimitMin = 1; + static constexpr auto kLimitMax = 100; + static constexpr auto kLimitDefault = 50; /** * @brief A struct to hold the marker data @@ -101,7 +101,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(nft_id), validation::Required{}, validation::CustomValidators::uint256HexStringValidator}, @@ -114,11 +114,11 @@ public: {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + modifiers::Clamp{kLimitMin, kLimitMax}}, {JS(marker), meta::WithCustomError{ validation::Type{}, - Status{RippledError::rpcINVALID_PARAMS, "invalidMarker"} + Status{RippledError::RpcInvalidParams, "invalidMarker"} }, meta::Section{ {JS(ledger), validation::Required{}, validation::Type{}}, @@ -126,7 +126,7 @@ public: }}, }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/rpc/handlers/NFTInfo.cpp b/src/rpc/handlers/NFTInfo.cpp index 6b09c8887..acaad62b9 100644 --- a/src/rpc/handlers/NFTInfo.cpp +++ b/src/rpc/handlers/NFTInfo.cpp @@ -20,14 +20,14 @@ #include -using namespace ripple; +using namespace xrpl; namespace rpc { NFTInfoHandler::Result NFTInfoHandler::process(NFTInfoHandler::Input const& input, Context const& ctx) const { - auto const tokenID = ripple::uint256{input.nftID.c_str()}; + auto const tokenID = xrpl::uint256{input.nftID.c_str()}; auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "NFTInfo's ledger range must be available"); @@ -46,7 +46,7 @@ NFTInfoHandler::process(NFTInfoHandler::Input const& input, Context const& ctx) auto const maybeNft = sharedPtrBackend_->fetchNFT(tokenID, lgrInfo.seq, ctx.yield); if (not maybeNft.has_value()) - return Error{Status{RippledError::rpcOBJECT_NOT_FOUND, "NFT not found"}}; + return Error{Status{RippledError::RpcObjectNotFound, "NFT not found"}}; // TODO - this formatting is exactly the same and SHOULD REMAIN THE SAME // for each element of the `nfts_by_issuer` API. We should factor this out @@ -64,7 +64,7 @@ NFTInfoHandler::process(NFTInfoHandler::Input const& input, Context const& ctx) output.transferFee = nft::getTransferFee(nft.tokenID); output.issuer = toBase58(nft::getIssuer(nft.tokenID)); output.taxon = nft::toUInt32(nft::getTaxon(nft.tokenID)); - output.serial = nft::getSerial(nft.tokenID); + output.serial = nft::getSequence(nft.tokenID); output.uri = strHex(nft.uri); return output; diff --git a/src/rpc/handlers/NFTInfo.hpp b/src/rpc/handlers/NFTInfo.hpp index 2fb1a8e96..56ddd95bf 100644 --- a/src/rpc/handlers/NFTInfo.hpp +++ b/src/rpc/handlers/NFTInfo.hpp @@ -76,7 +76,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(nft_id), validation::Required{}, validation::CustomValidators::uint256HexStringValidator}, @@ -84,7 +84,7 @@ public: {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/rpc/handlers/NFTOffersCommon.cpp b/src/rpc/handlers/NFTOffersCommon.cpp index 43fff643a..ce4efe203 100644 --- a/src/rpc/handlers/NFTOffersCommon.cpp +++ b/src/rpc/handlers/NFTOffersCommon.cpp @@ -32,16 +32,16 @@ #include #include -using namespace ripple; +using namespace xrpl; using namespace ::rpc; -namespace ripple { +namespace xrpl { // TODO: move to some common serialization impl place inline static void tag_invoke(boost::json::value_from_tag, boost::json::value& jv, SLE const& offer) { - auto amount = ::toBoostJson(offer.getFieldAmount(sfAmount).getJson(JsonOptions::none)); + auto amount = ::toBoostJson(offer.getFieldAmount(sfAmount).getJson(JsonOptions::Values::None)); boost::json::object obj = { {JS(nft_offer_index), to_string(offer.key())}, @@ -59,15 +59,15 @@ tag_invoke(boost::json::value_from_tag, boost::json::value& jv, SLE const& offer jv = std::move(obj); } -} // namespace ripple +} // namespace xrpl namespace rpc { NFTOffersHandlerBase::Result NFTOffersHandlerBase::iterateOfferDirectory( Input input, - ripple::uint256 const& tokenID, - ripple::Keylet const& directory, + xrpl::uint256 const& tokenID, + xrpl::Keylet const& directory, boost::asio::yield_context yield ) const { @@ -89,10 +89,10 @@ NFTOffersHandlerBase::iterateOfferDirectory( // TODO: just check for existence without pulling if (not sharedPtrBackend_->fetchLedgerObject(directory.key, lgrInfo.seq, yield)) - return Error{Status{RippledError::rpcOBJECT_NOT_FOUND, "notFound"}}; + return Error{Status{RippledError::RpcObjectNotFound, "notFound"}}; auto output = Output{.nftID = input.nftID, .offers = {}, .limit = {}, .marker = {}}; - auto offers = std::vector{}; + auto offers = std::vector{}; auto reserve = input.limit; auto cursor = uint256{}; auto startHint = uint64_t{0ul}; @@ -103,7 +103,7 @@ NFTOffersHandlerBase::iterateOfferDirectory( // We have a start point. Use limit - 1 from the result and use the very last one for the // resume. auto const sle = [this, &cursor, &lgrInfo, yield]() -> std::shared_ptr { - auto const key = keylet::nftoffer(cursor).key; + auto const key = keylet::nftokenOffer(cursor).key; if (auto const blob = sharedPtrBackend_->fetchLedgerObject(key, lgrInfo.seq, yield); blob) @@ -112,12 +112,12 @@ NFTOffersHandlerBase::iterateOfferDirectory( return nullptr; }(); - if (!sle || sle->getFieldU16(ripple::sfLedgerEntryType) != ripple::ltNFTOKEN_OFFER || - tokenID != sle->getFieldH256(ripple::sfNFTokenID)) { - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + if (!sle || sle->getFieldU16(xrpl::sfLedgerEntryType) != xrpl::ltNFTOKEN_OFFER || + tokenID != sle->getFieldH256(xrpl::sfNFTokenID)) { + return Error{Status{RippledError::RpcInvalidParams}}; } - startHint = sle->getFieldU64(ripple::sfNFTokenOfferNode); + startHint = sle->getFieldU64(xrpl::sfNFTokenOfferNode); output.offers.push_back(*sle); offers.reserve(reserve); } else { @@ -133,8 +133,8 @@ NFTOffersHandlerBase::iterateOfferDirectory( lgrInfo.seq, reserve, yield, - [&offers](ripple::SLE&& offer) { - if (offer.getType() == ripple::ltNFTOKEN_OFFER) { + [&offers](xrpl::SLE&& offer) { + if (offer.getType() == xrpl::ltNFTOKEN_OFFER) { offers.push_back(std::move(offer)); return true; } diff --git a/src/rpc/handlers/NFTOffersCommon.hpp b/src/rpc/handlers/NFTOffersCommon.hpp index 39ca80f16..d933febbc 100644 --- a/src/rpc/handlers/NFTOffersCommon.hpp +++ b/src/rpc/handlers/NFTOffersCommon.hpp @@ -30,16 +30,16 @@ class NFTOffersHandlerBase { std::shared_ptr sharedPtrBackend_; public: - static constexpr auto kLIMIT_MIN = 50; - static constexpr auto kLIMIT_MAX = 500; - static constexpr auto kLIMIT_DEFAULT = 250; + static constexpr auto kLimitMin = 50; + static constexpr auto kLimitMax = 500; + static constexpr auto kLimitDefault = 250; /** * @brief A struct to hold the output data of the command */ struct Output { std::string nftID; - std::vector offers; + std::vector offers; // validated should be sent via framework bool validated = true; @@ -54,7 +54,7 @@ public: std::string nftID; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = kLIMIT_DEFAULT; + uint32_t limit = kLimitDefault; std::optional marker; }; @@ -79,7 +79,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(nft_id), validation::Required{}, validation::CustomValidators::uint256HexStringValidator}, @@ -88,11 +88,11 @@ public: {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + modifiers::Clamp{kLimitMin, kLimitMax}}, {JS(marker), validation::CustomValidators::uint256HexStringValidator}, }; - return kRPC_SPEC; + return kRpcSpec; } protected: @@ -108,8 +108,8 @@ protected: [[nodiscard]] Result iterateOfferDirectory( Input input, - ripple::uint256 const& tokenID, - ripple::Keylet const& directory, + xrpl::uint256 const& tokenID, + xrpl::Keylet const& directory, boost::asio::yield_context yield ) const; diff --git a/src/rpc/handlers/NFTSellOffers.cpp b/src/rpc/handlers/NFTSellOffers.cpp index df2762600..0d46330e8 100644 --- a/src/rpc/handlers/NFTSellOffers.cpp +++ b/src/rpc/handlers/NFTSellOffers.cpp @@ -5,7 +5,7 @@ #include #include -using namespace ripple; +using namespace xrpl; namespace rpc { @@ -13,7 +13,7 @@ NFTSellOffersHandler::Result NFTSellOffersHandler::process(NFTSellOffersHandler::Input const& input, Context const& ctx) const { auto const tokenID = uint256{input.nftID.c_str()}; - auto const directory = keylet::nft_sells(tokenID); + auto const directory = keylet::nftSells(tokenID); return iterateOfferDirectory(input, tokenID, directory, ctx.yield); } diff --git a/src/rpc/handlers/NFTsByIssuer.cpp b/src/rpc/handlers/NFTsByIssuer.cpp index fcd624c77..471b50d9a 100644 --- a/src/rpc/handlers/NFTsByIssuer.cpp +++ b/src/rpc/handlers/NFTsByIssuer.cpp @@ -23,7 +23,7 @@ #include #include -using namespace ripple; +using namespace xrpl; namespace rpc { @@ -45,18 +45,18 @@ NFTsByIssuerHandler::process(NFTsByIssuerHandler::Input const& input, Context co auto const& lgrInfo = *expectedLgrInfo; - auto const limit = input.limit.value_or(NFTsByIssuerHandler::kLIMIT_DEFAULT); + auto const limit = input.limit.value_or(NFTsByIssuerHandler::kLimitDefault); auto const issuer = accountFromStringStrict(input.issuer); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::keylet::account(*issuer).key, + xrpl::keylet::account(*issuer).key, lgrInfo.seq, ctx.yield ); if (!accountLedgerObject) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; std::optional cursor; if (input.marker) @@ -92,7 +92,7 @@ NFTsByIssuerHandler::process(NFTsByIssuerHandler::Input const& input, Context co nftJson["transfer_fee"] = nft::getTransferFee(nft.tokenID); nftJson[JS(issuer)] = toBase58(nft::getIssuer(nft.tokenID)); nftJson[JS(nft_taxon)] = nft::toUInt32(nft::getTaxon(nft.tokenID)); - nftJson[JS(nft_serial)] = nft::getSerial(nft.tokenID); + nftJson[JS(nft_serial)] = nft::getSequence(nft.tokenID); output.nfts.push_back(nftJson); } diff --git a/src/rpc/handlers/NFTsByIssuer.hpp b/src/rpc/handlers/NFTsByIssuer.hpp index 6765fd180..6e79a6a3a 100644 --- a/src/rpc/handlers/NFTsByIssuer.hpp +++ b/src/rpc/handlers/NFTsByIssuer.hpp @@ -26,9 +26,9 @@ class NFTsByIssuerHandler { std::shared_ptr sharedPtrBackend_; public: - static constexpr auto kLIMIT_MIN = 1; - static constexpr auto kLIMIT_MAX = 100; - static constexpr auto kLIMIT_DEFAULT = 50; + static constexpr auto kLimitMin = 1; + static constexpr auto kLimitMax = 100; + static constexpr auto kLimitDefault = 50; /** * @brief A struct to hold the output data of the command @@ -76,7 +76,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(issuer), validation::Required{}, validation::CustomValidators::accountValidator}, {JS(nft_taxon), validation::Type{}}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, @@ -84,11 +84,11 @@ public: {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + modifiers::Clamp{kLimitMin, kLimitMax}}, {JS(marker), validation::CustomValidators::uint256HexStringValidator}, }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/rpc/handlers/NoRippleCheck.cpp b/src/rpc/handlers/NoRippleCheck.cpp index acf6c9e55..10d3dd091 100644 --- a/src/rpc/handlers/NoRippleCheck.cpp +++ b/src/rpc/handlers/NoRippleCheck.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -56,16 +57,16 @@ NoRippleCheckHandler::process(NoRippleCheckHandler::Input const& input, Context auto const& lgrInfo = *expectedLgrInfo; auto const accountID = accountFromStringStrict(input.account); auto const keylet = - ripple::keylet::account(*accountID).key; // NOLINT(bugprone-unchecked-optional-access) + xrpl::keylet::account(*accountID).key; // NOLINT(bugprone-unchecked-optional-access) auto const accountObj = sharedPtrBackend_->fetchLedgerObject(keylet, lgrInfo.seq, ctx.yield); if (!accountObj) - return Error{Status{RippledError::rpcACT_NOT_FOUND}}; + return Error{Status{RippledError::RpcActNotFound}}; - auto it = ripple::SerialIter{accountObj->data(), accountObj->size()}; - auto sle = ripple::SLE{it, keylet}; - auto accountSeq = sle.getFieldU32(ripple::sfSequence); - bool const bDefaultRipple = (sle.getFieldU32(ripple::sfFlags) & ripple::lsfDefaultRipple) != 0u; + auto it = xrpl::SerialIter{accountObj->data(), accountObj->size()}; + auto sle = xrpl::SLE{it, keylet}; + auto accountSeq = sle.getFieldU32(xrpl::sfSequence); + bool const bDefaultRipple = (sle.getFieldU32(xrpl::sfFlags) & xrpl::lsfDefaultRipple) != 0u; auto const fees = input.transactions ? sharedPtrBackend_->fetchFees(lgrInfo.seq, ctx.yield) : std::nullopt; @@ -74,10 +75,10 @@ NoRippleCheckHandler::process(NoRippleCheckHandler::Input const& input, Context if (input.transactions) output.transactions.emplace(boost::json::array()); - auto const getBaseTx = [&](ripple::AccountID const& accountID, std::uint32_t accountSeq) { + auto const getBaseTx = [&](xrpl::AccountID const& accountID, std::uint32_t accountSeq) { boost::json::object tx; tx[JS(Sequence)] = accountSeq; - tx[JS(Account)] = ripple::toBase58(accountID); + tx[JS(Account)] = xrpl::toBase58(accountID); tx[JS(Fee)] = toBoostJson(fees->base.jsonClipped()); return tx; @@ -96,7 +97,7 @@ NoRippleCheckHandler::process(NoRippleCheckHandler::Input const& input, Context auto tx = getBaseTx(*accountID, accountSeq++); // NOLINT(bugprone-unchecked-optional-access) tx[JS(TransactionType)] = "AccountSet"; - tx[JS(SetFlag)] = ripple::asfDefaultRipple; + tx[JS(SetFlag)] = xrpl::asfDefaultRipple; output.transactions->push_back(tx); } } @@ -110,15 +111,15 @@ NoRippleCheckHandler::process(NoRippleCheckHandler::Input const& input, Context std::numeric_limits::max(), {}, ctx.yield, - [&](ripple::SLE const ownedItem) { + [&](xrpl::SLE const ownedItem) { // don't push to result if limit is reached - if (limit != 0 && ownedItem.getType() == ripple::ltRIPPLE_STATE) { + if (limit != 0 && ownedItem.getType() == xrpl::ltRIPPLE_STATE) { bool const bLow = - accountID == ownedItem.getFieldAmount(ripple::sfLowLimit).getIssuer(); + accountID == ownedItem.getFieldAmount(xrpl::sfLowLimit).getIssuer(); bool const bNoRipple = - (ownedItem.getFieldU32(ripple::sfFlags) & - (bLow ? ripple::lsfLowNoRipple : ripple::lsfHighNoRipple)) != 0u; + (ownedItem.getFieldU32(xrpl::sfFlags) & + (bLow ? xrpl::lsfLowNoRipple : xrpl::lsfHighNoRipple)) != 0u; std::string problem; bool needFix = false; @@ -132,31 +133,33 @@ NoRippleCheckHandler::process(NoRippleCheckHandler::Input const& input, Context if (needFix) { --limit; - ripple::AccountID const peer = - ownedItem.getFieldAmount(bLow ? ripple::sfHighLimit : ripple::sfLowLimit) + xrpl::AccountID const peer = + ownedItem.getFieldAmount(bLow ? xrpl::sfHighLimit : xrpl::sfLowLimit) .getIssuer(); - ripple::STAmount const peerLimit = - ownedItem.getFieldAmount(bLow ? ripple::sfHighLimit : ripple::sfLowLimit); + xrpl::STAmount const peerLimit = + ownedItem.getFieldAmount(bLow ? xrpl::sfHighLimit : xrpl::sfLowLimit); problem += fmt::format( "{} line to {}", - to_string(peerLimit.getCurrency()), + to_string(peerLimit.get().currency), to_string(peerLimit.getIssuer()) ); output.problems.emplace_back(problem); if (input.transactions) { - ripple::STAmount limitAmount(ownedItem.getFieldAmount( - bLow ? ripple::sfLowLimit : ripple::sfHighLimit - )); - limitAmount.setIssuer(peer); + xrpl::STAmount limitAmount( + ownedItem.getFieldAmount(bLow ? xrpl::sfLowLimit : xrpl::sfHighLimit) + ); + limitAmount.setIssue( + xrpl::Issue{limitAmount.get().currency, peer} + ); auto tx = getBaseTx(*accountID, accountSeq++); tx[JS(TransactionType)] = "TrustSet"; tx[JS(LimitAmount)] = - toBoostJson(limitAmount.getJson(ripple::JsonOptions::none)); - tx[JS(Flags)] = bNoRipple ? ripple::tfClearNoRipple : ripple::tfSetNoRipple; + toBoostJson(limitAmount.getJson(xrpl::JsonOptions::Values::None)); + tx[JS(Flags)] = bNoRipple ? xrpl::tfClearNoRipple : xrpl::tfSetNoRipple; output.transactions->push_back(tx); } @@ -168,7 +171,7 @@ NoRippleCheckHandler::process(NoRippleCheckHandler::Input const& input, Context ); output.ledgerIndex = lgrInfo.seq; - output.ledgerHash = ripple::strHex(lgrInfo.hash); + output.ledgerHash = xrpl::strHex(lgrInfo.hash); return output; } diff --git a/src/rpc/handlers/NoRippleCheck.hpp b/src/rpc/handlers/NoRippleCheck.hpp index a8db6a64e..53e5bed92 100644 --- a/src/rpc/handlers/NoRippleCheck.hpp +++ b/src/rpc/handlers/NoRippleCheck.hpp @@ -36,9 +36,9 @@ class NoRippleCheckHandler { std::shared_ptr sharedPtrBackend_; public: - static constexpr auto kLIMIT_MIN = 1; - static constexpr auto kLIMIT_MAX = 500; - static constexpr auto kLIMIT_DEFAULT = 300; + static constexpr auto kLimitMin = 1; + static constexpr auto kLimitMax = 500; + static constexpr auto kLimitDefault = 300; /** * @brief A struct to hold the output data of the command @@ -60,7 +60,7 @@ public: bool roleGateway = false; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = kLIMIT_DEFAULT; + uint32_t limit = kLimitDefault; JsonBool transactions{false}; }; @@ -85,30 +85,30 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC_V1 = RpcSpec{ + static auto const kRpcSpecV1 = RpcSpec{ {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, {JS(role), validation::Required{}, meta::WithCustomError{ validation::OneOf{"gateway", "user"}, - Status{RippledError::rpcINVALID_PARAMS, "role field is invalid"} + Status{RippledError::RpcInvalidParams, "role field is invalid"} }}, {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(limit), validation::Type(), validation::Min(1u), - modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}} + modifiers::Clamp{kLimitMin, kLimitMax}} }; - static auto const kRPC_SPEC = RpcSpec{ - kRPC_SPEC_V1, + static auto const kRpcSpec = RpcSpec{ + kRpcSpecV1, { {JS(transactions), validation::Type()}, } }; - return apiVersion == 1 ? kRPC_SPEC_V1 : kRPC_SPEC; + return apiVersion == 1 ? kRpcSpecV1 : kRpcSpec; } /** diff --git a/src/rpc/handlers/Random.cpp b/src/rpc/handlers/Random.cpp index b35400208..f1046ee5a 100644 --- a/src/rpc/handlers/Random.cpp +++ b/src/rpc/handlers/Random.cpp @@ -16,10 +16,10 @@ namespace rpc { RandomHandler::Result RandomHandler::process([[maybe_unused]] Context const& ctx) { - ripple::uint256 rand; - beast::rngfill(rand.begin(), ripple::uint256::size(), ripple::crypto_prng()); + xrpl::uint256 rand; + beast::rngfill(rand.begin(), xrpl::uint256::size(), xrpl::cryptoPrng()); - return Output{ripple::strHex(rand)}; + return Output{xrpl::strHex(rand)}; } void diff --git a/src/rpc/handlers/ServerInfo.hpp b/src/rpc/handlers/ServerInfo.hpp index 95ce881fc..00303cc51 100644 --- a/src/rpc/handlers/ServerInfo.hpp +++ b/src/rpc/handlers/ServerInfo.hpp @@ -45,7 +45,7 @@ namespace rpc { */ template class BaseServerInfoHandler { - static constexpr auto kBACKEND_COUNTERS_KEY = "backend_counters"; + static constexpr auto kBackendCountersKey = "backend_counters"; std::shared_ptr backend_; std::shared_ptr subscriptions_; @@ -77,8 +77,8 @@ public: struct ValidatedLedgerSection { uint32_t age = 0; std::string hash; - ripple::LedgerIndex seq = {}; - std::optional fees = std::nullopt; + xrpl::LedgerIndex seq = {}; + std::optional fees = std::nullopt; }; /** @@ -88,7 +88,7 @@ public: std::size_t size = 0; bool isEnabled = false; bool isFull = false; - ripple::LedgerIndex latestLedgerSeq = {}; + xrpl::LedgerIndex latestLedgerSeq = {}; float objectHitRate = 1.0; float successorHitRate = 1.0; }; @@ -103,7 +103,7 @@ public: std::chrono::time_point time = std::chrono::system_clock::now(); std::chrono::seconds uptime = {}; std::string clioVersion = util::build::getClioVersionString(); - std::string xrplVersion = ripple::BuildInfo::getVersionString(); + std::string xrplVersion = xrpl::BuildInfo::getVersionString(); std::optional rippledInfo = std::nullopt; ValidatedLedgerSection validatedLedger = {}; CacheSection cache = {}; @@ -156,8 +156,8 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static RpcSpec const kRPC_SPEC = {}; - return kRPC_SPEC; + static RpcSpec const kRpcSpec = {}; + return kRpcSpec; } /** @@ -182,18 +182,18 @@ public: ctx.yield ); if (not lgrInfo.has_value()) - return Error{Status{RippledError::rpcINTERNAL}}; + return Error{Status{RippledError::RpcInternal}}; auto const fees = backend_->fetchFees(lgrInfo->seq, ctx.yield); if (not fees.has_value()) - return Error{Status{RippledError::rpcINTERNAL}}; + return Error{Status{RippledError::RpcInternal}}; auto output = Output{}; auto const sinceEpoch = duration_cast(system_clock::now().time_since_epoch()).count(); auto const age = static_cast(sinceEpoch) - static_cast(lgrInfo->closeTime.time_since_epoch().count()) - - static_cast(kRIPPLE_EPOCH_START); + static_cast(kRippleEpochStart); // NOLINTBEGIN(bugprone-unchecked-optional-access) output.info.completeLedgers = fmt::format("{}-{}", range->minSequence, range->maxSequence); @@ -222,7 +222,7 @@ public: } output.info.validatedLedger.age = age < 0 ? 0 : age; - output.info.validatedLedger.hash = ripple::strHex(lgrInfo->hash); + output.info.validatedLedger.hash = xrpl::strHex(lgrInfo->hash); output.info.validatedLedger.seq = lgrInfo->seq; output.info.validatedLedger.fees = fees; output.info.cache.size = backend_->cache().size(); @@ -254,7 +254,7 @@ private: tag_invoke(boost::json::value_from_tag, boost::json::value& jv, InfoSection const& info) { using boost::json::value_from; - using ripple::to_string; + using xrpl::to_string; jv = { {JS(complete_ledgers), info.completeLedgers}, @@ -292,7 +292,7 @@ private: jv.as_object()[JS(counters)].as_object()["subscriptions"] = info.adminSection->subscriptions; if (info.adminSection->backendCounters.has_value()) { - jv.as_object()[kBACKEND_COUNTERS_KEY] = *info.adminSection->backendCounters; + jv.as_object()[kBackendCountersKey] = *info.adminSection->backendCounters; } } } @@ -334,9 +334,9 @@ private: { auto input = BaseServerInfoHandler::Input{}; auto const jsonObject = jv.as_object(); - if (jsonObject.contains(kBACKEND_COUNTERS_KEY) && - jsonObject.at(kBACKEND_COUNTERS_KEY).is_bool()) - input.backendCounters = jv.at(kBACKEND_COUNTERS_KEY).as_bool(); + if (jsonObject.contains(kBackendCountersKey) && + jsonObject.at(kBackendCountersKey).is_bool()) + input.backendCounters = jv.at(kBackendCountersKey).as_bool(); return input; } }; diff --git a/src/rpc/handlers/Subscribe.cpp b/src/rpc/handlers/Subscribe.cpp index 8e038e241..078215457 100644 --- a/src/rpc/handlers/Subscribe.cpp +++ b/src/rpc/handlers/Subscribe.cpp @@ -49,33 +49,31 @@ SubscribeHandler::SubscribeHandler( RpcSpecConstRef SubscribeHandler::spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kBOOKS_VALIDATOR = validation::CustomValidator{ + static auto const kBooksValidator = validation::CustomValidator{ [](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_array()) { - return Error{ - Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotArray"} - }; + return Error{Status{RippledError::RpcInvalidParams, std::string(key) + "NotArray"}}; } for (auto const& book : value.as_array()) { if (!book.is_object()) { return Error{ - Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "ItemNotObject"} + Status{RippledError::RpcInvalidParams, std::string(key) + "ItemNotObject"} }; } if (book.as_object().contains("both") && !book.as_object().at("both").is_bool()) - return Error{Status{RippledError::rpcINVALID_PARAMS, "bothNotBool"}}; + return Error{Status{RippledError::RpcInvalidParams, "bothNotBool"}}; if (book.as_object().contains("snapshot") && !book.as_object().at("snapshot").is_bool()) - return Error{Status{RippledError::rpcINVALID_PARAMS, "snapshotNotBool"}}; + return Error{Status{RippledError::RpcInvalidParams, "snapshotNotBool"}}; if (book.as_object().contains("taker")) { if (auto err = meta::WithCustomError( validation::CustomValidators::accountValidator, - Status{RippledError::rpcBAD_ISSUER, "Issuer account malformed."} + Status{RippledError::RpcBadIssuer, "Issuer account malformed."} ) .verify(book.as_object(), "taker"); !err) @@ -91,17 +89,17 @@ SubscribeHandler::spec([[maybe_unused]] uint32_t apiVersion) } }; - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(streams), validation::CustomValidators::subscribeStreamValidator}, {JS(accounts), validation::CustomValidators::subscribeAccountsValidator}, {JS(accounts_proposed), validation::CustomValidators::subscribeAccountsValidator}, - {JS(books), kBOOKS_VALIDATOR}, + {JS(books), kBooksValidator}, {"user", check::Deprecated{}}, {JS(password), check::Deprecated{}}, {JS(rt_accounts), check::Deprecated{}} }; - return kRPC_SPEC; + return kRpcSpec; } SubscribeHandler::Result @@ -192,7 +190,7 @@ SubscribeHandler::subscribeToBooks( Output& output ) const { - static constexpr auto kFETCH_LIMIT = 200; + static constexpr auto kFetchLimit = 200; std::optional rng; @@ -206,14 +204,14 @@ SubscribeHandler::subscribeToBooks( auto const getOrderBook = [&](auto const& book, auto& snapshots) { auto const bookBase = getBookBase(book); auto const [offers, _] = sharedPtrBackend_->fetchBookOffers( - bookBase, rng->maxSequence, kFETCH_LIMIT, yield + bookBase, rng->maxSequence, kFetchLimit, yield ); // the taker is not really used, same issue with // https://github.com/XRPLF/xrpl-dev-portal/issues/1818 auto const takerID = internalBook.taker ? accountFromStringStrict(*(internalBook.taker)) - : beast::zero; + : beast::kZero; auto const orderBook = postProcessOrderBook( offers, @@ -233,7 +231,7 @@ SubscribeHandler::subscribeToBooks( if (!output.asks) output.asks = boost::json::array(); getOrderBook(internalBook.book, *(output.bids)); - getOrderBook(ripple::reversed(internalBook.book), *(output.asks)); + getOrderBook(xrpl::reversed(internalBook.book), *(output.asks)); } else { if (!output.offers) output.offers = boost::json::array(); @@ -244,7 +242,7 @@ SubscribeHandler::subscribeToBooks( subscriptions_->subBook(internalBook.book, session); if (internalBook.both) - subscriptions_->subBook(ripple::reversed(internalBook.book), session); + subscriptions_->subBook(xrpl::reversed(internalBook.book), session); } } diff --git a/src/rpc/handlers/Subscribe.hpp b/src/rpc/handlers/Subscribe.hpp index 5e8d43642..dc002e121 100644 --- a/src/rpc/handlers/Subscribe.hpp +++ b/src/rpc/handlers/Subscribe.hpp @@ -60,7 +60,7 @@ public: * @brief A struct to hold the data for one order book */ struct OrderBook { - ripple::Book book; + xrpl::Book book; std::optional taker; bool snapshot = false; bool both = false; diff --git a/src/rpc/handlers/TransactionEntry.cpp b/src/rpc/handlers/TransactionEntry.cpp index d4b4c2c52..9d2146756 100644 --- a/src/rpc/handlers/TransactionEntry.cpp +++ b/src/rpc/handlers/TransactionEntry.cpp @@ -45,7 +45,7 @@ TransactionEntryHandler::process( output.ledgerHeader = *expectedLgrInfo; auto const dbRet = - sharedPtrBackend_->fetchTransaction(ripple::uint256{input.txHash.c_str()}, ctx.yield); + sharedPtrBackend_->fetchTransaction(xrpl::uint256{input.txHash.c_str()}, ctx.yield); // Note: transaction_entry is meant to only search a specified ledger for // the specified transaction. tx searches the entire range of history. For // rippled, having two separate commands made sense, as tx would use SQLite @@ -57,7 +57,7 @@ TransactionEntryHandler::process( // is in a different ledger than the one specified. if (!dbRet || dbRet->ledgerSequence != output.ledgerHeader->seq) { return Error{ - Status{RippledError::rpcTXN_NOT_FOUND, "transactionNotFound", "Transaction not found."} + Status{RippledError::RpcTxnNotFound, "transactionNotFound", "Transaction not found."} }; } @@ -84,13 +84,13 @@ tag_invoke( {metaKey, output.metadata}, {JS(tx_json), output.tx}, {JS(ledger_index), output.ledgerHeader->seq}, - {JS(ledger_hash), ripple::strHex(output.ledgerHeader->hash)}, + {JS(ledger_hash), xrpl::strHex(output.ledgerHeader->hash)}, }; // NOLINTEND(bugprone-unchecked-optional-access) if (output.apiVersion > 1u) { // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - jv.as_object()[JS(close_time_iso)] = ripple::to_string_iso(output.ledgerHeader->closeTime); + jv.as_object()[JS(close_time_iso)] = xrpl::toStringIso(output.ledgerHeader->closeTime); if (output.tx.contains(JS(hash))) { jv.as_object()[JS(hash)] = output.tx.at(JS(hash)); jv.as_object()[JS(tx_json)].as_object().erase(JS(hash)); diff --git a/src/rpc/handlers/TransactionEntry.hpp b/src/rpc/handlers/TransactionEntry.hpp index 919893b4e..12d94e890 100644 --- a/src/rpc/handlers/TransactionEntry.hpp +++ b/src/rpc/handlers/TransactionEntry.hpp @@ -35,7 +35,7 @@ public: * @brief A struct to hold the output data of the command */ struct Output { - std::optional ledgerHeader; + std::optional ledgerHeader; // TODO: use a better type for this boost::json::object metadata; boost::json::object tx; @@ -74,7 +74,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(tx_hash), meta::WithCustomError{ validation::Required{}, Status(ClioError::RpcFieldNotFoundTransaction) @@ -84,7 +84,7 @@ public: {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/rpc/handlers/Tx.hpp b/src/rpc/handlers/Tx.hpp index 7ae874aca..b4bdf2cf2 100644 --- a/src/rpc/handlers/Tx.hpp +++ b/src/rpc/handlers/Tx.hpp @@ -61,7 +61,7 @@ public: std::nullopt; // NOLINT(readability-redundant-member-init) std::optional ctid = std::nullopt; // NOLINT(readability-redundant-member-init) ctid when binary=true - std::optional ledgerHeader = + std::optional ledgerHeader = std::nullopt; // NOLINT(readability-redundant-member-init) ledger hash when apiVersion // >= 2 uint32_t apiVersion = 0u; @@ -104,17 +104,17 @@ public: static RpcSpecConstRef spec(uint32_t apiVersion) { - static RpcSpec const kRPC_SPEC_FOR_V1 = { + static RpcSpec const kRpcSpecForV1 = { {JS(transaction), validation::CustomValidators::uint256HexStringValidator}, {JS(min_ledger), validation::Type{}}, {JS(max_ledger), validation::Type{}}, {JS(ctid), validation::Type{}}, }; - static auto const kRPC_SPEC = - RpcSpec{kRPC_SPEC_FOR_V1, {{JS(binary), validation::Type{}}}}; + static auto const kRpcSpec = + RpcSpec{kRpcSpecForV1, {{JS(binary), validation::Type{}}}}; - return apiVersion == 1 ? kRPC_SPEC_FOR_V1 : kRPC_SPEC; + return apiVersion == 1 ? kRpcSpecForV1 : kRpcSpec; } /** @@ -128,20 +128,20 @@ public: process(Input const& input, Context const& ctx) const { if (input.ctid && input.transaction) // ambiguous identifier - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; if (!input.ctid && !input.transaction) // at least one identifier must be supplied - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; - static constexpr auto kMAX_LEDGER_RANGE = 1000u; + static constexpr auto kMaxLedgerRange = 1000u; auto const rangeSupplied = input.minLedger && input.maxLedger; if (rangeSupplied) { if (*input.minLedger > *input.maxLedger) - return Error{Status{RippledError::rpcINVALID_LGR_RANGE}}; + return Error{Status{RippledError::RpcInvalidLgrRange}}; - if (*input.maxLedger - *input.minLedger > kMAX_LEDGER_RANGE) - return Error{Status{RippledError::rpcEXCESSIVE_LGR_RANGE}}; + if (*input.maxLedger - *input.minLedger > kMaxLedgerRange) + return Error{Status{RippledError::RpcExcessiveLgrRange}}; } std::optional currentNetId = std::nullopt; @@ -153,13 +153,13 @@ public: if (input.ctid) { auto const ctid = rpc::decodeCTID(*input.ctid); if (!ctid) - return Error{Status{RippledError::rpcINVALID_PARAMS}}; + return Error{Status{RippledError::RpcInvalidParams}}; auto const [lgrSeq, txnIdx, netId] = *ctid; // when current network id is available, let us check the network id from parameter if (currentNetId && netId != *currentNetId) { return Error{Status{ - RippledError::rpcWRONG_NETWORK, + RippledError::RpcWrongNetwork, fmt::format( "Wrong network. You should submit this request to a node running on " "NetworkID: {}", @@ -171,7 +171,7 @@ public: dbResponse = fetchTxViaCtid(lgrSeq, txnIdx, ctx.yield); } else { dbResponse = sharedPtrBackend_->fetchTransaction( - ripple::uint256{input.transaction->c_str()}, ctx.yield + xrpl::uint256{input.transaction->c_str()}, ctx.yield ); } @@ -191,10 +191,10 @@ public: boost::json::object extra; extra["searched_all"] = searchedAll; - return Error{Status{RippledError::rpcTXN_NOT_FOUND, std::move(extra)}}; + return Error{Status{RippledError::RpcTxnNotFound, std::move(extra)}}; } - return Error{Status{RippledError::rpcTXN_NOT_FOUND}}; + return Error{Status{RippledError::RpcTxnNotFound}}; } auto const [txn, meta] = @@ -204,8 +204,8 @@ public: output.tx = txn; output.meta = meta; } else { - output.txStr = ripple::strHex(dbResponse->transaction); - output.metaStr = ripple::strHex(dbResponse->metadata); + output.txStr = xrpl::strHex(dbResponse->transaction); + output.metaStr = xrpl::strHex(dbResponse->metadata); // input.transaction might be not available, get hash via tx object if (txn.contains(JS(hash))) @@ -299,8 +299,8 @@ private: obj[JS(ledger_index)] = output.ledgerIndex; if (output.ledgerHeader) { - obj[JS(ledger_hash)] = ripple::strHex(output.ledgerHeader->hash); - obj[JS(close_time_iso)] = ripple::to_string_iso(output.ledgerHeader->closeTime); + obj[JS(ledger_hash)] = xrpl::strHex(output.ledgerHeader->hash); + obj[JS(close_time_iso)] = xrpl::toStringIso(output.ledgerHeader->closeTime); } return obj; }; diff --git a/src/rpc/handlers/Unsubscribe.cpp b/src/rpc/handlers/Unsubscribe.cpp index 41a5b8ea0..d0923cd4e 100644 --- a/src/rpc/handlers/Unsubscribe.cpp +++ b/src/rpc/handlers/Unsubscribe.cpp @@ -35,23 +35,21 @@ UnsubscribeHandler::UnsubscribeHandler( RpcSpecConstRef UnsubscribeHandler::spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kBOOKS_VALIDATOR = validation::CustomValidator{ + static auto const kBooksValidator = validation::CustomValidator{ [](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_array()) { - return Error{ - Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotArray"} - }; + return Error{Status{RippledError::RpcInvalidParams, std::string(key) + "NotArray"}}; } for (auto const& book : value.as_array()) { if (!book.is_object()) { return Error{ - Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "ItemNotObject"} + Status{RippledError::RpcInvalidParams, std::string(key) + "ItemNotObject"} }; } if (book.as_object().contains("both") && !book.as_object().at("both").is_bool()) - return Error{Status{RippledError::rpcINVALID_PARAMS, "bothNotBool"}}; + return Error{Status{RippledError::RpcInvalidParams, "bothNotBool"}}; auto const parsedBook = parseBook(book.as_object()); if (!parsedBook.has_value()) @@ -62,17 +60,17 @@ UnsubscribeHandler::spec([[maybe_unused]] uint32_t apiVersion) } }; - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(streams), validation::CustomValidators::subscribeStreamValidator}, {JS(accounts), validation::CustomValidators::subscribeAccountsValidator}, {JS(accounts_proposed), validation::CustomValidators::subscribeAccountsValidator}, - {JS(books), kBOOKS_VALIDATOR}, + {JS(books), kBooksValidator}, {JS(url), check::Deprecated{}}, {JS(rt_accounts), check::Deprecated{}}, {"rt_transactions", check::Deprecated{}}, }; - return kRPC_SPEC; + return kRpcSpec; } UnsubscribeHandler::Result @@ -153,7 +151,7 @@ UnsubscribeHandler::unsubscribeFromBooks( subscriptions_->unsubBook(orderBook.book, session); if (orderBook.both) - subscriptions_->unsubBook(ripple::reversed(orderBook.book), session); + subscriptions_->unsubBook(xrpl::reversed(orderBook.book), session); } } diff --git a/src/rpc/handlers/Unsubscribe.hpp b/src/rpc/handlers/Unsubscribe.hpp index b41d9e7d0..42962a712 100644 --- a/src/rpc/handlers/Unsubscribe.hpp +++ b/src/rpc/handlers/Unsubscribe.hpp @@ -36,7 +36,7 @@ public: * @brief A struct to hold one order book */ struct OrderBook { - ripple::Book book; + xrpl::Book book; bool both = false; }; diff --git a/src/rpc/handlers/VaultInfo.cpp b/src/rpc/handlers/VaultInfo.cpp index 990cf3782..967f19a03 100644 --- a/src/rpc/handlers/VaultInfo.cpp +++ b/src/rpc/handlers/VaultInfo.cpp @@ -81,28 +81,28 @@ VaultInfoHandler::process(VaultInfoHandler::Input const& input, Context const& c auto const& lgrInfo = *expectedLgrInfo; // Extract the vault keylet based on input - auto const vaultKeylet = [&]() -> std::expected { + auto const vaultKeylet = [&]() -> std::expected { if (input.owner && input.tnxSequence) { auto const accountStr = *input.owner; auto const accountID = accountFromStringStrict(accountStr); // checks that account exists { - auto const accountKeylet = ripple::keylet::account(*accountID); + auto const accountKeylet = xrpl::keylet::account(*accountID); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject(accountKeylet.key, lgrInfo.seq, ctx.yield); if (!accountLedgerObject) - return std::unexpected{Status{RippledError::rpcENTRY_NOT_FOUND}}; + return std::unexpected{Status{RippledError::RpcEntryNotFound}}; } - return ripple::keylet::vault(*accountID, *input.tnxSequence); + return xrpl::keylet::vault(*accountID, *input.tnxSequence); } - ripple::uint256 nodeIndex; + xrpl::uint256 nodeIndex; if (nodeIndex.parseHex(*input.vaultID)) - return ripple::keylet::vault(nodeIndex); + return xrpl::keylet::vault(nodeIndex); - return std::unexpected{Status{RippledError::rpcENTRY_NOT_FOUND}}; + return std::unexpected{Status{RippledError::RpcEntryNotFound}}; }(); if (not vaultKeylet.has_value()) @@ -113,30 +113,30 @@ VaultInfoHandler::process(VaultInfoHandler::Input const& input, Context const& c sharedPtrBackend_->fetchLedgerObject(vaultKeylet->key, lgrInfo.seq, ctx.yield); if (not vaultLedgerObject) - return Error{Status{RippledError::rpcENTRY_NOT_FOUND, "vault object not found."}}; + return Error{Status{RippledError::RpcEntryNotFound, "vault object not found."}}; - ripple::STLedgerEntry const vaultSle{ - ripple::SerialIter{vaultLedgerObject->data(), vaultLedgerObject->size()}, vaultKeylet->key + xrpl::STLedgerEntry const vaultSle{ + xrpl::SerialIter{vaultLedgerObject->data(), vaultLedgerObject->size()}, vaultKeylet->key }; - auto const issuanceKeylet = ripple::keylet::mptIssuance(vaultSle[ripple::sfShareMPTID]).key; + auto const issuanceKeylet = xrpl::keylet::mptokenIssuance(vaultSle[xrpl::sfShareMPTID]).key; auto const issuanceObject = sharedPtrBackend_->fetchLedgerObject(issuanceKeylet, lgrInfo.seq, ctx.yield); if (not issuanceObject) - return Error{Status{RippledError::rpcENTRY_NOT_FOUND, "issuance object not found."}}; + return Error{Status{RippledError::RpcEntryNotFound, "issuance object not found."}}; - ripple::STLedgerEntry const issuanceSle{ - ripple::SerialIter{issuanceObject->data(), issuanceObject->size()}, issuanceKeylet + xrpl::STLedgerEntry const issuanceSle{ + xrpl::SerialIter{issuanceObject->data(), issuanceObject->size()}, issuanceKeylet }; // put issuance object into "shares" field of vault object // follows same logic as rippled: // https://github.com/XRPLF/rippled/pull/5224/files#diff-6cb544622c7942261f097d628f61f1c1fcf34a1bcfd954aedbada4238fc28f69R107 Output response; - response.vault = toBoostJson(vaultSle.getJson(ripple::JsonOptions::none)); + response.vault = toBoostJson(vaultSle.getJson(xrpl::JsonOptions::Values::None)); response.vault.as_object()[JS(shares)] = - toBoostJson(issuanceSle.getJson(ripple::JsonOptions::none)); + toBoostJson(issuanceSle.getJson(xrpl::JsonOptions::Values::None)); response.ledgerIndex = lgrInfo.seq; return response; diff --git a/src/rpc/handlers/VaultInfo.hpp b/src/rpc/handlers/VaultInfo.hpp index aae4af92c..c2a04818c 100644 --- a/src/rpc/handlers/VaultInfo.hpp +++ b/src/rpc/handlers/VaultInfo.hpp @@ -65,7 +65,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const kRPC_SPEC = RpcSpec{ + static auto const kRpcSpec = RpcSpec{ {JS(vault_id), meta::WithCustomError{ validation::CustomValidators::uint256HexStringValidator, @@ -83,7 +83,7 @@ public: {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, }; - return kRPC_SPEC; + return kRpcSpec; } /** diff --git a/src/util/AccountUtils.hpp b/src/util/AccountUtils.hpp index 397a2190d..395507fe0 100644 --- a/src/util/AccountUtils.hpp +++ b/src/util/AccountUtils.hpp @@ -28,7 +28,7 @@ parseBase58Wrapper(std::string const& str) })) return std::nullopt; - return ripple::parseBase58(str); + return xrpl::parseBase58(str); } /** @@ -43,14 +43,14 @@ parseBase58Wrapper(std::string const& str) */ template [[nodiscard]] std::optional -parseBase58Wrapper(ripple::TokenType type, std::string const& str) +parseBase58Wrapper(xrpl::TokenType type, std::string const& str) { if (!std::all_of(std::begin(str), std::end(str), [](unsigned char c) { return std::isalnum(c); })) return std::nullopt; - return ripple::parseBase58(type, str); + return xrpl::parseBase58(type, str); } } // namespace util diff --git a/src/util/Assert.hpp b/src/util/Assert.hpp index 03ea659a5..ba274c02b 100644 --- a/src/util/Assert.hpp +++ b/src/util/Assert.hpp @@ -1,7 +1,5 @@ #pragma once -#include "util/SourceLocation.hpp" - #include #include @@ -53,7 +51,7 @@ private: template constexpr void assertImpl( - SourceLocationType const location, + std::source_location const location, char const* expression, bool const condition, fmt::format_string format, @@ -86,7 +84,7 @@ assertImpl( } // namespace util::impl -#define ASSERT(condition, ...) \ - util::impl::assertImpl( \ - CURRENT_SRC_LOCATION, #condition, static_cast(condition), __VA_ARGS__ \ +#define ASSERT(condition, ...) \ + util::impl::assertImpl( \ + std::source_location::current(), #condition, static_cast(condition), __VA_ARGS__ \ ) diff --git a/src/util/Atomic.hpp b/src/util/Atomic.hpp index b2b155307..9062af5ed 100644 --- a/src/util/Atomic.hpp +++ b/src/util/Atomic.hpp @@ -76,7 +76,7 @@ public: * * @return The current value */ - ValueType + [[nodiscard]] ValueType value() const { return value_; diff --git a/src/util/CMakeLists.txt b/src/util/CMakeLists.txt index ee7031565..8e08507b7 100644 --- a/src/util/CMakeLists.txt +++ b/src/util/CMakeLists.txt @@ -21,6 +21,7 @@ target_sources( Retry.cpp Repeat.cpp requests/RequestBuilder.cpp + requests/SslContext.cpp requests/Types.cpp requests/WsConnection.cpp requests/impl/SslContext.cpp @@ -45,7 +46,7 @@ target_sources( ) # This must be above the target_link_libraries call otherwise backtrace doesn't work -if("${san}" STREQUAL "") +if(NOT SANITIZERS_ENABLED) target_link_libraries(clio_util PUBLIC Boost::stacktrace_backtrace) endif() @@ -54,7 +55,6 @@ target_link_libraries( PUBLIC Boost::headers Boost::iostreams - Boost::coroutine Boost::context fmt::fmt openssl::openssl diff --git a/src/util/Channel.hpp b/src/util/Channel.hpp index deeeee5c7..de3729b98 100644 --- a/src/util/Channel.hpp +++ b/src/util/Channel.hpp @@ -29,20 +29,20 @@ struct ChannelInstantiated; * @brief Specifies the producer concurrency model for a Channel. */ enum class ProducerType { - Single, /**< Only one Sender can exist (non-copyable). Uses direct Guard ownership for zero - overhead. */ - Multi /**< Multiple Senders can exist (copyable). Uses shared_ptr for shared ownership. - */ + Single, ///< Only one Sender can exist (non-copyable). + ///< Uses direct Guard ownership for zero overhead. + Multi ///< Multiple Senders can exist (copyable). + ///< Uses shared_ptr for shared ownership. }; /** * @brief Specifies the consumer concurrency model for a Channel. */ enum class ConsumerType { - Single, /**< Only one Receiver can exist (non-copyable). Uses direct Guard ownership for zero - overhead. */ - Multi /**< Multiple Receivers can exist (copyable). Uses shared_ptr for shared ownership. - */ + Single, ///< Only one Receiver can exist (non-copyable). + ///< Uses direct Guard ownership for zero overhead. + Multi ///< Multiple Receivers can exist (copyable). + ///< Uses shared_ptr for shared ownership. }; /** @@ -59,8 +59,8 @@ enum class ConsumerType { */ template class Channel { - static constexpr bool kIS_MULTI_PRODUCER = (P == ProducerType::Multi); - static constexpr bool kIS_MULTI_CONSUMER = (C == ConsumerType::Multi); + static constexpr bool kIsMultiProducer = (P == ProducerType::Multi); + static constexpr bool kIsMultiConsumer = (C == ConsumerType::Multi); private: class ControlBlock { @@ -134,7 +134,7 @@ public: */ class Sender { std::shared_ptr shared_; - std::conditional_t, Guard> guard_; + std::conditional_t, Guard> guard_; friend class Channel; @@ -144,7 +144,7 @@ public: */ Sender(std::shared_ptr shared) : shared_(shared), guard_([shared = std::move(shared)]() { - if constexpr (kIS_MULTI_PRODUCER) { + if constexpr (kIsMultiProducer) { return std::make_shared(std::move(shared)); } else { return Guard{std::move(shared)}; @@ -156,21 +156,21 @@ public: public: Sender(Sender&&) = default; Sender(Sender const&) - requires kIS_MULTI_PRODUCER + requires kIsMultiProducer = default; Sender(Sender const&) - requires(!kIS_MULTI_PRODUCER) + requires(!kIsMultiProducer) = delete; Sender& operator=(Sender&&) = default; Sender& operator=(Sender const&) - requires kIS_MULTI_PRODUCER + requires kIsMultiProducer = default; Sender& operator=(Sender const&) - requires(!kIS_MULTI_PRODUCER) + requires(!kIsMultiProducer) = delete; /** @@ -259,7 +259,7 @@ public: */ class Receiver { std::shared_ptr shared_; - std::conditional_t, Guard> guard_; + std::conditional_t, Guard> guard_; friend class Channel; @@ -269,7 +269,7 @@ public: */ Receiver(std::shared_ptr shared) : shared_(shared), guard_([shared = std::move(shared)]() { - if constexpr (kIS_MULTI_CONSUMER) { + if constexpr (kIsMultiConsumer) { return std::make_shared(std::move(shared)); } else { return Guard{std::move(shared)}; @@ -281,21 +281,21 @@ public: public: Receiver(Receiver&&) = default; Receiver(Receiver const&) - requires kIS_MULTI_CONSUMER + requires kIsMultiConsumer = default; Receiver(Receiver const&) - requires(!kIS_MULTI_CONSUMER) + requires(!kIsMultiConsumer) = delete; Receiver& operator=(Receiver&&) = default; Receiver& operator=(Receiver const&) - requires kIS_MULTI_CONSUMER + requires kIsMultiConsumer = default; Receiver& operator=(Receiver const&) - requires(!kIS_MULTI_CONSUMER) + requires(!kIsMultiConsumer) = delete; /** diff --git a/src/util/Concepts.hpp b/src/util/Concepts.hpp index 6461ba74d..115ba522d 100644 --- a/src/util/Concepts.hpp +++ b/src/util/Concepts.hpp @@ -18,7 +18,7 @@ concept SomeNumberType = std::is_arithmetic_v && !std::is_same_v && * @brief Checks that the list of given values contains no duplicates * * @param values The list of values to check - * @returns true if no duplicates exist; false otherwise + * @return true if no duplicates exist; false otherwise */ static consteval auto hasNoDuplicates(auto&&... values) @@ -33,15 +33,15 @@ hasNoDuplicates(auto&&... values) * @brief Checks that the list of given type contains no duplicates * * @tparam Types The types to check - * @returns true if no duplicates exist; false otherwise + * @return true if no duplicates exist; false otherwise */ template constexpr bool hasNoDuplicateNames() { - constexpr std::array kNAMES = {Types::kNAME...}; - return !std::ranges::any_of(kNAMES, [&](std::string_view const& name1) { - return std::ranges::any_of(kNAMES, [&](std::string_view const& name2) { + constexpr std::array kNames = {Types::kName...}; + return !std::ranges::any_of(kNames, [&](std::string_view const& name1) { + return std::ranges::any_of(kNames, [&](std::string_view const& name2) { return &name1 != &name2 && name1 == name2; // Ensure different elements are compared }); }); diff --git a/src/util/Constants.hpp b/src/util/Constants.hpp index 5bc749436..330820b9a 100644 --- a/src/util/Constants.hpp +++ b/src/util/Constants.hpp @@ -3,6 +3,6 @@ #include namespace util { -static constexpr std::size_t kMILLISECONDS_PER_SECOND = 1000; -static constexpr double kNANO_PER_SECOND = 1.0e9; +static constexpr std::size_t kMillisecondsPerSecond = 1000; +static constexpr double kNanoPerSecond = 1.0e9; } // namespace util diff --git a/src/util/Coroutine.cpp b/src/util/Coroutine.cpp index 067fb508e..a1d4c660b 100644 --- a/src/util/Coroutine.cpp +++ b/src/util/Coroutine.cpp @@ -7,7 +7,6 @@ #include #include -#include #include #include diff --git a/src/util/CoroutineGroup.hpp b/src/util/CoroutineGroup.hpp index a392957d6..0691eb859 100644 --- a/src/util/CoroutineGroup.hpp +++ b/src/util/CoroutineGroup.hpp @@ -79,7 +79,7 @@ public: * * @return size_t The number of coroutines in the group */ - size_t + [[nodiscard]] size_t size() const; /** @@ -87,7 +87,7 @@ public: * * @return true If the group is full false otherwise */ - bool + [[nodiscard]] bool isFull() const; private: diff --git a/src/util/LedgerUtils.cpp b/src/util/LedgerUtils.cpp index 8ce8b9623..ae87a3597 100644 --- a/src/util/LedgerUtils.cpp +++ b/src/util/LedgerUtils.cpp @@ -12,16 +12,16 @@ namespace util { -ripple::LedgerEntryType +xrpl::LedgerEntryType LedgerTypes::getLedgerEntryTypeFromStr(std::string const& entryName) { if (auto const result = getLedgerTypeAttributeFromStr(entryName); result.has_value()) { return result->get().type_; } - return ripple::ltANY; + return xrpl::ltANY; } -ripple::LedgerEntryType +xrpl::LedgerEntryType LedgerTypes::getAccountOwnedLedgerTypeFromStr(std::string const& entryName) { if (auto const result = getLedgerTypeAttributeFromStr(entryName); result.has_value() && @@ -29,7 +29,7 @@ LedgerTypes::getAccountOwnedLedgerTypeFromStr(std::string const& entryName) return result->get().type_; } - return ripple::ltANY; + return xrpl::ltANY; } std::optional> @@ -37,10 +37,10 @@ LedgerTypes::getLedgerTypeAttributeFromStr(std::string const& entryName) { static std::unordered_map< std::string, - std::reference_wrapper> const kNAME_MAP = []() { + std::reference_wrapper> const kNameMap = []() { std::unordered_map> map; - std::ranges::for_each(kLEDGER_TYPES, [&map](auto const& item) { + std::ranges::for_each(kLedgerTypes, [&map](auto const& item) { map.insert({util::toLower(item.name_), item}); }); return map; @@ -48,21 +48,21 @@ LedgerTypes::getLedgerTypeAttributeFromStr(std::string const& entryName) static std::unordered_map< std::string, - std::reference_wrapper> const kRPC_NAME_MAP = []() { + std::reference_wrapper> const kRpcNameMap = []() { std::unordered_map> map; - std::ranges::for_each(kLEDGER_TYPES, [&map](auto const& item) { + std::ranges::for_each(kLedgerTypes, [&map](auto const& item) { map.insert({item.rpcName_, item}); }); return map; }(); - if (auto const it = kRPC_NAME_MAP.find(entryName); it != kRPC_NAME_MAP.end()) { + if (auto const it = kRpcNameMap.find(entryName); it != kRpcNameMap.end()) { return it->second; } auto const entryNameLowercase = util::toLower(entryName); - if (auto const it = kNAME_MAP.find(entryNameLowercase); it != kNAME_MAP.end()) { + if (auto const it = kNameMap.find(entryNameLowercase); it != kNameMap.end()) { return it->second; } diff --git a/src/util/LedgerUtils.hpp b/src/util/LedgerUtils.hpp index 4a0c7f016..22b5d4ab2 100644 --- a/src/util/LedgerUtils.hpp +++ b/src/util/LedgerUtils.hpp @@ -32,7 +32,7 @@ class LedgerTypeAttribute { DeletionBlocker // The ledger object is owned by account and it blocks deletion }; - ripple::LedgerEntryType type_ = ripple::ltANY; + xrpl::LedgerEntryType type_ = xrpl::ltANY; char const* name_ = nullptr; char const* rpcName_ = nullptr; LedgerCategory category_ = LedgerCategory::Invalid; @@ -40,7 +40,7 @@ class LedgerTypeAttribute { constexpr LedgerTypeAttribute( char const* name, char const* rpcName, - ripple::LedgerEntryType type, + xrpl::LedgerEntryType type, LedgerCategory category ) : type_{type}, name_{name}, rpcName_{rpcName}, category_{category} @@ -49,19 +49,19 @@ class LedgerTypeAttribute { public: static constexpr LedgerTypeAttribute - chainLedgerType(char const* name, char const* rpcName, ripple::LedgerEntryType type) + chainLedgerType(char const* name, char const* rpcName, xrpl::LedgerEntryType type) { return LedgerTypeAttribute(name, rpcName, type, LedgerCategory::Chain); } static constexpr LedgerTypeAttribute - accountOwnedLedgerType(char const* name, char const* rpcName, ripple::LedgerEntryType type) + accountOwnedLedgerType(char const* name, char const* rpcName, xrpl::LedgerEntryType type) { return LedgerTypeAttribute(name, rpcName, type, LedgerCategory::AccountOwned); } static constexpr LedgerTypeAttribute - deletionBlockerLedgerType(char const* name, char const* rpcName, ripple::LedgerEntryType type) + deletionBlockerLedgerType(char const* name, char const* rpcName, xrpl::LedgerEntryType type) { return LedgerTypeAttribute(name, rpcName, type, LedgerCategory::DeletionBlocker); } @@ -78,84 +78,91 @@ class LedgerTypes { using LedgerTypeAttribute = impl::LedgerTypeAttribute; using LedgerTypeAttributeList = LedgerTypeAttribute[]; - static constexpr LedgerTypeAttributeList const kLEDGER_TYPES{ + static constexpr LedgerTypeAttributeList const kLedgerTypes{ LedgerTypeAttribute::accountOwnedLedgerType( JS(AccountRoot), JS(account), - ripple::ltACCOUNT_ROOT + xrpl::ltACCOUNT_ROOT ), - LedgerTypeAttribute::chainLedgerType(JS(Amendments), JS(amendments), ripple::ltAMENDMENTS), - LedgerTypeAttribute::deletionBlockerLedgerType(JS(Check), JS(check), ripple::ltCHECK), + LedgerTypeAttribute::chainLedgerType(JS(Amendments), JS(amendments), xrpl::ltAMENDMENTS), + LedgerTypeAttribute::deletionBlockerLedgerType(JS(Check), JS(check), xrpl::ltCHECK), LedgerTypeAttribute::accountOwnedLedgerType( JS(DepositPreauth), JS(deposit_preauth), - ripple::ltDEPOSIT_PREAUTH + xrpl::ltDEPOSIT_PREAUTH ), // dir node belongs to account, but can not be filtered from account_objects - LedgerTypeAttribute::chainLedgerType(JS(DirectoryNode), JS(directory), ripple::ltDIR_NODE), - LedgerTypeAttribute::deletionBlockerLedgerType(JS(Escrow), JS(escrow), ripple::ltESCROW), - LedgerTypeAttribute::chainLedgerType(JS(FeeSettings), JS(fee), ripple::ltFEE_SETTINGS), - LedgerTypeAttribute::chainLedgerType(JS(LedgerHashes), JS(hashes), ripple::ltLEDGER_HASHES), - LedgerTypeAttribute::accountOwnedLedgerType(JS(Offer), JS(offer), ripple::ltOFFER), + LedgerTypeAttribute::chainLedgerType(JS(DirectoryNode), JS(directory), xrpl::ltDIR_NODE), + LedgerTypeAttribute::deletionBlockerLedgerType(JS(Escrow), JS(escrow), xrpl::ltESCROW), + LedgerTypeAttribute::chainLedgerType(JS(FeeSettings), JS(fee), xrpl::ltFEE_SETTINGS), + LedgerTypeAttribute::chainLedgerType(JS(LedgerHashes), JS(hashes), xrpl::ltLEDGER_HASHES), + LedgerTypeAttribute::accountOwnedLedgerType(JS(Offer), JS(offer), xrpl::ltOFFER), LedgerTypeAttribute::deletionBlockerLedgerType( JS(PayChannel), JS(payment_channel), - ripple::ltPAYCHAN + xrpl::ltPAYCHAN ), LedgerTypeAttribute::accountOwnedLedgerType( JS(SignerList), JS(signer_list), - ripple::ltSIGNER_LIST + xrpl::ltSIGNER_LIST ), LedgerTypeAttribute::deletionBlockerLedgerType( JS(RippleState), JS(state), - ripple::ltRIPPLE_STATE + xrpl::ltRIPPLE_STATE ), - LedgerTypeAttribute::accountOwnedLedgerType(JS(Ticket), JS(ticket), ripple::ltTICKET), + LedgerTypeAttribute::accountOwnedLedgerType(JS(Ticket), JS(ticket), xrpl::ltTICKET), LedgerTypeAttribute::accountOwnedLedgerType( JS(NFTokenOffer), JS(nft_offer), - ripple::ltNFTOKEN_OFFER + xrpl::ltNFTOKEN_OFFER ), LedgerTypeAttribute::deletionBlockerLedgerType( JS(NFTokenPage), JS(nft_page), - ripple::ltNFTOKEN_PAGE + xrpl::ltNFTOKEN_PAGE ), - LedgerTypeAttribute::accountOwnedLedgerType(JS(AMM), JS(amm), ripple::ltAMM), - LedgerTypeAttribute::deletionBlockerLedgerType(JS(Bridge), JS(bridge), ripple::ltBRIDGE), + LedgerTypeAttribute::accountOwnedLedgerType(JS(AMM), JS(amm), xrpl::ltAMM), + LedgerTypeAttribute::deletionBlockerLedgerType(JS(Bridge), JS(bridge), xrpl::ltBRIDGE), LedgerTypeAttribute::deletionBlockerLedgerType( JS(XChainOwnedClaimID), JS(xchain_owned_claim_id), - ripple::ltXCHAIN_OWNED_CLAIM_ID + xrpl::ltXCHAIN_OWNED_CLAIM_ID ), LedgerTypeAttribute::deletionBlockerLedgerType( JS(XChainOwnedCreateAccountClaimID), JS(xchain_owned_create_account_claim_id), - ripple::ltXCHAIN_OWNED_CREATE_ACCOUNT_CLAIM_ID + xrpl::ltXCHAIN_OWNED_CREATE_ACCOUNT_CLAIM_ID ), - LedgerTypeAttribute::accountOwnedLedgerType(JS(DID), JS(did), ripple::ltDID), - LedgerTypeAttribute::accountOwnedLedgerType(JS(Oracle), JS(oracle), ripple::ltORACLE), + LedgerTypeAttribute::accountOwnedLedgerType(JS(DID), JS(did), xrpl::ltDID), + LedgerTypeAttribute::accountOwnedLedgerType(JS(Oracle), JS(oracle), xrpl::ltORACLE), LedgerTypeAttribute::accountOwnedLedgerType( JS(Credential), JS(credential), - ripple::ltCREDENTIAL + xrpl::ltCREDENTIAL ), - LedgerTypeAttribute::accountOwnedLedgerType(JS(Vault), JS(vault), ripple::ltVAULT), - LedgerTypeAttribute::chainLedgerType(JS(NegativeUNL), JS(nunl), ripple::ltNEGATIVE_UNL), + LedgerTypeAttribute::accountOwnedLedgerType(JS(Vault), JS(vault), xrpl::ltVAULT), + // loan broker is a pseudo-account object, like AMM and Vault + LedgerTypeAttribute::accountOwnedLedgerType( + JS(LoanBroker), + JS(loan_broker), + xrpl::ltLOAN_BROKER + ), + LedgerTypeAttribute::deletionBlockerLedgerType(JS(Loan), JS(loan), xrpl::ltLOAN), + LedgerTypeAttribute::chainLedgerType(JS(NegativeUNL), JS(nunl), xrpl::ltNEGATIVE_UNL), LedgerTypeAttribute::deletionBlockerLedgerType( JS(MPTokenIssuance), JS(mpt_issuance), - ripple::ltMPTOKEN_ISSUANCE + xrpl::ltMPTOKEN_ISSUANCE ), - LedgerTypeAttribute::deletionBlockerLedgerType(JS(MPToken), JS(mptoken), ripple::ltMPTOKEN), + LedgerTypeAttribute::deletionBlockerLedgerType(JS(MPToken), JS(mptoken), xrpl::ltMPTOKEN), LedgerTypeAttribute::deletionBlockerLedgerType( JS(PermissionedDomain), JS(permissioned_domain), - ripple::ltPERMISSIONED_DOMAIN + xrpl::ltPERMISSIONED_DOMAIN ), - LedgerTypeAttribute::accountOwnedLedgerType(JS(Delegate), JS(delegate), ripple::ltDELEGATE), + LedgerTypeAttribute::accountOwnedLedgerType(JS(Delegate), JS(delegate), xrpl::ltDELEGATE), }; public: @@ -166,8 +173,8 @@ public: static constexpr auto getLedgerEntryTypeStrList() { - std::array res{}; - std::ranges::transform(kLEDGER_TYPES, std::begin(res), [](auto const& item) { + std::array res{}; + std::ranges::transform(kLedgerTypes, std::begin(res), [](auto const& item) { return item.rpcName_; }); return res; @@ -181,16 +188,16 @@ public: static constexpr auto getDeletionBlockerLedgerTypes() { - constexpr auto kFILTER = [](auto const& item) { + constexpr auto kFilter = [](auto const& item) { return item.category_ == LedgerTypeAttribute::LedgerCategory::DeletionBlocker; }; - constexpr auto kDELETION_BLOCKERS_COUNT = - std::count_if(std::begin(kLEDGER_TYPES), std::end(kLEDGER_TYPES), kFILTER); - std::array res{}; + constexpr auto kDeletionBlockersCount = + std::count_if(std::begin(kLedgerTypes), std::end(kLedgerTypes), kFilter); + std::array res{}; auto it = std::begin(res); - std::ranges::for_each(kLEDGER_TYPES, [&](auto const& item) { - if (kFILTER(item)) { + std::ranges::for_each(kLedgerTypes, [&](auto const& item) { + if (kFilter(item)) { *it = item.type_; ++it; } @@ -199,23 +206,23 @@ public: } /** - * @brief Returns the ripple::LedgerEntryType from the given string. + * @brief Returns the xrpl::LedgerEntryType from the given string. * * @param entryName The name or canonical name (case-insensitive) of the ledger entry type for * all categories - * @return The ripple::LedgerEntryType of the given string, returns ltANY if not found. + * @return The xrpl::LedgerEntryType of the given string, returns ltANY if not found. */ - static ripple::LedgerEntryType + static xrpl::LedgerEntryType getLedgerEntryTypeFromStr(std::string const& entryName); /** - * @brief Returns the ripple::LedgerEntryType from the given string. + * @brief Returns the xrpl::LedgerEntryType from the given string. * * @param entryName The name or canonical name (case-insensitive) of the ledger entry type for * account owned category - * @return The ripple::LedgerEntryType of the given string, returns ltANY if not found. + * @return The xrpl::LedgerEntryType of the given string, returns ltANY if not found. */ - static ripple::LedgerEntryType + static xrpl::LedgerEntryType getAccountOwnedLedgerTypeFromStr(std::string const& entryName); private: @@ -224,32 +231,32 @@ private: }; /** - * @brief Deserializes a ripple::LedgerHeader from ripple::Slice of data. + * @brief Deserializes a xrpl::LedgerHeader from xrpl::Slice of data. * * @param data The slice to deserialize - * @return The deserialized ripple::LedgerHeader + * @return The deserialized xrpl::LedgerHeader */ -inline ripple::LedgerHeader -deserializeHeader(ripple::Slice data) +inline xrpl::LedgerHeader +deserializeHeader(xrpl::Slice data) { - return ripple::deserializeHeader(data, /* hasHash = */ true); + return xrpl::deserializeHeader(data, /* hasHash = */ true); } /** - * @brief A helper function that converts a ripple::LedgerHeader to a string representation. + * @brief A helper function that converts a xrpl::LedgerHeader to a string representation. * * @param info The ledger header * @return The string representation of the supplied ledger header */ inline std::string -toString(ripple::LedgerHeader const& info) +toString(xrpl::LedgerHeader const& info) { return fmt::format( "LedgerHeader {{Sequence: {}, Hash: {}, TxHash: {}, AccountHash: {}, ParentHash: {}}}", info.seq, - ripple::strHex(info.hash), + xrpl::strHex(info.hash), strHex(info.txHash), - ripple::strHex(info.accountHash), + xrpl::strHex(info.accountHash), strHex(info.parentHash) ); } diff --git a/src/util/Random.hpp b/src/util/Random.hpp index dc34b0100..4b8fc99c2 100644 --- a/src/util/Random.hpp +++ b/src/util/Random.hpp @@ -14,7 +14,7 @@ class RandomGeneratorInterface { public: virtual ~RandomGeneratorInterface() = default; - using SeedType = typename std::mt19937_64::result_type; + using SeedType = std::mt19937_64::result_type; /** * @brief Generate a random number between min and max diff --git a/src/util/ResponseExpirationCache.cpp b/src/util/ResponseExpirationCache.cpp index c1e5c3ba4..e43e53afc 100644 --- a/src/util/ResponseExpirationCache.cpp +++ b/src/util/ResponseExpirationCache.cpp @@ -4,11 +4,14 @@ #include +#include +#include #include #include #include #include #include +#include #include namespace util { @@ -44,9 +47,37 @@ ResponseExpirationCache::shouldCache(std::string const& cmd) return cache_.contains(cmd); } -std::optional -ResponseExpirationCache::get(std::string const& cmd) const +bool +ResponseExpirationCache::isBareRequest(boost::json::object const& request) { + // Keys that identify the command or are safe to ignore for caching purposes. + // + // "command" and "method" merely name the RPC command — they do not affect response content. + // + // "id" is safe to ignore because the web layer re-applies the current request's id to the + // response AFTER the cache lookup (see src/web/RPCServerHandler.hpp), so a cached body never + // leaks a stale id back to the client. Ignoring "id" is also necessary for WebSocket + // requests, which almost always carry an id and would otherwise never benefit from caching. + // + // "api_version" is intentionally NOT in this ignore-set: it can change the response body + // content (not just an echoed field), so requests carrying it must bypass the cache entirely. + static constexpr auto kIgnoredKeys = + std::to_array({"command", "method", "id"}); + + for (auto const& kv : request) { + std::string_view const key{kv.key()}; + if (not std::ranges::contains(kIgnoredKeys, key)) + return false; + } + return true; +} + +std::optional +ResponseExpirationCache::get(std::string const& cmd, boost::json::object const& request) const +{ + if (not isBareRequest(request)) + return std::nullopt; + auto it = cache_.find(cmd); if (it == cache_.end()) return std::nullopt; @@ -59,8 +90,15 @@ ResponseExpirationCache::get(std::string const& cmd) const } void -ResponseExpirationCache::put(std::string const& cmd, boost::json::object const& response) +ResponseExpirationCache::put( + std::string const& cmd, + boost::json::object const& request, + boost::json::object const& response +) { + if (not isBareRequest(request)) + return; + if (not shouldCache(cmd)) return; diff --git a/src/util/ResponseExpirationCache.hpp b/src/util/ResponseExpirationCache.hpp index 083a2daea..582f6faf6 100644 --- a/src/util/ResponseExpirationCache.hpp +++ b/src/util/ResponseExpirationCache.hpp @@ -62,6 +62,19 @@ class ResponseExpirationCache { bool shouldCache(std::string const& cmd); + /** + * @brief Check whether a request is "bare" (carries no response-customizing params). + * + * A request is bare iff every key it contains is one of: "command", "method", "id". + * Any other key (e.g. "api_version", "hash", "counters", "ledger_index") makes the request + * non-bare, and the cache must be bypassed for it. + * + * @param request The request object to inspect + * @return true if the request is bare; false otherwise + */ + static bool + isBareRequest(boost::json::object const& request); + public: /** * @brief Construct a new Cache object @@ -83,20 +96,30 @@ public: /** * @brief Get a response from the cache * + * Only bare requests (those carrying no response-customizing params beyond "command", "method", + * and "id") are served from the cache. Non-bare requests always return std::nullopt. + * * @param cmd The command to get the response for - * @return The response if it exists or std::nullopt otherwise + * @param request The full request object; used to determine whether the request is bare + * @return The cached response if available and not expired, or std::nullopt otherwise */ [[nodiscard]] std::optional - get(std::string const& cmd) const; + get(std::string const& cmd, boost::json::object const& request) const; /** * @brief Put a response into the cache if the request should be cached * + * Only bare requests (those carrying no response-customizing params beyond "command", "method", + * and "id") are stored in the cache. Non-bare requests are silently ignored. + * * @param cmd The command to store the response for + * @param request The full request object; used to determine whether the request is bare * @param response The response to store */ void - put(std::string const& cmd, boost::json::object const& response); + put(std::string const& cmd, + boost::json::object const& request, + boost::json::object const& response); /** * @brief Invalidate all entries in the cache diff --git a/src/util/Shasum.cpp b/src/util/Shasum.cpp index 01f4576ee..d4e8510b3 100644 --- a/src/util/Shasum.cpp +++ b/src/util/Shasum.cpp @@ -9,13 +9,13 @@ namespace util { -ripple::uint256 +xrpl::uint256 sha256sum(std::string_view s) { - ripple::sha256_hasher hasher; + xrpl::sha256_hasher hasher; hasher(s.data(), s.size()); - auto const hashData = static_cast(hasher); - ripple::uint256 sha256; + auto const hashData = static_cast(hasher); + xrpl::uint256 sha256; std::memcpy(sha256.data(), hashData.data(), hashData.size()); return sha256; } @@ -23,7 +23,7 @@ sha256sum(std::string_view s) std::string sha256sumString(std::string_view s) { - return ripple::to_string(sha256sum(s)); + return xrpl::to_string(sha256sum(s)); } void @@ -32,13 +32,13 @@ Sha256sum::update(void const* data, size_t size) hasher_(data, size); } -ripple::uint256 +xrpl::uint256 Sha256sum::finalize() && { - auto const hashData = static_cast(hasher_); - ripple::uint256 result; + auto const hashData = static_cast(hasher_); + xrpl::uint256 result; std::memcpy(result.data(), hashData.data(), hashData.size()); - hasher_ = ripple::sha256_hasher{}; + hasher_ = xrpl::sha256_hasher{}; return result; } diff --git a/src/util/Shasum.hpp b/src/util/Shasum.hpp index 65492a1e1..0f4664afa 100644 --- a/src/util/Shasum.hpp +++ b/src/util/Shasum.hpp @@ -12,9 +12,9 @@ namespace util { * @brief Calculates the SHA256 sum of a string. * * @param s The string to hash. - * @return The SHA256 sum as a ripple::uint256. + * @return The SHA256 sum as a xrpl::uint256. */ -ripple::uint256 +xrpl::uint256 sha256sum(std::string_view s); /** @@ -33,7 +33,7 @@ sha256sumString(std::string_view s); * without requiring all data to be in memory at once. */ class Sha256sum { - ripple::sha256_hasher hasher_; + xrpl::sha256_hasher hasher_; public: /** @@ -58,11 +58,11 @@ public: } /** - * @brief Finalize hash and return result as ripple::uint256. + * @brief Finalize hash and return result as xrpl::uint256. * * @return The SHA-256 hash. */ - ripple::uint256 + xrpl::uint256 finalize() &&; }; diff --git a/src/util/SignalsHandler.cpp b/src/util/SignalsHandler.cpp index b57d1f9ab..27631f3a7 100644 --- a/src/util/SignalsHandler.cpp +++ b/src/util/SignalsHandler.cpp @@ -87,7 +87,7 @@ SignalsHandler::notifyGracefulShutdownComplete() void SignalsHandler::setHandler(void (*handler)(int)) { - for (int const signal : kHANDLED_SIGNALS) + for (int const signal : kHandledSignals) std::signal(signal, handler == nullptr ? SIG_DFL : handler); } diff --git a/src/util/SignalsHandler.hpp b/src/util/SignalsHandler.hpp index 55acd7f0e..83137b3ac 100644 --- a/src/util/SignalsHandler.hpp +++ b/src/util/SignalsHandler.hpp @@ -60,7 +60,7 @@ public: */ SignalsHandler( util::config::ClioConfigDefinition const& config, - std::function forceExitHandler = kDEFAULT_FORCE_EXIT_HANDLER + std::function forceExitHandler = kDefaultForceExitHandler ); SignalsHandler(SignalsHandler const&) = delete; @@ -96,7 +96,7 @@ public: void notifyGracefulShutdownComplete(); - static constexpr auto kHANDLED_SIGNALS = {SIGINT, SIGTERM}; + static constexpr auto kHandledSignals = {SIGINT, SIGTERM}; private: /** @@ -113,7 +113,7 @@ private: void runStateMachine(); - static constexpr auto kDEFAULT_FORCE_EXIT_HANDLER = []() { std::exit(EXIT_FAILURE); }; + static constexpr auto kDefaultForceExitHandler = []() { std::exit(EXIT_FAILURE); }; }; } // namespace util diff --git a/src/util/SourceLocation.hpp b/src/util/SourceLocation.hpp deleted file mode 100644 index a158f2d8c..000000000 --- a/src/util/SourceLocation.hpp +++ /dev/null @@ -1,81 +0,0 @@ -#pragma once - -#if defined(HAS_SOURCE_LOCATION) && __has_builtin(__builtin_source_location) -// this is used by fully compatible compilers like gcc -#include - -#elif defined(HAS_EXPERIMENTAL_SOURCE_LOCATION) -// this is used by clang on linux where source_location is still not out of -// experimental headers -#include - -#else - -#include -#include -#endif - -namespace util { - -#if defined(HAS_SOURCE_LOCATION) && __has_builtin(__builtin_source_location) -using SourceLocationType = std::source_location; - -#elif defined(HAS_EXPERIMENTAL_SOURCE_LOCATION) -using SourceLocationType = std::experimental::source_location; - -#else -/** - * @brief A class representing the source location of the current code - * - * @note This is a workaround for AppleClang that is lacking source_location atm. - * TODO: remove this class when all compilers catch up to c++20 - */ -class SourceLocation { - char const* file_; - std::size_t line_; - -public: - /** - * @brief Construct a new Source Location object - * - * @param file The file name - * @param line The line number - */ - constexpr SourceLocation(char const* file, std::size_t line) : file_{file}, line_{line} - { - } - - /** - * @brief Get the file name - * - * @return The file name - */ - constexpr std::string_view - file_name() const - { - return file_; - } - - /** - * @brief Get the line number - * - * @return The line number - */ - constexpr std::size_t - line() const - { - return line_; - } -}; -using SourceLocationType = SourceLocation; -#define SOURCE_LOCATION_OLD_API - -#endif - -} // namespace util - -#if defined(SOURCE_LOCATION_OLD_API) -#define CURRENT_SRC_LOCATION util::SourceLocationType(__FILE__, __LINE__) -#else -#define CURRENT_SRC_LOCATION util::SourceLocationType::current() -#endif diff --git a/src/util/Spawn.hpp b/src/util/Spawn.hpp index c67f9e60c..a4781ef94 100644 --- a/src/util/Spawn.hpp +++ b/src/util/Spawn.hpp @@ -31,14 +31,14 @@ inline constexpr struct PropagatingCompletionHandler { if (ePtr) std::rethrow_exception(ePtr); } -} kPROPAGATE_EXCEPTIONS; +} kPropagateExceptions; } // namespace impl /** * @brief Spawns a coroutine using `boost::asio::spawn` * - * @note This uses kPROPAGATE_EXCEPTIONS to force asio to propagate exceptions through `io_context` + * @note This uses kPropagateExceptions to force asio to propagate exceptions through `io_context` * @note Since implicit strand was removed from boost::asio::spawn this helper function adds the * strand back * @@ -54,13 +54,13 @@ spawn(Ctx&& ctx, F&& func) { if constexpr (impl::IsStrand) { boost::asio::spawn( - std::forward(ctx), std::forward(func), impl::kPROPAGATE_EXCEPTIONS + std::forward(ctx), std::forward(func), impl::kPropagateExceptions ); } else { boost::asio::spawn( boost::asio::make_strand(std::forward(ctx).get_executor()), std::forward(func), - impl::kPROPAGATE_EXCEPTIONS + impl::kPropagateExceptions ); } } diff --git a/src/util/Taggable.cpp b/src/util/Taggable.cpp index 0cd3632ce..ac6cf07b6 100644 --- a/src/util/Taggable.cpp +++ b/src/util/Taggable.cpp @@ -11,18 +11,18 @@ namespace util::impl { UIntTagGenerator::TagType UIntTagGenerator::next() { - static std::atomic_uint64_t kNUM{0}; - return kNUM++; + static std::atomic_uint64_t kNum{0}; + return kNum++; } UUIDTagGenerator::TagType UUIDTagGenerator::next() { - static boost::uuids::random_generator kGEN{}; - static std::mutex kMTX{}; + static boost::uuids::random_generator kGen{}; + static std::mutex kMtx{}; - std::scoped_lock const lk(kMTX); - return kGEN(); + std::scoped_lock const lk(kMtx); + return kGen(); } } // namespace util::impl diff --git a/src/util/Taggable.hpp b/src/util/Taggable.hpp index ba178b298..f0b08a69d 100644 --- a/src/util/Taggable.hpp +++ b/src/util/Taggable.hpp @@ -100,7 +100,7 @@ public: template class TagDecorator final : public BaseTagDecorator { using ParentType = std::optional>; - using TagType = typename Generator::TagType; + using TagType = Generator::TagType; ParentType parent_ = std::nullopt; TagType tag_ = Generator::next(); @@ -169,9 +169,9 @@ class TagDecoratorFactory final { * @brief Represents the type of tag decorator. */ enum class Type { - NONE, /**< No decoration and no tag */ - UUID, /**< Tag based on `boost::uuids::uuid`, thread-safe via mutex */ - UINT /**< atomic_uint64_t tag, thread-safe, lock-free */ + NONE, ///< No decoration and no tag + UUID, ///< Tag based on `boost::uuids::uuid`, thread-safe via mutex + UINT ///< atomic_uint64_t tag, thread-safe, lock-free }; Type type_; /*< The type of TagDecorator this factory produces */ diff --git a/src/util/TimeUtils.cpp b/src/util/TimeUtils.cpp index de8243bc8..7642eecab 100644 --- a/src/util/TimeUtils.cpp +++ b/src/util/TimeUtils.cpp @@ -30,11 +30,9 @@ systemTpToUtcStr(std::chrono::system_clock::time_point const& tp, std::string co } [[nodiscard]] std::chrono::system_clock::time_point -systemTpFromLedgerCloseTime(ripple::NetClock::time_point closeTime) +systemTpFromLedgerCloseTime(xrpl::NetClock::time_point closeTime) { - return std::chrono::system_clock::time_point{ - closeTime.time_since_epoch() + ripple::epoch_offset - }; + return std::chrono::system_clock::time_point{closeTime.time_since_epoch() + xrpl::kEpochOffset}; } } // namespace util diff --git a/src/util/TimeUtils.hpp b/src/util/TimeUtils.hpp index 4f708b23e..d21a346a0 100644 --- a/src/util/TimeUtils.hpp +++ b/src/util/TimeUtils.hpp @@ -33,6 +33,6 @@ systemTpToUtcStr(std::chrono::system_clock::time_point const& tp, std::string co * @return The system_clock::time_point. */ [[nodiscard]] std::chrono::system_clock::time_point -systemTpFromLedgerCloseTime(ripple::NetClock::time_point closeTime); +systemTpFromLedgerCloseTime(xrpl::NetClock::time_point closeTime); } // namespace util diff --git a/src/util/TxUtils.cpp b/src/util/TxUtils.cpp index 6a4c91581..1ebccc8f2 100644 --- a/src/util/TxUtils.cpp +++ b/src/util/TxUtils.cpp @@ -17,17 +17,17 @@ namespace util { [[nodiscard]] std::unordered_set const& getTxTypesInLowercase() { - static std::unordered_set const kTYPES_KEYS_IN_LOWERCASE = []() { + static std::unordered_set const kTypesKeysInLowercase = []() { std::unordered_set keys; std::transform( - ripple::TxFormats::getInstance().begin(), - ripple::TxFormats::getInstance().end(), + xrpl::TxFormats::getInstance().begin(), + xrpl::TxFormats::getInstance().end(), std::inserter(keys, keys.begin()), [](auto const& pair) { return util::toLower(pair.getName()); } ); return keys; }(); - return kTYPES_KEYS_IN_LOWERCASE; + return kTypesKeysInLowercase; } } // namespace util diff --git a/src/util/UnsupportedType.hpp b/src/util/UnsupportedType.hpp index 6e9ef1206..7d8ad5082 100644 --- a/src/util/UnsupportedType.hpp +++ b/src/util/UnsupportedType.hpp @@ -2,7 +2,9 @@ namespace util { -/** @brief used for compile time checking of unsupported types */ +/** + * @brief used for compile time checking of unsupported types + */ template static constexpr bool Unsupported = false; // NOLINT(readability-identifier-naming) diff --git a/src/util/async/AnyExecutionContext.hpp b/src/util/async/AnyExecutionContext.hpp index 1d9241e37..92875a439 100644 --- a/src/util/async/AnyExecutionContext.hpp +++ b/src/util/async/AnyExecutionContext.hpp @@ -4,6 +4,7 @@ #include "util/async/AnyStopToken.hpp" #include "util/async/AnyStrand.hpp" #include "util/async/Concepts.hpp" +#include "util/async/impl/Any.hpp" #include "util/async/impl/ErasedOperation.hpp" #include @@ -62,16 +63,16 @@ public: * @brief Execute a function on the execution context * * @param fn The function to execute - * @returns A unstoppable operation that can be used to wait for the result + * @return A unstoppable operation that can be used to wait for the result */ [[nodiscard]] auto execute(SomeHandlerWithoutStopToken auto&& fn) { using RetType = std::decay_t>; - static_assert(not std::is_same_v); + static_assert(not std::is_same_v); return AnyOperation( - pimpl_->execute([fn = std::forward(fn)] mutable -> std::any { + pimpl_->execute([fn = std::forward(fn)] mutable -> impl::Any { if constexpr (std::is_void_v) { std::invoke(std::forward(fn)); return {}; @@ -86,7 +87,7 @@ public: * @brief Execute a function on the execution context * * @param fn The function to execute - * @returns A stoppable operation that can be used to wait for the result + * @return A stoppable operation that can be used to wait for the result * * @note The function is expected to take a stop token */ @@ -94,10 +95,10 @@ public: execute(SomeHandlerWith auto&& fn) { using RetType = std::decay_t>; - static_assert(not std::is_same_v); + static_assert(not std::is_same_v); return AnyOperation(pimpl_->execute( - [fn = std::forward(fn)](auto stopToken) mutable -> std::any { + [fn = std::forward(fn)](auto stopToken) mutable -> impl::Any { if constexpr (std::is_void_v) { std::invoke(std::forward(fn), std::move(stopToken)); return {}; @@ -115,7 +116,7 @@ public: * * @param fn The function to execute * @param timeout The timeout after which the function should be cancelled - * @returns A stoppable operation that can be used to wait for the result + * @return A stoppable operation that can be used to wait for the result * * @note The function is expected to take a stop token */ @@ -123,10 +124,10 @@ public: execute(SomeHandlerWith auto&& fn, SomeStdDuration auto timeout) { using RetType = std::decay_t>; - static_assert(not std::is_same_v); + static_assert(not std::is_same_v); return AnyOperation(pimpl_->execute( - [fn = std::forward(fn)](auto stopToken) mutable -> std::any { + [fn = std::forward(fn)](auto stopToken) mutable -> impl::Any { if constexpr (std::is_void_v) { std::invoke(std::forward(fn), std::move(stopToken)); return {}; @@ -145,7 +146,7 @@ public: * * @param delay The delay after which the function should be executed * @param fn The function to execute - * @returns A stoppable operation that can be used to wait for the result + * @return A stoppable operation that can be used to wait for the result * * @note The function is expected to take a stop token */ @@ -153,11 +154,11 @@ public: scheduleAfter(SomeStdDuration auto delay, SomeHandlerWith auto&& fn) { using RetType = std::decay_t>; - static_assert(not std::is_same_v); + static_assert(not std::is_same_v); auto const millis = std::chrono::duration_cast(delay); return AnyOperation(pimpl_->scheduleAfter( - millis, [fn = std::forward(fn)](auto stopToken) mutable -> std::any { + millis, [fn = std::forward(fn)](auto stopToken) mutable -> impl::Any { if constexpr (std::is_void_v) { std::invoke(std::forward(fn), std::move(stopToken)); return {}; @@ -175,7 +176,7 @@ public: * * @param delay The delay after which the function should be executed * @param fn The function to execute - * @returns A stoppable operation that can be used to wait for the result + * @return A stoppable operation that can be used to wait for the result * * @note The function is expected to take a stop token and a boolean representing whether the * scheduled operation got cancelled @@ -184,13 +185,13 @@ public: scheduleAfter(SomeStdDuration auto delay, SomeHandlerWith auto&& fn) { using RetType = std::decay_t>; - static_assert(not std::is_same_v); + static_assert(not std::is_same_v); auto const millis = std::chrono::duration_cast(delay); return AnyOperation(pimpl_->scheduleAfter( millis, [fn = std::forward(fn)](auto stopToken, auto cancelled) mutable - -> std::any { + -> impl::Any { if constexpr (std::is_void_v) { std::invoke(std::forward(fn), std::move(stopToken), cancelled); return {}; @@ -214,12 +215,12 @@ public: executeRepeatedly(SomeStdDuration auto interval, SomeHandlerWithoutStopToken auto&& fn) { using RetType = std::decay_t>; - static_assert(not std::is_same_v); + static_assert(not std::is_same_v); auto const millis = std::chrono::duration_cast(interval); return AnyOperation( // pimpl_->executeRepeatedly( - millis, [fn = std::forward(fn)] mutable -> std::any { + millis, [fn = std::forward(fn)] mutable -> impl::Any { std::invoke(std::forward(fn)); return {}; } @@ -277,18 +278,18 @@ private: virtual impl::ErasedOperation execute( - std::function, + std::function, std::optional timeout = std::nullopt ) = 0; - virtual impl::ErasedOperation execute(std::function) = 0; + virtual impl::ErasedOperation execute(std::function) = 0; virtual impl::ErasedOperation - scheduleAfter(std::chrono::milliseconds, std::function) = 0; + scheduleAfter(std::chrono::milliseconds, std::function) = 0; virtual impl::ErasedOperation scheduleAfter( std::chrono::milliseconds, - std::function + std::function ) = 0; virtual impl::ErasedOperation - executeRepeatedly(std::chrono::milliseconds, std::function) = 0; + executeRepeatedly(std::chrono::milliseconds, std::function) = 0; virtual void submit(std::function) = 0; virtual AnyStrand makeStrand() = 0; @@ -309,7 +310,7 @@ private: impl::ErasedOperation execute( - std::function fn, + std::function fn, std::optional timeout ) override { @@ -317,7 +318,7 @@ private: } impl::ErasedOperation - execute(std::function fn) override + execute(std::function fn) override { return ctx.execute(std::move(fn)); } @@ -325,7 +326,7 @@ private: impl::ErasedOperation scheduleAfter( std::chrono::milliseconds delay, - std::function fn + std::function fn ) override { return ctx.scheduleAfter(delay, std::move(fn)); @@ -334,14 +335,17 @@ private: impl::ErasedOperation scheduleAfter( std::chrono::milliseconds delay, - std::function fn + std::function fn ) override { return ctx.scheduleAfter(delay, std::move(fn)); } impl::ErasedOperation - executeRepeatedly(std::chrono::milliseconds interval, std::function fn) override + executeRepeatedly( + std::chrono::milliseconds interval, + std::function fn + ) override { return ctx.executeRepeatedly(interval, std::move(fn)); } diff --git a/src/util/async/AnyOperation.hpp b/src/util/async/AnyOperation.hpp index b6b8846cb..8bdf40dd9 100644 --- a/src/util/async/AnyOperation.hpp +++ b/src/util/async/AnyOperation.hpp @@ -1,6 +1,7 @@ #pragma once #include "util/async/Error.hpp" +#include "util/async/impl/Any.hpp" #include "util/async/impl/ErasedOperation.hpp" #include diff --git a/src/util/async/AnyStopToken.hpp b/src/util/async/AnyStopToken.hpp index 128e08d73..b52b7db47 100644 --- a/src/util/async/AnyStopToken.hpp +++ b/src/util/async/AnyStopToken.hpp @@ -54,7 +54,7 @@ public: /** * @brief Check if stop is requested * - * @returns true if stop is requested; false otherwise + * @return true if stop is requested; false otherwise */ [[nodiscard]] bool isStopRequested() const noexcept @@ -65,7 +65,7 @@ public: /** * @brief Check if stop is requested * - * @returns true if stop is requested; false otherwise + * @return true if stop is requested; false otherwise */ [[nodiscard]] operator bool() const noexcept @@ -77,7 +77,7 @@ public: * @brief Get the underlying boost::asio::yield_context * @note ASSERTs if the stop token is not convertible to boost::asio::yield_context * - * @returns The underlying boost::asio::yield_context + * @return The underlying boost::asio::yield_context */ [[nodiscard]] operator boost::asio::yield_context() const diff --git a/src/util/async/AnyStrand.hpp b/src/util/async/AnyStrand.hpp index 5e0d53edc..acf3b59c9 100644 --- a/src/util/async/AnyStrand.hpp +++ b/src/util/async/AnyStrand.hpp @@ -3,6 +3,7 @@ #include "util/async/AnyOperation.hpp" #include "util/async/AnyStopToken.hpp" #include "util/async/Concepts.hpp" +#include "util/async/impl/Any.hpp" #include "util/async/impl/ErasedOperation.hpp" #include @@ -46,10 +47,10 @@ public: execute(SomeHandlerWithoutStopToken auto&& fn) { using RetType = std::decay_t>; - static_assert(not std::is_same_v); + static_assert(not std::is_same_v); return AnyOperation( // - pimpl_->execute([fn = std::forward(fn)] mutable -> std::any { + pimpl_->execute([fn = std::forward(fn)] mutable -> impl::Any { if constexpr (std::is_void_v) { std::invoke(std::forward(fn)); return {}; @@ -70,11 +71,11 @@ public: execute(SomeHandlerWith auto&& fn) { using RetType = std::decay_t>; - static_assert(not std::is_same_v); + static_assert(not std::is_same_v); return AnyOperation( // pimpl_->execute( - [fn = std::forward(fn)](auto stopToken) mutable -> std::any { + [fn = std::forward(fn)](auto stopToken) mutable -> impl::Any { if constexpr (std::is_void_v) { std::invoke(std::forward(fn), std::move(stopToken)); return {}; @@ -99,11 +100,11 @@ public: execute(SomeHandlerWith auto&& fn, SomeStdDuration auto timeout) { using RetType = std::decay_t>; - static_assert(not std::is_same_v); + static_assert(not std::is_same_v); return AnyOperation( // pimpl_->execute( - [fn = std::forward(fn)](auto stopToken) mutable -> std::any { + [fn = std::forward(fn)](auto stopToken) mutable -> impl::Any { if constexpr (std::is_void_v) { std::invoke(std::forward(fn), std::move(stopToken)); return {}; @@ -129,12 +130,12 @@ public: executeRepeatedly(SomeStdDuration auto interval, SomeHandlerWithoutStopToken auto&& fn) { using RetType = std::decay_t>; - static_assert(not std::is_same_v); + static_assert(not std::is_same_v); auto const millis = std::chrono::duration_cast(interval); return AnyOperation( // pimpl_->executeRepeatedly( - millis, [fn = std::forward(fn)] mutable -> std::any { + millis, [fn = std::forward(fn)] mutable -> impl::Any { std::invoke(std::forward(fn)); return {}; } @@ -160,12 +161,12 @@ private: [[nodiscard]] virtual impl::ErasedOperation execute( - std::function, + std::function, std::optional timeout = std::nullopt ) = 0; - [[nodiscard]] virtual impl::ErasedOperation execute(std::function) = 0; + [[nodiscard]] virtual impl::ErasedOperation execute(std::function) = 0; [[nodiscard]] virtual impl::ErasedOperation - executeRepeatedly(std::chrono::milliseconds, std::function) = 0; + executeRepeatedly(std::chrono::milliseconds, std::function) = 0; virtual void submit(std::function) = 0; }; @@ -181,7 +182,7 @@ private: [[nodiscard]] impl::ErasedOperation execute( - std::function fn, + std::function fn, std::optional timeout ) override { @@ -189,13 +190,16 @@ private: } [[nodiscard]] impl::ErasedOperation - execute(std::function fn) override + execute(std::function fn) override { return strand.execute(std::move(fn)); } impl::ErasedOperation - executeRepeatedly(std::chrono::milliseconds interval, std::function fn) override + executeRepeatedly( + std::chrono::milliseconds interval, + std::function fn + ) override { return strand.executeRepeatedly(interval, std::move(fn)); } diff --git a/src/util/async/Error.hpp b/src/util/async/Error.hpp index 716f18c9f..273ea223a 100644 --- a/src/util/async/Error.hpp +++ b/src/util/async/Error.hpp @@ -6,11 +6,6 @@ #include #include -// for the static_assert at the bottom which fixes clang compilation: -// see: https://godbolt.org/z/fzTjMd7G1 vs https://godbolt.org/z/jhKG7deen -#include -#include - namespace util::async { /** @@ -49,7 +44,4 @@ struct ExecutionError { std::string message; }; -// these are not the droids you are looking for... -static_assert(std::is_copy_constructible_v>); - } // namespace util::async diff --git a/src/util/async/Operation.hpp b/src/util/async/Operation.hpp index 38afaab17..efcfe2374 100644 --- a/src/util/async/Operation.hpp +++ b/src/util/async/Operation.hpp @@ -28,7 +28,7 @@ protected: std::future future_; public: - using DataType = typename OutcomeType::DataType; + using DataType = OutcomeType::DataType; explicit BasicOperation(OutcomeType* outcome) : future_{outcome->getStdFuture()} { @@ -77,7 +77,7 @@ struct BasicScheduledOperation : util::MoveTracker { }; std::shared_ptr state = std::make_shared(); - typename CtxType::Timer timer; + CtxType::Timer timer; BasicScheduledOperation(auto& executor, auto delay, auto&& fn) : timer( @@ -177,7 +177,9 @@ public: StoppableOperation& operator=(StoppableOperation&&) = default; - /** @brief Requests the operation to stop */ + /** + * @brief Requests the operation to stop + */ void requestStop() noexcept { diff --git a/src/util/async/context/BasicExecutionContext.hpp b/src/util/async/context/BasicExecutionContext.hpp index d08de5d99..45f1c3114 100644 --- a/src/util/async/context/BasicExecutionContext.hpp +++ b/src/util/async/context/BasicExecutionContext.hpp @@ -119,21 +119,22 @@ class BasicExecutionContext : public ExecutionContextTag { /** @endcond */ public: - /** @brief Whether operations on this execution context are noexcept */ - static constexpr bool kIS_NOEXCEPT = - noexcept(ErrorHandlerType::wrap([](auto&) { throw 0; })) and + /** + * @brief Whether operations on this execution context are noexcept + */ + static constexpr bool kIsNoexcept = noexcept(ErrorHandlerType::wrap([](auto&) { throw 0; })) and noexcept(ErrorHandlerType::catchAndAssert([] { throw 0; })); using ContextHolderType = ContextType; - using ExecutorType = typename ContextHolderType::Executor; + using ExecutorType = ContextHolderType::Executor; template using ValueType = std::expected; using StopSource = StopSourceType; - using StopToken = typename StopSourceType::Token; + using StopToken = StopSourceType::Token; template using StoppableOperation = StoppableOperation, StopSourceType>; @@ -148,7 +149,7 @@ public: TimerContextProvider, ErrorHandlerType>; - using Timer = typename ContextHolderType::Timer; + using Timer = ContextHolderType::Timer; // note: scheduled operations are always stoppable template @@ -190,7 +191,7 @@ public: SomeStdDuration auto delay, SomeHandlerWith auto&& fn, std::optional timeout = std::nullopt - ) noexcept(kIS_NOEXCEPT) + ) noexcept(kIsNoexcept) { if constexpr (not std::is_same_v< decltype(TimerContextProvider::getContext(*this)), @@ -235,7 +236,7 @@ public: SomeStdDuration auto delay, SomeHandlerWith auto&& fn, std::optional timeout = std::nullopt - ) noexcept(kIS_NOEXCEPT) + ) noexcept(kIsNoexcept) { if constexpr (not std::is_same_v< decltype(TimerContextProvider::getContext(*this)), @@ -283,7 +284,7 @@ public: executeRepeatedly( SomeStdDuration auto interval, SomeHandlerWithoutStopToken auto&& fn - ) noexcept(kIS_NOEXCEPT) + ) noexcept(kIsNoexcept) { if constexpr (not std::is_same_v< decltype(TimerContextProvider::getContext(*this)), @@ -309,7 +310,7 @@ public: execute( SomeHandlerWith auto&& fn, std::optional timeout = std::nullopt - ) noexcept(kIS_NOEXCEPT) + ) noexcept(kIsNoexcept) { return DispatcherType::dispatch( context_, @@ -343,7 +344,7 @@ public: */ [[nodiscard]] auto execute(SomeHandlerWith auto&& fn, SomeStdDuration auto timeout) noexcept( - kIS_NOEXCEPT + kIsNoexcept ) { return execute( @@ -360,7 +361,7 @@ public: * @return A unstoppable operation that can be used to wait for the result */ [[nodiscard]] auto - execute(SomeHandlerWithoutStopToken auto&& fn) noexcept(kIS_NOEXCEPT) + execute(SomeHandlerWithoutStopToken auto&& fn) noexcept(kIsNoexcept) { return DispatcherType::dispatch( context_, @@ -384,7 +385,7 @@ public: * @param fn The block of code to execute */ void - submit(SomeHandlerWithoutStopToken auto&& fn) noexcept(kIS_NOEXCEPT) + submit(SomeHandlerWithoutStopToken auto&& fn) noexcept(kIsNoexcept) { DispatcherType::post(context_, ErrorHandlerType::catchAndAssert(fn)); } @@ -426,7 +427,7 @@ public: * * @return Reference to the underlying executor */ - typename ContextType::Executor& + ContextType::Executor& getExecutor() { return context_.getExecutor(); diff --git a/src/util/async/context/SystemExecutionContext.hpp b/src/util/async/context/SystemExecutionContext.hpp index cb9ec0c3a..01eb2ac9e 100644 --- a/src/util/async/context/SystemExecutionContext.hpp +++ b/src/util/async/context/SystemExecutionContext.hpp @@ -20,8 +20,8 @@ public: [[nodiscard]] static auto& instance() { - static util::async::PoolExecutionContext kSYSTEM_EXECUTION_CONTEXT{}; - return kSYSTEM_EXECUTION_CONTEXT; + static util::async::PoolExecutionContext kSystemExecutionContext{}; + return kSystemExecutionContext; } }; diff --git a/src/util/async/context/impl/Strand.hpp b/src/util/async/context/impl/Strand.hpp index f5db35cae..75c359c39 100644 --- a/src/util/async/context/impl/Strand.hpp +++ b/src/util/async/context/impl/Strand.hpp @@ -23,17 +23,17 @@ template < typename ErrorHandlerType = impl::DefaultErrorHandler> class BasicStrand { std::reference_wrapper parentContext_; - typename ParentContextType::ContextHolderType::Strand context_; + ParentContextType::ContextHolderType::Strand context_; friend AssociatedExecutorExtractor; public: - static constexpr bool kIS_NOEXCEPT = noexcept(ErrorHandlerType::wrap([](auto&) { throw 0; })); + static constexpr bool kIsNoexcept = noexcept(ErrorHandlerType::wrap([](auto&) { throw 0; })); - using ContextHolderType = typename ParentContextType::ContextHolderType::Strand; - using ExecutorType = typename ContextHolderType::Executor; - using StopToken = typename StopSourceType::Token; - using Timer = typename ParentContextType::ContextHolderType::Timer; // timers are associated - // with the parent context + using ContextHolderType = ParentContextType::ContextHolderType::Strand; + using ExecutorType = ContextHolderType::Executor; + using StopToken = StopSourceType::Token; + using Timer = ParentContextType::ContextHolderType::Timer; // timers are associated + // with the parent context using RepeatedOperation = RepeatingOperation; BasicStrand(ParentContextType& parent, auto&& strand) @@ -50,7 +50,7 @@ public: execute( SomeHandlerWith auto&& fn, std::optional timeout = std::nullopt - ) noexcept(kIS_NOEXCEPT) + ) noexcept(kIsNoexcept) { return DispatcherType::dispatch( context_, @@ -77,7 +77,7 @@ public: [[nodiscard]] auto execute(SomeHandlerWith auto&& fn, SomeStdDuration auto timeout) noexcept( - kIS_NOEXCEPT + kIsNoexcept ) { return execute( @@ -87,7 +87,7 @@ public: } [[nodiscard]] auto - execute(SomeHandlerWithoutStopToken auto&& fn) noexcept(kIS_NOEXCEPT) + execute(SomeHandlerWithoutStopToken auto&& fn) noexcept(kIsNoexcept) { return DispatcherType::dispatch( context_, @@ -108,7 +108,7 @@ public: executeRepeatedly( SomeStdDuration auto interval, SomeHandlerWithoutStopToken auto&& fn - ) noexcept(kIS_NOEXCEPT) + ) noexcept(kIsNoexcept) { if constexpr (not std::is_same_v< decltype(TimerContextProvider::getContext(*this)), @@ -124,7 +124,7 @@ public: } void - submit(SomeHandlerWithoutStopToken auto&& fn) noexcept(kIS_NOEXCEPT) + submit(SomeHandlerWithoutStopToken auto&& fn) noexcept(kIsNoexcept) { DispatcherType::post(context_, ErrorHandlerType::catchAndAssert(fn)); } diff --git a/src/util/async/context/impl/Utils.hpp b/src/util/async/context/impl/Utils.hpp index 58307ce2a..e1998397b 100644 --- a/src/util/async/context/impl/Utils.hpp +++ b/src/util/async/context/impl/Utils.hpp @@ -16,7 +16,7 @@ namespace util::async::impl { inline constexpr struct AssociatedExecutorExtractor { template - [[nodiscard]] typename CtxType::ExecutorType& + [[nodiscard]] CtxType::ExecutorType& operator()(CtxType& ctx) const noexcept { return ctx.context_.getExecutor(); @@ -31,7 +31,7 @@ getTimeoutHandleIfNeeded( SomeStopSource auto& stopSource ) { - using TimerType = typename CtxType::Timer; + using TimerType = CtxType::Timer; std::optional timer; if (timeout) { timer.emplace(extractAssociatedExecutor(ctx), *timeout, [&stopSource](auto cancelled) { diff --git a/src/util/async/impl/Any.hpp b/src/util/async/impl/Any.hpp new file mode 100644 index 000000000..18089399f --- /dev/null +++ b/src/util/async/impl/Any.hpp @@ -0,0 +1,41 @@ +#pragma once + +#include +#include + +namespace util::async::impl { + +/** + * @brief A wrapper for std::any used as the type-erased transport for async operation results. + * + * It exists to work around a recursive-constraint failure in libstdc++'s `` when the + * value type is a raw `std::any`: `std::any`'s greedy templated constructor makes + * `std::expected` ask whether `std::any` is constructible from + * `std::expected`, which re-enters the same constraint. Newer Clang rejects this as + * self-referential. + * + * `Any` only allows construction from `std::any` (never from an `expected`), which breaks the cycle + * while still allowing transparent unwrapping back to `std::any&`. + */ +class Any { + std::any value_; + +public: + Any() = default; + Any(Any const&) = default; + + Any(Any&&) = default; + // note: this needs to be `auto` instead of `std::any` because of a bug in gcc 11.4 + Any(auto&& v) + requires(std::is_same_v, std::any>) + : value_{std::forward(v)} + { + } + + operator std::any&() noexcept + { + return value_; + } +}; + +} // namespace util::async::impl diff --git a/src/util/async/impl/ErasedOperation.hpp b/src/util/async/impl/ErasedOperation.hpp index 4ac97a661..8fbb9292d 100644 --- a/src/util/async/impl/ErasedOperation.hpp +++ b/src/util/async/impl/ErasedOperation.hpp @@ -3,8 +3,8 @@ #include "util/Assert.hpp" #include "util/async/Concepts.hpp" #include "util/async/Error.hpp" +#include "util/async/impl/Any.hpp" -#include #include #include #include @@ -37,7 +37,7 @@ public: pimpl_->wait(); } - std::expected + std::expected get() { return pimpl_->get(); @@ -64,7 +64,7 @@ private: virtual void wait() noexcept = 0; - virtual std::expected + virtual std::expected get() = 0; virtual void abort() = 0; @@ -93,14 +93,14 @@ private: } } - std::expected + std::expected get() override { if constexpr (not SomeOperationWithData) { ASSERT(false, "Called get() on an operation that does not support it"); std::unreachable(); } else { - // Note: return type of the operation was already wrapped to std::any by + // Note: return type of the operation was already wrapped to impl::Any by // AnyExecutionContext return operation.get(); } diff --git a/src/util/build/Build.cpp b/src/util/build/Build.cpp index d92fbf057..9a8773dc7 100644 --- a/src/util/build/Build.cpp +++ b/src/util/build/Build.cpp @@ -17,44 +17,44 @@ namespace util::build { #error "BUILD_DATE must be defined" #endif -static constexpr char kVERSION_STRING[] = CLIO_VERSION; -static constexpr char kGIT_COMMIT_HASH[] = GIT_COMMIT_HASH; -static constexpr char kGIT_BUILD_BRANCH[] = GIT_BUILD_BRANCH; -static constexpr char kBUILD_DATE[] = BUILD_DATE; +static constexpr char kVersionString[] = CLIO_VERSION; +static constexpr char kGitCommitHash[] = GIT_COMMIT_HASH; +static constexpr char kGitBuildBranch[] = GIT_BUILD_BRANCH; +static constexpr char kBuildDate[] = BUILD_DATE; std::string const& getClioVersionString() { - static std::string const kVALUE = kVERSION_STRING; - return kVALUE; + static std::string const kValue = kVersionString; + return kValue; } std::string const& getClioFullVersionString() { - static std::string const kVALUE = "clio-" + getClioVersionString(); - return kVALUE; + static std::string const kValue = "clio-" + getClioVersionString(); + return kValue; } std::string const& getGitCommitHash() { - static std::string const kVALUE = kGIT_COMMIT_HASH; - return kVALUE; + static std::string const kValue = kGitCommitHash; + return kValue; } std::string const& getGitBuildBranch() { - static std::string const kVALUE = kGIT_BUILD_BRANCH; - return kVALUE; + static std::string const kValue = kGitBuildBranch; + return kValue; } std::string const& getBuildDate() { - static std::string const kVALUE = kBUILD_DATE; - return kVALUE; + static std::string const kValue = kBuildDate; + return kValue; } } // namespace util::build diff --git a/src/util/config/Array.cpp b/src/util/config/Array.cpp index e274a696e..44a132924 100644 --- a/src/util/config/Array.cpp +++ b/src/util/config/Array.cpp @@ -20,10 +20,10 @@ Array::Array(ConfigValue arg) : itemPattern_{std::move(arg)} std::string_view Array::prefix(std::string_view key) { - static constexpr std::string_view kARRAY_SUFFIX = ".[]"; - ASSERT(key.contains(kARRAY_SUFFIX), "Provided key is not an array key: {}", key); + static constexpr std::string_view kArraySuffix = ".[]"; + ASSERT(key.contains(kArraySuffix), "Provided key is not an array key: {}", key); - return key.substr(0, key.rfind(kARRAY_SUFFIX) + kARRAY_SUFFIX.size()); + return key.substr(0, key.rfind(kArraySuffix) + kArraySuffix.size()); } std::optional diff --git a/src/util/config/ConfigConstraints.cpp b/src/util/config/ConfigConstraints.cpp index 82a8ec0b1..4c384e138 100644 --- a/src/util/config/ConfigConstraints.cpp +++ b/src/util/config/ConfigConstraints.cpp @@ -36,7 +36,7 @@ PortConstraint::checkValueImpl(Value const& port) const } else { p = static_cast(std::get(port)); } - if (p >= kPORT_MIN && p <= kPORT_MAX) + if (p >= kPortMin && p <= kPortMax) return std::nullopt; return Error{"Port does not satisfy the constraint bounds"}; } @@ -57,11 +57,11 @@ ValidIPConstraint::checkValueImpl(Value const& ip) const if (not errorCode.failed()) return std::nullopt; - static std::regex const kHOST{ + static std::regex const kHost{ R"regex(^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$)regex" }; - if (std::regex_match(std::get(ip), kHOST)) + if (std::regex_match(std::get(ip), kHost)) return std::nullopt; return Error{"Ip is not a valid ip address or hostname"}; diff --git a/src/util/config/ConfigConstraints.hpp b/src/util/config/ConfigConstraints.hpp index bf60e50d0..766d96cef 100644 --- a/src/util/config/ConfigConstraints.hpp +++ b/src/util/config/ConfigConstraints.hpp @@ -26,7 +26,7 @@ class ConfigValue; /** * @brief specific values that are accepted for logger levels in config. */ -static constexpr std::array kLOG_LEVELS = { +static constexpr std::array kLogLevels = { "trace", "debug", "info", @@ -38,7 +38,7 @@ static constexpr std::array kLOG_LEVELS = { /** * @brief specific values that are accepted for logger tag style in config. */ -static constexpr std::array kLOG_TAGS = { +static constexpr std::array kLogTags = { "int", "uint", "null", @@ -49,7 +49,7 @@ static constexpr std::array kLOG_TAGS = { /** * @brief specific values that are accepted for cache loading in config. */ -static constexpr std::array kLOAD_CACHE_MODE = { +static constexpr std::array kLoadCacheMode = { "sync", "async", "none", @@ -58,17 +58,17 @@ static constexpr std::array kLOAD_CACHE_MODE = { /** * @brief specific values that are accepted for database type in config. */ -static constexpr std::array kDATABASE_TYPE = {"cassandra"}; +static constexpr std::array kDatabaseType = {"cassandra"}; /** * @brief specific values that are accepted for server's processing_policy in config. */ -static constexpr std::array kPROCESSING_POLICY = {"parallel", "sequent"}; +static constexpr std::array kProcessingPolicy = {"parallel", "sequent"}; /** * @brief specific values that are accepted for database provider in config. */ -static constexpr std::array kPROVIDER = {"cassandra", "aws_keyspace"}; +static constexpr std::array kProvider = {"cassandra", "aws_keyspace"}; /** * @brief An interface to enforce constraints on certain values within ClioConfigDefinition. @@ -199,12 +199,12 @@ private: print(std::ostream& stream) const override { stream << fmt::format( - "The minimum value is `{}`. The maximum value is `{}`.", kPORT_MIN, kPORT_MAX + "The minimum value is `{}`. The maximum value is `{}`.", kPortMin, kPortMax ); } - static constexpr uint32_t kPORT_MIN = 1; - static constexpr uint32_t kPORT_MAX = 65535; + static constexpr uint32_t kPortMin = 1; + static constexpr uint32_t kPortMax = 65535; }; /** @@ -462,13 +462,13 @@ private: static constinit PortConstraint gValidatePort{}; static constinit ValidIPConstraint gValidateIp{}; -static constinit OneOf gValidateChannelName{"channel", Logger::kCHANNELS}; -static constinit OneOf gValidateLogLevelName{"log.level", kLOG_LEVELS}; -static constinit OneOf gValidateCassandraName{"database.type", kDATABASE_TYPE}; -static constinit OneOf gValidateLoadMode{"cache.load", kLOAD_CACHE_MODE}; -static constinit OneOf gValidateLogTag{"log.tag_style", kLOG_TAGS}; -static constinit OneOf gValidateProcessingPolicy{"server.processing_policy", kPROCESSING_POLICY}; -static constinit OneOf gValidateProvider{"database.cassandra.provider", kPROVIDER}; +static constinit OneOf gValidateChannelName{"channel", Logger::kChannels}; +static constinit OneOf gValidateLogLevelName{"log.level", kLogLevels}; +static constinit OneOf gValidateCassandraName{"database.type", kDatabaseType}; +static constinit OneOf gValidateLoadMode{"cache.load", kLoadCacheMode}; +static constinit OneOf gValidateLogTag{"log.tag_style", kLogTags}; +static constinit OneOf gValidateProcessingPolicy{"server.processing_policy", kProcessingPolicy}; +static constinit OneOf gValidateProvider{"database.cassandra.provider", kProvider}; static constinit PositiveDouble gValidatePositiveDouble{}; @@ -498,8 +498,8 @@ static constinit NumberValueConstraint gValidateNonNegativeUint32{ std::numeric_limits::max() }; static constinit NumberValueConstraint gValidateApiVersion{ - rpc::kAPI_VERSION_MIN, - rpc::kAPI_VERSION_MAX + rpc::kApiVersionMin, + rpc::kApiVersionMax }; static constinit RpcNameConstraint gRpcNameConstraint{}; diff --git a/src/util/config/ConfigDefinition.cpp b/src/util/config/ConfigDefinition.cpp index e6a51177c..7166067fe 100644 --- a/src/util/config/ConfigDefinition.cpp +++ b/src/util/config/ConfigDefinition.cpp @@ -110,7 +110,7 @@ ClioConfigDefinition::toMilliseconds(float value) { ASSERT(value >= 0.0f, "Floating point value of seconds must be non-negative, got: {}", value); return std::chrono::milliseconds{ - std::lroundf(value * static_cast(util::kMILLISECONDS_PER_SECOND)) + std::lroundf(value * static_cast(util::kMillisecondsPerSecond)) }; } @@ -242,7 +242,7 @@ ClioConfigDefinition::parse(ConfigFileInterface const& config) ClioConfigDefinition& getClioConfig() { - static ClioConfigDefinition kCLIO_CONFIG{ + static ClioConfigDefinition kClioConfig{ {{"database.type", ConfigValue{ConfigType::String} .defaultValue("cassandra") @@ -444,15 +444,15 @@ getClioConfig() {"api_version.default", ConfigValue{ConfigType::Integer} - .defaultValue(rpc::kAPI_VERSION_DEFAULT) + .defaultValue(rpc::kApiVersionDefault) .withConstraint(gValidateApiVersion)}, {"api_version.min", ConfigValue{ConfigType::Integer} - .defaultValue(rpc::kAPI_VERSION_MIN) + .defaultValue(rpc::kApiVersionMin) .withConstraint(gValidateApiVersion)}, {"api_version.max", ConfigValue{ConfigType::Integer} - .defaultValue(rpc::kAPI_VERSION_MAX) + .defaultValue(rpc::kApiVersionMax) .withConstraint(gValidateApiVersion)}, {"migration.full_scan_threads", @@ -463,7 +463,7 @@ getClioConfig() ConfigValue{ConfigType::Integer}.defaultValue(100).withConstraint(gValidateUint32)}}, }; - return kCLIO_CONFIG; + return kClioConfig; } } // namespace util::config diff --git a/src/util/config/ConfigDescription.hpp b/src/util/config/ConfigDescription.hpp index a66b021ef..b0fee6c03 100644 --- a/src/util/config/ConfigDescription.hpp +++ b/src/util/config/ConfigDescription.hpp @@ -25,7 +25,9 @@ namespace util::config { */ struct ClioConfigDescription { public: - /** @brief Struct to represent a key-value pair*/ + /** + * @brief Struct to represent a key-value pair + */ struct KV { std::string_view key; std::string_view value; @@ -49,8 +51,8 @@ public: get(std::string_view key) { auto const itr = - std::ranges::find_if(kCONFIG_DESCRIPTION, [&](auto const& v) { return v.key == key; }); - ASSERT(itr != kCONFIG_DESCRIPTION.end(), "Key {} doesn't exist in config", key); + std::ranges::find_if(kConfigDescription, [&](auto const& v) { return v.key == key; }); + ASSERT(itr != kConfigDescription.end(), "Key {} doesn't exist in config", key); return itr->value; } @@ -95,9 +97,9 @@ public: static void writeConfigDescriptionToFile(std::ostream& file) { - file << kCONFIG_DESCRIPTION_HEADER; + file << kConfigDescriptionHeader; - for (auto const& [key, val] : kCONFIG_DESCRIPTION) { + for (auto const& [key, val] : kConfigDescription) { file << "\n### " << key << "\n\n"; // Every type of value is directed to operator<< in ConfigValue.hpp @@ -112,7 +114,7 @@ public: } private: - static constexpr auto kCONFIG_DESCRIPTION_HEADER = + static constexpr auto kConfigDescriptionHeader = R"(# Clio Config Description This document provides a list of all available Clio configuration properties in detail. @@ -125,7 +127,7 @@ This document provides a list of all available Clio configuration properties in ## Configuration Details )"; - static constexpr auto kCONFIG_DESCRIPTION = std::array{ + static constexpr auto kConfigDescription = std::array{ KV{.key = "database.type", .value = "Specifies the type of database used for storing and retrieving data required " "by the Clio server. Both " diff --git a/src/util/config/ConfigFileJson.hpp b/src/util/config/ConfigFileJson.hpp index e591353e6..a084733cb 100644 --- a/src/util/config/ConfigFileJson.hpp +++ b/src/util/config/ConfigFileJson.hpp @@ -15,7 +15,9 @@ namespace util::config { -/** @brief Json representation of config */ +/** + * @brief Json representation of config + */ class ConfigFileJson final : public ConfigFileInterface { boost::json::object jsonObject_; diff --git a/src/util/config/Error.hpp b/src/util/config/Error.hpp index 85453498c..92a3a6605 100644 --- a/src/util/config/Error.hpp +++ b/src/util/config/Error.hpp @@ -8,7 +8,9 @@ namespace util::config { -/** @brief Displays the different errors when parsing user config */ +/** + * @brief Displays the different errors when parsing user config + */ struct Error { /** * @brief Constructs an Error with a custom error message. diff --git a/src/util/config/Types.hpp b/src/util/config/Types.hpp index 381a7162e..16707e003 100644 --- a/src/util/config/Types.hpp +++ b/src/util/config/Types.hpp @@ -12,7 +12,9 @@ namespace util::config { -/** @brief Custom clio config types */ +/** + * @brief Custom clio config types + */ enum class ConfigType { Integer, String, Double, Boolean }; /** @@ -25,7 +27,9 @@ enum class ConfigType { Integer, String, Double, Boolean }; std::ostream& operator<<(std::ostream& stream, ConfigType type); -/** @brief Represents the supported Config Values */ +/** + * @brief Represents the supported Config Values + */ using Value = std::variant; /** diff --git a/src/util/log/Logger.cpp b/src/util/log/Logger.cpp index 2634fd478..7a28b3064 100644 --- a/src/util/log/Logger.cpp +++ b/src/util/log/Logger.cpp @@ -2,7 +2,6 @@ #include "util/Assert.hpp" #include "util/BytesConverter.hpp" -#include "util/SourceLocation.hpp" #include "util/config/ArrayView.hpp" #include "util/config/ConfigDefinition.hpp" #include "util/config/ObjectView.hpp" @@ -29,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -69,7 +69,7 @@ toSpdlogLevel(Severity sev) std::string_view toString(Severity sev) { - static constexpr std::array kLABELS = { + static constexpr std::array kLabels = { "TRC", "DBG", "NFO", @@ -78,7 +78,7 @@ toString(Severity sev) "FTL", }; - return kLABELS.at(static_cast(sev)); + return kLabels.at(static_cast(sev)); } } // namespace @@ -119,7 +119,7 @@ getSeverityLevel(std::string_view logLevel) class NonCriticalFormatter : public spdlog::formatter { public: NonCriticalFormatter(std::unique_ptr wrappedFormatter) - : wrapped_formatter_(std::move(wrappedFormatter)) + : wrappedFormatter_(std::move(wrappedFormatter)) { } @@ -128,18 +128,18 @@ public: { // Only format messages with severity less than critical if (msg.level != spdlog::level::critical) { - wrapped_formatter_->format(msg, dest); + wrappedFormatter_->format(msg, dest); } } [[nodiscard]] std::unique_ptr clone() const override { - return std::make_unique(wrapped_formatter_->clone()); + return std::make_unique(wrappedFormatter_->clone()); } private: - std::unique_ptr wrapped_formatter_; + std::unique_ptr wrappedFormatter_; }; /** @@ -215,7 +215,7 @@ static std::expected, std::string getMinSeverity(config::ClioConfigDefinition const& config, Severity defaultSeverity) { std::unordered_map minSeverity; - for (auto const& channel : Logger::kCHANNELS) + for (auto const& channel : Logger::kChannels) minSeverity[channel] = defaultSeverity; auto const overrides = config.getArray("log.channels"); @@ -225,7 +225,7 @@ getMinSeverity(config::ClioConfigDefinition const& config, Severity defaultSever ++it) { auto const& channelConfig = *it; auto const name = channelConfig.get("channel"); - if (not std::ranges::contains(Logger::kCHANNELS, name)) { + if (not std::ranges::contains(Logger::kChannels, name)) { return std::unexpected{ fmt::format("Can't override settings for log channel {}: invalid channel", name) }; @@ -258,9 +258,9 @@ LogServiceState::init( }); if (isAsync) { - static constexpr size_t kQUEUE_SIZE = 8192; - static constexpr size_t kTHREAD_COUNT = 1; - spdlog::init_thread_pool(kQUEUE_SIZE, kTHREAD_COUNT); + static constexpr size_t kQueueSize = 8192; + static constexpr size_t kThreadCount = 1; + spdlog::init_thread_pool(kQueueSize, kThreadCount); } } @@ -382,7 +382,7 @@ LogService::init(config::ClioConfigDefinition const& config) auto const minSeverity = std::move(maybeMinSeverity).value(); // Create loggers for each channel - for (auto const& channel : Logger::kCHANNELS) { + for (auto const& channel : Logger::kChannels) { auto const it = minSeverity.find(channel); auto const severity = (it != minSeverity.end()) ? it->second : defaultSeverity_; registerLogger(channel, severity); @@ -405,37 +405,37 @@ LogService::shutdown() } Logger::Pump -LogService::trace(SourceLocationType const& loc) +LogService::trace(std::source_location const& loc) { return Logger(spdlog::default_logger()).trace(loc); } Logger::Pump -LogService::debug(SourceLocationType const& loc) +LogService::debug(std::source_location const& loc) { return Logger(spdlog::default_logger()).debug(loc); } Logger::Pump -LogService::info(SourceLocationType const& loc) +LogService::info(std::source_location const& loc) { return Logger(spdlog::default_logger()).info(loc); } Logger::Pump -LogService::warn(SourceLocationType const& loc) +LogService::warn(std::source_location const& loc) { return Logger(spdlog::default_logger()).warn(loc); } Logger::Pump -LogService::error(SourceLocationType const& loc) +LogService::error(std::source_location const& loc) { return Logger(spdlog::default_logger()).error(loc); } Logger::Pump -LogService::fatal(SourceLocationType const& loc) +LogService::fatal(std::source_location const& loc) { return Logger(spdlog::default_logger()).fatal(loc); } @@ -454,14 +454,14 @@ Logger::Logger(std::string_view const channel) : logger_(LogServiceState::regist Logger::~Logger() { // One reference is held by logger_ and the other by spdlog registry - static constexpr size_t kLAST_LOGGER_REF_COUNT = 2; + static constexpr size_t kLastLoggerRefCount = 2; if (logger_ == nullptr) { return; } - bool const isDynamic = !std::ranges::contains(kCHANNELS, logger_->name()); - if (isDynamic && logger_.use_count() == kLAST_LOGGER_REF_COUNT) { + bool const isDynamic = !std::ranges::contains(kChannels, logger_->name()); + if (isDynamic && logger_.use_count() == kLastLoggerRefCount) { spdlog::drop(logger_->name()); } } @@ -469,7 +469,7 @@ Logger::~Logger() Logger::Pump::Pump( std::shared_ptr logger, Severity sev, - SourceLocationType const& loc + std::source_location const& loc ) : logger_(std::move(logger)) , severity_(sev) @@ -489,32 +489,32 @@ Logger::Pump::~Pump() } Logger::Pump -Logger::trace(SourceLocationType const& loc) const +Logger::trace(std::source_location const& loc) const { return {logger_, Severity::TRC, loc}; } Logger::Pump -Logger::debug(SourceLocationType const& loc) const +Logger::debug(std::source_location const& loc) const { return {logger_, Severity::DBG, loc}; } Logger::Pump -Logger::info(SourceLocationType const& loc) const +Logger::info(std::source_location const& loc) const { return {logger_, Severity::NFO, loc}; } Logger::Pump -Logger::warn(SourceLocationType const& loc) const +Logger::warn(std::source_location const& loc) const { return {logger_, Severity::WRN, loc}; } Logger::Pump -Logger::error(SourceLocationType const& loc) const +Logger::error(std::source_location const& loc) const { return {logger_, Severity::ERR, loc}; } Logger::Pump -Logger::fatal(SourceLocationType const& loc) const +Logger::fatal(std::source_location const& loc) const { return {logger_, Severity::FTL, loc}; } diff --git a/src/util/log/Logger.hpp b/src/util/log/Logger.hpp index 4dbe04715..9120cd5bc 100644 --- a/src/util/log/Logger.hpp +++ b/src/util/log/Logger.hpp @@ -1,13 +1,12 @@ #pragma once -#include "util/SourceLocation.hpp" - #include #include #include #include #include #include +#include #include #include #include @@ -47,9 +46,10 @@ class ClioConfigDefinition; * Note: Currently this introduces potential shadowing (unlikely). */ #ifndef COVERAGE_ENABLED -#define LOG(x) \ - if (auto clio_pump__ = x; not clio_pump__) { \ - } else \ +#define LOG(x) \ + if (auto clio_pump__ = x; not clio_pump__) \ + ; \ + else \ clio_pump__ #else #define LOG(x) x @@ -87,14 +87,14 @@ class Logger { class Pump final { std::shared_ptr logger_; Severity const severity_; - SourceLocationType const sourceLocation_; + std::source_location const sourceLocation_; std::ostringstream stream_; bool const enabled_; public: ~Pump(); - Pump(std::shared_ptr logger, Severity sev, SourceLocationType const& loc); + Pump(std::shared_ptr logger, Severity sev, std::source_location const& loc); Pump(Pump&&) = delete; Pump(Pump const&) = delete; @@ -130,7 +130,7 @@ class Logger { }; public: - static constexpr std::array kCHANNELS = { + static constexpr std::array kChannels = { "General", "WebServer", "Backend", @@ -169,7 +169,7 @@ public: * @return The pump to use for logging */ [[nodiscard]] Pump - trace(SourceLocationType const& loc = CURRENT_SRC_LOCATION) const; + trace(std::source_location const& loc = std::source_location::current()) const; /** * @brief Interface for logging at Severity::DBG severity @@ -178,7 +178,7 @@ public: * @return The pump to use for logging */ [[nodiscard]] Pump - debug(SourceLocationType const& loc = CURRENT_SRC_LOCATION) const; + debug(std::source_location const& loc = std::source_location::current()) const; /** * @brief Interface for logging at Severity::NFO severity @@ -187,7 +187,7 @@ public: * @return The pump to use for logging */ [[nodiscard]] Pump - info(SourceLocationType const& loc = CURRENT_SRC_LOCATION) const; + info(std::source_location const& loc = std::source_location::current()) const; /** * @brief Interface for logging at Severity::WRN severity @@ -196,7 +196,7 @@ public: * @return The pump to use for logging */ [[nodiscard]] Pump - warn(SourceLocationType const& loc = CURRENT_SRC_LOCATION) const; + warn(std::source_location const& loc = std::source_location::current()) const; /** * @brief Interface for logging at Severity::ERR severity @@ -205,7 +205,7 @@ public: * @return The pump to use for logging */ [[nodiscard]] Pump - error(SourceLocationType const& loc = CURRENT_SRC_LOCATION) const; + error(std::source_location const& loc = std::source_location::current()) const; /** * @brief Interface for logging at Severity::FTL severity @@ -214,7 +214,7 @@ public: * @return The pump to use for logging */ [[nodiscard]] Pump - fatal(SourceLocationType const& loc = CURRENT_SRC_LOCATION) const; + fatal(std::source_location const& loc = std::source_location::current()) const; private: Logger(std::shared_ptr logger); @@ -332,7 +332,7 @@ public: * @return The pump to use for logging */ [[nodiscard]] static Logger::Pump - trace(SourceLocationType const& loc = CURRENT_SRC_LOCATION); + trace(std::source_location const& loc = std::source_location::current()); /** * @brief Globally accessible General logger at Severity::DBG severity @@ -341,7 +341,7 @@ public: * @return The pump to use for logging */ [[nodiscard]] static Logger::Pump - debug(SourceLocationType const& loc = CURRENT_SRC_LOCATION); + debug(std::source_location const& loc = std::source_location::current()); /** * @brief Globally accessible General logger at Severity::NFO severity @@ -350,7 +350,7 @@ public: * @return The pump to use for logging */ [[nodiscard]] static Logger::Pump - info(SourceLocationType const& loc = CURRENT_SRC_LOCATION); + info(std::source_location const& loc = std::source_location::current()); /** * @brief Globally accessible General logger at Severity::WRN severity @@ -359,7 +359,7 @@ public: * @return The pump to use for logging */ [[nodiscard]] static Logger::Pump - warn(SourceLocationType const& loc = CURRENT_SRC_LOCATION); + warn(std::source_location const& loc = std::source_location::current()); /** * @brief Globally accessible General logger at Severity::ERR severity @@ -368,7 +368,7 @@ public: * @return The pump to use for logging */ [[nodiscard]] static Logger::Pump - error(SourceLocationType const& loc = CURRENT_SRC_LOCATION); + error(std::source_location const& loc = std::source_location::current()); /** * @brief Globally accessible General logger at Severity::FTL severity @@ -377,7 +377,7 @@ public: * @return The pump to use for logging */ [[nodiscard]] static Logger::Pump - fatal(SourceLocationType const& loc = CURRENT_SRC_LOCATION); + fatal(std::source_location const& loc = std::source_location::current()); private: /** diff --git a/src/util/prometheus/MetricsFamily.hpp b/src/util/prometheus/MetricsFamily.hpp index 6d26652fb..4e9142be5 100644 --- a/src/util/prometheus/MetricsFamily.hpp +++ b/src/util/prometheus/MetricsFamily.hpp @@ -20,7 +20,7 @@ namespace util::prometheus { class MetricsFamily { public: static std::unique_ptr - defaultMetricBuilder; /**< The default metric builder */ + defaultMetricBuilder; ///< The default metric builder /** * @brief Construct a new MetricsFamily object diff --git a/src/util/requests/RequestBuilder.cpp b/src/util/requests/RequestBuilder.cpp index fd3e3748e..ffb2a4b1f 100644 --- a/src/util/requests/RequestBuilder.cpp +++ b/src/util/requests/RequestBuilder.cpp @@ -12,7 +12,6 @@ #include #include #include -#include #include #include #include @@ -118,18 +117,16 @@ std::expected RequestBuilder::doSslRequest(asio::yield_context yield, beast::http::verb method) { auto streamData = impl::SslTcpStreamData::create(yield); - if (not streamData.has_value()) - return std::unexpected{std::move(streamData).error()}; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" - if (!SSL_set_tlsext_host_name(streamData->stream.native_handle(), host_.c_str())) { + if (!SSL_set_tlsext_host_name(streamData.stream.native_handle(), host_.c_str())) { #pragma GCC diagnostic pop beast::error_code errorCode; errorCode.assign(static_cast(::ERR_get_error()), asio::error::get_ssl_category()); return std::unexpected{RequestError{"SSL setup failed", errorCode}}; } - return doRequestImpl(std::move(streamData).value(), yield, method); + return doRequestImpl(std::move(streamData), yield, method); } std::expected @@ -185,7 +182,7 @@ RequestBuilder::doRequestImpl( request_.method(method); - if constexpr (StreamDataType::kSSL_ENABLED) { + if constexpr (StreamDataType::kSslEnabled) { beast::get_lowest_layer(stream).expires_after(timeout_); stream.async_handshake(asio::ssl::stream_base::client, yield[errorCode]); if (errorCode) diff --git a/src/util/requests/RequestBuilder.hpp b/src/util/requests/RequestBuilder.hpp index ad8622f6f..f701f7478 100644 --- a/src/util/requests/RequestBuilder.hpp +++ b/src/util/requests/RequestBuilder.hpp @@ -27,7 +27,7 @@ class RequestBuilder { util::Logger log_{"RequestBuilder"}; std::string host_; std::string port_; - std::chrono::milliseconds timeout_{kDEFAULT_TIMEOUT}; + std::chrono::milliseconds timeout_{kDefaultTimeout}; boost::beast::http::request request_; public: @@ -168,9 +168,9 @@ public: std::expected post(boost::asio::yield_context yield); - static constexpr std::chrono::milliseconds kDEFAULT_TIMEOUT{ + static constexpr std::chrono::milliseconds kDefaultTimeout{ 30000 - }; /**< Default timeout for requests */ + }; ///< Default timeout for requests private: std::expected diff --git a/src/util/requests/SslContext.cpp b/src/util/requests/SslContext.cpp new file mode 100644 index 000000000..a181d6fde --- /dev/null +++ b/src/util/requests/SslContext.cpp @@ -0,0 +1,16 @@ +#include "util/requests/SslContext.hpp" + +#include "util/requests/impl/SslContext.hpp" + +#include +#include + +namespace util::requests { + +std::expected +initClientSslContext() +{ + return impl::initClientSslContext(); +} + +} // namespace util::requests diff --git a/src/util/requests/SslContext.hpp b/src/util/requests/SslContext.hpp new file mode 100644 index 000000000..dffc5f9d5 --- /dev/null +++ b/src/util/requests/SslContext.hpp @@ -0,0 +1,21 @@ +#pragma once + +#include +#include + +namespace util::requests { + +/** + * @brief Create and cache the shared client SSL context. + * + * Intended to be called once during application startup so that an unrecoverable SSL + * misconfiguration (e.g. a missing system root certificate bundle) is reported immediately instead + * of causing every outgoing request to fail later. The context (including the potentially expensive + * parse of the root certificate bundle) is created once and reused for the lifetime of the process. + * + * @return An error message if the context could not be created + */ +std::expected +initClientSslContext(); + +} // namespace util::requests diff --git a/src/util/requests/WsConnection.cpp b/src/util/requests/WsConnection.cpp index 95b5eb833..dc3a44b36 100644 --- a/src/util/requests/WsConnection.cpp +++ b/src/util/requests/WsConnection.cpp @@ -80,12 +80,10 @@ std::expected WsConnectionBuilder::sslConnect(asio::yield_context yield) const { auto streamData = impl::SslWsStreamData::create(yield); - if (not streamData.has_value()) - return std::unexpected{std::move(streamData).error()}; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" - if (!SSL_set_tlsext_host_name(streamData->stream.next_layer().native_handle(), host_.c_str())) { + if (!SSL_set_tlsext_host_name(streamData.stream.next_layer().native_handle(), host_.c_str())) { #pragma GCC diagnostic pop beast::error_code errorCode; errorCode.assign( @@ -93,7 +91,7 @@ WsConnectionBuilder::sslConnect(asio::yield_context yield) const ); return std::unexpected{RequestError{"SSL setup failed", errorCode}}; } - return connectImpl(std::move(streamData).value(), yield); + return connectImpl(std::move(streamData), yield); } std::expected @@ -142,7 +140,7 @@ WsConnectionBuilder::connectImpl(StreamDataType&& streamData, asio::yield_contex if (errorCode) return std::unexpected{RequestError{"Connect error", errorCode}}; - if constexpr (StreamDataType::kSSL_ENABLED) { + if constexpr (StreamDataType::kSslEnabled) { beast::get_lowest_layer(ws).expires_after(connectionTimeout_); ws.next_layer().async_handshake(asio::ssl::stream_base::client, yield[errorCode]); if (errorCode) @@ -166,7 +164,7 @@ WsConnectionBuilder::connectImpl(StreamDataType&& streamData, asio::yield_contex if (errorCode) return std::unexpected{RequestError{"Handshake error", errorCode}}; - if constexpr (StreamDataType::kSSL_ENABLED) { + if constexpr (StreamDataType::kSslEnabled) { return std::make_unique(std::move(ws)); } else { return std::make_unique(std::move(ws)); diff --git a/src/util/requests/WsConnection.hpp b/src/util/requests/WsConnection.hpp index 709bd024f..55f353ea1 100644 --- a/src/util/requests/WsConnection.hpp +++ b/src/util/requests/WsConnection.hpp @@ -69,12 +69,10 @@ public: virtual std::optional close( boost::asio::yield_context yield, - std::chrono::steady_clock::duration timeout = kDEFAULT_TIMEOUT + std::chrono::steady_clock::duration timeout = kDefaultTimeout ) = 0; - static constexpr std::chrono::seconds kDEFAULT_TIMEOUT{ - 5 - }; /**< Default timeout for connecting */ + static constexpr std::chrono::seconds kDefaultTimeout{5}; ///< Default timeout for connecting }; using WsConnectionPtr = std::unique_ptr; @@ -86,8 +84,8 @@ class WsConnectionBuilder { std::string host_; std::string port_; std::vector headers_; - std::chrono::steady_clock::duration connectionTimeout_{kDEFAULT_TIMEOUT}; - std::chrono::steady_clock::duration wsHandshakeTimeout_{kDEFAULT_TIMEOUT}; + std::chrono::steady_clock::duration connectionTimeout_{kDefaultTimeout}; + std::chrono::steady_clock::duration wsHandshakeTimeout_{kDefaultTimeout}; std::string target_{"/"}; public: @@ -171,9 +169,7 @@ public: [[nodiscard]] std::expected connect(boost::asio::yield_context yield) const; - static constexpr std::chrono::seconds kDEFAULT_TIMEOUT{ - 5 - }; /**< Default timeout for connecting */ + static constexpr std::chrono::seconds kDefaultTimeout{5}; ///< Default timeout for connecting private: template diff --git a/src/util/requests/impl/SslContext.cpp b/src/util/requests/impl/SslContext.cpp index 511448a9c..6571f052f 100644 --- a/src/util/requests/impl/SslContext.cpp +++ b/src/util/requests/impl/SslContext.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -31,7 +32,7 @@ namespace { // Taken from https://go.dev/src/crypto/x509/root_linux.go -constexpr std::array kCERT_FILE_PATHS{ +constexpr std::array kCertFilePaths{ "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc. "/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL 6 "/etc/ssl/ca-bundle.pem", // OpenSUSE @@ -43,40 +44,83 @@ constexpr std::array kCERT_FILE_PATHS{ "/system/etc/security/cacerts", // Android }; -std::expected +std::optional +readCertificateFile(std::filesystem::path const& path) +{ + if (not std::filesystem::exists(path)) + return std::nullopt; + + std::ifstream const fileStream{path, std::ios::in}; + if (not fileStream.is_open()) + return std::nullopt; + + std::stringstream buffer; + buffer << fileStream.rdbuf(); + + return std::move(buffer).str(); +} + +std::optional getRootCertificate() { - for (auto const& path : kCERT_FILE_PATHS) { - if (std::filesystem::exists(path)) { - std::ifstream const fileStream{path, std::ios::in}; - if (not fileStream.is_open()) { - continue; - } - std::stringstream buffer; - buffer << fileStream.rdbuf(); - return std::move(buffer).str(); - } + // Honor the OpenSSL-standard SSL_CERT_FILE environment variable first. Some + // environments (e.g. the Nix-based CI/runtime image) point it at their CA + // bundle instead of installing certificates at the well-known system paths. + if (char const* const certFile = std::getenv("SSL_CERT_FILE"); certFile != nullptr) { + if (auto contents = readCertificateFile(certFile); contents.has_value()) + return contents; } - return std::unexpected{RequestError{"SSL setup failed: could not find root certificate"}}; + + for (auto const& path : kCertFilePaths) { + if (auto contents = readCertificateFile(path); contents.has_value()) + return contents; + } + + return std::nullopt; +} + +std::expected& +cachedClientSslContext() +{ + static std::expected context = + makeClientSslContext(getRootCertificate()); + return context; } } // namespace -std::expected -makeClientSslContext() +std::expected +makeClientSslContext(std::optional const& rootCertificate) { + if (not rootCertificate.has_value()) + return std::unexpected{RequestError{"SSL setup failed: could not find root certificate"}}; + ssl::context context{ssl::context::tls_client}; context.set_verify_mode(ssl::verify_peer); - auto const rootCertificate = getRootCertificate(); - if (not rootCertificate.has_value()) { - return std::unexpected{rootCertificate.error()}; - } - context.add_certificate_authority( + context.add_certificate_authority( // asio::buffer(rootCertificate->data(), rootCertificate->size()) ); + return context; } +std::expected +initClientSslContext() +{ + auto const& context = cachedClientSslContext(); + if (not context.has_value()) + return std::unexpected{context.error().message()}; + + return {}; +} + +ssl::context& +getClientSslContext() +{ + // initClientSslContext() called during startup + return cachedClientSslContext().value(); +} + std::optional sslErrorToString(boost::beast::error_code const& error) { @@ -89,8 +133,8 @@ sslErrorToString(boost::beast::error_code const& error) boost::lexical_cast(ERR_GET_REASON(error.value())) ); - static constexpr size_t kBUFFER_SIZE = 128; - char buf[kBUFFER_SIZE]; + static constexpr size_t kBufferSize = 128; + char buf[kBufferSize]; ::ERR_error_string_n(error.value(), buf, sizeof(buf)); errorString += buf; diff --git a/src/util/requests/impl/SslContext.hpp b/src/util/requests/impl/SslContext.hpp index e4705ee1d..c1056bcef 100644 --- a/src/util/requests/impl/SslContext.hpp +++ b/src/util/requests/impl/SslContext.hpp @@ -12,7 +12,13 @@ namespace util::requests::impl { std::expected -makeClientSslContext(); +makeClientSslContext(std::optional const& rootCertificate); + +std::expected +initClientSslContext(); + +boost::asio::ssl::context& +getClientSslContext(); std::optional sslErrorToString(boost::beast::error_code const& error); diff --git a/src/util/requests/impl/StreamData.hpp b/src/util/requests/impl/StreamData.hpp index 6834fb198..142cfbc93 100644 --- a/src/util/requests/impl/StreamData.hpp +++ b/src/util/requests/impl/StreamData.hpp @@ -1,6 +1,5 @@ #pragma once -#include "util/requests/Types.hpp" #include "util/requests/impl/SslContext.hpp" #include @@ -13,14 +12,11 @@ #include #include -#include -#include - namespace util::requests::impl { template struct PlainStreamData { - static constexpr bool kSSL_ENABLED = false; + static constexpr bool kSslEnabled = false; explicit PlainStreamData(boost::asio::yield_context yield) : stream(boost::asio::get_associated_executor(yield)) @@ -34,29 +30,19 @@ using TcpStreamData = PlainStreamData; using WsStreamData = PlainStreamData>; template -class SslStreamData { - boost::asio::ssl::context sslContext_; - -public: - static constexpr bool kSSL_ENABLED = true; - - static std::expected - create(boost::asio::yield_context yield) - { - auto sslContext = makeClientSslContext(); - if (not sslContext.has_value()) { - return std::unexpected{std::move(sslContext.error())}; - } - return SslStreamData{std::move(sslContext).value(), yield}; - } - +struct SslStreamData { + static constexpr bool kSslEnabled = true; StreamType stream; -private: - SslStreamData(boost::asio::ssl::context sslContext, boost::asio::yield_context yield) - : sslContext_(std::move(sslContext)) - , stream(boost::asio::get_associated_executor(yield), sslContext_) + static SslStreamData + create(boost::asio::yield_context yield) + { + return SslStreamData{getClientSslContext(), yield}; + } +private: + SslStreamData(boost::asio::ssl::context& sslContext, boost::asio::yield_context yield) + : stream(boost::asio::get_associated_executor(yield), sslContext) { } }; diff --git a/src/util/requests/impl/WsConnectionImpl.hpp b/src/util/requests/impl/WsConnectionImpl.hpp index eff8a654a..8df7a4a4a 100644 --- a/src/util/requests/impl/WsConnectionImpl.hpp +++ b/src/util/requests/impl/WsConnectionImpl.hpp @@ -88,7 +88,7 @@ public: std::optional close( boost::asio::yield_context yield, - std::chrono::steady_clock::duration const timeout = kDEFAULT_TIMEOUT + std::chrono::steady_clock::duration const timeout = kDefaultTimeout ) override { // Set the timeout for closing the connection diff --git a/src/web/AdminVerificationStrategy.cpp b/src/web/AdminVerificationStrategy.cpp index ca7687f00..fdb1cd4c0 100644 --- a/src/web/AdminVerificationStrategy.cpp +++ b/src/web/AdminVerificationStrategy.cpp @@ -6,7 +6,6 @@ #include -#include #include #include #include @@ -35,12 +34,12 @@ PasswordAdminVerificationStrategy::isAdmin(RequestHeader const& request, std::st return false; } auto userAuth = it->value(); - if (!userAuth.starts_with(kPASSWORD_PREFIX)) { + if (!userAuth.starts_with(kPasswordPrefix)) { // Invalid Authorization header return false; } - userAuth.remove_prefix(kPASSWORD_PREFIX.size()); + userAuth.remove_prefix(kPasswordPrefix.size()); return passwordSha256_ == util::toUpper(userAuth); } diff --git a/src/web/AdminVerificationStrategy.hpp b/src/web/AdminVerificationStrategy.hpp index d32ee3639..0f74639b4 100644 --- a/src/web/AdminVerificationStrategy.hpp +++ b/src/web/AdminVerificationStrategy.hpp @@ -60,7 +60,7 @@ public: /** * @brief The prefix for the password in the request header. */ - static constexpr std::string_view kPASSWORD_PREFIX = "Password "; + static constexpr std::string_view kPasswordPrefix = "Password "; /** * @brief Construct a new PasswordAdminVerificationStrategy object diff --git a/src/web/HttpSession.hpp b/src/web/HttpSession.hpp index c7f0d93e6..dbbeeff23 100644 --- a/src/web/HttpSession.hpp +++ b/src/web/HttpSession.hpp @@ -85,14 +85,18 @@ public: ~HttpSession() override = default; - /** @return The TCP stream */ + /** + * @return The TCP stream + */ boost::beast::tcp_stream& stream() { return stream_; } - /** @brief Starts reading from the stream. */ + /** + * @brief Starts reading from the stream. + */ void run() { @@ -104,7 +108,9 @@ public: ); } - /** @brief Closes the underlying socket. */ + /** + * @brief Closes the underlying socket. + */ void doClose() { @@ -112,7 +118,9 @@ public: stream_.socket().shutdown(tcp::socket::shutdown_send, ec); } - /** @brief Upgrade to WebSocket connection. */ + /** + * @brief Upgrade to WebSocket connection. + */ void upgrade() { diff --git a/src/web/PlainWsSession.hpp b/src/web/PlainWsSession.hpp index de53d1b10..87c555c4d 100644 --- a/src/web/PlainWsSession.hpp +++ b/src/web/PlainWsSession.hpp @@ -71,7 +71,9 @@ public: ~PlainWsSession() override = default; - /** @return The websocket stream. */ + /** + * @return The websocket stream. + */ StreamType& ws() { @@ -137,7 +139,9 @@ public: { } - /** @brief Initiate the upgrade. */ + /** + * @brief Initiate the upgrade. + */ void run() { @@ -155,8 +159,8 @@ private: { parser_.emplace(); - static constexpr auto kMAX_BODY_SIZE = 10000; - parser_->body_limit(kMAX_BODY_SIZE); + static constexpr auto kMaxBodySize = 10000; + parser_->body_limit(kMaxBodySize); boost::beast::get_lowest_layer(http_).expires_after(std::chrono::seconds(30)); onUpgrade(); diff --git a/src/web/ProxyIpResolver.cpp b/src/web/ProxyIpResolver.cpp index 04b82a294..5716a2ae3 100644 --- a/src/web/ProxyIpResolver.cpp +++ b/src/web/ProxyIpResolver.cpp @@ -57,7 +57,7 @@ ProxyIpResolver::resolveClientIp(std::string const& connectionIp, HttpHeaders co return extractClientIp(headers); } - if (auto it = headers.find(kPROXY_TOKEN_HEADER); it != headers.end()) { + if (auto it = headers.find(kProxyTokenHeader); it != headers.end()) { auto const tokenHash = util::sha256sum(it->value()); if (proxyTokens_.contains(tokenHash)) { return extractClientIp(headers); @@ -78,22 +78,22 @@ ProxyIpResolver::extractClientIp(HttpHeaders const& headers) // https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Forwarded#using_the_forwarded_header auto const headerValue = util::toLower(it->value()); - static constexpr std::string_view kFOR_PREFIX = "for="; - auto const startPos = headerValue.rfind(kFOR_PREFIX); + static constexpr std::string_view kForPrefix = "for="; + auto const startPos = headerValue.rfind(kForPrefix); if (startPos == std::string::npos) { return std::nullopt; } - auto value = it->value().substr(startPos + kFOR_PREFIX.size()); + auto value = it->value().substr(startPos + kForPrefix.size()); - static constexpr char kSECTION_DELIMITER = ';'; - static constexpr char kCHAIN_DELIMITER = ','; - auto const sectionEnd = value.find(kSECTION_DELIMITER); - auto const chainEnd = value.find(kCHAIN_DELIMITER); + static constexpr char kSectionDelimiter = ';'; + static constexpr char kChainDelimiter = ','; + auto const sectionEnd = value.find(kSectionDelimiter); + auto const chainEnd = value.find(kChainDelimiter); auto const endPos = std::min(sectionEnd, chainEnd); auto const ip = value.substr(0, endPos); - static constexpr auto kMIN_IP_LENGTH = 7; // minimum 3 dots + 4 digits - if (ip.size() < kMIN_IP_LENGTH) { + static constexpr auto kMinIpLength = 7; // minimum 3 dots + 4 digits + if (ip.size() < kMinIpLength) { return std::nullopt; } diff --git a/src/web/ProxyIpResolver.hpp b/src/web/ProxyIpResolver.hpp index 016e782ea..fc11fee0e 100644 --- a/src/web/ProxyIpResolver.hpp +++ b/src/web/ProxyIpResolver.hpp @@ -24,8 +24,8 @@ namespace web { */ class ProxyIpResolver { std::unordered_set proxyIps_; - // ripple::uint256 doesn't have hash implementation - std::unordered_set proxyTokens_; + // xrpl::uint256 doesn't have hash implementation + std::unordered_set proxyTokens_; public: /** @@ -52,7 +52,7 @@ public: using HttpHeaders = boost::beast::http::request::header_type; - static constexpr std::string_view kPROXY_TOKEN_HEADER = "X-Proxy-Token"; + static constexpr std::string_view kProxyTokenHeader = "X-Proxy-Token"; /** * @brief Resolves the client's IP address from the connection IP and HTTP headers. diff --git a/src/web/Resolver.hpp b/src/web/Resolver.hpp index fae02bd09..4674ba271 100644 --- a/src/web/Resolver.hpp +++ b/src/web/Resolver.hpp @@ -32,7 +32,7 @@ public: /** * @brief Resolve hostname to IP addresses. * - * @throw This method throws an exception when the hostname cannot be resolved. + * @throws This method throws an exception when the hostname cannot be resolved. * * @param hostname Hostname to resolve * @return IP addresses of the hostname @@ -43,7 +43,7 @@ public: /** * @brief Resolve to IP addresses with port. * - * @throw This method throws an exception when the hostname cannot be resolved. + * @throws This method throws an exception when the hostname cannot be resolved. * * @param hostname Hostname to resolve * @param service Service to resolve diff --git a/src/web/Server.hpp b/src/web/Server.hpp index a41b996af..d923d10e3 100644 --- a/src/web/Server.hpp +++ b/src/web/Server.hpp @@ -129,7 +129,9 @@ public: LOG(log_.info()) << "Detector failed (" << message << "): " << ec.message(); } - /** @brief Initiate the detection. */ + /** + * @brief Initiate the detection. + */ void run() { @@ -305,14 +307,18 @@ public: } } - /** @brief Start accepting incoming connections. */ + /** + * @brief Start accepting incoming connections. + */ void run() { doAccept(); } - /** @brief Stop accepting new connections */ + /** + * @brief Stop accepting new connections + */ void stop(boost::asio::yield_context) { @@ -359,7 +365,9 @@ private: } }; -/** @brief The final type of the HttpServer used by Clio. */ +/** + * @brief The final type of the HttpServer used by Clio. + */ template using HttpServer = Server; diff --git a/src/web/SslHttpSession.hpp b/src/web/SslHttpSession.hpp index 57e21359e..33168a41c 100644 --- a/src/web/SslHttpSession.hpp +++ b/src/web/SslHttpSession.hpp @@ -93,14 +93,18 @@ public: ~SslHttpSession() override = default; - /** @return The SSL stream. */ + /** + * @return The SSL stream. + */ boost::asio::ssl::stream& stream() { return stream_; } - /** @brief Initiates the handshake. */ + /** + * @brief Initiates the handshake. + */ void run() { @@ -135,7 +139,9 @@ public: this->doRead(); } - /** @brief Closes the underlying connection. */ + /** + * @brief Closes the underlying connection. + */ void doClose() { @@ -158,7 +164,9 @@ public: // At this point the connection is closed gracefully } - /** @brief Upgrades connection to secure websocket. */ + /** + * @brief Upgrades connection to secure websocket. + */ void upgrade() { diff --git a/src/web/SslWsSession.hpp b/src/web/SslWsSession.hpp index 50157a7d6..74c4e580f 100644 --- a/src/web/SslWsSession.hpp +++ b/src/web/SslWsSession.hpp @@ -72,7 +72,9 @@ public: ConnectionBase::isAdmin_ = isAdmin; // NOLINT(cppcoreguidelines-prefer-member-initializer) } - /** @return The secure websocket stream. */ + /** + * @return The secure websocket stream. + */ StreamType& ws() { @@ -139,7 +141,9 @@ public: ~SslWsUpgrader() = default; - /** @brief Initiate the upgrade. */ + /** + * @brief Initiate the upgrade. + */ void run() { @@ -160,8 +164,8 @@ private: parser_.emplace(); // Apply a reasonable limit to the allowed size of the body in bytes to prevent abuse. - static constexpr auto kMAX_BODY_SIZE = 10000; - parser_->body_limit(kMAX_BODY_SIZE); + static constexpr auto kMaxBodySize = 10000; + parser_->body_limit(kMaxBodySize); boost::beast::get_lowest_layer(https_).expires_after(std::chrono::seconds(30)); onUpgrade(); diff --git a/src/web/SubscriptionContext.hpp b/src/web/SubscriptionContext.hpp index a95c81979..8f2716ad0 100644 --- a/src/web/SubscriptionContext.hpp +++ b/src/web/SubscriptionContext.hpp @@ -74,7 +74,7 @@ public: * * @return The API subversion. */ - uint32_t + [[nodiscard]] uint32_t apiSubversion() const override; }; diff --git a/src/web/dosguard/DOSGuard.hpp b/src/web/dosguard/DOSGuard.hpp index 176bb4a88..8dcf2d367 100644 --- a/src/web/dosguard/DOSGuard.hpp +++ b/src/web/dosguard/DOSGuard.hpp @@ -31,8 +31,8 @@ class DOSGuard : public DOSGuardInterface { * @brief Accumulated state per IP, state will be reset accordingly */ struct ClientState { - std::uint32_t transferredByte = 0; /**< Accumulated transferred byte */ - std::uint32_t requestsCount = 0; /**< Accumulated served requests count */ + std::uint32_t transferredByte = 0; ///< Accumulated transferred byte + std::uint32_t requestsCount = 0; ///< Accumulated served requests count }; struct State { diff --git a/src/web/dosguard/WhitelistHandler.cpp b/src/web/dosguard/WhitelistHandler.cpp index 819ad8824..e7641d9b6 100644 --- a/src/web/dosguard/WhitelistHandler.cpp +++ b/src/web/dosguard/WhitelistHandler.cpp @@ -101,15 +101,15 @@ Whitelist::isInV6Subnet( bool Whitelist::isV4(std::string_view net) { - static std::regex const kIPV4_CIDR_REGEX(R"(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d{1,2}$)"); - return std::regex_match(std::string(net), kIPV4_CIDR_REGEX); + static std::regex const kIpV4CidrRegex(R"(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d{1,2}$)"); + return std::regex_match(std::string(net), kIpV4CidrRegex); } bool Whitelist::isV6(std::string_view net) { - static std::regex const kIPV6_CIDR_REGEX(R"(^([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}/\d{1,3}$)"); - return std::regex_match(std::string(net), kIPV6_CIDR_REGEX); + static std::regex const kIpV6CidrRegex(R"(^([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}/\d{1,3}$)"); + return std::regex_match(std::string(net), kIpV6CidrRegex); } bool diff --git a/src/web/dosguard/WhitelistHandlerInterface.hpp b/src/web/dosguard/WhitelistHandlerInterface.hpp index b666b102f..82c0939df 100644 --- a/src/web/dosguard/WhitelistHandlerInterface.hpp +++ b/src/web/dosguard/WhitelistHandlerInterface.hpp @@ -9,7 +9,9 @@ namespace web::dosguard { */ class WhitelistHandlerInterface { public: - /** @brief Virtual destructor */ + /** + * @brief Virtual destructor + */ virtual ~WhitelistHandlerInterface() = default; /** diff --git a/src/web/impl/ErrorHandling.hpp b/src/web/impl/ErrorHandling.hpp index ad08ddea1..2f631b448 100644 --- a/src/web/impl/ErrorHandling.hpp +++ b/src/web/impl/ErrorHandling.hpp @@ -102,7 +102,7 @@ public: sendInternalError() const { connection_->send( - boost::json::serialize(composeError(rpc::RippledError::rpcINTERNAL)), + boost::json::serialize(composeError(rpc::RippledError::RpcInternal)), boost::beast::http::status::internal_server_error ); } @@ -111,7 +111,7 @@ public: sendNotReadyError() const { connection_->send( - boost::json::serialize(composeError(rpc::RippledError::rpcNOT_READY)), + boost::json::serialize(composeError(rpc::RippledError::RpcNotReady)), boost::beast::http::status::ok ); } @@ -121,12 +121,12 @@ public: { if (connection_->upgraded) { connection_->send( - boost::json::serialize(rpc::makeError(rpc::RippledError::rpcTOO_BUSY)), + boost::json::serialize(rpc::makeError(rpc::RippledError::RpcTooBusy)), boost::beast::http::status::ok ); } else { connection_->send( - boost::json::serialize(rpc::makeError(rpc::RippledError::rpcTOO_BUSY)), + boost::json::serialize(rpc::makeError(rpc::RippledError::RpcTooBusy)), boost::beast::http::status::service_unavailable ); } @@ -137,7 +137,7 @@ public: { if (connection_->upgraded) { connection_->send( - boost::json::serialize(rpc::makeError(rpc::RippledError::rpcBAD_SYNTAX)) + boost::json::serialize(rpc::makeError(rpc::RippledError::RpcBadSyntax)) ); } else { connection_->send( diff --git a/src/web/impl/HttpBase.hpp b/src/web/impl/HttpBase.hpp index 41927c12f..0ed4d3f00 100644 --- a/src/web/impl/HttpBase.hpp +++ b/src/web/impl/HttpBase.hpp @@ -45,7 +45,7 @@ namespace web::impl { -static constexpr auto kHEALTH_CHECK_HTML = R"html( +static constexpr auto kHealthCheckHtml = R"html( Test page for Clio @@ -53,7 +53,7 @@ static constexpr auto kHEALTH_CHECK_HTML = R"html( )html"; -static constexpr auto kCACHE_CHECK_LOADED_HTML = R"html( +static constexpr auto kCacheCheckLoadedHtml = R"html( Cache state @@ -61,7 +61,7 @@ static constexpr auto kCACHE_CHECK_LOADED_HTML = R"html( )html"; -static constexpr auto kCACHE_CHECK_NOT_LOADED_HTML = R"html( +static constexpr auto kCacheCheckNotLoadedHtml = R"html( Cache state @@ -246,17 +246,15 @@ public: } if (req_.method() == http::verb::get and req_.target() == "/health") - return sender_(httpResponse(http::status::ok, "text/html", kHEALTH_CHECK_HTML)); + return sender_(httpResponse(http::status::ok, "text/html", kHealthCheckHtml)); if (req_.method() == http::verb::get and req_.target() == "/cache_state") { if (cache_.get().isFull()) { - return sender_( - httpResponse(http::status::ok, "text/html", kCACHE_CHECK_LOADED_HTML) - ); + return sender_(httpResponse(http::status::ok, "text/html", kCacheCheckLoadedHtml)); } return sender_(httpResponse( - http::status::service_unavailable, "text/html", kCACHE_CHECK_NOT_LOADED_HTML + http::status::service_unavailable, "text/html", kCacheCheckNotLoadedHtml )); } @@ -295,7 +293,7 @@ public: return sender_(httpResponse( http::status::internal_server_error, "application/json", - boost::json::serialize(rpc::makeError(rpc::RippledError::rpcINTERNAL)) + boost::json::serialize(rpc::makeError(rpc::RippledError::RpcInternal)) )); } } @@ -306,7 +304,7 @@ public: sender_(httpResponse( http::status::service_unavailable, "text/plain", - boost::json::serialize(rpc::makeError(rpc::RippledError::rpcSLOW_DOWN)) + boost::json::serialize(rpc::makeError(rpc::RippledError::RpcSlowDown)) )); } diff --git a/src/web/impl/WsBase.hpp b/src/web/impl/WsBase.hpp index c2ff0aac4..0e61c199c 100644 --- a/src/web/impl/WsBase.hpp +++ b/src/web/impl/WsBase.hpp @@ -151,7 +151,7 @@ public: void sendSlowDown(std::string const& request) override { - sendError(rpc::RippledError::rpcSLOW_DOWN, request); + sendError(rpc::RippledError::RpcSlowDown, request); } /** @@ -290,7 +290,7 @@ public: try { (*handler_)(requestStr, shared_from_this()); } catch (std::exception const&) { - sendError(rpc::RippledError::rpcINTERNAL, std::move(requestStr)); + sendError(rpc::RippledError::RpcInternal, std::move(requestStr)); } doRead(); diff --git a/src/web/ng/Connection.hpp b/src/web/ng/Connection.hpp index f11abb50b..c67970943 100644 --- a/src/web/ng/Connection.hpp +++ b/src/web/ng/Connection.hpp @@ -121,8 +121,7 @@ public: * @note This value should be higher than forwarding timeout to not disconnect clients if * rippled is slow. */ - static constexpr std::chrono::steady_clock::duration kDEFAULT_TIMEOUT = - std::chrono::seconds{11}; + static constexpr std::chrono::steady_clock::duration kDefaultTimeout = std::chrono::seconds{11}; /** * @brief Construct a new Connection object diff --git a/src/web/ng/RPCServerHandler.hpp b/src/web/ng/RPCServerHandler.hpp index 0eeb3ea32..64db667e5 100644 --- a/src/web/ng/RPCServerHandler.hpp +++ b/src/web/ng/RPCServerHandler.hpp @@ -340,7 +340,7 @@ private: static Response makeSlowDownResponse(Request const& request, std::optional requestJson) { - auto error = rpc::makeError(rpc::RippledError::rpcSLOW_DOWN); + auto error = rpc::makeError(rpc::RippledError::RpcSlowDown); if (not request.isHttp()) { try { diff --git a/src/web/ng/Request.cpp b/src/web/ng/Request.cpp index e3cbf1810..2214ad9f8 100644 --- a/src/web/ng/Request.cpp +++ b/src/web/ng/Request.cpp @@ -3,8 +3,6 @@ #include "util/OverloadSet.hpp" #include -#include -#include #include #include diff --git a/src/web/ng/Response.cpp b/src/web/ng/Response.cpp index c91455837..bd206334b 100644 --- a/src/web/ng/Response.cpp +++ b/src/web/ng/Response.cpp @@ -10,7 +10,6 @@ #include #include #include -#include #include #include #include diff --git a/src/web/ng/SubscriptionContext.hpp b/src/web/ng/SubscriptionContext.hpp index dc793b614..54be02377 100644 --- a/src/web/ng/SubscriptionContext.hpp +++ b/src/web/ng/SubscriptionContext.hpp @@ -103,7 +103,7 @@ public: * * @return The API subversion. */ - uint32_t + [[nodiscard]] uint32_t apiSubversion() const override; /** diff --git a/src/web/ng/impl/ConnectionHandler.cpp b/src/web/ng/impl/ConnectionHandler.cpp index 61f9d3ccc..ef3552b39 100644 --- a/src/web/ng/impl/ConnectionHandler.cpp +++ b/src/web/ng/impl/ConnectionHandler.cpp @@ -164,7 +164,7 @@ ConnectionHandler::processConnection(ConnectionPtr connectionPtr, boost::asio::y } if (shouldCloseGracefully) { - connectionRef.setTimeout(kCLOSE_CONNECTION_TIMEOUT); + connectionRef.setTimeout(kCloseConnectionTimeout); connectionRef.close(yield); LOG(log_.trace()) << connectionRef.tag() << "Closed gracefully"; } @@ -195,7 +195,7 @@ ConnectionHandler::stopConnection(Connection& connection, boost::asio::yield_con connection }; connection.send(std::move(response), yield); - connection.setTimeout(kCLOSE_CONNECTION_TIMEOUT); + connection.setTimeout(kCloseConnectionTimeout); connection.close(yield); LOG(log.trace()) << connection.tag() << "Connection closed"; } diff --git a/src/web/ng/impl/ConnectionHandler.hpp b/src/web/ng/impl/ConnectionHandler.hpp index 203ca835d..31068ac7f 100644 --- a/src/web/ng/impl/ConnectionHandler.hpp +++ b/src/web/ng/impl/ConnectionHandler.hpp @@ -81,7 +81,7 @@ public: ConnectionHandler(ConnectionHandler&&) = delete; - static constexpr std::chrono::milliseconds kCLOSE_CONNECTION_TIMEOUT{500}; + static constexpr std::chrono::milliseconds kCloseConnectionTimeout{500}; void onGet(std::string const& target, MessageHandler handler); diff --git a/src/web/ng/impl/ErrorHandling.cpp b/src/web/ng/impl/ErrorHandling.cpp index 4b46ccb2a..c86ce259a 100644 --- a/src/web/ng/impl/ErrorHandling.cpp +++ b/src/web/ng/impl/ErrorHandling.cpp @@ -111,7 +111,7 @@ ErrorHelper::makeInternalError() const { return Response{ http::status::internal_server_error, - composeError(rpc::RippledError::rpcINTERNAL), + composeError(rpc::RippledError::RpcInternal), rawRequest_ }; } @@ -119,7 +119,7 @@ ErrorHelper::makeInternalError() const Response ErrorHelper::makeNotReadyError() const { - return Response{http::status::ok, composeError(rpc::RippledError::rpcNOT_READY), rawRequest_}; + return Response{http::status::ok, composeError(rpc::RippledError::RpcNotReady), rawRequest_}; } Response @@ -128,14 +128,14 @@ ErrorHelper::makeTooBusyError() const if (not rawRequest_.get().isHttp()) { return Response{ http::status::too_many_requests, - rpc::makeError(rpc::RippledError::rpcTOO_BUSY), + rpc::makeError(rpc::RippledError::RpcTooBusy), rawRequest_ }; } return Response{ http::status::service_unavailable, - rpc::makeError(rpc::RippledError::rpcTOO_BUSY), + rpc::makeError(rpc::RippledError::RpcTooBusy), rawRequest_ }; } @@ -145,7 +145,7 @@ ErrorHelper::makeJsonParsingError() const { if (not rawRequest_.get().isHttp()) { return Response{ - http::status::bad_request, rpc::makeError(rpc::RippledError::rpcBAD_SYNTAX), rawRequest_ + http::status::bad_request, rpc::makeError(rpc::RippledError::RpcBadSyntax), rawRequest_ }; } diff --git a/src/web/ng/impl/HttpConnection.hpp b/src/web/ng/impl/HttpConnection.hpp index 3f397cf15..ca1bdb7bb 100644 --- a/src/web/ng/impl/HttpConnection.hpp +++ b/src/web/ng/impl/HttpConnection.hpp @@ -59,7 +59,7 @@ template class HttpConnection : public UpgradableConnection { StreamType stream_; std::optional> request_; - std::chrono::steady_clock::duration timeout_{kDEFAULT_TIMEOUT}; + std::chrono::steady_clock::duration timeout_{kDefaultTimeout}; using MessageType = boost::beast::http::response; SendingQueue sendingQueue_; diff --git a/src/web/ng/impl/WsConnection.hpp b/src/web/ng/impl/WsConnection.hpp index 3e28183ba..b009ef74e 100644 --- a/src/web/ng/impl/WsConnection.hpp +++ b/src/web/ng/impl/WsConnection.hpp @@ -164,7 +164,7 @@ private: { // Disable the timeout. The websocket::stream uses its own timeout settings. boost::beast::get_lowest_layer(stream_).expires_never(); - setTimeout(kDEFAULT_TIMEOUT); + setTimeout(kDefaultTimeout); stream_.set_option( boost::beast::websocket::stream_base::decorator( [](boost::beast::websocket::response_type& res) { diff --git a/tests/common/CMakeLists.txt b/tests/common/CMakeLists.txt index bd5f7c52b..51b41e6a6 100644 --- a/tests/common/CMakeLists.txt +++ b/tests/common/CMakeLists.txt @@ -7,6 +7,7 @@ target_sources( util/BinaryTestObject.cpp util/CallWithTimeout.cpp util/LoggerFixtures.cpp + util/MPTokenTestObjects.cpp util/MockAssert.cpp util/StringUtils.cpp util/TestHttpClient.cpp diff --git a/tests/common/data/cassandra/FakesAndMocks.hpp b/tests/common/data/cassandra/FakesAndMocks.hpp index 4e805751d..2f36e5c2e 100644 --- a/tests/common/data/cassandra/FakesAndMocks.hpp +++ b/tests/common/data/cassandra/FakesAndMocks.hpp @@ -1,3 +1,5 @@ +#pragma once + #include "data/cassandra/Error.hpp" #include "data/cassandra/impl/AsyncExecutor.hpp" diff --git a/tests/common/etl/FakeDiffProvider.hpp b/tests/common/etl/FakeDiffProvider.hpp index eefb9429c..47c35db09 100644 --- a/tests/common/etl/FakeDiffProvider.hpp +++ b/tests/common/etl/FakeDiffProvider.hpp @@ -17,7 +17,7 @@ struct DiffProvider { std::vector getLatestDiff() // NOLINT(readability-convert-member-functions-to-static) { - using namespace ripple; + using namespace xrpl; return { {.key = uint256{"05E1EAC2574BE082B00B16F907CE32E6058DEB8F9E81CF34A00E80A5D71FA4FE"}, @@ -45,7 +45,7 @@ struct DiffProvider { }; } - std::optional + std::optional nextKey(std::size_t keysSize) { // mock the result from doFetchSuccessorKey, be aware this function will be called from @@ -54,14 +54,14 @@ struct DiffProvider { keysMap->operator[](std::this_thread::get_id())++; if (keysMap->operator[](std::this_thread::get_id()) == keysSize - 1) { - return data::kLAST_KEY; + return data::kLastKey; } if (keysMap->operator[](std::this_thread::get_id()) == keysSize) { keysMap->operator[](std::this_thread::get_id()) = 0; return std::nullopt; } - return ripple::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"}; + return xrpl::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"}; } private: diff --git a/tests/common/migration/TestMigrators.hpp b/tests/common/migration/TestMigrators.hpp index 6980b08fe..290d534e3 100644 --- a/tests/common/migration/TestMigrators.hpp +++ b/tests/common/migration/TestMigrators.hpp @@ -1,3 +1,5 @@ +#pragma once + #include "util/MockMigrationBackend.hpp" #include "util/config/ObjectView.hpp" @@ -5,9 +7,9 @@ struct SimpleTestMigrator { using Backend = MockMigrationBackend; - static constexpr auto kNAME = "SimpleTestMigrator"; - static constexpr auto kDESCRIPTION = "The migrator for version 0 -> 1"; - static constexpr auto kCAN_BLOCK_CLIO = true; + static constexpr auto kName = "SimpleTestMigrator"; + static constexpr auto kDescription = "The migrator for version 0 -> 1"; + static constexpr auto kCanBlockClio = true; static void runMigration(std::shared_ptr, util::config::ObjectView const&) @@ -17,8 +19,8 @@ struct SimpleTestMigrator { struct SimpleTestMigrator2 { using Backend = MockMigrationBackend; - static constexpr auto kNAME = "SimpleTestMigrator2"; - static constexpr auto kDESCRIPTION = "The migrator for version 1 -> 2"; + static constexpr auto kName = "SimpleTestMigrator2"; + static constexpr auto kDescription = "The migrator for version 1 -> 2"; static void runMigration(std::shared_ptr, util::config::ObjectView const&) { @@ -27,9 +29,9 @@ struct SimpleTestMigrator2 { struct SimpleTestMigrator3 { using Backend = MockMigrationBackend; - static constexpr auto kNAME = "SimpleTestMigrator3"; - static constexpr auto kDESCRIPTION = "The migrator for version 3 -> 4"; - static constexpr auto kCAN_BLOCK_CLIO = false; + static constexpr auto kName = "SimpleTestMigrator3"; + static constexpr auto kDescription = "The migrator for version 3 -> 4"; + static constexpr auto kCanBlockClio = false; static void runMigration(std::shared_ptr, util::config::ObjectView const&) diff --git a/tests/common/rpc/FakesAndMocks.hpp b/tests/common/rpc/FakesAndMocks.hpp index 789e26a8b..e277b68d6 100644 --- a/tests/common/rpc/FakesAndMocks.hpp +++ b/tests/common/rpc/FakesAndMocks.hpp @@ -60,12 +60,12 @@ public: { using namespace rpc::validation; - static auto const kRPC_SPEC = rpc::RpcSpec{ + static auto const kRpcSpec = rpc::RpcSpec{ {"hello", Required{}, Type{}, EqualTo{"world"}}, {"limit", Type{}, Between{0, 100}}, // optional field }; - return kRPC_SPEC; + return kRpcSpec; } static Result @@ -99,12 +99,12 @@ public: { using namespace rpc::validation; - static auto const kRPC_SPEC = rpc::RpcSpec{ + static auto const kRpcSpec = rpc::RpcSpec{ {"hello", Required{}, Type{}, EqualTo{"world"}}, {"limit", Type{}, Between{0u, 100u}}, // optional field }; - return kRPC_SPEC; + return kRpcSpec; } static Result diff --git a/tests/common/util/AsioContextTestFixture.hpp b/tests/common/util/AsioContextTestFixture.hpp index 381972cdb..c8329a74d 100644 --- a/tests/common/util/AsioContextTestFixture.hpp +++ b/tests/common/util/AsioContextTestFixture.hpp @@ -101,8 +101,8 @@ struct SyncAsioContextTest : virtual public ::testing::Test { void runContext() { - static constexpr auto kTIMEOUT = std::chrono::seconds{30}; - ctx_.run_for(kTIMEOUT); + static constexpr auto kTimeout = std::chrono::seconds{30}; + ctx_.run_for(kTimeout); ctx_.restart(); } diff --git a/tests/common/util/BinaryTestObject.cpp b/tests/common/util/BinaryTestObject.cpp index 63913ce65..2b6a61dbd 100644 --- a/tests/common/util/BinaryTestObject.cpp +++ b/tests/common/util/BinaryTestObject.cpp @@ -25,8 +25,8 @@ namespace { -constinit auto const kSEQ = 30; -constinit auto const kRAW_HEADER = +constinit auto const kSeq = 30; +constinit auto const kRawHeader = "03C3141A01633CD656F91B4EBB5EB89B791BD34DBC8A04BB6F407C5335BC54351E" "DD733898497E809E04074D14D271E4832D7888754F9230800761563A292FA2315A" "6DB6FE30CC5909B285080FCD6773CC883F9FE0EE4D439340AC592AADB973ED3CF5" @@ -43,20 +43,20 @@ createTxAndMetaBlobs(std::string metaStr, std::string txnStr) return {hexStringToBinaryString(metaStr), hexStringToBinaryString(txnStr)}; } -std::pair +std::pair createTxAndMeta(std::string hashStr, std::string metaStr, std::string txnStr) { - ripple::uint256 hash; + xrpl::uint256 hash; EXPECT_TRUE(hash.parseHex(hashStr)); auto const [metaBlob, txnBlob] = createTxAndMetaBlobs(metaStr, txnStr); - ripple::SerialIter it{txnBlob.data(), txnBlob.size()}; - return {ripple::STTx{it}, ripple::TxMeta{hash, kSEQ, metaBlob}}; + xrpl::SerialIter it{txnBlob.data(), txnBlob.size()}; + return {xrpl::STTx{it}, xrpl::TxMeta{hash, kSeq, xrpl::Blob{metaBlob.begin(), metaBlob.end()}}}; } etl::model::Transaction -createTransaction(ripple::TxType type, std::string hashStr, std::string metaStr, std::string txnStr) +createTransaction(xrpl::TxType type, std::string hashStr, std::string metaStr, std::string txnStr) { auto const [sttx, meta] = createTxAndMeta(hashStr, metaStr, txnStr); return { @@ -64,7 +64,7 @@ createTransaction(ripple::TxType type, std::string hashStr, std::string metaStr, .metaRaw = "", .sttx = sttx, .meta = meta, - .id = ripple::uint256{"0000000000000000000000000000000000000000000000000000000000000001"}, + .id = xrpl::uint256{"0000000000000000000000000000000000000000000000000000000000000001"}, .key = "0000000000000000000000000000000000000000000000000000000000000001", .type = type }; @@ -74,11 +74,11 @@ etl::model::Object createObject(etl::model::Object::ModType modType, std::string key) { // random object taken from initial ledger load - static constinit auto const kOBJ_PRED = + static constinit auto const kObjPred = "B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960A"; - static constinit auto const kOBJ_SUCC = + static constinit auto const kObjSucc = "B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960F"; - static constinit auto const kOBJ_BLOB = + static constinit auto const kObjBlob = "11007222002200002504270918370000000000000C4538000000000000000A554D94799200CC37EFAF45DA7670" "4ED3CBEDBB4B4FCD" "56E9CBA5399EB40A7B3BEC629546DD24CDB4C0004C4A5059000000000000000000000000000000000000000000" @@ -92,13 +92,13 @@ createObject(etl::model::Object::ModType modType, std::string key) .key = binaryStringToUint256(hexStringToBinaryString(key)), .keyRaw = hexStringToBinaryString(key), .data = modType == etl::model::Object::ModType::Deleted - ? ripple::Blob{} - : *ripple::strUnHex(kOBJ_BLOB), // NOLINT(bugprone-unchecked-optional-access) + ? xrpl::Blob{} + : *xrpl::strUnHex(kObjBlob), // NOLINT(bugprone-unchecked-optional-access) .dataRaw = modType == etl::model::Object::ModType::Deleted ? "" - : hexStringToBinaryString(kOBJ_BLOB), - .successor = hexStringToBinaryString(kOBJ_SUCC), - .predecessor = hexStringToBinaryString(kOBJ_PRED), + : hexStringToBinaryString(kObjBlob), + .successor = hexStringToBinaryString(kObjSucc), + .predecessor = hexStringToBinaryString(kObjPred), .type = modType, }; } @@ -107,11 +107,11 @@ etl::model::Object createObjectWithBookBase(etl::model::Object::ModType modType, std::string key) { // random object taken from initial ledger load - static constinit auto const kOBJ_PRED = + static constinit auto const kObjPred = "B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960A"; - static constinit auto const kOBJ_SUCC = + static constinit auto const kObjSucc = "B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960F"; - static constinit auto const kOBJ_BLOB = + static constinit auto const kObjBlob = "11006422000000022505A681E855B4E076DD06D6D583804F9DC94F641337ECB97F71860300EEC17E530A2001D6" "C9583FFBFAD704E299BE" "3E544090ECCB12AF45FD03CAEEA852E5048E57F48FD45B505A0008138882D0F98C64A1A0E6D15053589771AD08" @@ -122,13 +122,13 @@ createObjectWithBookBase(etl::model::Object::ModType modType, std::string key) .key = binaryStringToUint256(hexStringToBinaryString(key)), .keyRaw = hexStringToBinaryString(key), .data = modType == etl::model::Object::ModType::Deleted - ? ripple::Blob{} - : *ripple::strUnHex(kOBJ_BLOB), // NOLINT(bugprone-unchecked-optional-access) + ? xrpl::Blob{} + : *xrpl::strUnHex(kObjBlob), // NOLINT(bugprone-unchecked-optional-access) .dataRaw = modType == etl::model::Object::ModType::Deleted ? "" - : hexStringToBinaryString(kOBJ_BLOB), - .successor = hexStringToBinaryString(kOBJ_SUCC), - .predecessor = hexStringToBinaryString(kOBJ_PRED), + : hexStringToBinaryString(kObjBlob), + .successor = hexStringToBinaryString(kObjSucc), + .predecessor = hexStringToBinaryString(kObjPred), .type = modType, }; } @@ -138,22 +138,22 @@ createObjectWithTwoNFTs() { std::string const url1 = "abcd1"; std::string const url2 = "abcd2"; - ripple::Blob const uri1Blob(url1.begin(), url1.end()); - ripple::Blob const uri2Blob(url2.begin(), url2.end()); + xrpl::Blob const uri1Blob(url1.begin(), url1.end()); + xrpl::Blob const uri2Blob(url2.begin(), url2.end()); - constexpr auto kACCOUNT = "rM2AGCCCRb373FRuD8wHyUwUsh2dV4BW5Q"; - constexpr auto kNFT_ID = "0008013AE1CD8B79A8BCB52335CD40DE97401B2D60A828720000099B00000000"; - constexpr auto kNFT_ID2 = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DA"; + constexpr auto kAccount = "rM2AGCCCRb373FRuD8wHyUwUsh2dV4BW5Q"; + constexpr auto kNftId = "0008013AE1CD8B79A8BCB52335CD40DE97401B2D60A828720000099B00000000"; + constexpr auto kNftID2 = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DA"; - auto const nftPage = createNftTokenPage({{kNFT_ID, url1}, {kNFT_ID2, url2}}, std::nullopt); + auto const nftPage = createNftTokenPage({{kNftId, url1}, {kNftID2, url2}}, std::nullopt); auto const serializerNftPage = nftPage.getSerializer(); - auto const account = getAccountIdWithString(kACCOUNT); + auto const account = getAccountIdWithString(kAccount); // key is a token made up from owner's account ID followed by unused (in Clio) value described // here: // https://github.com/XRPLF/XRPL-Standards/tree/master/XLS-0020-non-fungible-tokens#tokenpage-id-format - constexpr auto kEXTRA_BYTES = "000000000000"; - auto const key = std::string(std::begin(account), std::end(account)) + kEXTRA_BYTES; + constexpr auto kExtraBytes = "000000000000"; + auto const key = std::string(std::begin(account), std::end(account)) + kExtraBytes; return { .key = {}, @@ -172,16 +172,16 @@ createObjectWithTwoNFTs() etl::model::Object createObjectWithMPT() { - constexpr auto kACCOUNT = "rM2AGCCCRb373FRuD8wHyUwUsh2dV4BW5Q"; + constexpr auto kAccount = "rM2AGCCCRb373FRuD8wHyUwUsh2dV4BW5Q"; - auto const account = getAccountIdWithString(kACCOUNT); - auto const mptID = ripple::makeMptID(2, getAccountIdWithString(kACCOUNT)); - auto const mptokenObject = createMpTokenObject(kACCOUNT, mptID); + auto const account = getAccountIdWithString(kAccount); + auto const mptID = xrpl::makeMptID(2, getAccountIdWithString(kAccount)); + auto const mptokenObject = createMpTokenObject(kAccount, mptID); // key is a token made up from several fields described here: // https://github.com/XRPLF/XRPL-Standards/tree/master/XLS-0033-multi-purpose-tokens#2121-mptoken-ledger-identifier - constexpr auto kSPACE_KEY = 0x007F; - auto const keySha512Half = ripple::sha512Half(kSPACE_KEY, mptID, account); + constexpr auto kSpaceKey = 0x007F; + auto const keySha512Half = xrpl::sha512Half(kSpaceKey, mptID, account); return { .key = {}, @@ -202,10 +202,10 @@ createSuccessor() { return { .firstBook = uint256ToString( - ripple::uint256{"A000000000000000000000000000000000000000000000000000000000000000"} + xrpl::uint256{"A000000000000000000000000000000000000000000000000000000000000000"} ), .bookBase = uint256ToString( - ripple::uint256{"A000000000000000000000000000000000000000000000000000000000000001"} + xrpl::uint256{"A000000000000000000000000000000000000000000000000000000000000001"} ), }; } @@ -213,7 +213,7 @@ createSuccessor() etl::impl::PBLedgerResponseType createDataAndDiff() { - auto const rawHeaderBlob = hexStringToBinaryString(kRAW_HEADER); + auto const rawHeaderBlob = hexStringToBinaryString(kRawHeader); auto res = etl::impl::PBLedgerResponseType(); res.set_ledger_header(rawHeaderBlob); @@ -259,7 +259,7 @@ createDataAndDiff() etl::impl::PBLedgerResponseType createData() { - auto const rawHeaderBlob = hexStringToBinaryString(kRAW_HEADER); + auto const rawHeaderBlob = hexStringToBinaryString(kRawHeader); auto res = etl::impl::PBLedgerResponseType(); res.set_ledger_header(rawHeaderBlob); diff --git a/tests/common/util/BinaryTestObject.hpp b/tests/common/util/BinaryTestObject.hpp index 44d9dbdfc..1fb52bfd1 100644 --- a/tests/common/util/BinaryTestObject.hpp +++ b/tests/common/util/BinaryTestObject.hpp @@ -13,7 +13,7 @@ namespace util { -static constexpr auto kDEFAULT_TXN_HEX = +static constexpr auto kDefaultTxnHex = "1200192200000008240011CC9B201B001F71D6202A0000000168400000" "000000000C7321ED475D1452031E8F9641AF1631519A58F7B8681E172E" "4838AA0E59408ADA1727DD74406960041F34F10E0CBB39444B4D4E577F" @@ -22,7 +22,7 @@ static constexpr auto kDEFAULT_TXN_HEX = "677265677765697362726F642E636F6D81146203F49C21D5D6E022CB16" "DE3538F248662FC73C"; -static constexpr auto kDEFAULT_TXN_META = +static constexpr auto kDefaultTxnMeta = "201C00000001F8E511005025001F71B3556ED9C9459001E4F4A9121F4E" "07AB6D14898A5BBEF13D85C25D743540DB59F3CF566203F49C21D5D6E0" "22CB16DE3538F248662FC73CFFFFFFFFFFFFFFFFFFFFFFFFE6FAEC5A00" @@ -121,42 +121,39 @@ static constexpr auto kDEFAULT_TXN_META = "066240000002540BE3E081146203F49C21D5D6E022CB16DE3538F24866" "2FC73CE1E1F1031000"; -static constexpr auto kDEFAULT_HASH = +static constexpr auto kDefaultHash = "6C7F69A6D25A13AC4A2E9145999F45D4674F939900017A96885FDC2757E9284E"; -static constexpr auto kDEFAULT_OBJ_KEY = +static constexpr auto kDefaultObjKey = "B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960D"; [[maybe_unused, nodiscard]] std::pair -createTxAndMetaBlobs( - std::string metaStr = kDEFAULT_TXN_META, - std::string txnStr = kDEFAULT_TXN_HEX -); +createTxAndMetaBlobs(std::string metaStr = kDefaultTxnMeta, std::string txnStr = kDefaultTxnHex); -[[maybe_unused, nodiscard]] std::pair +[[maybe_unused, nodiscard]] std::pair createTxAndMeta( - std::string hashStr = kDEFAULT_HASH, - std::string metaStr = kDEFAULT_TXN_META, - std::string txnStr = kDEFAULT_TXN_HEX + std::string hashStr = kDefaultHash, + std::string metaStr = kDefaultTxnMeta, + std::string txnStr = kDefaultTxnHex ); [[maybe_unused, nodiscard]] etl::model::Transaction createTransaction( - ripple::TxType type, - std::string hashStr = kDEFAULT_HASH, - std::string metaStr = kDEFAULT_TXN_META, - std::string txnStr = kDEFAULT_TXN_HEX + xrpl::TxType type, + std::string hashStr = kDefaultHash, + std::string metaStr = kDefaultTxnMeta, + std::string txnStr = kDefaultTxnHex ); [[maybe_unused, nodiscard]] etl::model::Object createObject( etl::model::Object::ModType modType = etl::model::Object::ModType::Created, - std::string key = kDEFAULT_OBJ_KEY + std::string key = kDefaultObjKey ); [[maybe_unused, nodiscard]] etl::model::Object createObjectWithBookBase( etl::model::Object::ModType modType = etl::model::Object::ModType::Created, - std::string key = kDEFAULT_OBJ_KEY + std::string key = kDefaultObjKey ); [[maybe_unused, nodiscard]] etl::model::Object diff --git a/tests/common/util/CallWithTimeout.cpp b/tests/common/util/CallWithTimeout.cpp index 780518756..a31e11aa3 100644 --- a/tests/common/util/CallWithTimeout.cpp +++ b/tests/common/util/CallWithTimeout.cpp @@ -3,7 +3,6 @@ #include #include -#include #include #include #include diff --git a/tests/common/util/LoggerBuffer.hpp b/tests/common/util/LoggerBuffer.hpp index 8c62f66a7..138736f56 100644 --- a/tests/common/util/LoggerBuffer.hpp +++ b/tests/common/util/LoggerBuffer.hpp @@ -1,4 +1,5 @@ #pragma once + #include "util/StringBuffer.hpp" #include diff --git a/tests/common/util/LoggerFixtures.cpp b/tests/common/util/LoggerFixtures.cpp index 1d580f403..047fb1ea7 100644 --- a/tests/common/util/LoggerFixtures.cpp +++ b/tests/common/util/LoggerFixtures.cpp @@ -17,7 +17,7 @@ LoggerFixture::init() { util::LogServiceState::init(false, util::Severity::FTL, {}); - std::ranges::for_each(util::Logger::kCHANNELS, [](std::string_view const channel) { + std::ranges::for_each(util::Logger::kChannels, [](std::string_view const channel) { util::LogService::registerLogger(channel); }); diff --git a/tests/common/util/MPTokenTestObjects.cpp b/tests/common/util/MPTokenTestObjects.cpp new file mode 100644 index 000000000..f9ac46141 --- /dev/null +++ b/tests/common/util/MPTokenTestObjects.cpp @@ -0,0 +1,54 @@ +#include "util/MPTokenTestObjects.hpp" + +#include "util/TestObject.hpp" + +#include +#include +#include +#include + +#include +#include +#include + +namespace util { + +xrpl::STObject +createMPTokenNode( + xrpl::SField const& nodeType, + xrpl::uint192 const& issuanceID, + std::string_view holder +) +{ + auto const& fieldsName = + nodeType == xrpl::sfCreatedNode ? xrpl::sfNewFields : xrpl::sfFinalFields; + + xrpl::STObject fields(fieldsName); + fields.setAccountID(xrpl::sfAccount, ::getAccountIdWithString(holder)); + fields[xrpl::sfMPTokenIssuanceID] = issuanceID; + + xrpl::STObject node(nodeType); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltMPTOKEN); + node.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{}); + node.set(std::move(fields)); + return node; +} + +xrpl::STObject +createMPTokenIssuanceNode(xrpl::SField const& nodeType, std::uint32_t seq, std::string_view issuer) +{ + auto const& fieldsName = + nodeType == xrpl::sfCreatedNode ? xrpl::sfNewFields : xrpl::sfFinalFields; + + xrpl::STObject fields(fieldsName); + fields.setFieldU32(xrpl::sfSequence, seq); + fields.setAccountID(xrpl::sfIssuer, ::getAccountIdWithString(issuer)); + + xrpl::STObject node(nodeType); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltMPTOKEN_ISSUANCE); + node.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{}); + node.set(std::move(fields)); + return node; +} + +} // namespace util diff --git a/tests/common/util/MPTokenTestObjects.hpp b/tests/common/util/MPTokenTestObjects.hpp new file mode 100644 index 000000000..befbb8106 --- /dev/null +++ b/tests/common/util/MPTokenTestObjects.hpp @@ -0,0 +1,22 @@ +#pragma once + +#include +#include +#include + +#include +#include + +namespace util { + +[[nodiscard]] xrpl::STObject +createMPTokenNode( + xrpl::SField const& nodeType, + xrpl::uint192 const& issuanceID, + std::string_view holder +); + +[[nodiscard]] xrpl::STObject +createMPTokenIssuanceNode(xrpl::SField const& nodeType, std::uint32_t seq, std::string_view issuer); + +} // namespace util diff --git a/tests/common/util/MockBackend.hpp b/tests/common/util/MockBackend.hpp index 111af2bc2..f2385c087 100644 --- a/tests/common/util/MockBackend.hpp +++ b/tests/common/util/MockBackend.hpp @@ -26,16 +26,16 @@ struct MockBackend : public BackendInterface { } MOCK_METHOD( - std::optional, + std::optional, fetchLedgerBySequence, (std::uint32_t const, boost::asio::yield_context), (const, override) ); MOCK_METHOD( - std::optional, + std::optional, fetchLedgerByHash, - (ripple::uint256 const&, boost::asio::yield_context), + (xrpl::uint256 const&, boost::asio::yield_context), (const, override) ); @@ -49,21 +49,21 @@ struct MockBackend : public BackendInterface { MOCK_METHOD( std::optional, fetchTransaction, - (ripple::uint256 const&, boost::asio::yield_context), + (xrpl::uint256 const&, boost::asio::yield_context), (const, override) ); MOCK_METHOD( std::vector, fetchTransactions, - (std::vector const&, boost::asio::yield_context), + (std::vector const&, boost::asio::yield_context), (const, override) ); MOCK_METHOD( data::TransactionsAndCursor, fetchAccountTransactions, - (ripple::AccountID const&, + (xrpl::AccountID const&, std::uint32_t const, bool, std::optional const&, @@ -79,7 +79,7 @@ struct MockBackend : public BackendInterface { ); MOCK_METHOD( - std::vector, + std::vector, fetchAllTransactionHashesInLedger, (std::uint32_t const, boost::asio::yield_context), (const, override) @@ -88,14 +88,14 @@ struct MockBackend : public BackendInterface { MOCK_METHOD( std::optional, fetchNFT, - (ripple::uint256 const&, std::uint32_t const, boost::asio::yield_context), + (xrpl::uint256 const&, std::uint32_t const, boost::asio::yield_context), (const, override) ); MOCK_METHOD( data::TransactionsAndCursor, fetchNFTTransactions, - (ripple::uint256 const&, + (xrpl::uint256 const&, std::uint32_t const, bool const, std::optional const&, @@ -103,14 +103,37 @@ struct MockBackend : public BackendInterface { (const, override) ); + MOCK_METHOD( + data::TransactionsAndCursor, + fetchMPTokenIssuanceTransactions, + (xrpl::uint192 const&, + std::uint32_t, + bool, + std::optional const&, + boost::asio::yield_context), + (const, override) + ); + + MOCK_METHOD( + data::TransactionsAndCursor, + fetchAccountMPTokenIssuanceTransactions, + (xrpl::uint192 const&, + xrpl::AccountID const&, + std::uint32_t, + bool, + std::optional const&, + boost::asio::yield_context), + (const, override) + ); + MOCK_METHOD( data::NFTsAndCursor, fetchNFTsByIssuer, - (ripple::AccountID const& issuer, + (xrpl::AccountID const& issuer, std::optional const& taxon, std::uint32_t const ledgerSequence, std::uint32_t const limit, - std::optional const& cursorIn, + std::optional const& cursorIn, boost::asio::yield_context yield), (const, override) ); @@ -118,12 +141,12 @@ struct MockBackend : public BackendInterface { MOCK_METHOD( std::vector, doFetchLedgerObjects, - (std::vector const&, std::uint32_t const, boost::asio::yield_context), + (std::vector const&, std::uint32_t const, boost::asio::yield_context), (const, override) ); MOCK_METHOD( - std::vector, + std::vector, fetchAccountRoots, (std::uint32_t, std::uint32_t, std::uint32_t, boost::asio::yield_context), (const, override) @@ -132,14 +155,14 @@ struct MockBackend : public BackendInterface { MOCK_METHOD( std::optional, doFetchLedgerObject, - (ripple::uint256 const&, std::uint32_t const, boost::asio::yield_context), + (xrpl::uint256 const&, std::uint32_t const, boost::asio::yield_context), (const, override) ); MOCK_METHOD( std::optional, doFetchLedgerObjectSeq, - (ripple::uint256 const&, std::uint32_t const, boost::asio::yield_context), + (xrpl::uint256 const&, std::uint32_t const, boost::asio::yield_context), (const, override) ); @@ -151,9 +174,9 @@ struct MockBackend : public BackendInterface { ); MOCK_METHOD( - std::optional, + std::optional, doFetchSuccessorKey, - (ripple::uint256, std::uint32_t const, boost::asio::yield_context), + (xrpl::uint256, std::uint32_t const, boost::asio::yield_context), (const, override) ); @@ -180,7 +203,7 @@ struct MockBackend : public BackendInterface { (const, override) ); - MOCK_METHOD(void, writeLedger, (ripple::LedgerHeader const&, std::string&&), (override)); + MOCK_METHOD(void, writeLedger, (xrpl::LedgerHeader const&, std::string&&), (override)); MOCK_METHOD( void, @@ -204,6 +227,20 @@ struct MockBackend : public BackendInterface { MOCK_METHOD(void, writeNFTTransactions, (std::vector const&), (override)); + MOCK_METHOD( + void, + writeMPTokenIssuanceTransactions, + (std::vector const&), + (override) + ); + + MOCK_METHOD( + void, + writeAccountMPTokenIssuanceTransactions, + (std::vector const&), + (override) + ); + MOCK_METHOD( void, writeSuccessor, @@ -240,9 +277,9 @@ struct MockBackend : public BackendInterface { MOCK_METHOD( data::MPTHoldersAndCursor, fetchMPTHolders, - (ripple::uint192 const& mptID, + (xrpl::uint192 const& mptID, std::uint32_t const, - (std::optional const&), + (std::optional const&), std::uint32_t const, boost::asio::yield_context), (const, override) diff --git a/tests/common/util/MockExecutionContext.hpp b/tests/common/util/MockExecutionContext.hpp index 377c57c08..d9381ee5a 100644 --- a/tests/common/util/MockExecutionContext.hpp +++ b/tests/common/util/MockExecutionContext.hpp @@ -5,10 +5,10 @@ #include "util/MockStrand.hpp" #include "util/async/AnyStopToken.hpp" #include "util/async/Error.hpp" +#include "util/async/impl/Any.hpp" #include -#include #include #include #include @@ -18,6 +18,8 @@ struct MockExecutionContext { template using ValueType = std::expected; + using Any = util::async::impl::Any; + using StopSource = MockStopSource; using StopToken = MockStopToken; using Strand = MockStrand; @@ -34,36 +36,35 @@ struct MockExecutionContext { template using RepeatingOperation = MockRepeatingOperation; - MOCK_METHOD(Operation const&, execute, (std::function), ()); + MOCK_METHOD(Operation const&, execute, (std::function), ()); MOCK_METHOD( - Operation const&, + Operation const&, execute, - (std::function, std::optional), + (std::function, std::optional), () ); MOCK_METHOD( - StoppableOperation const&, + StoppableOperation const&, execute, - (std::function, - std::optional), + (std::function, std::optional), () ); MOCK_METHOD( - ScheduledOperation const&, + ScheduledOperation const&, scheduleAfter, - (std::chrono::milliseconds, std::function), + (std::chrono::milliseconds, std::function), () ); MOCK_METHOD( - ScheduledOperation const&, + ScheduledOperation const&, scheduleAfter, - (std::chrono::milliseconds, std::function), + (std::chrono::milliseconds, std::function), () ); MOCK_METHOD( - RepeatingOperation const&, + RepeatingOperation const&, executeRepeatedly, - (std::chrono::milliseconds, std::function), + (std::chrono::milliseconds, std::function), () ); MOCK_METHOD(void, submit, (std::function), ()); diff --git a/tests/common/util/MockLedgerCache.hpp b/tests/common/util/MockLedgerCache.hpp index c8c062e8f..6219822c1 100644 --- a/tests/common/util/MockLedgerCache.hpp +++ b/tests/common/util/MockLedgerCache.hpp @@ -30,7 +30,7 @@ struct MockLedgerCache : data::LedgerCacheInterface { MOCK_METHOD( std::optional, get, - (ripple::uint256 const& a, uint32_t b), + (xrpl::uint256 const& a, uint32_t b), (const, override) ); @@ -39,21 +39,21 @@ struct MockLedgerCache : data::LedgerCacheInterface { MOCK_METHOD( std::optional, getDeleted, - (ripple::uint256 const&, uint32_t), + (xrpl::uint256 const&, uint32_t), (const, override) ); MOCK_METHOD( std::optional, getSuccessor, - (ripple::uint256 const& a, uint32_t b), + (xrpl::uint256 const& a, uint32_t b), (const, override) ); MOCK_METHOD( std::optional, getPredecessor, - (ripple::uint256 const& a, uint32_t b), + (xrpl::uint256 const& a, uint32_t b), (const, override) ); diff --git a/tests/common/util/MockLedgerPublisher.hpp b/tests/common/util/MockLedgerPublisher.hpp index f53fef1b6..13a56dba5 100644 --- a/tests/common/util/MockLedgerPublisher.hpp +++ b/tests/common/util/MockLedgerPublisher.hpp @@ -16,7 +16,7 @@ struct MockLedgerPublisher : public etl::LedgerPublisherInterface { (uint32_t, std::optional, std::chrono::steady_clock::duration), (override) ); - MOCK_METHOD(void, publish, (ripple::LedgerHeader const&), ()); + MOCK_METHOD(void, publish, (xrpl::LedgerHeader const&), ()); MOCK_METHOD(std::uint32_t, lastPublishAgeSeconds, (), (const)); MOCK_METHOD( std::chrono::time_point, diff --git a/tests/common/util/MockRPCEngine.hpp b/tests/common/util/MockRPCEngine.hpp index c395ecaa1..90fb35808 100644 --- a/tests/common/util/MockRPCEngine.hpp +++ b/tests/common/util/MockRPCEngine.hpp @@ -1,4 +1,5 @@ #pragma once + #include "rpc/common/Types.hpp" #include "util/Spawn.hpp" #include "web/Context.hpp" diff --git a/tests/common/util/MockRandomGenerator.hpp b/tests/common/util/MockRandomGenerator.hpp index f2f124dbb..b9f5eacf4 100644 --- a/tests/common/util/MockRandomGenerator.hpp +++ b/tests/common/util/MockRandomGenerator.hpp @@ -1,4 +1,5 @@ #pragma once + #include "util/Random.hpp" #include diff --git a/tests/common/util/MockStrand.hpp b/tests/common/util/MockStrand.hpp index 000c5f266..a45334c31 100644 --- a/tests/common/util/MockStrand.hpp +++ b/tests/common/util/MockStrand.hpp @@ -3,10 +3,10 @@ #include "util/MockOperation.hpp" #include "util/async/AnyStopToken.hpp" #include "util/async/Error.hpp" +#include "util/async/impl/Any.hpp" #include -#include #include #include #include @@ -16,6 +16,8 @@ struct MockStrand { template using ValueType = std::expected; + using Any = util::async::impl::Any; + template using Operation = MockOperation; @@ -25,30 +27,29 @@ struct MockStrand { template using RepeatingOperation = MockRepeatingOperation; - MOCK_METHOD(Operation const&, execute, (std::function), (const)); + MOCK_METHOD(Operation const&, execute, (std::function), (const)); MOCK_METHOD( - Operation const&, + Operation const&, execute, - (std::function, std::optional), + (std::function, std::optional), (const) ); MOCK_METHOD( - StoppableOperation const&, + StoppableOperation const&, execute, - (std::function), + (std::function), (const) ); MOCK_METHOD( - StoppableOperation const&, + StoppableOperation const&, execute, - (std::function, - std::optional), + (std::function, std::optional), (const) ); MOCK_METHOD( - RepeatingOperation const&, + RepeatingOperation const&, executeRepeatedly, - (std::chrono::milliseconds, std::function), + (std::chrono::milliseconds, std::function), (const) ); MOCK_METHOD(void, submit, (std::function), (const)); diff --git a/tests/common/util/MockSubscriptionManager.hpp b/tests/common/util/MockSubscriptionManager.hpp index 9860f8d40..f0ae17736 100644 --- a/tests/common/util/MockSubscriptionManager.hpp +++ b/tests/common/util/MockSubscriptionManager.hpp @@ -29,14 +29,14 @@ struct MockSubscriptionManager : feed::SubscriptionManagerInterface { MOCK_METHOD( void, pubLedger, - (ripple::LedgerHeader const&, ripple::Fees const&, std::string const&, std::uint32_t), + (xrpl::LedgerHeader const&, xrpl::Fees const&, std::string const&, std::uint32_t), (override) ); MOCK_METHOD( void, pubBookChanges, - (ripple::LedgerHeader const&, std::vector const&), + (xrpl::LedgerHeader const&, std::vector const&), (override) ); @@ -49,32 +49,27 @@ struct MockSubscriptionManager : feed::SubscriptionManagerInterface { MOCK_METHOD( void, pubTransaction, - (data::TransactionAndMetadata const&, ripple::LedgerHeader const&), + (data::TransactionAndMetadata const&, xrpl::LedgerHeader const&), (override) ); MOCK_METHOD( void, subAccount, - (ripple::AccountID const&, feed::SubscriberSharedPtr const&), + (xrpl::AccountID const&, feed::SubscriberSharedPtr const&), (override) ); MOCK_METHOD( void, unsubAccount, - (ripple::AccountID const&, feed::SubscriberSharedPtr const&), + (xrpl::AccountID const&, feed::SubscriberSharedPtr const&), (override) ); - MOCK_METHOD(void, subBook, (ripple::Book const&, feed::SubscriberSharedPtr const&), (override)); + MOCK_METHOD(void, subBook, (xrpl::Book const&, feed::SubscriberSharedPtr const&), (override)); - MOCK_METHOD( - void, - unsubBook, - (ripple::Book const&, feed::SubscriberSharedPtr const&), - (override) - ); + MOCK_METHOD(void, unsubBook, (xrpl::Book const&, feed::SubscriberSharedPtr const&), (override)); MOCK_METHOD(void, subBookChanges, (feed::SubscriberSharedPtr const&), (override)); @@ -97,14 +92,14 @@ struct MockSubscriptionManager : feed::SubscriptionManagerInterface { MOCK_METHOD( void, subProposedAccount, - (ripple::AccountID const&, feed::SubscriberSharedPtr const&), + (xrpl::AccountID const&, feed::SubscriberSharedPtr const&), (override) ); MOCK_METHOD( void, unsubProposedAccount, - (ripple::AccountID const&, feed::SubscriberSharedPtr const&), + (xrpl::AccountID const&, feed::SubscriberSharedPtr const&), (override) ); diff --git a/tests/common/util/NameGenerator.hpp b/tests/common/util/NameGenerator.hpp index a3174e814..166b3a931 100644 --- a/tests/common/util/NameGenerator.hpp +++ b/tests/common/util/NameGenerator.hpp @@ -2,6 +2,6 @@ namespace tests::util { -static auto const kNAME_GENERATOR = [](auto const& info) { return info.param.testName; }; +static auto const kNameGenerator = [](auto const& info) { return info.param.testName; }; } // namespace tests::util diff --git a/tests/common/util/StringUtils.cpp b/tests/common/util/StringUtils.cpp index c639e011d..6fe3948bd 100644 --- a/tests/common/util/StringUtils.cpp +++ b/tests/common/util/StringUtils.cpp @@ -11,7 +11,7 @@ std::string hexStringToBinaryString(std::string const& hex) { - auto const blob = ripple::strUnHex(hex); + auto const blob = xrpl::strUnHex(hex); std::string strBlob; for (auto c : *blob) // NOLINT(bugprone-unchecked-optional-access) @@ -20,14 +20,14 @@ hexStringToBinaryString(std::string const& hex) return strBlob; } -ripple::uint256 +xrpl::uint256 binaryStringToUint256(std::string const& bin) { - return ripple::uint256::fromVoid(static_cast(bin.data())); + return xrpl::uint256::fromVoid(static_cast(bin.data())); } std::string -ledgerHeaderToBinaryString(ripple::LedgerHeader const& info) +ledgerHeaderToBinaryString(xrpl::LedgerHeader const& info) { auto const blob = rpc::ledgerHeaderToBlob(info, true); std::string strBlob; diff --git a/tests/common/util/StringUtils.hpp b/tests/common/util/StringUtils.hpp index 7a4e9250b..cc6ff5e40 100644 --- a/tests/common/util/StringUtils.hpp +++ b/tests/common/util/StringUtils.hpp @@ -9,8 +9,8 @@ std::string hexStringToBinaryString(std::string const& hex); -ripple::uint256 +xrpl::uint256 binaryStringToUint256(std::string const& bin); std::string -ledgerHeaderToBinaryString(ripple::LedgerHeader const& info); +ledgerHeaderToBinaryString(xrpl::LedgerHeader const& info); diff --git a/tests/common/util/TestHttpClient.cpp b/tests/common/util/TestHttpClient.cpp index 3b83a03ea..3c0880b17 100644 --- a/tests/common/util/TestHttpClient.cpp +++ b/tests/common/util/TestHttpClient.cpp @@ -17,7 +17,6 @@ #include #include // IWYU pragma: keep #include -#include #include #include #include diff --git a/tests/common/util/TestHttpServer.cpp b/tests/common/util/TestHttpServer.cpp index 04e36a178..8aadd1f11 100644 --- a/tests/common/util/TestHttpServer.cpp +++ b/tests/common/util/TestHttpServer.cpp @@ -14,7 +14,6 @@ #include #include #include // IWYU pragma: keep -#include #include #include diff --git a/tests/common/util/TestObject.cpp b/tests/common/util/TestObject.cpp index 388963723..3e6be2b27 100644 --- a/tests/common/util/TestObject.cpp +++ b/tests/common/util/TestObject.cpp @@ -40,73 +40,69 @@ #include namespace { -constexpr auto kINDEX1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; -ripple::Slice const kSLICE("test", 4); +constexpr auto kIndex1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; +xrpl::Slice const kSlice("test", 4); } // namespace -ripple::AccountID +xrpl::AccountID getAccountIdWithString(std::string_view id) { // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - return *util::parseBase58Wrapper(std::string(id)); + return *util::parseBase58Wrapper(std::string(id)); } -ripple::uint256 +xrpl::uint256 getAccountKey(std::string_view id) { - return ripple::keylet::account(getAccountIdWithString(id)).key; + return xrpl::keylet::account(getAccountIdWithString(id)).key; } -ripple::uint256 -getAccountKey(ripple::AccountID const& acc) +xrpl::uint256 +getAccountKey(xrpl::AccountID const& acc) { - return ripple::keylet::account(acc).key; + return xrpl::keylet::account(acc).key; } -ripple::LedgerHeader -createLedgerHeader( - std::string_view ledgerHash, - ripple::LedgerIndex seq, - std::optional age -) +xrpl::LedgerHeader +createLedgerHeader(std::string_view ledgerHash, xrpl::LedgerIndex seq, std::optional age) { using namespace std::chrono; - auto ledgerHeader = ripple::LedgerHeader(); - ledgerHeader.hash = ripple::uint256{ledgerHash}; + auto ledgerHeader = xrpl::LedgerHeader(); + ledgerHeader.hash = xrpl::uint256{ledgerHash}; ledgerHeader.seq = seq; if (age) { // Note: be cautious of using age values close to each other as the underlying NetClock // precision is seconds and the small time difference may lead to comparison bugs auto const now = duration_cast(system_clock::now().time_since_epoch()); - auto const closeTime = (now - seconds{*age}).count() - kRIPPLE_EPOCH_START; - ledgerHeader.closeTime = ripple::NetClock::time_point{seconds{closeTime}}; + auto const closeTime = (now - seconds{*age}).count() - kRippleEpochStart; + ledgerHeader.closeTime = xrpl::NetClock::time_point{seconds{closeTime}}; } return ledgerHeader; } -ripple::LedgerHeader +xrpl::LedgerHeader createLedgerHeaderWithUnixTime( std::string_view ledgerHash, - ripple::LedgerIndex seq, + xrpl::LedgerIndex seq, uint64_t closeTimeUnixStamp ) { using namespace std::chrono; - auto ledgerHeader = ripple::LedgerHeader(); - ledgerHeader.hash = ripple::uint256{ledgerHash}; + auto ledgerHeader = xrpl::LedgerHeader(); + ledgerHeader.hash = xrpl::uint256{ledgerHash}; ledgerHeader.seq = seq; - auto const closeTime = closeTimeUnixStamp - seconds{kRIPPLE_EPOCH_START}.count(); - ledgerHeader.closeTime = ripple::NetClock::time_point{seconds{closeTime}}; + auto const closeTime = closeTimeUnixStamp - seconds{kRippleEpochStart}.count(); + ledgerHeader.closeTime = xrpl::NetClock::time_point{seconds{closeTime}}; return ledgerHeader; } -ripple::STObject +xrpl::STObject createLegacyFeeSettingLedgerObject( uint64_t base, uint32_t reserveInc, @@ -115,34 +111,34 @@ createLegacyFeeSettingLedgerObject( uint32_t flag ) { - ripple::STObject obj(ripple::sfFee); - obj.setFieldU16(ripple::sfLedgerEntryType, ripple::ltFEE_SETTINGS); - obj.setFieldU64(ripple::sfBaseFee, base); - obj.setFieldU32(ripple::sfReserveIncrement, reserveInc); - obj.setFieldU32(ripple::sfReserveBase, reserveBase); - obj.setFieldU32(ripple::sfReferenceFeeUnits, refFeeUnit); - obj.setFieldU32(ripple::sfFlags, flag); + xrpl::STObject obj(xrpl::sfFee); + obj.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltFEE_SETTINGS); + obj.setFieldU64(xrpl::sfBaseFee, base); + obj.setFieldU32(xrpl::sfReserveIncrement, reserveInc); + obj.setFieldU32(xrpl::sfReserveBase, reserveBase); + obj.setFieldU32(xrpl::sfReferenceFeeUnits, refFeeUnit); + obj.setFieldU32(xrpl::sfFlags, flag); return obj; } -ripple::STObject +xrpl::STObject createFeeSettingLedgerObject( - ripple::STAmount base, - ripple::STAmount reserveInc, - ripple::STAmount reserveBase, + xrpl::STAmount base, + xrpl::STAmount reserveInc, + xrpl::STAmount reserveBase, uint32_t flag ) { - ripple::STObject obj(ripple::sfFee); - obj.setFieldU16(ripple::sfLedgerEntryType, ripple::ltFEE_SETTINGS); - obj.setFieldAmount(ripple::sfBaseFeeDrops, base); - obj.setFieldAmount(ripple::sfReserveBaseDrops, reserveBase); - obj.setFieldAmount(ripple::sfReserveIncrementDrops, reserveInc); - obj.setFieldU32(ripple::sfFlags, flag); + xrpl::STObject obj(xrpl::sfFee); + obj.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltFEE_SETTINGS); + obj.setFieldAmount(xrpl::sfBaseFeeDrops, base); + obj.setFieldAmount(xrpl::sfReserveBaseDrops, reserveBase); + obj.setFieldAmount(xrpl::sfReserveIncrementDrops, reserveInc); + obj.setFieldU32(xrpl::sfFlags, flag); return obj; } -ripple::Blob +xrpl::Blob createLegacyFeeSettingBlob( uint64_t base, uint32_t reserveInc, @@ -155,11 +151,11 @@ createLegacyFeeSettingBlob( return lo.getSerializer().peekData(); } -ripple::Blob +xrpl::Blob createFeeSettingBlob( - ripple::STAmount base, - ripple::STAmount reserveInc, - ripple::STAmount reserveBase, + xrpl::STAmount base, + xrpl::STAmount reserveInc, + xrpl::STAmount reserveBase, uint32_t flag ) { @@ -167,7 +163,7 @@ createFeeSettingBlob( return lo.getSerializer().peekData(); } -ripple::STObject +xrpl::STObject createPaymentTransactionObject( std::string_view accountId1, std::string_view accountId2, @@ -176,21 +172,21 @@ createPaymentTransactionObject( uint32_t seq ) { - ripple::STObject obj(ripple::sfTransaction); - obj.setFieldU16(ripple::sfTransactionType, ripple::ttPAYMENT); - auto account = util::parseBase58Wrapper(std::string(accountId1)); - obj.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) - obj.setFieldAmount(ripple::sfAmount, ripple::STAmount(amount, false)); - obj.setFieldAmount(ripple::sfFee, ripple::STAmount(fee, false)); - auto account2 = util::parseBase58Wrapper(std::string(accountId2)); + xrpl::STObject obj(xrpl::sfTransaction); + obj.setFieldU16(xrpl::sfTransactionType, xrpl::ttPAYMENT); + auto account = util::parseBase58Wrapper(std::string(accountId1)); + obj.setAccountID(xrpl::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) + obj.setFieldAmount(xrpl::sfAmount, xrpl::STAmount(amount, false)); + obj.setFieldAmount(xrpl::sfFee, xrpl::STAmount(fee, false)); + auto account2 = util::parseBase58Wrapper(std::string(accountId2)); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - obj.setAccountID(ripple::sfDestination, *account2); - obj.setFieldU32(ripple::sfSequence, seq); - obj.setFieldVL(ripple::sfSigningPubKey, kSLICE); + obj.setAccountID(xrpl::sfDestination, *account2); + obj.setFieldU32(xrpl::sfSequence, seq); + obj.setFieldVL(xrpl::sfSigningPubKey, kSlice); return obj; } -ripple::STObject +xrpl::STObject createPaymentTransactionMetaObject( std::string_view accountId1, std::string_view accountId2, @@ -199,31 +195,31 @@ createPaymentTransactionMetaObject( uint32_t transactionIndex ) { - ripple::STObject finalFields(ripple::sfFinalFields); - finalFields.setAccountID(ripple::sfAccount, getAccountIdWithString(accountId1)); - finalFields.setFieldAmount(ripple::sfBalance, ripple::STAmount(finalBalance1)); + xrpl::STObject finalFields(xrpl::sfFinalFields); + finalFields.setAccountID(xrpl::sfAccount, getAccountIdWithString(accountId1)); + finalFields.setFieldAmount(xrpl::sfBalance, xrpl::STAmount(finalBalance1)); - ripple::STObject finalFields2(ripple::sfFinalFields); - finalFields2.setAccountID(ripple::sfAccount, getAccountIdWithString(accountId2)); - finalFields2.setFieldAmount(ripple::sfBalance, ripple::STAmount(finalBalance2)); + xrpl::STObject finalFields2(xrpl::sfFinalFields); + finalFields2.setAccountID(xrpl::sfAccount, getAccountIdWithString(accountId2)); + finalFields2.setFieldAmount(xrpl::sfBalance, xrpl::STAmount(finalBalance2)); - ripple::STObject metaObj(ripple::sfTransactionMetaData); - ripple::STArray metaArray{2}; - ripple::STObject node(ripple::sfModifiedNode); - node.setFieldU16(ripple::sfLedgerEntryType, ripple::ltACCOUNT_ROOT); - node.emplace_back(std::move(finalFields)); + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + xrpl::STArray metaArray{2}; + xrpl::STObject node(xrpl::sfModifiedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltACCOUNT_ROOT); + node.set(std::move(finalFields)); metaArray.push_back(node); - ripple::STObject node2(ripple::sfModifiedNode); - node2.setFieldU16(ripple::sfLedgerEntryType, ripple::ltACCOUNT_ROOT); - node2.emplace_back(std::move(finalFields2)); + xrpl::STObject node2(xrpl::sfModifiedNode); + node2.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltACCOUNT_ROOT); + node2.set(std::move(finalFields2)); metaArray.push_back(node2); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, transactionIndex); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, transactionIndex); return metaObj; } -ripple::STObject +xrpl::STObject createDidObject( std::string_view accountId, std::string_view didDoc, @@ -231,23 +227,23 @@ createDidObject( std::string_view data ) { - ripple::STObject did(ripple::sfLedgerEntry); - did.setAccountID(ripple::sfAccount, getAccountIdWithString(accountId)); - did.setFieldU16(ripple::sfLedgerEntryType, ripple::ltDID); - did.setFieldU32(ripple::sfFlags, 0); - did.setFieldU64(ripple::sfOwnerNode, 0); - did.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - did.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); - ripple::Slice const sliceDoc(didDoc.data(), didDoc.size()); - did.setFieldVL(ripple::sfDIDDocument, sliceDoc); - ripple::Slice const sliceUri(uri.data(), uri.size()); - did.setFieldVL(ripple::sfURI, sliceUri); - ripple::Slice const sliceData(data.data(), data.size()); - did.setFieldVL(ripple::sfData, sliceData); + xrpl::STObject did(xrpl::sfLedgerEntry); + did.setAccountID(xrpl::sfAccount, getAccountIdWithString(accountId)); + did.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltDID); + did.setFieldU32(xrpl::sfFlags, 0); + did.setFieldU64(xrpl::sfOwnerNode, 0); + did.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + did.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); + xrpl::Slice const sliceDoc(didDoc.data(), didDoc.size()); + did.setFieldVL(xrpl::sfDIDDocument, sliceDoc); + xrpl::Slice const sliceUri(uri.data(), uri.size()); + did.setFieldVL(xrpl::sfURI, sliceUri); + xrpl::Slice const sliceData(data.data(), data.size()); + did.setFieldVL(xrpl::sfData, sliceData); return did; } -ripple::STObject +xrpl::STObject createAccountRootObject( std::string_view accountId, uint32_t flag, @@ -257,27 +253,27 @@ createAccountRootObject( std::string_view previousTxnID, uint32_t previousTxnSeq, uint32_t transferRate, - std::optional ammID + std::optional ammID ) { - ripple::STObject accountRoot(ripple::sfAccount); - accountRoot.setFieldU16(ripple::sfLedgerEntryType, ripple::ltACCOUNT_ROOT); - accountRoot.setFieldU32(ripple::sfFlags, flag); - accountRoot.setAccountID(ripple::sfAccount, getAccountIdWithString(accountId)); - accountRoot.setFieldU32(ripple::sfSequence, seq); - accountRoot.setFieldAmount(ripple::sfBalance, ripple::STAmount(balance, false)); - accountRoot.setFieldU32(ripple::sfOwnerCount, ownerCount); - accountRoot.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{previousTxnID}); - accountRoot.setFieldU32(ripple::sfPreviousTxnLgrSeq, previousTxnSeq); - accountRoot.setFieldU32(ripple::sfTransferRate, transferRate); + xrpl::STObject accountRoot(xrpl::sfAccount); + accountRoot.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltACCOUNT_ROOT); + accountRoot.setFieldU32(xrpl::sfFlags, flag); + accountRoot.setAccountID(xrpl::sfAccount, getAccountIdWithString(accountId)); + accountRoot.setFieldU32(xrpl::sfSequence, seq); + accountRoot.setFieldAmount(xrpl::sfBalance, xrpl::STAmount(balance, false)); + accountRoot.setFieldU32(xrpl::sfOwnerCount, ownerCount); + accountRoot.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{previousTxnID}); + accountRoot.setFieldU32(xrpl::sfPreviousTxnLgrSeq, previousTxnSeq); + accountRoot.setFieldU32(xrpl::sfTransferRate, transferRate); if (ammID) - accountRoot.setFieldH256(ripple::sfAMMID, *ammID); + accountRoot.setFieldH256(xrpl::sfAMMID, *ammID); return accountRoot; } -ripple::STObject +xrpl::STObject createCreateOfferTransactionObject( std::string_view accountId, int fee, @@ -289,52 +285,52 @@ createCreateOfferTransactionObject( bool reverse ) { - ripple::STObject obj(ripple::sfTransaction); - obj.setFieldU16(ripple::sfTransactionType, ripple::ttOFFER_CREATE); - auto account = util::parseBase58Wrapper(std::string(accountId)); - obj.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) - auto amount = ripple::STAmount(fee, false); - obj.setFieldAmount(ripple::sfFee, amount); - obj.setFieldU32(ripple::sfSequence, seq); + xrpl::STObject obj(xrpl::sfTransaction); + obj.setFieldU16(xrpl::sfTransactionType, xrpl::ttOFFER_CREATE); + auto account = util::parseBase58Wrapper(std::string(accountId)); + obj.setAccountID(xrpl::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) + auto amount = xrpl::STAmount(fee, false); + obj.setFieldAmount(xrpl::sfFee, amount); + obj.setFieldU32(xrpl::sfSequence, seq); // add amount - ripple::Issue const issue1( - ripple::Currency{currency}, + xrpl::Issue const issue1( + xrpl::Currency{currency}, // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - *util::parseBase58Wrapper(std::string(issuer)) + *util::parseBase58Wrapper(std::string(issuer)) ); if (reverse) { - obj.setFieldAmount(ripple::sfTakerPays, ripple::STAmount(issue1, takerGets)); - obj.setFieldAmount(ripple::sfTakerGets, ripple::STAmount(takerPays, false)); + obj.setFieldAmount(xrpl::sfTakerPays, xrpl::STAmount(issue1, takerGets)); + obj.setFieldAmount(xrpl::sfTakerGets, xrpl::STAmount(takerPays, false)); } else { - obj.setFieldAmount(ripple::sfTakerGets, ripple::STAmount(issue1, takerGets)); - obj.setFieldAmount(ripple::sfTakerPays, ripple::STAmount(takerPays, false)); + obj.setFieldAmount(xrpl::sfTakerGets, xrpl::STAmount(issue1, takerGets)); + obj.setFieldAmount(xrpl::sfTakerPays, xrpl::STAmount(takerPays, false)); } auto key = "test"; - ripple::Slice const slice(key, 4); - obj.setFieldVL(ripple::sfSigningPubKey, slice); + xrpl::Slice const slice(key, 4); + obj.setFieldVL(xrpl::sfSigningPubKey, slice); return obj; } -ripple::Issue +xrpl::Issue getIssue(std::string_view currency, std::string_view issuerId) { // standard currency if (currency.size() == 3) { - return ripple::Issue( - ripple::to_currency(std::string(currency)), + return xrpl::Issue( + xrpl::toCurrency(std::string(currency)), // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - *util::parseBase58Wrapper(std::string(issuerId)) + *util::parseBase58Wrapper(std::string(issuerId)) ); } - return ripple::Issue( - ripple::Currency{currency}, + return xrpl::Issue( + xrpl::Currency{currency}, // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - *util::parseBase58Wrapper(std::string(issuerId)) + *util::parseBase58Wrapper(std::string(issuerId)) ); } -ripple::STObject +xrpl::STObject createMetaDataForBookChange( std::string_view currency, std::string_view issueId, @@ -346,29 +342,29 @@ createMetaDataForBookChange( std::optional domain ) { - ripple::STObject finalFields(ripple::sfFinalFields); - ripple::Issue const issue1 = getIssue(currency, issueId); - finalFields.setFieldAmount(ripple::sfTakerPays, ripple::STAmount(issue1, finalTakerPays)); - finalFields.setFieldAmount(ripple::sfTakerGets, ripple::STAmount(finalTakerGets, false)); + xrpl::STObject finalFields(xrpl::sfFinalFields); + xrpl::Issue const issue1 = getIssue(currency, issueId); + finalFields.setFieldAmount(xrpl::sfTakerPays, xrpl::STAmount(issue1, finalTakerPays)); + finalFields.setFieldAmount(xrpl::sfTakerGets, xrpl::STAmount(finalTakerGets, false)); if (domain.has_value()) - finalFields.setFieldH256(ripple::sfDomainID, ripple::uint256{*domain}); - ripple::STObject previousFields(ripple::sfPreviousFields); - previousFields.setFieldAmount(ripple::sfTakerPays, ripple::STAmount(issue1, previousTakerPays)); - previousFields.setFieldAmount(ripple::sfTakerGets, ripple::STAmount(previousTakerGets, false)); - ripple::STObject metaObj(ripple::sfTransactionMetaData); - ripple::STArray metaArray{1}; - ripple::STObject node(ripple::sfModifiedNode); - node.setFieldU16(ripple::sfLedgerEntryType, ripple::ltOFFER); - node.emplace_back(std::move(finalFields)); - node.emplace_back(std::move(previousFields)); + finalFields.setFieldH256(xrpl::sfDomainID, xrpl::uint256{*domain}); + xrpl::STObject previousFields(xrpl::sfPreviousFields); + previousFields.setFieldAmount(xrpl::sfTakerPays, xrpl::STAmount(issue1, previousTakerPays)); + previousFields.setFieldAmount(xrpl::sfTakerGets, xrpl::STAmount(previousTakerGets, false)); + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + xrpl::STArray metaArray{1}; + xrpl::STObject node(xrpl::sfModifiedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltOFFER); + node.set(std::move(finalFields)); + node.set(std::move(previousFields)); metaArray.push_back(node); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, transactionIndex); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, transactionIndex); return metaObj; } -ripple::STObject +xrpl::STObject createMetaDataForCreateOffer( std::string_view currency, std::string_view issueId, @@ -378,28 +374,28 @@ createMetaDataForCreateOffer( bool reverse ) { - ripple::STObject finalFields(ripple::sfNewFields); - ripple::Issue const issue1 = getIssue(currency, issueId); + xrpl::STObject finalFields(xrpl::sfNewFields); + xrpl::Issue const issue1 = getIssue(currency, issueId); if (reverse) { - finalFields.setFieldAmount(ripple::sfTakerGets, ripple::STAmount(issue1, finalTakerPays)); - finalFields.setFieldAmount(ripple::sfTakerPays, ripple::STAmount(finalTakerGets, false)); + finalFields.setFieldAmount(xrpl::sfTakerGets, xrpl::STAmount(issue1, finalTakerPays)); + finalFields.setFieldAmount(xrpl::sfTakerPays, xrpl::STAmount(finalTakerGets, false)); } else { - finalFields.setFieldAmount(ripple::sfTakerPays, ripple::STAmount(issue1, finalTakerPays)); - finalFields.setFieldAmount(ripple::sfTakerGets, ripple::STAmount(finalTakerGets, false)); + finalFields.setFieldAmount(xrpl::sfTakerPays, xrpl::STAmount(issue1, finalTakerPays)); + finalFields.setFieldAmount(xrpl::sfTakerGets, xrpl::STAmount(finalTakerGets, false)); } - ripple::STObject metaObj(ripple::sfTransactionMetaData); - ripple::STArray metaArray{1}; - ripple::STObject node(ripple::sfCreatedNode); - node.setFieldU16(ripple::sfLedgerEntryType, ripple::ltOFFER); - node.emplace_back(std::move(finalFields)); + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + xrpl::STArray metaArray{1}; + xrpl::STObject node(xrpl::sfCreatedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltOFFER); + node.set(std::move(finalFields)); metaArray.push_back(node); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, transactionIndex); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, transactionIndex); return metaObj; } -ripple::STObject +xrpl::STObject createMetaDataForCancelOffer( std::string_view currency, std::string_view issueId, @@ -408,34 +404,34 @@ createMetaDataForCancelOffer( int finalTakerPays ) { - ripple::STObject finalFields(ripple::sfFinalFields); - ripple::Issue const issue1 = getIssue(currency, issueId); - finalFields.setFieldAmount(ripple::sfTakerPays, ripple::STAmount(issue1, finalTakerPays)); - finalFields.setFieldAmount(ripple::sfTakerGets, ripple::STAmount(finalTakerGets, false)); - ripple::STObject metaObj(ripple::sfTransactionMetaData); - ripple::STArray metaArray{1}; - ripple::STObject node(ripple::sfDeletedNode); - node.setFieldU16(ripple::sfLedgerEntryType, ripple::ltOFFER); - node.emplace_back(std::move(finalFields)); + xrpl::STObject finalFields(xrpl::sfFinalFields); + xrpl::Issue const issue1 = getIssue(currency, issueId); + finalFields.setFieldAmount(xrpl::sfTakerPays, xrpl::STAmount(issue1, finalTakerPays)); + finalFields.setFieldAmount(xrpl::sfTakerGets, xrpl::STAmount(finalTakerGets, false)); + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + xrpl::STArray metaArray{1}; + xrpl::STObject node(xrpl::sfDeletedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltOFFER); + node.set(std::move(finalFields)); metaArray.push_back(node); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, transactionIndex); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, transactionIndex); return metaObj; } -ripple::STObject -createOwnerDirLedgerObject(std::vector indexes, std::string_view rootIndex) +xrpl::STObject +createOwnerDirLedgerObject(std::vector indexes, std::string_view rootIndex) { - ripple::STObject ownerDir(ripple::sfLedgerEntry); - ownerDir.setFieldU16(ripple::sfLedgerEntryType, ripple::ltDIR_NODE); - ownerDir.setFieldV256(ripple::sfIndexes, ripple::STVector256{indexes}); - ownerDir.setFieldH256(ripple::sfRootIndex, ripple::uint256{rootIndex}); - ownerDir.setFieldU32(ripple::sfFlags, 0); + xrpl::STObject ownerDir(xrpl::sfLedgerEntry); + ownerDir.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltDIR_NODE); + ownerDir.setFieldV256(xrpl::sfIndexes, xrpl::STVector256{indexes}); + ownerDir.setFieldH256(xrpl::sfRootIndex, xrpl::uint256{rootIndex}); + ownerDir.setFieldU32(xrpl::sfFlags, 0); return ownerDir; } -ripple::STObject +xrpl::STObject createPaymentChannelLedgerObject( std::string_view accountId, std::string_view destId, @@ -446,25 +442,25 @@ createPaymentChannelLedgerObject( uint32_t previousTxnSeq ) { - ripple::STObject channel(ripple::sfLedgerEntry); - channel.setFieldU16(ripple::sfLedgerEntryType, ripple::ltPAYCHAN); - channel.setAccountID(ripple::sfAccount, getAccountIdWithString(accountId)); - channel.setAccountID(ripple::sfDestination, getAccountIdWithString(destId)); - channel.setFieldAmount(ripple::sfAmount, ripple::STAmount(amount, false)); - channel.setFieldAmount(ripple::sfBalance, ripple::STAmount(balance, false)); - channel.setFieldU32(ripple::sfSettleDelay, settleDelay); - channel.setFieldU64(ripple::sfOwnerNode, 0); - channel.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{previousTxnId}); - channel.setFieldU32(ripple::sfPreviousTxnLgrSeq, previousTxnSeq); - channel.setFieldU32(ripple::sfFlags, 0); + xrpl::STObject channel(xrpl::sfLedgerEntry); + channel.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltPAYCHAN); + channel.setAccountID(xrpl::sfAccount, getAccountIdWithString(accountId)); + channel.setAccountID(xrpl::sfDestination, getAccountIdWithString(destId)); + channel.setFieldAmount(xrpl::sfAmount, xrpl::STAmount(amount, false)); + channel.setFieldAmount(xrpl::sfBalance, xrpl::STAmount(balance, false)); + channel.setFieldU32(xrpl::sfSettleDelay, settleDelay); + channel.setFieldU64(xrpl::sfOwnerNode, 0); + channel.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{previousTxnId}); + channel.setFieldU32(xrpl::sfPreviousTxnLgrSeq, previousTxnSeq); + channel.setFieldU32(xrpl::sfFlags, 0); uint8_t key[33] = {0}; key[0] = 2; // KeyType::secp256k1 - ripple::Slice const slice(key, 33); - channel.setFieldVL(ripple::sfPublicKey, slice); + xrpl::Slice const slice(key, 33); + channel.setFieldVL(xrpl::sfPublicKey, slice); return channel; } -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createRippleStateLedgerObject( std::string_view currency, std::string_view issuerId, @@ -478,22 +474,22 @@ createRippleStateLedgerObject( uint32_t flag ) { - auto line = ripple::STObject(ripple::sfLedgerEntry); - line.setFieldU16(ripple::sfLedgerEntryType, ripple::ltRIPPLE_STATE); - line.setFieldU32(ripple::sfFlags, flag); - line.setFieldAmount(ripple::sfBalance, ripple::STAmount(getIssue(currency, issuerId), balance)); + auto line = xrpl::STObject(xrpl::sfLedgerEntry); + line.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltRIPPLE_STATE); + line.setFieldU32(xrpl::sfFlags, flag); + line.setFieldAmount(xrpl::sfBalance, xrpl::STAmount(getIssue(currency, issuerId), balance)); line.setFieldAmount( - ripple::sfHighLimit, ripple::STAmount(getIssue(currency, highNodeAccountId), highLimit) + xrpl::sfHighLimit, xrpl::STAmount(getIssue(currency, highNodeAccountId), highLimit) ); line.setFieldAmount( - ripple::sfLowLimit, ripple::STAmount(getIssue(currency, lowNodeAccountId), lowLimit) + xrpl::sfLowLimit, xrpl::STAmount(getIssue(currency, lowNodeAccountId), lowLimit) ); - line.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{previousTxnId}); - line.setFieldU32(ripple::sfPreviousTxnLgrSeq, previousTxnSeq); + line.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{previousTxnId}); + line.setFieldU32(xrpl::sfPreviousTxnLgrSeq, previousTxnSeq); return line; } -ripple::STObject +xrpl::STObject createOfferLedgerObject( std::string_view account, int takerGets, @@ -506,106 +502,106 @@ createOfferLedgerObject( std::optional domain ) { - ripple::STObject offer(ripple::sfLedgerEntry); - offer.setFieldU16(ripple::sfLedgerEntryType, ripple::ltOFFER); - offer.setAccountID(ripple::sfAccount, getAccountIdWithString(account)); - offer.setFieldU32(ripple::sfSequence, 0); - offer.setFieldU32(ripple::sfFlags, 0); - ripple::Issue const issue1 = getIssue(getsCurrency, getsIssueId); - offer.setFieldAmount(ripple::sfTakerGets, ripple::STAmount(issue1, takerGets)); - ripple::Issue const issue2 = getIssue(paysCurrency, paysIssueId); - offer.setFieldAmount(ripple::sfTakerPays, ripple::STAmount(issue2, takerPays)); - offer.setFieldH256(ripple::sfBookDirectory, ripple::uint256{}); - offer.setFieldU64(ripple::sfBookNode, 0); - offer.setFieldU64(ripple::sfOwnerNode, 0); - offer.setFieldH256(ripple::sfBookDirectory, ripple::uint256{dirId}); - offer.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - offer.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); + xrpl::STObject offer(xrpl::sfLedgerEntry); + offer.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltOFFER); + offer.setAccountID(xrpl::sfAccount, getAccountIdWithString(account)); + offer.setFieldU32(xrpl::sfSequence, 0); + offer.setFieldU32(xrpl::sfFlags, 0); + xrpl::Issue const issue1 = getIssue(getsCurrency, getsIssueId); + offer.setFieldAmount(xrpl::sfTakerGets, xrpl::STAmount(issue1, takerGets)); + xrpl::Issue const issue2 = getIssue(paysCurrency, paysIssueId); + offer.setFieldAmount(xrpl::sfTakerPays, xrpl::STAmount(issue2, takerPays)); + offer.setFieldH256(xrpl::sfBookDirectory, xrpl::uint256{}); + offer.setFieldU64(xrpl::sfBookNode, 0); + offer.setFieldU64(xrpl::sfOwnerNode, 0); + offer.setFieldH256(xrpl::sfBookDirectory, xrpl::uint256{dirId}); + offer.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + offer.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); if (domain.has_value()) - offer.setFieldH256(ripple::sfDomainID, ripple::uint256{*domain}); + offer.setFieldH256(xrpl::sfDomainID, xrpl::uint256{*domain}); return offer; } -ripple::STObject +xrpl::STObject createTicketLedgerObject(std::string_view account, uint32_t sequence) { - ripple::STObject ticket(ripple::sfLedgerEntry); - ticket.setFieldU16(ripple::sfLedgerEntryType, ripple::ltTICKET); - ticket.setAccountID(ripple::sfAccount, getAccountIdWithString(account)); - ticket.setFieldU32(ripple::sfFlags, 0); - ticket.setFieldU64(ripple::sfOwnerNode, 0); - ticket.setFieldU32(ripple::sfTicketSequence, sequence); - ticket.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - ticket.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); + xrpl::STObject ticket(xrpl::sfLedgerEntry); + ticket.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltTICKET); + ticket.setAccountID(xrpl::sfAccount, getAccountIdWithString(account)); + ticket.setFieldU32(xrpl::sfFlags, 0); + ticket.setFieldU64(xrpl::sfOwnerNode, 0); + ticket.setFieldU32(xrpl::sfTicketSequence, sequence); + ticket.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + ticket.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); return ticket; } -ripple::STObject +xrpl::STObject createEscrowLedgerObject(std::string_view account, std::string_view dest) { - ripple::STObject escrow(ripple::sfLedgerEntry); - escrow.setFieldU16(ripple::sfLedgerEntryType, ripple::ltESCROW); - escrow.setAccountID(ripple::sfAccount, getAccountIdWithString(account)); - escrow.setAccountID(ripple::sfDestination, getAccountIdWithString(dest)); - escrow.setFieldAmount(ripple::sfAmount, ripple::STAmount(0, false)); - escrow.setFieldU64(ripple::sfOwnerNode, 0); - escrow.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - escrow.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); - escrow.setFieldU32(ripple::sfFlags, 0); + xrpl::STObject escrow(xrpl::sfLedgerEntry); + escrow.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltESCROW); + escrow.setAccountID(xrpl::sfAccount, getAccountIdWithString(account)); + escrow.setAccountID(xrpl::sfDestination, getAccountIdWithString(dest)); + escrow.setFieldAmount(xrpl::sfAmount, xrpl::STAmount(0, false)); + escrow.setFieldU64(xrpl::sfOwnerNode, 0); + escrow.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + escrow.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); + escrow.setFieldU32(xrpl::sfFlags, 0); return escrow; } -ripple::STObject +xrpl::STObject createCheckLedgerObject(std::string_view account, std::string_view dest) { - ripple::STObject check(ripple::sfLedgerEntry); - check.setFieldU16(ripple::sfLedgerEntryType, ripple::ltCHECK); - check.setAccountID(ripple::sfAccount, getAccountIdWithString(account)); - check.setAccountID(ripple::sfDestination, getAccountIdWithString(dest)); - check.setFieldU32(ripple::sfFlags, 0); - check.setFieldU64(ripple::sfOwnerNode, 0); - check.setFieldU64(ripple::sfDestinationNode, 0); - check.setFieldAmount(ripple::sfSendMax, ripple::STAmount(0, false)); - check.setFieldU32(ripple::sfSequence, 0); - check.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - check.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); + xrpl::STObject check(xrpl::sfLedgerEntry); + check.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltCHECK); + check.setAccountID(xrpl::sfAccount, getAccountIdWithString(account)); + check.setAccountID(xrpl::sfDestination, getAccountIdWithString(dest)); + check.setFieldU32(xrpl::sfFlags, 0); + check.setFieldU64(xrpl::sfOwnerNode, 0); + check.setFieldU64(xrpl::sfDestinationNode, 0); + check.setFieldAmount(xrpl::sfSendMax, xrpl::STAmount(0, false)); + check.setFieldU32(xrpl::sfSequence, 0); + check.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + check.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); return check; } -ripple::STObject +xrpl::STObject createDepositPreauthLedgerObjectByAuth(std::string_view account, std::string_view auth) { - ripple::STObject depositPreauth(ripple::sfLedgerEntry); - depositPreauth.setFieldU16(ripple::sfLedgerEntryType, ripple::ltDEPOSIT_PREAUTH); - depositPreauth.setAccountID(ripple::sfAccount, getAccountIdWithString(account)); - depositPreauth.setAccountID(ripple::sfAuthorize, getAccountIdWithString(auth)); - depositPreauth.setFieldU32(ripple::sfFlags, 0); - depositPreauth.setFieldU64(ripple::sfOwnerNode, 0); - depositPreauth.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - depositPreauth.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); + xrpl::STObject depositPreauth(xrpl::sfLedgerEntry); + depositPreauth.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltDEPOSIT_PREAUTH); + depositPreauth.setAccountID(xrpl::sfAccount, getAccountIdWithString(account)); + depositPreauth.setAccountID(xrpl::sfAuthorize, getAccountIdWithString(auth)); + depositPreauth.setFieldU32(xrpl::sfFlags, 0); + depositPreauth.setFieldU64(xrpl::sfOwnerNode, 0); + depositPreauth.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + depositPreauth.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); return depositPreauth; } -ripple::STObject +xrpl::STObject createDepositPreauthLedgerObjectByAuthCredentials( std::string_view account, std::string_view issuer, std::string_view credType ) { - ripple::STObject depositPreauth(ripple::sfLedgerEntry); - depositPreauth.setFieldU16(ripple::sfLedgerEntryType, ripple::ltDEPOSIT_PREAUTH); - depositPreauth.setAccountID(ripple::sfAccount, getAccountIdWithString(account)); + xrpl::STObject depositPreauth(xrpl::sfLedgerEntry); + depositPreauth.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltDEPOSIT_PREAUTH); + depositPreauth.setAccountID(xrpl::sfAccount, getAccountIdWithString(account)); depositPreauth.setFieldArray( - ripple::sfAuthorizeCredentials, + xrpl::sfAuthorizeCredentials, createAuthCredentialArray( std::vector{issuer}, std::vector{credType} ) ); - depositPreauth.setFieldU32(ripple::sfFlags, 0); - depositPreauth.setFieldU64(ripple::sfOwnerNode, 0); - depositPreauth.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - depositPreauth.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); + depositPreauth.setFieldU32(xrpl::sfFlags, 0); + depositPreauth.setFieldU64(xrpl::sfOwnerNode, 0); + depositPreauth.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + depositPreauth.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); return depositPreauth; } @@ -613,91 +609,91 @@ data::NFT createNft( std::string_view tokenID, std::string_view account, - ripple::LedgerIndex seq, - ripple::Blob uri, + xrpl::LedgerIndex seq, + xrpl::Blob uri, bool isBurned ) { - return data::NFT{ripple::uint256(tokenID), seq, getAccountIdWithString(account), uri, isBurned}; + return data::NFT{xrpl::uint256(tokenID), seq, getAccountIdWithString(account), uri, isBurned}; } -ripple::STObject +xrpl::STObject createNftBuyOffer(std::string_view tokenID, std::string_view account) { - ripple::STObject offer(ripple::sfLedgerEntry); - offer.setFieldH256(ripple::sfNFTokenID, ripple::uint256{tokenID}); - offer.setFieldU16(ripple::sfLedgerEntryType, ripple::ltNFTOKEN_OFFER); - offer.setFieldU32(ripple::sfFlags, 0u); - offer.setFieldAmount(ripple::sfAmount, ripple::STAmount{123}); - offer.setFieldU64(ripple::sfOwnerNode, 0ul); - offer.setAccountID(ripple::sfOwner, getAccountIdWithString(account)); - offer.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - offer.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0u); - offer.setFieldU64(ripple::sfNFTokenOfferNode, 0ul); + xrpl::STObject offer(xrpl::sfLedgerEntry); + offer.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{tokenID}); + offer.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltNFTOKEN_OFFER); + offer.setFieldU32(xrpl::sfFlags, 0u); + offer.setFieldAmount(xrpl::sfAmount, xrpl::STAmount{123}); + offer.setFieldU64(xrpl::sfOwnerNode, 0ul); + offer.setAccountID(xrpl::sfOwner, getAccountIdWithString(account)); + offer.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + offer.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0u); + offer.setFieldU64(xrpl::sfNFTokenOfferNode, 0ul); return offer; } -ripple::STObject +xrpl::STObject createNftSellOffer(std::string_view tokenID, std::string_view account) { - ripple::STObject offer(ripple::sfLedgerEntry); - offer.setFieldH256(ripple::sfNFTokenID, ripple::uint256{tokenID}); - offer.setFieldU16(ripple::sfLedgerEntryType, ripple::ltNFTOKEN_OFFER); - offer.setFieldU32(ripple::sfFlags, 0u); - offer.setFieldAmount(ripple::sfAmount, ripple::STAmount{123}); - offer.setFieldU64(ripple::sfOwnerNode, 0ul); - offer.setAccountID(ripple::sfOwner, getAccountIdWithString(account)); - offer.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - offer.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0u); - offer.setFieldU64(ripple::sfNFTokenOfferNode, 0ul); + xrpl::STObject offer(xrpl::sfLedgerEntry); + offer.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{tokenID}); + offer.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltNFTOKEN_OFFER); + offer.setFieldU32(xrpl::sfFlags, 0u); + offer.setFieldAmount(xrpl::sfAmount, xrpl::STAmount{123}); + offer.setFieldU64(xrpl::sfOwnerNode, 0ul); + offer.setAccountID(xrpl::sfOwner, getAccountIdWithString(account)); + offer.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + offer.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0u); + offer.setFieldU64(xrpl::sfNFTokenOfferNode, 0ul); return offer; } -ripple::STObject +xrpl::STObject createSignerLists(std::vector> const& signers) { - auto signerlists = ripple::STObject(ripple::sfLedgerEntry); - signerlists.setFieldU16(ripple::sfLedgerEntryType, ripple::ltSIGNER_LIST); - signerlists.setFieldU32(ripple::sfFlags, 0); - signerlists.setFieldU64(ripple::sfOwnerNode, 0); - signerlists.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256()); - signerlists.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); - signerlists.setFieldU32(ripple::sfSignerListID, 0); + auto signerlists = xrpl::STObject(xrpl::sfLedgerEntry); + signerlists.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltSIGNER_LIST); + signerlists.setFieldU32(xrpl::sfFlags, 0); + signerlists.setFieldU64(xrpl::sfOwnerNode, 0); + signerlists.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256()); + signerlists.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); + signerlists.setFieldU32(xrpl::sfSignerListID, 0); uint32_t quorum = 0; - ripple::STArray list; + xrpl::STArray list; for (auto const& signer : signers) { - auto entry = ripple::STObject(ripple::sfSignerEntry); - entry.setAccountID(ripple::sfAccount, getAccountIdWithString(signer.first)); - entry.setFieldU16(ripple::sfSignerWeight, signer.second); + auto entry = xrpl::STObject(xrpl::sfSignerEntry); + entry.setAccountID(xrpl::sfAccount, getAccountIdWithString(signer.first)); + entry.setFieldU16(xrpl::sfSignerWeight, signer.second); quorum += signer.second; list.push_back(std::move(entry)); } - signerlists.setFieldU32(ripple::sfSignerQuorum, quorum); - signerlists.setFieldArray(ripple::sfSignerEntries, list); + signerlists.setFieldU32(xrpl::sfSignerQuorum, quorum); + signerlists.setFieldArray(xrpl::sfSignerEntries, list); return signerlists; } -ripple::STObject +xrpl::STObject createNftTokenPage( std::vector> const& tokens, - std::optional previousPage + std::optional previousPage ) { - auto tokenPage = ripple::STObject(ripple::sfLedgerEntry); - tokenPage.setFieldU16(ripple::sfLedgerEntryType, ripple::ltNFTOKEN_PAGE); - tokenPage.setFieldU32(ripple::sfFlags, 0); - tokenPage.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256()); - tokenPage.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); + auto tokenPage = xrpl::STObject(xrpl::sfLedgerEntry); + tokenPage.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltNFTOKEN_PAGE); + tokenPage.setFieldU32(xrpl::sfFlags, 0); + tokenPage.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256()); + tokenPage.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); if (previousPage) - tokenPage.setFieldH256(ripple::sfPreviousPageMin, *previousPage); - ripple::STArray list; + tokenPage.setFieldH256(xrpl::sfPreviousPageMin, *previousPage); + xrpl::STArray list; for (auto const& token : tokens) { - auto entry = ripple::STObject(ripple::sfNFToken); - entry.setFieldH256(ripple::sfNFTokenID, ripple::uint256{token.first.c_str()}); - entry.setFieldVL(ripple::sfURI, ripple::Slice(token.second.c_str(), token.second.size())); + auto entry = xrpl::STObject(xrpl::sfNFToken); + entry.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{token.first.c_str()}); + entry.setFieldVL(xrpl::sfURI, xrpl::Slice(token.second.c_str(), token.second.size())); list.push_back(std::move(entry)); } - tokenPage.setFieldArray(ripple::sfNFTokens, list); + tokenPage.setFieldArray(xrpl::sfNFTokens, list); return tokenPage; } @@ -711,50 +707,50 @@ createMintNftTxWithMetadata( ) { // tx - ripple::STObject tx(ripple::sfTransaction); - tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_MINT); - auto account = util::parseBase58Wrapper(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) - auto amount = ripple::STAmount(fee, false); - tx.setFieldAmount(ripple::sfFee, amount); + xrpl::STObject tx(xrpl::sfTransaction); + tx.setFieldU16(xrpl::sfTransactionType, xrpl::ttNFTOKEN_MINT); + auto account = util::parseBase58Wrapper(std::string(accountId)); + tx.setAccountID(xrpl::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) + auto amount = xrpl::STAmount(fee, false); + tx.setFieldAmount(xrpl::sfFee, amount); // required field for ttNFTOKEN_MINT - tx.setFieldU32(ripple::sfNFTokenTaxon, nfTokenTaxon); - tx.setFieldU32(ripple::sfSequence, seq); - tx.setFieldVL(ripple::sfSigningPubKey, kSLICE); + tx.setFieldU32(xrpl::sfNFTokenTaxon, nfTokenTaxon); + tx.setFieldU32(xrpl::sfSequence, seq); + tx.setFieldVL(xrpl::sfSigningPubKey, kSlice); // meta - ripple::STObject metaObj(ripple::sfTransactionMetaData); - ripple::STArray metaArray{1}; - ripple::STObject node(ripple::sfModifiedNode); - node.setFieldU16(ripple::sfLedgerEntryType, ripple::ltNFTOKEN_PAGE); + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + xrpl::STArray metaArray{1}; + xrpl::STObject node(xrpl::sfModifiedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltNFTOKEN_PAGE); - ripple::STObject finalFields(ripple::sfFinalFields); - ripple::STArray nftArray1{2}; + xrpl::STObject finalFields(xrpl::sfFinalFields); + xrpl::STArray nftArray1{2}; // finalFields contain new NFT while previousFields does not - auto entry = ripple::STObject(ripple::sfNFToken); - entry.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftID}); + auto entry = xrpl::STObject(xrpl::sfNFToken); + entry.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{nftID}); char const* url = "testurl"; - entry.setFieldVL(ripple::sfURI, ripple::Slice(url, 7)); + entry.setFieldVL(xrpl::sfURI, xrpl::Slice(url, 7)); nftArray1.push_back(entry); - auto entry2 = ripple::STObject(ripple::sfNFToken); - entry2.setFieldH256(ripple::sfNFTokenID, ripple::uint256{kINDEX1}); - entry2.setFieldVL(ripple::sfURI, ripple::Slice(url, 7)); + auto entry2 = xrpl::STObject(xrpl::sfNFToken); + entry2.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{kIndex1}); + entry2.setFieldVL(xrpl::sfURI, xrpl::Slice(url, 7)); nftArray1.push_back(entry2); - finalFields.setFieldArray(ripple::sfNFTokens, nftArray1); + finalFields.setFieldArray(xrpl::sfNFTokens, nftArray1); nftArray1.erase(nftArray1.begin()); - ripple::STObject previousFields(ripple::sfPreviousFields); - previousFields.setFieldArray(ripple::sfNFTokens, nftArray1); + xrpl::STObject previousFields(xrpl::sfPreviousFields); + previousFields.setFieldArray(xrpl::sfNFTokens, nftArray1); - node.emplace_back(std::move(finalFields)); - node.emplace_back(std::move(previousFields)); + node.set(std::move(finalFields)); + node.set(std::move(previousFields)); metaArray.push_back(node); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 0); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); data::TransactionAndMetadata ret; ret.transaction = tx.getSerializer().peekData(); @@ -774,52 +770,52 @@ createMintNftTxWithMetadataOfCreatedNode( ) { // tx - ripple::STObject tx(ripple::sfTransaction); - tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_MINT); - auto account = util::parseBase58Wrapper(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) - auto amount = ripple::STAmount(fee, false); - tx.setFieldAmount(ripple::sfFee, amount); + xrpl::STObject tx(xrpl::sfTransaction); + tx.setFieldU16(xrpl::sfTransactionType, xrpl::ttNFTOKEN_MINT); + auto account = util::parseBase58Wrapper(std::string(accountId)); + tx.setAccountID(xrpl::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) + auto amount = xrpl::STAmount(fee, false); + tx.setFieldAmount(xrpl::sfFee, amount); // required field for ttNFTOKEN_MINT - tx.setFieldU32(ripple::sfNFTokenTaxon, nfTokenTaxon); - tx.setFieldU32(ripple::sfSequence, seq); - tx.setFieldVL(ripple::sfSigningPubKey, kSLICE); + tx.setFieldU32(xrpl::sfNFTokenTaxon, nfTokenTaxon); + tx.setFieldU32(xrpl::sfSequence, seq); + tx.setFieldVL(xrpl::sfSigningPubKey, kSlice); if (uri) - tx.setFieldVL(ripple::sfURI, ripple::Slice(uri->data(), uri->size())); + tx.setFieldVL(xrpl::sfURI, xrpl::Slice(uri->data(), uri->size())); // meta - ripple::STObject metaObj(ripple::sfTransactionMetaData); - ripple::STArray metaArray{1}; - ripple::STObject node(ripple::sfCreatedNode); - node.setFieldU16(ripple::sfLedgerEntryType, ripple::ltNFTOKEN_PAGE); + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + xrpl::STArray metaArray{1}; + xrpl::STObject node(xrpl::sfCreatedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltNFTOKEN_PAGE); - ripple::STObject newFields(ripple::sfNewFields); - ripple::STArray nftArray1{1}; + xrpl::STObject newFields(xrpl::sfNewFields); + xrpl::STArray nftArray1{1}; if (nftID) { // finalFields contain new NFT while previousFields does not - auto entry = ripple::STObject(ripple::sfNFToken); - entry.setFieldH256(ripple::sfNFTokenID, ripple::uint256{*nftID}); + auto entry = xrpl::STObject(xrpl::sfNFToken); + entry.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{*nftID}); if (uri) - entry.setFieldVL(ripple::sfURI, ripple::Slice(uri->data(), uri->size())); + entry.setFieldVL(xrpl::sfURI, xrpl::Slice(uri->data(), uri->size())); nftArray1.push_back(entry); } - newFields.setFieldArray(ripple::sfNFTokens, nftArray1); - node.emplace_back(std::move(newFields)); + newFields.setFieldArray(xrpl::sfNFTokens, nftArray1); + node.set(std::move(newFields)); if (pageIndex) - node.setFieldH256(ripple::sfLedgerIndex, ripple::uint256{*pageIndex}); + node.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{*pageIndex}); // add a ledger object ahead of nft page - ripple::STObject node2(ripple::sfCreatedNode); - node2.setFieldU16(ripple::sfLedgerEntryType, ripple::ltACCOUNT_ROOT); + xrpl::STObject node2(xrpl::sfCreatedNode); + node2.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltACCOUNT_ROOT); metaArray.push_back(node2); metaArray.push_back(node); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 0); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); data::TransactionAndMetadata ret; ret.transaction = tx.getSerializer().peekData(); @@ -828,56 +824,56 @@ createMintNftTxWithMetadataOfCreatedNode( } data::TransactionAndMetadata -createNftModifyTxWithMetadata(std::string_view accountId, std::string_view nftID, ripple::Blob uri) +createNftModifyTxWithMetadata(std::string_view accountId, std::string_view nftID, xrpl::Blob uri) { // tx - ripple::STObject tx(ripple::sfTransaction); - tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_MODIFY); - auto account = ripple::parseBase58(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) - auto amount = ripple::STAmount(10, false); - tx.setFieldAmount(ripple::sfFee, amount); - tx.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftID}); - tx.setFieldU32(ripple::sfSequence, 100); - tx.setFieldVL(ripple::sfSigningPubKey, kSLICE); + xrpl::STObject tx(xrpl::sfTransaction); + tx.setFieldU16(xrpl::sfTransactionType, xrpl::ttNFTOKEN_MODIFY); + auto account = xrpl::parseBase58(std::string(accountId)); + tx.setAccountID(xrpl::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) + auto amount = xrpl::STAmount(10, false); + tx.setFieldAmount(xrpl::sfFee, amount); + tx.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{nftID}); + tx.setFieldU32(xrpl::sfSequence, 100); + tx.setFieldVL(xrpl::sfSigningPubKey, kSlice); if (!uri.empty()) // sfURI should be absent if empty - tx.setFieldVL(ripple::sfURI, uri); + tx.setFieldVL(xrpl::sfURI, uri); // meta - ripple::STObject metaObj(ripple::sfTransactionMetaData); - ripple::STArray metaArray{1}; - ripple::STObject node(ripple::sfModifiedNode); - node.setFieldU16(ripple::sfLedgerEntryType, ripple::ltNFTOKEN_PAGE); + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + xrpl::STArray metaArray{1}; + xrpl::STObject node(xrpl::sfModifiedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltNFTOKEN_PAGE); - ripple::STObject finalFields(ripple::sfFinalFields); - ripple::STArray nftArray1{1}; - ripple::STArray nftArray2{1}; + xrpl::STObject finalFields(xrpl::sfFinalFields); + xrpl::STArray nftArray1{1}; + xrpl::STArray nftArray2{1}; // finalFields contain new NFT while previousFields does not - auto entry = ripple::STObject(ripple::sfNFToken); - entry.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftID}); + auto entry = xrpl::STObject(xrpl::sfNFToken); + entry.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{nftID}); if (!uri.empty()) - entry.setFieldVL(ripple::sfURI, uri); + entry.setFieldVL(xrpl::sfURI, uri); nftArray1.push_back(entry); - auto entry2 = ripple::STObject(ripple::sfNFToken); - entry2.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftID}); + auto entry2 = xrpl::STObject(xrpl::sfNFToken); + entry2.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{nftID}); char const* url = "previous"; - entry2.setFieldVL(ripple::sfURI, ripple::Slice(url, 7)); + entry2.setFieldVL(xrpl::sfURI, xrpl::Slice(url, 7)); nftArray2.push_back(entry2); - finalFields.setFieldArray(ripple::sfNFTokens, nftArray1); + finalFields.setFieldArray(xrpl::sfNFTokens, nftArray1); - ripple::STObject previousFields(ripple::sfPreviousFields); - previousFields.setFieldArray(ripple::sfNFTokens, nftArray2); + xrpl::STObject previousFields(xrpl::sfPreviousFields); + previousFields.setFieldArray(xrpl::sfNFTokens, nftArray2); - node.emplace_back(std::move(finalFields)); - node.emplace_back(std::move(previousFields)); + node.set(std::move(finalFields)); + node.set(std::move(previousFields)); metaArray.push_back(node); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 0); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); data::TransactionAndMetadata ret; ret.transaction = tx.getSerializer().peekData(); @@ -889,40 +885,40 @@ data::TransactionAndMetadata createNftBurnTxWithMetadataOfDeletedNode(std::string_view accountId, std::string_view nftID) { // tx - ripple::STObject tx(ripple::sfTransaction); - tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_BURN); + xrpl::STObject tx(xrpl::sfTransaction); + tx.setFieldU16(xrpl::sfTransactionType, xrpl::ttNFTOKEN_BURN); auto account = getAccountIdWithString(accountId); - tx.setAccountID(ripple::sfAccount, account); - auto amount = ripple::STAmount(10, false); - tx.setFieldAmount(ripple::sfFee, amount); - tx.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftID}); - tx.setFieldU32(ripple::sfSequence, 100); - tx.setFieldVL(ripple::sfSigningPubKey, kSLICE); + tx.setAccountID(xrpl::sfAccount, account); + auto amount = xrpl::STAmount(10, false); + tx.setFieldAmount(xrpl::sfFee, amount); + tx.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{nftID}); + tx.setFieldU32(xrpl::sfSequence, 100); + tx.setFieldVL(xrpl::sfSigningPubKey, kSlice); // meta - ripple::STObject metaObj(ripple::sfTransactionMetaData); - ripple::STArray metaArray{1}; - ripple::STObject node(ripple::sfDeletedNode); - node.setFieldU16(ripple::sfLedgerEntryType, ripple::ltNFTOKEN_PAGE); + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + xrpl::STArray metaArray{1}; + xrpl::STObject node(xrpl::sfDeletedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltNFTOKEN_PAGE); // deleted node should contain finalFields - ripple::STObject finalFields(ripple::sfFinalFields); - ripple::STArray nftArray{1}; - auto entry = ripple::STObject(ripple::sfNFToken); - entry.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftID}); + xrpl::STObject finalFields(xrpl::sfFinalFields); + xrpl::STArray nftArray{1}; + auto entry = xrpl::STObject(xrpl::sfNFToken); + entry.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{nftID}); nftArray.push_back(entry); - finalFields.setFieldArray(ripple::sfNFTokens, nftArray); + finalFields.setFieldArray(xrpl::sfNFTokens, nftArray); - node.emplace_back(std::move(finalFields)); + node.set(std::move(finalFields)); // add a ledger object ahead of nft page - ripple::STObject node2(ripple::sfCreatedNode); - node2.setFieldU16(ripple::sfLedgerEntryType, ripple::ltACCOUNT_ROOT); + xrpl::STObject node2(xrpl::sfCreatedNode); + node2.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltACCOUNT_ROOT); metaArray.push_back(node2); metaArray.push_back(node); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 0); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); data::TransactionAndMetadata ret; ret.transaction = tx.getSerializer().peekData(); @@ -934,36 +930,36 @@ data::TransactionAndMetadata createNftBurnTxWithMetadataOfModifiedNode(std::string_view accountId, std::string_view nftID) { // tx - ripple::STObject tx(ripple::sfTransaction); - tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_BURN); + xrpl::STObject tx(xrpl::sfTransaction); + tx.setFieldU16(xrpl::sfTransactionType, xrpl::ttNFTOKEN_BURN); auto account = getAccountIdWithString(accountId); - tx.setAccountID(ripple::sfAccount, account); - auto amount = ripple::STAmount(10, false); - tx.setFieldAmount(ripple::sfFee, amount); - tx.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftID}); - tx.setFieldU32(ripple::sfSequence, 100); - tx.setFieldVL(ripple::sfSigningPubKey, kSLICE); + tx.setAccountID(xrpl::sfAccount, account); + auto amount = xrpl::STAmount(10, false); + tx.setFieldAmount(xrpl::sfFee, amount); + tx.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{nftID}); + tx.setFieldU32(xrpl::sfSequence, 100); + tx.setFieldVL(xrpl::sfSigningPubKey, kSlice); // meta - ripple::STObject metaObj(ripple::sfTransactionMetaData); - ripple::STArray metaArray{1}; - ripple::STObject node(ripple::sfModifiedNode); - node.setFieldU16(ripple::sfLedgerEntryType, ripple::ltNFTOKEN_PAGE); + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + xrpl::STArray metaArray{1}; + xrpl::STObject node(xrpl::sfModifiedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltNFTOKEN_PAGE); - ripple::STObject finalFields(ripple::sfFinalFields); - ripple::STArray nftArray{1}; - ripple::STObject previousFields(ripple::sfPreviousFields); - auto entry = ripple::STObject(ripple::sfNFToken); - entry.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftID}); + xrpl::STObject finalFields(xrpl::sfFinalFields); + xrpl::STArray nftArray{1}; + xrpl::STObject previousFields(xrpl::sfPreviousFields); + auto entry = xrpl::STObject(xrpl::sfNFToken); + entry.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{nftID}); nftArray.push_back(entry); - previousFields.setFieldArray(ripple::sfNFTokens, nftArray); + previousFields.setFieldArray(xrpl::sfNFTokens, nftArray); - node.emplace_back(std::move(previousFields)); - node.emplace_back(std::move(finalFields)); + node.set(std::move(previousFields)); + node.set(std::move(finalFields)); metaArray.push_back(node); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 0); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); data::TransactionAndMetadata ret; ret.transaction = tx.getSerializer().peekData(); @@ -981,35 +977,35 @@ createAcceptNftBuyerOfferTxWithMetadata( ) { // tx - ripple::STObject tx(ripple::sfTransaction); - tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_ACCEPT_OFFER); - auto account = util::parseBase58Wrapper(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) - auto amount = ripple::STAmount(fee, false); - tx.setFieldAmount(ripple::sfFee, amount); - tx.setFieldU32(ripple::sfSequence, seq); - tx.setFieldH256(ripple::sfNFTokenBuyOffer, ripple::uint256{offerId}); - tx.setFieldVL(ripple::sfSigningPubKey, kSLICE); + xrpl::STObject tx(xrpl::sfTransaction); + tx.setFieldU16(xrpl::sfTransactionType, xrpl::ttNFTOKEN_ACCEPT_OFFER); + auto account = util::parseBase58Wrapper(std::string(accountId)); + tx.setAccountID(xrpl::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) + auto amount = xrpl::STAmount(fee, false); + tx.setFieldAmount(xrpl::sfFee, amount); + tx.setFieldU32(xrpl::sfSequence, seq); + tx.setFieldH256(xrpl::sfNFTokenBuyOffer, xrpl::uint256{offerId}); + tx.setFieldVL(xrpl::sfSigningPubKey, kSlice); // meta // create deletedNode with ltNFTOKEN_OFFER - ripple::STObject metaObj(ripple::sfTransactionMetaData); - ripple::STArray metaArray{1}; - ripple::STObject node(ripple::sfDeletedNode); - node.setFieldU16(ripple::sfLedgerEntryType, ripple::ltNFTOKEN_OFFER); + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + xrpl::STArray metaArray{1}; + xrpl::STObject node(xrpl::sfDeletedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltNFTOKEN_OFFER); - ripple::STObject finalFields(ripple::sfFinalFields); - finalFields.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftId}); + xrpl::STObject finalFields(xrpl::sfFinalFields); + finalFields.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{nftId}); // for buyer offer, the offer owner is the nft's new owner // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - finalFields.setAccountID(ripple::sfOwner, *account); + finalFields.setAccountID(xrpl::sfOwner, *account); - node.emplace_back(std::move(finalFields)); - node.setFieldH256(ripple::sfLedgerIndex, ripple::uint256{offerId}); + node.set(std::move(finalFields)); + node.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{offerId}); metaArray.push_back(node); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 0); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); data::TransactionAndMetadata ret; ret.transaction = tx.getSerializer().peekData(); @@ -1029,80 +1025,80 @@ createAcceptNftSellerOfferTxWithMetadata( ) { // tx - ripple::STObject tx(ripple::sfTransaction); - tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_ACCEPT_OFFER); - auto account = util::parseBase58Wrapper(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) - auto amount = ripple::STAmount(fee, false); - tx.setFieldAmount(ripple::sfFee, amount); - tx.setFieldU32(ripple::sfSequence, seq); - tx.setFieldH256(ripple::sfNFTokenSellOffer, ripple::uint256{offerId}); - tx.setFieldVL(ripple::sfSigningPubKey, kSLICE); + xrpl::STObject tx(xrpl::sfTransaction); + tx.setFieldU16(xrpl::sfTransactionType, xrpl::ttNFTOKEN_ACCEPT_OFFER); + auto account = util::parseBase58Wrapper(std::string(accountId)); + tx.setAccountID(xrpl::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) + auto amount = xrpl::STAmount(fee, false); + tx.setFieldAmount(xrpl::sfFee, amount); + tx.setFieldU32(xrpl::sfSequence, seq); + tx.setFieldH256(xrpl::sfNFTokenSellOffer, xrpl::uint256{offerId}); + tx.setFieldVL(xrpl::sfSigningPubKey, kSlice); // meta // create deletedNode with ltNFTOKEN_OFFER - ripple::STObject metaObj(ripple::sfTransactionMetaData); - ripple::STArray metaArray{1}; - ripple::STObject node(ripple::sfDeletedNode); - node.setFieldU16(ripple::sfLedgerEntryType, ripple::ltNFTOKEN_OFFER); + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + xrpl::STArray metaArray{1}; + xrpl::STObject node(xrpl::sfDeletedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltNFTOKEN_OFFER); - ripple::STObject finalFields(ripple::sfFinalFields); - finalFields.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftId}); + xrpl::STObject finalFields(xrpl::sfFinalFields); + finalFields.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{nftId}); // offer owner is not the nft's new owner for seller offer, we need to create other nodes for // processing new owner // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - finalFields.setAccountID(ripple::sfOwner, *account); + finalFields.setAccountID(xrpl::sfOwner, *account); - node.emplace_back(finalFields); - node.setFieldH256(ripple::sfLedgerIndex, ripple::uint256{offerId}); + node.set(xrpl::STObject{finalFields}); + node.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{offerId}); metaArray.push_back(node); // new owner's nft page node changed: 1 new nft page node added 2 old nft page node modified if (isNewPageCreated) { - ripple::STObject node2(ripple::sfCreatedNode); - node2.setFieldU16(ripple::sfLedgerEntryType, ripple::ltNFTOKEN_PAGE); + xrpl::STObject node2(xrpl::sfCreatedNode); + node2.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltNFTOKEN_PAGE); - ripple::STObject newFields(ripple::sfNewFields); - ripple::STArray nftArray1{1}; + xrpl::STObject newFields(xrpl::sfNewFields); + xrpl::STArray nftArray1{1}; - auto entry = ripple::STObject(ripple::sfNFToken); - entry.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftId}); + auto entry = xrpl::STObject(xrpl::sfNFToken); + entry.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{nftId}); nftArray1.push_back(entry); - newFields.setFieldArray(ripple::sfNFTokens, nftArray1); - node2.emplace_back(std::move(newFields)); - node2.setFieldH256(ripple::sfLedgerIndex, ripple::uint256{pageIndex}); + newFields.setFieldArray(xrpl::sfNFTokens, nftArray1); + node2.set(std::move(newFields)); + node2.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{pageIndex}); metaArray.push_back(node2); } else { - ripple::STObject node2(ripple::sfModifiedNode); - node2.setFieldU16(ripple::sfLedgerEntryType, ripple::ltNFTOKEN_PAGE); + xrpl::STObject node2(xrpl::sfModifiedNode); + node2.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltNFTOKEN_PAGE); - ripple::STArray nftArray1{2}; + xrpl::STArray nftArray1{2}; // finalFields contain new NFT while previousFields does not - auto entry = ripple::STObject(ripple::sfNFToken); - entry.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftId}); + auto entry = xrpl::STObject(xrpl::sfNFToken); + entry.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{nftId}); nftArray1.push_back(entry); - auto entry2 = ripple::STObject(ripple::sfNFToken); - entry2.setFieldH256(ripple::sfNFTokenID, ripple::uint256{kINDEX1}); + auto entry2 = xrpl::STObject(xrpl::sfNFToken); + entry2.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{kIndex1}); nftArray1.push_back(entry2); - finalFields.setFieldArray(ripple::sfNFTokens, nftArray1); + finalFields.setFieldArray(xrpl::sfNFTokens, nftArray1); nftArray1.erase(nftArray1.begin()); - ripple::STObject previousFields(ripple::sfPreviousFields); - previousFields.setFieldArray(ripple::sfNFTokens, nftArray1); + xrpl::STObject previousFields(xrpl::sfPreviousFields); + previousFields.setFieldArray(xrpl::sfNFTokens, nftArray1); - node2.emplace_back(std::move(finalFields)); - node2.emplace_back(std::move(previousFields)); - node2.setFieldH256(ripple::sfLedgerIndex, ripple::uint256{pageIndex}); + node2.set(std::move(finalFields)); + node2.set(std::move(previousFields)); + node2.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{pageIndex}); metaArray.push_back(node2); } - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 0); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); data::TransactionAndMetadata ret; ret.transaction = tx.getSerializer().peekData(); @@ -1120,40 +1116,40 @@ createCancelNftOffersTxWithMetadata( ) { // tx - ripple::STObject tx(ripple::sfTransaction); - tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_CANCEL_OFFER); - auto account = util::parseBase58Wrapper(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) - auto amount = ripple::STAmount(fee, false); - tx.setFieldAmount(ripple::sfFee, amount); - tx.setFieldU32(ripple::sfSequence, seq); - ripple::STVector256 offers; + xrpl::STObject tx(xrpl::sfTransaction); + tx.setFieldU16(xrpl::sfTransactionType, xrpl::ttNFTOKEN_CANCEL_OFFER); + auto account = util::parseBase58Wrapper(std::string(accountId)); + tx.setAccountID(xrpl::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) + auto amount = xrpl::STAmount(fee, false); + tx.setFieldAmount(xrpl::sfFee, amount); + tx.setFieldU32(xrpl::sfSequence, seq); + xrpl::STVector256 offers; offers.resize(nftOffers.size()); std::ranges::transform(nftOffers, offers.begin(), [&](auto const& nftId) { - return ripple::uint256{nftId.c_str()}; + return xrpl::uint256{nftId.c_str()}; }); - tx.setFieldV256(ripple::sfNFTokenOffers, offers); - tx.setFieldVL(ripple::sfSigningPubKey, kSLICE); + tx.setFieldV256(xrpl::sfNFTokenOffers, offers); + tx.setFieldVL(xrpl::sfSigningPubKey, kSlice); // meta // create deletedNode with ltNFTOKEN_OFFER // reuse the offer id as nft id - ripple::STObject metaObj(ripple::sfTransactionMetaData); - ripple::STArray metaArray{nftOffers.size()}; + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + xrpl::STArray metaArray{nftOffers.size()}; for (auto const& nftId : nftOffers) { - ripple::STObject node(ripple::sfDeletedNode); - node.setFieldU16(ripple::sfLedgerEntryType, ripple::ltNFTOKEN_OFFER); + xrpl::STObject node(xrpl::sfDeletedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltNFTOKEN_OFFER); - ripple::STObject finalFields(ripple::sfFinalFields); - finalFields.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftId.c_str()}); + xrpl::STObject finalFields(xrpl::sfFinalFields); + finalFields.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{nftId.c_str()}); - node.emplace_back(std::move(finalFields)); + node.set(std::move(finalFields)); metaArray.push_back(node); } - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 0); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); data::TransactionAndMetadata ret; ret.transaction = tx.getSerializer().peekData(); @@ -1172,31 +1168,31 @@ createCreateNftOfferTxWithMetadata( ) { // tx - ripple::STObject tx(ripple::sfTransaction); - tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_CREATE_OFFER); - auto account = util::parseBase58Wrapper(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) - auto amount = ripple::STAmount(fee, false); - tx.setFieldAmount(ripple::sfFee, amount); - auto price = ripple::STAmount(offerPrice, false); - tx.setFieldAmount(ripple::sfAmount, price); - tx.setFieldU32(ripple::sfSequence, seq); - tx.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftId}); - tx.setFieldVL(ripple::sfSigningPubKey, kSLICE); + xrpl::STObject tx(xrpl::sfTransaction); + tx.setFieldU16(xrpl::sfTransactionType, xrpl::ttNFTOKEN_CREATE_OFFER); + auto account = util::parseBase58Wrapper(std::string(accountId)); + tx.setAccountID(xrpl::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) + auto amount = xrpl::STAmount(fee, false); + tx.setFieldAmount(xrpl::sfFee, amount); + auto price = xrpl::STAmount(offerPrice, false); + tx.setFieldAmount(xrpl::sfAmount, price); + tx.setFieldU32(xrpl::sfSequence, seq); + tx.setFieldH256(xrpl::sfNFTokenID, xrpl::uint256{nftId}); + tx.setFieldVL(xrpl::sfSigningPubKey, kSlice); // meta // create createdNode with LedgerIndex - ripple::STObject metaObj(ripple::sfTransactionMetaData); - ripple::STArray metaArray{1}; + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + xrpl::STArray metaArray{1}; - ripple::STObject node(ripple::sfCreatedNode); - node.setFieldU16(ripple::sfLedgerEntryType, ripple::ltNFTOKEN_OFFER); - node.setFieldH256(ripple::sfLedgerIndex, ripple::uint256{offerId}); + xrpl::STObject node(xrpl::sfCreatedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltNFTOKEN_OFFER); + node.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{offerId}); metaArray.push_back(node); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 0); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); data::TransactionAndMetadata ret; ret.transaction = tx.getSerializer().peekData(); @@ -1211,43 +1207,43 @@ createOracleSetTxWithMetadata( uint32_t fee, uint32_t docId, std::uint32_t lastUpdateTime, - ripple::STArray priceDataSeries, + xrpl::STArray priceDataSeries, std::string_view oracleIndex, bool created, std::string_view previousTxnId ) { // tx - ripple::STObject tx(ripple::sfTransaction); - tx.setFieldU16(ripple::sfTransactionType, ripple::ttORACLE_SET); - auto account = util::parseBase58Wrapper(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) - auto amount = ripple::STAmount(fee, false); - tx.setFieldAmount(ripple::sfFee, amount); - tx.setFieldU32(ripple::sfLastUpdateTime, lastUpdateTime); - tx.setFieldU32(ripple::sfOracleDocumentID, docId); - tx.setFieldU32(ripple::sfSequence, seq); - tx.setFieldVL(ripple::sfSigningPubKey, kSLICE); - tx.setFieldArray(ripple::sfPriceDataSeries, priceDataSeries); + xrpl::STObject tx(xrpl::sfTransaction); + tx.setFieldU16(xrpl::sfTransactionType, xrpl::ttORACLE_SET); + auto account = util::parseBase58Wrapper(std::string(accountId)); + tx.setAccountID(xrpl::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) + auto amount = xrpl::STAmount(fee, false); + tx.setFieldAmount(xrpl::sfFee, amount); + tx.setFieldU32(xrpl::sfLastUpdateTime, lastUpdateTime); + tx.setFieldU32(xrpl::sfOracleDocumentID, docId); + tx.setFieldU32(xrpl::sfSequence, seq); + tx.setFieldVL(xrpl::sfSigningPubKey, kSlice); + tx.setFieldArray(xrpl::sfPriceDataSeries, priceDataSeries); // meta - ripple::STObject metaObj(ripple::sfTransactionMetaData); - ripple::STArray metaArray{1}; + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + xrpl::STArray metaArray{1}; - ripple::STObject node(created ? ripple::sfCreatedNode : ripple::sfModifiedNode); - node.setFieldU16(ripple::sfLedgerEntryType, ripple::ltORACLE); - node.setFieldH256(ripple::sfLedgerIndex, ripple::uint256{oracleIndex}); - node.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{previousTxnId}); - ripple::STObject fields(created ? ripple::sfNewFields : ripple::sfFinalFields); - fields.setFieldU32(ripple::sfOracleDocumentID, docId); - fields.setFieldU32(ripple::sfLastUpdateTime, lastUpdateTime); - fields.setFieldArray(ripple::sfPriceDataSeries, priceDataSeries); - node.emplace_back(std::move(fields)); + xrpl::STObject node(created ? xrpl::sfCreatedNode : xrpl::sfModifiedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltORACLE); + node.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{oracleIndex}); + node.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{previousTxnId}); + xrpl::STObject fields(created ? xrpl::sfNewFields : xrpl::sfFinalFields); + fields.setFieldU32(xrpl::sfOracleDocumentID, docId); + fields.setFieldU32(xrpl::sfLastUpdateTime, lastUpdateTime); + fields.setFieldArray(xrpl::sfPriceDataSeries, priceDataSeries); + node.set(std::move(fields)); metaArray.push_back(node); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 0); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); data::TransactionAndMetadata ret; ret.transaction = tx.getSerializer().peekData(); @@ -1255,28 +1251,28 @@ createOracleSetTxWithMetadata( return ret; } -ripple::STObject -createAmendmentsObject(std::vector const& enabledAmendments) +xrpl::STObject +createAmendmentsObject(std::vector const& enabledAmendments) { - auto amendments = ripple::STObject(ripple::sfLedgerEntry); - amendments.setFieldU16(ripple::sfLedgerEntryType, ripple::ltAMENDMENTS); - amendments.setFieldU32(ripple::sfFlags, 0); - ripple::STVector256 const list(enabledAmendments); - amendments.setFieldV256(ripple::sfAmendments, list); + auto amendments = xrpl::STObject(xrpl::sfLedgerEntry); + amendments.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltAMENDMENTS); + amendments.setFieldU32(xrpl::sfFlags, 0); + xrpl::STVector256 const list(enabledAmendments); + amendments.setFieldV256(xrpl::sfAmendments, list); return amendments; } -ripple::STObject +xrpl::STObject createBrokenAmendmentsObject() { - auto amendments = ripple::STObject(ripple::sfLedgerEntry); - amendments.setFieldU16(ripple::sfLedgerEntryType, ripple::ltAMENDMENTS); - amendments.setFieldU32(ripple::sfFlags, 0); + auto amendments = xrpl::STObject(xrpl::sfLedgerEntry); + amendments.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltAMENDMENTS); + amendments.setFieldU32(xrpl::sfFlags, 0); // Note: no sfAmendments present return amendments; } -ripple::STObject +xrpl::STObject createAmmObject( std::string_view accountId, std::string_view assetCurrency, @@ -1289,30 +1285,28 @@ createAmmObject( uint64_t ownerNode ) { - auto amm = ripple::STObject(ripple::sfLedgerEntry); - amm.setFieldU16(ripple::sfLedgerEntryType, ripple::ltAMM); - amm.setAccountID(ripple::sfAccount, getAccountIdWithString(accountId)); - amm.setFieldU16(ripple::sfTradingFee, tradingFee); - amm.setFieldU64(ripple::sfOwnerNode, ownerNode); + auto amm = xrpl::STObject(xrpl::sfLedgerEntry); + amm.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltAMM); + amm.setAccountID(xrpl::sfAccount, getAccountIdWithString(accountId)); + amm.setFieldU16(xrpl::sfTradingFee, tradingFee); + amm.setFieldU64(xrpl::sfOwnerNode, ownerNode); amm.setFieldIssue( - ripple::sfAsset, ripple::STIssue{ripple::sfAsset, getIssue(assetCurrency, assetIssuer)} + xrpl::sfAsset, xrpl::STIssue{xrpl::sfAsset, getIssue(assetCurrency, assetIssuer)} ); amm.setFieldIssue( - ripple::sfAsset2, ripple::STIssue{ripple::sfAsset2, getIssue(asset2Currency, asset2Issuer)} + xrpl::sfAsset2, xrpl::STIssue{xrpl::sfAsset2, getIssue(asset2Currency, asset2Issuer)} ); - ripple::Issue const issue1( - ripple::Currency{lpTokenBalanceIssueCurrency}, + xrpl::Issue const issue1( + xrpl::Currency{lpTokenBalanceIssueCurrency}, // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - *util::parseBase58Wrapper(std::string(accountId)) + *util::parseBase58Wrapper(std::string(accountId)) ); - amm.setFieldAmount( - ripple::sfLPTokenBalance, ripple::STAmount(issue1, lpTokenBalanceIssueAmount) - ); - amm.setFieldU32(ripple::sfFlags, 0); + amm.setFieldAmount(xrpl::sfLPTokenBalance, xrpl::STAmount(issue1, lpTokenBalanceIssueAmount)); + amm.setFieldU32(xrpl::sfFlags, 0); return amm; } -ripple::STObject +xrpl::STObject createBridgeObject( std::string_view accountId, std::string_view lockingDoor, @@ -1321,34 +1315,34 @@ createBridgeObject( std::string_view issuingIssuer ) { - auto bridge = ripple::STObject(ripple::sfLedgerEntry); - bridge.setFieldU16(ripple::sfLedgerEntryType, ripple::ltBRIDGE); - bridge.setAccountID(ripple::sfAccount, getAccountIdWithString(accountId)); - bridge.setFieldAmount(ripple::sfSignatureReward, ripple::STAmount(10, false)); - bridge.setFieldU64(ripple::sfXChainClaimID, 100); - bridge.setFieldU64(ripple::sfXChainAccountCreateCount, 100); - bridge.setFieldU64(ripple::sfXChainAccountClaimCount, 100); - bridge.setFieldU64(ripple::sfOwnerNode, 100); - bridge.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - bridge.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); - bridge.setFieldU32(ripple::sfFlags, 0); - Json::Value lockingIssue; + auto bridge = xrpl::STObject(xrpl::sfLedgerEntry); + bridge.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltBRIDGE); + bridge.setAccountID(xrpl::sfAccount, getAccountIdWithString(accountId)); + bridge.setFieldAmount(xrpl::sfSignatureReward, xrpl::STAmount(10, false)); + bridge.setFieldU64(xrpl::sfXChainClaimID, 100); + bridge.setFieldU64(xrpl::sfXChainAccountCreateCount, 100); + bridge.setFieldU64(xrpl::sfXChainAccountClaimCount, 100); + bridge.setFieldU64(xrpl::sfOwnerNode, 100); + bridge.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + bridge.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); + bridge.setFieldU32(xrpl::sfFlags, 0); + json::Value lockingIssue; lockingIssue["currency"] = "XRP"; - Json::Value issuingIssue; + json::Value issuingIssue; issuingIssue["currency"] = std::string(issuingCurrency); issuingIssue["issuer"] = std::string(issuingIssuer); - bridge[ripple::sfXChainBridge] = ripple::STXChainBridge( + bridge[xrpl::sfXChainBridge] = xrpl::STXChainBridge( getAccountIdWithString(lockingDoor), - ripple::issueFromJson(lockingIssue), + xrpl::issueFromJson(lockingIssue), getAccountIdWithString(issuingDoor), - ripple::issueFromJson(issuingIssue) + xrpl::issueFromJson(issuingIssue) ); - bridge.setFieldU32(ripple::sfFlags, 0); + bridge.setFieldU32(xrpl::sfFlags, 0); return bridge; } -ripple::STObject +xrpl::STObject createChainOwnedClaimIdObject( std::string_view accountId, std::string_view lockingDoor, @@ -1358,36 +1352,36 @@ createChainOwnedClaimIdObject( std::string_view otherChainSource ) { - auto chainOwnedClaimID = ripple::STObject(ripple::sfLedgerEntry); - chainOwnedClaimID.setFieldU16(ripple::sfLedgerEntryType, ripple::ltXCHAIN_OWNED_CLAIM_ID); - chainOwnedClaimID.setAccountID(ripple::sfAccount, getAccountIdWithString(accountId)); - chainOwnedClaimID.setFieldAmount(ripple::sfSignatureReward, ripple::STAmount(10, false)); - chainOwnedClaimID.setFieldU64(ripple::sfXChainClaimID, 100); - chainOwnedClaimID.setFieldU64(ripple::sfOwnerNode, 100); - chainOwnedClaimID.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - chainOwnedClaimID.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); - chainOwnedClaimID.setFieldU32(ripple::sfFlags, 0); - Json::Value lockingIssue; + auto chainOwnedClaimID = xrpl::STObject(xrpl::sfLedgerEntry); + chainOwnedClaimID.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltXCHAIN_OWNED_CLAIM_ID); + chainOwnedClaimID.setAccountID(xrpl::sfAccount, getAccountIdWithString(accountId)); + chainOwnedClaimID.setFieldAmount(xrpl::sfSignatureReward, xrpl::STAmount(10, false)); + chainOwnedClaimID.setFieldU64(xrpl::sfXChainClaimID, 100); + chainOwnedClaimID.setFieldU64(xrpl::sfOwnerNode, 100); + chainOwnedClaimID.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + chainOwnedClaimID.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); + chainOwnedClaimID.setFieldU32(xrpl::sfFlags, 0); + json::Value lockingIssue; lockingIssue["currency"] = "XRP"; - Json::Value issuingIssue; + json::Value issuingIssue; issuingIssue["currency"] = std::string(issuingCurrency); issuingIssue["issuer"] = std::string(issuingIssuer); - chainOwnedClaimID[ripple::sfXChainBridge] = ripple::STXChainBridge( + chainOwnedClaimID[xrpl::sfXChainBridge] = xrpl::STXChainBridge( getAccountIdWithString(lockingDoor), - ripple::issueFromJson(lockingIssue), + xrpl::issueFromJson(lockingIssue), getAccountIdWithString(issuingDoor), - ripple::issueFromJson(issuingIssue) + xrpl::issueFromJson(issuingIssue) ); - chainOwnedClaimID.setFieldU32(ripple::sfFlags, 0); + chainOwnedClaimID.setFieldU32(xrpl::sfFlags, 0); chainOwnedClaimID.setAccountID( - ripple::sfOtherChainSource, getAccountIdWithString(otherChainSource) + xrpl::sfOtherChainSource, getAccountIdWithString(otherChainSource) ); - chainOwnedClaimID.setFieldArray(ripple::sfXChainClaimAttestations, ripple::STArray{}); + chainOwnedClaimID.setFieldArray(xrpl::sfXChainClaimAttestations, xrpl::STArray{}); return chainOwnedClaimID; } -ripple::STObject +xrpl::STObject createChainOwnedCreateAccountClaimId( std::string_view accountId, std::string_view lockingDoor, @@ -1396,100 +1390,98 @@ createChainOwnedCreateAccountClaimId( std::string_view issuingIssuer ) { - auto chainOwnedCreateAccountClaimID = ripple::STObject(ripple::sfLedgerEntry); + auto chainOwnedCreateAccountClaimID = xrpl::STObject(xrpl::sfLedgerEntry); chainOwnedCreateAccountClaimID.setFieldU16( - ripple::sfLedgerEntryType, ripple::ltXCHAIN_OWNED_CLAIM_ID + xrpl::sfLedgerEntryType, xrpl::ltXCHAIN_OWNED_CLAIM_ID ); - chainOwnedCreateAccountClaimID.setAccountID( - ripple::sfAccount, getAccountIdWithString(accountId) - ); - chainOwnedCreateAccountClaimID.setFieldU64(ripple::sfXChainAccountCreateCount, 100); - chainOwnedCreateAccountClaimID.setFieldU64(ripple::sfOwnerNode, 100); - chainOwnedCreateAccountClaimID.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - chainOwnedCreateAccountClaimID.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); - chainOwnedCreateAccountClaimID.setFieldU32(ripple::sfFlags, 0); - Json::Value lockingIssue; + chainOwnedCreateAccountClaimID.setAccountID(xrpl::sfAccount, getAccountIdWithString(accountId)); + chainOwnedCreateAccountClaimID.setFieldU64(xrpl::sfXChainAccountCreateCount, 100); + chainOwnedCreateAccountClaimID.setFieldU64(xrpl::sfOwnerNode, 100); + chainOwnedCreateAccountClaimID.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + chainOwnedCreateAccountClaimID.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); + chainOwnedCreateAccountClaimID.setFieldU32(xrpl::sfFlags, 0); + json::Value lockingIssue; lockingIssue["currency"] = "XRP"; - Json::Value issuingIssue; + json::Value issuingIssue; issuingIssue["currency"] = std::string(issuingCurrency); issuingIssue["issuer"] = std::string(issuingIssuer); - chainOwnedCreateAccountClaimID[ripple::sfXChainBridge] = ripple::STXChainBridge( + chainOwnedCreateAccountClaimID[xrpl::sfXChainBridge] = xrpl::STXChainBridge( getAccountIdWithString(lockingDoor), - ripple::issueFromJson(lockingIssue), + xrpl::issueFromJson(lockingIssue), getAccountIdWithString(issuingDoor), - ripple::issueFromJson(issuingIssue) + xrpl::issueFromJson(issuingIssue) ); - chainOwnedCreateAccountClaimID.setFieldU32(ripple::sfFlags, 0); + chainOwnedCreateAccountClaimID.setFieldU32(xrpl::sfFlags, 0); chainOwnedCreateAccountClaimID.setFieldArray( - ripple::sfXChainCreateAccountAttestations, ripple::STArray{} + xrpl::sfXChainCreateAccountAttestations, xrpl::STArray{} ); return chainOwnedCreateAccountClaimID; } void ammAddVoteSlot( - ripple::STObject& amm, - ripple::AccountID const& accountId, + xrpl::STObject& amm, + xrpl::AccountID const& accountId, uint16_t tradingFee, uint32_t voteWeight ) { - if (!amm.isFieldPresent(ripple::sfVoteSlots)) - amm.setFieldArray(ripple::sfVoteSlots, ripple::STArray{}); + if (!amm.isFieldPresent(xrpl::sfVoteSlots)) + amm.setFieldArray(xrpl::sfVoteSlots, xrpl::STArray{}); - auto& arr = amm.peekFieldArray(ripple::sfVoteSlots); - auto slot = ripple::STObject(ripple::sfVoteEntry); - slot.setAccountID(ripple::sfAccount, accountId); - slot.setFieldU16(ripple::sfTradingFee, tradingFee); - slot.setFieldU32(ripple::sfVoteWeight, voteWeight); + auto& arr = amm.peekFieldArray(xrpl::sfVoteSlots); + auto slot = xrpl::STObject(xrpl::sfVoteEntry); + slot.setAccountID(xrpl::sfAccount, accountId); + slot.setFieldU16(xrpl::sfTradingFee, tradingFee); + slot.setFieldU32(xrpl::sfVoteWeight, voteWeight); arr.push_back(slot); } void ammSetAuctionSlot( - ripple::STObject& amm, - ripple::AccountID const& accountId, - ripple::STAmount price, + xrpl::STObject& amm, + xrpl::AccountID const& accountId, + xrpl::STAmount price, uint16_t discountedFee, uint32_t expiration, - std::vector const& authAccounts + std::vector const& authAccounts ) { ASSERT(expiration >= 24 * 3600, "Expiration must be at least 24 hours"); - if (!amm.isFieldPresent(ripple::sfAuctionSlot)) - amm.makeFieldPresent(ripple::sfAuctionSlot); + if (!amm.isFieldPresent(xrpl::sfAuctionSlot)) + amm.makeFieldPresent(xrpl::sfAuctionSlot); - auto& auctionSlot = amm.peekFieldObject(ripple::sfAuctionSlot); - auctionSlot.setAccountID(ripple::sfAccount, accountId); - auctionSlot.setFieldAmount(ripple::sfPrice, price); - auctionSlot.setFieldU16(ripple::sfDiscountedFee, discountedFee); - auctionSlot.setFieldU32(ripple::sfExpiration, expiration); + auto& auctionSlot = amm.peekFieldObject(xrpl::sfAuctionSlot); + auctionSlot.setAccountID(xrpl::sfAccount, accountId); + auctionSlot.setFieldAmount(xrpl::sfPrice, price); + auctionSlot.setFieldU16(xrpl::sfDiscountedFee, discountedFee); + auctionSlot.setFieldU32(xrpl::sfExpiration, expiration); if (not authAccounts.empty()) { - ripple::STArray accounts; + xrpl::STArray accounts; for (auto const& acc : authAccounts) { - ripple::STObject authAcc(ripple::sfAuthAccount); - authAcc.setAccountID(ripple::sfAccount, acc); + xrpl::STObject authAcc(xrpl::sfAuthAccount); + authAcc.setAccountID(xrpl::sfAccount, acc); accounts.push_back(authAcc); } - auctionSlot.setFieldArray(ripple::sfAuthAccounts, accounts); + auctionSlot.setFieldArray(xrpl::sfAuthAccounts, accounts); } } -ripple::Currency +xrpl::Currency createLptCurrency(std::string_view assetCurrency, std::string_view asset2Currency) { - return ripple::ammLPTCurrency( - ripple::to_currency(std::string(assetCurrency)), - ripple::to_currency(std::string(asset2Currency)) + return xrpl::ammLPTCurrency( + xrpl::Issue{xrpl::toCurrency(std::string(assetCurrency)), xrpl::xrpAccount()}, + xrpl::Issue{xrpl::toCurrency(std::string(asset2Currency)), xrpl::xrpAccount()} ); } -ripple::STObject +xrpl::STObject createMptIssuanceObject( std::string_view accountId, std::uint32_t seq, @@ -1504,105 +1496,105 @@ createMptIssuanceObject( std::optional mutableFlags ) { - ripple::STObject mptIssuance(ripple::sfLedgerEntry); - mptIssuance.setAccountID(ripple::sfIssuer, getAccountIdWithString(accountId)); - mptIssuance.setFieldU16(ripple::sfLedgerEntryType, ripple::ltMPTOKEN_ISSUANCE); - mptIssuance.setFieldU32(ripple::sfSequence, seq); - mptIssuance.setFieldU64(ripple::sfOwnerNode, 0); - mptIssuance.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - mptIssuance.setFieldU32(ripple::sfFlags, flags); - mptIssuance.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); - mptIssuance.setFieldU64(ripple::sfOutstandingAmount, outstandingAmount); + xrpl::STObject mptIssuance(xrpl::sfLedgerEntry); + mptIssuance.setAccountID(xrpl::sfIssuer, getAccountIdWithString(accountId)); + mptIssuance.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltMPTOKEN_ISSUANCE); + mptIssuance.setFieldU32(xrpl::sfSequence, seq); + mptIssuance.setFieldU64(xrpl::sfOwnerNode, 0); + mptIssuance.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + mptIssuance.setFieldU32(xrpl::sfFlags, flags); + mptIssuance.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); + mptIssuance.setFieldU64(xrpl::sfOutstandingAmount, outstandingAmount); if (transferFee.has_value()) - mptIssuance.setFieldU16(ripple::sfTransferFee, *transferFee); + mptIssuance.setFieldU16(xrpl::sfTransferFee, *transferFee); if (assetScale.has_value()) - mptIssuance.setFieldU8(ripple::sfAssetScale, *assetScale); + mptIssuance.setFieldU8(xrpl::sfAssetScale, *assetScale); if (maxAmount.has_value()) - mptIssuance.setFieldU64(ripple::sfMaximumAmount, *maxAmount); + mptIssuance.setFieldU64(xrpl::sfMaximumAmount, *maxAmount); if (lockedAmount.has_value()) - mptIssuance.setFieldU64(ripple::sfLockedAmount, *lockedAmount); + mptIssuance.setFieldU64(xrpl::sfLockedAmount, *lockedAmount); if (metadata.has_value()) { - ripple::Slice const sliceMetadata(metadata->data(), metadata->size()); - mptIssuance.setFieldVL(ripple::sfMPTokenMetadata, sliceMetadata); + xrpl::Slice const sliceMetadata(metadata->data(), metadata->size()); + mptIssuance.setFieldVL(xrpl::sfMPTokenMetadata, sliceMetadata); } if (domainId.has_value()) - mptIssuance.setFieldH256(ripple::sfDomainID, ripple::uint256{*domainId}); + mptIssuance.setFieldH256(xrpl::sfDomainID, xrpl::uint256{*domainId}); if (mutableFlags.has_value()) - mptIssuance.setFieldU32(ripple::sfMutableFlags, *mutableFlags); + mptIssuance.setFieldU32(xrpl::sfMutableFlags, *mutableFlags); return mptIssuance; } -ripple::STObject +xrpl::STObject createMpTokenObject( std::string_view accountId, - ripple::uint192 issuanceID, + xrpl::uint192 issuanceID, std::uint64_t mptAmount, std::uint32_t flags, std::optional lockedAmount ) { - ripple::STObject mptoken(ripple::sfLedgerEntry); - mptoken.setAccountID(ripple::sfAccount, getAccountIdWithString(accountId)); - mptoken[ripple::sfMPTokenIssuanceID] = issuanceID; - mptoken.setFieldU16(ripple::sfLedgerEntryType, ripple::ltMPTOKEN); - mptoken.setFieldU32(ripple::sfFlags, flags); - mptoken.setFieldU64(ripple::sfOwnerNode, 0); - mptoken.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - mptoken.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); + xrpl::STObject mptoken(xrpl::sfLedgerEntry); + mptoken.setAccountID(xrpl::sfAccount, getAccountIdWithString(accountId)); + mptoken[xrpl::sfMPTokenIssuanceID] = issuanceID; + mptoken.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltMPTOKEN); + mptoken.setFieldU32(xrpl::sfFlags, flags); + mptoken.setFieldU64(xrpl::sfOwnerNode, 0); + mptoken.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + mptoken.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); if (mptAmount != 0u) - mptoken.setFieldU64(ripple::sfMPTAmount, mptAmount); + mptoken.setFieldU64(xrpl::sfMPTAmount, mptAmount); if (lockedAmount.has_value()) - mptoken.setFieldU64(ripple::sfLockedAmount, *lockedAmount); + mptoken.setFieldU64(xrpl::sfLockedAmount, *lockedAmount); return mptoken; } -ripple::STObject +xrpl::STObject createMPTIssuanceCreateTx(std::string_view accountId, uint32_t fee, uint32_t seq) { - ripple::STObject tx(ripple::sfTransaction); - tx.setFieldU16(ripple::sfTransactionType, ripple::ttMPTOKEN_ISSUANCE_CREATE); - tx.setAccountID(ripple::sfAccount, getAccountIdWithString(accountId)); - tx.setFieldAmount(ripple::sfFee, ripple::STAmount(fee, false)); - tx.setFieldU32(ripple::sfSequence, seq); - tx.setFieldVL(ripple::sfSigningPubKey, kSLICE); + xrpl::STObject tx(xrpl::sfTransaction); + tx.setFieldU16(xrpl::sfTransactionType, xrpl::ttMPTOKEN_ISSUANCE_CREATE); + tx.setAccountID(xrpl::sfAccount, getAccountIdWithString(accountId)); + tx.setFieldAmount(xrpl::sfFee, xrpl::STAmount(fee, false)); + tx.setFieldU32(xrpl::sfSequence, seq); + tx.setFieldVL(xrpl::sfSigningPubKey, kSlice); return tx; } data::TransactionAndMetadata createMPTIssuanceCreateTxWithMetadata(std::string_view accountId, uint32_t fee, uint32_t seq) { - ripple::STObject const tx = createMPTIssuanceCreateTx(accountId, fee, seq); + xrpl::STObject const tx = createMPTIssuanceCreateTx(accountId, fee, seq); - ripple::STObject metaObj(ripple::sfTransactionMetaData); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 0); + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); - ripple::STObject newFields(ripple::sfNewFields); - newFields.setAccountID(ripple::sfIssuer, getAccountIdWithString(accountId)); - newFields.setFieldU16(ripple::sfLedgerEntryType, ripple::ltMPTOKEN_ISSUANCE); - newFields.setFieldU32(ripple::sfFlags, 0); - newFields.setFieldU32(ripple::sfSequence, seq); - newFields.setFieldU64(ripple::sfOwnerNode, 0); - newFields.setFieldU64(ripple::sfMaximumAmount, 0); - newFields.setFieldU64(ripple::sfOutstandingAmount, 0); - newFields.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - newFields.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); + xrpl::STObject newFields(xrpl::sfNewFields); + newFields.setAccountID(xrpl::sfIssuer, getAccountIdWithString(accountId)); + newFields.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltMPTOKEN_ISSUANCE); + newFields.setFieldU32(xrpl::sfFlags, 0); + newFields.setFieldU32(xrpl::sfSequence, seq); + newFields.setFieldU64(xrpl::sfOwnerNode, 0); + newFields.setFieldU64(xrpl::sfMaximumAmount, 0); + newFields.setFieldU64(xrpl::sfOutstandingAmount, 0); + newFields.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + newFields.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); std::string_view const metadata = "test-meta"; - ripple::Slice const sliceMetadata(metadata.data(), metadata.size()); - newFields.setFieldVL(ripple::sfMPTokenMetadata, sliceMetadata); + xrpl::Slice const sliceMetadata(metadata.data(), metadata.size()); + newFields.setFieldVL(xrpl::sfMPTokenMetadata, sliceMetadata); - ripple::STObject createdNode(ripple::sfCreatedNode); - createdNode.setFieldU16(ripple::sfLedgerEntryType, ripple::ltMPTOKEN_ISSUANCE); - createdNode.setFieldH256(ripple::sfLedgerIndex, ripple::uint256{}); - createdNode.emplace_back(std::move(newFields)); + xrpl::STObject createdNode(xrpl::sfCreatedNode); + createdNode.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltMPTOKEN_ISSUANCE); + createdNode.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{}); + createdNode.set(std::move(newFields)); - ripple::STArray affectedNodes(ripple::sfAffectedNodes); + xrpl::STArray affectedNodes(xrpl::sfAffectedNodes); affectedNodes.push_back(std::move(createdNode)); - metaObj.setFieldArray(ripple::sfAffectedNodes, affectedNodes); + metaObj.setFieldArray(xrpl::sfAffectedNodes, affectedNodes); data::TransactionAndMetadata ret; ret.transaction = tx.getSerializer().peekData(); @@ -1610,28 +1602,28 @@ createMPTIssuanceCreateTxWithMetadata(std::string_view accountId, uint32_t fee, return ret; } -ripple::STObject +xrpl::STObject createMPTokenAuthorizeTx( std::string_view accountId, - ripple::uint192 const& mptIssuanceID, + xrpl::uint192 const& mptIssuanceID, uint32_t fee, uint32_t seq, std::optional holder, std::optional flags ) { - ripple::STObject tx(ripple::sfTransaction); - tx.setFieldU16(ripple::sfTransactionType, ripple::ttMPTOKEN_AUTHORIZE); - tx.setAccountID(ripple::sfAccount, getAccountIdWithString(accountId)); - tx[ripple::sfMPTokenIssuanceID] = mptIssuanceID; - tx.setFieldAmount(ripple::sfFee, ripple::STAmount(fee, false)); - tx.setFieldU32(ripple::sfSequence, seq); - tx.setFieldVL(ripple::sfSigningPubKey, kSLICE); + xrpl::STObject tx(xrpl::sfTransaction); + tx.setFieldU16(xrpl::sfTransactionType, xrpl::ttMPTOKEN_AUTHORIZE); + tx.setAccountID(xrpl::sfAccount, getAccountIdWithString(accountId)); + tx[xrpl::sfMPTokenIssuanceID] = mptIssuanceID; + tx.setFieldAmount(xrpl::sfFee, xrpl::STAmount(fee, false)); + tx.setFieldU32(xrpl::sfSequence, seq); + tx.setFieldVL(xrpl::sfSigningPubKey, kSlice); if (holder) - tx.setAccountID(ripple::sfHolder, getAccountIdWithString(*holder)); + tx.setAccountID(xrpl::sfHolder, getAccountIdWithString(*holder)); if (flags) - tx.setFieldU32(ripple::sfFlags, *flags); + tx.setFieldU32(xrpl::sfFlags, *flags); return tx; } @@ -1639,30 +1631,30 @@ createMPTokenAuthorizeTx( data::TransactionAndMetadata createMPTokenAuthorizeTxWithMetadata( std::string_view accountId, - ripple::uint192 const& mptIssuanceID, + xrpl::uint192 const& mptIssuanceID, uint32_t fee, uint32_t seq ) { - ripple::STObject const tx = createMPTokenAuthorizeTx(accountId, mptIssuanceID, fee, seq); + xrpl::STObject const tx = createMPTokenAuthorizeTx(accountId, mptIssuanceID, fee, seq); - ripple::STObject metaObj(ripple::sfTransactionMetaData); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 0); + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); - ripple::STObject finalFields(ripple::sfFinalFields); - finalFields.setFieldU16(ripple::sfLedgerEntryType, ripple::ltMPTOKEN); - finalFields[ripple::sfMPTokenIssuanceID] = mptIssuanceID; - finalFields.setFieldU64(ripple::sfMPTAmount, 0); + xrpl::STObject finalFields(xrpl::sfFinalFields); + finalFields.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltMPTOKEN); + finalFields[xrpl::sfMPTokenIssuanceID] = mptIssuanceID; + finalFields.setFieldU64(xrpl::sfMPTAmount, 0); - ripple::STObject modifiedNode(ripple::sfModifiedNode); - modifiedNode.setFieldU16(ripple::sfLedgerEntryType, ripple::ltMPTOKEN); - modifiedNode.setFieldH256(ripple::sfLedgerIndex, ripple::uint256{}); - modifiedNode.emplace_back(std::move(finalFields)); + xrpl::STObject modifiedNode(xrpl::sfModifiedNode); + modifiedNode.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltMPTOKEN); + modifiedNode.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{}); + modifiedNode.set(std::move(finalFields)); - ripple::STArray affectedNodes(ripple::sfAffectedNodes); + xrpl::STArray affectedNodes(xrpl::sfAffectedNodes); affectedNodes.push_back(std::move(modifiedNode)); - metaObj.setFieldArray(ripple::sfAffectedNodes, affectedNodes); + metaObj.setFieldArray(xrpl::sfAffectedNodes, affectedNodes); data::TransactionAndMetadata ret; ret.transaction = tx.getSerializer().peekData(); @@ -1670,113 +1662,113 @@ createMPTokenAuthorizeTxWithMetadata( return ret; } -ripple::STObject +xrpl::STObject createPermissionedDomainObject( std::string_view accountId, std::string_view ledgerIndex, - ripple::LedgerIndex seq, + xrpl::LedgerIndex seq, uint64_t ownerNode, - ripple::uint256 previousTxId, + xrpl::uint256 previousTxId, uint32_t previousTxSeq ) { - ripple::STObject object(ripple::sfLedgerEntry); - object.setFieldH256(ripple::sfLedgerIndex, ripple::uint256(ledgerIndex)); - object.setAccountID(ripple::sfOwner, getAccountIdWithString(accountId)); - object.setFieldU32(ripple::sfSequence, seq); - object.setFieldArray(ripple::sfAcceptedCredentials, ripple::STArray{}); - object.setFieldU64(ripple::sfOwnerNode, ownerNode); - object.setFieldH256(ripple::sfPreviousTxnID, previousTxId); - object.setFieldU32(ripple::sfPreviousTxnLgrSeq, previousTxSeq); - object.setFieldU32(ripple::sfFlags, 0); - object.setFieldU16(ripple::sfLedgerEntryType, ripple::ltPERMISSIONED_DOMAIN); + xrpl::STObject object(xrpl::sfLedgerEntry); + object.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256(ledgerIndex)); + object.setAccountID(xrpl::sfOwner, getAccountIdWithString(accountId)); + object.setFieldU32(xrpl::sfSequence, seq); + object.setFieldArray(xrpl::sfAcceptedCredentials, xrpl::STArray{}); + object.setFieldU64(xrpl::sfOwnerNode, ownerNode); + object.setFieldH256(xrpl::sfPreviousTxnID, previousTxId); + object.setFieldU32(xrpl::sfPreviousTxnLgrSeq, previousTxSeq); + object.setFieldU32(xrpl::sfFlags, 0); + object.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltPERMISSIONED_DOMAIN); return object; } -ripple::STObject +xrpl::STObject createDelegateObject( std::string_view accountId, std::string_view authorize, std::string_view ledgerIndex, uint64_t ownerNode, - ripple::uint256 previousTxId, + xrpl::uint256 previousTxId, uint32_t previousTxSeq ) { - ripple::STObject object(ripple::sfLedgerEntry); + xrpl::STObject object(xrpl::sfLedgerEntry); - object.setFieldH256(ripple::sfLedgerIndex, ripple::uint256(ledgerIndex)); - object.setFieldU16(ripple::sfLedgerEntryType, ripple::ltDELEGATE); - object.setAccountID(ripple::sfAccount, getAccountIdWithString(accountId)); - object.setAccountID(ripple::sfAuthorize, getAccountIdWithString(authorize)); - object.setFieldArray(ripple::sfPermissions, ripple::STArray{}); - object.setFieldU64(ripple::sfOwnerNode, ownerNode); - object.setFieldH256(ripple::sfPreviousTxnID, previousTxId); - object.setFieldU32(ripple::sfPreviousTxnLgrSeq, previousTxSeq); - object.setFieldU32(ripple::sfFlags, 0); + object.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256(ledgerIndex)); + object.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltDELEGATE); + object.setAccountID(xrpl::sfAccount, getAccountIdWithString(accountId)); + object.setAccountID(xrpl::sfAuthorize, getAccountIdWithString(authorize)); + object.setFieldArray(xrpl::sfPermissions, xrpl::STArray{}); + object.setFieldU64(xrpl::sfOwnerNode, ownerNode); + object.setFieldH256(xrpl::sfPreviousTxnID, previousTxId); + object.setFieldU32(xrpl::sfPreviousTxnLgrSeq, previousTxSeq); + object.setFieldU32(xrpl::sfFlags, 0); return object; } -ripple::STObject +xrpl::STObject createOraclePriceData( uint64_t assetPrice, - ripple::Currency baseAssetCurrency, - ripple::Currency quoteAssetCurrency, + xrpl::Currency baseAssetCurrency, + xrpl::Currency quoteAssetCurrency, uint8_t scale ) { - auto priceData = ripple::STObject(ripple::sfPriceData); - priceData.setFieldU64(ripple::sfAssetPrice, assetPrice); + auto priceData = xrpl::STObject(xrpl::sfPriceData); + priceData.setFieldU64(xrpl::sfAssetPrice, assetPrice); priceData.setFieldCurrency( - ripple::sfBaseAsset, ripple::STCurrency{ripple::sfBaseAsset, baseAssetCurrency} + xrpl::sfBaseAsset, xrpl::STCurrency{xrpl::sfBaseAsset, baseAssetCurrency} ); priceData.setFieldCurrency( - ripple::sfQuoteAsset, ripple::STCurrency{ripple::sfQuoteAsset, quoteAssetCurrency} + xrpl::sfQuoteAsset, xrpl::STCurrency{xrpl::sfQuoteAsset, quoteAssetCurrency} ); - priceData.setFieldU8(ripple::sfScale, scale); + priceData.setFieldU8(xrpl::sfScale, scale); return priceData; } -ripple::STArray -createPriceDataSeries(std::vector const& series) +xrpl::STArray +createPriceDataSeries(std::vector const& series) { - return ripple::STArray{series.begin(), series.end()}; + return xrpl::STArray{series.begin(), series.end()}; } -ripple::STObject +xrpl::STObject createOracleObject( std::string_view accountId, std::string_view provider, uint64_t ownerNode, uint32_t lastUpdateTime, - ripple::Blob uri, - ripple::Blob assetClass, + xrpl::Blob uri, + xrpl::Blob assetClass, uint32_t previousTxSeq, - ripple::uint256 previousTxId, - ripple::STArray priceDataSeries + xrpl::uint256 previousTxId, + xrpl::STArray priceDataSeries ) { - auto ledgerObject = ripple::STObject(ripple::sfLedgerEntry); - ledgerObject.setFieldU16(ripple::sfLedgerEntryType, ripple::ltORACLE); - ledgerObject.setFieldU32(ripple::sfFlags, 0); - ledgerObject.setAccountID(ripple::sfOwner, getAccountIdWithString(accountId)); - ledgerObject.setFieldVL(ripple::sfProvider, ripple::Blob{provider.begin(), provider.end()}); - ledgerObject.setFieldU64(ripple::sfOwnerNode, ownerNode); - ledgerObject.setFieldU32(ripple::sfLastUpdateTime, lastUpdateTime); - ledgerObject.setFieldVL(ripple::sfURI, uri); - ledgerObject.setFieldVL(ripple::sfAssetClass, assetClass); - ledgerObject.setFieldU32(ripple::sfPreviousTxnLgrSeq, previousTxSeq); - ledgerObject.setFieldH256(ripple::sfPreviousTxnID, previousTxId); - ledgerObject.setFieldArray(ripple::sfPriceDataSeries, priceDataSeries); + auto ledgerObject = xrpl::STObject(xrpl::sfLedgerEntry); + ledgerObject.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltORACLE); + ledgerObject.setFieldU32(xrpl::sfFlags, 0); + ledgerObject.setAccountID(xrpl::sfOwner, getAccountIdWithString(accountId)); + ledgerObject.setFieldVL(xrpl::sfProvider, xrpl::Blob{provider.begin(), provider.end()}); + ledgerObject.setFieldU64(xrpl::sfOwnerNode, ownerNode); + ledgerObject.setFieldU32(xrpl::sfLastUpdateTime, lastUpdateTime); + ledgerObject.setFieldVL(xrpl::sfURI, uri); + ledgerObject.setFieldVL(xrpl::sfAssetClass, assetClass); + ledgerObject.setFieldU32(xrpl::sfPreviousTxnLgrSeq, previousTxSeq); + ledgerObject.setFieldH256(xrpl::sfPreviousTxnID, previousTxId); + ledgerObject.setFieldArray(xrpl::sfPriceDataSeries, priceDataSeries); return ledgerObject; } // acc2 issue credential for acc1 so acc2 is issuer -ripple::STObject +xrpl::STObject createCredentialObject( std::string_view acc1, std::string_view acc2, @@ -1785,147 +1777,145 @@ createCredentialObject( std::optional expiration ) { - ripple::STObject credObj(ripple::sfCredential); - credObj.setFieldU16(ripple::sfLedgerEntryType, ripple::ltCREDENTIAL); - credObj.setFieldVL(ripple::sfCredentialType, ripple::Blob{credType.begin(), credType.end()}); - credObj.setAccountID(ripple::sfSubject, getAccountIdWithString(acc1)); - credObj.setAccountID(ripple::sfIssuer, getAccountIdWithString(acc2)); + xrpl::STObject credObj(xrpl::sfCredential); + credObj.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltCREDENTIAL); + credObj.setFieldVL(xrpl::sfCredentialType, xrpl::Blob{credType.begin(), credType.end()}); + credObj.setAccountID(xrpl::sfSubject, getAccountIdWithString(acc1)); + credObj.setAccountID(xrpl::sfIssuer, getAccountIdWithString(acc2)); if (expiration.has_value()) - credObj.setFieldU32(ripple::sfExpiration, *expiration); + credObj.setFieldU32(xrpl::sfExpiration, *expiration); if (accept) { - credObj.setFieldU32(ripple::sfFlags, ripple::lsfAccepted); + credObj.setFieldU32(xrpl::sfFlags, xrpl::lsfAccepted); } else { - credObj.setFieldU32(ripple::sfFlags, 0); + credObj.setFieldU32(xrpl::sfFlags, 0); } - credObj.setFieldU64(ripple::sfSubjectNode, 0); - credObj.setFieldU64(ripple::sfIssuerNode, 0); - credObj.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{}); - credObj.setFieldU32(ripple::sfPreviousTxnLgrSeq, 0); + credObj.setFieldU64(xrpl::sfSubjectNode, 0); + credObj.setFieldU64(xrpl::sfIssuerNode, 0); + credObj.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{}); + credObj.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 0); return credObj; } -ripple::STArray +xrpl::STArray createAuthCredentialArray( std::vector issuer, std::vector credType ) { - ripple::STArray arr; + xrpl::STArray arr; ASSERT(issuer.size() == credType.size(), "issuer and credtype vector must be same length"); for (std::size_t i = 0; i < issuer.size(); ++i) { - auto credential = ripple::STObject::makeInnerObject(ripple::sfCredential); - credential.setAccountID(ripple::sfIssuer, getAccountIdWithString(issuer[i])); + auto credential = xrpl::STObject::makeInnerObject(xrpl::sfCredential); + credential.setAccountID(xrpl::sfIssuer, getAccountIdWithString(issuer[i])); credential.setFieldVL( - ripple::sfCredentialType, + xrpl::sfCredentialType, // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - *ripple::strUnHex(std::string(credType[i])) + *xrpl::strUnHex(std::string(credType[i])) ); arr.push_back(credential); } return arr; } -ripple::STObject +xrpl::STObject createVault( std::string_view owner, std::string_view account, - ripple::LedgerIndex seq, + xrpl::LedgerIndex seq, std::string_view assetCurrency, std::string_view assetIssuer, - ripple::uint192 shareMPTID, + xrpl::uint192 shareMPTID, uint64_t ownerNode, - ripple::uint256 previousTxId, + xrpl::uint256 previousTxId, uint32_t previousTxSeq ) { - auto vault = ripple::STObject(ripple::sfLedgerEntry); - vault.setAccountID(ripple::sfOwner, getAccountIdWithString(owner)); - vault.setAccountID(ripple::sfAccount, getAccountIdWithString(account)); - vault.setFieldU32(ripple::sfSequence, seq); - vault.setFieldU64(ripple::sfOwnerNode, ownerNode); - vault.setFieldH256(ripple::sfPreviousTxnID, previousTxId); - vault.setFieldU32(ripple::sfPreviousTxnLgrSeq, previousTxSeq); + auto vault = xrpl::STObject(xrpl::sfLedgerEntry); + vault.setAccountID(xrpl::sfOwner, getAccountIdWithString(owner)); + vault.setAccountID(xrpl::sfAccount, getAccountIdWithString(account)); + vault.setFieldU32(xrpl::sfSequence, seq); + vault.setFieldU64(xrpl::sfOwnerNode, ownerNode); + vault.setFieldH256(xrpl::sfPreviousTxnID, previousTxId); + vault.setFieldU32(xrpl::sfPreviousTxnLgrSeq, previousTxSeq); vault.setFieldIssue( - ripple::sfAsset, ripple::STIssue{ripple::sfAsset, getIssue(assetCurrency, assetIssuer)} + xrpl::sfAsset, xrpl::STIssue{xrpl::sfAsset, getIssue(assetCurrency, assetIssuer)} ); - vault[ripple::sfShareMPTID] = shareMPTID; - vault.setFieldNumber(ripple::sfAssetsTotal, ripple::STNumber{ripple::sfAssetsTotal, 300}); - vault.setFieldNumber( - ripple::sfAssetsAvailable, ripple::STNumber{ripple::sfAssetsAvailable, 300} - ); - vault.setFieldNumber(ripple::sfLossUnrealized, ripple::STNumber{ripple::sfLossUnrealized, 1}); - vault.setFieldU8(ripple::sfWithdrawalPolicy, 200); + vault[xrpl::sfShareMPTID] = shareMPTID; + vault.setFieldNumber(xrpl::sfAssetsTotal, xrpl::STNumber{xrpl::sfAssetsTotal, 300}); + vault.setFieldNumber(xrpl::sfAssetsAvailable, xrpl::STNumber{xrpl::sfAssetsAvailable, 300}); + vault.setFieldNumber(xrpl::sfLossUnrealized, xrpl::STNumber{xrpl::sfLossUnrealized, 1}); + vault.setFieldU8(xrpl::sfWithdrawalPolicy, 200); - vault.setFieldU32(ripple::sfFlags, 0); - vault.setFieldU16(ripple::sfLedgerEntryType, ripple::ltVAULT); + vault.setFieldU32(xrpl::sfFlags, 0); + vault.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltVAULT); return vault; } -ripple::STObject +xrpl::STObject createLoanBroker( std::string_view owner, std::string_view account, - ripple::LedgerIndex seq, - ripple::uint256 vaultID, + xrpl::LedgerIndex seq, + xrpl::uint256 vaultID, uint32_t loanSequence, - ripple::uint256 previousTxId, + xrpl::uint256 previousTxId, uint32_t previousTxSeq ) { - auto loanBroker = ripple::STObject(ripple::sfLedgerEntry); - loanBroker.setAccountID(ripple::sfOwner, getAccountIdWithString(owner)); - loanBroker.setAccountID(ripple::sfAccount, getAccountIdWithString(account)); - loanBroker.setFieldU32(ripple::sfSequence, seq); - loanBroker.setFieldU64(ripple::sfOwnerNode, 0); - loanBroker.setFieldU64(ripple::sfVaultNode, 0); - loanBroker.setFieldH256(ripple::sfVaultID, vaultID); - loanBroker.setFieldH256(ripple::sfPreviousTxnID, previousTxId); - loanBroker.setFieldU32(ripple::sfPreviousTxnLgrSeq, previousTxSeq); - loanBroker.setFieldU32(ripple::sfLoanSequence, loanSequence); + auto loanBroker = xrpl::STObject(xrpl::sfLedgerEntry); + loanBroker.setAccountID(xrpl::sfOwner, getAccountIdWithString(owner)); + loanBroker.setAccountID(xrpl::sfAccount, getAccountIdWithString(account)); + loanBroker.setFieldU32(xrpl::sfSequence, seq); + loanBroker.setFieldU64(xrpl::sfOwnerNode, 0); + loanBroker.setFieldU64(xrpl::sfVaultNode, 0); + loanBroker.setFieldH256(xrpl::sfVaultID, vaultID); + loanBroker.setFieldH256(xrpl::sfPreviousTxnID, previousTxId); + loanBroker.setFieldU32(xrpl::sfPreviousTxnLgrSeq, previousTxSeq); + loanBroker.setFieldU32(xrpl::sfLoanSequence, loanSequence); // Optional/default fields - not setting them as they will use default values - loanBroker.setFieldU32(ripple::sfFlags, 0); - loanBroker.setFieldU16(ripple::sfLedgerEntryType, ripple::ltLOAN_BROKER); + loanBroker.setFieldU32(xrpl::sfFlags, 0); + loanBroker.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltLOAN_BROKER); return loanBroker; } -ripple::STObject +xrpl::STObject createLoan( std::string_view borrower, - ripple::uint256 loanBrokerID, + xrpl::uint256 loanBrokerID, uint32_t loanSequence, uint32_t startDate, uint32_t paymentInterval, int64_t periodicPaymentValue, - ripple::uint256 previousTxId, + xrpl::uint256 previousTxId, uint32_t previousTxSeq ) { - auto loan = ripple::STObject(ripple::sfLedgerEntry); - loan.setAccountID(ripple::sfBorrower, getAccountIdWithString(borrower)); - loan.setFieldH256(ripple::sfLoanBrokerID, loanBrokerID); - loan.setFieldU32(ripple::sfLoanSequence, loanSequence); - loan.setFieldU64(ripple::sfOwnerNode, 0); - loan.setFieldU64(ripple::sfLoanBrokerNode, 0); - loan.setFieldH256(ripple::sfPreviousTxnID, previousTxId); - loan.setFieldU32(ripple::sfPreviousTxnLgrSeq, previousTxSeq); + auto loan = xrpl::STObject(xrpl::sfLedgerEntry); + loan.setAccountID(xrpl::sfBorrower, getAccountIdWithString(borrower)); + loan.setFieldH256(xrpl::sfLoanBrokerID, loanBrokerID); + loan.setFieldU32(xrpl::sfLoanSequence, loanSequence); + loan.setFieldU64(xrpl::sfOwnerNode, 0); + loan.setFieldU64(xrpl::sfLoanBrokerNode, 0); + loan.setFieldH256(xrpl::sfPreviousTxnID, previousTxId); + loan.setFieldU32(xrpl::sfPreviousTxnLgrSeq, previousTxSeq); - loan.setFieldU32(ripple::sfStartDate, startDate); - loan.setFieldU32(ripple::sfPaymentInterval, paymentInterval); + loan.setFieldU32(xrpl::sfStartDate, startDate); + loan.setFieldU32(xrpl::sfPaymentInterval, paymentInterval); loan.setFieldNumber( - ripple::sfPeriodicPayment, ripple::STNumber{ripple::sfPeriodicPayment, periodicPaymentValue} + xrpl::sfPeriodicPayment, xrpl::STNumber{xrpl::sfPeriodicPayment, periodicPaymentValue} ); // Optional/default fields - not setting them as they will use default values - loan.setFieldU32(ripple::sfFlags, 0); - loan.setFieldU16(ripple::sfLedgerEntryType, ripple::ltLOAN); + loan.setFieldU32(xrpl::sfFlags, 0); + loan.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltLOAN); return loan; } diff --git a/tests/common/util/TestObject.hpp b/tests/common/util/TestObject.hpp index d22b1d7b1..aa0b8b88f 100644 --- a/tests/common/util/TestObject.hpp +++ b/tests/common/util/TestObject.hpp @@ -26,45 +26,45 @@ /* * Create AccountID object with string */ -[[nodiscard]] ripple::AccountID +[[nodiscard]] xrpl::AccountID getAccountIdWithString(std::string_view id); /** * Create AccountID object with string and return its key */ -[[nodiscard]] ripple::uint256 +[[nodiscard]] xrpl::uint256 getAccountKey(std::string_view id); /* * Gets the account key from an account id */ -[[nodiscard]] ripple::uint256 -getAccountKey(ripple::AccountID const& acc); +[[nodiscard]] xrpl::uint256 +getAccountKey(xrpl::AccountID const& acc); /* * Create a simple ledgerHeader object with only hash and seq */ -[[nodiscard]] ripple::LedgerHeader +[[nodiscard]] xrpl::LedgerHeader createLedgerHeader( std::string_view ledgerHash, - ripple::LedgerIndex seq, + xrpl::LedgerIndex seq, std::optional age = std::nullopt ); /* * Create a simple ledgerHeader object with hash, seq and unix timestamp */ -[[nodiscard]] ripple::LedgerHeader +[[nodiscard]] xrpl::LedgerHeader createLedgerHeaderWithUnixTime( std::string_view ledgerHash, - ripple::LedgerIndex seq, + xrpl::LedgerIndex seq, uint64_t closeTimeUnixStamp ); /* * Create a Legacy (pre XRPFees amendment) FeeSetting ledger object */ -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createLegacyFeeSettingLedgerObject( uint64_t base, uint32_t reserveInc, @@ -76,18 +76,18 @@ createLegacyFeeSettingLedgerObject( /* * Create a FeeSetting ledger object */ -ripple::STObject +xrpl::STObject createFeeSettingLedgerObject( - ripple::STAmount base, - ripple::STAmount reserveInc, - ripple::STAmount reserveBase, + xrpl::STAmount base, + xrpl::STAmount reserveInc, + xrpl::STAmount reserveBase, uint32_t flag ); /* * Create a Legacy (pre XRPFees amendment) FeeSetting ledger object and return its blob */ -[[nodiscard]] ripple::Blob +[[nodiscard]] xrpl::Blob createLegacyFeeSettingBlob( uint64_t base, uint32_t reserveInc, @@ -99,18 +99,18 @@ createLegacyFeeSettingBlob( /* * Create a FeeSetting ledger object and return its blob */ -ripple::Blob +xrpl::Blob createFeeSettingBlob( - ripple::STAmount base, - ripple::STAmount reserveInc, - ripple::STAmount reserveBase, + xrpl::STAmount base, + xrpl::STAmount reserveInc, + xrpl::STAmount reserveBase, uint32_t flag ); /* * Create a payment transaction object */ -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createPaymentTransactionObject( std::string_view accountId1, std::string_view accountId2, @@ -119,7 +119,7 @@ createPaymentTransactionObject( uint32_t seq ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createPaymentTransactionMetaObject( std::string_view accountId1, std::string_view accountId2, @@ -131,7 +131,7 @@ createPaymentTransactionMetaObject( /* * Create an account root ledger object */ -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createAccountRootObject( std::string_view accountId, uint32_t flag, @@ -141,7 +141,7 @@ createAccountRootObject( std::string_view previousTxnID, uint32_t previousTxnSeq, uint32_t transferRate = 0, - std::optional ammID = std::nullopt + std::optional ammID = std::nullopt ); /* @@ -149,7 +149,7 @@ createAccountRootObject( * Taker pay is XRP * If reverse is true, taker gets is XRP */ -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createCreateOfferTransactionObject( std::string_view accountId, int fee, @@ -164,13 +164,13 @@ createCreateOfferTransactionObject( /* * Return an issue object with given currency and issue account */ -[[nodiscard]] ripple::Issue +[[nodiscard]] xrpl::Issue getIssue(std::string_view currency, std::string_view issuerId); /* * Create a offer change meta data */ -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createMetaDataForBookChange( std::string_view currency, std::string_view issueId, @@ -187,7 +187,7 @@ createMetaDataForBookChange( * finalTakerGets is XRP * If reverse is true, finalTakerPays is XRP */ -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createMetaDataForCreateOffer( std::string_view currency, std::string_view issueId, @@ -200,7 +200,7 @@ createMetaDataForCreateOffer( /* * Meta data for removing a offer object */ -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createMetaDataForCancelOffer( std::string_view currency, std::string_view issueId, @@ -212,13 +212,13 @@ createMetaDataForCancelOffer( /* * Create a owner dir ledger object */ -[[nodiscard]] ripple::STObject -createOwnerDirLedgerObject(std::vector indexes, std::string_view rootIndex); +[[nodiscard]] xrpl::STObject +createOwnerDirLedgerObject(std::vector indexes, std::string_view rootIndex); /* * Create a payment channel ledger object */ -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createPaymentChannelLedgerObject( std::string_view accountId, std::string_view destId, @@ -229,7 +229,7 @@ createPaymentChannelLedgerObject( uint32_t previousTxnSeq ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createRippleStateLedgerObject( std::string_view currency, std::string_view issuerId, @@ -243,7 +243,7 @@ createRippleStateLedgerObject( uint32_t flag = 0 ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createOfferLedgerObject( std::string_view account, int takerGets, @@ -256,19 +256,19 @@ createOfferLedgerObject( std::optional domain = std::nullopt ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createTicketLedgerObject(std::string_view account, uint32_t sequence); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createEscrowLedgerObject(std::string_view account, std::string_view dest); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createCheckLedgerObject(std::string_view account, std::string_view dest); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createDepositPreauthLedgerObjectByAuth(std::string_view account, std::string_view auth); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createDepositPreauthLedgerObjectByAuthCredentials( std::string_view account, std::string_view issuer, @@ -279,24 +279,24 @@ createDepositPreauthLedgerObjectByAuthCredentials( createNft( std::string_view tokenID, std::string_view account, - ripple::LedgerIndex seq = 1234u, - ripple::Blob uri = ripple::Blob{'u', 'r', 'i'}, + xrpl::LedgerIndex seq = 1234u, + xrpl::Blob uri = xrpl::Blob{'u', 'r', 'i'}, bool isBurned = false ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createNftBuyOffer(std::string_view tokenID, std::string_view account); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createNftSellOffer(std::string_view tokenID, std::string_view account); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createSignerLists(std::vector> const& signers); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createNftTokenPage( std::vector> const& tokens, - std::optional previousPage + std::optional previousPage ); /** @@ -326,7 +326,7 @@ createMintNftTxWithMetadataOfCreatedNode( ); [[nodiscard]] data::TransactionAndMetadata -createNftModifyTxWithMetadata(std::string_view accountId, std::string_view nftID, ripple::Blob uri); +createNftModifyTxWithMetadata(std::string_view accountId, std::string_view nftID, xrpl::Blob uri); /** * Create NFToken burn tx, tx causes a nft page node deleted @@ -378,13 +378,13 @@ createCreateNftOfferTxWithMetadata( std::string_view offerId ); -[[nodiscard]] ripple::STObject -createAmendmentsObject(std::vector const& enabledAmendments); +[[nodiscard]] xrpl::STObject +createAmendmentsObject(std::vector const& enabledAmendments); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createBrokenAmendmentsObject(); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createAmmObject( std::string_view accountId, std::string_view assetCurrency, @@ -397,7 +397,7 @@ createAmmObject( uint64_t ownerNode = 0u ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createBridgeObject( std::string_view accountId, std::string_view lockingDoor, @@ -406,7 +406,7 @@ createBridgeObject( std::string_view issuingIssuer ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createChainOwnedClaimIdObject( std::string_view accountId, std::string_view lockingDoor, @@ -416,7 +416,7 @@ createChainOwnedClaimIdObject( std::string_view otherChainSource ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createChainOwnedCreateAccountClaimId( std::string_view accountId, std::string_view lockingDoor, @@ -427,23 +427,23 @@ createChainOwnedCreateAccountClaimId( void ammAddVoteSlot( - ripple::STObject& amm, - ripple::AccountID const& accountId, + xrpl::STObject& amm, + xrpl::AccountID const& accountId, uint16_t tradingFee, uint32_t voteWeight ); void ammSetAuctionSlot( - ripple::STObject& amm, - ripple::AccountID const& accountId, - ripple::STAmount price, + xrpl::STObject& amm, + xrpl::AccountID const& accountId, + xrpl::STAmount price, uint16_t discountedFee, uint32_t expiration, - std::vector const& authAccounts = {} + std::vector const& authAccounts = {} ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createDidObject( std::string_view accountId, std::string_view didDoc, @@ -451,10 +451,10 @@ createDidObject( std::string_view data ); -[[nodiscard]] ripple::Currency +[[nodiscard]] xrpl::Currency createLptCurrency(std::string_view assetCurrency, std::string_view asset2Currency); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createMptIssuanceObject( std::string_view accountId, std::uint32_t seq, @@ -469,26 +469,26 @@ createMptIssuanceObject( std::optional mutableFlags = std::nullopt ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createMpTokenObject( std::string_view accountId, - ripple::uint192 issuanceID, + xrpl::uint192 issuanceID, std::uint64_t mptAmount = 1, std::uint32_t flags = 0, std::optional lockedAmount = std::nullopt ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createMPTIssuanceCreateTx(std::string_view accountId, uint32_t fee, uint32_t seq); [[nodiscard]] data::TransactionAndMetadata createMPTIssuanceCreateTxWithMetadata(std::string_view accountId, uint32_t fee, uint32_t seq); [[nodiscard]] -ripple::STObject +xrpl::STObject createMPTokenAuthorizeTx( std::string_view accountId, - ripple::uint192 const& mptIssuanceID, + xrpl::uint192 const& mptIssuanceID, uint32_t fee, uint32_t seq, std::optional holder = std::nullopt, @@ -499,53 +499,53 @@ createMPTokenAuthorizeTx( data::TransactionAndMetadata createMPTokenAuthorizeTxWithMetadata( std::string_view accountId, - ripple::uint192 const& mptIssuanceID, + xrpl::uint192 const& mptIssuanceID, uint32_t fee, uint32_t seq ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createPermissionedDomainObject( std::string_view accountId, std::string_view ledgerIndex, - ripple::LedgerIndex seq, + xrpl::LedgerIndex seq, uint64_t ownerNode, - ripple::uint256 previousTxId, + xrpl::uint256 previousTxId, uint32_t previousTxSeq ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createDelegateObject( std::string_view accountId, std::string_view authorize, std::string_view ledgerIndex, uint64_t ownerNode, - ripple::uint256 previousTxId, + xrpl::uint256 previousTxId, uint32_t previousTxSeq ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createOraclePriceData( uint64_t assetPrice, - ripple::Currency baseAssetCurrency, - ripple::Currency quoteAssetCurrency, + xrpl::Currency baseAssetCurrency, + xrpl::Currency quoteAssetCurrency, uint8_t scale ); -[[nodiscard]] ripple::STArray -createPriceDataSeries(std::vector const& series); +[[nodiscard]] xrpl::STArray +createPriceDataSeries(std::vector const& series); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createOracleObject( std::string_view accountId, std::string_view provider, uint64_t ownerNode, uint32_t lastUpdateTime, - ripple::Blob uri, - ripple::Blob assetClass, + xrpl::Blob uri, + xrpl::Blob assetClass, uint32_t previousTxSeq, - ripple::uint256 previousTxId, - ripple::STArray priceDataSeries + xrpl::uint256 previousTxId, + xrpl::STArray priceDataSeries ); [[nodiscard]] data::TransactionAndMetadata @@ -555,13 +555,13 @@ createOracleSetTxWithMetadata( uint32_t fee, uint32_t docId, std::uint32_t lastUpdateTime, - ripple::STArray priceDataSeries, + xrpl::STArray priceDataSeries, std::string_view oracleIndex, bool created, std::string_view previousTxnId ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createCredentialObject( std::string_view acc1, std::string_view acc2, @@ -570,44 +570,44 @@ createCredentialObject( std::optional expiration = std::nullopt ); -[[nodiscard]] ripple::STArray +[[nodiscard]] xrpl::STArray createAuthCredentialArray( std::vector issuer, std::vector credType ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createVault( std::string_view owner, std::string_view account, - ripple::LedgerIndex seq, + xrpl::LedgerIndex seq, std::string_view assetCurrency, std::string_view assetIssuer, - ripple::uint192 shareMPTID, + xrpl::uint192 shareMPTID, uint64_t ownerNode, - ripple::uint256 previousTxId, + xrpl::uint256 previousTxId, uint32_t previousTxSeq ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createLoanBroker( std::string_view owner, std::string_view account, - ripple::LedgerIndex seq, - ripple::uint256 vaultID, + xrpl::LedgerIndex seq, + xrpl::uint256 vaultID, uint32_t loanSequence, - ripple::uint256 previousTxId, + xrpl::uint256 previousTxId, uint32_t previousTxSeq ); -[[nodiscard]] ripple::STObject +[[nodiscard]] xrpl::STObject createLoan( std::string_view borrower, - ripple::uint256 loanBrokerID, + xrpl::uint256 loanBrokerID, uint32_t loanSequence, uint32_t startDate, uint32_t paymentInterval, int64_t periodicPaymentValue, - ripple::uint256 previousTxId, + xrpl::uint256 previousTxId, uint32_t previousTxSeq ); diff --git a/tests/common/util/TestWsServer.cpp b/tests/common/util/TestWsServer.cpp index 1992cde48..8c26f6537 100644 --- a/tests/common/util/TestWsServer.cpp +++ b/tests/common/util/TestWsServer.cpp @@ -14,8 +14,6 @@ #include #include #include -#include -#include #include #include #include diff --git a/tests/common/util/config/FakeConfigData.hpp b/tests/common/util/config/FakeConfigData.hpp index 84b0798d5..4af0b1e62 100644 --- a/tests/common/util/config/FakeConfigData.hpp +++ b/tests/common/util/config/FakeConfigData.hpp @@ -85,7 +85,7 @@ generateConfig() */ /* Used to test overwriting default values in ClioConfigDefinition Above */ -static constexpr auto kJSON_DATA = R"JSON({ +static constexpr auto kJsonData = R"JSON({ "header": { "text1": "value", "port": 321, @@ -177,7 +177,7 @@ format; */ // Invalid Json key/values -static constexpr auto kINVALID_JSON_DATA = R"JSON({ +static constexpr auto kInvalidJsonData = R"JSON({ "header": { "port": "999", "admin": "true" diff --git a/tests/integration/CMakeLists.txt b/tests/integration/CMakeLists.txt index b9312eed1..03b72f750 100644 --- a/tests/integration/CMakeLists.txt +++ b/tests/integration/CMakeLists.txt @@ -28,3 +28,5 @@ set_target_properties( clio_integration_tests PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} ) + +patch_nix_binary(clio_integration_tests) diff --git a/tests/integration/TestGlobals.cpp b/tests/integration/TestGlobals.cpp index 0fcd7ad0d..1f43d7225 100644 --- a/tests/integration/TestGlobals.cpp +++ b/tests/integration/TestGlobals.cpp @@ -9,8 +9,8 @@ TestGlobals& TestGlobals::instance() { - static TestGlobals kINST; - return kINST; + static TestGlobals kInst; + return kInst; } void diff --git a/tests/integration/data/BackendFactoryTests.cpp b/tests/integration/data/BackendFactoryTests.cpp index 1471f8806..6dd6cc875 100644 --- a/tests/integration/data/BackendFactoryTests.cpp +++ b/tests/integration/data/BackendFactoryTests.cpp @@ -24,8 +24,8 @@ using namespace util::config; struct BackendCassandraFactoryTest : SyncAsioContextTest, util::prometheus::WithPrometheus { - static constexpr auto kKEYSPACE = "factory_test"; - static constexpr auto kPROVIDER = "cassandra"; + static constexpr auto kKeyspace = "factory_test"; + static constexpr auto kProvider = "cassandra"; protected: ClioConfigDefinition cfg_{ @@ -34,8 +34,8 @@ protected: ConfigValue{ConfigType::String}.defaultValue(TestGlobals::instance().backendHost)}, {"database.cassandra.secure_connect_bundle", ConfigValue{ConfigType::String}.optional()}, {"database.cassandra.port", ConfigValue{ConfigType::Integer}.optional()}, - {"database.cassandra.keyspace", ConfigValue{ConfigType::String}.defaultValue(kKEYSPACE)}, - {"database.cassandra.provider", ConfigValue{ConfigType::String}.defaultValue(kPROVIDER)}, + {"database.cassandra.keyspace", ConfigValue{ConfigType::String}.defaultValue(kKeyspace)}, + {"database.cassandra.provider", ConfigValue{ConfigType::String}.defaultValue(kProvider)}, {"database.cassandra.replication_factor", ConfigValue{ConfigType::Integer}.defaultValue(1)}, {"database.cassandra.table_prefix", ConfigValue{ConfigType::String}.optional()}, {"database.cassandra.max_write_requests_outstanding", @@ -81,7 +81,7 @@ public: // drop the keyspace for next test data::cassandra::Handle const handle{TestGlobals::instance().backendHost}; EXPECT_TRUE(handle.connect()); - EXPECT_TRUE(handle.execute("DROP KEYSPACE IF EXISTS " + std::string{kKEYSPACE})); + EXPECT_TRUE(handle.execute("DROP KEYSPACE IF EXISTS " + std::string{kKeyspace})); } }; @@ -122,12 +122,12 @@ TEST_F(BackendCassandraFactoryTestWithDB, CreateCassandraBackend) EXPECT_TRUE(handle.connect()); EXPECT_TRUE(handle.execute( fmt::format( - "INSERT INTO {}.ledger_range (is_latest, sequence) VALUES (False, 100)", kKEYSPACE + "INSERT INTO {}.ledger_range (is_latest, sequence) VALUES (False, 100)", kKeyspace ) )); EXPECT_TRUE(handle.execute( fmt::format( - "INSERT INTO {}.ledger_range (is_latest, sequence) VALUES (True, 500)", kKEYSPACE + "INSERT INTO {}.ledger_range (is_latest, sequence) VALUES (True, 500)", kKeyspace ) )); } diff --git a/tests/integration/data/cassandra/BackendTests.cpp b/tests/integration/data/cassandra/BackendTests.cpp index 449572a41..3a925e714 100644 --- a/tests/integration/data/cassandra/BackendTests.cpp +++ b/tests/integration/data/cassandra/BackendTests.cpp @@ -29,10 +29,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -48,6 +50,7 @@ #include #include #include +#include #include #include #include @@ -66,17 +69,17 @@ using namespace data::cassandra; class BackendCassandraTestBase : public SyncAsioContextTest, public WithPrometheus { protected: - static constexpr auto kCASSANDRA = "cassandra"; + static constexpr auto kCassandra = "cassandra"; ClioConfigDefinition cfg_{ - {"database.type", ConfigValue{ConfigType::String}.defaultValue(kCASSANDRA)}, + {"database.type", ConfigValue{ConfigType::String}.defaultValue(kCassandra)}, {"database.cassandra.contact_points", ConfigValue{ConfigType::String}.defaultValue(TestGlobals::instance().backendHost)}, {"database.cassandra.secure_connect_bundle", ConfigValue{ConfigType::String}.optional()}, {"database.cassandra.port", ConfigValue{ConfigType::Integer}.optional()}, {"database.cassandra.keyspace", ConfigValue{ConfigType::String}.defaultValue(TestGlobals::instance().backendKeyspace)}, - {"database.cassandra.provider", ConfigValue{ConfigType::String}.defaultValue(kCASSANDRA)}, + {"database.cassandra.provider", ConfigValue{ConfigType::String}.defaultValue(kCassandra)}, {"database.cassandra.replication_factor", ConfigValue{ConfigType::Integer}.defaultValue(1)}, {"database.cassandra.table_prefix", ConfigValue{ConfigType::String}.optional()}, {"database.cassandra.max_write_requests_outstanding", @@ -102,7 +105,7 @@ protected: {"read_only", ConfigValue{ConfigType::Boolean}.defaultValue(false)} }; - static constexpr auto kRAWHEADER = + static constexpr auto kRawheader = "03C3141A01633CD656F91B4EBB5EB89B791BD34DBC8A04BB6F407C5335BC54351E" "DD733898497E809E04074D14D271E4832D7888754F9230800761563A292FA2315A" "6DB6FE30CC5909B285080FCD6773CC883F9FE0EE4D439340AC592AADB973ED3CF5" @@ -148,12 +151,11 @@ TEST_F(BackendCassandraTest, Basic) "CE5AA29652EFFD80AC59CD91416E4E13DBBE"; std::string rawHeaderBlob = hexStringToBinaryString(rawHeader); - ripple::LedgerHeader const lgrInfo = - util::deserializeHeader(ripple::makeSlice(rawHeaderBlob)); + xrpl::LedgerHeader const lgrInfo = util::deserializeHeader(xrpl::makeSlice(rawHeaderBlob)); backend_->writeLedger(lgrInfo, std::move(rawHeaderBlob)); backend_->writeSuccessor( - uint256ToString(data::kFIRST_KEY), lgrInfo.seq, uint256ToString(data::kLAST_KEY) + uint256ToString(data::kFirstKey), lgrInfo.seq, uint256ToString(data::kLastKey) ); ASSERT_TRUE(backend_->finishWrites(lgrInfo.seq)); { @@ -387,7 +389,7 @@ TEST_F(BackendCassandraTest, Basic) std::string const nftTxnHashHex = "6C7F69A6D25A13AC4A2E9145999F45D4674F939900017A96885FDC2757" "E9284E"; - ripple::uint256 nftID; + xrpl::uint256 nftID; EXPECT_TRUE(nftID.parseHex( "000800006203F49C21D5D6E022CB16DE3538F248662" "FC73CEF7FF5C60000002C" @@ -398,7 +400,7 @@ TEST_F(BackendCassandraTest, Basic) std::string const hashBlob = hexStringToBinaryString(hashHex); std::string accountBlob = hexStringToBinaryString(accountHex); std::string const accountIndexBlob = hexStringToBinaryString(accountIndexHex); - std::vector affectedAccounts; + std::vector affectedAccounts; std::string nftTxnBlob = hexStringToBinaryString(nftTxnHex); std::string const nftTxnMetaBlob = hexStringToBinaryString(nftTxnMeta); @@ -410,9 +412,11 @@ TEST_F(BackendCassandraTest, Basic) lgrInfoNext.parentHash = lgrInfoNext.hash; lgrInfoNext.hash++; - ripple::uint256 hash256; + xrpl::uint256 hash256; EXPECT_TRUE(hash256.parseHex(hashHex)); - ripple::TxMeta const txMeta{hash256, lgrInfoNext.seq, metaBlob}; + xrpl::TxMeta const txMeta{ + hash256, lgrInfoNext.seq, xrpl::Blob{metaBlob.begin(), metaBlob.end()} + }; auto accountsSet = txMeta.getAffectedAccounts(); for (auto& a : accountsSet) { affectedAccounts.push_back(a); @@ -420,11 +424,15 @@ TEST_F(BackendCassandraTest, Basic) std::vector accountTxData; accountTxData.emplace_back(txMeta, hash256); - ripple::uint256 nftHash256; + xrpl::uint256 nftHash256; EXPECT_TRUE(nftHash256.parseHex(nftTxnHashHex)); - ripple::TxMeta const nftTxMeta{nftHash256, lgrInfoNext.seq, nftTxnMetaBlob}; - ripple::SerialIter it{nftTxnBlob.data(), nftTxnBlob.size()}; - ripple::STTx const sttx{it}; + xrpl::TxMeta const nftTxMeta{ + nftHash256, + lgrInfoNext.seq, + xrpl::Blob{nftTxnMetaBlob.begin(), nftTxnMetaBlob.end()} + }; + xrpl::SerialIter it{nftTxnBlob.data(), nftTxnBlob.size()}; + xrpl::STTx const sttx{it}; auto const [parsedNFTTxsRef, parsedNFT] = etl::getNFTDataFromTx(nftTxMeta, sttx); // need to copy the nft txns so we can std::move later std::vector parsedNFTTxs; @@ -451,10 +459,10 @@ TEST_F(BackendCassandraTest, Basic) std::string{accountIndexBlob}, lgrInfoNext.seq, std::string{accountBlob} ); backend_->writeSuccessor( - uint256ToString(data::kFIRST_KEY), lgrInfoNext.seq, std::string{accountIndexBlob} + uint256ToString(data::kFirstKey), lgrInfoNext.seq, std::string{accountIndexBlob} ); backend_->writeSuccessor( - std::string{accountIndexBlob}, lgrInfoNext.seq, uint256ToString(data::kLAST_KEY) + std::string{accountIndexBlob}, lgrInfoNext.seq, uint256ToString(data::kLastKey) ); ASSERT_TRUE(backend_->finishWrites(lgrInfoNext.seq)); @@ -480,7 +488,7 @@ TEST_F(BackendCassandraTest, Basic) ); auto hashes = backend_->fetchAllTransactionHashesInLedger(lgrInfoNext.seq, yield); EXPECT_EQ(hashes.size(), 1); - EXPECT_EQ(ripple::strHex(hashes[0]), hashHex); + EXPECT_EQ(xrpl::strHex(hashes[0]), hashHex); for (auto& a : affectedAccounts) { auto [accountTransactions, cursor] = backend_->fetchAccountTransactions(a, 100, true, {}, yield); @@ -495,7 +503,7 @@ TEST_F(BackendCassandraTest, Basic) EXPECT_EQ(nftTxns[0], nftTxns[0]); EXPECT_FALSE(cursor); - ripple::uint256 key256; + xrpl::uint256 key256; EXPECT_TRUE(key256.parseHex(accountIndexHex)); auto obj = backend_->fetchLedgerObject(key256, lgrInfoNext.seq, yield); EXPECT_TRUE(obj); @@ -540,7 +548,7 @@ TEST_F(BackendCassandraTest, Basic) auto txns = backend_->fetchAllTransactionsInLedger(lgrInfoNext.seq, yield); EXPECT_EQ(txns.size(), 0); - ripple::uint256 key256; + xrpl::uint256 key256; EXPECT_TRUE(key256.parseHex(accountIndexHex)); auto obj = backend_->fetchLedgerObject(key256, lgrInfoNext.seq, yield); EXPECT_TRUE(obj); @@ -575,7 +583,7 @@ TEST_F(BackendCassandraTest, Basic) std::string{accountIndexBlob}, lgrInfoNext.seq, std::string{} ); backend_->writeSuccessor( - uint256ToString(data::kFIRST_KEY), lgrInfoNext.seq, uint256ToString(data::kLAST_KEY) + uint256ToString(data::kFirstKey), lgrInfoNext.seq, uint256ToString(data::kLastKey) ); ASSERT_TRUE(backend_->finishWrites(lgrInfoNext.seq)); @@ -591,7 +599,7 @@ TEST_F(BackendCassandraTest, Basic) auto txns = backend_->fetchAllTransactionsInLedger(lgrInfoNext.seq, yield); EXPECT_EQ(txns.size(), 0); - ripple::uint256 key256; + xrpl::uint256 key256; EXPECT_TRUE(key256.parseHex(accountIndexHex)); auto obj = backend_->fetchLedgerObject(key256, lgrInfoNext.seq, yield); EXPECT_FALSE(obj); @@ -609,13 +617,13 @@ TEST_F(BackendCassandraTest, Basic) auto generateObjects = [](size_t numObjects, uint32_t ledgerSequence) { std::vector> res{numObjects}; - ripple::uint256 key; + xrpl::uint256 key; key = ledgerSequence * 100000ul; for (auto& blob : res) { ++key; std::string const keyStr{ - reinterpret_cast(key.data()), ripple::uint256::size() + reinterpret_cast(key.data()), xrpl::uint256::size() }; blob.first = keyStr; blob.second = std::to_string(ledgerSequence) + keyStr; @@ -630,12 +638,12 @@ TEST_F(BackendCassandraTest, Basic) }; auto generateTxns = [](size_t numTxns, uint32_t ledgerSequence) { std::vector> res{numTxns}; - ripple::uint256 base; + xrpl::uint256 base; base = ledgerSequence * 100000ul; for (auto& blob : res) { ++base; std::string const hashStr{ - reinterpret_cast(base.data()), ripple::uint256::size() + reinterpret_cast(base.data()), xrpl::uint256::size() }; std::string const txnStr = "tx" + std::to_string(ledgerSequence) + hashStr; std::string const metaStr = "meta" + std::to_string(ledgerSequence) + hashStr; @@ -644,8 +652,8 @@ TEST_F(BackendCassandraTest, Basic) return res; }; auto generateAccounts = [](uint32_t ledgerSequence, uint32_t numAccounts) { - std::vector accounts; - ripple::AccountID base; + std::vector accounts; + xrpl::AccountID base; base = ledgerSequence * 998765ul; for (size_t i = 0; i < numAccounts; ++i) { ++base; @@ -710,9 +718,7 @@ TEST_F(BackendCassandraTest, Basic) ); } else { backend_->writeSuccessor( - std::string{objs[i].first}, - lgrInfo.seq, - uint256ToString(data::kLAST_KEY) + std::string{objs[i].first}, lgrInfo.seq, uint256ToString(data::kLastKey) ); } } @@ -724,7 +730,7 @@ TEST_F(BackendCassandraTest, Basic) ); } else { backend_->writeSuccessor( - uint256ToString(data::kFIRST_KEY), lgrInfo.seq, std::string{objs[0].first} + uint256ToString(data::kFirstKey), lgrInfo.seq, std::string{objs[0].first} ); } } @@ -788,7 +794,7 @@ TEST_F(BackendCassandraTest, Basic) ); } } - std::vector keys; + std::vector keys; for (auto [key, obj] : objs) { auto retObj = backend_->fetchLedgerObject(binaryStringToUint256(key), seq, yield); if (obj.size()) { @@ -833,9 +839,9 @@ TEST_F(BackendCassandraTest, Basic) for (auto const& obj : objs) { bool found = false; for (auto const& retObj : retObjs) { - if (ripple::strHex(obj.first) == ripple::strHex(retObj.key)) { + if (xrpl::strHex(obj.first) == xrpl::strHex(retObj.key)) { found = true; - ASSERT_EQ(ripple::strHex(obj.second), ripple::strHex(retObj.blob)); + ASSERT_EQ(xrpl::strHex(obj.second), xrpl::strHex(retObj.blob)); } } if (found != (obj.second.size() != 0)) @@ -846,8 +852,8 @@ TEST_F(BackendCassandraTest, Basic) std::map>> state; std::map>> allTxns; std::unordered_map> allTxnsMap; - std::map>> allAccountTx; - std::map lgrInfos; + std::map>> allAccountTx; + std::map lgrInfos; for (size_t i = 0; i < 10; ++i) { lgrInfoNext = generateNextLedger(lgrInfoNext); auto objs = generateObjects(25, lgrInfoNext.seq); @@ -856,7 +862,7 @@ TEST_F(BackendCassandraTest, Basic) for (auto rec : accountTx) { for (auto account : rec.accounts) { allAccountTx[lgrInfoNext.seq][account].emplace_back( - reinterpret_cast(rec.txHash.data()), ripple::uint256::size() + reinterpret_cast(rec.txHash.data()), xrpl::uint256::size() ); } } @@ -887,7 +893,7 @@ TEST_F(BackendCassandraTest, Basic) for (auto rec : accountTx) { for (auto account : rec.accounts) { allAccountTx[lgrInfoNext.seq][account].emplace_back( - reinterpret_cast(rec.txHash.data()), ripple::uint256::size() + reinterpret_cast(rec.txHash.data()), xrpl::uint256::size() ); } } @@ -927,7 +933,7 @@ TEST_F(BackendCassandraTest, Basic) auto flattenAccountTx = [&](uint32_t max) { std::unordered_map< - ripple::AccountID, + xrpl::AccountID, std::vector>> accountTx; for (auto const& [seq, map] : allAccountTx) { @@ -975,16 +981,15 @@ TEST_F(BackendCassandraTest, CacheIntegration) std::string const accountIndexHex = "E0311EB450B6177F969B94DBDDA83E99B7A0576ACD9079573876F16C0C004F06"; - std::string rawHeaderBlob = hexStringToBinaryString(kRAWHEADER); + std::string rawHeaderBlob = hexStringToBinaryString(kRawheader); std::string accountBlob = hexStringToBinaryString(accountHex); std::string const accountIndexBlob = hexStringToBinaryString(accountIndexHex); - ripple::LedgerHeader const lgrInfo = - util::deserializeHeader(ripple::makeSlice(rawHeaderBlob)); + xrpl::LedgerHeader const lgrInfo = util::deserializeHeader(xrpl::makeSlice(rawHeaderBlob)); backend_->startWrites(); backend_->writeLedger(lgrInfo, std::move(rawHeaderBlob)); backend_->writeSuccessor( - uint256ToString(data::kFIRST_KEY), lgrInfo.seq, uint256ToString(data::kLAST_KEY) + uint256ToString(data::kFirstKey), lgrInfo.seq, uint256ToString(data::kLastKey) ); ASSERT_TRUE(backend_->finishWrites(lgrInfo.seq)); { @@ -1059,15 +1064,15 @@ TEST_F(BackendCassandraTest, CacheIntegration) backend_->writeLedgerObject( std::string{accountIndexBlob}, lgrInfoNext.seq, std::string{accountBlob} ); - auto key = ripple::uint256::fromVoidChecked(accountIndexBlob); + auto key = xrpl::uint256::fromVoidChecked(accountIndexBlob); backend_->cache().update( {{.key = *key, .blob = {accountBlob.begin(), accountBlob.end()}}}, lgrInfoNext.seq ); backend_->writeSuccessor( - uint256ToString(data::kFIRST_KEY), lgrInfoNext.seq, std::string{accountIndexBlob} + uint256ToString(data::kFirstKey), lgrInfoNext.seq, std::string{accountIndexBlob} ); backend_->writeSuccessor( - std::string{accountIndexBlob}, lgrInfoNext.seq, uint256ToString(data::kLAST_KEY) + std::string{accountIndexBlob}, lgrInfoNext.seq, uint256ToString(data::kLastKey) ); ASSERT_TRUE(backend_->finishWrites(lgrInfoNext.seq)); @@ -1080,7 +1085,7 @@ TEST_F(BackendCassandraTest, CacheIntegration) auto retLgr = backend_->fetchLedgerBySequence(lgrInfoNext.seq, yield); EXPECT_TRUE(retLgr); EXPECT_EQ(ledgerHeaderToBlob(*retLgr), ledgerHeaderToBlob(lgrInfoNext)); - ripple::uint256 key256; + xrpl::uint256 key256; EXPECT_TRUE(key256.parseHex(accountIndexHex)); auto obj = backend_->fetchLedgerObject(key256, lgrInfoNext.seq, yield); EXPECT_TRUE(obj); @@ -1108,7 +1113,7 @@ TEST_F(BackendCassandraTest, CacheIntegration) backend_->writeLedger(lgrInfoNext, ledgerHeaderToBinaryString(lgrInfoNext)); std::shuffle(accountBlob.begin(), accountBlob.end(), randomEngine_); - auto key = ripple::uint256::fromVoidChecked(accountIndexBlob); + auto key = xrpl::uint256::fromVoidChecked(accountIndexBlob); backend_->cache().update( {{.key = *key, .blob = {accountBlob.begin(), accountBlob.end()}}}, lgrInfoNext.seq ); @@ -1126,7 +1131,7 @@ TEST_F(BackendCassandraTest, CacheIntegration) auto retLgr = backend_->fetchLedgerBySequence(lgrInfoNext.seq, yield); EXPECT_TRUE(retLgr); - ripple::uint256 key256; + xrpl::uint256 key256; EXPECT_TRUE(key256.parseHex(accountIndexHex)); auto obj = backend_->fetchLedgerObject(key256, lgrInfoNext.seq, yield); EXPECT_TRUE(obj); @@ -1158,13 +1163,13 @@ TEST_F(BackendCassandraTest, CacheIntegration) lgrInfoNext.accountHash = ~(lgrInfoNext.accountHash ^ lgrInfoNext.txHash); backend_->writeLedger(lgrInfoNext, ledgerHeaderToBinaryString(lgrInfoNext)); - auto key = ripple::uint256::fromVoidChecked(accountIndexBlob); + auto key = xrpl::uint256::fromVoidChecked(accountIndexBlob); backend_->cache().update({{.key = *key, .blob = {}}}, lgrInfoNext.seq); backend_->writeLedgerObject( std::string{accountIndexBlob}, lgrInfoNext.seq, std::string{} ); backend_->writeSuccessor( - uint256ToString(data::kFIRST_KEY), lgrInfoNext.seq, uint256ToString(data::kLAST_KEY) + uint256ToString(data::kFirstKey), lgrInfoNext.seq, uint256ToString(data::kLastKey) ); ASSERT_TRUE(backend_->finishWrites(lgrInfoNext.seq)); @@ -1177,7 +1182,7 @@ TEST_F(BackendCassandraTest, CacheIntegration) auto retLgr = backend_->fetchLedgerBySequence(lgrInfoNext.seq, yield); EXPECT_TRUE(retLgr); - ripple::uint256 key256; + xrpl::uint256 key256; EXPECT_TRUE(key256.parseHex(accountIndexHex)); auto obj = backend_->fetchLedgerObject(key256, lgrInfoNext.seq, yield); EXPECT_FALSE(obj); @@ -1195,13 +1200,13 @@ TEST_F(BackendCassandraTest, CacheIntegration) auto generateObjects = [](size_t numObjects, uint64_t ledgerSequence) { std::vector> res{numObjects}; - ripple::uint256 key; + xrpl::uint256 key; key = ledgerSequence * 100000; for (auto& blob : res) { ++key; std::string const keyStr{ - reinterpret_cast(key.data()), ripple::uint256::size() + reinterpret_cast(key.data()), xrpl::uint256::size() }; blob.first = keyStr; blob.second = std::to_string(ledgerSequence) + keyStr; @@ -1230,7 +1235,7 @@ TEST_F(BackendCassandraTest, CacheIntegration) std::vector cacheUpdates; for (auto [key, obj] : objs) { backend_->writeLedgerObject(std::string{key}, lgrInfo.seq, std::string{obj}); - auto key256 = ripple::uint256::fromVoidChecked(key); + auto key256 = xrpl::uint256::fromVoidChecked(key); cacheUpdates.push_back({*key256, {obj.begin(), obj.end()}}); } backend_->cache().update(cacheUpdates, lgrInfo.seq); @@ -1247,9 +1252,7 @@ TEST_F(BackendCassandraTest, CacheIntegration) ); } else { backend_->writeSuccessor( - std::string{objs[i].first}, - lgrInfo.seq, - uint256ToString(data::kLAST_KEY) + std::string{objs[i].first}, lgrInfo.seq, uint256ToString(data::kLastKey) ); } } @@ -1261,7 +1264,7 @@ TEST_F(BackendCassandraTest, CacheIntegration) ); } else { backend_->writeSuccessor( - uint256ToString(data::kFIRST_KEY), lgrInfo.seq, std::string{objs[0].first} + uint256ToString(data::kFirstKey), lgrInfo.seq, std::string{objs[0].first} ); } } @@ -1286,7 +1289,7 @@ TEST_F(BackendCassandraTest, CacheIntegration) << "; retLgr parentHash:" << retLgr->parentHash << "; lgr Info parentHash:" << lgrInfo.parentHash; - std::vector keys; + std::vector keys; for (auto [key, obj] : objs) { auto retObj = backend_->fetchLedgerObject(binaryStringToUint256(key), seq, yield); if (obj.size()) { @@ -1329,9 +1332,9 @@ TEST_F(BackendCassandraTest, CacheIntegration) for (auto const& obj : objs) { bool found = false; for (auto const& retObj : retObjs) { - if (ripple::strHex(obj.first) == ripple::strHex(retObj.key)) { + if (xrpl::strHex(obj.first) == xrpl::strHex(retObj.key)) { found = true; - ASSERT_EQ(ripple::strHex(obj.second), ripple::strHex(retObj.blob)); + ASSERT_EQ(xrpl::strHex(obj.second), xrpl::strHex(retObj.blob)); } } if (found != (obj.second.size() != 0)) @@ -1340,7 +1343,7 @@ TEST_F(BackendCassandraTest, CacheIntegration) }; std::map>> state; - std::map lgrInfos; + std::map lgrInfos; for (size_t i = 0; i < 10; ++i) { lgrInfoNext = generateNextLedger(lgrInfoNext); auto objs = generateObjects(25, lgrInfoNext.seq); @@ -1423,9 +1426,8 @@ public: TEST_F(CacheBackendCassandraTest, CacheFetchLedgerBySeq) { runSpawn([&](boost::asio::yield_context yield) { - auto rawHeaderBlob = hexStringToBinaryString(kRAWHEADER); - ripple::LedgerHeader const lgrInfo = - util::deserializeHeader(ripple::makeSlice(rawHeaderBlob)); + auto rawHeaderBlob = hexStringToBinaryString(kRawheader); + xrpl::LedgerHeader const lgrInfo = util::deserializeHeader(xrpl::makeSlice(rawHeaderBlob)); backend_->writeLedger(lgrInfo, std::move(rawHeaderBlob)); auto const testLedgerSeq = lgrInfo.seq; @@ -1465,37 +1467,428 @@ TEST_F(CacheBackendCassandraTest, CacheFetchLedgerBySeq) }); } +struct BackendCassandraMPTokenIssuanceTest : BackendCassandraTest { + static xrpl::uint192 + makeMptIssuanceId() + { + return xrpl::makeMptID(1, makeAccount(0x01)); + } + + static xrpl::AccountID + makeAccount(std::uint8_t seed) + { + return xrpl::AccountID{seed}; + } + + static xrpl::uint256 + makeHash(std::uint8_t seed) + { + return xrpl::uint256{seed}; + } + + // Writes a single ledger so that fetchLedgerRange() is populated, which the fetchers + // require before reading any index rows. + void + setupLedgerRange(std::uint32_t seq) + { + std::string rawHeaderBlob = hexStringToBinaryString(kRawheader); + xrpl::LedgerHeader lgrInfo = util::deserializeHeader(xrpl::makeSlice(rawHeaderBlob)); + lgrInfo.seq = seq; + backend_->writeLedger(lgrInfo, std::move(rawHeaderBlob)); + backend_->writeSuccessor( + uint256ToString(data::kFirstKey), lgrInfo.seq, uint256ToString(data::kLastKey) + ); + ASSERT_TRUE(backend_->finishWrites(lgrInfo.seq)); + auto const rng = backend_->fetchLedgerRange(); + ASSERT_TRUE(rng.has_value()); + } + + void + writeTxBlob(xrpl::uint256 const& hash, std::uint32_t seq) + { + backend_->writeTransaction( + uint256ToString(hash), seq, 0, "tx_" + xrpl::strHex(hash), "meta_" + xrpl::strHex(hash) + ); + } +}; + +TEST_F(BackendCassandraMPTokenIssuanceTest, RoundTripIssuanceAndAccountIndexes) +{ + runSpawn([this](boost::asio::yield_context yield) { + auto const mptIssuanceId = makeMptIssuanceId(); + auto const account = makeAccount(0x42); + auto const secondAccount = makeAccount(0x43); + std::uint32_t const seq = 100; + + setupLedgerRange(seq); + + auto const hash = makeHash(0x01); + writeTxBlob(hash, seq); + auto const expectedTxBlob = "tx_" + xrpl::strHex(hash); + auto const expectedMetaBlob = "meta_" + xrpl::strHex(hash); + + auto expectFetchedSingle = [&](auto const& txns) { + ASSERT_EQ(txns.size(), 1); + EXPECT_EQ( + std::string(txns[0].transaction.begin(), txns[0].transaction.end()), expectedTxBlob + ); + EXPECT_EQ( + std::string(txns[0].metadata.begin(), txns[0].metadata.end()), expectedMetaBlob + ); + EXPECT_EQ(txns[0].ledgerSequence, seq); + }; + + MPTokenIssuanceTransactionsData const record{ + .mptIssuanceID = mptIssuanceId, + .accounts = {account, secondAccount}, + .ledgerSequence = seq, + .transactionIndex = 1, + .txHash = hash + }; + backend_->writeMPTokenIssuanceTransactions({record}); + backend_->writeAccountMPTokenIssuanceTransactions({record}); + backend_->waitForWritesToFinish(); + + { + auto [txns, cursor] = + backend_->fetchMPTokenIssuanceTransactions(mptIssuanceId, 100, false, {}, yield); + expectFetchedSingle(txns); + EXPECT_FALSE(cursor); + } + { + auto [txns, cursor] = backend_->fetchAccountMPTokenIssuanceTransactions( + mptIssuanceId, account, 100, false, {}, yield + ); + expectFetchedSingle(txns); + EXPECT_FALSE(cursor); + } + // Both affected accounts are indexed: one row was written per account. + { + auto [txns, cursor] = backend_->fetchAccountMPTokenIssuanceTransactions( + mptIssuanceId, secondAccount, 100, false, {}, yield + ); + expectFetchedSingle(txns); + EXPECT_FALSE(cursor); + } + { + auto [txns, cursor] = backend_->fetchAccountMPTokenIssuanceTransactions( + mptIssuanceId, makeAccount(0x99), 100, false, {}, yield + ); + EXPECT_EQ(txns.size(), 0); + } + { + auto const secondHash = makeHash(0x02); + writeTxBlob(secondHash, seq); + auto const expectedSecondTxBlob = "tx_" + xrpl::strHex(secondHash); + auto const expectedSecondMetaBlob = "meta_" + xrpl::strHex(secondHash); + auto expectFetchedSecond = [&](auto const& txns) { + ASSERT_EQ(txns.size(), 1); + EXPECT_EQ( + std::string(txns[0].transaction.begin(), txns[0].transaction.end()), + expectedSecondTxBlob + ); + EXPECT_EQ( + std::string(txns[0].metadata.begin(), txns[0].metadata.end()), + expectedSecondMetaBlob + ); + EXPECT_EQ(txns[0].ledgerSequence, seq); + }; + MPTokenIssuanceTransactionsData const secondRecord{ + .mptIssuanceID = mptIssuanceId, + .accounts = {account}, + .ledgerSequence = seq, + .transactionIndex = 2, + .txHash = secondHash + }; + backend_->writeMPTokenIssuanceTransactions({secondRecord}); + backend_->writeAccountMPTokenIssuanceTransactions({secondRecord}); + backend_->waitForWritesToFinish(); + + { + auto [txns, cursor] = + backend_->fetchMPTokenIssuanceTransactions(mptIssuanceId, 1, false, {}, yield); + expectFetchedSecond(txns); + EXPECT_TRUE(cursor); + } + { + auto [txns, cursor] = backend_->fetchAccountMPTokenIssuanceTransactions( + mptIssuanceId, account, 1, false, {}, yield + ); + expectFetchedSecond(txns); + EXPECT_TRUE(cursor); + } + } + }); +} + +TEST_F(BackendCassandraMPTokenIssuanceTest, DescendingOrderForwardAndReverse) +{ + runSpawn([this](boost::asio::yield_context yield) { + auto const mptIssuanceId = makeMptIssuanceId(); + std::uint32_t const baseSeq = 200; + + // Three txns in three different ledgers, so ordering is checked across ledgers, + // not just by transaction index within one ledger. + std::vector hashes; + std::vector seqs; + for (std::uint8_t i = 1; i <= 3; ++i) { + auto const seq = baseSeq + i; + seqs.push_back(seq); + setupLedgerRange(seq); + auto const hash = makeHash(i); + hashes.push_back(hash); + writeTxBlob(hash, seq); + MPTokenIssuanceTransactionsData const record{ + .mptIssuanceID = mptIssuanceId, + .accounts = {}, + .ledgerSequence = seq, + .transactionIndex = i, + .txHash = hash + }; + backend_->writeMPTokenIssuanceTransactions({record}); + } + backend_->waitForWritesToFinish(); + + auto txBlobToString = [](data::TransactionAndMetadata const& tx) { + return std::string(tx.transaction.begin(), tx.transaction.end()); + }; + auto expectedBlob = [&](std::uint8_t i) { return "tx_" + xrpl::strHex(makeHash(i)); }; + + // Reverse (forward=false): newest first -> rows 3, 2, 1. + { + auto [txns, cursor] = + backend_->fetchMPTokenIssuanceTransactions(mptIssuanceId, 100, false, {}, yield); + ASSERT_EQ(txns.size(), 3); + EXPECT_FALSE(cursor); + EXPECT_EQ(txBlobToString(txns[0]), expectedBlob(3)); + EXPECT_EQ(txBlobToString(txns[1]), expectedBlob(2)); + EXPECT_EQ(txBlobToString(txns[2]), expectedBlob(1)); + } + // Forward (forward=true): oldest first -> rows 1, 2, 3 (the reverse order). + { + auto [txns, cursor] = + backend_->fetchMPTokenIssuanceTransactions(mptIssuanceId, 100, true, {}, yield); + ASSERT_EQ(txns.size(), 3); + EXPECT_FALSE(cursor); + EXPECT_EQ(txBlobToString(txns[0]), expectedBlob(1)); + EXPECT_EQ(txBlobToString(txns[1]), expectedBlob(2)); + EXPECT_EQ(txBlobToString(txns[2]), expectedBlob(3)); + } + }); +} + +TEST_F(BackendCassandraMPTokenIssuanceTest, MarkerPaginationRoundTrip) +{ + runSpawn([this](boost::asio::yield_context yield) { + auto const mptIssuanceId = makeMptIssuanceId(); + std::uint32_t const baseSeq = 300; + + enum class ExpectedPaginationEnd { PartialPage, EmptyPage }; + + auto txBlobToString = [](data::TransactionAndMetadata const& tx) { + return std::string(tx.transaction.begin(), tx.transaction.end()); + }; + auto expectedBlob = [&](std::uint8_t i) { return "tx_" + xrpl::strHex(makeHash(i)); }; + auto expectSeenInOrder = [](std::vector const& seen, + bool forward, + std::set const& expected) { + std::vector expectedOrder(expected.begin(), expected.end()); + if (not forward) + std::ranges::reverse(expectedOrder); + + EXPECT_EQ(seen, expectedOrder) + << "pagination returned rows out of order for forward=" << forward; + }; + + // Writes `total` rows, each in its own ledger and at a distinct transaction index, + // so paging covers ordering across both. + auto setup = + [&](xrpl::uint192 const& issuanceId, std::uint8_t total, std::uint32_t firstSeq) { + std::set expected; + for (std::uint8_t i = 1; i <= total; ++i) { + auto const seq = firstSeq + i - 1; + setupLedgerRange(seq); + auto const hash = makeHash(i); + writeTxBlob(hash, seq); + MPTokenIssuanceTransactionsData const record{ + .mptIssuanceID = issuanceId, + .accounts = {}, + .ledgerSequence = seq, + .transactionIndex = i, + .txHash = hash + }; + backend_->writeMPTokenIssuanceTransactions({record}); + expected.insert(expectedBlob(i)); + } + backend_->waitForWritesToFinish(); + return expected; + }; + + // Page through every row; assert page order plus that the union of pages equals `expected` + // exactly: every row seen exactly once (no duplicates from a repeated cursor row, no gaps + // from a dropped row). Each full page (one that returns a cursor) must be exactly `limit`. + auto pageThrough = [&](xrpl::uint192 const& issuanceId, + bool forward, + std::uint32_t limit, + std::set const& expected, + ExpectedPaginationEnd expectedEnd) { + ASSERT_NE(limit, 0u); + auto const limitSize = static_cast(limit); + + std::vector seen; + std::optional cursor; + std::size_t pages = 0; + auto const maxPages = (expected.size() / limitSize) + 2; + bool sawEmptyTerminator = false; + do { + auto [txns, retCursor] = backend_->fetchMPTokenIssuanceTransactions( + issuanceId, limit, forward, cursor, yield + ); + ++pages; + // Guard against an infinite loop from a non-advancing cursor. + ASSERT_LE(pages, maxPages) + << "pagination did not terminate cleanly for forward=" << forward; + if (txns.empty()) { + sawEmptyTerminator = true; + EXPECT_FALSE(retCursor); + } else { + EXPECT_LE(txns.size(), limitSize); + if (retCursor) + EXPECT_EQ(txns.size(), limitSize); + } + for (auto const& tx : txns) + seen.push_back(txBlobToString(tx)); + cursor = retCursor; + } while (cursor); + + if (expectedEnd == ExpectedPaginationEnd::EmptyPage) { + EXPECT_TRUE(sawEmptyTerminator) + << "expected a trailing empty page after the last full page's cursor"; + } else { + EXPECT_FALSE(sawEmptyTerminator) + << "did not expect a trailing empty pagination page"; + } + + // No duplicates. + std::set const seenSet(seen.begin(), seen.end()); + EXPECT_EQ(seen.size(), seenSet.size()) << "pagination returned duplicate rows"; + // No gaps: union equals the full expected set. + EXPECT_EQ(seenSet, expected) << "pagination dropped or repeated rows"; + EXPECT_EQ(seen.size(), expected.size()); + expectSeenInOrder(seen, forward, expected); + }; + + // Case A: total not a multiple of the limit (25 rows, limit 10 -> 10,10,5). + { + auto const expected = setup(mptIssuanceId, 25, baseSeq + 1); + pageThrough(mptIssuanceId, false, 10, expected, ExpectedPaginationEnd::PartialPage); + pageThrough(mptIssuanceId, true, 10, expected, ExpectedPaginationEnd::PartialPage); + } + + // Case B: total is an exact multiple of the limit (20 rows, limit 10). + // The last full page still returns a cursor, so the next fetch must return an empty page + // and end the loop -- no infinite loop and no spurious trailing duplicate. + { + // Use a dedicated issuance id so rows from case A do not bleed in. + xrpl::uint192 mptIssuanceIdB; + EXPECT_TRUE( + mptIssuanceIdB.parseHex("00000002BE223A7216F1B07AE9C36F107879B6E9D3A3C1B0") + ); + // Continue the ledger sequence contiguously after case A (which ended at + // baseSeq + 25); the backend's finishWrites enforces contiguous ledgers. + auto const expectedB = setup(mptIssuanceIdB, 20, baseSeq + 26); + + pageThrough(mptIssuanceIdB, false, 10, expectedB, ExpectedPaginationEnd::EmptyPage); + pageThrough(mptIssuanceIdB, true, 10, expectedB, ExpectedPaginationEnd::EmptyPage); + } + }); +} + +TEST_F(BackendCassandraMPTokenIssuanceTest, MissingBlobYieldsInPositionEmptyRecord) +{ + runSpawn([this](boost::asio::yield_context yield) { + auto const mptIssuanceId = makeMptIssuanceId(); + std::uint32_t const seq = 400; + setupLedgerRange(seq); + + // hash 1 and 3 have a Transactions row; hash 2 does NOT (missing blob). + auto const h1 = makeHash(1); + auto const h2 = makeHash(2); + auto const h3 = makeHash(3); + writeTxBlob(h1, seq); + writeTxBlob(h3, seq); + + backend_->writeMPTokenIssuanceTransactions({MPTokenIssuanceTransactionsData{ + .mptIssuanceID = mptIssuanceId, + .accounts = {}, + .ledgerSequence = seq, + .transactionIndex = 1, + .txHash = h1 + }}); + backend_->writeMPTokenIssuanceTransactions({MPTokenIssuanceTransactionsData{ + .mptIssuanceID = mptIssuanceId, + .accounts = {}, + .ledgerSequence = seq, + .transactionIndex = 2, + .txHash = h2 + }}); + backend_->writeMPTokenIssuanceTransactions({MPTokenIssuanceTransactionsData{ + .mptIssuanceID = mptIssuanceId, + .accounts = {}, + .ledgerSequence = seq, + .transactionIndex = 3, + .txHash = h3 + }}); + backend_->waitForWritesToFinish(); + + auto [txns, cursor] = + backend_->fetchMPTokenIssuanceTransactions(mptIssuanceId, 100, false, {}, yield); + // The page is NOT shortened: the missing blob yields an in-position empty record. + ASSERT_EQ(txns.size(), 3); + EXPECT_FALSE(cursor); + + // Reverse order is newest-first: index 3, 2, 1. Middle entry (index 2) is empty. + EXPECT_EQ(txns[1], data::TransactionAndMetadata{}); + EXPECT_NE(txns[0], data::TransactionAndMetadata{}); + EXPECT_NE(txns[2], data::TransactionAndMetadata{}); + }); +} + struct BackendCassandraNodeMessageTest : BackendCassandraTest { - boost::uuids::random_generator generateUuid{}; + static boost::uuids::uuid + generateUuid() + { + return boost::uuids::random_generator{}(); + } }; TEST_F(BackendCassandraNodeMessageTest, UpdateFetch) { - static boost::uuids::uuid const kUUID = generateUuid(); - static std::string const kMESSAGE = "some message"; + static boost::uuids::uuid const kUuid = generateUuid(); + static std::string const kMessage = "some message"; - EXPECT_NO_THROW({ backend_->writeNodeMessage(kUUID, kMESSAGE); }); + EXPECT_NO_THROW({ backend_->writeNodeMessage(kUuid, kMessage); }); runSpawn([&](boost::asio::yield_context yield) { auto const readResult = backend_->fetchClioNodesData(yield); ASSERT_TRUE(readResult) << readResult.error(); ASSERT_EQ(readResult->size(), 1); auto const& [uuid, message] = (*readResult)[0]; - EXPECT_EQ(uuid, kUUID); - EXPECT_EQ(message, kMESSAGE); + EXPECT_EQ(uuid, kUuid); + EXPECT_EQ(message, kMessage); }); } TEST_F(BackendCassandraNodeMessageTest, UpdateFetchMultipleMessages) { - std::unordered_map kDATA = { + std::unordered_map kData = { {generateUuid(), std::string{"some message"}}, {generateUuid(), std::string{"other message"}}, {generateUuid(), std::string{"message 3"}} }; EXPECT_NO_THROW({ - for (auto const& [uuid, message] : kDATA) { + for (auto const& [uuid, message] : kData) { backend_->writeNodeMessage(uuid, message); } }); @@ -1503,12 +1896,12 @@ TEST_F(BackendCassandraNodeMessageTest, UpdateFetchMultipleMessages) runSpawn([&](boost::asio::yield_context yield) { auto const readResult = backend_->fetchClioNodesData(yield); ASSERT_TRUE(readResult) << readResult.error(); - ASSERT_EQ(readResult->size(), kDATA.size()); + ASSERT_EQ(readResult->size(), kData.size()); for (size_t i = 0; i < readResult->size(); ++i) { auto const& [uuid, message] = (*readResult)[i]; - auto const it = kDATA.find(uuid); - ASSERT_NE(it, kDATA.end()) << uuid << " not found"; + auto const it = kData.find(uuid); + ASSERT_NE(it, kData.end()) << uuid << " not found"; EXPECT_EQ(it->second, message); } }); @@ -1531,13 +1924,13 @@ TEST_F(BackendCassandraNodeMessageTest, UpdatingMessageKeepsItAlive) #if defined(__APPLE__) GTEST_SKIP() << "Skipping test on Apple platform due to slow DB"; #else - static boost::uuids::uuid const kUUID = generateUuid(); - static std::string const kUPDATED_MESSAGE = "updated message"; + static boost::uuids::uuid const kUuid = generateUuid(); + static std::string const kUpdatedMessage = "updated message"; - EXPECT_NO_THROW({ backend_->writeNodeMessage(kUUID, "some message"); }); + EXPECT_NO_THROW({ backend_->writeNodeMessage(kUuid, "some message"); }); std::this_thread::sleep_for(std::chrono::milliseconds{1000}); - EXPECT_NO_THROW({ backend_->writeNodeMessage(kUUID, kUPDATED_MESSAGE); }); + EXPECT_NO_THROW({ backend_->writeNodeMessage(kUuid, kUpdatedMessage); }); std::this_thread::sleep_for(std::chrono::milliseconds{1005}); runSpawn([&](boost::asio::yield_context yield) { @@ -1545,8 +1938,8 @@ TEST_F(BackendCassandraNodeMessageTest, UpdatingMessageKeepsItAlive) ASSERT_TRUE(readResult) << readResult.error(); ASSERT_EQ(readResult->size(), 1); auto const& [uuid, message] = (*readResult)[0]; - EXPECT_EQ(uuid, kUUID); - EXPECT_EQ(message, kUPDATED_MESSAGE); + EXPECT_EQ(uuid, kUuid); + EXPECT_EQ(message, kUpdatedMessage); }); #endif } diff --git a/tests/integration/migration/cassandra/CassandraMigrationManagerTests.cpp b/tests/integration/migration/cassandra/CassandraMigrationManagerTests.cpp index ecf46fb73..9aa8ad5f3 100644 --- a/tests/integration/migration/cassandra/CassandraMigrationManagerTests.cpp +++ b/tests/integration/migration/cassandra/CassandraMigrationManagerTests.cpp @@ -81,15 +81,15 @@ class MigrationCassandraSimpleTest : public WithPrometheus { } protected: - static constexpr auto kCASSANDRA = "cassandra"; + static constexpr auto kCassandra = "cassandra"; ClioConfigDefinition cfg_{ - {{"database.type", ConfigValue{ConfigType::String}.defaultValue(kCASSANDRA)}, + {{"database.type", ConfigValue{ConfigType::String}.defaultValue(kCassandra)}, {"database.cassandra.contact_points", ConfigValue{ConfigType::String}.defaultValue(TestGlobals::instance().backendHost)}, {"database.cassandra.keyspace", ConfigValue{ConfigType::String}.defaultValue(TestGlobals::instance().backendKeyspace)}, - {"database.cassandra.provider", ConfigValue{ConfigType::String}.defaultValue(kCASSANDRA)}, + {"database.cassandra.provider", ConfigValue{ConfigType::String}.defaultValue(kCassandra)}, {"database.cassandra.replication_factor", ConfigValue{ConfigType::Integer}.defaultValue(1)}, {"database.cassandra.replication_factor", @@ -214,14 +214,14 @@ class MigrationCassandraManagerTxTableTest : public MigrationCassandraSimpleTest TEST_F(MigrationCassandraManagerTxTableTest, MigrateExampleTransactionsMigrator) { - constexpr auto kTRANSACTIONS_MIGRATOR_NAME = "ExampleTransactionsMigrator"; + constexpr auto kTransactionsMigratorName = "ExampleTransactionsMigrator"; EXPECT_EQ( - testMigrationManager_->getMigratorStatusByName(kTRANSACTIONS_MIGRATOR_NAME), + testMigrationManager_->getMigratorStatusByName(kTransactionsMigratorName), MigratorStatus::Status::NotMigrated ); ExampleTransactionsMigrator::count = 0; - testMigrationManager_->runMigration(kTRANSACTIONS_MIGRATOR_NAME); + testMigrationManager_->runMigration(kTransactionsMigratorName); EXPECT_EQ(ExampleTransactionsMigrator::count, gTransactionsRawData.size()); auto const newTableSize = data::synchronous([&](auto ctx) { @@ -232,35 +232,35 @@ TEST_F(MigrationCassandraManagerTxTableTest, MigrateExampleTransactionsMigrator) EXPECT_EQ(newTableSize, gTransactionsRawData.size()); // check a few tx types - auto const getTxType = [&](ripple::uint256 const& txHash) -> std::optional { + auto const getTxType = [&](xrpl::uint256 const& txHash) -> std::optional { return data::synchronous([&](auto ctx) { return testMigrationBackend_->fetchTxTypeViaID(uint256ToString(txHash), ctx); }); }; auto txType = getTxType( - ripple::uint256("CEECF7E516F8A53C5D32A357B737ED54D3186FDD510B1973D908AD8D93AD8E00") + xrpl::uint256("CEECF7E516F8A53C5D32A357B737ED54D3186FDD510B1973D908AD8D93AD8E00") ); ASSERT_TRUE(txType.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(txType.value(), "OracleSet"); txType = getTxType( - ripple::uint256("35DBFB1A88DE17EBD2BCE37F6E1FD6D3B9887C92B7933ED2FCF2A84E9138B7CA") + xrpl::uint256("35DBFB1A88DE17EBD2BCE37F6E1FD6D3B9887C92B7933ED2FCF2A84E9138B7CA") ); ASSERT_TRUE(txType.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(txType.value(), "Payment"); txType = getTxType( - ripple::uint256("FCACE9D00625FA3BCC5316078324EA153EC8551243AC1701D496CC1CA2B8A474") + xrpl::uint256("FCACE9D00625FA3BCC5316078324EA153EC8551243AC1701D496CC1CA2B8A474") ); ASSERT_TRUE(txType.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(txType.value(), "AMMCreate"); EXPECT_EQ( - testMigrationManager_->getMigratorStatusByName(kTRANSACTIONS_MIGRATOR_NAME), + testMigrationManager_->getMigratorStatusByName(kTransactionsMigratorName), MigratorStatus::Status::Migrated ); } @@ -281,19 +281,19 @@ class MigrationCassandraManagerObjectsTableTest : public MigrationCassandraSimpl TEST_F(MigrationCassandraManagerObjectsTableTest, MigrateExampleObjectsMigrator) { - constexpr auto kOBJECTS_MIGRATOR_NAME = "ExampleObjectsMigrator"; + constexpr auto kObjectsMigratorName = "ExampleObjectsMigrator"; EXPECT_EQ( - testMigrationManager_->getMigratorStatusByName(kOBJECTS_MIGRATOR_NAME), + testMigrationManager_->getMigratorStatusByName(kObjectsMigratorName), MigratorStatus::Status::NotMigrated ); - testMigrationManager_->runMigration(kOBJECTS_MIGRATOR_NAME); + testMigrationManager_->runMigration(kObjectsMigratorName); EXPECT_EQ(ExampleObjectsMigrator::count, gObjectsRawData.size()); EXPECT_EQ(ExampleObjectsMigrator::accountCount, 37); EXPECT_EQ( - testMigrationManager_->getMigratorStatusByName(kOBJECTS_MIGRATOR_NAME), + testMigrationManager_->getMigratorStatusByName(kObjectsMigratorName), MigratorStatus::Status::Migrated ); } @@ -315,15 +315,15 @@ class MigrationCassandraManagerLedgerTableTest : public MigrationCassandraSimple TEST_F(MigrationCassandraManagerLedgerTableTest, MigrateExampleLedgerMigrator) { - constexpr auto kHEADER_MIGRATOR_NAME = "ExampleLedgerMigrator"; + constexpr auto kHeaderMigratorName = "ExampleLedgerMigrator"; EXPECT_EQ( - testMigrationManager_->getMigratorStatusByName(kHEADER_MIGRATOR_NAME), + testMigrationManager_->getMigratorStatusByName(kHeaderMigratorName), MigratorStatus::Status::NotMigrated ); - testMigrationManager_->runMigration(kHEADER_MIGRATOR_NAME); + testMigrationManager_->runMigration(kHeaderMigratorName); EXPECT_EQ( - testMigrationManager_->getMigratorStatusByName(kHEADER_MIGRATOR_NAME), + testMigrationManager_->getMigratorStatusByName(kHeaderMigratorName), MigratorStatus::Status::Migrated ); @@ -340,15 +340,15 @@ TEST_F(MigrationCassandraManagerLedgerTableTest, MigrateExampleLedgerMigrator) EXPECT_EQ( getAccountHash(5619393), - ripple::uint256("D1DE0F83A6858DF52811E31FE97B8449A4DD55A7D9E0023FE5DC2B335E4C49E8") + xrpl::uint256("D1DE0F83A6858DF52811E31FE97B8449A4DD55A7D9E0023FE5DC2B335E4C49E8") ); EXPECT_EQ( getAccountHash(5619394), - ripple::uint256("3FEF485204772F03842AA8757B4631E8F146E17AD9762E0552540A517DD38A24") + xrpl::uint256("3FEF485204772F03842AA8757B4631E8F146E17AD9762E0552540A517DD38A24") ); EXPECT_EQ( getAccountHash(5619395), - ripple::uint256("D0A61C158AD8941868666AD51C4662EEAAA2A141BF0F4435BC22B9BC6783AF65") + xrpl::uint256("D0A61C158AD8941868666AD51C4662EEAAA2A141BF0F4435BC22B9BC6783AF65") ); } @@ -357,9 +357,9 @@ class MigrationCassandraManagerDropTableTest : public MigrationCassandraSimpleTe TEST_F(MigrationCassandraManagerDropTableTest, MigrateDropTableMigrator) { - constexpr auto kDROP_TABLE_MIGRATOR_NAME = "ExampleDropTableMigrator"; + constexpr auto kDropTableMigratorName = "ExampleDropTableMigrator"; EXPECT_EQ( - testMigrationManager_->getMigratorStatusByName(kDROP_TABLE_MIGRATOR_NAME), + testMigrationManager_->getMigratorStatusByName(kDropTableMigratorName), MigratorStatus::Status::NotMigrated ); @@ -367,9 +367,9 @@ TEST_F(MigrationCassandraManagerDropTableTest, MigrateDropTableMigrator) data::synchronous([&](auto ctx) { return testMigrationBackend_->fetchDiffTableSize(ctx); }); EXPECT_EQ(beforeDropSize, 0); - testMigrationManager_->runMigration(kDROP_TABLE_MIGRATOR_NAME); + testMigrationManager_->runMigration(kDropTableMigratorName); EXPECT_EQ( - testMigrationManager_->getMigratorStatusByName(kDROP_TABLE_MIGRATOR_NAME), + testMigrationManager_->getMigratorStatusByName(kDropTableMigratorName), MigratorStatus::Status::Migrated ); diff --git a/tests/integration/migration/cassandra/CassandraMigrationTestBackend.hpp b/tests/integration/migration/cassandra/CassandraMigrationTestBackend.hpp index 3f353846c..6f24334a7 100644 --- a/tests/integration/migration/cassandra/CassandraMigrationTestBackend.hpp +++ b/tests/integration/migration/cassandra/CassandraMigrationTestBackend.hpp @@ -57,7 +57,7 @@ public: void writeTxIndexExample(std::string const& hash, std::string const& txType) { - static auto kINSERT_TX_INDEX_EXAMPLE = [this]() { + static auto kInsertTxIndexExample = [this]() { return handle_.prepare( fmt::format( R"( @@ -69,7 +69,7 @@ public: ) ); }(); - executor_.writeSync(kINSERT_TX_INDEX_EXAMPLE.bind(hash, data::cassandra::Text(txType))); + executor_.writeSync(kInsertTxIndexExample.bind(hash, data::cassandra::Text(txType))); } /** @@ -83,7 +83,7 @@ public: std::optional fetchTxTypeViaID(std::string const& hash, boost::asio::yield_context ctx) { - static auto kFETCH_TX_TYPE = [this]() { + static auto kFetchTxType = [this]() { return handle_.prepare( fmt::format( R"( @@ -93,7 +93,7 @@ public: ) ); }(); - auto const res = executor_.read(ctx, kFETCH_TX_TYPE.bind(hash)); + auto const res = executor_.read(ctx, kFetchTxType.bind(hash)); if (not res) { return std::nullopt; } @@ -119,7 +119,7 @@ public: std::optional fetchTxIndexTableSize(boost::asio::yield_context ctx) { - static auto kINSERT_TX_INDEX_EXAMPLE = [this]() { + static auto kInsertTxIndexExample = [this]() { return handle_.prepare( fmt::format( R"( @@ -132,7 +132,7 @@ public: // This function will be called after table being dropped, catch the exception try { - auto const res = executor_.read(ctx, kINSERT_TX_INDEX_EXAMPLE); + auto const res = executor_.read(ctx, kInsertTxIndexExample); if (not res) { return std::nullopt; } @@ -161,7 +161,7 @@ public: void writeLedgerAccountHash(std::uint64_t sequence, std::string const& accountHash) { - static auto kINSERT_LEDGER_EXAMPLE = [this]() { + static auto kInsertLedgerExample = [this]() { return handle_.prepare( fmt::format( R"( @@ -173,7 +173,7 @@ public: ) ); }(); - executor_.writeSync(kINSERT_LEDGER_EXAMPLE.bind(sequence, accountHash)); + executor_.writeSync(kInsertLedgerExample.bind(sequence, accountHash)); } /** @@ -184,10 +184,10 @@ public: * @param ctx The boost asio context * @return The account hash if found, otherwise std::nullopt */ - std::optional + std::optional fetchAccountHashViaSequence(std::uint64_t sequence, boost::asio::yield_context ctx) { - static auto kFETCH_ACCOUNT_HASH = [this]() { + static auto kFetchAccountHash = [this]() { return handle_.prepare( fmt::format( R"( @@ -197,7 +197,7 @@ public: ) ); }(); - auto const res = executor_.read(ctx, kFETCH_ACCOUNT_HASH.bind(sequence)); + auto const res = executor_.read(ctx, kFetchAccountHash.bind(sequence)); if (not res) { return std::nullopt; } @@ -207,7 +207,7 @@ public: return std::nullopt; } - for (auto const& [accountHash] : data::cassandra::extract(result)) { + for (auto const& [accountHash] : data::cassandra::extract(result)) { return accountHash; } return std::nullopt; @@ -222,7 +222,7 @@ public: std::optional fetchLedgerTableSize(boost::asio::yield_context ctx) { - static auto kINSERT_LEDGER_EXAMPLE = [this]() { + static auto kInsertLedgerExample = [this]() { return handle_.prepare( fmt::format( R"( @@ -235,7 +235,7 @@ public: // This function will be called after table being dropped, catch the exception try { - auto const res = executor_.read(ctx, kINSERT_LEDGER_EXAMPLE); + auto const res = executor_.read(ctx, kInsertLedgerExample); if (not res) { return std::nullopt; } @@ -281,7 +281,7 @@ public: std::optional fetchDiffTableSize(boost::asio::yield_context ctx) { - static auto kCOUNT_DIFF = [this]() { + static auto kCountDiff = [this]() { return handle_.prepare( fmt::format( R"( @@ -294,7 +294,7 @@ public: // This function will be called after table being dropped, catch the exception try { - auto const res = executor_.read(ctx, kCOUNT_DIFF); + auto const res = executor_.read(ctx, kCountDiff); if (not res) { return std::nullopt; } diff --git a/tests/integration/migration/cassandra/ExampleDropTableMigrator.hpp b/tests/integration/migration/cassandra/ExampleDropTableMigrator.hpp index 671a5fd77..0bc550daf 100644 --- a/tests/integration/migration/cassandra/ExampleDropTableMigrator.hpp +++ b/tests/integration/migration/cassandra/ExampleDropTableMigrator.hpp @@ -12,8 +12,8 @@ struct ExampleDropTableMigrator { using Backend = CassandraMigrationTestBackend; - static constexpr char const* kNAME = "ExampleDropTableMigrator"; - static constexpr char const* kDESCRIPTION = "The migrator for dropping the table"; + static constexpr char const* kName = "ExampleDropTableMigrator"; + static constexpr char const* kDescription = "The migrator for dropping the table"; static void runMigration(std::shared_ptr const& backend, util::config::ObjectView const& config); diff --git a/tests/integration/migration/cassandra/ExampleLedgerMigrator.hpp b/tests/integration/migration/cassandra/ExampleLedgerMigrator.hpp index 5f736ce94..3651bed1d 100644 --- a/tests/integration/migration/cassandra/ExampleLedgerMigrator.hpp +++ b/tests/integration/migration/cassandra/ExampleLedgerMigrator.hpp @@ -12,8 +12,8 @@ * key of ledgers table, we can just fetch the data via ledger sequence without full table scan. */ struct ExampleLedgerMigrator { - static constexpr char const* kNAME = "ExampleLedgerMigrator"; - static constexpr char const* kDESCRIPTION = "The migrator for ledgers table"; + static constexpr char const* kName = "ExampleLedgerMigrator"; + static constexpr char const* kDescription = "The migrator for ledgers table"; using Backend = CassandraMigrationTestBackend; diff --git a/tests/integration/migration/cassandra/ExampleObjectsMigrator.cpp b/tests/integration/migration/cassandra/ExampleObjectsMigrator.cpp index ca459bce1..d568d75ce 100644 --- a/tests/integration/migration/cassandra/ExampleObjectsMigrator.cpp +++ b/tests/integration/migration/cassandra/ExampleObjectsMigrator.cpp @@ -27,15 +27,15 @@ ExampleObjectsMigrator::runMigration( auto const jobsFullScan = config.get("full_scan_jobs"); auto const cursorPerJobsFullScan = config.get("cursors_per_job"); - std::unordered_set idx; + std::unordered_set idx; migration::cassandra::impl::ObjectsScanner scanner( {.ctxThreadsNum = ctxFullScanThreads, .jobsNum = jobsFullScan, .cursorsPerJob = cursorPerJobsFullScan}, migration::cassandra::impl::ObjectsAdapter( - backend, [&](std::uint32_t, std::optional sle) { + backend, [&](std::uint32_t, std::optional sle) { if (sle.has_value()) { - if (sle->getType() == ripple::ltACCOUNT_ROOT) { + if (sle->getType() == xrpl::ltACCOUNT_ROOT) { if (!idx.contains(sle->key())) { ExampleObjectsMigrator::accountCount++; } diff --git a/tests/integration/migration/cassandra/ExampleObjectsMigrator.hpp b/tests/integration/migration/cassandra/ExampleObjectsMigrator.hpp index f7e280d50..1232ec12b 100644 --- a/tests/integration/migration/cassandra/ExampleObjectsMigrator.hpp +++ b/tests/integration/migration/cassandra/ExampleObjectsMigrator.hpp @@ -16,8 +16,8 @@ struct ExampleObjectsMigrator { using Backend = CassandraMigrationTestBackend; - static constexpr char const* kNAME = "ExampleObjectsMigrator"; - static constexpr char const* kDESCRIPTION = "The migrator for objects table"; + static constexpr char const* kName = "ExampleObjectsMigrator"; + static constexpr char const* kDescription = "The migrator for objects table"; static std::atomic_int64_t count; static std::atomic_int64_t accountCount; diff --git a/tests/integration/migration/cassandra/ExampleTransactionsMigrator.cpp b/tests/integration/migration/cassandra/ExampleTransactionsMigrator.cpp index dd280516b..7401ae5ee 100644 --- a/tests/integration/migration/cassandra/ExampleTransactionsMigrator.cpp +++ b/tests/integration/migration/cassandra/ExampleTransactionsMigrator.cpp @@ -35,9 +35,9 @@ ExampleTransactionsMigrator::runMigration( .jobsNum = jobsFullScan, .cursorsPerJob = cursorPerJobsFullScan}, migration::cassandra::impl::TransactionsAdapter( - backend, [&](ripple::STTx const& tx, ripple::TxMeta const&) { - hashSet.lock()->insert(ripple::to_string(tx.getTransactionID())); - auto const json = tx.getJson(ripple::JsonOptions::none); + backend, [&](xrpl::STTx const& tx, xrpl::TxMeta const&) { + hashSet.lock()->insert(xrpl::to_string(tx.getTransactionID())); + auto const json = tx.getJson(xrpl::JsonOptions::Values::None); auto const txType = json["TransactionType"].asString(); backend->writeTxIndexExample(uint256ToString(tx.getTransactionID()), txType); } diff --git a/tests/integration/migration/cassandra/ExampleTransactionsMigrator.hpp b/tests/integration/migration/cassandra/ExampleTransactionsMigrator.hpp index 999b67cd8..a627e0d6d 100644 --- a/tests/integration/migration/cassandra/ExampleTransactionsMigrator.hpp +++ b/tests/integration/migration/cassandra/ExampleTransactionsMigrator.hpp @@ -12,8 +12,8 @@ * hash to transaction type string. */ struct ExampleTransactionsMigrator { - static constexpr char const* kNAME = "ExampleTransactionsMigrator"; - static constexpr char const* kDESCRIPTION = "The migrator for transactions table"; + static constexpr char const* kName = "ExampleTransactionsMigrator"; + static constexpr char const* kDescription = "The migrator for transactions table"; using Backend = CassandraMigrationTestBackend; static std::uint64_t count; diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index df88b91b9..a5a35a406 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -48,6 +48,7 @@ target_sources( etl/LoadBalancerTests.cpp etl/LoadingTests.cpp etl/MonitorTests.cpp + etl/MPTHelpersTests.cpp etl/NetworkValidatedLedgersTests.cpp etl/NFTHelpersTests.cpp etl/RegistryTests.cpp @@ -239,6 +240,8 @@ set_target_properties( PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} ) +patch_nix_binary(clio_tests) + # Generate `coverage_report` target if coverage is enabled if(coverage) if(DEFINED CODE_COVERAGE_REPORT_FORMAT) diff --git a/tests/unit/JsonUtilTests.cpp b/tests/unit/JsonUtilTests.cpp index 956460129..b809e3fd9 100644 --- a/tests/unit/JsonUtilTests.cpp +++ b/tests/unit/JsonUtilTests.cpp @@ -179,7 +179,7 @@ INSTANTIATE_TEST_CASE_P( .expectedResult = std::unexpected{"'validated' ledger index is requested"} } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(GetLedgerIndexParameterTest, getLedgerIndexParams) diff --git a/tests/unit/app/CliArgsTests.cpp b/tests/unit/app/CliArgsTests.cpp index 0d46396a8..77b617e60 100644 --- a/tests/unit/app/CliArgsTests.cpp +++ b/tests/unit/app/CliArgsTests.cpp @@ -30,7 +30,7 @@ TEST_F(CliArgsTests, Parse_NoArgs) int const returnCode = 123; EXPECT_CALL(onRunMock, Call).WillOnce([](CliArgs::Action::Run const& run) { - EXPECT_EQ(run.configPath, CliArgs::kDEFAULT_CONFIG_PATH); + EXPECT_EQ(run.configPath, CliArgs::kDefaultConfigPath); EXPECT_FALSE(run.useNgWebServer); return returnCode; }); @@ -53,7 +53,7 @@ TEST_F(CliArgsTests, Parse_NgWebServer) int const returnCode = 123; EXPECT_CALL(onRunMock, Call).WillOnce([](CliArgs::Action::Run const& run) { - EXPECT_EQ(run.configPath, CliArgs::kDEFAULT_CONFIG_PATH); + EXPECT_EQ(run.configPath, CliArgs::kDefaultConfigPath); EXPECT_TRUE(run.useNgWebServer); return returnCode; }); @@ -209,14 +209,11 @@ TEST_F(CliArgsTestsWithTmpFile, Parse_ConfigDescriptionFileContent) inFile.close(); auto const fileContent = buffer.str(); - EXPECT_TRUE(fileContent.find("# Clio Config Description") != std::string::npos); - EXPECT_TRUE( - fileContent.find( - "This document provides a list of all available Clio configuration properties in " - "detail." - ) != std::string::npos - ); - EXPECT_TRUE(fileContent.find("## Configuration Details") != std::string::npos); + EXPECT_TRUE(fileContent.contains("# Clio Config Description")); + EXPECT_TRUE(fileContent.contains( + "This document provides a list of all available Clio configuration properties in detail." + )); + EXPECT_TRUE(fileContent.contains("## Configuration Details")); // all keys that exist in clio config should be listed in config description file for (auto const& key : getClioConfig()) diff --git a/tests/unit/app/VerifyConfigTests.cpp b/tests/unit/app/VerifyConfigTests.cpp index 6ce55c7bc..638f0278c 100644 --- a/tests/unit/app/VerifyConfigTests.cpp +++ b/tests/unit/app/VerifyConfigTests.cpp @@ -9,22 +9,22 @@ using namespace util::config; TEST(VerifyConfigTest, InvalidConfig) { - auto const tmpConfigFile = TmpFile(kJSON_DATA); + auto const tmpConfigFile = TmpFile(kJsonData); - // false because json data(kJSON_DATA) is not compatible with current configDefinition + // false because json data(kJsonData) is not compatible with current configDefinition EXPECT_FALSE(parseConfig(tmpConfigFile.path)); } TEST(VerifyConfigTest, ValidConfig) { // used to Verify Config test - static constexpr auto kVALID_JSON_DATA = R"JSON({ + static constexpr auto kValidJsonData = R"JSON({ "server": { "ip": "0.0.0.0", "port": 51233 } })JSON"; - auto const tmpConfigFile = TmpFile(kVALID_JSON_DATA); + auto const tmpConfigFile = TmpFile(kValidJsonData); // current example config should always be compatible with configDefinition EXPECT_TRUE(parseConfig(tmpConfigFile.path)); @@ -38,13 +38,13 @@ TEST(VerifyConfigTest, ConfigFileNotExist) TEST(VerifyConfigTest, InvalidJsonFile) { // invalid json because extra "," after 51233 - static constexpr auto kINVALID_JSON = R"JSON({ + static constexpr auto kInvalidJson = R"JSON({ "server": { "ip": "0.0.0.0", "port": 51233, } })JSON"; - auto const tmpConfigFile = TmpFile(kINVALID_JSON); + auto const tmpConfigFile = TmpFile(kInvalidJson); EXPECT_FALSE(parseConfig(tmpConfigFile.path)); } diff --git a/tests/unit/app/WebHandlersTests.cpp b/tests/unit/app/WebHandlersTests.cpp index 34149cbad..cf86f38f4 100644 --- a/tests/unit/app/WebHandlersTests.cpp +++ b/tests/unit/app/WebHandlersTests.cpp @@ -20,7 +20,6 @@ #include #include #include -#include #include #include #include @@ -212,7 +211,7 @@ TEST_F(RequestHandlerTest, RpcHandlerThrows) auto const body = boost::json::parse(httpResponse.body()).as_object(); EXPECT_EQ(body.at("error").as_string(), "internal"); - EXPECT_EQ(body.at("error_code").as_int64(), rpc::RippledError::rpcINTERNAL); + EXPECT_EQ(body.at("error_code").as_int64(), rpc::RippledError::RpcInternal); EXPECT_EQ(body.at("status").as_string(), "error"); }); } diff --git a/tests/unit/cluster/ClioNodeTests.cpp b/tests/unit/cluster/ClioNodeTests.cpp index c380c2dff..43e735298 100644 --- a/tests/unit/cluster/ClioNodeTests.cpp +++ b/tests/unit/cluster/ClioNodeTests.cpp @@ -15,7 +15,6 @@ #include #include -#include #include #include #include @@ -26,7 +25,7 @@ struct ClioNodeTest : testing::Test { std::string const updateTimeStr = "2015-05-15T12:00:00Z"; std::chrono::system_clock::time_point const updateTime = // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - *util::systemTpFromUtcStr(updateTimeStr, ClioNode::kTIME_FORMAT); + *util::systemTpFromUtcStr(updateTimeStr, ClioNode::kTimeFormat); }; TEST_F(ClioNodeTest, Serialization) @@ -205,7 +204,7 @@ INSTANTIATE_TEST_SUITE_P( .role = ClioNode::DbRole::FallbackRecovery } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(ClioNodeDbRoleTest, Serialization) @@ -317,7 +316,7 @@ INSTANTIATE_TEST_SUITE_P( .expectedRole = ClioNode::DbRole::FallbackRecovery } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(ClioNodeFromTest, FromWriterState) diff --git a/tests/unit/cluster/ClusterCommunicationServiceTests.cpp b/tests/unit/cluster/ClusterCommunicationServiceTests.cpp index b5e263f3b..e49d47ab1 100644 --- a/tests/unit/cluster/ClusterCommunicationServiceTests.cpp +++ b/tests/unit/cluster/ClusterCommunicationServiceTests.cpp @@ -38,7 +38,7 @@ struct ClusterCommunicationServiceTest : util::prometheus::WithPrometheus, MockB std::unique_ptr cacheLoadingState = std::make_unique(); - static constexpr std::chrono::milliseconds kSHORT_INTERVAL{1}; + static constexpr std::chrono::milliseconds kShortInterval{1}; static boost::uuids::uuid makeUuid(uint8_t value) @@ -118,8 +118,8 @@ TEST_F(ClusterCommunicationServiceTest, BackendReadsAndWritesData) backend_, std::move(writerState), std::move(cacheLoadingState), - kSHORT_INTERVAL, - kSHORT_INTERVAL + kShortInterval, + kShortInterval }; service.run(); @@ -163,8 +163,8 @@ TEST_F(ClusterCommunicationServiceTest, MetricsGetsNewStateFromBackend) backend_, std::move(writerState), std::move(cacheLoadingState), - kSHORT_INTERVAL, - kSHORT_INTERVAL + kShortInterval, + kShortInterval }; service.run(); @@ -212,8 +212,8 @@ TEST_F(ClusterCommunicationServiceTest, WriterDeciderCallsWriterStateMethodsAcco backend_, std::move(writerState), std::move(cacheLoadingState), - kSHORT_INTERVAL, - kSHORT_INTERVAL + kShortInterval, + kShortInterval }; service.run(); @@ -246,8 +246,8 @@ TEST_F(ClusterCommunicationServiceTest, StopHaltsBackendOperations) backend_, std::move(writerState), std::move(cacheLoadingState), - kSHORT_INTERVAL, - kSHORT_INTERVAL + kShortInterval, + kShortInterval }; service.run(); @@ -284,7 +284,7 @@ INSTANTIATE_TEST_SUITE_P( .limitLoadInCluster = false } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(ClusterCommunicationServiceMakeTest, LoadingAllowedMatchesConfig) diff --git a/tests/unit/cluster/RepeatedTaskTests.cpp b/tests/unit/cluster/RepeatedTaskTests.cpp index 4fb4929e5..823b256c9 100644 --- a/tests/unit/cluster/RepeatedTaskTests.cpp +++ b/tests/unit/cluster/RepeatedTaskTests.cpp @@ -16,7 +16,7 @@ using namespace cluster::impl; using namespace testing; struct RepeatedTaskTest : AsyncAsioContextTest { - static constexpr auto kTIMEOUT = std::chrono::seconds{5}; + static constexpr auto kTimeout = std::chrono::seconds{5}; }; template @@ -57,7 +57,7 @@ TYPED_TEST(RepeatedTaskTypedTest, CallsFunctionRepeatedly) task.run(this->mockFn.AsStdFunction()); - EXPECT_TRUE(this->semaphore.try_acquire_for(TestFixture::kTIMEOUT)); + EXPECT_TRUE(this->semaphore.try_acquire_for(TestFixture::kTimeout)); task.stop(); } @@ -84,7 +84,7 @@ TYPED_TEST(RepeatedTaskTypedTest, MultipleStops) task.run(this->mockFn.AsStdFunction()); - EXPECT_TRUE(this->semaphore.try_acquire_for(TestFixture::kTIMEOUT)); + EXPECT_TRUE(this->semaphore.try_acquire_for(TestFixture::kTimeout)); task.stop(); task.stop(); @@ -100,7 +100,7 @@ TYPED_TEST(RepeatedTaskTypedTest, DestructorStopsTask) task.run(this->mockFn.AsStdFunction()); - EXPECT_TRUE(this->semaphore.try_acquire_for(TestFixture::kTIMEOUT)); + EXPECT_TRUE(this->semaphore.try_acquire_for(TestFixture::kTimeout)); // Destructor will call stop() } @@ -149,8 +149,8 @@ TEST_F(RepeatedTaskTest, MultipleTasksRunConcurrently) task1.run(mockFn1.AsStdFunction()); task2.run(mockFn2.AsStdFunction()); - EXPECT_TRUE(semaphore1.try_acquire_for(kTIMEOUT)); - EXPECT_TRUE(semaphore2.try_acquire_for(kTIMEOUT)); + EXPECT_TRUE(semaphore1.try_acquire_for(kTimeout)); + EXPECT_TRUE(semaphore2.try_acquire_for(kTimeout)); task1.stop(); task2.stop(); @@ -166,7 +166,7 @@ TYPED_TEST(RepeatedTaskTypedTest, TaskStateTransitionsCorrectly) task.run(this->mockFn.AsStdFunction()); - EXPECT_TRUE(this->semaphore.try_acquire_for(TestFixture::kTIMEOUT)); + EXPECT_TRUE(this->semaphore.try_acquire_for(TestFixture::kTimeout)); task.stop(); @@ -200,7 +200,7 @@ TEST_F(RepeatedTaskTest, FunctionCanAccessYieldContext) task.run(mockFn.AsStdFunction()); - EXPECT_TRUE(semaphore.try_acquire_for(kTIMEOUT)); + EXPECT_TRUE(semaphore.try_acquire_for(kTimeout)); task.stop(); diff --git a/tests/unit/data/AmendmentCenterTests.cpp b/tests/unit/data/AmendmentCenterTests.cpp index 5dd1265a0..93faf11b6 100644 --- a/tests/unit/data/AmendmentCenterTests.cpp +++ b/tests/unit/data/AmendmentCenterTests.cpp @@ -20,7 +20,7 @@ using namespace data; -constexpr auto kSEQ = 30u; +constexpr auto kSeq = 30u; struct AmendmentCenterTest : util::prometheus::WithPrometheus, MockBackendTest, @@ -32,14 +32,14 @@ struct AmendmentCenterTest : util::prometheus::WithPrometheus, // some Amendment that we forgot to register in data::Amendments. TEST_F(AmendmentCenterTest, AllAmendmentsFromLibXRPLAreSupported) { - for (auto const& [name, _] : ripple::allAmendments()) { + for (auto const& [name, _] : xrpl::allAmendments()) { EXPECT_TRUE(amendmentCenter.isSupported(name)) << "XRPL amendment not supported by Clio: " << name; } // We support at least all the amendments currently exposed by libXRPL - ASSERT_GE(amendmentCenter.getSupported().size(), ripple::allAmendments().size()); - ASSERT_GE(amendmentCenter.getAll().size(), ripple::allAmendments().size()); + ASSERT_GE(amendmentCenter.getSupported().size(), xrpl::allAmendments().size()); + ASSERT_GE(amendmentCenter.getAll().size(), xrpl::allAmendments().size()); } TEST_F(AmendmentCenterTest, Accessors) @@ -48,14 +48,14 @@ TEST_F(AmendmentCenterTest, Accessors) auto const am = amendmentCenter.getAmendment("DisallowIncoming"); EXPECT_EQ( am.feature, - ripple::uint256("47C3002ABA31628447E8E9A8B315FAA935CE30183F9A9B86845E469CA2CDC3DF") + xrpl::uint256("47C3002ABA31628447E8E9A8B315FAA935CE30183F9A9B86845E469CA2CDC3DF") ); } { auto const am = amendmentCenter["DisallowIncoming"]; EXPECT_EQ( am.feature, - ripple::uint256("47C3002ABA31628447E8E9A8B315FAA935CE30183F9A9B86845E469CA2CDC3DF") + xrpl::uint256("47C3002ABA31628447E8E9A8B315FAA935CE30183F9A9B86845E469CA2CDC3DF") ); } @@ -70,25 +70,25 @@ TEST_F(AmendmentCenterTest, IsEnabled) EXPECT_FALSE(amendmentCenter.isSupported("unknown")); auto const amendments = createAmendmentsObject({Amendments::fixUniversalNumber}); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::keylet::amendments().key, kSEQ, testing::_)) + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::amendments().key, kSeq, testing::_)) .WillRepeatedly(testing::Return(amendments.getSerializer().peekData())); - EXPECT_TRUE(amendmentCenter.isEnabled("fixUniversalNumber", kSEQ)); - EXPECT_FALSE(amendmentCenter.isEnabled("unknown", kSEQ)); - EXPECT_FALSE(amendmentCenter.isEnabled("ImmediateOfferKilled", kSEQ)); + EXPECT_TRUE(amendmentCenter.isEnabled("fixUniversalNumber", kSeq)); + EXPECT_FALSE(amendmentCenter.isEnabled("unknown", kSeq)); + EXPECT_FALSE(amendmentCenter.isEnabled("ImmediateOfferKilled", kSeq)); } TEST_F(AmendmentCenterTest, IsMultipleEnabled) { auto const amendments = createAmendmentsObject({Amendments::fixUniversalNumber}); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::keylet::amendments().key, kSEQ, testing::_)) + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::amendments().key, kSeq, testing::_)) .WillOnce(testing::Return(amendments.getSerializer().peekData())); runSpawn([this](auto yield) { std::vector const keys{ "fixUniversalNumber", "unknown", "ImmediateOfferKilled" }; - auto const result = amendmentCenter.isEnabled(yield, keys, kSEQ); + auto const result = amendmentCenter.isEnabled(yield, keys, kSeq); EXPECT_EQ(result.size(), keys.size()); EXPECT_TRUE(result.at(0)); @@ -99,34 +99,34 @@ TEST_F(AmendmentCenterTest, IsMultipleEnabled) TEST_F(AmendmentCenterTest, IsEnabledReturnsFalseWhenAmendmentsLedgerObjectUnavailable) { - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::keylet::amendments().key, kSEQ, testing::_)) + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::amendments().key, kSeq, testing::_)) .WillOnce(testing::Return(std::nullopt)); runSpawn([this](auto yield) { - EXPECT_NO_THROW(EXPECT_FALSE(amendmentCenter.isEnabled(yield, "irrelevant", kSEQ))); + EXPECT_NO_THROW(EXPECT_FALSE(amendmentCenter.isEnabled(yield, "irrelevant", kSeq))); }); } TEST_F(AmendmentCenterTest, IsEnabledReturnsFalseWhenNoAmendments) { auto const amendments = createBrokenAmendmentsObject(); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::keylet::amendments().key, kSEQ, testing::_)) + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::amendments().key, kSeq, testing::_)) .WillOnce(testing::Return(amendments.getSerializer().peekData())); runSpawn([this](auto yield) { - EXPECT_FALSE(amendmentCenter.isEnabled(yield, "irrelevant", kSEQ)); + EXPECT_FALSE(amendmentCenter.isEnabled(yield, "irrelevant", kSeq)); }); } TEST_F(AmendmentCenterTest, IsEnabledReturnsVectorOfFalseWhenAmendmentsLedgerObjectUnavailable) { - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::keylet::amendments().key, kSEQ, testing::_)) + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::amendments().key, kSeq, testing::_)) .WillOnce(testing::Return(std::nullopt)); runSpawn([this](auto yield) { std::vector const keys{"fixUniversalNumber", "ImmediateOfferKilled"}; std::vector vec; - EXPECT_NO_THROW(vec = amendmentCenter.isEnabled(yield, keys, kSEQ)); + EXPECT_NO_THROW(vec = amendmentCenter.isEnabled(yield, keys, kSeq)); EXPECT_EQ(vec.size(), keys.size()); EXPECT_TRUE(std::ranges::all_of(vec, std::logical_not<>{})); @@ -136,12 +136,12 @@ TEST_F(AmendmentCenterTest, IsEnabledReturnsVectorOfFalseWhenAmendmentsLedgerObj TEST_F(AmendmentCenterTest, IsEnabledReturnsVectorOfFalseWhenNoAmendments) { auto const amendments = createBrokenAmendmentsObject(); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::keylet::amendments().key, kSEQ, testing::_)) + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::amendments().key, kSeq, testing::_)) .WillOnce(testing::Return(amendments.getSerializer().peekData())); runSpawn([this](auto yield) { std::vector const keys{"fixUniversalNumber", "ImmediateOfferKilled"}; - auto const vec = amendmentCenter.isEnabled(yield, keys, kSEQ); + auto const vec = amendmentCenter.isEnabled(yield, keys, kSeq); EXPECT_EQ(vec.size(), keys.size()); EXPECT_TRUE(std::ranges::all_of(vec, [](bool val) { return val == false; })); @@ -151,7 +151,7 @@ TEST_F(AmendmentCenterTest, IsEnabledReturnsVectorOfFalseWhenNoAmendments) TEST_F(AmendmentCenterTest, DeletedLibXRPLAmendmentIsNotKnownToLibXRPL) { // OwnerPaysFee was removed from libXRPL in 2.6.0; confirm it's not present upstream - EXPECT_FALSE(ripple::allAmendments().contains(std::string{Amendments::OwnerPaysFee})); + EXPECT_FALSE(xrpl::allAmendments().contains(std::string{Amendments::OwnerPaysFee})); } TEST_F(AmendmentCenterTest, DeletedLibXRPLAmendmentIsPresentInGetAllWithCorrectFlags) @@ -178,7 +178,7 @@ TEST(AmendmentTest, GenerateAmendmentId) { // https://xrpl.org/known-amendments.html#disallowincoming refer to the published id EXPECT_EQ( - ripple::uint256("47C3002ABA31628447E8E9A8B315FAA935CE30183F9A9B86845E469CA2CDC3DF"), + xrpl::uint256("47C3002ABA31628447E8E9A8B315FAA935CE30183F9A9B86845E469CA2CDC3DF"), Amendment::getAmendmentId("DisallowIncoming") ); } @@ -208,14 +208,14 @@ TEST_F(AmendmentKeyTest, Convertible) std::string const s1 = first; EXPECT_EQ(s1, key1); - ripple::uint256 const k1 = first; - ripple::uint256 const k2 = second; + xrpl::uint256 const k1 = first; + xrpl::uint256 const k2 = second; EXPECT_EQ( - k1, ripple::uint256{"7E365F775657DC0EB960E6295A1F44B3F67479F54D5D12C5D87E6DB234F072E3"} + k1, xrpl::uint256{"7E365F775657DC0EB960E6295A1F44B3F67479F54D5D12C5D87E6DB234F072E3"} ); EXPECT_EQ( - k2, ripple::uint256{"B4F33541E0E2FC2F7AA17D2D2E6A9B424809123485251D3413E91CC462309772"} + k2, xrpl::uint256{"B4F33541E0E2FC2F7AA17D2D2E6A9B424809123485251D3413E91CC462309772"} ); }); } diff --git a/tests/unit/data/BackendCountersTests.cpp b/tests/unit/data/BackendCountersTests.cpp index 789a6538b..c8baa7c87 100644 --- a/tests/unit/data/BackendCountersTests.cpp +++ b/tests/unit/data/BackendCountersTests.cpp @@ -136,15 +136,15 @@ TEST_F(BackendCountersTest, RegisterReadFinished) TEST_F(BackendCountersTest, RegisterReadStartedFinishedWithCounters) { - static constexpr auto kOPERATIONS_STARTED = 7u; - static constexpr auto kOPERATIONS_COMPLETED = 4u; + static constexpr auto kOperationsStarted = 7u; + static constexpr auto kOperationsCompleted = 4u; - counters->registerReadStarted(kOPERATIONS_STARTED); - counters->registerReadFinished(startTime, kOPERATIONS_COMPLETED); + counters->registerReadStarted(kOperationsStarted); + counters->registerReadFinished(startTime, kOperationsCompleted); auto expectedReport = emptyReport(); - expectedReport["read_async_pending"] = kOPERATIONS_STARTED - kOPERATIONS_COMPLETED; - expectedReport["read_async_completed"] = kOPERATIONS_COMPLETED; + expectedReport["read_async_pending"] = kOperationsStarted - kOperationsCompleted; + expectedReport["read_async_completed"] = kOperationsCompleted; EXPECT_EQ(counters->report(), expectedReport); } @@ -160,19 +160,19 @@ TEST_F(BackendCountersTest, RegisterReadRetry) TEST_F(BackendCountersTest, RegisterReadError) { - static constexpr auto kOPERATIONS_STARTED = 7u; - static constexpr auto kOPERATIONS_ERROR = 2u; - static constexpr auto kOPERATIONS_COMPLETED = 1u; + static constexpr auto kOperationsStarted = 7u; + static constexpr auto kOperationsError = 2u; + static constexpr auto kOperationsCompleted = 1u; - counters->registerReadStarted(kOPERATIONS_STARTED); - counters->registerReadError(kOPERATIONS_ERROR); - counters->registerReadFinished(startTime, kOPERATIONS_COMPLETED); + counters->registerReadStarted(kOperationsStarted); + counters->registerReadError(kOperationsError); + counters->registerReadFinished(startTime, kOperationsCompleted); auto expectedReport = emptyReport(); expectedReport["read_async_pending"] = - kOPERATIONS_STARTED - kOPERATIONS_COMPLETED - kOPERATIONS_ERROR; - expectedReport["read_async_completed"] = kOPERATIONS_COMPLETED; - expectedReport["read_async_error"] = kOPERATIONS_ERROR; + kOperationsStarted - kOperationsCompleted - kOperationsError; + expectedReport["read_async_completed"] = kOperationsCompleted; + expectedReport["read_async_error"] = kOperationsError; EXPECT_EQ(counters->report(), expectedReport); } diff --git a/tests/unit/data/BackendInterfaceTests.cpp b/tests/unit/data/BackendInterfaceTests.cpp index 9d5d25031..19e3267a6 100644 --- a/tests/unit/data/BackendInterfaceTests.cpp +++ b/tests/unit/data/BackendInterfaceTests.cpp @@ -21,28 +21,28 @@ using namespace testing; namespace { -constexpr auto kMAX_SEQ = 30; -constexpr auto kMIN_SEQ = 10; +constexpr auto kMaxSeq = 30; +constexpr auto kMinSeq = 10; } // namespace struct BackendInterfaceTest : WithPrometheus, MockBackendTestNaggy, SyncAsioContextTest { BackendInterfaceTest() { - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); } }; TEST_F(BackendInterfaceTest, FetchFeesSuccessPath) { - using namespace ripple; + using namespace xrpl; // New fee setting (after XRPFees amendment) - EXPECT_CALL(*backend_, doFetchLedgerObject(keylet::fees().key, kMAX_SEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(keylet::feeSettings().key, kMaxSeq, _)) .WillRepeatedly(Return(createFeeSettingBlob(XRPAmount(1), XRPAmount(2), XRPAmount(3), 0))); runSpawn([this](auto yield) { - auto fees = backend_->fetchFees(kMAX_SEQ, yield); + auto fees = backend_->fetchFees(kMaxSeq, yield); EXPECT_TRUE(fees.has_value()); EXPECT_EQ(fees->base, XRPAmount(1)); @@ -53,14 +53,14 @@ TEST_F(BackendInterfaceTest, FetchFeesSuccessPath) TEST_F(BackendInterfaceTest, FetchFeesLegacySuccessPath) { - using namespace ripple; + using namespace xrpl; // Legacy fee setting (before XRPFees amendment) - EXPECT_CALL(*backend_, doFetchLedgerObject(keylet::fees().key, kMAX_SEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(keylet::feeSettings().key, kMaxSeq, _)) .WillRepeatedly(Return(createLegacyFeeSettingBlob(1, 2, 3, 4, 0))); runSpawn([this](auto yield) { - auto fees = backend_->fetchFees(kMAX_SEQ, yield); + auto fees = backend_->fetchFees(kMaxSeq, yield); EXPECT_TRUE(fees.has_value()); EXPECT_EQ(fees->base, XRPAmount(1)); @@ -71,7 +71,7 @@ TEST_F(BackendInterfaceTest, FetchFeesLegacySuccessPath) TEST_F(BackendInterfaceTest, FetchLedgerPageSuccessPath) { - using namespace ripple; + using namespace xrpl; auto state = etl::SystemState{}; backend_->setCorruptionDetector(etl::CorruptionDetector{state, backend_->cache()}); @@ -86,14 +86,14 @@ TEST_F(BackendInterfaceTest, FetchLedgerPageSuccessPath) .WillOnce(Return(std::vector(10, Blob{'s'}))); runSpawn([this](auto yield) { - backend_->fetchLedgerPage(std::nullopt, kMAX_SEQ, 10, false, yield); + backend_->fetchLedgerPage(std::nullopt, kMaxSeq, 10, false, yield); }); EXPECT_FALSE(backend_->cache().isDisabled()); } TEST_F(BackendInterfaceTest, FetchLedgerPageDisablesCacheOnMissingData) { - using namespace ripple; + using namespace xrpl; auto state = etl::SystemState{}; backend_->setCorruptionDetector(etl::CorruptionDetector{state, backend_->cache()}); @@ -121,7 +121,7 @@ TEST_F(BackendInterfaceTest, FetchLedgerPageDisablesCacheOnMissingData) )); runSpawn([this](auto yield) { - backend_->fetchLedgerPage(std::nullopt, kMAX_SEQ, 10, false, yield); + backend_->fetchLedgerPage(std::nullopt, kMaxSeq, 10, false, yield); }); EXPECT_TRUE(backend_->cache().isDisabled()); } @@ -131,7 +131,7 @@ TEST_F( FetchLedgerPageWithoutCorruptionDetectorDoesNotDisableCacheOnMissingData ) { - using namespace ripple; + using namespace xrpl; EXPECT_FALSE(backend_->cache().isDisabled()); EXPECT_CALL(*backend_, doFetchSuccessorKey(_, _, _)) @@ -156,7 +156,7 @@ TEST_F( )); runSpawn([this](auto yield) { - backend_->fetchLedgerPage(std::nullopt, kMAX_SEQ, 10, false, yield); + backend_->fetchLedgerPage(std::nullopt, kMaxSeq, 10, false, yield); }); EXPECT_FALSE(backend_->cache().isDisabled()); } diff --git a/tests/unit/data/LedgerCacheSaverTests.cpp b/tests/unit/data/LedgerCacheSaverTests.cpp index 3811de020..c6fd4c83c 100644 --- a/tests/unit/data/LedgerCacheSaverTests.cpp +++ b/tests/unit/data/LedgerCacheSaverTests.cpp @@ -25,7 +25,7 @@ using namespace util::config; struct LedgerCacheSaverTest : virtual testing::Test { testing::StrictMock cache; - constexpr static auto kFILE_PATH = "./cache.bin"; + constexpr static auto kFilePath = "./cache.bin"; static ClioConfigDefinition generateConfig(bool cacheFilePathHasValue, bool asyncSave) @@ -41,7 +41,7 @@ struct LedgerCacheSaverTest : virtual testing::Test { boost::json::parse( fmt::format( R"JSON({{"cache": {{"file": {{"path": "{}", "async_save": {} }} }} }})JSON", - kFILE_PATH, + kFilePath, asyncSave ) ) @@ -59,7 +59,7 @@ TEST_F(LedgerCacheSaverTest, SaveSuccessfully) auto const config = generateConfig(/* cacheFilePathHasValue = */ true, /* asyncSave = */ true); LedgerCacheSaver saver{config, cache}; - EXPECT_CALL(cache, saveToFile(kFILE_PATH)) + EXPECT_CALL(cache, saveToFile(kFilePath)) .WillOnce(testing::Return(std::expected{})); saver.save(); @@ -71,7 +71,7 @@ TEST_F(LedgerCacheSaverTest, SaveWithError) auto const config = generateConfig(/* cacheFilePathHasValue = */ true, /* asyncSave = */ true); LedgerCacheSaver saver{config, cache}; - EXPECT_CALL(cache, saveToFile(kFILE_PATH)) + EXPECT_CALL(cache, saveToFile(kFilePath)) .WillOnce( testing::Return(std::expected(std::unexpected("Failed to save"))) ); @@ -96,7 +96,7 @@ TEST_F(LedgerCacheSaverTest, DestructorWaitsForCompletion) std::binary_semaphore semaphore{1}; std::atomic_bool saveCompleted{false}; - EXPECT_CALL(cache, saveToFile(kFILE_PATH)).WillOnce([&]() { + EXPECT_CALL(cache, saveToFile(kFilePath)).WillOnce([&]() { semaphore.release(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); saveCompleted = true; @@ -117,7 +117,7 @@ TEST_F(LedgerCacheSaverTest, WaitToFinishCanBeCalledMultipleTimes) auto const config = generateConfig(/* cacheFilePathHasValue = */ true, /* asyncSave = */ true); LedgerCacheSaver saver{config, cache}; - EXPECT_CALL(cache, saveToFile(kFILE_PATH)); + EXPECT_CALL(cache, saveToFile(kFilePath)); saver.save(); saver.waitToFinish(); @@ -140,7 +140,7 @@ TEST_F(LedgerCacheSaverAssertTest, MultipleSavesNotAllowed) LedgerCacheSaver saver{config, cache}; std::binary_semaphore semaphore{0}; - EXPECT_CALL(cache, saveToFile(kFILE_PATH)).WillOnce([&](auto&&) { + EXPECT_CALL(cache, saveToFile(kFilePath)).WillOnce([&](auto&&) { semaphore.acquire(); return std::expected{}; }); @@ -157,7 +157,7 @@ TEST_F(LedgerCacheSaverTest, SyncSaveWaitsForCompletion) std::atomic_bool saveCompleted{false}; - EXPECT_CALL(cache, saveToFile(kFILE_PATH)).WillOnce([&]() { + EXPECT_CALL(cache, saveToFile(kFilePath)).WillOnce([&]() { std::this_thread::sleep_for(std::chrono::milliseconds(50)); saveCompleted = true; return std::expected{}; @@ -176,7 +176,7 @@ TEST_F(LedgerCacheSaverTest, AsyncSaveDoesNotWaitForCompletion) std::binary_semaphore continueExecution{0}; std::atomic_bool saveCompleted{false}; - EXPECT_CALL(cache, saveToFile(kFILE_PATH)).WillOnce([&]() { + EXPECT_CALL(cache, saveToFile(kFilePath)).WillOnce([&]() { saveStarted.release(); continueExecution.acquire(); saveCompleted = true; diff --git a/tests/unit/data/LedgerCacheTests.cpp b/tests/unit/data/LedgerCacheTests.cpp index 6a93b9ac6..db660b174 100644 --- a/tests/unit/data/LedgerCacheTests.cpp +++ b/tests/unit/data/LedgerCacheTests.cpp @@ -84,8 +84,8 @@ TEST_F(LedgerCachePrometheusMetricTest, startLoading) } struct LedgerCacheSaveLoadTest : LedgerCacheTest { - ripple::uint256 const key1{1}; - ripple::uint256 const key2{2}; + xrpl::uint256 const key1{1}; + xrpl::uint256 const key2{2}; std::vector const objs{ etl::model::Object{ .key = key1, @@ -106,7 +106,7 @@ struct LedgerCacheSaveLoadTest : LedgerCacheTest { .type = {} } }; - uint32_t const kLEDGER_SEQ = 100; + uint32_t const kLedgerSeq = 100; }; TEST_F(LedgerCacheSaveLoadTest, saveToFileFailsWhenCacheNotFull) @@ -120,18 +120,18 @@ TEST_F(LedgerCacheSaveLoadTest, saveToFileFailsWhenCacheNotFull) TEST_F(LedgerCacheSaveLoadTest, saveAndLoadFromFile) { - cache.update(objs, kLEDGER_SEQ); + cache.update(objs, kLedgerSeq); cache.setFull(); ASSERT_TRUE(cache.isFull()); EXPECT_EQ(cache.size(), 2u); - EXPECT_EQ(cache.latestLedgerSequence(), kLEDGER_SEQ); + EXPECT_EQ(cache.latestLedgerSequence(), kLedgerSeq); - auto const blob1 = cache.get(key1, kLEDGER_SEQ); + auto const blob1 = cache.get(key1, kLedgerSeq); ASSERT_TRUE(blob1.has_value()); EXPECT_EQ(blob1.value(), objs.front().data); // NOLINT(bugprone-unchecked-optional-access) - auto const blob2 = cache.get(key2, kLEDGER_SEQ); + auto const blob2 = cache.get(key2, kLedgerSeq); ASSERT_TRUE(blob2.has_value()); EXPECT_EQ(blob2.value(), objs.back().data); // NOLINT(bugprone-unchecked-optional-access) @@ -145,13 +145,13 @@ TEST_F(LedgerCacheSaveLoadTest, saveAndLoadFromFile) EXPECT_TRUE(newCache.isFull()); EXPECT_EQ(newCache.size(), 2u); - EXPECT_EQ(newCache.latestLedgerSequence(), kLEDGER_SEQ); + EXPECT_EQ(newCache.latestLedgerSequence(), kLedgerSeq); - auto const loadedBlob1 = newCache.get(key1, kLEDGER_SEQ); + auto const loadedBlob1 = newCache.get(key1, kLedgerSeq); ASSERT_TRUE(loadedBlob1.has_value()); EXPECT_EQ(loadedBlob1.value(), blob1); // NOLINT(bugprone-unchecked-optional-access) - auto const loadedBlob2 = newCache.get(key2, kLEDGER_SEQ); + auto const loadedBlob2 = newCache.get(key2, kLedgerSeq); ASSERT_TRUE(loadedBlob2.has_value()); EXPECT_EQ(loadedBlob2.value(), blob2); // NOLINT(bugprone-unchecked-optional-access) @@ -160,23 +160,23 @@ TEST_F(LedgerCacheSaveLoadTest, saveAndLoadFromFile) TEST_F(LedgerCacheSaveLoadTest, saveAndLoadFromFileWithDeletedObjects) { - cache.update(objs, kLEDGER_SEQ - 1); + cache.update(objs, kLedgerSeq - 1); auto objsCopy = objs; objsCopy.front().data = {}; - cache.update(objsCopy, kLEDGER_SEQ); + cache.update(objsCopy, kLedgerSeq); cache.setFull(); // Verify deleted object is accessible via getDeleted - auto const blob1 = cache.get(key1, kLEDGER_SEQ); + auto const blob1 = cache.get(key1, kLedgerSeq); ASSERT_FALSE(blob1.has_value()); - auto const blob2 = cache.get(key2, kLEDGER_SEQ); + auto const blob2 = cache.get(key2, kLedgerSeq); ASSERT_TRUE(blob2.has_value()); EXPECT_EQ(blob2.value(), objs.back().data); // NOLINT(bugprone-unchecked-optional-access) - auto const deletedBlob = cache.getDeleted(key1, kLEDGER_SEQ - 1); + auto const deletedBlob = cache.getDeleted(key1, kLedgerSeq - 1); ASSERT_TRUE(deletedBlob.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(deletedBlob.value(), objs.front().data); @@ -191,16 +191,16 @@ TEST_F(LedgerCacheSaveLoadTest, saveAndLoadFromFileWithDeletedObjects) ASSERT_TRUE(loadResult.has_value()) << "Load failed: " << loadResult.error(); // Verify deleted object is preserved - auto const loadedDeletedBlob = newCache.getDeleted(key1, kLEDGER_SEQ - 1); + auto const loadedDeletedBlob = newCache.getDeleted(key1, kLedgerSeq - 1); ASSERT_TRUE(loadedDeletedBlob.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(loadedDeletedBlob.value(), deletedBlob); // Verify active object - auto const loadedBlob1 = newCache.get(key1, kLEDGER_SEQ); + auto const loadedBlob1 = newCache.get(key1, kLedgerSeq); ASSERT_FALSE(loadedBlob1.has_value()); - auto const loadedBlob2 = newCache.get(key2, kLEDGER_SEQ); + auto const loadedBlob2 = newCache.get(key2, kLedgerSeq); ASSERT_TRUE(loadedBlob2.has_value()); EXPECT_EQ(loadedBlob2.value(), blob2); // NOLINT(bugprone-unchecked-optional-access) diff --git a/tests/unit/data/cassandra/ExecutionStrategyTests.cpp b/tests/unit/data/cassandra/ExecutionStrategyTests.cpp index 8707cae13..7a8efc633 100644 --- a/tests/unit/data/cassandra/ExecutionStrategyTests.cpp +++ b/tests/unit/data/cassandra/ExecutionStrategyTests.cpp @@ -84,7 +84,7 @@ protected: MockHandle handle_{}; MockBackendCounters::PtrType counters_ = MockBackendCounters::make(); - static constexpr auto kNUM_STATEMENTS = 3u; + static constexpr auto kNumStatements = 3u; DefaultExecutionStrategy makeStrategy(Settings s = {}) @@ -197,7 +197,7 @@ TEST_F(BackendCassandraExecutionStrategyTest, ReadBatchInCoroutineSuccessful) ) ) .WillByDefault([](auto const& statements, auto&& cb) { - EXPECT_EQ(statements.size(), kNUM_STATEMENTS); + EXPECT_EQ(statements.size(), kNumStatements); cb({}); // pretend we got data return FakeFutureWithCallback{}; }); @@ -208,11 +208,11 @@ TEST_F(BackendCassandraExecutionStrategyTest, ReadBatchInCoroutineSuccessful) ) ) .Times(1); - EXPECT_CALL(*counters_, registerReadStartedImpl(kNUM_STATEMENTS)); - EXPECT_CALL(*counters_, registerReadFinishedImpl(testing::_, kNUM_STATEMENTS)); + EXPECT_CALL(*counters_, registerReadStartedImpl(kNumStatements)); + EXPECT_CALL(*counters_, registerReadFinishedImpl(testing::_, kNumStatements)); runSpawn([&strat](boost::asio::yield_context yield) { - auto statements = std::vector(kNUM_STATEMENTS); + auto statements = std::vector(kNumStatements); strat.read(yield, statements); }); } @@ -228,7 +228,7 @@ TEST_F(BackendCassandraExecutionStrategyTest, ReadBatchInCoroutineThrowsOnTimeou ) ) .WillByDefault([](auto const& statements, auto&& cb) { - EXPECT_EQ(statements.size(), kNUM_STATEMENTS); + EXPECT_EQ(statements.size(), kNumStatements); auto res = FakeResultOrError{CassandraError{"timeout", CASS_ERROR_LIB_REQUEST_TIMED_OUT}}; cb(res); // notify that item is ready @@ -241,11 +241,11 @@ TEST_F(BackendCassandraExecutionStrategyTest, ReadBatchInCoroutineThrowsOnTimeou ) ) .Times(1); - EXPECT_CALL(*counters_, registerReadStartedImpl(kNUM_STATEMENTS)); - EXPECT_CALL(*counters_, registerReadErrorImpl(kNUM_STATEMENTS)); + EXPECT_CALL(*counters_, registerReadStartedImpl(kNumStatements)); + EXPECT_CALL(*counters_, registerReadErrorImpl(kNumStatements)); runSpawn([&strat](boost::asio::yield_context yield) { - auto statements = std::vector(kNUM_STATEMENTS); + auto statements = std::vector(kNumStatements); EXPECT_THROW(strat.read(yield, statements), data::DatabaseTimeout); }); } @@ -261,7 +261,7 @@ TEST_F(BackendCassandraExecutionStrategyTest, ReadBatchInCoroutineThrowsOnInvali ) ) .WillByDefault([](auto const& statements, auto&& cb) { - EXPECT_EQ(statements.size(), kNUM_STATEMENTS); + EXPECT_EQ(statements.size(), kNumStatements); auto res = FakeResultOrError{CassandraError{"invalid", CASS_ERROR_SERVER_INVALID_QUERY}}; cb(res); // notify that item is ready @@ -274,11 +274,11 @@ TEST_F(BackendCassandraExecutionStrategyTest, ReadBatchInCoroutineThrowsOnInvali ) ) .Times(1); - EXPECT_CALL(*counters_, registerReadStartedImpl(kNUM_STATEMENTS)); - EXPECT_CALL(*counters_, registerReadErrorImpl(kNUM_STATEMENTS)); + EXPECT_CALL(*counters_, registerReadStartedImpl(kNumStatements)); + EXPECT_CALL(*counters_, registerReadErrorImpl(kNumStatements)); runSpawn([&strat](boost::asio::yield_context yield) { - auto statements = std::vector(kNUM_STATEMENTS); + auto statements = std::vector(kNumStatements); EXPECT_THROW(strat.read(yield, statements), std::runtime_error); }); } @@ -297,7 +297,7 @@ TEST_F( ) ) .WillByDefault([this, &strat](auto const& statements, auto&& cb) { - EXPECT_EQ(statements.size(), kNUM_STATEMENTS); + EXPECT_EQ(statements.size(), kNumStatements); EXPECT_CALL(*counters_, registerTooBusy()); EXPECT_TRUE(strat.isTooBusy()); // 2 was the limit, we sent 3 @@ -311,12 +311,12 @@ TEST_F( ) ) .Times(1); - EXPECT_CALL(*counters_, registerReadStartedImpl(kNUM_STATEMENTS)); - EXPECT_CALL(*counters_, registerReadFinishedImpl(testing::_, kNUM_STATEMENTS)); + EXPECT_CALL(*counters_, registerReadStartedImpl(kNumStatements)); + EXPECT_CALL(*counters_, registerReadFinishedImpl(testing::_, kNumStatements)); runSpawn([&strat](boost::asio::yield_context yield) { EXPECT_FALSE(strat.isTooBusy()); // 2 was the limit, 0 atm - auto statements = std::vector(kNUM_STATEMENTS); + auto statements = std::vector(kNumStatements); strat.read(yield, statements); EXPECT_FALSE(strat.isTooBusy()); // after read completes it's 0 again }); @@ -341,12 +341,12 @@ TEST_F(BackendCassandraExecutionStrategyTest, ReadEachInCoroutineSuccessful) A&&>() ) ) - .Times(kNUM_STATEMENTS); // once per statement - EXPECT_CALL(*counters_, registerReadStartedImpl(kNUM_STATEMENTS)); - EXPECT_CALL(*counters_, registerReadFinishedImpl(testing::_, kNUM_STATEMENTS)); + .Times(kNumStatements); // once per statement + EXPECT_CALL(*counters_, registerReadStartedImpl(kNumStatements)); + EXPECT_CALL(*counters_, registerReadFinishedImpl(testing::_, kNumStatements)); runSpawn([&strat](boost::asio::yield_context yield) { - auto statements = std::vector(kNUM_STATEMENTS); + auto statements = std::vector(kNumStatements); auto res = strat.readEach(yield, statements); EXPECT_EQ(res.size(), statements.size()); }); @@ -377,13 +377,13 @@ TEST_F(BackendCassandraExecutionStrategyTest, ReadEachInCoroutineThrowsOnFailure A&&>() ) ) - .Times(kNUM_STATEMENTS); // once per statement - EXPECT_CALL(*counters_, registerReadStartedImpl(kNUM_STATEMENTS)); + .Times(kNumStatements); // once per statement + EXPECT_CALL(*counters_, registerReadStartedImpl(kNumStatements)); EXPECT_CALL(*counters_, registerReadErrorImpl(1)); EXPECT_CALL(*counters_, registerReadFinishedImpl(testing::_, 2)); runSpawn([&strat](boost::asio::yield_context yield) { - auto statements = std::vector(kNUM_STATEMENTS); + auto statements = std::vector(kNumStatements); EXPECT_THROW(strat.readEach(yield, statements), data::DatabaseTimeout); }); } @@ -472,7 +472,7 @@ TEST_F(BackendCassandraExecutionStrategyTest, StatsCallsCountersReport) { auto strat = makeStrategy(); EXPECT_CALL(*counters_, report()); - strat.stats(); + [[maybe_unused]] auto _ = strat.stats(); } TEST_F(BackendCassandraExecutionStrategyTest, WriteEachAndCallSyncSucceeds) diff --git a/tests/unit/data/cassandra/LedgerHeaderCacheTests.cpp b/tests/unit/data/cassandra/LedgerHeaderCacheTests.cpp index a381802e0..0834494dd 100644 --- a/tests/unit/data/cassandra/LedgerHeaderCacheTests.cpp +++ b/tests/unit/data/cassandra/LedgerHeaderCacheTests.cpp @@ -6,8 +6,8 @@ using namespace data; using Test = ::testing::Test; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constinit auto const kLEDGER_HASH2 = +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constinit auto const kLedgerHasH2 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; class FetchLedgerCacheTest : public Test { @@ -23,7 +23,7 @@ TEST_F(FetchLedgerCacheTest, DefaultCacheIsEmpty) TEST_F(FetchLedgerCacheTest, CanStoreAndRetrieveEntry) { - auto const ledger = createLedgerHeader(kLEDGER_HASH, 42); + auto const ledger = createLedgerHeader(kLedgerHash, 42); FetchLedgerCache::CacheEntry const entry{.ledger = ledger, .seq = 42}; cache_.put(entry); @@ -35,8 +35,8 @@ TEST_F(FetchLedgerCacheTest, CanStoreAndRetrieveEntry) TEST_F(FetchLedgerCacheTest, PutOverwritesPreviousEntry) { - auto const ledger1 = createLedgerHeader(kLEDGER_HASH, 1); - auto const ledger2 = createLedgerHeader(kLEDGER_HASH2, 2); + auto const ledger1 = createLedgerHeader(kLedgerHash, 1); + auto const ledger2 = createLedgerHeader(kLedgerHasH2, 2); FetchLedgerCache::CacheEntry const entry1{.ledger = ledger1, .seq = 1}; FetchLedgerCache::CacheEntry const entry2{.ledger = ledger2, .seq = 2}; diff --git a/tests/unit/data/cassandra/SettingsProviderTests.cpp b/tests/unit/data/cassandra/SettingsProviderTests.cpp index 0da165f6f..51919611b 100644 --- a/tests/unit/data/cassandra/SettingsProviderTests.cpp +++ b/tests/unit/data/cassandra/SettingsProviderTests.cpp @@ -21,7 +21,6 @@ using namespace util; using namespace util::config; using namespace std; -namespace json = boost::json; using namespace data::cassandra; @@ -67,7 +66,7 @@ class SettingsProviderTest : virtual public ::testing::Test {}; TEST_F(SettingsProviderTest, Defaults) { auto const cfg = getParseSettingsConfig( - json::parse(R"JSON({"database.cassandra.contact_points": "127.0.0.1"})JSON") + boost::json::parse(R"JSON({"database.cassandra.contact_points": "127.0.0.1"})JSON") ); SettingsProvider const provider{cfg.getObject("database.cassandra")}; @@ -97,7 +96,7 @@ TEST_F(SettingsProviderTest, Defaults) TEST_F(SettingsProviderTest, SimpleConfig) { - auto const cfg = getParseSettingsConfig(json::parse(R"JSON({ + auto const cfg = getParseSettingsConfig(boost::json::parse(R"JSON({ "database.cassandra.contact_points": "123.123.123.123", "database.cassandra.port": 1234, "database.cassandra.keyspace": "test", @@ -122,7 +121,7 @@ TEST_F(SettingsProviderTest, SimpleConfig) TEST_F(SettingsProviderTest, DriverOptionalOptionsSpecified) { - auto const cfg = getParseSettingsConfig(json::parse(R"JSON({ + auto const cfg = getParseSettingsConfig(boost::json::parse(R"JSON({ "database.cassandra.contact_points": "123.123.123.123", "database.cassandra.queue_size_io": 2 })JSON")); @@ -135,7 +134,7 @@ TEST_F(SettingsProviderTest, DriverOptionalOptionsSpecified) TEST_F(SettingsProviderTest, SecureBundleConfig) { auto const cfg = getParseSettingsConfig( - json::parse(R"JSON({"database.cassandra.secure_connect_bundle": "bundleData"})JSON") + boost::json::parse(R"JSON({"database.cassandra.secure_connect_bundle": "bundleData"})JSON") ); SettingsProvider const provider{cfg.getObject("database.cassandra")}; @@ -149,7 +148,7 @@ TEST_F(SettingsProviderTest, CertificateConfig) { TmpFile const file{"certificateData"}; auto const cfg = getParseSettingsConfig( - json::parse( + boost::json::parse( fmt::format( R"JSON({{ "database.cassandra.contact_points": "127.0.0.1", diff --git a/tests/unit/data/impl/LedgerCacheFileTests.cpp b/tests/unit/data/impl/LedgerCacheFileTests.cpp index 60f3b26b2..b0faaf053 100644 --- a/tests/unit/data/impl/LedgerCacheFileTests.cpp +++ b/tests/unit/data/impl/LedgerCacheFileTests.cpp @@ -129,21 +129,21 @@ struct LedgerCacheFileTestBase : ::testing::Test { std::filesystem::remove(pathWithNewPrefix); } - static std::vector const kDATA_SIZE_PARAMS; - static std::vector const kCORRUPTION_PARAMS; + static std::vector const kDataSizeParams; + static std::vector const kCorruptionParams; TmpFile tmpFile = TmpFile::empty(); - static uint32_t constexpr kLATEST_SEQUENCE = 12345; + static uint32_t constexpr kLatestSequence = 12345; static LedgerCacheFile::Data createTestData(size_t mapSize, size_t deletedSize, size_t blobSize) { LedgerCacheFile::Data data; - data.latestSeq = kLATEST_SEQUENCE; + data.latestSeq = kLatestSequence; for (size_t i = 0; i < mapSize; ++i) { - ripple::uint256 key; - std::memset(key.data(), static_cast(i), ripple::uint256::size()); + xrpl::uint256 key; + std::memset(key.data(), static_cast(i), xrpl::uint256::size()); data::LedgerCache::CacheEntry entry; entry.seq = static_cast(1000 + i); @@ -154,8 +154,8 @@ struct LedgerCacheFileTestBase : ::testing::Test { } for (size_t i = 0; i < deletedSize; ++i) { - ripple::uint256 key; - std::memset(key.data(), static_cast(i + 200), ripple::uint256::size()); + xrpl::uint256 key; + std::memset(key.data(), static_cast(i + 200), xrpl::uint256::size()); data::LedgerCache::CacheEntry entry; entry.seq = static_cast(2000 + i); @@ -307,7 +307,7 @@ struct LedgerCacheFileTestBase : ::testing::Test { }; std::vector< - LedgerCacheFileTestBase::DataSizeParams> const LedgerCacheFileTestBase::kDATA_SIZE_PARAMS = { + LedgerCacheFileTestBase::DataSizeParams> const LedgerCacheFileTestBase::kDataSizeParams = { {.mapEntries = 0, .deletedEntries = 0, .blobSize = 0, .description = "empty"}, {.mapEntries = 1, .deletedEntries = 0, .blobSize = 10, .description = "single_map_small_blob"}, {.mapEntries = 0, @@ -325,7 +325,7 @@ std::vector< }; std::vector const - LedgerCacheFileTestBase::kCORRUPTION_PARAMS = { + LedgerCacheFileTestBase::kCorruptionParams = { {.type = CorruptionType::InvalidVersion, .description = "invalid_version"}, {.type = CorruptionType::CorruptedSeparator1, .description = "corrupted_separator1"}, {.type = CorruptionType::CorruptedSeparator2, .description = "corrupted_separator2"}, @@ -357,7 +357,7 @@ struct LedgerCacheFileTest INSTANTIATE_TEST_SUITE_P( AllDataSizes, LedgerCacheFileTest, - ::testing::ValuesIn(LedgerCacheFileTestBase::kDATA_SIZE_PARAMS), + ::testing::ValuesIn(LedgerCacheFileTestBase::kDataSizeParams), LedgerCacheFileTest::roundTripParamName ); @@ -395,7 +395,7 @@ struct LedgerCacheFileCorruptionTest INSTANTIATE_TEST_SUITE_P( AllCorruptions, LedgerCacheFileCorruptionTest, - ::testing::ValuesIn(LedgerCacheFileTestBase::kCORRUPTION_PARAMS), + ::testing::ValuesIn(LedgerCacheFileTestBase::kCorruptionParams), LedgerCacheFileCorruptionTest::corruptionParamName ); @@ -535,16 +535,16 @@ TEST_F(LedgerCacheFileEdgeCaseTest, SpecialKeyPatterns) LedgerCacheFile::Data testData; testData.latestSeq = 100; - ripple::uint256 zeroKey; - std::memset(zeroKey.data(), 0, ripple::uint256::size()); + xrpl::uint256 zeroKey; + std::memset(zeroKey.data(), 0, xrpl::uint256::size()); testData.map.emplace(zeroKey, data::LedgerCache::CacheEntry{.seq = 1, .blob = {1, 2, 3}}); - ripple::uint256 onesKey; - std::memset(onesKey.data(), 0xFF, ripple::uint256::size()); + xrpl::uint256 onesKey; + std::memset(onesKey.data(), 0xFF, xrpl::uint256::size()); testData.map.emplace(onesKey, data::LedgerCache::CacheEntry{.seq = 2, .blob = {4, 5, 6}}); - ripple::uint256 altKey; - for (size_t i = 0; i < ripple::uint256::size(); ++i) { + xrpl::uint256 altKey; + for (size_t i = 0; i < xrpl::uint256::size(); ++i) { altKey.data()[i] = static_cast(((i % 2) != 0u) ? 0xAA : 0x55); } testData.deleted.emplace(altKey, data::LedgerCache::CacheEntry{.seq = 3, .blob = {7, 8, 9}}); @@ -583,10 +583,10 @@ TEST_F(LedgerCacheFileEdgeCaseTest, SequenceNumber) LedgerCacheFile::Data testData; testData.latestSeq = 0; - ripple::uint256 key1, key2, key3; - std::memset(key1.data(), 1, ripple::uint256::size()); - std::memset(key2.data(), 2, ripple::uint256::size()); - std::memset(key3.data(), 3, ripple::uint256::size()); + xrpl::uint256 key1, key2, key3; + std::memset(key1.data(), 1, xrpl::uint256::size()); + std::memset(key2.data(), 2, xrpl::uint256::size()); + std::memset(key3.data(), 3, xrpl::uint256::size()); testData.map.emplace(key1, data::LedgerCache::CacheEntry{.seq = 0, .blob = {1}}); testData.map.emplace( @@ -701,7 +701,7 @@ INSTANTIATE_TEST_SUITE_P( .testName = "accept_zero_sequence" } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(LedgerCacheFileMinSequenceValidationTest, ValidateMinSequence) diff --git a/tests/unit/etl/AmendmentBlockHandlerTests.cpp b/tests/unit/etl/AmendmentBlockHandlerTests.cpp index f5f0d3fb3..336dcf650 100644 --- a/tests/unit/etl/AmendmentBlockHandlerTests.cpp +++ b/tests/unit/etl/AmendmentBlockHandlerTests.cpp @@ -8,7 +8,6 @@ #include #include -#include #include using namespace etl::impl; @@ -23,7 +22,7 @@ protected: TEST_F(AmendmentBlockHandlerTests, CallToNotifyAmendmentBlockedSetsStateAndRepeatedlyCallsAction) { - static constexpr auto kMAX_ITERATIONS = 10uz; + static constexpr auto kMaxIterations = 10uz; etl::impl::AmendmentBlockHandler handler{ ctx_, state_, std::chrono::nanoseconds{1}, actionMock_.AsStdFunction() }; @@ -32,12 +31,12 @@ TEST_F(AmendmentBlockHandlerTests, CallToNotifyAmendmentBlockedSetsStateAndRepea EXPECT_FALSE(state_.isAmendmentBlocked); EXPECT_CALL(actionMock_, Call()).Times(testing::AtLeast(10)).WillRepeatedly([&]() { - if (++counter; counter > kMAX_ITERATIONS) + if (++counter; counter > kMaxIterations) stop.release(); }); handler.notifyAmendmentBlocked(); - stop.acquire(); // wait for the counter to reach over kMAX_ITERATIONS + stop.acquire(); // wait for the counter to reach over kMaxIterations handler.stop(); EXPECT_TRUE(state_.isAmendmentBlocked); @@ -47,7 +46,7 @@ struct DefaultAmendmentBlockActionTest : LoggerFixture {}; TEST_F(DefaultAmendmentBlockActionTest, Call) { - AmendmentBlockHandler::kDEFAULT_AMENDMENT_BLOCK_ACTION(); + AmendmentBlockHandler::kDefaultAmendmentBlockAction(); auto const loggerString = getLoggerString(); EXPECT_TRUE(loggerString.starts_with("cri:ETL - Can't process new ledgers")) << "LoggerString " << loggerString; diff --git a/tests/unit/etl/CacheLoaderSettingsTests.cpp b/tests/unit/etl/CacheLoaderSettingsTests.cpp index cef6243da..f370da47e 100644 --- a/tests/unit/etl/CacheLoaderSettingsTests.cpp +++ b/tests/unit/etl/CacheLoaderSettingsTests.cpp @@ -10,7 +10,6 @@ #include #include -namespace json = boost::json; using namespace etl; using namespace testing; using namespace util::config; @@ -54,7 +53,7 @@ TEST_F(CacheLoaderSettingsTest, DefaultSettingsParsedCorrectly) TEST_F(CacheLoaderSettingsTest, NumThreadsCorrectlyPropagatedThroughConfig) { - auto const cfg = getParseCacheConfig(json::parse(R"JSON({"io_threads": 42})JSON")); + auto const cfg = getParseCacheConfig(boost::json::parse(R"JSON({"io_threads": 42})JSON")); auto const settings = makeCacheLoaderSettings(cfg); EXPECT_EQ(settings.numThreads, 42); @@ -62,7 +61,8 @@ TEST_F(CacheLoaderSettingsTest, NumThreadsCorrectlyPropagatedThroughConfig) TEST_F(CacheLoaderSettingsTest, NumDiffsCorrectlyPropagatedThroughConfig) { - auto const cfg = getParseCacheConfig(json::parse(R"JSON({"cache": {"num_diffs": 42}})JSON")); + auto const cfg = + getParseCacheConfig(boost::json::parse(R"JSON({"cache": {"num_diffs": 42}})JSON")); auto const settings = makeCacheLoaderSettings(cfg); EXPECT_EQ(settings.numCacheDiffs, 42); @@ -70,7 +70,8 @@ TEST_F(CacheLoaderSettingsTest, NumDiffsCorrectlyPropagatedThroughConfig) TEST_F(CacheLoaderSettingsTest, NumMarkersCorrectlyPropagatedThroughConfig) { - auto const cfg = getParseCacheConfig(json::parse(R"JSON({"cache": {"num_markers": 42}})JSON")); + auto const cfg = + getParseCacheConfig(boost::json::parse(R"JSON({"cache": {"num_markers": 42}})JSON")); auto const settings = makeCacheLoaderSettings(cfg); EXPECT_EQ(settings.numCacheMarkers, 42); @@ -79,7 +80,7 @@ TEST_F(CacheLoaderSettingsTest, NumMarkersCorrectlyPropagatedThroughConfig) TEST_F(CacheLoaderSettingsTest, PageFetchSizeCorrectlyPropagatedThroughConfig) { auto const cfg = - getParseCacheConfig(json::parse(R"JSON({"cache": {"page_fetch_size": 42}})JSON")); + getParseCacheConfig(boost::json::parse(R"JSON({"cache": {"page_fetch_size": 42}})JSON")); auto const settings = makeCacheLoaderSettings(cfg); EXPECT_EQ(settings.cachePageFetchSize, 42); @@ -87,7 +88,8 @@ TEST_F(CacheLoaderSettingsTest, PageFetchSizeCorrectlyPropagatedThroughConfig) TEST_F(CacheLoaderSettingsTest, SyncLoadStyleCorrectlyPropagatedThroughConfig) { - auto const cfg = getParseCacheConfig(json::parse(R"JSON({"cache": {"load": "sYNC"}})JSON")); + auto const cfg = + getParseCacheConfig(boost::json::parse(R"JSON({"cache": {"load": "sYNC"}})JSON")); auto const settings = makeCacheLoaderSettings(cfg); EXPECT_EQ(settings.loadStyle, CacheLoaderSettings::LoadStyle::SYNC); @@ -96,7 +98,8 @@ TEST_F(CacheLoaderSettingsTest, SyncLoadStyleCorrectlyPropagatedThroughConfig) TEST_F(CacheLoaderSettingsTest, AsyncLoadStyleCorrectlyPropagatedThroughConfig) { - auto const cfg = getParseCacheConfig(json::parse(R"JSON({"cache": {"load": "aSynC"}})JSON")); + auto const cfg = + getParseCacheConfig(boost::json::parse(R"JSON({"cache": {"load": "aSynC"}})JSON")); auto const settings = makeCacheLoaderSettings(cfg); EXPECT_EQ(settings.loadStyle, CacheLoaderSettings::LoadStyle::ASYNC); @@ -106,14 +109,16 @@ TEST_F(CacheLoaderSettingsTest, AsyncLoadStyleCorrectlyPropagatedThroughConfig) TEST_F(CacheLoaderSettingsTest, NoLoadStyleCorrectlyPropagatedThroughConfig) { { - auto const cfg = getParseCacheConfig(json::parse(R"JSON({"cache": {"load": "nONe"}})JSON")); + auto const cfg = + getParseCacheConfig(boost::json::parse(R"JSON({"cache": {"load": "nONe"}})JSON")); auto const settings = makeCacheLoaderSettings(cfg); EXPECT_EQ(settings.loadStyle, CacheLoaderSettings::LoadStyle::NONE); EXPECT_TRUE(settings.isDisabled()); } { - auto const cfg = getParseCacheConfig(json::parse(R"JSON({"cache": {"load": "nO"}})JSON")); + auto const cfg = + getParseCacheConfig(boost::json::parse(R"JSON({"cache": {"load": "nO"}})JSON")); auto const settings = makeCacheLoaderSettings(cfg); EXPECT_EQ(settings.loadStyle, CacheLoaderSettings::LoadStyle::NONE); @@ -123,15 +128,15 @@ TEST_F(CacheLoaderSettingsTest, NoLoadStyleCorrectlyPropagatedThroughConfig) TEST_F(CacheLoaderSettingsTest, CacheFilePathCorrectlyPropagatedThroughConfig) { - static constexpr auto kCACHE_FILE_PATH = "/path/to/cache.dat"; + static constexpr auto kCacheFilePath = "/path/to/cache.dat"; auto const jsonStr = - fmt::format(R"JSON({{"cache": {{"file": {{"path": "{}"}}}}}})JSON", kCACHE_FILE_PATH); - auto const cfg = getParseCacheConfig(json::parse(jsonStr)); + fmt::format(R"JSON({{"cache": {{"file": {{"path": "{}"}}}}}})JSON", kCacheFilePath); + auto const cfg = getParseCacheConfig(boost::json::parse(jsonStr)); auto const settings = makeCacheLoaderSettings(cfg); ASSERT_TRUE(settings.cacheFileSettings.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - EXPECT_EQ(settings.cacheFileSettings->path, kCACHE_FILE_PATH); + EXPECT_EQ(settings.cacheFileSettings->path, kCacheFilePath); } TEST_F(CacheLoaderSettingsTest, CacheFilePathNotSetWhenAbsentFromConfig) @@ -149,7 +154,7 @@ TEST_F(CacheLoaderSettingsTest, MaxSequenceLagPropagatedThoughConfig) R"JSON({{"cache": {{"file": {{"path": "doesnt_matter", "max_sequence_age": {} }}}}}})JSON", seq ); - auto const cfg = getParseCacheConfig(json::parse(jsonStr)); + auto const cfg = getParseCacheConfig(boost::json::parse(jsonStr)); auto const settings = makeCacheLoaderSettings(cfg); ASSERT_TRUE(settings.cacheFileSettings.has_value()); diff --git a/tests/unit/etl/CacheLoaderTests.cpp b/tests/unit/etl/CacheLoaderTests.cpp index 61df612ed..202e34877 100644 --- a/tests/unit/etl/CacheLoaderTests.cpp +++ b/tests/unit/etl/CacheLoaderTests.cpp @@ -3,6 +3,7 @@ #include "etl/CacheLoaderSettings.hpp" #include "etl/FakeDiffProvider.hpp" #include "etl/impl/CacheLoader.hpp" +#include "util/LoggerFixtures.hpp" #include "util/MockBackendTestFixture.hpp" #include "util/MockLedgerCache.hpp" #include "util/MockLedgerCacheLoadingState.hpp" @@ -22,11 +23,11 @@ #include #include #include +#include #include #include #include -namespace json = boost::json; using namespace etl; using namespace util; using namespace data; @@ -61,7 +62,7 @@ getParseCacheConfig(boost::json::value val) return config; } -constexpr auto kSEQ = 30; +constexpr auto kSeq = 30; struct CacheLoaderTest : util::prometheus::WithPrometheus, MockBackendTest { DiffProvider diffProvider; @@ -76,6 +77,59 @@ struct ParametrizedCacheLoaderTest : CacheLoaderTest, WithParamInterface cache; + async::CoroExecutionContext ctx{1}; + + etl::impl::CacheLoaderImpl loader{ + ctx, + backend_, + cache, + kSeq, + /* numCacheMarkers */ 0, + /* cachePageFetchSize */ 512, + {} + }; + + template + void + runGuarded(Work&& work) + { + loader.runGuarded(std::forward(work)); + } +}; + +TEST_F(CacheLoaderImplTests, GuardDisablesCacheAndLogsOnStdException) +{ + EXPECT_CALL(cache, setDisabled).Times(1); + + runGuarded([] { throw std::runtime_error("boom"); }); + + EXPECT_THAT(getLoggerString(), HasSubstr("boom")); +} + +TEST_F(CacheLoaderImplTests, GuardDisablesCacheAndLogsUnknownOnNonStdException) +{ + EXPECT_CALL(cache, setDisabled).Times(1); + + runGuarded([] { throw 42; }); + + EXPECT_THAT(getLoggerString(), HasSubstr("unknown")); +} + +TEST_F(CacheLoaderImplTests, GuardDoesNotDisableCacheOnSuccess) +{ + EXPECT_CALL(cache, setDisabled).Times(0); + + bool called = false; + runGuarded([&] { called = true; }); + + EXPECT_TRUE(called); +} + // // Tests of implementation // @@ -188,11 +242,11 @@ TEST_P(ParametrizedCacheLoaderTest, LoadCacheWithDifferentSettings) auto const keysSize = 14; EXPECT_CALL(*backend_, fetchLedgerDiff(_, _)).WillRepeatedly(Return(diffs)); - EXPECT_CALL(*backend_, doFetchSuccessorKey(_, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchSuccessorKey(_, kSeq, _)) .Times(keysSize * loops) .WillRepeatedly([this]() { return diffProvider.nextKey(keysSize); }); - EXPECT_CALL(*backend_, doFetchLedgerObjects(_, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObjects(_, kSeq, _)) .WillRepeatedly(Return(std::vector(keysSize - 1, Blob{'s'}))); EXPECT_CALL(cache, isDisabled).WillRepeatedly(Return(false)); @@ -206,10 +260,10 @@ TEST_P(ParametrizedCacheLoaderTest, LoadCacheWithDifferentSettings) ctx, backend_, cache, - kSEQ, + kSeq, settings.numCacheMarkers, settings.cachePageFetchSize, - provider.getCursors(kSEQ) + provider.getCursors(kSeq) }; loader.wait(); @@ -223,11 +277,11 @@ TEST_P(ParametrizedCacheLoaderTest, AutomaticallyCancelledAndAwaitedInDestructor auto const keysSize = 1024; EXPECT_CALL(*backend_, fetchLedgerDiff(_, _)).WillRepeatedly(Return(diffs)); - EXPECT_CALL(*backend_, doFetchSuccessorKey(_, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchSuccessorKey(_, kSeq, _)) .Times(AtMost(keysSize * loops)) .WillRepeatedly([this]() { return diffProvider.nextKey(keysSize); }); - EXPECT_CALL(*backend_, doFetchLedgerObjects(_, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObjects(_, kSeq, _)) .WillRepeatedly(Return(std::vector(keysSize - 1, Blob{'s'}))); EXPECT_CALL(cache, isDisabled).WillRepeatedly(Return(false)); @@ -241,10 +295,10 @@ TEST_P(ParametrizedCacheLoaderTest, AutomaticallyCancelledAndAwaitedInDestructor ctx, backend_, cache, - kSEQ, + kSeq, settings.numCacheMarkers, settings.cachePageFetchSize, - provider.getCursors(kSEQ) + provider.getCursors(kSeq) }; // no loader.wait(): loader is immediately stopped and awaited in destructor @@ -258,11 +312,11 @@ TEST_P(ParametrizedCacheLoaderTest, CacheDisabledLeadsToCancellation) auto const keysSize = 1024; EXPECT_CALL(*backend_, fetchLedgerDiff(_, _)).WillRepeatedly(Return(diffs)); - EXPECT_CALL(*backend_, doFetchSuccessorKey(_, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchSuccessorKey(_, kSeq, _)) .Times(AtMost(keysSize * loops)) .WillRepeatedly([this]() { return diffProvider.nextKey(keysSize); }); - EXPECT_CALL(*backend_, doFetchLedgerObjects(_, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObjects(_, kSeq, _)) .WillRepeatedly(Return(std::vector(keysSize - 1, Blob{'s'}))); EXPECT_CALL(cache, isDisabled).WillOnce(Return(false)).WillRepeatedly(Return(true)); @@ -276,10 +330,42 @@ TEST_P(ParametrizedCacheLoaderTest, CacheDisabledLeadsToCancellation) ctx, backend_, cache, - kSEQ, + kSeq, settings.numCacheMarkers, settings.cachePageFetchSize, - provider.getCursors(kSEQ) + provider.getCursors(kSeq) + }; + + loader.wait(); +} + +TEST_P(ParametrizedCacheLoaderTest, NonTimeoutErrorDisablesCacheInsteadOfEscaping) +{ + auto const& settings = GetParam(); + auto const diffs = diffProvider.getLatestDiff(); + + EXPECT_CALL(*backend_, fetchLedgerDiff(_, _)).WillRepeatedly(Return(diffs)); + + EXPECT_CALL(*backend_, doFetchSuccessorKey(_, kSeq, _)) + .WillRepeatedly(Throw(std::runtime_error("simulated non-timeout backend failure"))); + EXPECT_CALL(*backend_, doFetchLedgerObjects(_, kSeq, _)) + .WillRepeatedly(Return(std::vector{})); + + EXPECT_CALL(cache, isDisabled).WillRepeatedly(Return(false)); + EXPECT_CALL(cache, setDisabled).Times(AtLeast(1)); + EXPECT_CALL(cache, setFull).Times(0); + + async::CoroExecutionContext ctx{settings.numThreads}; + etl::impl::CursorFromFixDiffNumProvider const provider{backend_, settings.numCacheDiffs}; + + etl::impl::CacheLoaderImpl loader{ + ctx, + backend_, + cache, + kSeq, + settings.numCacheMarkers, + settings.cachePageFetchSize, + provider.getCursors(kSeq) }; loader.wait(); @@ -290,7 +376,8 @@ TEST_P(ParametrizedCacheLoaderTest, CacheDisabledLeadsToCancellation) // TEST_F(CacheLoaderTest, SyncCacheLoaderWaitsTillFullyLoaded) { - auto const cfg = getParseCacheConfig(json::parse(R"JSON({"cache": {"load": "sync"}})JSON")); + auto const cfg = + getParseCacheConfig(boost::json::parse(R"JSON({"cache": {"load": "sync"}})JSON")); CacheLoader<> loader{cfg, backend_, cache, std::move(cacheLoadingState)}; auto const diffs = diffProvider.getLatestDiff(); @@ -302,7 +389,7 @@ TEST_F(CacheLoaderTest, SyncCacheLoaderWaitsTillFullyLoaded) return diffProvider.nextKey(keysSize); }); - EXPECT_CALL(*backend_, doFetchLedgerObjects(_, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObjects(_, kSeq, _)) .Times(loops) .WillRepeatedly(Return(std::vector{keysSize - 1, Blob{'s'}})); @@ -313,12 +400,13 @@ TEST_F(CacheLoaderTest, SyncCacheLoaderWaitsTillFullyLoaded) EXPECT_CALL(cache, startLoading).Times(1); EXPECT_CALL(cacheLoadingStateRef, waitForLoadingAllowed()); - loader.load(kSEQ); + loader.load(kSeq); } TEST_F(CacheLoaderTest, AsyncCacheLoaderCanBeStopped) { - auto const cfg = getParseCacheConfig(json::parse(R"JSON({"cache": {"load": "async"}})JSON")); + auto const cfg = + getParseCacheConfig(boost::json::parse(R"JSON({"cache": {"load": "async"}})JSON")); CacheLoader<> loader{cfg, backend_, cache, std::move(cacheLoadingState)}; auto const diffs = diffProvider.getLatestDiff(); @@ -330,7 +418,7 @@ TEST_F(CacheLoaderTest, AsyncCacheLoaderCanBeStopped) .Times(AtMost(keysSize * loops)) .WillRepeatedly([this]() { return diffProvider.nextKey(keysSize); }); - EXPECT_CALL(*backend_, doFetchLedgerObjects(_, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObjects(_, kSeq, _)) .Times(AtMost(loops)) .WillRepeatedly(Return(std::vector{keysSize - 1, Blob{'s'}})); @@ -341,33 +429,35 @@ TEST_F(CacheLoaderTest, AsyncCacheLoaderCanBeStopped) EXPECT_CALL(cache, startLoading).Times(1); EXPECT_CALL(cacheLoadingStateRef, waitForLoadingAllowed()).Times(1); - loader.load(kSEQ); + loader.load(kSeq); loader.stop(); loader.wait(); } TEST_F(CacheLoaderTest, DisabledCacheLoaderDoesNotLoadCache) { - auto const cfg = getParseCacheConfig(json::parse(R"JSON({"cache": {"load": "none"}})JSON")); + auto const cfg = + getParseCacheConfig(boost::json::parse(R"JSON({"cache": {"load": "none"}})JSON")); CacheLoader<> loader{cfg, backend_, cache, std::move(cacheLoadingState)}; EXPECT_CALL(cache, updateImpl).Times(0); EXPECT_CALL(cache, isFull).WillRepeatedly(Return(false)); EXPECT_CALL(cache, setDisabled).Times(1); - loader.load(kSEQ); + loader.load(kSeq); } TEST_F(CacheLoaderTest, DisabledCacheLoaderCanCallStopAndWait) { - auto const cfg = getParseCacheConfig(json::parse(R"JSON({"cache": {"load": "none"}})JSON")); + auto const cfg = + getParseCacheConfig(boost::json::parse(R"JSON({"cache": {"load": "none"}})JSON")); CacheLoader<> loader{cfg, backend_, cache, std::move(cacheLoadingState)}; EXPECT_CALL(cache, updateImpl).Times(0); EXPECT_CALL(cache, isFull).WillRepeatedly(Return(false)); EXPECT_CALL(cache, setDisabled).Times(1); - loader.load(kSEQ); + loader.load(kSeq); EXPECT_NO_THROW(loader.stop()); EXPECT_NO_THROW(loader.wait()); @@ -376,13 +466,13 @@ TEST_F(CacheLoaderTest, DisabledCacheLoaderCanCallStopAndWait) struct CacheLoaderFromFileTest : CacheLoaderTest { CacheLoaderFromFileTest() { - backend_->setRange(kSEQ - 20, kSEQ); + backend_->setRange(kSeq - 20, kSeq); } std::string const filePath = "./cache.bin"; uint32_t const maxSequenceLag = 10; ClioConfigDefinition const cfg = getParseCacheConfig( - json::parse( + boost::json::parse( fmt::format( R"JSON({{"cache": {{"load": "sync", "file": {{"path": "{}", "max_sequence_age": {}}}}}}})JSON", filePath, @@ -395,18 +485,18 @@ struct CacheLoaderFromFileTest : CacheLoaderTest { TEST_F(CacheLoaderFromFileTest, Success) { - constexpr uint32_t kLOADED_SEQ = 12345; + constexpr uint32_t kLoadedSeq = 12345; EXPECT_CALL(cache, isFull).WillOnce(Return(false)); - EXPECT_CALL(cache, loadFromFile(filePath, kSEQ - maxSequenceLag)) + EXPECT_CALL(cache, loadFromFile(filePath, kSeq - maxSequenceLag)) .WillOnce(Return(std::expected{})); - EXPECT_CALL(cache, latestLedgerSequence).WillOnce(Return(kLOADED_SEQ)); + EXPECT_CALL(cache, latestLedgerSequence).WillOnce(Return(kLoadedSeq)); EXPECT_CALL(cache, setFull); - loader.load(kSEQ); + loader.load(kSeq); std::optional const expectedLedgerRange = - LedgerRange{.minSequence = kSEQ - 20, .maxSequence = kSEQ}; + LedgerRange{.minSequence = kSeq - 20, .maxSequence = kSeq}; EXPECT_EQ(backend_->fetchLedgerRange(), expectedLedgerRange); } @@ -416,7 +506,7 @@ TEST_F(CacheLoaderFromFileTest, FailureBackToNormalLoad) auto const loops = diffs.size() + 1; auto const keysSize = 14; - EXPECT_CALL(cache, loadFromFile(filePath, kSEQ - maxSequenceLag)) + EXPECT_CALL(cache, loadFromFile(filePath, kSeq - maxSequenceLag)) .WillOnce(Return(std::expected(std::unexpected("File not found")))); EXPECT_CALL(cacheLoadingStateRef, waitForLoadingAllowed()).Times(1); @@ -425,7 +515,7 @@ TEST_F(CacheLoaderFromFileTest, FailureBackToNormalLoad) return diffProvider.nextKey(keysSize); }); - EXPECT_CALL(*backend_, doFetchLedgerObjects(_, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObjects(_, kSeq, _)) .Times(loops) .WillRepeatedly(Return(std::vector{keysSize - 1, Blob{'s'}})); @@ -435,13 +525,15 @@ TEST_F(CacheLoaderFromFileTest, FailureBackToNormalLoad) EXPECT_CALL(cache, setFull).Times(1); EXPECT_CALL(cache, startLoading).Times(1); - loader.load(kSEQ); + loader.load(kSeq); } TEST_F(CacheLoaderFromFileTest, DontLoadWhenCacheIsDisabled) { auto const disabledCacheCfg = getParseCacheConfig( - json::parse(R"JSON({"cache": {"load": "none", "file": {"path": "/tmp/cache.bin"}}})JSON") + boost::json::parse( + R"JSON({"cache": {"load": "none", "file": {"path": "/tmp/cache.bin"}}})JSON" + ) ); CacheLoader<> loaderWithCacheDisabled{ disabledCacheCfg, backend_, cache, std::make_unique() @@ -450,46 +542,46 @@ TEST_F(CacheLoaderFromFileTest, DontLoadWhenCacheIsDisabled) EXPECT_CALL(cache, isFull).WillOnce(Return(false)); EXPECT_CALL(cache, setDisabled); - loaderWithCacheDisabled.load(kSEQ); + loaderWithCacheDisabled.load(kSeq); } TEST_F(CacheLoaderFromFileTest, MaxSequenceLagCalculation) { - constexpr uint32_t kLOADED_SEQ = 12345; + constexpr uint32_t kLoadedSeq = 12345; EXPECT_CALL(cache, isFull).WillOnce(Return(false)); - EXPECT_CALL(cache, loadFromFile(filePath, kSEQ - maxSequenceLag)) + EXPECT_CALL(cache, loadFromFile(filePath, kSeq - maxSequenceLag)) .WillOnce(Return(std::expected{})); - EXPECT_CALL(cache, latestLedgerSequence).WillOnce(Return(kLOADED_SEQ)); + EXPECT_CALL(cache, latestLedgerSequence).WillOnce(Return(kLoadedSeq)); EXPECT_CALL(cache, setFull).Times(1); - loader.load(kSEQ); + loader.load(kSeq); } TEST_F(CacheLoaderFromFileTest, FileSequenceBehindBackendFetchesMissingLedgersFromDB) { - constexpr uint32_t kFILE_SEQ = kSEQ - 2; + constexpr uint32_t kFileSeq = kSeq - 2; auto const diffs = diffProvider.getLatestDiff(); EXPECT_CALL(cache, isFull).WillOnce(Return(false)); - EXPECT_CALL(cache, loadFromFile(filePath, kSEQ - maxSequenceLag)) + EXPECT_CALL(cache, loadFromFile(filePath, kSeq - maxSequenceLag)) .WillOnce(Return(std::expected{})); // latestLedgerSequence is called twice per loop iteration (condition + seqToLoad + 1) // plus once for the final exit check EXPECT_CALL(cache, latestLedgerSequence) - .WillOnce(Return(kFILE_SEQ)) // iteration 1: condition (true) - .WillOnce(Return(kFILE_SEQ)) // iteration 1: seqToLoad + 1 = kFILE_SEQ + 1 - .WillOnce(Return(kFILE_SEQ + 1)) // iteration 2: condition (true) - .WillOnce(Return(kFILE_SEQ + 1)) // iteration 2: seqToLoad + 1 = kFILE_SEQ + 2 - .WillOnce(Return(kSEQ)); // exit condition (false) + .WillOnce(Return(kFileSeq)) // iteration 1: condition (true) + .WillOnce(Return(kFileSeq)) // iteration 1: seqToLoad + 1 = kFileSeq + 1 + .WillOnce(Return(kFileSeq + 1)) // iteration 2: condition (true) + .WillOnce(Return(kFileSeq + 1)) // iteration 2: seqToLoad + 1 = kFileSeq + 2 + .WillOnce(Return(kSeq)); // exit condition (false) - EXPECT_CALL(*backend_, fetchLedgerDiff(kFILE_SEQ + 1, _)).WillOnce(Return(diffs)); - EXPECT_CALL(*backend_, fetchLedgerDiff(kFILE_SEQ + 2, _)).WillOnce(Return(diffs)); + EXPECT_CALL(*backend_, fetchLedgerDiff(kFileSeq + 1, _)).WillOnce(Return(diffs)); + EXPECT_CALL(*backend_, fetchLedgerDiff(kFileSeq + 2, _)).WillOnce(Return(diffs)); EXPECT_CALL(cache, updateImpl).Times(2); EXPECT_CALL(cache, setFull).Times(1); - loader.load(kSEQ); + loader.load(kSeq); } TEST_F(CacheLoaderFromFileTest, MaxSequenceLagClampedToMinOfLedgerRange) diff --git a/tests/unit/etl/CorruptionDetectorTests.cpp b/tests/unit/etl/CorruptionDetectorTests.cpp index a85a2089b..845929e0b 100644 --- a/tests/unit/etl/CorruptionDetectorTests.cpp +++ b/tests/unit/etl/CorruptionDetectorTests.cpp @@ -14,7 +14,7 @@ struct CorruptionDetectorTest : WithPrometheus {}; TEST_F(CorruptionDetectorTest, DisableCacheOnCorruption) { - using namespace ripple; + using namespace xrpl; auto state = etl::SystemState{}; auto cache = MockLedgerCache{}; auto detector = etl::CorruptionDetector{state, cache}; diff --git a/tests/unit/etl/CursorFromAccountProviderTests.cpp b/tests/unit/etl/CursorFromAccountProviderTests.cpp index 098b45812..e8c75d360 100644 --- a/tests/unit/etl/CursorFromAccountProviderTests.cpp +++ b/tests/unit/etl/CursorFromAccountProviderTests.cpp @@ -16,18 +16,18 @@ using namespace testing; namespace { -constexpr auto kSEQ = 30; +constexpr auto kSeq = 30; -std::vector const kACCOUNT_ROOTS = { - ripple::uint256{"05E1EAC2574BE082B00B16F907CE32E6058DEB8F9E81CF34A00E80A5D71FA4FE"}, - ripple::uint256{"110872C7196EE6EF7032952F1852B11BB461A96FF2D7E06A8003B4BB30FD130B"}, - ripple::uint256{"3B3A84E850C724E914293271785A31D0BFC8B9DD1B6332E527B149AD72E80E18"}, - ripple::uint256{"4EC98C5C3F34C44409BC058998CBD64F6AED3FF6C0CAAEC15F7F42DF14EE9F04"}, - ripple::uint256{"58CEC9F17733EA7BA68C88E6179B8F207D001EE04D4E0366F958CC04FF6AB834"}, - ripple::uint256{"64FB1712146BA604C274CC335C5DE7ADFE52D1F8C3E904A9F9765FE8158A3E01"}, - ripple::uint256{"700BE23B1D9EE3E6BF52543D05843D5345B85D9EDB3D33BBD6B4C3A13C54B38E"}, - ripple::uint256{"82C297FCBCD634C4424F263D17480AA2F13975DF5846A5BB57246022CEEBE441"}, - ripple::uint256{"A2AA4C212DC2CA2C49BF58805F7C63363BC981018A01AC9609A7CBAB2A02CEDF"}, +std::vector const kAccountRoots = { + xrpl::uint256{"05E1EAC2574BE082B00B16F907CE32E6058DEB8F9E81CF34A00E80A5D71FA4FE"}, + xrpl::uint256{"110872C7196EE6EF7032952F1852B11BB461A96FF2D7E06A8003B4BB30FD130B"}, + xrpl::uint256{"3B3A84E850C724E914293271785A31D0BFC8B9DD1B6332E527B149AD72E80E18"}, + xrpl::uint256{"4EC98C5C3F34C44409BC058998CBD64F6AED3FF6C0CAAEC15F7F42DF14EE9F04"}, + xrpl::uint256{"58CEC9F17733EA7BA68C88E6179B8F207D001EE04D4E0366F958CC04FF6AB834"}, + xrpl::uint256{"64FB1712146BA604C274CC335C5DE7ADFE52D1F8C3E904A9F9765FE8158A3E01"}, + xrpl::uint256{"700BE23B1D9EE3E6BF52543D05843D5345B85D9EDB3D33BBD6B4C3A13C54B38E"}, + xrpl::uint256{"82C297FCBCD634C4424F263D17480AA2F13975DF5846A5BB57246022CEEBE441"}, + xrpl::uint256{"A2AA4C212DC2CA2C49BF58805F7C63363BC981018A01AC9609A7CBAB2A02CEDF"}, }; struct CursorFromAccountProviderTests : util::prometheus::WithPrometheus, MockBackendTestNaggy {}; @@ -39,13 +39,13 @@ TEST_F(CursorFromAccountProviderTests, EnoughAccountRoots) auto const pageSize = 100; auto const provider = etl::impl::CursorFromAccountProvider{backend_, numCursors, pageSize}; - ON_CALL(*backend_, fetchAccountRoots(numCursors, _, kSEQ, _)) - .WillByDefault(Return(kACCOUNT_ROOTS)); + ON_CALL(*backend_, fetchAccountRoots(numCursors, _, kSeq, _)) + .WillByDefault(Return(kAccountRoots)); EXPECT_CALL(*backend_, fetchAccountRoots(_, _, _, _)).Times(1); - auto const cursors = provider.getCursors(kSEQ); + auto const cursors = provider.getCursors(kSeq); ASSERT_EQ(cursors.size(), numCursors + 1); - EXPECT_EQ(cursors.front().start, kFIRST_KEY); - EXPECT_EQ(cursors.back().end, kLAST_KEY); + EXPECT_EQ(cursors.front().start, kFirstKey); + EXPECT_EQ(cursors.back().end, kLastKey); } diff --git a/tests/unit/etl/CursorFromDiffProviderTests.cpp b/tests/unit/etl/CursorFromDiffProviderTests.cpp index c0b473b2b..ce86146c9 100644 --- a/tests/unit/etl/CursorFromDiffProviderTests.cpp +++ b/tests/unit/etl/CursorFromDiffProviderTests.cpp @@ -16,55 +16,55 @@ using namespace testing; namespace { -constexpr auto kSEQ = 30; +constexpr auto kSeq = 30; -std::vector const kDIFFS_FOR_SEQ = { - {.key = ripple::uint256{"05E1EAC2574BE082B00B16F907CE32E6058DEB8F9E81CF34A00E80A5D71FA4FE"}, +std::vector const kDiffsForSeq = { + {.key = xrpl::uint256{"05E1EAC2574BE082B00B16F907CE32E6058DEB8F9E81CF34A00E80A5D71FA4FE"}, .blob = Blob{}}, // This object is removed in Seq while it exists in Seq-1 - {.key = ripple::uint256{"110872C7196EE6EF7032952F1852B11BB461A96FF2D7E06A8003B4BB30FD130B"}, + {.key = xrpl::uint256{"110872C7196EE6EF7032952F1852B11BB461A96FF2D7E06A8003B4BB30FD130B"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"3B3A84E850C724E914293271785A31D0BFC8B9DD1B6332E527B149AD72E80E18"}, + {.key = xrpl::uint256{"3B3A84E850C724E914293271785A31D0BFC8B9DD1B6332E527B149AD72E80E18"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"4EC98C5C3F34C44409BC058998CBD64F6AED3FF6C0CAAEC15F7F42DF14EE9F04"}, + {.key = xrpl::uint256{"4EC98C5C3F34C44409BC058998CBD64F6AED3FF6C0CAAEC15F7F42DF14EE9F04"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"58CEC9F17733EA7BA68C88E6179B8F207D001EE04D4E0366F958CC04FF6AB834"}, + {.key = xrpl::uint256{"58CEC9F17733EA7BA68C88E6179B8F207D001EE04D4E0366F958CC04FF6AB834"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"64FB1712146BA604C274CC335C5DE7ADFE52D1F8C3E904A9F9765FE8158A3E01"}, + {.key = xrpl::uint256{"64FB1712146BA604C274CC335C5DE7ADFE52D1F8C3E904A9F9765FE8158A3E01"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"700BE23B1D9EE3E6BF52543D05843D5345B85D9EDB3D33BBD6B4C3A13C54B38E"}, + {.key = xrpl::uint256{"700BE23B1D9EE3E6BF52543D05843D5345B85D9EDB3D33BBD6B4C3A13C54B38E"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"82C297FCBCD634C4424F263D17480AA2F13975DF5846A5BB57246022CEEBE441"}, + {.key = xrpl::uint256{"82C297FCBCD634C4424F263D17480AA2F13975DF5846A5BB57246022CEEBE441"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"A2AA4C212DC2CA2C49BF58805F7C63363BC981018A01AC9609A7CBAB2A02CEDF"}, + {.key = xrpl::uint256{"A2AA4C212DC2CA2C49BF58805F7C63363BC981018A01AC9609A7CBAB2A02CEDF"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"BC0DAE09C0BFBC4A49AA94B849266588BFD6E1F554B184B5788AC55D6E07EB95"}, + {.key = xrpl::uint256{"BC0DAE09C0BFBC4A49AA94B849266588BFD6E1F554B184B5788AC55D6E07EB95"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"DCC8759A35CB946511763AA5553A82AA25F20B901C98C9BB74D423BCFAFF5F9D"}, + {.key = xrpl::uint256{"DCC8759A35CB946511763AA5553A82AA25F20B901C98C9BB74D423BCFAFF5F9D"}, .blob = Blob{'s'}}, }; -std::vector const kDIFFS_FOR_SEQ_MINUS1 = { - {.key = ripple::uint256{"05E1EAC2574BE082B00B16F907CE32E6058DEB8F9E81CF34A00E80A5D71FA4FE"}, +std::vector const kDiffsForSeqMinuS1 = { + {.key = xrpl::uint256{"05E1EAC2574BE082B00B16F907CE32E6058DEB8F9E81CF34A00E80A5D71FA4FE"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"110872C7196EE6EF7032952F1852B11BB461A96FF2D7E06A8003B4BB30FD1301"}, + {.key = xrpl::uint256{"110872C7196EE6EF7032952F1852B11BB461A96FF2D7E06A8003B4BB30FD1301"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"3B3A84E850C724E914293271785A31D0BFC8B9DD1B6332E527B149AD72E80E12"}, + {.key = xrpl::uint256{"3B3A84E850C724E914293271785A31D0BFC8B9DD1B6332E527B149AD72E80E12"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"4EC98C5C3F34C44409BC058998CBD64F6AED3FF6C0CAAEC15F7F42DF14EE9F03"}, + {.key = xrpl::uint256{"4EC98C5C3F34C44409BC058998CBD64F6AED3FF6C0CAAEC15F7F42DF14EE9F03"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"58CEC9F17733EA7BA68C88E6179B8F207D001EE04D4E0366F958CC04FF6AB834"}, + {.key = xrpl::uint256{"58CEC9F17733EA7BA68C88E6179B8F207D001EE04D4E0366F958CC04FF6AB834"}, .blob = Blob{'s'}}, // This object is changed in both Seq and Seq-1 - {.key = ripple::uint256{"64FB1712146BA604C274CC335C5DE7ADFE52D1F8C3E904A9F9765FE8158A3E05"}, + {.key = xrpl::uint256{"64FB1712146BA604C274CC335C5DE7ADFE52D1F8C3E904A9F9765FE8158A3E05"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"700BE23B1D9EE3E6BF52543D05843D5345B85D9EDB3D33BBD6B4C3A13C54B386"}, + {.key = xrpl::uint256{"700BE23B1D9EE3E6BF52543D05843D5345B85D9EDB3D33BBD6B4C3A13C54B386"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"82C297FCBCD634C4424F263D17480AA2F13975DF5846A5BB57246022CEEBE447"}, + {.key = xrpl::uint256{"82C297FCBCD634C4424F263D17480AA2F13975DF5846A5BB57246022CEEBE447"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"A2AA4C212DC2CA2C49BF58805F7C63363BC981018A01AC9609A7CBAB2A02CED8"}, + {.key = xrpl::uint256{"A2AA4C212DC2CA2C49BF58805F7C63363BC981018A01AC9609A7CBAB2A02CED8"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"BC0DAE09C0BFBC4A49AA94B849266588BFD6E1F554B184B5788AC55D6E07EB99"}, + {.key = xrpl::uint256{"BC0DAE09C0BFBC4A49AA94B849266588BFD6E1F554B184B5788AC55D6E07EB99"}, .blob = Blob{'s'}}, - {.key = ripple::uint256{"DCC8759A35CB946511763AA5553A82AA25F20B901C98C9BB74D423BCFAFF5F90"}, + {.key = xrpl::uint256{"DCC8759A35CB946511763AA5553A82AA25F20B901C98C9BB74D423BCFAFF5F90"}, .blob = Blob{'s'}}, }; @@ -76,16 +76,16 @@ TEST_F(CursorFromDiffProviderTests, MultipleDiffs) auto const numCursors = 15; auto const provider = etl::impl::CursorFromDiffProvider{backend_, numCursors}; - backend_->setRange(kSEQ - 10, kSEQ); - ON_CALL(*backend_, fetchLedgerDiff(kSEQ, _)).WillByDefault(Return(kDIFFS_FOR_SEQ)); - ON_CALL(*backend_, fetchLedgerDiff(kSEQ - 1, _)).WillByDefault(Return(kDIFFS_FOR_SEQ_MINUS1)); + backend_->setRange(kSeq - 10, kSeq); + ON_CALL(*backend_, fetchLedgerDiff(kSeq, _)).WillByDefault(Return(kDiffsForSeq)); + ON_CALL(*backend_, fetchLedgerDiff(kSeq - 1, _)).WillByDefault(Return(kDiffsForSeqMinuS1)); EXPECT_CALL(*backend_, fetchLedgerDiff(_, _)).Times(2); - auto const cursors = provider.getCursors(kSEQ); + auto const cursors = provider.getCursors(kSeq); ASSERT_EQ(cursors.size(), numCursors + 1); - EXPECT_EQ(cursors.front().start, kFIRST_KEY); - EXPECT_EQ(cursors.back().end, kLAST_KEY); + EXPECT_EQ(cursors.front().start, kFirstKey); + EXPECT_EQ(cursors.back().end, kLastKey); } TEST_F(CursorFromDiffProviderTests, NotEnoughDiffs) @@ -93,21 +93,20 @@ TEST_F(CursorFromDiffProviderTests, NotEnoughDiffs) auto const numCursors = 35; auto const provider = etl::impl::CursorFromDiffProvider{backend_, numCursors}; auto const availableDiffs = 10; - backend_->setRange(kSEQ - availableDiffs + 1, kSEQ); + backend_->setRange(kSeq - availableDiffs + 1, kSeq); ON_CALL(*backend_, fetchLedgerDiff(_, _)) .WillByDefault(Return(std::vector{})); - ON_CALL(*backend_, fetchLedgerDiff(kSEQ, _)).WillByDefault(Return(kDIFFS_FOR_SEQ)); - ON_CALL(*backend_, fetchLedgerDiff(kSEQ - 1, _)).WillByDefault(Return(kDIFFS_FOR_SEQ_MINUS1)); + ON_CALL(*backend_, fetchLedgerDiff(kSeq, _)).WillByDefault(Return(kDiffsForSeq)); + ON_CALL(*backend_, fetchLedgerDiff(kSeq - 1, _)).WillByDefault(Return(kDiffsForSeqMinuS1)); EXPECT_CALL(*backend_, fetchLedgerDiff(_, _)).Times(availableDiffs); - auto const cursors = provider.getCursors(kSEQ); + auto const cursors = provider.getCursors(kSeq); auto const removed = 2; // lost 2 objects because it is removed. auto const repeated = 1; // repeated 1 object ASSERT_EQ( - cursors.size(), - kDIFFS_FOR_SEQ.size() + kDIFFS_FOR_SEQ_MINUS1.size() - removed - repeated + 1 + cursors.size(), kDiffsForSeq.size() + kDiffsForSeqMinuS1.size() - removed - repeated + 1 ); - EXPECT_EQ(cursors.front().start, kFIRST_KEY); - EXPECT_EQ(cursors.back().end, kLAST_KEY); + EXPECT_EQ(cursors.front().start, kFirstKey); + EXPECT_EQ(cursors.back().end, kLastKey); } diff --git a/tests/unit/etl/CursorFromFixDiffNumProviderTests.cpp b/tests/unit/etl/CursorFromFixDiffNumProviderTests.cpp index 852397961..556521383 100644 --- a/tests/unit/etl/CursorFromFixDiffNumProviderTests.cpp +++ b/tests/unit/etl/CursorFromFixDiffNumProviderTests.cpp @@ -16,7 +16,7 @@ using namespace testing; namespace { -constexpr auto kSEQ = 30; +constexpr auto kSeq = 30; struct CursorProviderTest : util::prometheus::WithPrometheus, MockBackendTestNaggy { DiffProvider diffProvider; @@ -44,11 +44,11 @@ TEST_P(ParametrizedCursorProviderTest, GetCursorsWithDifferentProviderSettings) ON_CALL(*backend_, fetchLedgerDiff(_, _)).WillByDefault(Return(diffs)); EXPECT_CALL(*backend_, fetchLedgerDiff(_, _)).Times(numDiffs); - auto const cursors = provider.getCursors(kSEQ); + auto const cursors = provider.getCursors(kSeq); ASSERT_EQ(cursors.size(), diffs.size() + 1); - EXPECT_EQ(cursors.front().start, kFIRST_KEY); - EXPECT_EQ(cursors.back().end, kLAST_KEY); + EXPECT_EQ(cursors.front().start, kFirstKey); + EXPECT_EQ(cursors.back().end, kLastKey); } TEST_F(CursorProviderTest, EmptyCursorIsHandledCorrectly) @@ -59,9 +59,9 @@ TEST_F(CursorProviderTest, EmptyCursorIsHandledCorrectly) ON_CALL(*backend_, fetchLedgerDiff(_, _)).WillByDefault(Return(diffs)); EXPECT_CALL(*backend_, fetchLedgerDiff(_, _)).Times(0); - auto const cursors = provider.getCursors(kSEQ); + auto const cursors = provider.getCursors(kSeq); ASSERT_EQ(cursors.size(), 1); - EXPECT_EQ(cursors.front().start, kFIRST_KEY); - EXPECT_EQ(cursors.back().end, kLAST_KEY); + EXPECT_EQ(cursors.front().start, kFirstKey); + EXPECT_EQ(cursors.back().end, kLastKey); } diff --git a/tests/unit/etl/ETLServiceTests.cpp b/tests/unit/etl/ETLServiceTests.cpp index abf6eb266..57a31b4b5 100644 --- a/tests/unit/etl/ETLServiceTests.cpp +++ b/tests/unit/etl/ETLServiceTests.cpp @@ -53,8 +53,8 @@ using namespace util::config; namespace { -constinit auto const kSEQ = 100; -constinit auto const kLEDGER_HASH = +constinit auto const kSeq = 100; +constinit auto const kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; struct MockMonitor : public etl::MonitorInterface { @@ -90,7 +90,7 @@ struct MockLoader : etl::LoaderInterface { using ExpectedType = std::expected; MOCK_METHOD(ExpectedType, load, (etl::model::LedgerData const&), (override)); MOCK_METHOD( - std::optional, + std::optional, loadInitialLedger, (etl::model::LedgerData const&), (override) @@ -152,7 +152,7 @@ struct MockMonitorProvider : etl::MonitorProviderInterface { auto createTestData(uint32_t seq) { - auto const header = createLedgerHeader(kLEDGER_HASH, seq); + auto const header = createLedgerHeader(kLedgerHash, seq); return etl::model::LedgerData{ .transactions = {}, .objects = {util::createObject(), util::createObject(), util::createObject()}, @@ -305,29 +305,29 @@ TEST_F(ETLServiceTests, RunWithEmptyDatabase) { auto mockTaskManager = std::make_unique>(); auto& mockTaskManagerRef = *mockTaskManager; - auto ledgerData = createTestData(kSEQ); + auto ledgerData = createTestData(kSeq); EXPECT_FALSE(systemState_->etlStarted); testing::Sequence const s; EXPECT_CALL(*backend_, hardFetchLedgerRange) .InSequence(s) .WillOnce(testing::Return(std::nullopt)); - EXPECT_CALL(*ledgers_, getMostRecent()).WillRepeatedly(testing::Return(kSEQ)); - EXPECT_CALL(*extractor_, extractLedgerOnly(kSEQ)).WillOnce(testing::Return(ledgerData)); - EXPECT_CALL(*balancer_, loadInitialLedger(kSEQ, testing::_, testing::_)) + EXPECT_CALL(*ledgers_, getMostRecent()).WillRepeatedly(testing::Return(kSeq)); + EXPECT_CALL(*extractor_, extractLedgerOnly(kSeq)).WillOnce(testing::Return(ledgerData)); + EXPECT_CALL(*balancer_, loadInitialLedger(kSeq, testing::_, testing::_)) .WillOnce(testing::Return(std::vector{})); - EXPECT_CALL(*loader_, loadInitialLedger).WillOnce(testing::Return(ripple::LedgerHeader{})); + EXPECT_CALL(*loader_, loadInitialLedger).WillOnce(testing::Return(xrpl::LedgerHeader{})); EXPECT_CALL(*backend_, hardFetchLedgerRange) .Times(1) .InSequence(s) - .WillOnce(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); + .WillOnce(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); EXPECT_CALL(mockTaskManagerRef, run); - EXPECT_CALL(*taskManagerProvider_, make(testing::_, testing::_, kSEQ + 1, testing::_)) + EXPECT_CALL(*taskManagerProvider_, make(testing::_, testing::_, kSeq + 1, testing::_)) .WillOnce([&](auto&&...) { EXPECT_TRUE(systemState_->etlStarted); return std::unique_ptr(mockTaskManager.release()); }); - EXPECT_CALL(*monitorProvider_, make(testing::_, testing::_, testing::_, kSEQ + 1, testing::_)) + EXPECT_CALL(*monitorProvider_, make(testing::_, testing::_, testing::_, kSeq + 1, testing::_)) .WillOnce([this](auto, auto, auto, auto, auto) { EXPECT_FALSE(systemState_->etlStarted); return std::make_unique>(); @@ -339,16 +339,16 @@ TEST_F(ETLServiceTests, RunWithEmptyDatabase) TEST_F(ETLServiceTests, RunWithPopulatedDatabase) { EXPECT_FALSE(systemState_->etlStarted); - backend_->cache().update({}, kSEQ, false); + backend_->cache().update({}, kSeq, false); EXPECT_CALL(*backend_, hardFetchLedgerRange) - .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); - EXPECT_CALL(*monitorProvider_, make(testing::_, testing::_, testing::_, kSEQ + 1, testing::_)) + .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); + EXPECT_CALL(*monitorProvider_, make(testing::_, testing::_, testing::_, kSeq + 1, testing::_)) .WillOnce([this](auto, auto, auto, auto, auto) { EXPECT_FALSE(systemState_->etlStarted); return std::make_unique>(); }); - EXPECT_CALL(*ledgers_, getMostRecent()).WillRepeatedly(testing::Return(kSEQ)); - EXPECT_CALL(*cacheLoader_, load(kSEQ)); + EXPECT_CALL(*ledgers_, getMostRecent()).WillRepeatedly(testing::Return(kSeq)); + EXPECT_CALL(*cacheLoader_, load(kSeq)); service_.run(); } @@ -356,17 +356,17 @@ TEST_F(ETLServiceTests, RunWithPopulatedDatabase) TEST_F(ETLServiceTests, SyncCacheWithDbBeforeStartingMonitor) { EXPECT_FALSE(systemState_->etlStarted); - backend_->cache().update({}, kSEQ - 2, false); + backend_->cache().update({}, kSeq - 2, false); EXPECT_CALL(*backend_, hardFetchLedgerRange) - .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); + .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); - EXPECT_CALL(*monitorProvider_, make(testing::_, testing::_, testing::_, kSEQ + 1, testing::_)) + EXPECT_CALL(*monitorProvider_, make(testing::_, testing::_, testing::_, kSeq + 1, testing::_)) .WillOnce([this](auto, auto, auto, auto, auto) { EXPECT_FALSE(systemState_->etlStarted); return std::make_unique>(); }); - EXPECT_CALL(*ledgers_, getMostRecent()).WillRepeatedly(testing::Return(kSEQ)); - EXPECT_CALL(*cacheLoader_, load(kSEQ)); + EXPECT_CALL(*ledgers_, getMostRecent()).WillRepeatedly(testing::Return(kSeq)); + EXPECT_CALL(*cacheLoader_, load(kSeq)); service_.run(); } @@ -404,19 +404,19 @@ TEST_F(ETLServiceTests, HandlesWriteConflictInMonitorSubscription) EXPECT_CALL(mockMonitorRef, run); // Set cache to be in sync with DB to avoid syncCacheWithDb loop - backend_->cache().update({}, kSEQ, false); + backend_->cache().update({}, kSeq, false); EXPECT_CALL(*backend_, hardFetchLedgerRange) - .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); - EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSEQ)); - EXPECT_CALL(*cacheLoader_, load(kSEQ)); + .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); + EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSeq)); + EXPECT_CALL(*cacheLoader_, load(kSeq)); service_.run(); writeCommandConnection_.disconnect(); systemState_->writeCommandSignal(etl::SystemState::WriteCommand::StopWriting); - EXPECT_CALL(*publisher_, publish(kSEQ + 1, testing::_, testing::_)); + EXPECT_CALL(*publisher_, publish(kSeq + 1, testing::_, testing::_)); ASSERT_TRUE(capturedCallback); - capturedCallback(kSEQ + 1); + capturedCallback(kSeq + 1); EXPECT_FALSE(systemState_->isWriting); } @@ -440,25 +440,25 @@ TEST_F(ETLServiceTests, NormalFlowInMonitorSubscription) EXPECT_CALL(mockMonitorRef, run); // Set cache to be in sync with DB to avoid syncCacheWithDb loop - backend_->cache().update({}, kSEQ, false); + backend_->cache().update({}, kSeq, false); EXPECT_CALL(*backend_, hardFetchLedgerRange) - .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); - EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSEQ)); - EXPECT_CALL(*cacheLoader_, load(kSEQ)); + .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); + EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSeq)); + EXPECT_CALL(*cacheLoader_, load(kSeq)); service_.run(); systemState_->isWriting = false; std::vector const dummyDiff = {}; - EXPECT_CALL(*backend_, fetchLedgerDiff(kSEQ + 1, testing::_)) + EXPECT_CALL(*backend_, fetchLedgerDiff(kSeq + 1, testing::_)) .WillOnce(testing::Return(dummyDiff)); EXPECT_CALL( - *cacheUpdater_, update(kSEQ + 1, testing::A const&>()) + *cacheUpdater_, update(kSeq + 1, testing::A const&>()) ); - EXPECT_CALL(*publisher_, publish(kSEQ + 1, testing::_, testing::_)); + EXPECT_CALL(*publisher_, publish(kSeq + 1, testing::_, testing::_)); ASSERT_TRUE(capturedCallback); - capturedCallback(kSEQ + 1); + capturedCallback(kSeq + 1); } TEST_F(ETLServiceTests, AttemptTakeoverWriter) @@ -484,11 +484,11 @@ TEST_F(ETLServiceTests, AttemptTakeoverWriter) EXPECT_CALL(mockMonitorRef, run); // Set cache to be in sync with DB to avoid syncCacheWithDb loop - backend_->cache().update({}, kSEQ, false); + backend_->cache().update({}, kSeq, false); EXPECT_CALL(*backend_, hardFetchLedgerRange) - .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); - EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSEQ)); - EXPECT_CALL(*cacheLoader_, load(kSEQ)); + .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); + EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSeq)); + EXPECT_CALL(*cacheLoader_, load(kSeq)); service_.run(); systemState_->isStrictReadonly = false; // writer node @@ -498,7 +498,7 @@ TEST_F(ETLServiceTests, AttemptTakeoverWriter) auto& mockTaskManagerRef = *mockTaskManager; EXPECT_CALL(mockTaskManagerRef, run); - EXPECT_CALL(*taskManagerProvider_, make(testing::_, testing::_, kSEQ + 1, testing::_)) + EXPECT_CALL(*taskManagerProvider_, make(testing::_, testing::_, kSeq + 1, testing::_)) .WillOnce(testing::Return(std::move(mockTaskManager))); EXPECT_CALL( @@ -534,21 +534,21 @@ TEST_F(ETLServiceTests, GiveUpWriterAfterWriteConflict) EXPECT_CALL(mockMonitorRef, run); // Set cache to be in sync with DB to avoid syncCacheWithDb loop - backend_->cache().update({}, kSEQ, false); + backend_->cache().update({}, kSeq, false); EXPECT_CALL(*backend_, hardFetchLedgerRange) - .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); - EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSEQ)); - EXPECT_CALL(*cacheLoader_, load(kSEQ)); + .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); + EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSeq)); + EXPECT_CALL(*cacheLoader_, load(kSeq)); service_.run(); systemState_->isWriting = true; writeCommandConnection_.disconnect(); systemState_->writeCommandSignal(etl::SystemState::WriteCommand::StopWriting); - EXPECT_CALL(*publisher_, publish(kSEQ + 1, testing::_, testing::_)); + EXPECT_CALL(*publisher_, publish(kSeq + 1, testing::_, testing::_)); ASSERT_TRUE(capturedCallback); - capturedCallback(kSEQ + 1); + capturedCallback(kSeq + 1); EXPECT_FALSE(systemState_->isWriting); // gives up writing } @@ -556,8 +556,8 @@ TEST_F(ETLServiceTests, GiveUpWriterAfterWriteConflict) TEST_F(ETLServiceTests, CancelledLoadInitialLedger) { EXPECT_CALL(*backend_, hardFetchLedgerRange).WillOnce(testing::Return(std::nullopt)); - EXPECT_CALL(*ledgers_, getMostRecent()).WillRepeatedly(testing::Return(kSEQ)); - EXPECT_CALL(*extractor_, extractLedgerOnly(kSEQ)).WillOnce(testing::Return(std::nullopt)); + EXPECT_CALL(*ledgers_, getMostRecent()).WillRepeatedly(testing::Return(kSeq)); + EXPECT_CALL(*extractor_, extractLedgerOnly(kSeq)).WillOnce(testing::Return(std::nullopt)); // These calls should not happen because loading the initial ledger fails EXPECT_CALL(*balancer_, loadInitialLedger(testing::_, testing::_, testing::_)).Times(0); @@ -572,7 +572,7 @@ TEST_F(ETLServiceTests, WaitForValidatedLedgerIsAbortedLeadToFailToLoadInitialLe testing::Sequence const s; EXPECT_CALL(*backend_, hardFetchLedgerRange).WillOnce(testing::Return(std::nullopt)); EXPECT_CALL(*ledgers_, getMostRecent()).InSequence(s).WillOnce(testing::Return(std::nullopt)); - EXPECT_CALL(*ledgers_, getMostRecent()).InSequence(s).WillOnce(testing::Return(kSEQ)); + EXPECT_CALL(*ledgers_, getMostRecent()).InSequence(s).WillOnce(testing::Return(kSeq)); // No other calls should happen because we exit early EXPECT_CALL(*extractor_, extractLedgerOnly).Times(0); @@ -585,20 +585,20 @@ TEST_F(ETLServiceTests, WaitForValidatedLedgerIsAbortedLeadToFailToLoadInitialLe TEST_F(ETLServiceTests, RunStopsIfInitialLoadIsCancelledByBalancer) { - constexpr uint32_t kMOCK_START_SEQUENCE = 123u; + constexpr uint32_t kMockStartSequence = 123u; systemState_->isStrictReadonly = false; testing::Sequence const s; EXPECT_CALL(*backend_, hardFetchLedgerRange).WillOnce(testing::Return(std::nullopt)); EXPECT_CALL(*ledgers_, getMostRecent) .InSequence(s) - .WillOnce(testing::Return(kMOCK_START_SEQUENCE)); + .WillOnce(testing::Return(kMockStartSequence)); EXPECT_CALL(*ledgers_, getMostRecent) .InSequence(s) - .WillOnce(testing::Return(kMOCK_START_SEQUENCE + 10)); + .WillOnce(testing::Return(kMockStartSequence + 10)); - auto const dummyLedgerData = createTestData(kMOCK_START_SEQUENCE); - EXPECT_CALL(*extractor_, extractLedgerOnly(kMOCK_START_SEQUENCE)) + auto const dummyLedgerData = createTestData(kMockStartSequence); + EXPECT_CALL(*extractor_, extractLedgerOnly(kMockStartSequence)) .WillOnce(testing::Return(dummyLedgerData)); EXPECT_CALL(*balancer_, loadInitialLedger(testing::_, testing::_, testing::_)) .WillOnce(testing::Return(std::unexpected{etl::InitialLedgerLoadError::Cancelled})); @@ -628,11 +628,11 @@ TEST_F(ETLServiceTests, DbStalledDoesNotTriggerSignalWhenStrictReadonly) EXPECT_CALL(mockMonitorRef, run); // Set cache to be in sync with DB to avoid syncCacheWithDb loop - backend_->cache().update({}, kSEQ, false); + backend_->cache().update({}, kSeq, false); EXPECT_CALL(*backend_, hardFetchLedgerRange) - .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); - EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSEQ)); - EXPECT_CALL(*cacheLoader_, load(kSEQ)); + .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); + EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSeq)); + EXPECT_CALL(*cacheLoader_, load(kSeq)); service_.run(); systemState_->isStrictReadonly = true; // strict readonly mode @@ -667,11 +667,11 @@ TEST_F(ETLServiceTests, DbStalledDoesNotTriggerSignalWhenAlreadyWriting) EXPECT_CALL(mockMonitorRef, run); // Set cache to be in sync with DB to avoid syncCacheWithDb loop - backend_->cache().update({}, kSEQ, false); + backend_->cache().update({}, kSeq, false); EXPECT_CALL(*backend_, hardFetchLedgerRange) - .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); - EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSEQ)); - EXPECT_CALL(*cacheLoader_, load(kSEQ)); + .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); + EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSeq)); + EXPECT_CALL(*cacheLoader_, load(kSeq)); service_.run(); systemState_->isStrictReadonly = false; @@ -704,33 +704,33 @@ TEST_F(ETLServiceTests, CacheUpdatesDependOnActualCacheState_WriterMode) EXPECT_CALL(mockMonitorRef, run); // Set cache to be in sync with DB initially to avoid syncCacheWithDb loop - backend_->cache().update({}, kSEQ, false); + backend_->cache().update({}, kSeq, false); EXPECT_CALL(*backend_, hardFetchLedgerRange) - .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); - EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSEQ)); - EXPECT_CALL(*cacheLoader_, load(kSEQ)); + .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); + EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSeq)); + EXPECT_CALL(*cacheLoader_, load(kSeq)); service_.run(); systemState_->isWriting = true; // In writer mode // Simulate cache is behind (e.g., update failed previously) - // Cache latestLedgerSequence returns kSEQ (behind the new seq kSEQ + 1) + // Cache latestLedgerSequence returns kSeq (behind the new seq kSeq + 1) std::vector const emptyObjs = {}; - backend_->cache().update(emptyObjs, kSEQ); // Set cache to kSEQ + backend_->cache().update(emptyObjs, kSeq); // Set cache to kSeq std::vector const dummyDiff = {}; - EXPECT_CALL(*backend_, fetchLedgerDiff(kSEQ + 1, testing::_)) + EXPECT_CALL(*backend_, fetchLedgerDiff(kSeq + 1, testing::_)) .WillOnce(testing::Return(dummyDiff)); // Cache should be updated even though we're in writer mode EXPECT_CALL( - *cacheUpdater_, update(kSEQ + 1, testing::A const&>()) + *cacheUpdater_, update(kSeq + 1, testing::A const&>()) ); - EXPECT_CALL(*publisher_, publish(kSEQ + 1, testing::_, testing::_)); + EXPECT_CALL(*publisher_, publish(kSeq + 1, testing::_, testing::_)); ASSERT_TRUE(capturedCallback); - capturedCallback(kSEQ + 1); + capturedCallback(kSeq + 1); } TEST_F(ETLServiceTests, OnlyCacheUpdatesWhenBackendIsCurrent) @@ -739,7 +739,7 @@ TEST_F(ETLServiceTests, OnlyCacheUpdatesWhenBackendIsCurrent) auto& mockMonitorRef = *mockMonitor; std::function capturedCallback; // Set cache to be in sync with DB initially to avoid syncCacheWithDb loop - backend_->cache().update({}, kSEQ, false); + backend_->cache().update({}, kSeq, false); EXPECT_CALL(*monitorProvider_, make).WillOnce([&mockMonitor](auto, auto, auto, auto, auto) { return std::move(mockMonitor); @@ -753,28 +753,28 @@ TEST_F(ETLServiceTests, OnlyCacheUpdatesWhenBackendIsCurrent) EXPECT_CALL(mockMonitorRef, run); EXPECT_CALL(*backend_, hardFetchLedgerRange) - .WillOnce(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); - EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSEQ)); - EXPECT_CALL(*cacheLoader_, load(kSEQ)); + .WillOnce(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); + EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSeq)); + EXPECT_CALL(*cacheLoader_, load(kSeq)); service_.run(); systemState_->isWriting = false; - // Cache is behind (at kSEQ) + // Cache is behind (at kSeq) std::vector const emptyObjs = {}; - backend_->cache().update(emptyObjs, kSEQ); + backend_->cache().update(emptyObjs, kSeq); std::vector const dummyDiff = {}; - EXPECT_CALL(*backend_, fetchLedgerDiff(kSEQ + 1, testing::_)) + EXPECT_CALL(*backend_, fetchLedgerDiff(kSeq + 1, testing::_)) .WillOnce(testing::Return(dummyDiff)); EXPECT_CALL( - *cacheUpdater_, update(kSEQ + 1, testing::A const&>()) + *cacheUpdater_, update(kSeq + 1, testing::A const&>()) ); - EXPECT_CALL(*publisher_, publish(kSEQ + 1, testing::_, testing::_)); + EXPECT_CALL(*publisher_, publish(kSeq + 1, testing::_, testing::_)); ASSERT_TRUE(capturedCallback); - capturedCallback(kSEQ + 1); + capturedCallback(kSeq + 1); } TEST_F(ETLServiceTests, NoUpdatesWhenBothCacheAndBackendAreCurrent) @@ -783,7 +783,7 @@ TEST_F(ETLServiceTests, NoUpdatesWhenBothCacheAndBackendAreCurrent) auto& mockMonitorRef = *mockMonitor; std::function capturedCallback; // Set cache to be in sync with DB initially to avoid syncCacheWithDb loop - backend_->cache().update({}, kSEQ, false); + backend_->cache().update({}, kSeq, false); EXPECT_CALL(*monitorProvider_, make).WillOnce([&mockMonitor](auto, auto, auto, auto, auto) { return std::move(mockMonitor); @@ -797,15 +797,15 @@ TEST_F(ETLServiceTests, NoUpdatesWhenBothCacheAndBackendAreCurrent) EXPECT_CALL(mockMonitorRef, run); EXPECT_CALL(*backend_, hardFetchLedgerRange) - .WillOnce(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); - EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSEQ)); - EXPECT_CALL(*cacheLoader_, load(kSEQ)); + .WillOnce(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); + EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSeq)); + EXPECT_CALL(*cacheLoader_, load(kSeq)); service_.run(); - // Cache is current (at kSEQ + 1) + // Cache is current (at kSeq + 1) std::vector const emptyObjs = {}; - backend_->cache().update(emptyObjs, kSEQ + 1); + backend_->cache().update(emptyObjs, kSeq + 1); // Neither should be updated EXPECT_CALL(*backend_, fetchLedgerDiff).Times(0); @@ -814,26 +814,26 @@ TEST_F(ETLServiceTests, NoUpdatesWhenBothCacheAndBackendAreCurrent) ) .Times(0); - EXPECT_CALL(*publisher_, publish(kSEQ + 1, testing::_, testing::_)); + EXPECT_CALL(*publisher_, publish(kSeq + 1, testing::_, testing::_)); ASSERT_TRUE(capturedCallback); - capturedCallback(kSEQ + 1); + capturedCallback(kSeq + 1); } TEST_F(ETLServiceTests, StopWaitsForWriteCommandHandlersToComplete) { auto mockMonitor = std::make_unique>(); // Set cache to be in sync with DB to avoid syncCacheWithDb loop - backend_->cache().update({}, kSEQ, false); + backend_->cache().update({}, kSeq, false); EXPECT_CALL(*monitorProvider_, make).WillOnce([&mockMonitor](auto, auto, auto, auto, auto) { return std::move(mockMonitor); }); EXPECT_CALL(*backend_, hardFetchLedgerRange) - .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); - EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSEQ)); - EXPECT_CALL(*cacheLoader_, load(kSEQ)); + .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); + EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSeq)); + EXPECT_CALL(*cacheLoader_, load(kSeq)); service_.run(); systemState_->isStrictReadonly = false; @@ -843,7 +843,7 @@ TEST_F(ETLServiceTests, StopWaitsForWriteCommandHandlersToComplete) EXPECT_CALL( mockWriteSignalCommandCallback_, Call(etl::SystemState::WriteCommand::StartWriting) ); - EXPECT_CALL(*taskManagerProvider_, make(testing::_, testing::_, kSEQ + 1, testing::_)) + EXPECT_CALL(*taskManagerProvider_, make(testing::_, testing::_, kSeq + 1, testing::_)) .WillOnce(testing::Return(std::move(mockTaskManager))); // Emit a command @@ -878,11 +878,11 @@ TEST_F(ETLServiceTests, WriteConflictIsHandledImmediately_NotDelayed) EXPECT_CALL(mockMonitorRef, run); // Set cache to be in sync with DB to avoid syncCacheWithDb loop - backend_->cache().update({}, kSEQ, false); + backend_->cache().update({}, kSeq, false); EXPECT_CALL(*backend_, hardFetchLedgerRange) - .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); - EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSEQ)); - EXPECT_CALL(*cacheLoader_, load(kSEQ)); + .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); + EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSeq)); + EXPECT_CALL(*cacheLoader_, load(kSeq)); service_.run(); systemState_->isWriting = true; @@ -905,11 +905,11 @@ TEST_F(ETLServiceTests, WriteCommandsAreSerializedOnStrand) }); // Set cache to be in sync with DB to avoid syncCacheWithDb loop - backend_->cache().update({}, kSEQ, false); + backend_->cache().update({}, kSeq, false); EXPECT_CALL(*backend_, hardFetchLedgerRange) - .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSEQ})); - EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSEQ)); - EXPECT_CALL(*cacheLoader_, load(kSEQ)); + .WillRepeatedly(testing::Return(data::LedgerRange{.minSequence = 1, .maxSequence = kSeq})); + EXPECT_CALL(*ledgers_, getMostRecent()).WillOnce(testing::Return(kSeq)); + EXPECT_CALL(*cacheLoader_, load(kSeq)); service_.run(); systemState_->isStrictReadonly = false; @@ -927,7 +927,7 @@ TEST_F(ETLServiceTests, WriteCommandsAreSerializedOnStrand) EXPECT_CALL( mockWriteSignalCommandCallback_, Call(etl::SystemState::WriteCommand::StartWriting) ); - EXPECT_CALL(*taskManagerProvider_, make(testing::_, testing::_, kSEQ + 1, testing::_)) + EXPECT_CALL(*taskManagerProvider_, make(testing::_, testing::_, kSeq + 1, testing::_)) .WillOnce(testing::Return(std::move(mockTaskManager1))); // Then StopWriting @@ -939,7 +939,7 @@ TEST_F(ETLServiceTests, WriteCommandsAreSerializedOnStrand) EXPECT_CALL( mockWriteSignalCommandCallback_, Call(etl::SystemState::WriteCommand::StartWriting) ); - EXPECT_CALL(*taskManagerProvider_, make(testing::_, testing::_, kSEQ + 1, testing::_)) + EXPECT_CALL(*taskManagerProvider_, make(testing::_, testing::_, kSeq + 1, testing::_)) .WillOnce(testing::Return(std::move(mockTaskManager2))); } diff --git a/tests/unit/etl/ETLStateTests.cpp b/tests/unit/etl/ETLStateTests.cpp index b49d74fd4..3db5702f6 100644 --- a/tests/unit/etl/ETLStateTests.cpp +++ b/tests/unit/etl/ETLStateTests.cpp @@ -8,7 +8,6 @@ #include -namespace json = boost::json; using namespace util; using namespace testing; @@ -26,7 +25,7 @@ TEST_F(ETLStateTest, Error) TEST_F(ETLStateTest, NetworkIdValid) { - auto const json = json::parse( + auto const json = boost::json::parse( R"JSON({ "result": { "info": { @@ -43,7 +42,7 @@ TEST_F(ETLStateTest, NetworkIdValid) TEST_F(ETLStateTest, NetworkIdInvalid) { - auto const json = json::parse( + auto const json = boost::json::parse( R"JSON({ "result": { "info": { @@ -60,7 +59,7 @@ TEST_F(ETLStateTest, NetworkIdInvalid) TEST_F(ETLStateTest, ResponseHasError) { - auto const json = json::parse( + auto const json = boost::json::parse( R"JSON({ "error": "error" })JSON" diff --git a/tests/unit/etl/ExtractionTests.cpp b/tests/unit/etl/ExtractionTests.cpp index 1f6d70f8a..230ae6eeb 100644 --- a/tests/unit/etl/ExtractionTests.cpp +++ b/tests/unit/etl/ExtractionTests.cpp @@ -4,6 +4,7 @@ #include "etl/Models.hpp" #include "etl/impl/Extraction.hpp" #include "util/BinaryTestObject.hpp" +#include "util/MockAmendmentBlockHandler.hpp" #include "util/MockAssert.hpp" #include "util/TestObject.hpp" @@ -22,14 +23,15 @@ #include #include #include +#include #include namespace { -constinit auto const kLEDGER_HASH = +constinit auto const kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constinit auto const kLEDGER_HASH2 = +constinit auto const kLedgerHasH2 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; -constinit auto const kSEQ = 30; +constinit auto const kSeq = 30; } // namespace struct ExtractionModelTests : virtual public ::testing::Test {}; @@ -38,16 +40,16 @@ TEST_F(ExtractionModelTests, LedgerDataCopyableAndEquatable) { auto const first = etl::model::LedgerData{ .transactions = - {util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_CREATE_OFFER)}, + {util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_CREATE_OFFER)}, .objects = {util::createObject(), util::createObject(), util::createObject()}, .successors = std::vector{{.firstBook = "first", .bookBase = "base"}}, .edgeKeys = std::vector{"key1", "key2"}, - .header = createLedgerHeader(kLEDGER_HASH, kSEQ, 1), + .header = createLedgerHeader(kLedgerHash, kSeq, 1), .rawHeader = {1, 2, 3}, - .seq = kSEQ + .seq = kSeq }; auto const second = first; @@ -77,7 +79,7 @@ TEST_F(ExtractionModelTests, LedgerDataCopyableAndEquatable) { auto third = second; third.header = createLedgerHeader( - kLEDGER_HASH2, kSEQ, 100 + kLedgerHasH2, kSeq, 100 ); // Using large age value to avoid flaky test EXPECT_NE(first, third); } @@ -88,18 +90,18 @@ TEST_F(ExtractionModelTests, LedgerDataCopyableAndEquatable) } { auto third = second; - third.seq = kSEQ - 1; + third.seq = kSeq - 1; EXPECT_NE(first, third); } } TEST_F(ExtractionModelTests, TransactionIsEquatable) { - auto const tx = std::vector{util::createTransaction(ripple::TxType::ttNFTOKEN_BURN)}; + auto const tx = std::vector{util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN)}; auto other = tx; EXPECT_EQ(tx, other); - other.push_back(util::createTransaction(ripple::TxType::ttNFTOKEN_ACCEPT_OFFER)); + other.push_back(util::createTransaction(xrpl::TxType::ttNFTOKEN_ACCEPT_OFFER)); EXPECT_NE(tx, other); } @@ -111,7 +113,7 @@ TEST_F(ExtractionModelTests, ObjectCopyableAndEquatable) { auto third = other; - third.key = ripple::uint256{42}; + third.key = xrpl::uint256{42}; EXPECT_NE(obj, third); } { @@ -181,15 +183,15 @@ TEST_F(ExtractionTests, OneTransaction) { using namespace etl::impl; - auto expected = util::createTransaction(ripple::TxType::ttNFTOKEN_CREATE_OFFER); + auto expected = util::createTransaction(xrpl::TxType::ttNFTOKEN_CREATE_OFFER); auto original = org::xrpl::rpc::v1::TransactionAndMetadata(); auto [metaRaw, txRaw] = util::createTxAndMetaBlobs(); original.set_transaction_blob(txRaw); original.set_metadata_blob(metaRaw); - auto res = extractTx(original, kSEQ); - EXPECT_EQ(res.meta.getLgrSeq(), kSEQ); + auto res = extractTx(original, kSeq); + EXPECT_EQ(res.meta.getLgrSeq(), kSeq); EXPECT_EQ(res.meta.getLgrSeq(), expected.meta.getLgrSeq()); EXPECT_EQ(res.meta.getTxID(), expected.meta.getTxID()); EXPECT_EQ(res.sttx.getTxnType(), expected.sttx.getTxnType()); @@ -199,7 +201,7 @@ TEST_F(ExtractionTests, MultipleTransactions) { using namespace etl::impl; - auto expected = util::createTransaction(ripple::TxType::ttNFTOKEN_CREATE_OFFER); + auto expected = util::createTransaction(xrpl::TxType::ttNFTOKEN_CREATE_OFFER); auto original = org::xrpl::rpc::v1::TransactionAndMetadata(); auto [metaRaw, txRaw] = util::createTxAndMetaBlobs(); @@ -212,11 +214,11 @@ TEST_F(ExtractionTests, MultipleTransactions) *p = original; } - auto res = extractTxs(list.transactions(), kSEQ); + auto res = extractTxs(list.transactions(), kSeq); EXPECT_EQ(res.size(), 10); for (auto const& tx : res) { - EXPECT_EQ(tx.meta.getLgrSeq(), kSEQ); + EXPECT_EQ(tx.meta.getLgrSeq(), kSeq); EXPECT_EQ(tx.meta.getLgrSeq(), expected.meta.getLgrSeq()); EXPECT_EQ(tx.meta.getTxID(), expected.meta.getTxID()); EXPECT_EQ(tx.sttx.getTxnType(), expected.sttx.getTxnType()); @@ -237,10 +239,10 @@ TEST_F(ExtractionTests, OneObject) ); auto res = extractObj(original); - EXPECT_EQ(ripple::strHex(res.key), ripple::strHex(expected.keyRaw)); - EXPECT_EQ(ripple::strHex(res.data), ripple::strHex(expected.dataRaw)); - EXPECT_EQ(res.predecessor, uint256ToString(data::kLAST_KEY)); - EXPECT_EQ(res.successor, uint256ToString(data::kFIRST_KEY)); + EXPECT_EQ(xrpl::strHex(res.key), xrpl::strHex(expected.keyRaw)); + EXPECT_EQ(xrpl::strHex(res.data), xrpl::strHex(expected.dataRaw)); + EXPECT_EQ(res.predecessor, uint256ToString(data::kLastKey)); + EXPECT_EQ(res.successor, uint256ToString(data::kFirstKey)); EXPECT_EQ(res.type, expected.type); } @@ -260,8 +262,8 @@ TEST_F(ExtractionTests, OneObjectWithSuccessorAndPredecessor) ); auto res = extractObj(original); - EXPECT_EQ(ripple::strHex(res.key), ripple::strHex(expected.keyRaw)); - EXPECT_EQ(ripple::strHex(res.data), ripple::strHex(expected.dataRaw)); + EXPECT_EQ(xrpl::strHex(res.key), xrpl::strHex(expected.keyRaw)); + EXPECT_EQ(xrpl::strHex(res.data), xrpl::strHex(expected.dataRaw)); EXPECT_EQ(res.predecessor, expected.predecessor); EXPECT_EQ(res.successor, expected.successor); EXPECT_EQ(res.type, expected.type); @@ -290,10 +292,10 @@ TEST_F(ExtractionTests, MultipleObjects) EXPECT_EQ(res.size(), 10); for (auto const& obj : res) { - EXPECT_EQ(ripple::strHex(obj.key), ripple::strHex(expected.keyRaw)); - EXPECT_EQ(ripple::strHex(obj.data), ripple::strHex(expected.dataRaw)); - EXPECT_EQ(obj.predecessor, uint256ToString(data::kLAST_KEY)); - EXPECT_EQ(obj.successor, uint256ToString(data::kFIRST_KEY)); + EXPECT_EQ(xrpl::strHex(obj.key), xrpl::strHex(expected.keyRaw)); + EXPECT_EQ(xrpl::strHex(obj.data), xrpl::strHex(expected.dataRaw)); + EXPECT_EQ(obj.predecessor, uint256ToString(data::kLastKey)); + EXPECT_EQ(obj.successor, uint256ToString(data::kFirstKey)); EXPECT_EQ(obj.type, expected.type); } } @@ -308,8 +310,8 @@ TEST_F(ExtractionTests, OneSuccessor) original.set_book_base(expected.bookBase); auto res = extractSuccessor(original); - EXPECT_EQ(ripple::strHex(res.firstBook), ripple::strHex(expected.firstBook)); - EXPECT_EQ(ripple::strHex(res.bookBase), ripple::strHex(expected.bookBase)); + EXPECT_EQ(xrpl::strHex(res.firstBook), xrpl::strHex(expected.firstBook)); + EXPECT_EQ(xrpl::strHex(res.bookBase), xrpl::strHex(expected.bookBase)); } TEST_F(ExtractionTests, MultipleSuccessors) @@ -370,20 +372,56 @@ struct MockFetcher : etl::LedgerFetcherInterface { struct ExtractorTests : ExtractionTests { std::shared_ptr fetcher = std::make_shared(); - etl::impl::Extractor extractor{fetcher}; + std::shared_ptr amendmentBlockHandler = + std::make_shared(); + etl::impl::Extractor extractor{fetcher, amendmentBlockHandler}; }; +inline etl::impl::PBLedgerResponseType +makeResponseWithUndeserializableTx() +{ + auto response = util::createData(); + auto& txs = *response.mutable_transactions_list(); + + auto blob = txs.transactions(0).transaction_blob(); + blob.at(1) = static_cast(0xff); + blob.at(2) = static_cast(0xff); + txs.mutable_transactions(0)->set_transaction_blob(std::move(blob)); + + return response; +} + TEST_F(ExtractorTests, ExtractLedgerWithDiffNoResult) { - EXPECT_CALL(*fetcher, fetchDataAndDiff(kSEQ)).WillOnce(testing::Return(std::nullopt)); - auto res = extractor.extractLedgerWithDiff(kSEQ); + EXPECT_CALL(*fetcher, fetchDataAndDiff(kSeq)).WillOnce(testing::Return(std::nullopt)); + auto res = extractor.extractLedgerWithDiff(kSeq); EXPECT_FALSE(res.has_value()); } TEST_F(ExtractorTests, ExtractLedgerOnlyNoResult) { - EXPECT_CALL(*fetcher, fetchData(kSEQ)).WillOnce(testing::Return(std::nullopt)); - auto res = extractor.extractLedgerOnly(kSEQ); + EXPECT_CALL(*fetcher, fetchData(kSeq)).WillOnce(testing::Return(std::nullopt)); + auto res = extractor.extractLedgerOnly(kSeq); + EXPECT_FALSE(res.has_value()); +} + +TEST_F(ExtractorTests, ExtractLedgerOnlyDeserializeFailureTriggersAmendmentBlock) +{ + EXPECT_CALL(*fetcher, fetchData(kSeq)) + .WillOnce(testing::Return(makeResponseWithUndeserializableTx())); + EXPECT_CALL(*amendmentBlockHandler, notifyAmendmentBlocked()).Times(1); + + auto const res = extractor.extractLedgerOnly(kSeq); + EXPECT_FALSE(res.has_value()); +} + +TEST_F(ExtractorTests, ExtractLedgerWithDiffDeserializeFailureTriggersAmendmentBlock) +{ + EXPECT_CALL(*fetcher, fetchDataAndDiff(kSeq)) + .WillOnce(testing::Return(makeResponseWithUndeserializableTx())); + EXPECT_CALL(*amendmentBlockHandler, notifyAmendmentBlocked()).Times(1); + + auto const res = extractor.extractLedgerWithDiff(kSeq); EXPECT_FALSE(res.has_value()); } @@ -391,8 +429,8 @@ TEST_F(ExtractorTests, ExtractLedgerWithDiffWithResult) { auto original = util::createDataAndDiff(); - EXPECT_CALL(*fetcher, fetchDataAndDiff(kSEQ)).WillOnce(testing::Return(original)); - auto res = extractor.extractLedgerWithDiff(kSEQ); + EXPECT_CALL(*fetcher, fetchDataAndDiff(kSeq)).WillOnce(testing::Return(original)); + auto res = extractor.extractLedgerWithDiff(kSeq); EXPECT_TRUE(res.has_value()); // NOLINTBEGIN(bugprone-unchecked-optional-access) @@ -408,8 +446,8 @@ TEST_F(ExtractorTests, ExtractLedgerOnlyWithResult) { auto original = util::createData(); - EXPECT_CALL(*fetcher, fetchData(kSEQ)).WillOnce(testing::Return(original)); - auto res = extractor.extractLedgerOnly(kSEQ); + EXPECT_CALL(*fetcher, fetchData(kSeq)).WillOnce(testing::Return(original)); + auto res = extractor.extractLedgerOnly(kSeq); EXPECT_TRUE(res.has_value()); // NOLINTBEGIN(bugprone-unchecked-optional-access) diff --git a/tests/unit/etl/GrpcSourceTests.cpp b/tests/unit/etl/GrpcSourceTests.cpp index 34d9cab5c..d378756e2 100644 --- a/tests/unit/etl/GrpcSourceTests.cpp +++ b/tests/unit/etl/GrpcSourceTests.cpp @@ -57,8 +57,8 @@ struct GrpcSourceTests : virtual public ::testing::Test, tests::util::WithMockXr } class KeyStore { - std::vector keys_; - using Store = std::map, std::greater<>>; + std::vector keys_; + using Store = std::map, std::greater<>>; util::Mutex store_; @@ -71,7 +71,7 @@ struct GrpcSourceTests : virtual public ::testing::Test, tests::util::WithMockXr auto store = store_.lock(); for (auto mi = 0uz; mi < markers.size(); ++mi) { for (auto i = 0uz; i < totalPerMarker; ++i) { - auto const mapKey = ripple::strHex(markers.at(mi)).substr(0, 2); + auto const mapKey = xrpl::strHex(markers.at(mi)).substr(0, 2); store->operator[](mapKey).push(keys_.at((mi * totalPerMarker) + i)); } } @@ -82,7 +82,7 @@ struct GrpcSourceTests : virtual public ::testing::Test, tests::util::WithMockXr { auto store = store_.lock(); - auto const mapKey = ripple::strHex(marker).substr(0, 2); + auto const mapKey = xrpl::strHex(marker).substr(0, 2); auto it = store->lower_bound(mapKey); ASSERT(it != store->end(), "Lower bound not found for '{}'", mapKey); @@ -101,7 +101,7 @@ struct GrpcSourceTests : virtual public ::testing::Test, tests::util::WithMockXr { auto store = store_.lock(); - auto const mapKey = ripple::strHex(marker).substr(0, 2); + auto const mapKey = xrpl::strHex(marker).substr(0, 2); auto it = store->lower_bound(mapKey); ASSERT(it != store->end(), "Lower bound not found for '{}'", mapKey); @@ -179,7 +179,7 @@ TEST_F(GrpcSourceLoadInitialLedgerTests, GetLedgerDataNotFound) TEST_F(GrpcSourceLoadInitialLedgerTests, ObserverCalledCorrectly) { - auto const key = ripple::uint256{4}; + auto const key = xrpl::uint256{4}; auto const keyStr = uint256ToString(key); auto const object = createTicketLedgerObject("rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", sequence_); auto const objectData = object.getSerializer().peekData(); @@ -349,7 +349,7 @@ TEST_F(GrpcSourceStopTests, LoadInitialLedgerStopsWhenRequested) TEST_F(GrpcSourceTests, DeadlineIsHandledCorrectly) { - static constexpr auto kDEADLINE = std::chrono::milliseconds{5}; + static constexpr auto kDeadline = std::chrono::milliseconds{5}; uint32_t const sequence = 123u; bool const getObjects = true; @@ -358,7 +358,7 @@ TEST_F(GrpcSourceTests, DeadlineIsHandledCorrectly) std::binary_semaphore sem(0); auto grpcSource = std::make_unique( - "localhost", std::to_string(getXRPLMockPort()), kDEADLINE + "localhost", std::to_string(getXRPLMockPort()), kDeadline ); // Note: this may not be called at all if gRPC cancels before it gets a chance to call the stub @@ -375,7 +375,7 @@ TEST_F(GrpcSourceTests, DeadlineIsHandledCorrectly) auto const [status, response] = grpcSource->fetchLedger(sequence, getObjects, getObjectNeighbors); - ASSERT_FALSE(status.ok()); // timed out after kDEADLINE + ASSERT_FALSE(status.ok()); // timed out after kDeadline sem.release(); // we don't need to hold GetLedger thread any longer grpcSource.reset(); diff --git a/tests/unit/etl/LedgerPublisherTests.cpp b/tests/unit/etl/LedgerPublisherTests.cpp index 90b7ba14a..798d14333 100644 --- a/tests/unit/etl/LedgerPublisherTests.cpp +++ b/tests/unit/etl/LedgerPublisherTests.cpp @@ -27,15 +27,15 @@ using namespace std::chrono; namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kSEQ = 30; -constexpr auto kAGE = 800; -constexpr auto kAMOUNT = 100; -constexpr auto kFEE = 3; -constexpr auto kFINAL_BALANCE = 110; -constexpr auto kFINAL_BALANCE2 = 30; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kSeq = 30; +constexpr auto kAge = 800; +constexpr auto kAmount = 100; +constexpr auto kFee = 3; +constexpr auto kFinalBalance = 110; +constexpr auto kFinalBalancE2 = 30; MATCHER_P(ledgerHeaderMatcher, expectedHeader, "Headers match") { @@ -53,19 +53,19 @@ struct ETLLedgerPublisherTest : util::prometheus::WithPrometheus, MockBackendTes TEST_F(ETLLedgerPublisherTest, PublishLedgerHeaderSkipDueToAge) { - // Use kAGE (800) which is > MAX_LEDGER_AGE_SECONDS (600) to test skipping - auto const dummyLedgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ, kAGE); + // Use kAge (800) which is > MAX_LEDGER_AGE_SECONDS (600) to test skipping + auto const dummyLedgerHeader = createLedgerHeader(kLedgerHash, kSeq, kAge); auto dummyState = etl::SystemState{}; auto publisher = impl::LedgerPublisher(ctx, backend_, mockSubscriptionManagerPtr, dummyState); - backend_->setRange(kSEQ - 1, kSEQ); + backend_->setRange(kSeq - 1, kSeq); publisher.publish(dummyLedgerHeader); // Verify last published sequence is set immediately auto const seq = publisher.getLastPublishedSequence(); ASSERT_TRUE(seq.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - EXPECT_EQ(seq.value(), kSEQ); + EXPECT_EQ(seq.value(), kSeq); // Since age > MAX_LEDGER_AGE_SECONDS, these should not be called EXPECT_CALL(*backend_, doFetchLedgerObject).Times(0); @@ -80,28 +80,28 @@ TEST_F(ETLLedgerPublisherTest, PublishLedgerHeaderSkipDueToAge) TEST_F(ETLLedgerPublisherTest, PublishLedgerHeaderWithinAgeLimit) { // Use age 0 which is < MAX_LEDGER_AGE_SECONDS to ensure publishing happens - auto const dummyLedgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ, 0); + auto const dummyLedgerHeader = createLedgerHeader(kLedgerHash, kSeq, 0); auto dummyState = etl::SystemState{}; auto publisher = impl::LedgerPublisher(ctx, backend_, mockSubscriptionManagerPtr, dummyState); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, kSeq, _)) .WillOnce(Return(createLegacyFeeSettingBlob(1, 2, 3, 4, 0))); - EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSEQ, _)) + EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSeq, _)) .WillOnce(Return(std::vector{})); EXPECT_CALL( - *mockSubscriptionManagerPtr, pubLedger(_, _, fmt::format("{}-{}", kSEQ - 1, kSEQ), 0) + *mockSubscriptionManagerPtr, pubLedger(_, _, fmt::format("{}-{}", kSeq - 1, kSeq), 0) ); EXPECT_CALL(*mockSubscriptionManagerPtr, pubBookChanges); - backend_->setRange(kSEQ - 1, kSEQ); + backend_->setRange(kSeq - 1, kSeq); publisher.publish(dummyLedgerHeader); // Verify last published sequence is set immediately auto const seq = publisher.getLastPublishedSequence(); ASSERT_TRUE(seq.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - EXPECT_EQ(seq.value(), kSEQ); + EXPECT_EQ(seq.value(), kSeq); ctx.join(); EXPECT_TRUE(publisher.lastPublishAgeSeconds() <= 1); @@ -111,14 +111,14 @@ TEST_F(ETLLedgerPublisherTest, PublishLedgerHeaderIsWritingTrue) { auto dummyState = etl::SystemState{}; dummyState.isWriting = true; - auto const dummyLedgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ, kAGE); + auto const dummyLedgerHeader = createLedgerHeader(kLedgerHash, kSeq, kAge); auto publisher = impl::LedgerPublisher(ctx, backend_, mockSubscriptionManagerPtr, dummyState); publisher.publish(dummyLedgerHeader); auto const seq = publisher.getLastPublishedSequence(); ASSERT_TRUE(seq.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - EXPECT_EQ(seq.value(), kSEQ); + EXPECT_EQ(seq.value(), kSeq); ctx.join(); @@ -130,28 +130,28 @@ TEST_F(ETLLedgerPublisherTest, PublishLedgerHeaderInRange) auto dummyState = etl::SystemState{}; dummyState.isWriting = true; - auto const dummyLedgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ, 0); // age is 0 + auto const dummyLedgerHeader = createLedgerHeader(kLedgerHash, kSeq, 0); // age is 0 auto publisher = impl::LedgerPublisher(ctx, backend_, mockSubscriptionManagerPtr, dummyState); - backend_->setRange(kSEQ - 1, kSEQ); + backend_->setRange(kSeq - 1, kSeq); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, kSeq, _)) .WillOnce(Return(createLegacyFeeSettingBlob(1, 2, 3, 4, 0))); TransactionAndMetadata t1; - t1.transaction = createPaymentTransactionObject(kACCOUNT, kACCOUNT2, kAMOUNT, kFEE, kSEQ) + t1.transaction = createPaymentTransactionObject(kAccount, kAccount2, kAmount, kFee, kSeq) .getSerializer() .peekData(); t1.metadata = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, kFINAL_BALANCE, kFINAL_BALANCE2) + createPaymentTransactionMetaObject(kAccount, kAccount2, kFinalBalance, kFinalBalancE2) .getSerializer() .peekData(); - t1.ledgerSequence = kSEQ; + t1.ledgerSequence = kSeq; EXPECT_CALL(*backend_, fetchAllTransactionsInLedger) .WillOnce(Return(std::vector{t1})); EXPECT_CALL( - *mockSubscriptionManagerPtr, pubLedger(_, _, fmt::format("{}-{}", kSEQ - 1, kSEQ), 1) + *mockSubscriptionManagerPtr, pubLedger(_, _, fmt::format("{}-{}", kSeq - 1, kSeq), 1) ); EXPECT_CALL(*mockSubscriptionManagerPtr, pubBookChanges); // mock 1 transaction @@ -161,7 +161,7 @@ TEST_F(ETLLedgerPublisherTest, PublishLedgerHeaderInRange) auto const seq = publisher.getLastPublishedSequence(); ASSERT_TRUE(seq.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - EXPECT_EQ(seq.value(), kSEQ); + EXPECT_EQ(seq.value(), kSeq); ctx.join(); @@ -173,34 +173,34 @@ TEST_F(ETLLedgerPublisherTest, PublishLedgerHeaderCloseTimeGreaterThanNow) auto dummyState = etl::SystemState{}; dummyState.isWriting = true; - auto dummyLedgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ, 0); + auto dummyLedgerHeader = createLedgerHeader(kLedgerHash, kSeq, 0); auto const nowPlus10 = system_clock::now() + seconds(10); auto const closeTime = - duration_cast(nowPlus10.time_since_epoch()).count() - kRIPPLE_EPOCH_START; - dummyLedgerHeader.closeTime = ripple::NetClock::time_point{seconds{closeTime}}; + duration_cast(nowPlus10.time_since_epoch()).count() - kRippleEpochStart; + dummyLedgerHeader.closeTime = xrpl::NetClock::time_point{seconds{closeTime}}; - backend_->setRange(kSEQ - 1, kSEQ); + backend_->setRange(kSeq - 1, kSeq); auto publisher = impl::LedgerPublisher(ctx, backend_, mockSubscriptionManagerPtr, dummyState); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, kSeq, _)) .WillOnce(Return(createLegacyFeeSettingBlob(1, 2, 3, 4, 0))); TransactionAndMetadata t1; - t1.transaction = createPaymentTransactionObject(kACCOUNT, kACCOUNT2, kAMOUNT, kFEE, kSEQ) + t1.transaction = createPaymentTransactionObject(kAccount, kAccount2, kAmount, kFee, kSeq) .getSerializer() .peekData(); t1.metadata = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, kFINAL_BALANCE, kFINAL_BALANCE2) + createPaymentTransactionMetaObject(kAccount, kAccount2, kFinalBalance, kFinalBalancE2) .getSerializer() .peekData(); - t1.ledgerSequence = kSEQ; + t1.ledgerSequence = kSeq; - EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSEQ, _)) + EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSeq, _)) .WillOnce(Return(std::vector{t1})); EXPECT_CALL( - *mockSubscriptionManagerPtr, pubLedger(_, _, fmt::format("{}-{}", kSEQ - 1, kSEQ), 1) + *mockSubscriptionManagerPtr, pubLedger(_, _, fmt::format("{}-{}", kSeq - 1, kSeq), 1) ); EXPECT_CALL(*mockSubscriptionManagerPtr, pubBookChanges); EXPECT_CALL(*mockSubscriptionManagerPtr, pubTransaction); @@ -209,7 +209,7 @@ TEST_F(ETLLedgerPublisherTest, PublishLedgerHeaderCloseTimeGreaterThanNow) auto const seq = publisher.getLastPublishedSequence(); ASSERT_TRUE(seq.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - EXPECT_EQ(seq.value(), kSEQ); + EXPECT_EQ(seq.value(), kSeq); ctx.join(); @@ -221,7 +221,7 @@ TEST_F(ETLLedgerPublisherTest, PublishLedgerSeqStopIsTrue) auto dummyState = etl::SystemState{}; auto publisher = impl::LedgerPublisher(ctx, backend_, mockSubscriptionManagerPtr, dummyState); publisher.stop(); - EXPECT_FALSE(publisher.publish(kSEQ, {})); + EXPECT_FALSE(publisher.publish(kSeq, {})); } TEST_F(ETLLedgerPublisherTest, PublishLedgerSeqMaxAttempt) @@ -229,12 +229,12 @@ TEST_F(ETLLedgerPublisherTest, PublishLedgerSeqMaxAttempt) auto dummyState = etl::SystemState{}; auto publisher = impl::LedgerPublisher(ctx, backend_, mockSubscriptionManagerPtr, dummyState); - static constexpr auto kMAX_ATTEMPT = 2; + static constexpr auto kMaxAttempt = 2; - LedgerRange const range{.minSequence = kSEQ - 1, .maxSequence = kSEQ - 1}; - EXPECT_CALL(*backend_, hardFetchLedgerRange).Times(kMAX_ATTEMPT).WillRepeatedly(Return(range)); + LedgerRange const range{.minSequence = kSeq - 1, .maxSequence = kSeq - 1}; + EXPECT_CALL(*backend_, hardFetchLedgerRange).Times(kMaxAttempt).WillRepeatedly(Return(range)); - EXPECT_FALSE(publisher.publish(kSEQ, kMAX_ATTEMPT, std::chrono::milliseconds{1})); + EXPECT_FALSE(publisher.publish(kSeq, kMaxAttempt, std::chrono::milliseconds{1})); } TEST_F(ETLLedgerPublisherTest, PublishLedgerSeqStopIsFalse) @@ -242,13 +242,13 @@ TEST_F(ETLLedgerPublisherTest, PublishLedgerSeqStopIsFalse) auto dummyState = etl::SystemState{}; auto publisher = impl::LedgerPublisher(ctx, backend_, mockSubscriptionManagerPtr, dummyState); - LedgerRange const range{.minSequence = kSEQ, .maxSequence = kSEQ}; + LedgerRange const range{.minSequence = kSeq, .maxSequence = kSeq}; EXPECT_CALL(*backend_, hardFetchLedgerRange).WillOnce(Return(range)); - auto const dummyLedgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ, kAGE); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kSEQ, _)).WillOnce(Return(dummyLedgerHeader)); + auto const dummyLedgerHeader = createLedgerHeader(kLedgerHash, kSeq, kAge); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kSeq, _)).WillOnce(Return(dummyLedgerHeader)); - EXPECT_TRUE(publisher.publish(kSEQ, {})); + EXPECT_TRUE(publisher.publish(kSeq, {})); ctx.join(); } @@ -257,40 +257,40 @@ TEST_F(ETLLedgerPublisherTest, PublishMultipleTxInOrder) auto dummyState = etl::SystemState{}; dummyState.isWriting = true; - auto const dummyLedgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ, 0); // age is 0 + auto const dummyLedgerHeader = createLedgerHeader(kLedgerHash, kSeq, 0); // age is 0 auto publisher = impl::LedgerPublisher(ctx, backend_, mockSubscriptionManagerPtr, dummyState); - backend_->setRange(kSEQ - 1, kSEQ); + backend_->setRange(kSeq - 1, kSeq); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, kSeq, _)) .WillOnce(Return(createLegacyFeeSettingBlob(1, 2, 3, 4, 0))); // t1 index > t2 index TransactionAndMetadata t1; - t1.transaction = createPaymentTransactionObject(kACCOUNT, kACCOUNT2, kAMOUNT, kFEE, kSEQ) + t1.transaction = createPaymentTransactionObject(kAccount, kAccount2, kAmount, kFee, kSeq) .getSerializer() .peekData(); t1.metadata = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, kFINAL_BALANCE, kFINAL_BALANCE2, 2) + createPaymentTransactionMetaObject(kAccount, kAccount2, kFinalBalance, kFinalBalancE2, 2) .getSerializer() .peekData(); - t1.ledgerSequence = kSEQ; + t1.ledgerSequence = kSeq; t1.date = 1; TransactionAndMetadata t2; - t2.transaction = createPaymentTransactionObject(kACCOUNT, kACCOUNT2, kAMOUNT, kFEE, kSEQ) + t2.transaction = createPaymentTransactionObject(kAccount, kAccount2, kAmount, kFee, kSeq) .getSerializer() .peekData(); t2.metadata = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, kFINAL_BALANCE, kFINAL_BALANCE2, 1) + createPaymentTransactionMetaObject(kAccount, kAccount2, kFinalBalance, kFinalBalancE2, 1) .getSerializer() .peekData(); - t2.ledgerSequence = kSEQ; + t2.ledgerSequence = kSeq; t2.date = 2; - EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSEQ, _)) + EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSeq, _)) .WillOnce(Return(std::vector{t1, t2})); EXPECT_CALL( - *mockSubscriptionManagerPtr, pubLedger(_, _, fmt::format("{}-{}", kSEQ - 1, kSEQ), 2) + *mockSubscriptionManagerPtr, pubLedger(_, _, fmt::format("{}-{}", kSeq - 1, kSeq), 2) ); EXPECT_CALL(*mockSubscriptionManagerPtr, pubBookChanges); @@ -302,7 +302,7 @@ TEST_F(ETLLedgerPublisherTest, PublishMultipleTxInOrder) auto const seq = publisher.getLastPublishedSequence(); ASSERT_TRUE(seq.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - EXPECT_EQ(seq.value(), kSEQ); + EXPECT_EQ(seq.value(), kSeq); ctx.join(); @@ -315,9 +315,9 @@ TEST_F(ETLLedgerPublisherTest, PublishVeryOldLedgerShouldSkip) dummyState.isWriting = true; // Create a ledger header with age (800) greater than MAX_LEDGER_AGE_SECONDS (600) - auto const dummyLedgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ, 800); + auto const dummyLedgerHeader = createLedgerHeader(kLedgerHash, kSeq, 800); auto publisher = impl::LedgerPublisher(ctx, backend_, mockSubscriptionManagerPtr, dummyState); - backend_->setRange(kSEQ - 1, kSEQ); + backend_->setRange(kSeq - 1, kSeq); EXPECT_CALL(*mockSubscriptionManagerPtr, pubLedger).Times(0); EXPECT_CALL(*mockSubscriptionManagerPtr, pubBookChanges).Times(0); @@ -327,7 +327,7 @@ TEST_F(ETLLedgerPublisherTest, PublishVeryOldLedgerShouldSkip) auto const seq = publisher.getLastPublishedSequence(); ASSERT_TRUE(seq.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - EXPECT_EQ(seq.value(), kSEQ); + EXPECT_EQ(seq.value(), kSeq); ctx.join(); } @@ -337,19 +337,19 @@ TEST_F(ETLLedgerPublisherTest, PublishMultipleLedgersInQuickSuccession) auto dummyState = etl::SystemState{}; dummyState.isWriting = true; - auto const dummyLedgerHeader1 = createLedgerHeader(kLEDGER_HASH, kSEQ, 0); - auto const dummyLedgerHeader2 = createLedgerHeader(kLEDGER_HASH, kSEQ + 1, 0); + auto const dummyLedgerHeader1 = createLedgerHeader(kLedgerHash, kSeq, 0); + auto const dummyLedgerHeader2 = createLedgerHeader(kLedgerHash, kSeq + 1, 0); auto publisher = impl::LedgerPublisher(ctx, backend_, mockSubscriptionManagerPtr, dummyState); - backend_->setRange(kSEQ - 1, kSEQ + 1); + backend_->setRange(kSeq - 1, kSeq + 1); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, kSeq, _)) .WillOnce(Return(createLegacyFeeSettingBlob(1, 2, 3, 4, 0))); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, kSEQ + 1, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, kSeq + 1, _)) .WillOnce(Return(createLegacyFeeSettingBlob(1, 2, 3, 4, 0))); - EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSEQ, _)) + EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSeq, _)) .WillOnce(Return(std::vector{})); - EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSEQ + 1, _)) + EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSeq + 1, _)) .WillOnce(Return(std::vector{})); Sequence const s; @@ -377,7 +377,7 @@ TEST_F(ETLLedgerPublisherTest, PublishMultipleLedgersInQuickSuccession) auto const seq = publisher.getLastPublishedSequence(); ASSERT_TRUE(seq.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - EXPECT_EQ(seq.value(), kSEQ + 1); + EXPECT_EQ(seq.value(), kSeq + 1); ctx.join(); } diff --git a/tests/unit/etl/LoadBalancerTests.cpp b/tests/unit/etl/LoadBalancerTests.cpp index 7034ea7dc..243c27616 100644 --- a/tests/unit/etl/LoadBalancerTests.cpp +++ b/tests/unit/etl/LoadBalancerTests.cpp @@ -48,7 +48,7 @@ using namespace util::prometheus; namespace { -constinit auto const kTWO_SOURCES_LEDGER_RESPONSE = R"JSON({ +constinit auto const kTwoSourcesLedgerResponse = R"JSON({ "etl_sources": [ { "ip": "127.0.0.1", @@ -63,7 +63,7 @@ constinit auto const kTWO_SOURCES_LEDGER_RESPONSE = R"JSON({ ] })JSON"; -constinit auto const kTHREE_SOURCES_LEDGER_RESPONSE = R"JSON({ +constinit auto const kThreeSourcesLedgerResponse = R"JSON({ "etl_sources": [ { "ip": "127.0.0.1", @@ -156,7 +156,7 @@ protected: StrictMockNetworkValidatedLedgersPtr networkManager_; StrictMockSourceFactory sourceFactory_{2}; boost::asio::io_context ioContext_; - boost::json::value configJson_ = boost::json::parse(kTWO_SOURCES_LEDGER_RESPONSE); + boost::json::value configJson_ = boost::json::parse(kTwoSourcesLedgerResponse); }; TEST_F(LoadBalancerConstructorTests, construct) @@ -429,7 +429,7 @@ struct LoadBalancer3SourcesTests : LoadBalancerConstructorTests { LoadBalancer3SourcesTests() { sourceFactory_.setSourcesNumber(3); - configJson_ = boost::json::parse(kTHREE_SOURCES_LEDGER_RESPONSE); + configJson_ = boost::json::parse(kThreeSourcesLedgerResponse); EXPECT_CALL(sourceFactory_, makeSource).Times(3); EXPECT_CALL(sourceFactory_.sourceAt(0), forwardToRippled) @@ -684,9 +684,7 @@ TEST_F(LoadBalancerForwardToRippledTests, forward) auto loadBalancer = makeLoadBalancer(); EXPECT_CALL( sourceFactory_.sourceAt(0), - forwardToRippled( - request_, clientIP_, LoadBalancer::kADMIN_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request_, clientIP_, LoadBalancer::kAdminForwardingXUserValue, testing::_) ) .WillOnce(Return(response_)); @@ -701,9 +699,7 @@ TEST_F(LoadBalancerForwardToRippledTests, forwardWithXUserHeader) auto loadBalancer = makeLoadBalancer(); EXPECT_CALL( sourceFactory_.sourceAt(0), - forwardToRippled( - request_, clientIP_, LoadBalancer::kUSER_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request_, clientIP_, LoadBalancer::kUserForwardingXUserValue, testing::_) ) .WillOnce(Return(response_)); @@ -718,16 +714,12 @@ TEST_F(LoadBalancerForwardToRippledTests, source0Fails) auto loadBalancer = makeLoadBalancer(); EXPECT_CALL( sourceFactory_.sourceAt(0), - forwardToRippled( - request_, clientIP_, LoadBalancer::kUSER_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request_, clientIP_, LoadBalancer::kUserForwardingXUserValue, testing::_) ) .WillOnce(Return(std::unexpected{rpc::ClioError::EtlConnectionError})); EXPECT_CALL( sourceFactory_.sourceAt(1), - forwardToRippled( - request_, clientIP_, LoadBalancer::kUSER_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request_, clientIP_, LoadBalancer::kUserForwardingXUserValue, testing::_) ) .WillOnce(Return(response_)); @@ -758,9 +750,7 @@ TEST_F(LoadBalancerForwardToRippledPrometheusTests, forwardingCacheEnabled) EXPECT_CALL( sourceFactory_.sourceAt(0), - forwardToRippled( - request, clientIP_, LoadBalancer::kUSER_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request, clientIP_, LoadBalancer::kUserForwardingXUserValue, testing::_) ) .WillOnce(Return(response_)); @@ -772,6 +762,42 @@ TEST_F(LoadBalancerForwardToRippledPrometheusTests, forwardingCacheEnabled) }); } +TEST_F(LoadBalancerForwardToRippledPrometheusTests, forwardingCacheBypassedForNonBareRequest) +{ + configJson_.as_object()["forwarding"] = boost::json::object{{"cache_timeout", 10.}}; + EXPECT_CALL(sourceFactory_, makeSource).Times(2); + auto loadBalancer = makeLoadBalancer(); + + auto const nonBareRequest = boost::json::object{{"command", "server_info"}, {"counters", true}}; + + auto& cacheHitCounter = makeMock("forwarding_cache_hit_counter", ""); + auto& cacheMissCounter = makeMock("forwarding_cache_miss_counter", ""); + auto& successDurationCounter = + makeMock("forwarding_duration_milliseconds_counter", "{status=\"success\"}"); + + EXPECT_CALL(cacheMissCounter, add(1)).Times(2); + EXPECT_CALL(cacheHitCounter, add(testing::_)).Times(0); + EXPECT_CALL(successDurationCounter, add(testing::_)).Times(2); + + EXPECT_CALL( + sourceFactory_.sourceAt(0), + forwardToRippled( + nonBareRequest, clientIP_, LoadBalancer::kUserForwardingXUserValue, testing::_ + ) + ) + .Times(2) + .WillRepeatedly(Return(response_)); + + runSpawn([&](boost::asio::yield_context yield) { + EXPECT_EQ( + loadBalancer->forwardToRippled(nonBareRequest, clientIP_, false, yield), response_ + ); + EXPECT_EQ( + loadBalancer->forwardToRippled(nonBareRequest, clientIP_, false, yield), response_ + ); + }); +} + TEST_F(LoadBalancerForwardToRippledPrometheusTests, source0Fails) { EXPECT_CALL(sourceFactory_, makeSource).Times(2); @@ -791,16 +817,12 @@ TEST_F(LoadBalancerForwardToRippledPrometheusTests, source0Fails) EXPECT_CALL( sourceFactory_.sourceAt(0), - forwardToRippled( - request_, clientIP_, LoadBalancer::kUSER_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request_, clientIP_, LoadBalancer::kUserForwardingXUserValue, testing::_) ) .WillOnce(Return(std::unexpected{rpc::ClioError::EtlConnectionError})); EXPECT_CALL( sourceFactory_.sourceAt(1), - forwardToRippled( - request_, clientIP_, LoadBalancer::kUSER_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request_, clientIP_, LoadBalancer::kUserForwardingXUserValue, testing::_) ) .WillOnce(Return(response_)); @@ -826,9 +848,7 @@ TEST_F(LoadBalancerForwardToRippledPrometheusTests, adminRequestAlwaysCacheMiss) EXPECT_CALL( sourceFactory_.sourceAt(0), - forwardToRippled( - request, clientIP_, LoadBalancer::kADMIN_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request, clientIP_, LoadBalancer::kAdminForwardingXUserValue, testing::_) ) .Times(2) .WillRepeatedly(Return(response_)); @@ -885,7 +905,7 @@ INSTANTIATE_TEST_SUITE_P( rpc::ClioError::EtlInvalidResponse } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(LoadBalancerForwardToRippledErrorTests, bothSourcesFail) @@ -894,16 +914,12 @@ TEST_P(LoadBalancerForwardToRippledErrorTests, bothSourcesFail) auto loadBalancer = makeLoadBalancer(); EXPECT_CALL( sourceFactory_.sourceAt(0), - forwardToRippled( - request_, clientIP_, LoadBalancer::kUSER_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request_, clientIP_, LoadBalancer::kUserForwardingXUserValue, testing::_) ) .WillOnce(Return(std::unexpected{GetParam().firstSourceError})); EXPECT_CALL( sourceFactory_.sourceAt(1), - forwardToRippled( - request_, clientIP_, LoadBalancer::kUSER_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request_, clientIP_, LoadBalancer::kUserForwardingXUserValue, testing::_) ) .WillOnce(Return(std::unexpected{GetParam().secondSourceError})); @@ -924,9 +940,7 @@ TEST_F(LoadBalancerForwardToRippledTests, forwardingCacheEnabled) EXPECT_CALL( sourceFactory_.sourceAt(0), - forwardToRippled( - request, clientIP_, LoadBalancer::kUSER_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request, clientIP_, LoadBalancer::kUserForwardingXUserValue, testing::_) ) .WillOnce(Return(response_)); @@ -946,9 +960,7 @@ TEST_F(LoadBalancerForwardToRippledTests, adminRequestBypassesForwardingCache) EXPECT_CALL( sourceFactory_.sourceAt(0), - forwardToRippled( - request, clientIP_, LoadBalancer::kADMIN_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request, clientIP_, LoadBalancer::kAdminForwardingXUserValue, testing::_) ) .Times(2) .WillRepeatedly(Return(response_)); @@ -969,16 +981,12 @@ TEST_F(LoadBalancerForwardToRippledTests, adminResponseNotCachedForSubsequentUse EXPECT_CALL( sourceFactory_.sourceAt(0), - forwardToRippled( - request, clientIP_, LoadBalancer::kADMIN_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request, clientIP_, LoadBalancer::kAdminForwardingXUserValue, testing::_) ) .WillOnce(Return(response_)); EXPECT_CALL( sourceFactory_.sourceAt(0), - forwardToRippled( - request, clientIP_, LoadBalancer::kUSER_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request, clientIP_, LoadBalancer::kUserForwardingXUserValue, testing::_) ) .WillOnce(Return(response_)); @@ -1008,16 +1016,12 @@ TEST_F(LoadBalancerForwardToRippledTests, onLedgerClosedHookInvalidatesCache) EXPECT_CALL( sourceFactory_.sourceAt(0), - forwardToRippled( - request, clientIP_, LoadBalancer::kUSER_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request, clientIP_, LoadBalancer::kUserForwardingXUserValue, testing::_) ) .WillOnce(Return(response_)); EXPECT_CALL( sourceFactory_.sourceAt(1), - forwardToRippled( - request, clientIP_, LoadBalancer::kUSER_FORWARDING_X_USER_VALUE, testing::_ - ) + forwardToRippled(request, clientIP_, LoadBalancer::kUserForwardingXUserValue, testing::_) ) .WillOnce(Return(boost::json::object{})); diff --git a/tests/unit/etl/LoadingTests.cpp b/tests/unit/etl/LoadingTests.cpp index 747aa5746..9926dd4cd 100644 --- a/tests/unit/etl/LoadingTests.cpp +++ b/tests/unit/etl/LoadingTests.cpp @@ -29,9 +29,9 @@ using namespace data; namespace { -constinit auto const kLEDGER_HASH = +constinit auto const kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constinit auto const kSEQ = 30; +constinit auto const kSeq = 30; struct MockRegistry : etl::RegistryInterface { MOCK_METHOD( @@ -67,7 +67,7 @@ struct LoadingAssertTest : common::util::WithMockAssert, LoadingTests {}; auto createTestData() { - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); return LedgerData{ .transactions = {}, .objects = {util::createObject(), util::createObject(), util::createObject()}, @@ -75,7 +75,7 @@ createTestData() .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq }; } @@ -129,9 +129,9 @@ TEST_F(LoadingTests, OnInitialLoadGotMoreObjectsWithKey) auto const data = createTestData(); auto const lastKey = std::make_optional("something"); - EXPECT_CALL(*mockRegistryPtr_, dispatchInitialObjects(kSEQ, data.objects, lastKey->data())); + EXPECT_CALL(*mockRegistryPtr_, dispatchInitialObjects(kSeq, data.objects, lastKey->data())); - loader_.onInitialLoadGotMoreObjects(kSEQ, data.objects, lastKey); + loader_.onInitialLoadGotMoreObjects(kSeq, data.objects, lastKey); } TEST_F(LoadingTests, OnInitialLoadGotMoreObjectsWithoutKey) @@ -139,9 +139,9 @@ TEST_F(LoadingTests, OnInitialLoadGotMoreObjectsWithoutKey) auto const data = createTestData(); auto const lastKey = std::optional{}; - EXPECT_CALL(*mockRegistryPtr_, dispatchInitialObjects(kSEQ, data.objects, std::string{})); + EXPECT_CALL(*mockRegistryPtr_, dispatchInitialObjects(kSeq, data.objects, std::string{})); - loader_.onInitialLoadGotMoreObjects(kSEQ, data.objects, lastKey); + loader_.onInitialLoadGotMoreObjects(kSeq, data.objects, lastKey); } TEST_F(LoadingTests, OnInitialLoadGotMoreObjectsFailure) @@ -149,11 +149,11 @@ TEST_F(LoadingTests, OnInitialLoadGotMoreObjectsFailure) auto const data = createTestData(); auto const lastKey = std::optional{}; - EXPECT_CALL(*mockRegistryPtr_, dispatchInitialObjects(kSEQ, data.objects, std::string{})) + EXPECT_CALL(*mockRegistryPtr_, dispatchInitialObjects(kSeq, data.objects, std::string{})) .WillOnce([](auto, auto, auto) { throw std::runtime_error("some error"); }); EXPECT_CALL(*mockAmendmentBlockHandlerPtr_, notifyAmendmentBlocked()); - loader_.onInitialLoadGotMoreObjects(kSEQ, data.objects, lastKey); + loader_.onInitialLoadGotMoreObjects(kSeq, data.objects, lastKey); } TEST_F(LoadingTests, LoadInitialLedgerFailure) @@ -175,7 +175,7 @@ TEST_F(LoadingTests, LoadInitialLedgerFailure) TEST_F(LoadingAssertTest, LoadInitialLedgerHasDataInDB) { auto const data = createTestData(); - auto const range = LedgerRange{.minSequence = kSEQ - 1, .maxSequence = kSEQ}; + auto const range = LedgerRange{.minSequence = kSeq - 1, .maxSequence = kSeq}; // backend_ leaks due to death test. would be nice to figure out a better solution but for now // we simply don't set expectations and allow the mock to leak diff --git a/tests/unit/etl/MPTHelpersTests.cpp b/tests/unit/etl/MPTHelpersTests.cpp new file mode 100644 index 000000000..5ea6ab482 --- /dev/null +++ b/tests/unit/etl/MPTHelpersTests.cpp @@ -0,0 +1,453 @@ +#include "data/DBHelpers.hpp" +#include "etl/MPTHelpers.hpp" +#include "util/MPTokenTestObjects.hpp" +#include "util/TestObject.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace { + +constexpr auto kAccount = "rM2AGCCCRb373FRuD8wHyUwUsh2dV4BW5Q"; +constexpr auto kAccount2 = "rnd1nHuzceyQDqnLH8urWNr4QBKt4v7WVk"; +constexpr auto kIssuer = "rK1EX542EgA9m948JrJRaEzwLVEhqWvnr9"; +constexpr auto kTX = "13F1A95D7AAB7108D5CE7EEAF504B2894B8C674E6D68499076441C4837282BF8"; +constexpr std::uint32_t kIssuanceSeq = 7; +constexpr std::uint32_t kLedgerSeq = 99; +constexpr std::uint32_t kTxIndex = 4; + +xrpl::Slice const kSlice("test", 4); + +xrpl::uint192 +defaultIssuanceID() +{ + return xrpl::makeMptID(kIssuanceSeq, getAccountIdWithString(kIssuer)); +} + +xrpl::STObject +createAccountRootNode(std::string_view account) +{ + xrpl::STObject fields(xrpl::sfFinalFields); + fields.setAccountID(xrpl::sfAccount, getAccountIdWithString(account)); + + xrpl::STObject node(xrpl::sfModifiedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltACCOUNT_ROOT); + node.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{}); + node.set(std::move(fields)); + return node; +} + +xrpl::STObject +createMPTokenNodeWithoutIssuanceID() +{ + xrpl::STObject fields(xrpl::sfFinalFields); + fields.setAccountID(xrpl::sfAccount, getAccountIdWithString(kAccount)); + + xrpl::STObject node(xrpl::sfModifiedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltMPTOKEN); + node.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{}); + node.set(std::move(fields)); + return node; +} + +xrpl::STObject +createMPTokenIssuanceNodeWithoutIssuer() +{ + xrpl::STObject fields(xrpl::sfFinalFields); + fields.setFieldU32(xrpl::sfSequence, kIssuanceSeq); + + xrpl::STObject node(xrpl::sfModifiedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltMPTOKEN_ISSUANCE); + node.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{}); + node.set(std::move(fields)); + return node; +} + +xrpl::TxMeta +createTxMeta(std::vector nodes, int result = xrpl::tesSUCCESS) +{ + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + metaObj.setFieldU8(xrpl::sfTransactionResult, result); + metaObj.setFieldU32(xrpl::sfTransactionIndex, kTxIndex); + + xrpl::STArray affectedNodes(xrpl::sfAffectedNodes); + for (auto& node : nodes) + affectedNodes.push_back(std::move(node)); + metaObj.setFieldArray(xrpl::sfAffectedNodes, affectedNodes); + + return xrpl::TxMeta{xrpl::uint256(kTX), kLedgerSeq, metaObj.getSerializer().peekData()}; +} + +xrpl::STTx +createTx(xrpl::TxType type) +{ + xrpl::STObject obj(xrpl::sfTransaction); + obj.setFieldU16(xrpl::sfTransactionType, type); + obj.setAccountID(xrpl::sfAccount, getAccountIdWithString(kAccount)); + obj.setFieldAmount(xrpl::sfFee, xrpl::STAmount(10, false)); + obj.setFieldU32(xrpl::sfSequence, 1); + obj.setFieldVL(xrpl::sfSigningPubKey, kSlice); + + // Satisfy the per-type required fields of the SOTemplate + switch (type) { + case xrpl::ttPAYMENT: + obj.setFieldAmount(xrpl::sfAmount, xrpl::STAmount(100, false)); + obj.setAccountID(xrpl::sfDestination, getAccountIdWithString(kAccount2)); + break; + case xrpl::ttCLAWBACK: + obj.setFieldAmount(xrpl::sfAmount, xrpl::STAmount(100, false)); + break; + case xrpl::ttOFFER_CREATE: + obj.setFieldAmount(xrpl::sfTakerPays, xrpl::STAmount(100, false)); + obj.setFieldAmount(xrpl::sfTakerGets, xrpl::STAmount(200, false)); + break; + case xrpl::ttAMM_DEPOSIT: + obj.setFieldIssue(xrpl::sfAsset, xrpl::STIssue{xrpl::sfAsset, xrpl::xrpIssue()}); + obj.setFieldIssue(xrpl::sfAsset2, xrpl::STIssue{xrpl::sfAsset2, xrpl::xrpIssue()}); + break; + case xrpl::ttMPTOKEN_ISSUANCE_DESTROY: + case xrpl::ttMPTOKEN_ISSUANCE_SET: + obj[xrpl::sfMPTokenIssuanceID] = defaultIssuanceID(); + break; + default: + break; + } + + auto const serialized = obj.getSerializer(); + return xrpl::STTx{xrpl::SerialIter{serialized.slice()}}; +} + +xrpl::STTx +createPaymentTxWithMPTAmount(xrpl::uint192 const& issuanceID) +{ + xrpl::STObject obj(xrpl::sfTransaction); + obj.setFieldU16(xrpl::sfTransactionType, xrpl::ttPAYMENT); + obj.setAccountID(xrpl::sfAccount, getAccountIdWithString(kAccount)); + obj.setFieldAmount( + xrpl::sfAmount, xrpl::STAmount(xrpl::MPTAmount{100}, xrpl::MPTIssue{issuanceID}) + ); + obj.setFieldAmount(xrpl::sfFee, xrpl::STAmount(10, false)); + obj.setAccountID(xrpl::sfDestination, getAccountIdWithString(kAccount2)); + obj.setFieldU32(xrpl::sfSequence, 1); + obj.setFieldVL(xrpl::sfSigningPubKey, kSlice); + + auto const serialized = obj.getSerializer(); + return xrpl::STTx{xrpl::SerialIter{serialized.slice()}}; +} + +xrpl::STTx +createAMMDepositTxWithMPTIssue(xrpl::uint192 const& issuanceID) +{ + xrpl::STObject obj(xrpl::sfTransaction); + obj.setFieldU16(xrpl::sfTransactionType, xrpl::ttAMM_DEPOSIT); + obj.setAccountID(xrpl::sfAccount, getAccountIdWithString(kAccount)); + obj.setFieldAmount(xrpl::sfFee, xrpl::STAmount(10, false)); + obj.setFieldU32(xrpl::sfSequence, 1); + obj.setFieldVL(xrpl::sfSigningPubKey, kSlice); + obj.setFieldIssue(xrpl::sfAsset, xrpl::STIssue{xrpl::sfAsset, xrpl::MPTIssue{issuanceID}}); + obj.setFieldIssue(xrpl::sfAsset2, xrpl::STIssue{xrpl::sfAsset2, xrpl::xrpIssue()}); + + auto const serialized = obj.getSerializer(); + return xrpl::STTx{xrpl::SerialIter{serialized.slice()}}; +} + +} // namespace + +struct MPTHelpersTest : virtual public ::testing::Test { +protected: + static void + verifyCommonFields( + MPTokenIssuanceTransactionsData const& data, + xrpl::STTx const& sttx, + xrpl::TxMeta const& txMeta + ) + { + EXPECT_EQ(data.accounts, txMeta.getAffectedAccounts()); + EXPECT_EQ(data.ledgerSequence, txMeta.getLgrSeq()); + EXPECT_EQ(data.transactionIndex, txMeta.getIndex()); + EXPECT_EQ(data.txHash, sttx.getTransactionID()); + } +}; + +TEST_F(MPTHelpersTest, FailedTxWithoutIssuanceReferenceProducesNoRecords) +{ + std::vector nodes; + auto const txMeta = createTxMeta(std::move(nodes), xrpl::tecINCOMPLETE); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, createTx(xrpl::ttPAYMENT)); + + EXPECT_TRUE(records.empty()); +} + +TEST_F(MPTHelpersTest, FailedTxIgnoresMPTAffectedNodes) +{ + std::vector nodes; + nodes.push_back(util::createMPTokenIssuanceNode(xrpl::sfModifiedNode, kIssuanceSeq, kIssuer)); + nodes.push_back(util::createMPTokenNode(xrpl::sfCreatedNode, defaultIssuanceID(), kAccount)); + auto const txMeta = createTxMeta(std::move(nodes), xrpl::tecINCOMPLETE); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, createTx(xrpl::ttPAYMENT)); + + EXPECT_TRUE(records.empty()); +} + +TEST_F(MPTHelpersTest, FailedTxWithTopLevelIssuanceIDProducesRecord) +{ + auto const txMeta = createTxMeta({}, xrpl::tecINCOMPLETE); + auto const sttx = createTx(xrpl::ttMPTOKEN_ISSUANCE_SET); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, sttx); + + ASSERT_EQ(records.size(), 1); + EXPECT_EQ(records[0].mptIssuanceID, defaultIssuanceID()); + verifyCommonFields(records[0], sttx, txMeta); +} + +TEST_F(MPTHelpersTest, FailedTxWithMPTAmountProducesRecord) +{ + auto const txMeta = createTxMeta({}, xrpl::tecINCOMPLETE); + auto const sttx = createPaymentTxWithMPTAmount(defaultIssuanceID()); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, sttx); + + ASSERT_EQ(records.size(), 1); + EXPECT_EQ(records[0].mptIssuanceID, defaultIssuanceID()); + verifyCommonFields(records[0], sttx, txMeta); +} + +TEST_F(MPTHelpersTest, FailedTxWithMPTIssueProducesRecord) +{ + auto const txMeta = createTxMeta({}, xrpl::tecINCOMPLETE); + auto const sttx = createAMMDepositTxWithMPTIssue(defaultIssuanceID()); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, sttx); + + ASSERT_EQ(records.size(), 1); + EXPECT_EQ(records[0].mptIssuanceID, defaultIssuanceID()); + verifyCommonFields(records[0], sttx, txMeta); +} + +TEST_F(MPTHelpersTest, IssuanceCreateProducesRecordWithReconstructedID) +{ + auto const tx = createMPTIssuanceCreateTxWithMetadata(kIssuer, 2, kIssuanceSeq); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, tx.metadata); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, sttx); + + ASSERT_EQ(records.size(), 1); + EXPECT_EQ(records[0].mptIssuanceID, defaultIssuanceID()); + verifyCommonFields(records[0], sttx, txMeta); +} + +TEST_F(MPTHelpersTest, IssuanceDestroyProducesRecordFromDeletedNode) +{ + std::vector nodes; + nodes.push_back(util::createMPTokenIssuanceNode(xrpl::sfDeletedNode, kIssuanceSeq, kIssuer)); + auto const txMeta = createTxMeta(std::move(nodes)); + auto const sttx = createTx(xrpl::ttMPTOKEN_ISSUANCE_DESTROY); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, sttx); + + ASSERT_EQ(records.size(), 1); + EXPECT_EQ(records[0].mptIssuanceID, defaultIssuanceID()); + verifyCommonFields(records[0], sttx, txMeta); +} + +TEST_F(MPTHelpersTest, IssuanceSetProducesRecordFromModifiedNode) +{ + std::vector nodes; + nodes.push_back(util::createMPTokenIssuanceNode(xrpl::sfModifiedNode, kIssuanceSeq, kIssuer)); + auto const txMeta = createTxMeta(std::move(nodes)); + auto const sttx = createTx(xrpl::ttMPTOKEN_ISSUANCE_SET); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, sttx); + + ASSERT_EQ(records.size(), 1); + EXPECT_EQ(records[0].mptIssuanceID, defaultIssuanceID()); + verifyCommonFields(records[0], sttx, txMeta); +} + +TEST_F(MPTHelpersTest, AuthorizeProducesRecordFromMPTokenNode) +{ + auto const issuanceID = defaultIssuanceID(); + auto const tx = createMPTokenAuthorizeTxWithMetadata(kAccount, issuanceID, 2, 3); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, tx.metadata); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, sttx); + + ASSERT_EQ(records.size(), 1); + EXPECT_EQ(records[0].mptIssuanceID, issuanceID); + verifyCommonFields(records[0], sttx, txMeta); +} + +TEST_F(MPTHelpersTest, DedupsAcrossMPTokenAndIssuanceNodes) +{ + // Both nodes resolve to the same issuance ID: the MPToken node carries it directly while the + // MPTokenIssuance node requires reconstruction via makeMptID. + std::vector nodes; + nodes.push_back(util::createMPTokenNode(xrpl::sfCreatedNode, defaultIssuanceID(), kAccount)); + nodes.push_back(util::createMPTokenIssuanceNode(xrpl::sfModifiedNode, kIssuanceSeq, kIssuer)); + auto const txMeta = createTxMeta(std::move(nodes)); + auto const sttx = createTx(xrpl::ttPAYMENT); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, sttx); + + ASSERT_EQ(records.size(), 1); + EXPECT_EQ(records[0].mptIssuanceID, defaultIssuanceID()); + EXPECT_TRUE(records[0].accounts.contains(getAccountIdWithString(kAccount))); + EXPECT_TRUE(records[0].accounts.contains(getAccountIdWithString(kIssuer))); + verifyCommonFields(records[0], sttx, txMeta); +} + +TEST_F(MPTHelpersTest, MultipleIssuancesFanOutAndDedup) +{ + auto const issuanceA = xrpl::makeMptID(1, getAccountIdWithString(kIssuer)); + auto const issuanceB = xrpl::makeMptID(2, getAccountIdWithString(kIssuer)); + ASSERT_LT(issuanceA, issuanceB); + + // issuanceA is touched twice and should produce only one index record. + std::vector nodes; + nodes.push_back(util::createMPTokenNode(xrpl::sfCreatedNode, issuanceB, kAccount)); + nodes.push_back(util::createMPTokenNode(xrpl::sfModifiedNode, issuanceA, kAccount2)); + nodes.push_back(util::createMPTokenNode(xrpl::sfDeletedNode, issuanceA, kAccount)); + auto const txMeta = createTxMeta(std::move(nodes)); + auto const sttx = createTx(xrpl::ttPAYMENT); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, sttx); + + ASSERT_EQ(records.size(), 2); + EXPECT_EQ(records[0].mptIssuanceID, issuanceA); + EXPECT_EQ(records[1].mptIssuanceID, issuanceB); + for (auto const& record : records) { + EXPECT_EQ(record.accounts, txMeta.getAffectedAccounts()); + verifyCommonFields(record, sttx, txMeta); + } +} + +TEST_F(MPTHelpersTest, IndexesMPTNodesRegardlessOfTransactionType) +{ + constexpr xrpl::TxType kTypes[] = { + xrpl::ttPAYMENT, xrpl::ttCLAWBACK, xrpl::ttOFFER_CREATE, xrpl::ttAMM_DEPOSIT + }; + + for (auto const type : kTypes) { + std::vector nodes; + nodes.push_back( + util::createMPTokenNode(xrpl::sfModifiedNode, defaultIssuanceID(), kAccount) + ); + auto const txMeta = createTxMeta(std::move(nodes)); + auto const sttx = createTx(type); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, sttx); + + ASSERT_EQ(records.size(), 1) << "TransactionType " << type; + EXPECT_EQ(records[0].mptIssuanceID, defaultIssuanceID()); + verifyCommonFields(records[0], sttx, txMeta); + } +} + +TEST_F(MPTHelpersTest, MPTNodeWithoutFieldsProducesNoRecords) +{ + // A ModifiedNode carrying no FinalFields must be skipped without crashing. + xrpl::STObject node(xrpl::sfModifiedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltMPTOKEN_ISSUANCE); + node.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{}); + + std::vector nodes; + nodes.push_back(std::move(node)); + auto const txMeta = createTxMeta(std::move(nodes)); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, createTx(xrpl::ttPAYMENT)); + + EXPECT_TRUE(records.empty()); +} + +TEST_F(MPTHelpersTest, MPTNodesMissingRequiredFieldsProduceNoRecords) +{ + std::vector nodes; + nodes.push_back(createMPTokenNodeWithoutIssuanceID()); + nodes.push_back(createMPTokenIssuanceNodeWithoutIssuer()); + auto const txMeta = createTxMeta(std::move(nodes)); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, createTx(xrpl::ttPAYMENT)); + + EXPECT_TRUE(records.empty()); +} + +TEST_F(MPTHelpersTest, NoMPTNodesProducesNoRecords) +{ + std::vector nodes; + nodes.push_back(createAccountRootNode(kAccount)); + auto const txMeta = createTxMeta(std::move(nodes)); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, createTx(xrpl::ttPAYMENT)); + + EXPECT_TRUE(records.empty()); +} + +TEST_F(MPTHelpersTest, RecordCarriesAllAffectedAccounts) +{ + std::vector nodes; + nodes.push_back(util::createMPTokenNode(xrpl::sfCreatedNode, defaultIssuanceID(), kAccount)); + nodes.push_back(util::createMPTokenIssuanceNode(xrpl::sfModifiedNode, kIssuanceSeq, kIssuer)); + nodes.push_back(createAccountRootNode(kAccount2)); + auto const txMeta = createTxMeta(std::move(nodes)); + auto const sttx = createTx(xrpl::ttPAYMENT); + + auto const records = etl::getMPTokenIssuanceTxsFromTx(txMeta, sttx); + + ASSERT_EQ(records.size(), 1); + EXPECT_EQ(records[0].accounts, txMeta.getAffectedAccounts()); + EXPECT_EQ(records[0].accounts.size(), 3); + EXPECT_TRUE(records[0].accounts.contains(getAccountIdWithString(kAccount))); + EXPECT_TRUE(records[0].accounts.contains(getAccountIdWithString(kAccount2))); + EXPECT_TRUE(records[0].accounts.contains(getAccountIdWithString(kIssuer))); +} + +TEST_F(MPTHelpersTest, ExtractionIsDeterministic) +{ + auto const issuanceA = xrpl::makeMptID(1, getAccountIdWithString(kIssuer)); + + std::vector nodes; + nodes.push_back(util::createMPTokenNode(xrpl::sfCreatedNode, issuanceA, kAccount)); + nodes.push_back(util::createMPTokenIssuanceNode(xrpl::sfModifiedNode, kIssuanceSeq, kIssuer)); + auto const txMeta = createTxMeta(std::move(nodes)); + auto const sttx = createTx(xrpl::ttPAYMENT); + + auto const first = etl::getMPTokenIssuanceTxsFromTx(txMeta, sttx); + auto const second = etl::getMPTokenIssuanceTxsFromTx(txMeta, sttx); + + ASSERT_EQ(first.size(), 2); + ASSERT_EQ(first.size(), second.size()); + for (std::size_t i = 0; i < first.size(); ++i) { + EXPECT_EQ(first[i].mptIssuanceID, second[i].mptIssuanceID); + EXPECT_EQ(first[i].accounts, second[i].accounts); + EXPECT_EQ(first[i].ledgerSequence, second[i].ledgerSequence); + EXPECT_EQ(first[i].transactionIndex, second[i].transactionIndex); + EXPECT_EQ(first[i].txHash, second[i].txHash); + } +} diff --git a/tests/unit/etl/MonitorTests.cpp b/tests/unit/etl/MonitorTests.cpp index ef223f378..bd3e556f9 100644 --- a/tests/unit/etl/MonitorTests.cpp +++ b/tests/unit/etl/MonitorTests.cpp @@ -11,7 +11,6 @@ #include #include -#include #include #include #include @@ -21,8 +20,8 @@ using namespace etl::impl; using namespace data; namespace { -constexpr auto kSTART_SEQ = 123u; -constexpr auto kNO_NEW_LEDGER_REPORT_DELAY = std::chrono::milliseconds(1u); +constexpr auto kStartSeq = 123u; +constexpr auto kNoNewLedgerReportDelay = std::chrono::milliseconds(1u); } // namespace struct MonitorTests : util::prometheus::WithPrometheus, MockBackendTest { @@ -33,13 +32,13 @@ protected: testing::StrictMock> dbStalledMock_; etl::impl::Monitor monitor_ = - etl::impl::Monitor(ctx_, backend_, ledgers_, kSTART_SEQ, kNO_NEW_LEDGER_REPORT_DELAY); + etl::impl::Monitor(ctx_, backend_, ledgers_, kStartSeq, kNoNewLedgerReportDelay); }; TEST_F(MonitorTests, ConsumesAndNotifiesForAllOutstandingSequencesAtOnce) { uint8_t count = 3; - LedgerRange const range(kSTART_SEQ, kSTART_SEQ + count - 1); + LedgerRange const range(kStartSeq, kStartSeq + count - 1); std::binary_semaphore unblock(0); @@ -58,7 +57,7 @@ TEST_F(MonitorTests, ConsumesAndNotifiesForAllOutstandingSequencesAtOnce) TEST_F(MonitorTests, NotifiesForEachSequence) { uint8_t count = 3; - LedgerRange range(kSTART_SEQ, kSTART_SEQ); + LedgerRange range(kStartSeq, kStartSeq); std::binary_semaphore unblock(0); @@ -80,7 +79,7 @@ TEST_F(MonitorTests, NotifiesForEachSequence) TEST_F(MonitorTests, NotifiesWhenForcedByNewSequenceAvailableFromNetwork) { - LedgerRange const range(kSTART_SEQ, kSTART_SEQ); + LedgerRange const range(kStartSeq, kStartSeq); std::binary_semaphore unblock(0); std::function pusher; @@ -93,13 +92,13 @@ TEST_F(MonitorTests, NotifiesWhenForcedByNewSequenceAvailableFromNetwork) auto subscription = monitor_.subscribeToNewSequence(actionMock_.AsStdFunction()); monitor_.run(std::chrono::seconds{10}); // expected to be force-invoked sooner than in 10 sec - pusher(kSTART_SEQ); // pretend network validated a new ledger + pusher(kStartSeq); // pretend network validated a new ledger unblock.acquire(); } TEST_F(MonitorTests, NotifiesWhenForcedByLedgerLoaded) { - LedgerRange const range(kSTART_SEQ, kSTART_SEQ); + LedgerRange const range(kStartSeq, kStartSeq); std::binary_semaphore unblock(0); EXPECT_CALL(*ledgers_, subscribe(testing::_)); @@ -107,18 +106,18 @@ TEST_F(MonitorTests, NotifiesWhenForcedByLedgerLoaded) EXPECT_CALL(actionMock_, Call).WillOnce([&] { unblock.release(); }); auto subscription = monitor_.subscribeToNewSequence(actionMock_.AsStdFunction()); - monitor_.run(std::chrono::seconds{10}); // expected to be force-invoked sooner than in 10 sec - monitor_.notifySequenceLoaded(kSTART_SEQ); // notify about newly committed ledger + monitor_.run(std::chrono::seconds{10}); // expected to be force-invoked sooner than in 10 sec + monitor_.notifySequenceLoaded(kStartSeq); // notify about newly committed ledger unblock.acquire(); } TEST_F(MonitorTests, ResumesMonitoringFromNextSequenceAfterWriteConflict) { - constexpr uint32_t kCONFLICT_SEQ = 456u; - constexpr uint32_t kEXPECTED_NEXT_SEQ = kCONFLICT_SEQ + 1; + constexpr uint32_t kConflictSeq = 456u; + constexpr uint32_t kExpectedNextSeq = kConflictSeq + 1; - LedgerRange const rangeBeforeConflict(kSTART_SEQ, kSTART_SEQ); - LedgerRange const rangeAfterConflict(kEXPECTED_NEXT_SEQ, kEXPECTED_NEXT_SEQ); + LedgerRange const rangeBeforeConflict(kStartSeq, kStartSeq); + LedgerRange const rangeAfterConflict(kExpectedNextSeq, kExpectedNextSeq); std::binary_semaphore unblock(0); EXPECT_CALL(*ledgers_, subscribe(testing::_)); @@ -131,14 +130,14 @@ TEST_F(MonitorTests, ResumesMonitoringFromNextSequenceAfterWriteConflict) .WillRepeatedly(testing::Return(rangeAfterConflict)); } - EXPECT_CALL(actionMock_, Call(kEXPECTED_NEXT_SEQ)).WillOnce([&](uint32_t seq) { - EXPECT_EQ(seq, kEXPECTED_NEXT_SEQ); + EXPECT_CALL(actionMock_, Call(kExpectedNextSeq)).WillOnce([&](uint32_t seq) { + EXPECT_EQ(seq, kExpectedNextSeq); unblock.release(); }); auto subscription = monitor_.subscribeToNewSequence(actionMock_.AsStdFunction()); monitor_.run(std::chrono::nanoseconds{100}); - monitor_.notifyWriteConflict(kCONFLICT_SEQ); + monitor_.notifyWriteConflict(kConflictSeq); unblock.acquire(); } diff --git a/tests/unit/etl/NFTHelpersTests.cpp b/tests/unit/etl/NFTHelpersTests.cpp index 938cba80e..ee745aa49 100644 --- a/tests/unit/etl/NFTHelpersTests.cpp +++ b/tests/unit/etl/NFTHelpersTests.cpp @@ -24,15 +24,15 @@ namespace { -constexpr auto kACCOUNT = "rM2AGCCCRb373FRuD8wHyUwUsh2dV4BW5Q"; -constexpr auto kACCOUNT2 = "rnd1nHuzceyQDqnLH8urWNr4QBKt4v7WVk"; -constexpr auto kNFT_ID = "0008013AE1CD8B79A8BCB52335CD40DE97401B2D60A828720000099B00000000"; -constexpr auto kNFT_ID2 = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DA"; -constexpr auto kOFFER1 = "23F1A95D7AAB7108D5CE7EEAF504B2894B8C674E6D68499076441C4837282BF8"; +constexpr auto kAccount = "rM2AGCCCRb373FRuD8wHyUwUsh2dV4BW5Q"; +constexpr auto kAccount2 = "rnd1nHuzceyQDqnLH8urWNr4QBKt4v7WVk"; +constexpr auto kNftId = "0008013AE1CD8B79A8BCB52335CD40DE97401B2D60A828720000099B00000000"; +constexpr auto kNftID2 = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DA"; +constexpr auto kOffer1 = "23F1A95D7AAB7108D5CE7EEAF504B2894B8C674E6D68499076441C4837282BF8"; constexpr auto kTX = "13F1A95D7AAB7108D5CE7EEAF504B2894B8C674E6D68499076441C4837282BF8"; // Page index is a valid nft page for ACCOUNT -constexpr auto kPAGE_INDEX = "E1CD8B79A8BCB52335CD40DE97401B2D60A82872FFFFFFFFFFFFFFFFFFFFFFFF"; -constexpr auto kOFFER_ID = "AA86CBF29770F72FA3FF4A5D9A9FA54D6F399A8E038F72393EF782224865E27F"; +constexpr auto kPageIndex = "E1CD8B79A8BCB52335CD40DE97401B2D60A82872FFFFFFFFFFFFFFFFFFFFFFFF"; +constexpr auto kOfferId = "AA86CBF29770F72FA3FF4A5D9A9FA54D6F399A8E038F72393EF782224865E27F"; } // namespace @@ -41,12 +41,12 @@ protected: static void verifyNFTTransactionsData( NFTTransactionsData const& data, - ripple::STTx const& sttx, - ripple::TxMeta const& txMeta, + xrpl::STTx const& sttx, + xrpl::TxMeta const& txMeta, std::string_view nftId ) { - EXPECT_EQ(data.tokenID, ripple::uint256(nftId)); + EXPECT_EQ(data.tokenID, xrpl::uint256(nftId)); EXPECT_EQ(data.ledgerSequence, txMeta.getLgrSeq()); EXPECT_EQ(data.transactionIndex, txMeta.getIndex()); EXPECT_EQ(data.txHash, sttx.getTransactionID()); @@ -55,34 +55,34 @@ protected: static void verifyNFTsData( NFTsData const& data, - ripple::STTx const& sttx, - ripple::TxMeta const& txMeta, + xrpl::STTx const& sttx, + xrpl::TxMeta const& txMeta, std::string_view nftId, std::optional const& owner ) { - EXPECT_EQ(data.tokenID, ripple::uint256(nftId)); + EXPECT_EQ(data.tokenID, xrpl::uint256(nftId)); EXPECT_EQ(data.ledgerSequence, txMeta.getLgrSeq()); EXPECT_EQ(data.transactionIndex, txMeta.getIndex()); if (owner) EXPECT_EQ(data.owner, getAccountIdWithString(*owner)); - if (sttx.getTxnType() == ripple::ttNFTOKEN_MINT || - sttx.getTxnType() == ripple::ttNFTOKEN_MODIFY) { + if (sttx.getTxnType() == xrpl::ttNFTOKEN_MINT || + sttx.getTxnType() == xrpl::ttNFTOKEN_MODIFY) { ASSERT_TRUE(data.uri.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - EXPECT_EQ(*data.uri, sttx.getFieldVL(ripple::sfURI)); + EXPECT_EQ(*data.uri, sttx.getFieldVL(xrpl::sfURI)); } else { EXPECT_FALSE(data.uri.has_value()); } - if (sttx.getTxnType() == ripple::ttNFTOKEN_BURN) { + if (sttx.getTxnType() == xrpl::ttNFTOKEN_BURN) { EXPECT_TRUE(data.isBurned); } else { EXPECT_FALSE(data.isBurned); } - if (sttx.getTxnType() == ripple::ttNFTOKEN_MODIFY) { + if (sttx.getTxnType() == xrpl::ttNFTOKEN_MODIFY) { EXPECT_TRUE(data.onlyUriChanged); } else { EXPECT_FALSE(data.onlyUriChanged); @@ -92,16 +92,16 @@ protected: TEST_F(NFTHelpersTest, NFTDataFromFailedTx) { - auto const tx = createNftModifyTxWithMetadata(kACCOUNT, kNFT_ID, ripple::Blob{}); + auto const tx = createNftModifyTxWithMetadata(kAccount, kNftId, xrpl::Blob{}); // Inject a failed result - ripple::SerialIter sitMeta(ripple::makeSlice(tx.metadata)); - ripple::STObject objMeta(sitMeta, ripple::sfMetadata); - objMeta.setFieldU8(ripple::sfTransactionResult, ripple::tecINCOMPLETE); + xrpl::SerialIter sitMeta(xrpl::makeSlice(tx.metadata)); + xrpl::STObject objMeta(sitMeta, xrpl::sfMetadata); + objMeta.setFieldU8(xrpl::sfTransactionResult, xrpl::tecINCOMPLETE); - ripple::TxMeta const txMeta(ripple::uint256(kTX), 1, objMeta.getSerializer().peekData()); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, objMeta.getSerializer().peekData()); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx( - txMeta, ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}) + txMeta, xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}) ); EXPECT_EQ(nftTxs.size(), 0); @@ -111,23 +111,23 @@ TEST_F(NFTHelpersTest, NFTDataFromFailedTx) TEST_F(NFTHelpersTest, NotNFTTx) { auto const tx = createOracleSetTxWithMetadata( - kACCOUNT, + kAccount, 1, 123, 1, 4321u, createPriceDataSeries( - {createOraclePriceData(1e3, ripple::to_currency("EUR"), ripple::to_currency("XRP"), 2)} + {createOraclePriceData(1e3, xrpl::toCurrency("EUR"), xrpl::toCurrency("XRP"), 2)} ), - kPAGE_INDEX, + kPageIndex, false, kTX ); - ripple::TxMeta const txMeta(ripple::uint256(kTX), 1, tx.metadata); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, tx.metadata); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx( - txMeta, ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}) + txMeta, xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}) ); EXPECT_EQ(nftTxs.size(), 0); @@ -137,66 +137,63 @@ TEST_F(NFTHelpersTest, NotNFTTx) TEST_F(NFTHelpersTest, NFTModifyWithURI) { std::string const uri("1234567890A"); - ripple::Blob const uriBlob(uri.begin(), uri.end()); + xrpl::Blob const uriBlob(uri.begin(), uri.end()); - auto const tx = createNftModifyTxWithMetadata(kACCOUNT, kNFT_ID, uriBlob); - ripple::TxMeta const txMeta(ripple::uint256(kTX), 1, tx.metadata); + auto const tx = createNftModifyTxWithMetadata(kAccount, kNftId, uriBlob); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, tx.metadata); - auto const sttx = - ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx( - txMeta, ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}) + txMeta, xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}) ); EXPECT_EQ(nftTxs.size(), 1); - verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNftId); ASSERT_TRUE(nftDatas.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, std::nullopt); + verifyNFTsData(*nftDatas, sttx, txMeta, kNftId, std::nullopt); } TEST_F(NFTHelpersTest, NFTModifyWithoutURI) { - auto const tx = createNftModifyTxWithMetadata(kACCOUNT, kNFT_ID, ripple::Blob{}); - ripple::TxMeta const txMeta(ripple::uint256(kTX), 1, tx.metadata); - auto const sttx = - ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}); + auto const tx = createNftModifyTxWithMetadata(kAccount, kNftId, xrpl::Blob{}); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, tx.metadata); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx(txMeta, sttx); EXPECT_EQ(nftTxs.size(), 1); - verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNftId); ASSERT_TRUE(nftDatas.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, std::nullopt); + verifyNFTsData(*nftDatas, sttx, txMeta, kNftId, std::nullopt); } TEST_F(NFTHelpersTest, NFTMintFromModifiedNode) { - auto const tx = createMintNftTxWithMetadata(kACCOUNT, 1, 20, 1, kNFT_ID); - ripple::TxMeta txMeta(ripple::uint256(kTX), 1, tx.metadata); - txMeta.getNodes()[0].setFieldH256(ripple::sfLedgerIndex, ripple::uint256(kPAGE_INDEX)); - auto const sttx = - ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}); + auto const tx = createMintNftTxWithMetadata(kAccount, 1, 20, 1, kNftId); + xrpl::TxMeta txMeta(xrpl::uint256(kTX), 1, tx.metadata); + txMeta.getNodes()[0].setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256(kPageIndex)); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx(txMeta, sttx); EXPECT_EQ(nftTxs.size(), 1); - verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNftId); ASSERT_TRUE(nftDatas.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); + verifyNFTsData(*nftDatas, sttx, txMeta, kNftId, kAccount); } TEST_F(NFTHelpersTest, NFTMintCantFindNewNFT) { // No NFT added to the page auto const tx = createMintNftTxWithMetadataOfCreatedNode( - kACCOUNT, 1, 20, 1, std::nullopt, std::nullopt, kPAGE_INDEX + kAccount, 1, 20, 1, std::nullopt, std::nullopt, kPageIndex ); - ripple::TxMeta const txMeta(ripple::uint256(kTX), 1, tx.metadata); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, tx.metadata); EXPECT_THROW( etl::getNFTDataFromTx( - txMeta, ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}) + txMeta, xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}) ), std::runtime_error ); @@ -205,51 +202,49 @@ TEST_F(NFTHelpersTest, NFTMintCantFindNewNFT) TEST_F(NFTHelpersTest, NFTMintFromCreatedNode) { std::string const uri("1234567890A"); - ripple::Blob const uriBlob(uri.begin(), uri.end()); + xrpl::Blob const uriBlob(uri.begin(), uri.end()); auto const tx = - createMintNftTxWithMetadataOfCreatedNode(kACCOUNT, 1, 20, 1, kNFT_ID, uri, kPAGE_INDEX); - ripple::TxMeta const txMeta(ripple::uint256(kTX), 1, tx.metadata); - auto const sttx = - ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}); + createMintNftTxWithMetadataOfCreatedNode(kAccount, 1, 20, 1, kNftId, uri, kPageIndex); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, tx.metadata); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx(txMeta, sttx); EXPECT_EQ(nftTxs.size(), 1); - verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNftId); ASSERT_TRUE(nftDatas.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); + verifyNFTsData(*nftDatas, sttx, txMeta, kNftId, kAccount); } TEST_F(NFTHelpersTest, NFTMintWithoutUriField) { auto const tx = createMintNftTxWithMetadataOfCreatedNode( - kACCOUNT, 1, 20, 1, kNFT_ID, std::nullopt, kPAGE_INDEX + kAccount, 1, 20, 1, kNftId, std::nullopt, kPageIndex ); - ripple::TxMeta const txMeta(ripple::uint256(kTX), 1, tx.metadata); - auto const sttx = - ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, tx.metadata); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx(txMeta, sttx); EXPECT_EQ(nftTxs.size(), 1); - verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNftId); ASSERT_TRUE(nftDatas.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); + verifyNFTsData(*nftDatas, sttx, txMeta, kNftId, kAccount); } TEST_F(NFTHelpersTest, NFTMintZeroMetaNode) { auto const tx = createMintNftTxWithMetadataOfCreatedNode( - kACCOUNT, 1, 20, 1, kNFT_ID, std::nullopt, kPAGE_INDEX + kAccount, 1, 20, 1, kNftId, std::nullopt, kPageIndex ); - ripple::TxMeta txMeta(ripple::uint256(kTX), 1, tx.metadata); + xrpl::TxMeta txMeta(xrpl::uint256(kTX), 1, tx.metadata); txMeta.getNodes().clear(); EXPECT_THROW( etl::getNFTDataFromTx( - txMeta, ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}) + txMeta, xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}) ), std::runtime_error ); @@ -257,29 +252,28 @@ TEST_F(NFTHelpersTest, NFTMintZeroMetaNode) TEST_F(NFTHelpersTest, NFTBurnFromDeletedNode) { - auto const tx = createNftBurnTxWithMetadataOfDeletedNode(kACCOUNT, kNFT_ID); - ripple::TxMeta txMeta(ripple::uint256(kTX), 1, tx.metadata); - txMeta.getNodes()[1].setFieldH256(ripple::sfLedgerIndex, ripple::uint256(kPAGE_INDEX)); - auto const sttx = - ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}); + auto const tx = createNftBurnTxWithMetadataOfDeletedNode(kAccount, kNftId); + xrpl::TxMeta txMeta(xrpl::uint256(kTX), 1, tx.metadata); + txMeta.getNodes()[1].setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256(kPageIndex)); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx(txMeta, sttx); EXPECT_EQ(nftTxs.size(), 1); - verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNftId); ASSERT_TRUE(nftDatas.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); + verifyNFTsData(*nftDatas, sttx, txMeta, kNftId, kAccount); } TEST_F(NFTHelpersTest, NFTBurnZeroMetaNode) { - auto const tx = createNftBurnTxWithMetadataOfDeletedNode(kACCOUNT, kNFT_ID); - ripple::TxMeta txMeta(ripple::uint256(kTX), 1, tx.metadata); + auto const tx = createNftBurnTxWithMetadataOfDeletedNode(kAccount, kNftId); + xrpl::TxMeta txMeta(xrpl::uint256(kTX), 1, tx.metadata); txMeta.getNodes().clear(); EXPECT_THROW( etl::getNFTDataFromTx( - txMeta, ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}) + txMeta, xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}) ), std::runtime_error ); @@ -287,52 +281,49 @@ TEST_F(NFTHelpersTest, NFTBurnZeroMetaNode) TEST_F(NFTHelpersTest, NFTBurnFromModifiedNode) { - auto const tx = createNftBurnTxWithMetadataOfModifiedNode(kACCOUNT, kNFT_ID); - ripple::TxMeta txMeta(ripple::uint256(kTX), 1, tx.metadata); - txMeta.getNodes()[0].setFieldH256(ripple::sfLedgerIndex, ripple::uint256(kPAGE_INDEX)); + auto const tx = createNftBurnTxWithMetadataOfModifiedNode(kAccount, kNftId); + xrpl::TxMeta txMeta(xrpl::uint256(kTX), 1, tx.metadata); + txMeta.getNodes()[0].setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256(kPageIndex)); - auto const sttx = - ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx(txMeta, sttx); EXPECT_EQ(nftTxs.size(), 1); - verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNftId); ASSERT_TRUE(nftDatas.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); + verifyNFTsData(*nftDatas, sttx, txMeta, kNftId, kAccount); } TEST_F(NFTHelpersTest, NFTCancelOffer) { auto const tx = createCancelNftOffersTxWithMetadata( - kACCOUNT, 1, 2, std::vector{kNFT_ID, kNFT_ID2} + kAccount, 1, 2, std::vector{kNftId, kNftID2} ); - ripple::TxMeta txMeta(ripple::uint256(kTX), 1, tx.metadata); - txMeta.getNodes()[0].setFieldH256(ripple::sfLedgerIndex, ripple::uint256(kPAGE_INDEX)); - auto const sttx = - ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}); + xrpl::TxMeta txMeta(xrpl::uint256(kTX), 1, tx.metadata); + txMeta.getNodes()[0].setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256(kPageIndex)); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx(txMeta, sttx); EXPECT_EQ(nftTxs.size(), 2); EXPECT_FALSE(nftDatas); - verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); - verifyNFTTransactionsData(nftTxs[1], sttx, txMeta, kNFT_ID2); + verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNftId); + verifyNFTTransactionsData(nftTxs[1], sttx, txMeta, kNftID2); } TEST_F(NFTHelpersTest, NFTCancelOfferContainsDuplicateNFTs) { auto const tx = createCancelNftOffersTxWithMetadata( - kACCOUNT, 1, 2, std::vector{kNFT_ID2, kNFT_ID, kNFT_ID2, kNFT_ID} + kAccount, 1, 2, std::vector{kNftID2, kNftId, kNftID2, kNftId} ); - ripple::TxMeta const txMeta(ripple::uint256(kTX), 1, tx.metadata); - auto const sttx = - ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, tx.metadata); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx(txMeta, sttx); EXPECT_EQ(nftTxs.size(), 2); EXPECT_FALSE(nftDatas); - verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); - verifyNFTTransactionsData(nftTxs[1], sttx, txMeta, kNFT_ID2); + verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNftId); + verifyNFTTransactionsData(nftTxs[1], sttx, txMeta, kNftID2); } TEST_F(NFTHelpersTest, UniqueNFTDatas) @@ -340,23 +331,23 @@ TEST_F(NFTHelpersTest, UniqueNFTDatas) std::vector nftDatas; auto const generateNFTsData = [](char const* nftID, std::uint32_t txIndex) { - auto const tx = createCreateNftOfferTxWithMetadata(kACCOUNT, 1, 50, nftID, 123, kOFFER1); - ripple::SerialIter s{tx.metadata.data(), tx.metadata.size()}; - ripple::STObject meta{s, ripple::sfMetadata}; - meta.setFieldU32(ripple::sfTransactionIndex, txIndex); - ripple::TxMeta const txMeta(ripple::uint256(kTX), 1, meta.getSerializer().peekData()); + auto const tx = createCreateNftOfferTxWithMetadata(kAccount, 1, 50, nftID, 123, kOffer1); + xrpl::SerialIter s{tx.metadata.data(), tx.metadata.size()}; + xrpl::STObject meta{s, xrpl::sfMetadata}; + meta.setFieldU32(xrpl::sfTransactionIndex, txIndex); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, meta.getSerializer().peekData()); - auto const account = getAccountIdWithString(kACCOUNT); - return NFTsData{ripple::uint256(nftID), account, ripple::Blob{}, txMeta}; + auto const account = getAccountIdWithString(kAccount); + return NFTsData{xrpl::uint256(nftID), account, xrpl::Blob{}, txMeta}; }; - nftDatas.push_back(generateNFTsData(kNFT_ID, 3)); - nftDatas.push_back(generateNFTsData(kNFT_ID, 1)); - nftDatas.push_back(generateNFTsData(kNFT_ID, 2)); + nftDatas.push_back(generateNFTsData(kNftId, 3)); + nftDatas.push_back(generateNFTsData(kNftId, 1)); + nftDatas.push_back(generateNFTsData(kNftId, 2)); - nftDatas.push_back(generateNFTsData(kNFT_ID2, 4)); - nftDatas.push_back(generateNFTsData(kNFT_ID2, 1)); - nftDatas.push_back(generateNFTsData(kNFT_ID2, 5)); + nftDatas.push_back(generateNFTsData(kNftID2, 4)); + nftDatas.push_back(generateNFTsData(kNftID2, 1)); + nftDatas.push_back(generateNFTsData(kNftID2, 5)); auto const uniqueNFTDatas = etl::getUniqueNFTsDatas(nftDatas); @@ -365,37 +356,36 @@ TEST_F(NFTHelpersTest, UniqueNFTDatas) EXPECT_EQ(uniqueNFTDatas[1].ledgerSequence, 1); EXPECT_EQ(uniqueNFTDatas[0].transactionIndex, 5); EXPECT_EQ(uniqueNFTDatas[1].transactionIndex, 3); - EXPECT_EQ(uniqueNFTDatas[0].tokenID, ripple::uint256(kNFT_ID2)); - EXPECT_EQ(uniqueNFTDatas[1].tokenID, ripple::uint256(kNFT_ID)); + EXPECT_EQ(uniqueNFTDatas[0].tokenID, xrpl::uint256(kNftID2)); + EXPECT_EQ(uniqueNFTDatas[1].tokenID, xrpl::uint256(kNftId)); } TEST_F(NFTHelpersTest, NFTAcceptBuyerOffer) { - auto const tx = createAcceptNftBuyerOfferTxWithMetadata(kACCOUNT, 1, 2, kNFT_ID, kOFFER_ID); - ripple::TxMeta const txMeta(ripple::uint256(kTX), 1, tx.metadata); - auto const sttx = - ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}); + auto const tx = createAcceptNftBuyerOfferTxWithMetadata(kAccount, 1, 2, kNftId, kOfferId); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, tx.metadata); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx(txMeta, sttx); EXPECT_EQ(nftTxs.size(), 1); EXPECT_TRUE(nftDatas); - verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNftId); ASSERT_TRUE(nftDatas.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); + verifyNFTsData(*nftDatas, sttx, txMeta, kNftId, kAccount); } // The offer id in tx is different from the offer id in deleted node in metadata TEST_F(NFTHelpersTest, NFTAcceptBuyerOfferCheckOfferIDFail) { - auto const tx = createAcceptNftBuyerOfferTxWithMetadata(kACCOUNT, 1, 2, kNFT_ID, kOFFER_ID); - ripple::TxMeta txMeta(ripple::uint256(kTX), 1, tx.metadata); + auto const tx = createAcceptNftBuyerOfferTxWithMetadata(kAccount, 1, 2, kNftId, kOfferId); + xrpl::TxMeta txMeta(xrpl::uint256(kTX), 1, tx.metadata); // inject a different offer id - txMeta.getNodes()[0].setFieldH256(ripple::sfLedgerIndex, ripple::uint256(kPAGE_INDEX)); + txMeta.getNodes()[0].setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256(kPageIndex)); EXPECT_THROW( etl::getNFTDataFromTx( - txMeta, ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}) + txMeta, xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}) ), std::runtime_error ); @@ -404,50 +394,48 @@ TEST_F(NFTHelpersTest, NFTAcceptBuyerOfferCheckOfferIDFail) TEST_F(NFTHelpersTest, NFTAcceptSellerOfferFromCreatedNode) { auto const tx = createAcceptNftSellerOfferTxWithMetadata( - kACCOUNT2, 1, 2, kNFT_ID, kOFFER_ID, kPAGE_INDEX, true + kAccount2, 1, 2, kNftId, kOfferId, kPageIndex, true ); - ripple::TxMeta const txMeta(ripple::uint256(kTX), 1, tx.metadata); - auto const sttx = - ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, tx.metadata); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx(txMeta, sttx); EXPECT_EQ(nftTxs.size(), 1); EXPECT_TRUE(nftDatas); - verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNftId); ASSERT_TRUE(nftDatas.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); + verifyNFTsData(*nftDatas, sttx, txMeta, kNftId, kAccount); } TEST_F(NFTHelpersTest, NFTAcceptSellerOfferFromModifiedNode) { auto const tx = createAcceptNftSellerOfferTxWithMetadata( - kACCOUNT2, 1, 2, kNFT_ID, kOFFER_ID, kPAGE_INDEX, false + kAccount2, 1, 2, kNftId, kOfferId, kPageIndex, false ); - ripple::TxMeta const txMeta(ripple::uint256(kTX), 1, tx.metadata); - auto const sttx = - ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, tx.metadata); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx(txMeta, sttx); EXPECT_EQ(nftTxs.size(), 1); EXPECT_TRUE(nftDatas); - verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNftId); ASSERT_TRUE(nftDatas.has_value()); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); + verifyNFTsData(*nftDatas, sttx, txMeta, kNftId, kAccount); } TEST_F(NFTHelpersTest, NFTAcceptSellerOfferCheckFail) { // The only changed nft page is owned by ACCOUNT, thus can't find the new owner auto const tx = createAcceptNftSellerOfferTxWithMetadata( - kACCOUNT, 1, 2, kNFT_ID, kOFFER_ID, kPAGE_INDEX, true + kAccount, 1, 2, kNftId, kOfferId, kPageIndex, true ); - ripple::TxMeta const txMeta(ripple::uint256(kTX), 1, tx.metadata); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 1, tx.metadata); EXPECT_THROW( etl::getNFTDataFromTx( - txMeta, ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}) + txMeta, xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}) ), std::runtime_error ); @@ -456,15 +444,15 @@ TEST_F(NFTHelpersTest, NFTAcceptSellerOfferCheckFail) TEST_F(NFTHelpersTest, NFTAcceptSellerOfferNotInMeta) { auto const tx = createAcceptNftSellerOfferTxWithMetadata( - kACCOUNT, 1, 2, kNFT_ID, kOFFER_ID, kPAGE_INDEX, true + kAccount, 1, 2, kNftId, kOfferId, kPageIndex, true ); - ripple::TxMeta txMeta(ripple::uint256(kTX), 1, tx.metadata); + xrpl::TxMeta txMeta(xrpl::uint256(kTX), 1, tx.metadata); // inject a different offer id - txMeta.getNodes()[0].setFieldH256(ripple::sfLedgerIndex, ripple::uint256(kPAGE_INDEX)); + txMeta.getNodes()[0].setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256(kPageIndex)); EXPECT_THROW( etl::getNFTDataFromTx( - txMeta, ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}) + txMeta, xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}) ), std::runtime_error ); @@ -473,14 +461,14 @@ TEST_F(NFTHelpersTest, NFTAcceptSellerOfferNotInMeta) TEST_F(NFTHelpersTest, NFTAcceptSellerOfferZeroMetaNode) { auto const tx = createAcceptNftSellerOfferTxWithMetadata( - kACCOUNT2, 1, 2, kNFT_ID, kOFFER_ID, kPAGE_INDEX, true + kAccount2, 1, 2, kNftId, kOfferId, kPageIndex, true ); - ripple::TxMeta txMeta(ripple::uint256(kTX), 1, tx.metadata); + xrpl::TxMeta txMeta(xrpl::uint256(kTX), 1, tx.metadata); txMeta.getNodes().clear(); EXPECT_THROW( etl::getNFTDataFromTx( - txMeta, ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}) + txMeta, xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}) ), std::runtime_error ); @@ -489,18 +477,18 @@ TEST_F(NFTHelpersTest, NFTAcceptSellerOfferZeroMetaNode) TEST_F(NFTHelpersTest, NFTAcceptSellerOfferIDNotInMetaData) { auto const tx = createAcceptNftSellerOfferTxWithMetadata( - kACCOUNT2, 1, 2, kNFT_ID, kOFFER_ID, kPAGE_INDEX, true + kAccount2, 1, 2, kNftId, kOfferId, kPageIndex, true ); - ripple::TxMeta txMeta(ripple::uint256(kTX), 1, tx.metadata); + xrpl::TxMeta txMeta(xrpl::uint256(kTX), 1, tx.metadata); // The first node is offer, the second is nft page. Change the offer id to something else txMeta.getNodes()[0] - .getField(ripple::sfFinalFields) - .downcast() - .setFieldH256(ripple::sfNFTokenID, ripple::uint256(kNFT_ID2)); + .getField(xrpl::sfFinalFields) + .downcast() + .setFieldH256(xrpl::sfNFTokenID, xrpl::uint256(kNftID2)); EXPECT_THROW( etl::getNFTDataFromTx( - txMeta, ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}) + txMeta, xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}) ), std::runtime_error ); @@ -508,26 +496,25 @@ TEST_F(NFTHelpersTest, NFTAcceptSellerOfferIDNotInMetaData) TEST_F(NFTHelpersTest, NFTCreateOffer) { - auto const tx = createCreateNftOfferTxWithMetadata(kACCOUNT, 1, 2, kNFT_ID, 1, kOFFER_ID); - ripple::TxMeta const txMeta(ripple::uint256(kTX), 5, tx.metadata); - auto const sttx = - ripple::STTx(ripple::SerialIter{tx.transaction.data(), tx.transaction.size()}); + auto const tx = createCreateNftOfferTxWithMetadata(kAccount, 1, 2, kNftId, 1, kOfferId); + xrpl::TxMeta const txMeta(xrpl::uint256(kTX), 5, tx.metadata); + auto const sttx = xrpl::STTx(xrpl::SerialIter{tx.transaction.data(), tx.transaction.size()}); auto const [nftTxs, nftDatas] = etl::getNFTDataFromTx(txMeta, sttx); EXPECT_EQ(nftTxs.size(), 1); EXPECT_FALSE(nftDatas); - verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNftId); } TEST_F(NFTHelpersTest, NFTDataFromLedgerObject) { std::string const url1 = "abcd1"; std::string const url2 = "abcd2"; - ripple::Blob const uri1Blob(url1.begin(), url1.end()); - ripple::Blob const uri2Blob(url2.begin(), url2.end()); + xrpl::Blob const uri1Blob(url1.begin(), url1.end()); + xrpl::Blob const uri2Blob(url2.begin(), url2.end()); - auto const account = getAccountIdWithString(kACCOUNT); - auto const nftPage = createNftTokenPage({{kNFT_ID, url1}, {kNFT_ID2, url2}}, std::nullopt); + auto const account = getAccountIdWithString(kAccount); + auto const nftPage = createNftTokenPage({{kNftId, url1}, {kNftID2, url2}}, std::nullopt); auto const serializerNftPage = nftPage.getSerializer(); auto const blob = std::string( static_cast(serializerNftPage.getDataPtr()), serializerNftPage.getDataLength() @@ -536,24 +523,24 @@ TEST_F(NFTHelpersTest, NFTDataFromLedgerObject) // key is a token made up from owner's account ID followed by unused (in Clio) value described // here: // https://github.com/XRPLF/XRPL-Standards/tree/master/XLS-0020-non-fungible-tokens#tokenpage-id-format - constexpr auto kEXTRA_BYTES = "000000000000"; - auto const key = std::string(std::begin(account), std::end(account)) + kEXTRA_BYTES; + constexpr auto kExtraBytes = "000000000000"; + auto const key = std::string(std::begin(account), std::end(account)) + kExtraBytes; - uint32_t constexpr kSEQ{5}; - auto const nftDatas = etl::getNFTDataFromObj(kSEQ, key, blob); + uint32_t constexpr kSeq{5}; + auto const nftDatas = etl::getNFTDataFromObj(kSeq, key, blob); EXPECT_EQ(nftDatas.size(), 2); - EXPECT_EQ(nftDatas[0].tokenID, ripple::uint256(kNFT_ID)); + EXPECT_EQ(nftDatas[0].tokenID, xrpl::uint256(kNftId)); EXPECT_EQ(*(nftDatas[0].uri), uri1Blob); // NOLINT(bugprone-unchecked-optional-access) EXPECT_FALSE(nftDatas[0].onlyUriChanged); EXPECT_EQ(nftDatas[0].owner, account); - EXPECT_EQ(nftDatas[0].ledgerSequence, kSEQ); + EXPECT_EQ(nftDatas[0].ledgerSequence, kSeq); EXPECT_FALSE(nftDatas[0].isBurned); - EXPECT_EQ(nftDatas[1].tokenID, ripple::uint256(kNFT_ID2)); + EXPECT_EQ(nftDatas[1].tokenID, xrpl::uint256(kNftID2)); EXPECT_EQ(*(nftDatas[1].uri), uri2Blob); // NOLINT(bugprone-unchecked-optional-access) EXPECT_FALSE(nftDatas[1].onlyUriChanged); EXPECT_EQ(nftDatas[1].owner, account); - EXPECT_EQ(nftDatas[1].ledgerSequence, kSEQ); + EXPECT_EQ(nftDatas[1].ledgerSequence, kSeq); EXPECT_FALSE(nftDatas[1].isBurned); } diff --git a/tests/unit/etl/NetworkValidatedLedgersTests.cpp b/tests/unit/etl/NetworkValidatedLedgersTests.cpp index 3e188a943..101cc18ad 100644 --- a/tests/unit/etl/NetworkValidatedLedgersTests.cpp +++ b/tests/unit/etl/NetworkValidatedLedgersTests.cpp @@ -6,7 +6,6 @@ #include #include -#include #include #include @@ -31,9 +30,9 @@ TEST_F(NetworkValidatedLedgersTests, WaitUntilValidatedByNetworkWithoutTimeout) TEST_F(NetworkValidatedLedgersTests, WaitUntilValidatedByNetworkWithTimeout) { - static constexpr auto kTIMEOUT_MILLIS = 10u; + static constexpr auto kTimeoutMillis = 10u; auto awaitable = ctx_.execute([this] { - return ledgers_->waitUntilValidatedByNetwork(123u, kTIMEOUT_MILLIS); + return ledgers_->waitUntilValidatedByNetwork(123u, kTimeoutMillis); }); ledgers_->push(122u); diff --git a/tests/unit/etl/RegistryTests.cpp b/tests/unit/etl/RegistryTests.cpp index 7143f953a..9b515f429 100644 --- a/tests/unit/etl/RegistryTests.cpp +++ b/tests/unit/etl/RegistryTests.cpp @@ -42,7 +42,7 @@ struct Ext4SpecMissing { }; struct Ext4Fixed { - using spec = etl::model::Spec; + using spec = etl::model::Spec; static void onTransaction(uint32_t, etl::model::Transaction const&); @@ -59,7 +59,7 @@ struct Ext6SpecMissing { }; struct Ext6Fixed { - using spec = etl::model::Spec; + using spec = etl::model::Spec; static void onInitialTransaction(uint32_t, etl::model::Transaction const&); @@ -67,11 +67,11 @@ struct Ext6Fixed { struct ExtRealistic { using spec = etl::model::Spec< - ripple::TxType::ttNFTOKEN_BURN, - ripple::TxType::ttNFTOKEN_ACCEPT_OFFER, - ripple::TxType::ttNFTOKEN_CREATE_OFFER, - ripple::TxType::ttNFTOKEN_CANCEL_OFFER, - ripple::TxType::ttNFTOKEN_MINT>; + xrpl::TxType::ttNFTOKEN_BURN, + xrpl::TxType::ttNFTOKEN_ACCEPT_OFFER, + xrpl::TxType::ttNFTOKEN_CREATE_OFFER, + xrpl::TxType::ttNFTOKEN_CANCEL_OFFER, + xrpl::TxType::ttNFTOKEN_MINT>; static void onLedgerData(etl::model::LedgerData const&); @@ -98,13 +98,13 @@ static_assert(SomeExtension); static_assert(not SomeExtension); struct ValidSpec { - using spec = etl::model::Spec; + using spec = etl::model::Spec; }; // invalid spec does not compile: // struct DuplicatesSpec { -// using spec = etl::model::Spec; +// using spec = etl::model::Spec; // }; static_assert(ContainsSpec); @@ -113,9 +113,9 @@ static_assert(ContainsSpec); namespace { -constinit auto const kLEDGER_HASH = +constinit auto const kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constinit auto const kSEQ = 30; +constinit auto const kSeq = 30; struct MockExtLedgerData { MOCK_METHOD(void, onLedgerData, (etl::model::LedgerData const&), (const)); @@ -130,15 +130,15 @@ struct MockExtOnObject { }; struct MockExtTransactionNftBurn { - using spec = etl::model::Spec; + using spec = etl::model::Spec; MOCK_METHOD(void, onTransaction, (uint32_t, etl::model::Transaction const&), (const)); }; struct MockExtTransactionNftOffer { using spec = etl::model::Spec< - ripple::TxType::ttNFTOKEN_CREATE_OFFER, - ripple::TxType::ttNFTOKEN_CANCEL_OFFER, - ripple::TxType::ttNFTOKEN_ACCEPT_OFFER>; + xrpl::TxType::ttNFTOKEN_CREATE_OFFER, + xrpl::TxType::ttNFTOKEN_CANCEL_OFFER, + xrpl::TxType::ttNFTOKEN_ACCEPT_OFFER>; MOCK_METHOD(void, onTransaction, (uint32_t, etl::model::Transaction const&), (const)); }; @@ -156,15 +156,15 @@ struct MockExtInitialObjects { }; struct MockExtNftBurn { - using spec = etl::model::Spec; + using spec = etl::model::Spec; MOCK_METHOD(void, onInitialTransaction, (uint32_t, etl::model::Transaction const&), (const)); }; struct MockExtNftOffer { using spec = etl::model::Spec< - ripple::TxType::ttNFTOKEN_CREATE_OFFER, - ripple::TxType::ttNFTOKEN_CANCEL_OFFER, - ripple::TxType::ttNFTOKEN_ACCEPT_OFFER>; + xrpl::TxType::ttNFTOKEN_CREATE_OFFER, + xrpl::TxType::ttNFTOKEN_CANCEL_OFFER, + xrpl::TxType::ttNFTOKEN_ACCEPT_OFFER>; MOCK_METHOD(void, onInitialTransaction, (uint32_t, etl::model::Transaction const&), (const)); }; @@ -200,7 +200,7 @@ struct MockExtOnObjectReadonly { }; struct MockExtTransactionNftBurnReadonly { - using spec = etl::model::Spec; + using spec = etl::model::Spec; MOCK_METHOD(void, onTransaction, (uint32_t, etl::model::Transaction const&), (const)); static bool @@ -236,7 +236,7 @@ struct MockExtInitialObjectsReadonly { }; struct MockExtNftBurnReadonly { - using spec = etl::model::Spec; + using spec = etl::model::Spec; MOCK_METHOD(void, onInitialTransaction, (uint32_t, etl::model::Transaction const&), (const)); static bool @@ -261,9 +261,9 @@ protected: TEST_F(RegistryTest, FilteringOfTxWorksCorrectlyForInitialTransaction) { auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_CREATE_OFFER), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_CREATE_OFFER), }; auto extBurn = MockExtNftBurn{}; @@ -272,7 +272,7 @@ TEST_F(RegistryTest, FilteringOfTxWorksCorrectlyForInitialTransaction) EXPECT_CALL(extBurn, onInitialTransaction(testing::_, testing::_)).Times(2); // 2 burn txs EXPECT_CALL(extOffer, onInitialTransaction(testing::_, testing::_)); // 1 create offer - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry(state_, extBurn, extOffer); reg.dispatchInitialData( etl::model::LedgerData{ @@ -282,7 +282,7 @@ TEST_F(RegistryTest, FilteringOfTxWorksCorrectlyForInitialTransaction) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ, + .seq = kSeq, } ); } @@ -290,9 +290,9 @@ TEST_F(RegistryTest, FilteringOfTxWorksCorrectlyForInitialTransaction) TEST_F(RegistryTest, FilteringOfTxWorksCorrectlyForTransaction) { auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_CREATE_OFFER), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_CREATE_OFFER), }; auto extBurn = MockExtTransactionNftBurn{}; @@ -301,7 +301,7 @@ TEST_F(RegistryTest, FilteringOfTxWorksCorrectlyForTransaction) EXPECT_CALL(extBurn, onTransaction(testing::_, testing::_)).Times(2); // 2 burn txs EXPECT_CALL(extOffer, onTransaction(testing::_, testing::_)); // 1 create offer - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry( state_, extBurn, extOffer ); @@ -313,7 +313,7 @@ TEST_F(RegistryTest, FilteringOfTxWorksCorrectlyForTransaction) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); } @@ -329,7 +329,7 @@ TEST_F(RegistryTest, InitialObjectsEmpty) ); // 1 vector passed as is auto reg = Registry(state_, extObj, extObjs); - reg.dispatchInitialObjects(kSEQ, {}, {}); + reg.dispatchInitialObjects(kSeq, {}, {}); } TEST_F(RegistryTest, InitialObjectsDispatched) @@ -344,7 +344,7 @@ TEST_F(RegistryTest, InitialObjectsDispatched) auto reg = Registry(state_, extObj, extObjs); reg.dispatchInitialObjects( - kSEQ, {util::createObject(), util::createObject(), util::createObject()}, {} + kSeq, {util::createObject(), util::createObject(), util::createObject()}, {} ); } @@ -354,7 +354,7 @@ TEST_F(RegistryTest, ObjectsDispatched) EXPECT_CALL(extObj, onObject(testing::_, testing::_)).Times(3); // 3 objects sent - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry(state_, extObj); reg.dispatch( etl::model::LedgerData{ @@ -364,7 +364,7 @@ TEST_F(RegistryTest, ObjectsDispatched) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); } @@ -372,16 +372,16 @@ TEST_F(RegistryTest, ObjectsDispatched) TEST_F(RegistryTest, OnLedgerDataForBatch) { auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_CREATE_OFFER), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_CREATE_OFFER), }; auto ext = MockExtLedgerData{}; EXPECT_CALL(ext, onLedgerData(testing::_)); // 1 batch (dispatch call) - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry(state_, ext); reg.dispatch( etl::model::LedgerData{ @@ -391,7 +391,7 @@ TEST_F(RegistryTest, OnLedgerDataForBatch) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); } @@ -407,7 +407,7 @@ TEST_F(RegistryTest, InitialObjectsCorrectOrderOfHookCalls) auto reg = Registry(state_, extObj, extObjs); reg.dispatchInitialObjects( - kSEQ, {util::createObject(), util::createObject(), util::createObject()}, {} + kSeq, {util::createObject(), util::createObject(), util::createObject()}, {} ); } @@ -417,16 +417,16 @@ TEST_F(RegistryTest, InitialDataCorrectOrderOfHookCalls) auto extInitialTransaction = MockExtNftBurn{}; auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_CREATE_OFFER), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_CREATE_OFFER), }; testing::InSequence const seqGuard; EXPECT_CALL(extInitialData, onInitialData); EXPECT_CALL(extInitialTransaction, onInitialTransaction).Times(2); - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry( state_, extInitialTransaction, extInitialData ); @@ -438,7 +438,7 @@ TEST_F(RegistryTest, InitialDataCorrectOrderOfHookCalls) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); } @@ -450,9 +450,9 @@ TEST_F(RegistryTest, LedgerDataCorrectOrderOfHookCalls) auto extOnObject = MockExtOnObject{}; auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_CREATE_OFFER), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_CREATE_OFFER), }; auto objects = std::vector{ util::createObject(), @@ -466,7 +466,7 @@ TEST_F(RegistryTest, LedgerDataCorrectOrderOfHookCalls) EXPECT_CALL(extOnTransaction, onTransaction).Times(2); EXPECT_CALL(extOnObject, onObject).Times(3); - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry( state_, extOnObject, extOnTransaction, extLedgerData ); @@ -478,7 +478,7 @@ TEST_F(RegistryTest, LedgerDataCorrectOrderOfHookCalls) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); } @@ -486,8 +486,8 @@ TEST_F(RegistryTest, LedgerDataCorrectOrderOfHookCalls) TEST_F(RegistryTest, ReadonlyModeLedgerDataAllowed) { auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), }; auto ext = MockExtLedgerDataReadonly{}; @@ -495,7 +495,7 @@ TEST_F(RegistryTest, ReadonlyModeLedgerDataAllowed) EXPECT_CALL(ext, onLedgerData(testing::_)); - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry(state_, ext); reg.dispatch( etl::model::LedgerData{ @@ -505,7 +505,7 @@ TEST_F(RegistryTest, ReadonlyModeLedgerDataAllowed) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); } @@ -513,8 +513,8 @@ TEST_F(RegistryTest, ReadonlyModeLedgerDataAllowed) TEST_F(RegistryTest, ReadonlyModeTransactionAllowed) { auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), }; auto extTx = MockExtTransactionNftBurnReadonly{}; @@ -522,7 +522,7 @@ TEST_F(RegistryTest, ReadonlyModeTransactionAllowed) EXPECT_CALL(extTx, onTransaction(testing::_, testing::_)).Times(2); - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry(state_, extTx); reg.dispatch( etl::model::LedgerData{ @@ -532,7 +532,7 @@ TEST_F(RegistryTest, ReadonlyModeTransactionAllowed) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); } @@ -550,7 +550,7 @@ TEST_F(RegistryTest, ReadonlyModeObjectAllowed) EXPECT_CALL(extObj, onObject(testing::_, testing::_)).Times(3); - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry(state_, extObj); reg.dispatch( etl::model::LedgerData{ @@ -560,7 +560,7 @@ TEST_F(RegistryTest, ReadonlyModeObjectAllowed) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); } @@ -568,8 +568,8 @@ TEST_F(RegistryTest, ReadonlyModeObjectAllowed) TEST_F(RegistryTest, ReadonlyModeInitialDataAllowed) { auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), }; auto extInitialData = MockExtInitialDataReadonly{}; @@ -577,7 +577,7 @@ TEST_F(RegistryTest, ReadonlyModeInitialDataAllowed) EXPECT_CALL(extInitialData, onInitialData(testing::_)); - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry(state_, extInitialData); reg.dispatchInitialData( etl::model::LedgerData{ @@ -587,7 +587,7 @@ TEST_F(RegistryTest, ReadonlyModeInitialDataAllowed) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); } @@ -595,8 +595,8 @@ TEST_F(RegistryTest, ReadonlyModeInitialDataAllowed) TEST_F(RegistryTest, ReadonlyModeInitialTransactionAllowed) { auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), }; auto extTx = MockExtNftBurnReadonly{}; @@ -604,7 +604,7 @@ TEST_F(RegistryTest, ReadonlyModeInitialTransactionAllowed) EXPECT_CALL(extTx, onInitialTransaction(testing::_, testing::_)).Times(2); - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry(state_, extTx); reg.dispatchInitialData( etl::model::LedgerData{ @@ -614,7 +614,7 @@ TEST_F(RegistryTest, ReadonlyModeInitialTransactionAllowed) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); } @@ -628,7 +628,7 @@ TEST_F(RegistryTest, ReadonlyModeInitialObjectAllowed) auto reg = Registry(state_, extObj); reg.dispatchInitialObjects( - kSEQ, {util::createObject(), util::createObject(), util::createObject()}, {} + kSeq, {util::createObject(), util::createObject(), util::createObject()}, {} ); } @@ -641,7 +641,7 @@ TEST_F(RegistryTest, ReadonlyModeInitialObjectsAllowed) auto reg = Registry(state_, extObjs); reg.dispatchInitialObjects( - kSEQ, {util::createObject(), util::createObject(), util::createObject()}, {} + kSeq, {util::createObject(), util::createObject(), util::createObject()}, {} ); } @@ -659,7 +659,7 @@ TEST_F(RegistryTest, ReadonlyModeRegularExtensionsNotCalled) EXPECT_CALL(extLedgerData, onLedgerData(testing::_)) .Times(0); // Should NOT be called in readonly mode - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry(state_, extLedgerData); reg.dispatch( etl::model::LedgerData{ @@ -669,7 +669,7 @@ TEST_F(RegistryTest, ReadonlyModeRegularExtensionsNotCalled) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); } @@ -690,7 +690,7 @@ TEST_F(RegistryTest, MixedReadonlyAndRegularExtensions) EXPECT_CALL(extRegular, onLedgerData(testing::_)) .Times(0); // Should NOT be called in readonly mode - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry(state_, extReadonly, extRegular); reg.dispatch( @@ -701,7 +701,7 @@ TEST_F(RegistryTest, MixedReadonlyAndRegularExtensions) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); } @@ -728,9 +728,9 @@ TEST_F(RegistryTest, MonitorInterfaceExecution) }; auto monitor = MockMonitor{}; - EXPECT_CALL(monitor, notifySequenceLoaded(kSEQ)).Times(1); + EXPECT_CALL(monitor, notifySequenceLoaded(kSeq)).Times(1); - monitor.notifySequenceLoaded(kSEQ); + monitor.notifySequenceLoaded(kSeq); } TEST_F(RegistryTest, ReadonlyModeWithAllowInReadonlyTest) @@ -750,7 +750,7 @@ TEST_F(RegistryTest, ReadonlyModeWithAllowInReadonlyTest) EXPECT_CALL(ext, onLedgerData(testing::_)).Times(1); - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry(state_, ext); reg.dispatch( etl::model::LedgerData{ @@ -760,7 +760,7 @@ TEST_F(RegistryTest, ReadonlyModeWithAllowInReadonlyTest) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); } @@ -788,7 +788,7 @@ TEST_F(RegistryTest, ReadonlyModeExecutePluralHooksIfAllowedPaths) state_.isWriting = false; auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), }; auto objects = std::vector{ util::createObject(), @@ -798,7 +798,7 @@ TEST_F(RegistryTest, ReadonlyModeExecutePluralHooksIfAllowedPaths) EXPECT_CALL(ext, onInitialData(testing::_)).Times(1); EXPECT_CALL(ext, onInitialObjects(testing::_, testing::_, testing::_)).Times(1); - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry(state_, ext); reg.dispatch( @@ -809,7 +809,7 @@ TEST_F(RegistryTest, ReadonlyModeExecutePluralHooksIfAllowedPaths) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); @@ -821,17 +821,17 @@ TEST_F(RegistryTest, ReadonlyModeExecutePluralHooksIfAllowedPaths) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); - reg.dispatchInitialObjects(kSEQ, objects, {}); + reg.dispatchInitialObjects(kSeq, objects, {}); } TEST_F(RegistryTest, ReadonlyModeExecuteByOneHooksIfAllowedPaths) { struct ExtWithBothHooksAndAllowReadonly { - using spec = etl::model::Spec; + using spec = etl::model::Spec; MOCK_METHOD(void, onObject, (uint32_t, etl::model::Object const&), (const)); MOCK_METHOD(void, onInitialObject, (uint32_t, etl::model::Object const&), (const)); @@ -854,7 +854,7 @@ TEST_F(RegistryTest, ReadonlyModeExecuteByOneHooksIfAllowedPaths) state_.isWriting = false; auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), }; auto objects = std::vector{ util::createObject(), @@ -865,7 +865,7 @@ TEST_F(RegistryTest, ReadonlyModeExecuteByOneHooksIfAllowedPaths) EXPECT_CALL(ext, onInitialTransaction(testing::_, testing::_)).Times(1); EXPECT_CALL(ext, onInitialObject(testing::_, testing::_)).Times(1); - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); auto reg = Registry(state_, ext); reg.dispatch( @@ -876,7 +876,7 @@ TEST_F(RegistryTest, ReadonlyModeExecuteByOneHooksIfAllowedPaths) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); @@ -888,9 +888,9 @@ TEST_F(RegistryTest, ReadonlyModeExecuteByOneHooksIfAllowedPaths) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq } ); - reg.dispatchInitialObjects(kSEQ, objects, {}); + reg.dispatchInitialObjects(kSeq, objects, {}); } diff --git a/tests/unit/etl/SubscriptionSourceTests.cpp b/tests/unit/etl/SubscriptionSourceTests.cpp index 03f6db6c7..71c5bebcf 100644 --- a/tests/unit/etl/SubscriptionSourceTests.cpp +++ b/tests/unit/etl/SubscriptionSourceTests.cpp @@ -16,7 +16,6 @@ #include #include -#include #include #include #include diff --git a/tests/unit/etl/SystemStateTests.cpp b/tests/unit/etl/SystemStateTests.cpp index af99a5000..01367f45e 100644 --- a/tests/unit/etl/SystemStateTests.cpp +++ b/tests/unit/etl/SystemStateTests.cpp @@ -10,8 +10,6 @@ #include #include -#include - using namespace etl; using namespace util::config; diff --git a/tests/unit/etl/TaskManagerTests.cpp b/tests/unit/etl/TaskManagerTests.cpp index b3a6996ec..417c0d245 100644 --- a/tests/unit/etl/TaskManagerTests.cpp +++ b/tests/unit/etl/TaskManagerTests.cpp @@ -29,8 +29,8 @@ using namespace etl::impl; namespace { -constinit auto const kSEQ = 30; -constinit auto const kLEDGER_HASH = +constinit auto const kSeq = 30; +constinit auto const kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; struct MockScheduler : etl::SchedulerInterface { @@ -46,7 +46,7 @@ struct MockLoader : etl::LoaderInterface { using ExpectedType = std::expected; MOCK_METHOD(ExpectedType, load, (LedgerData const&), (override)); MOCK_METHOD( - std::optional, + std::optional, loadInitialLedger, (LedgerData const&), (override) @@ -91,14 +91,14 @@ protected: *mockExtractorPtr_, *mockLoaderPtr_, *mockMonitorPtr_, - kSEQ + kSeq }; }; auto createTestData(uint32_t seq) { - auto const header = createLedgerHeader(kLEDGER_HASH, seq); + auto const header = createLedgerHeader(kLedgerHash, seq); return LedgerData{ .transactions = {}, .objects = {util::createObject(), util::createObject(), util::createObject()}, @@ -114,10 +114,10 @@ createTestData(uint32_t seq) TEST_F(TaskManagerTests, LoaderGetsDataIfNextSequenceIsExtracted) { - static constexpr auto kTOTAL = 64uz; - static constexpr auto kEXTRACTORS = 4uz; + static constexpr auto kTotal = 64uz; + static constexpr auto kExtractors = 4uz; - std::atomic_uint32_t seq = kSEQ; + std::atomic_uint32_t seq = kSeq; std::vector loaded; std::binary_semaphore done{0}; @@ -127,40 +127,40 @@ TEST_F(TaskManagerTests, LoaderGetsDataIfNextSequenceIsExtracted) EXPECT_CALL(*mockExtractorPtr_, extractLedgerWithDiff(testing::_)) .WillRepeatedly([](uint32_t seq) -> std::optional { - if (seq > kSEQ + kTOTAL - 1) + if (seq > kSeq + kTotal - 1) return std::nullopt; return createTestData(seq); }); EXPECT_CALL(*mockLoaderPtr_, load(testing::_)) - .Times(kTOTAL) + .Times(kTotal) .WillRepeatedly([&](LedgerData data) -> std::expected { loaded.push_back(data.seq); - if (loaded.size() == kTOTAL) + if (loaded.size() == kTotal) done.release(); return {}; }); - EXPECT_CALL(*mockMonitorPtr_, notifySequenceLoaded(testing::_)).Times(kTOTAL); + EXPECT_CALL(*mockMonitorPtr_, notifySequenceLoaded(testing::_)).Times(kTotal); - taskManager_.run(kEXTRACTORS); + taskManager_.run(kExtractors); done.acquire(); taskManager_.stop(); - EXPECT_EQ(loaded.size(), kTOTAL); + EXPECT_EQ(loaded.size(), kTotal); for (std::size_t i = 0; i < loaded.size(); ++i) - EXPECT_EQ(loaded[i], kSEQ + i); + EXPECT_EQ(loaded[i], kSeq + i); } TEST_F(TaskManagerTests, WriteConflictHandling) { - static constexpr auto kTOTAL = 64uz; - static constexpr auto kCONFLICT_AFTER = 32uz; // Conflict after 32 ledgers - static constexpr auto kEXTRACTORS = 4uz; + static constexpr auto kTotal = 64uz; + static constexpr auto kConflictAfter = 32uz; // Conflict after 32 ledgers + static constexpr auto kExtractors = 4uz; - std::atomic_uint32_t seq = kSEQ; + std::atomic_uint32_t seq = kSeq; std::vector loaded; std::binary_semaphore done{0}; bool conflictOccurred = false; @@ -171,50 +171,50 @@ TEST_F(TaskManagerTests, WriteConflictHandling) EXPECT_CALL(*mockExtractorPtr_, extractLedgerWithDiff(testing::_)) .WillRepeatedly([](uint32_t seq) -> std::optional { - if (seq > kSEQ + kTOTAL - 1) + if (seq > kSeq + kTotal - 1) return std::nullopt; return createTestData(seq); }); - // First kCONFLICT_AFTER calls succeed, then we get a write conflict + // First kConflictAfter calls succeed, then we get a write conflict EXPECT_CALL(*mockLoaderPtr_, load(testing::_)) .WillRepeatedly([&](LedgerData data) -> std::expected { loaded.push_back(data.seq); - if (loaded.size() == kCONFLICT_AFTER) { + if (loaded.size() == kConflictAfter) { conflictOccurred = true; done.release(); return std::unexpected(etl::LoaderError::WriteConflict); } - if (loaded.size() == kTOTAL) + if (loaded.size() == kTotal) done.release(); return {}; }); - EXPECT_CALL(*mockMonitorPtr_, notifySequenceLoaded(testing::_)).Times(kCONFLICT_AFTER - 1); - EXPECT_CALL(*mockMonitorPtr_, notifyWriteConflict(kSEQ + kCONFLICT_AFTER - 1)); + EXPECT_CALL(*mockMonitorPtr_, notifySequenceLoaded(testing::_)).Times(kConflictAfter - 1); + EXPECT_CALL(*mockMonitorPtr_, notifyWriteConflict(kSeq + kConflictAfter - 1)); - taskManager_.run(kEXTRACTORS); + taskManager_.run(kExtractors); done.acquire(); taskManager_.stop(); - EXPECT_EQ(loaded.size(), kCONFLICT_AFTER); + EXPECT_EQ(loaded.size(), kConflictAfter); EXPECT_TRUE(conflictOccurred); for (std::size_t i = 0; i < loaded.size(); ++i) - EXPECT_EQ(loaded[i], kSEQ + i); + EXPECT_EQ(loaded[i], kSeq + i); } TEST_F(TaskManagerTests, AmendmentBlockedHandling) { - static constexpr auto kTOTAL = 64uz; - static constexpr auto kAMENDMENT_BLOCKED_AFTER = 20uz; // Amendment block after 20 ledgers - static constexpr auto kEXTRACTORS = 2uz; + static constexpr auto kTotal = 64uz; + static constexpr auto kAmendmentBlockedAfter = 20uz; // Amendment block after 20 ledgers + static constexpr auto kExtractors = 2uz; - std::atomic_uint32_t seq = kSEQ; + std::atomic_uint32_t seq = kSeq; std::vector loaded; std::binary_semaphore done{0}; bool amendmentBlockedOccurred = false; @@ -225,7 +225,7 @@ TEST_F(TaskManagerTests, AmendmentBlockedHandling) EXPECT_CALL(*mockExtractorPtr_, extractLedgerWithDiff(testing::_)) .WillRepeatedly([](uint32_t seq) -> std::optional { - if (seq > kSEQ + kTOTAL - 1) + if (seq > kSeq + kTotal - 1) return std::nullopt; return createTestData(seq); @@ -235,29 +235,29 @@ TEST_F(TaskManagerTests, AmendmentBlockedHandling) .WillRepeatedly([&](LedgerData data) -> std::expected { loaded.push_back(data.seq); - if (loaded.size() == kAMENDMENT_BLOCKED_AFTER) { + if (loaded.size() == kAmendmentBlockedAfter) { amendmentBlockedOccurred = true; done.release(); return std::unexpected(etl::LoaderError::AmendmentBlocked); } - if (loaded.size() == kTOTAL) + if (loaded.size() == kTotal) done.release(); return {}; }); EXPECT_CALL(*mockMonitorPtr_, notifySequenceLoaded(testing::_)) - .Times(kAMENDMENT_BLOCKED_AFTER - 1); + .Times(kAmendmentBlockedAfter - 1); EXPECT_CALL(*mockMonitorPtr_, notifyWriteConflict(testing::_)).Times(0); - taskManager_.run(kEXTRACTORS); + taskManager_.run(kExtractors); done.acquire(); taskManager_.stop(); - EXPECT_EQ(loaded.size(), kAMENDMENT_BLOCKED_AFTER); + EXPECT_EQ(loaded.size(), kAmendmentBlockedAfter); EXPECT_TRUE(amendmentBlockedOccurred); for (std::size_t i = 0; i < loaded.size(); ++i) - EXPECT_EQ(loaded[i], kSEQ + i); + EXPECT_EQ(loaded[i], kSeq + i); } diff --git a/tests/unit/etl/ext/CacheTests.cpp b/tests/unit/etl/ext/CacheTests.cpp index 8f75b0e9b..2b75f7020 100644 --- a/tests/unit/etl/ext/CacheTests.cpp +++ b/tests/unit/etl/ext/CacheTests.cpp @@ -17,16 +17,16 @@ using namespace etl::impl; using namespace data; namespace { -constinit auto const kSEQ = 123u; -constinit auto const kLEDGER_HASH = +constinit auto const kSeq = 123u; +constinit auto const kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constinit auto const kUNUSED_LAST_KEY = "unused"; +constinit auto const kUnusedLastKey = "unused"; auto createTestData() { auto objects = std::vector{util::createObject(), util::createObject(), util::createObject()}; - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); return etl::model::LedgerData{ .transactions = {}, .objects = std::move(objects), @@ -34,7 +34,7 @@ createTestData() .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq }; } @@ -71,9 +71,9 @@ TEST_F(CacheExtTests, OnInitialObjectsUpdateCache) { auto const objects = std::vector{util::createObject(), util::createObject()}; - EXPECT_CALL(cache_, update(objects, kSEQ)); + EXPECT_CALL(cache_, update(objects, kSeq)); - ext_.onInitialObjects(kSEQ, objects, kUNUSED_LAST_KEY); + ext_.onInitialObjects(kSeq, objects, kUnusedLastKey); } TEST_F(CacheExtTests, AllowInReadonlyReturnsTrue) diff --git a/tests/unit/etl/ext/CoreTests.cpp b/tests/unit/etl/ext/CoreTests.cpp index e11a6bc12..76a35c513 100644 --- a/tests/unit/etl/ext/CoreTests.cpp +++ b/tests/unit/etl/ext/CoreTests.cpp @@ -16,20 +16,20 @@ using namespace etl::impl; using namespace data; namespace { -constinit auto const kSEQ = 123u; -constinit auto const kLEDGER_HASH = +constinit auto const kSeq = 123u; +constinit auto const kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; auto createTestData() { auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_CREATE_OFFER), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_CREATE_OFFER), }; - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); return etl::model::LedgerData{ .transactions = std::move(transactions), .objects = {}, @@ -37,7 +37,7 @@ createTestData() .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq }; } @@ -74,16 +74,16 @@ TEST_F(CoreExtTests, OnInitialObjectWritesLedgerObject) { auto const data = util::createObject(); - EXPECT_CALL(*backend_, writeLedgerObject(auto{data.keyRaw}, kSEQ, auto{data.dataRaw})); + EXPECT_CALL(*backend_, writeLedgerObject(auto{data.keyRaw}, kSeq, auto{data.dataRaw})); - ext_.onInitialObject(kSEQ, data); + ext_.onInitialObject(kSeq, data); } TEST_F(CoreExtTests, OnObjectWritesLedgerObject) { auto const data = util::createObject(); - EXPECT_CALL(*backend_, writeLedgerObject(auto{data.keyRaw}, kSEQ, auto{data.dataRaw})); + EXPECT_CALL(*backend_, writeLedgerObject(auto{data.keyRaw}, kSeq, auto{data.dataRaw})); - ext_.onObject(kSEQ, data); + ext_.onObject(kSeq, data); } diff --git a/tests/unit/etl/ext/MPTTests.cpp b/tests/unit/etl/ext/MPTTests.cpp index 39c8859e7..4abd5053b 100644 --- a/tests/unit/etl/ext/MPTTests.cpp +++ b/tests/unit/etl/ext/MPTTests.cpp @@ -1,16 +1,36 @@ +#include "data/DBHelpers.hpp" #include "etl/Models.hpp" #include "etl/impl/ext/MPT.hpp" #include "rpc/RPCHelpers.hpp" #include "util/BinaryTestObject.hpp" +#include "util/MPTokenTestObjects.hpp" #include "util/MockBackendTestFixture.hpp" #include "util/MockPrometheus.hpp" #include "util/TestObject.hpp" #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include #include +#include +#include +#include +#include #include #include @@ -21,12 +41,14 @@ using namespace testing; namespace { -constinit auto const kSEQ = 123u; -constinit auto const kLEDGER_HASH = +constinit auto const kSeq = 123u; +constinit auto const kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constinit auto const kHOLDER_ACCOUNT = "rK1EX542EgA9m948JrJRaEzwLVEhqWvnr9"; +constinit auto const kHolderAccount = "rK1EX542EgA9m948JrJRaEzwLVEhqWvnr9"; +constinit auto const kHolderAccount2 = "rnd1nHuzceyQDqnLH8urWNr4QBKt4v7WVk"; +constinit auto const kMptIssuanceID = "000004C463C52827307480341125DA0577DEFC38405B0E3E"; -constinit auto const kTXN_HEX = +constinit auto const kTxnHex = "120039220000000024002DBD1A201B002DBDA36840000000000000017321EDECF25C029811CAD07AFD616EB75E3803" "E44D0D59A6826AC25FE3" "4A43626D2D157440244262E760314164843026CE2F100D0BFEB0DD6F75026FEB3F75FCAA943F5C874FF0411BC82A85" @@ -35,7 +57,7 @@ constinit auto const kTXN_HEX = "DE4F9978B8FCD8A50636" "30B5737DA605"; -constinit auto const kTXN_META = +constinit auto const kTxnMeta = "201C00000002F8E311007F562668E165750018E0AE5808C131BAF4C26441D2BCF76F8628774DFDF098B7250BE88114" "CEF330DB51154D8DEE24" "9CC3D6DFD04B91F648EE0115002DBD1817E0AF9FDE4F9978B8FCD8A5063630B5737DA605E1E1E511006425002DBD2F" @@ -50,25 +72,182 @@ constinit auto const kTXN_META = "00000024002DBD1B2D00" "000002624000000005F5E0FE8114CEF330DB51154D8DEE249CC3D6DFD04B91F648EEE1E1F1031000"; -constinit auto const kHASH = "6005B465CBBF7FA8E41AC0C0CD38491026D9411FCB7BA46E2AEBB3AF7654261B"; -constinit auto const kHASH2 = "6005B465CBBF7FA8E41AC0C0CD38491026D9411FCB7BA46E2AEBB3AF7654261C"; -constinit auto const kHASH3 = "6005B465CBBF7FA8E41AC0C0CD38491026D9411FCB7BA46E2AEBB3AF7654261D"; +constinit auto const kHash = "6005B465CBBF7FA8E41AC0C0CD38491026D9411FCB7BA46E2AEBB3AF7654261B"; +constinit auto const kHash2 = "6005B465CBBF7FA8E41AC0C0CD38491026D9411FCB7BA46E2AEBB3AF7654261C"; +constinit auto const kHash3 = "6005B465CBBF7FA8E41AC0C0CD38491026D9411FCB7BA46E2AEBB3AF7654261D"; + +// The issuance ID carried by the ltMPTOKEN CreatedNode in kTxnMeta. +constinit auto const kIssuanceID = "002DBD1817E0AF9FDE4F9978B8FCD8A5063630B5737DA605"; + +constinit auto const kAccount = "rM2AGCCCRb373FRuD8wHyUwUsh2dV4BW5Q"; +constinit auto const kAccount2 = "rnd1nHuzceyQDqnLH8urWNr4QBKt4v7WVk"; +constexpr auto kHighFanoutAccountCount = 1001u; + +xrpl::AccountID +accountIDFromSeed(std::uint32_t seed) +{ + std::array bytes{}; + bytes[16] = static_cast(seed >> 24); + bytes[17] = static_cast(seed >> 16); + bytes[18] = static_cast(seed >> 8); + bytes[19] = static_cast(seed); + return xrpl::AccountID::fromVoid(bytes.data()); +} + +xrpl::STObject +createAccountRootNode(xrpl::AccountID const& account) +{ + xrpl::STObject fields(xrpl::sfFinalFields); + fields.setAccountID(xrpl::sfAccount, account); + + xrpl::STObject node(xrpl::sfModifiedNode); + node.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltACCOUNT_ROOT); + node.setFieldH256(xrpl::sfLedgerIndex, xrpl::uint256{}); + node.set(std::move(fields)); + return node; +} + +// One Payment transaction touching two distinct issuances with three affected accounts. +etl::model::Transaction +createMultiIssuanceTransaction() +{ + xrpl::Slice const slice("test", 4); + xrpl::STObject tx(xrpl::sfTransaction); + tx.setFieldU16(xrpl::sfTransactionType, xrpl::ttPAYMENT); + tx.setAccountID(xrpl::sfAccount, getAccountIdWithString(kAccount)); + tx.setFieldAmount(xrpl::sfAmount, xrpl::STAmount(100, false)); + tx.setFieldAmount(xrpl::sfFee, xrpl::STAmount(10, false)); + tx.setAccountID(xrpl::sfDestination, getAccountIdWithString(kAccount2)); + tx.setFieldU32(xrpl::sfSequence, 1); + tx.setFieldVL(xrpl::sfSigningPubKey, slice); + + auto const serialized = tx.getSerializer(); + auto const sttx = xrpl::STTx{xrpl::SerialIter{serialized.slice()}}; + + auto const issuanceA = xrpl::makeMptID(1, getAccountIdWithString(kHolderAccount)); + auto const issuanceB = xrpl::makeMptID(2, getAccountIdWithString(kHolderAccount)); + + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); + + xrpl::STArray affectedNodes(xrpl::sfAffectedNodes); + affectedNodes.push_back(util::createMPTokenNode(xrpl::sfModifiedNode, issuanceA, kAccount)); + affectedNodes.push_back(util::createMPTokenNode(xrpl::sfModifiedNode, issuanceB, kAccount2)); + affectedNodes.push_back( + util::createMPTokenIssuanceNode(xrpl::sfModifiedNode, 1, kHolderAccount) + ); // issuanceA again + metaObj.setFieldArray(xrpl::sfAffectedNodes, affectedNodes); + + auto const txMeta = + xrpl::TxMeta{sttx.getTransactionID(), kSeq, metaObj.getSerializer().peekData()}; + + return etl::model::Transaction{ + .raw = "", + .metaRaw = "", + .sttx = sttx, + .meta = txMeta, + .id = sttx.getTransactionID(), + .key = "0000000000000000000000000000000000000000000000000000000000000002", + .type = sttx.getTxnType() + }; +} + +etl::model::Transaction +createHighFanoutIssuanceTransaction() +{ + xrpl::Slice const slice("test", 4); + xrpl::STObject tx(xrpl::sfTransaction); + tx.setFieldU16(xrpl::sfTransactionType, xrpl::ttPAYMENT); + tx.setAccountID(xrpl::sfAccount, getAccountIdWithString(kAccount)); + tx.setFieldAmount(xrpl::sfAmount, xrpl::STAmount(100, false)); + tx.setFieldAmount(xrpl::sfFee, xrpl::STAmount(10, false)); + tx.setAccountID(xrpl::sfDestination, getAccountIdWithString(kAccount2)); + tx.setFieldU32(xrpl::sfSequence, 1); + tx.setFieldVL(xrpl::sfSigningPubKey, slice); + + auto const serialized = tx.getSerializer(); + auto const sttx = xrpl::STTx{xrpl::SerialIter{serialized.slice()}}; + + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); + + xrpl::STArray affectedNodes(xrpl::sfAffectedNodes); + affectedNodes.push_back( + util::createMPTokenNode(xrpl::sfModifiedNode, xrpl::uint192{kMptIssuanceID}, kHolderAccount) + ); + for (std::uint32_t i = 0; i < kHighFanoutAccountCount; ++i) + affectedNodes.push_back(createAccountRootNode(accountIDFromSeed(i + 1))); + metaObj.setFieldArray(xrpl::sfAffectedNodes, affectedNodes); + + auto const txMeta = + xrpl::TxMeta{sttx.getTransactionID(), kSeq, metaObj.getSerializer().peekData()}; + + return etl::model::Transaction{ + .raw = "", + .metaRaw = "", + .sttx = sttx, + .meta = txMeta, + .id = sttx.getTransactionID(), + .key = "0000000000000000000000000000000000000000000000000000000000000003", + .type = sttx.getTxnType() + }; +} auto -createTestData() +createTransactionFromObjects( + xrpl::STObject const& txObj, + xrpl::STObject const& metaObj, + xrpl::TxType type +) { - auto transactions = std::vector{ - util::createTransaction( - ripple::TxType::ttMPTOKEN_ISSUANCE_CREATE - ), // not AUTHORIZE so will not be written - util::createTransaction(ripple::TxType::ttMPTOKEN_AUTHORIZE, kHASH, kTXN_META, kTXN_HEX), - util::createTransaction(ripple::TxType::ttAMM_CREATE), // not MPT - will be filtered - util::createTransaction( - ripple::TxType::ttMPTOKEN_ISSUANCE_CREATE - ), // not unique - will be filtered - }; + auto const txBlob = txObj.getSerializer().peekData(); + auto const metaBlob = metaObj.getSerializer().peekData(); - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + xrpl::SerialIter txIter{txBlob.data(), txBlob.size()}; + xrpl::uint256 const id{kHash}; + + return etl::model::Transaction{ + .raw = "", + .metaRaw = "", + .sttx = xrpl::STTx{txIter}, + .meta = xrpl::TxMeta{id, kSeq, metaBlob}, + .id = id, + .key = std::string{kHash}, + .type = type + }; +} + +xrpl::STObject +createPaymentMetaWithNewMPTokens(xrpl::TER result = xrpl::tesSUCCESS) +{ + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + metaObj.setFieldU8(xrpl::sfTransactionResult, TERtoInt(result)); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 0); + + xrpl::STArray affectedNodes(xrpl::sfAffectedNodes); + affectedNodes.push_back( + util::createMPTokenNode(xrpl::sfCreatedNode, xrpl::uint192{kMptIssuanceID}, kHolderAccount) + ); + affectedNodes.push_back( + util::createMPTokenNode(xrpl::sfCreatedNode, xrpl::uint192{kMptIssuanceID}, kHolderAccount2) + ); + metaObj.setFieldArray(xrpl::sfAffectedNodes, affectedNodes); + + return metaObj; +} + +auto +createPaymentWithMultipleHoldersTestData(xrpl::TER result = xrpl::tesSUCCESS) +{ + auto transactions = std::vector{createTransactionFromObjects( + createPaymentTransactionObject(kHolderAccount, kHolderAccount2, 1, 1, 1), + createPaymentMetaWithNewMPTokens(result), + xrpl::TxType::ttPAYMENT + )}; + + auto const header = createLedgerHeader(kLedgerHash, kSeq); return etl::model::LedgerData{ .transactions = std::move(transactions), .objects = {}, @@ -76,20 +255,89 @@ createTestData() .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq }; } +auto +createTestDataWithoutMPToken() +{ + auto transactions = std::vector{ + util::createTransaction( + xrpl::TxType::ttMPTOKEN_ISSUANCE_CREATE + ), // metadata does not create an MPT holder + util::createTransaction(xrpl::TxType::ttAMM_CREATE), // metadata is not MPT + }; + + auto const header = createLedgerHeader(kLedgerHash, kSeq); + return etl::model::LedgerData{ + .transactions = std::move(transactions), + .objects = {}, + .successors = {}, + .edgeKeys = {}, + .header = header, + .rawHeader = {}, + .seq = kSeq + }; +} + +auto +createTestData() +{ + // Only the AUTHORIZE transaction carries metadata with MPT affected nodes. + auto transactions = std::vector{ + util::createTransaction( + xrpl::TxType::ttMPTOKEN_ISSUANCE_CREATE + ), // metadata does not create an MPT holder + util::createTransaction(xrpl::TxType::ttMPTOKEN_AUTHORIZE, kHash, kTxnMeta, kTxnHex), + util::createTransaction(xrpl::TxType::ttAMM_CREATE), // metadata is not MPT + util::createTransaction( + xrpl::TxType::ttMPTOKEN_ISSUANCE_CREATE + ), // metadata does not create an MPT holder + }; + + auto const header = createLedgerHeader(kLedgerHash, kSeq); + return etl::model::LedgerData{ + .transactions = std::move(transactions), + .objects = {}, + .successors = {}, + .edgeKeys = {}, + .header = header, + .rawHeader = {}, + .seq = kSeq + }; +} + +// Same AUTHORIZE fixture as kTxnMeta, with a distinct transaction index. +etl::model::Transaction +createAuthorizeTransactionWithIndex(std::string const& hashStr, std::uint32_t txIndex) +{ + auto tx = + util::createTransaction(xrpl::TxType::ttMPTOKEN_AUTHORIZE, hashStr, kTxnMeta, kTxnHex); + + auto const metaBlob = xrpl::strUnHex(kTxnMeta); + EXPECT_TRUE(metaBlob.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + xrpl::SerialIter sitMeta{xrpl::makeSlice(*metaBlob)}; + xrpl::STObject metaObj{sitMeta, xrpl::sfMetadata}; + metaObj.setFieldU32(xrpl::sfTransactionIndex, txIndex); + + xrpl::uint256 hash; + EXPECT_TRUE(hash.parseHex(hashStr)); + tx.meta = xrpl::TxMeta{hash, kSeq, metaObj.getSerializer().peekData()}; + return tx; +} + auto createMultipleHoldersTestData() { auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttMPTOKEN_AUTHORIZE, kHASH, kTXN_META, kTXN_HEX), - util::createTransaction(ripple::TxType::ttMPTOKEN_AUTHORIZE, kHASH2, kTXN_META, kTXN_HEX), - util::createTransaction(ripple::TxType::ttMPTOKEN_AUTHORIZE, kHASH3, kTXN_META, kTXN_HEX) + createAuthorizeTransactionWithIndex(kHash, 0), + createAuthorizeTransactionWithIndex(kHash2, 1), + createAuthorizeTransactionWithIndex(kHash3, 2) }; - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); return etl::model::LedgerData{ .transactions = std::move(transactions), .objects = {}, @@ -97,7 +345,7 @@ createMultipleHoldersTestData() .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq }; } @@ -113,10 +361,23 @@ TEST_F(MPTExtTests, OnLedgerDataFiltersAndWritesMPTs) auto const data = createTestData(); EXPECT_CALL(*backend_, writeMPTHolders).WillOnce([](auto const& holders) { - EXPECT_EQ(holders.size(), 1); // Only AUTHORIZE is written in the end + EXPECT_EQ(holders.size(), 1); // Only metadata creating an MPToken is written }); + std::vector issuanceTxs; + std::vector accountIssuanceTxs; + EXPECT_CALL(*backend_, writeMPTokenIssuanceTransactions).WillOnce(SaveArg<0>(&issuanceTxs)); + EXPECT_CALL(*backend_, writeAccountMPTokenIssuanceTransactions) + .WillOnce(SaveArg<0>(&accountIssuanceTxs)); + ext_.onLedgerData(data); + + // Only the AUTHORIZE fixture touches an MPT object. + ASSERT_EQ(issuanceTxs.size(), 1); + EXPECT_EQ(issuanceTxs[0].mptIssuanceID, xrpl::uint192(kIssuanceID)); + EXPECT_FALSE(issuanceTxs[0].accounts.empty()); + EXPECT_TRUE(issuanceTxs[0].accounts.contains(getAccountIdWithString(kHolderAccount))); + EXPECT_EQ(issuanceTxs, accountIssuanceTxs); // same vector goes to both tables } TEST_F(MPTExtTests, OnInitialDataFiltersAndWritesMPTs) @@ -124,10 +385,23 @@ TEST_F(MPTExtTests, OnInitialDataFiltersAndWritesMPTs) auto const data = createTestData(); EXPECT_CALL(*backend_, writeMPTHolders).WillOnce([](auto const& holders) { - EXPECT_EQ(holders.size(), 1); // Only AUTHORIZE is written in the end + EXPECT_EQ(holders.size(), 1); // Only metadata creating an MPToken is written }); + std::vector issuanceTxs; + std::vector accountIssuanceTxs; + EXPECT_CALL(*backend_, writeMPTokenIssuanceTransactions).WillOnce(SaveArg<0>(&issuanceTxs)); + EXPECT_CALL(*backend_, writeAccountMPTokenIssuanceTransactions) + .WillOnce(SaveArg<0>(&accountIssuanceTxs)); + ext_.onInitialData(data); + + // Only the AUTHORIZE fixture touches an MPT object. + ASSERT_EQ(issuanceTxs.size(), 1); + EXPECT_EQ(issuanceTxs[0].mptIssuanceID, xrpl::uint192(kIssuanceID)); + EXPECT_FALSE(issuanceTxs[0].accounts.empty()); + EXPECT_TRUE(issuanceTxs[0].accounts.contains(getAccountIdWithString(kHolderAccount))); + EXPECT_EQ(issuanceTxs, accountIssuanceTxs); // same vector goes to both tables } TEST_F(MPTExtTests, OnInitialObjectWritesMPT) @@ -138,7 +412,7 @@ TEST_F(MPTExtTests, OnInitialObjectWritesMPT) EXPECT_EQ(holders.size(), 1); }); - ext_.onInitialObject(kSEQ, data); + ext_.onInitialObject(kSeq, data); } TEST_F(MPTExtTests, OnInitialDataWithMultipleHolders) @@ -146,14 +420,173 @@ TEST_F(MPTExtTests, OnInitialDataWithMultipleHolders) auto const data = createMultipleHoldersTestData(); EXPECT_CALL(*backend_, writeMPTHolders).WillOnce([](auto const& holders) { - EXPECT_EQ(holders.size(), 3); // Expect all three AUTHORIZE transactions + EXPECT_EQ(holders.size(), 3); // All three AUTHORIZE transactions auto const expectedAccount = - rpc::accountFromStringStrict(kHOLDER_ACCOUNT); // Expect all three to be the same + rpc::accountFromStringStrict(kHolderAccount); // Same holder in each fixture EXPECT_TRUE(std::ranges::all_of(holders, [&expectedAccount](auto const& data) { return data.holder == expectedAccount; })); }); + std::vector issuanceTxs; + std::vector accountIssuanceTxs; + EXPECT_CALL(*backend_, writeMPTokenIssuanceTransactions).WillOnce(SaveArg<0>(&issuanceTxs)); + EXPECT_CALL(*backend_, writeAccountMPTokenIssuanceTransactions) + .WillOnce(SaveArg<0>(&accountIssuanceTxs)); + + ext_.onInitialData(data); + + // One record per AUTHORIZE transaction; each has a distinct transaction index. + ASSERT_EQ(issuanceTxs.size(), 3); + EXPECT_TRUE(std::ranges::all_of(issuanceTxs, [](auto const& record) { + return record.mptIssuanceID == xrpl::uint192(kIssuanceID); + })); + std::vector indices; + std::ranges::transform(issuanceTxs, std::back_inserter(indices), [](auto const& record) { + return record.transactionIndex; + }); + EXPECT_THAT(indices, UnorderedElementsAre(0, 1, 2)); + EXPECT_EQ(issuanceTxs, accountIssuanceTxs); +} + +TEST_F(MPTExtTests, NoMPTTransactionsWritesNothing) +{ + auto transactions = std::vector{ + util::createTransaction(xrpl::TxType::ttAMM_CREATE), + util::createTransaction(xrpl::TxType::ttAMM_CREATE) + }; + + auto const header = createLedgerHeader(kLedgerHash, kSeq); + auto const data = etl::model::LedgerData{ + .transactions = std::move(transactions), + .objects = {}, + .successors = {}, + .edgeKeys = {}, + .header = header, + .rawHeader = {}, + .seq = kSeq + }; + + EXPECT_CALL(*backend_, writeMPTHolders).Times(0); + EXPECT_CALL(*backend_, writeMPTokenIssuanceTransactions).Times(0); + EXPECT_CALL(*backend_, writeAccountMPTokenIssuanceTransactions).Times(0); + + ext_.onLedgerData(data); +} + +TEST_F(MPTExtTests, OnLedgerDataDedupsMultiIssuanceFanout) +{ + auto transactions = std::vector{createMultiIssuanceTransaction()}; + + auto const header = createLedgerHeader(kLedgerHash, kSeq); + auto const data = etl::model::LedgerData{ + .transactions = std::move(transactions), + .objects = {}, + .successors = {}, + .edgeKeys = {}, + .header = header, + .rawHeader = {}, + .seq = kSeq + }; + + std::vector issuanceTxs; + std::vector accountIssuanceTxs; + EXPECT_CALL(*backend_, writeMPTokenIssuanceTransactions).WillOnce(SaveArg<0>(&issuanceTxs)); + EXPECT_CALL(*backend_, writeAccountMPTokenIssuanceTransactions) + .WillOnce(SaveArg<0>(&accountIssuanceTxs)); + + ext_.onLedgerData(data); + + // issuanceA is touched twice, issuanceB once; each record carries the full account set. + auto const issuanceA = xrpl::makeMptID(1, getAccountIdWithString(kHolderAccount)); + auto const issuanceB = xrpl::makeMptID(2, getAccountIdWithString(kHolderAccount)); + + ASSERT_EQ(issuanceTxs.size(), 2); + EXPECT_EQ(issuanceTxs[0].mptIssuanceID, issuanceA); + EXPECT_EQ(issuanceTxs[1].mptIssuanceID, issuanceB); + for (auto const& record : issuanceTxs) { + EXPECT_EQ(record.accounts.size(), 3); + EXPECT_TRUE(record.accounts.contains(getAccountIdWithString(kAccount))); + EXPECT_TRUE(record.accounts.contains(getAccountIdWithString(kAccount2))); + EXPECT_TRUE(record.accounts.contains(getAccountIdWithString(kHolderAccount))); + EXPECT_EQ(record.ledgerSequence, kSeq); + } + EXPECT_EQ(issuanceTxs, accountIssuanceTxs); +} + +TEST_F(MPTExtTests, OnLedgerDataWritesHighFanoutIssuanceIndexWithoutHolders) +{ + auto transactions = std::vector{createHighFanoutIssuanceTransaction()}; + + auto const header = createLedgerHeader(kLedgerHash, kSeq); + auto const data = etl::model::LedgerData{ + .transactions = std::move(transactions), + .objects = {}, + .successors = {}, + .edgeKeys = {}, + .header = header, + .rawHeader = {}, + .seq = kSeq + }; + + EXPECT_CALL(*backend_, writeMPTHolders).Times(0); + + std::vector issuanceTxs; + std::vector accountIssuanceTxs; + EXPECT_CALL(*backend_, writeMPTokenIssuanceTransactions).WillOnce(SaveArg<0>(&issuanceTxs)); + EXPECT_CALL(*backend_, writeAccountMPTokenIssuanceTransactions) + .WillOnce(SaveArg<0>(&accountIssuanceTxs)); + + ext_.onLedgerData(data); + + ASSERT_EQ(issuanceTxs.size(), 1); + EXPECT_EQ(issuanceTxs[0].mptIssuanceID, xrpl::uint192{kMptIssuanceID}); + EXPECT_GT(issuanceTxs[0].accounts.size(), kHighFanoutAccountCount); + EXPECT_EQ(issuanceTxs[0].ledgerSequence, kSeq); + EXPECT_EQ(issuanceTxs, accountIssuanceTxs); +} + +TEST_F(MPTExtTests, OnInitialDataDoesNotWriteFailedMPTokenCreations) +{ + auto const data = createPaymentWithMultipleHoldersTestData(xrpl::tecINCOMPLETE); + + EXPECT_CALL(*backend_, writeMPTHolders).Times(0); + + ext_.onInitialData(data); +} + +TEST_F(MPTExtTests, OnInitialDataDoesNotWriteWithoutCreatedMPToken) +{ + auto const data = createTestDataWithoutMPToken(); + + EXPECT_CALL(*backend_, writeMPTHolders).Times(0); + + ext_.onInitialData(data); +} + +TEST_F(MPTExtTests, OnInitialDataWritesAllMPTsCreatedByPayment) +{ + auto const data = createPaymentWithMultipleHoldersTestData(); + auto const expectedMptID = xrpl::uint192{kMptIssuanceID}; + auto const expectedAccount = getAccountIdWithString(kHolderAccount); + auto const expectedAccount2 = getAccountIdWithString(kHolderAccount2); + + EXPECT_CALL(*backend_, writeMPTHolders).WillOnce([&](auto const& holders) { + EXPECT_THAT( + holders, + UnorderedElementsAre( + AllOf( + Field(&MPTHolderData::mptID, expectedMptID), + Field(&MPTHolderData::holder, expectedAccount) + ), + AllOf( + Field(&MPTHolderData::mptID, expectedMptID), + Field(&MPTHolderData::holder, expectedAccount2) + ) + ) + ); + }); + ext_.onInitialData(data); } diff --git a/tests/unit/etl/ext/NFTTests.cpp b/tests/unit/etl/ext/NFTTests.cpp index 15308d0ef..82b7e4c66 100644 --- a/tests/unit/etl/ext/NFTTests.cpp +++ b/tests/unit/etl/ext/NFTTests.cpp @@ -16,11 +16,11 @@ using namespace etl::impl; using namespace data; namespace { -constinit auto const kSEQ = 123u; -constinit auto const kLEDGER_HASH = +constinit auto const kSeq = 123u; +constinit auto const kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constinit auto const kTXN_HEX2 = +constinit auto const kTxnHeX2 = "12001D230606B58324048A8B6F501C50E8EBCD412E6CF9D0C2EB6D38BDE1E1C83406AFCB45437DF39A8B0677A9487E" "501DA2A1BC9A62AAEB2A" "2A70F895587A3FB752514AA03F8C6E7C84864653B8673E0368400000000000001E60134000000000001F09732103B8" @@ -31,7 +31,7 @@ constinit auto const kTXN_HEX2 = "9425204A8491C73B1301" "E34FF9EA7D0F7872702E63616665202D2073616C65E1F1"; -constinit auto const kTXN_META2 = +constinit auto const kTxnMetA2 = "201C00000040F8E51100502505A59E11552ABC2FD74D879BE58489A588838AA2BA59E1E05A48A574226CD8B6CE7799" "8971560B639A808E3B97" "42A25334E5CF68EEDEDE52F54E50F4E63921C9F3C40588E426E6FAEC5A000827104B18F97F9209869C9E9CC33EC2AA" @@ -383,19 +383,19 @@ constinit auto const kTXN_META2 = "C2926F1ADA669262B5D362BFC2DB1417D837CBF382AA37F2D88214246B3E06AB367AB9614566B6F90C718B52A44408" "E1E1F1031000"; -constinit auto const kHASH2 = "D7604B124D5D9C89EC1854A6CBD5A1FFD92502E945411B9C8DE397E7F19A74F8"; +constinit auto const kHash2 = "D7604B124D5D9C89EC1854A6CBD5A1FFD92502E945411B9C8DE397E7F19A74F8"; auto createTestData() { auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN, kHASH2, kTXN_META2, kTXN_HEX2), - util::createTransaction(ripple::TxType::ttAMM_CREATE), // not NFT - will be filtered - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), // not unique - will be filtered + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN, kHash2, kTxnMetA2, kTxnHeX2), + util::createTransaction(xrpl::TxType::ttAMM_CREATE), // not NFT - will be filtered + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), // not unique - will be filtered }; - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); return etl::model::LedgerData{ .transactions = std::move(transactions), .objects = {}, @@ -403,7 +403,7 @@ createTestData() .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq }; } @@ -444,5 +444,5 @@ TEST_F(NFTExtTests, OnInitialObjectExtractsAndWritesNFTData) EXPECT_CALL(*backend_, writeNFTs).WillOnce([](auto const& nfts) { EXPECT_EQ(nfts.size(), 2); }); - ext_.onInitialObject(kSEQ, data); + ext_.onInitialObject(kSeq, data); } diff --git a/tests/unit/etl/ext/SuccessorTests.cpp b/tests/unit/etl/ext/SuccessorTests.cpp index 183222011..4f23f8fc3 100644 --- a/tests/unit/etl/ext/SuccessorTests.cpp +++ b/tests/unit/etl/ext/SuccessorTests.cpp @@ -29,20 +29,20 @@ using namespace etl::impl; using namespace data; namespace { -constinit auto const kSEQ = 123u; -constinit auto const kLEDGER_HASH = +constinit auto const kSeq = 123u; +constinit auto const kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; auto createTestData(std::vector objects) { auto transactions = std::vector{ - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_BURN), - util::createTransaction(ripple::TxType::ttNFTOKEN_CREATE_OFFER), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_BURN), + util::createTransaction(xrpl::TxType::ttNFTOKEN_CREATE_OFFER), }; - auto const header = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const header = createLedgerHeader(kLedgerHash, kSeq); return etl::model::LedgerData{ .transactions = std::move(transactions), .objects = std::move(objects), @@ -50,12 +50,12 @@ createTestData(std::vector objects) .edgeKeys = {}, .header = header, .rawHeader = {}, - .seq = kSEQ + .seq = kSeq }; } [[maybe_unused]] auto -createInitialTestData(std::vector edgeKeys) +createInitialTestData(std::vector edgeKeys) { // initial data expects objects to be empty as well as non-empty edgeKeys ASSERT(not edgeKeys.empty(), "Initial data requires edgeKeys"); @@ -80,7 +80,7 @@ TEST_F(SuccessorExtTests, OnLedgerDataLogicErrorIfCacheIsNotFullButSuccessorsNot auto const data = createTestData({}); EXPECT_CALL(cache_, isFull()).WillRepeatedly(testing::Return(false)); - EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSEQ)); + EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSeq)); EXPECT_THROW(ext_.onLedgerData(data), std::logic_error); } @@ -93,7 +93,7 @@ TEST_F( auto const data = createTestData({}); EXPECT_CALL(cache_, isFull()).WillRepeatedly(testing::Return(true)); - EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSEQ - 1)); + EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSeq - 1)); EXPECT_THROW(ext_.onLedgerData(data), std::logic_error); } @@ -113,18 +113,18 @@ TEST_F( }); EXPECT_CALL(cache_, isFull()).WillRepeatedly(testing::Return(true)); - EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSEQ)); + EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSeq)); - EXPECT_CALL(cache_, getPredecessor(deletedObj.key, kSEQ)) + EXPECT_CALL(cache_, getPredecessor(deletedObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); - EXPECT_CALL(cache_, getSuccessor(deletedObj.key, kSEQ)) + EXPECT_CALL(cache_, getSuccessor(deletedObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); EXPECT_CALL( *backend_, - writeSuccessor(uint256ToString(data::kFIRST_KEY), kSEQ, uint256ToString(data::kLAST_KEY)) + writeSuccessor(uint256ToString(data::kFirstKey), kSeq, uint256ToString(data::kLastKey)) ); - EXPECT_CALL(cache_, getDeleted(deletedObj.key, kSEQ - 1)) + EXPECT_CALL(cache_, getDeleted(deletedObj.key, kSeq - 1)) .WillRepeatedly(testing::Return(Blob{'0'})); ext_.onLedgerData(data); @@ -145,20 +145,20 @@ TEST_F( }); EXPECT_CALL(cache_, isFull()).WillRepeatedly(testing::Return(true)); - EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSEQ)); + EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSeq)); - EXPECT_CALL(cache_, getPredecessor(createdObj.key, kSEQ)) + EXPECT_CALL(cache_, getPredecessor(createdObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); - EXPECT_CALL(cache_, getSuccessor(createdObj.key, kSEQ)) + EXPECT_CALL(cache_, getSuccessor(createdObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); EXPECT_CALL( *backend_, - writeSuccessor(uint256ToString(data::kFIRST_KEY), kSEQ, uint256ToString(createdObj.key)) + writeSuccessor(uint256ToString(data::kFirstKey), kSeq, uint256ToString(createdObj.key)) ); EXPECT_CALL( *backend_, - writeSuccessor(uint256ToString(createdObj.key), kSEQ, uint256ToString(data::kLAST_KEY)) + writeSuccessor(uint256ToString(createdObj.key), kSeq, uint256ToString(data::kLastKey)) ); ext_.onLedgerData(data); @@ -180,24 +180,24 @@ TEST_F( auto const bookBase = getBookBase(createdObj.key); EXPECT_CALL(cache_, isFull()).WillRepeatedly(testing::Return(true)); - EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSEQ)); + EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSeq)); - EXPECT_CALL(cache_, getPredecessor(createdObj.key, kSEQ)) + EXPECT_CALL(cache_, getPredecessor(createdObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); - EXPECT_CALL(cache_, getSuccessor(createdObj.key, kSEQ)) + EXPECT_CALL(cache_, getSuccessor(createdObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); EXPECT_CALL( *backend_, - writeSuccessor(uint256ToString(data::kFIRST_KEY), kSEQ, uint256ToString(createdObj.key)) + writeSuccessor(uint256ToString(data::kFirstKey), kSeq, uint256ToString(createdObj.key)) ); EXPECT_CALL( *backend_, - writeSuccessor(uint256ToString(createdObj.key), kSEQ, uint256ToString(data::kLAST_KEY)) + writeSuccessor(uint256ToString(createdObj.key), kSeq, uint256ToString(data::kLastKey)) ); - EXPECT_CALL(cache_, get(createdObj.key, kSEQ)).WillRepeatedly(testing::Return(std::nullopt)); - EXPECT_CALL(cache_, getSuccessor(bookBase, kSEQ)) + EXPECT_CALL(cache_, get(createdObj.key, kSeq)).WillRepeatedly(testing::Return(std::nullopt)); + EXPECT_CALL(cache_, getSuccessor(bookBase, kSeq)) .WillRepeatedly(testing::Return(LedgerObject{})); ext_.onLedgerData(data); @@ -220,27 +220,27 @@ TEST_F( [[maybe_unused]] testing::InSequence const inSeq; EXPECT_CALL(cache_, isFull()).WillRepeatedly(testing::Return(true)); - EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSEQ)); + EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSeq)); - EXPECT_CALL(cache_, getPredecessor(createdObj.key, kSEQ)) + EXPECT_CALL(cache_, getPredecessor(createdObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); - EXPECT_CALL(cache_, getSuccessor(createdObj.key, kSEQ)) + EXPECT_CALL(cache_, getSuccessor(createdObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); EXPECT_CALL( *backend_, - writeSuccessor(uint256ToString(data::kFIRST_KEY), kSEQ, uint256ToString(createdObj.key)) + writeSuccessor(uint256ToString(data::kFirstKey), kSeq, uint256ToString(createdObj.key)) ); EXPECT_CALL( *backend_, - writeSuccessor(uint256ToString(createdObj.key), kSEQ, uint256ToString(data::kLAST_KEY)) + writeSuccessor(uint256ToString(createdObj.key), kSeq, uint256ToString(data::kLastKey)) ); - EXPECT_CALL(cache_, get(createdObj.key, kSEQ)).WillRepeatedly(testing::Return(data::Blob{'0'})); - EXPECT_CALL(cache_, getSuccessor(bookBase, kSEQ)) + EXPECT_CALL(cache_, get(createdObj.key, kSeq)).WillRepeatedly(testing::Return(data::Blob{'0'})); + EXPECT_CALL(cache_, getSuccessor(bookBase, kSeq)) .WillRepeatedly(testing::Return(LedgerObject{.key = createdObj.key, .blob = {}})); - EXPECT_CALL(*backend_, writeSuccessor(uint256ToString(bookBase), kSEQ, testing::_)); + EXPECT_CALL(*backend_, writeSuccessor(uint256ToString(bookBase), kSeq, testing::_)); ext_.onLedgerData(data); } @@ -264,24 +264,24 @@ TEST_F( [[maybe_unused]] testing::InSequence const inSeq; EXPECT_CALL(cache_, isFull()).WillRepeatedly(testing::Return(true)); - EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSEQ)); + EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSeq)); - EXPECT_CALL(cache_, getPredecessor(deletedObj.key, kSEQ)) + EXPECT_CALL(cache_, getPredecessor(deletedObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); - EXPECT_CALL(cache_, getSuccessor(deletedObj.key, kSEQ)) + EXPECT_CALL(cache_, getSuccessor(deletedObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); EXPECT_CALL( *backend_, - writeSuccessor(uint256ToString(data::kFIRST_KEY), kSEQ, uint256ToString(data::kLAST_KEY)) + writeSuccessor(uint256ToString(data::kFirstKey), kSeq, uint256ToString(data::kLastKey)) ); - EXPECT_CALL(cache_, getDeleted(deletedObj.key, kSEQ - 1)) + EXPECT_CALL(cache_, getDeleted(deletedObj.key, kSeq - 1)) .WillOnce(testing::Return(oldCachedObj)); - EXPECT_CALL(cache_, get(deletedObj.key, kSEQ)).WillOnce(testing::Return(std::nullopt)); - EXPECT_CALL(cache_, getSuccessor(bookBase, kSEQ)).WillOnce(testing::Return(std::nullopt)); + EXPECT_CALL(cache_, get(deletedObj.key, kSeq)).WillOnce(testing::Return(std::nullopt)); + EXPECT_CALL(cache_, getSuccessor(bookBase, kSeq)).WillOnce(testing::Return(std::nullopt)); EXPECT_CALL( - *backend_, writeSuccessor(uint256ToString(bookBase), kSEQ, uint256ToString(data::kLAST_KEY)) + *backend_, writeSuccessor(uint256ToString(bookBase), kSeq, uint256ToString(data::kLastKey)) ); ext_.onLedgerData(data); @@ -306,25 +306,25 @@ TEST_F( [[maybe_unused]] testing::InSequence const inSeq; EXPECT_CALL(cache_, isFull()).WillRepeatedly(testing::Return(true)); - EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSEQ)); + EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSeq)); - EXPECT_CALL(cache_, getPredecessor(deletedObj.key, kSEQ)) + EXPECT_CALL(cache_, getPredecessor(deletedObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); - EXPECT_CALL(cache_, getSuccessor(deletedObj.key, kSEQ)) + EXPECT_CALL(cache_, getSuccessor(deletedObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); EXPECT_CALL( *backend_, - writeSuccessor(uint256ToString(data::kFIRST_KEY), kSEQ, uint256ToString(data::kLAST_KEY)) + writeSuccessor(uint256ToString(data::kFirstKey), kSeq, uint256ToString(data::kLastKey)) ); - EXPECT_CALL(cache_, getDeleted(deletedObj.key, kSEQ - 1)) + EXPECT_CALL(cache_, getDeleted(deletedObj.key, kSeq - 1)) .WillOnce(testing::Return(oldCachedObj)); - EXPECT_CALL(cache_, get(deletedObj.key, kSEQ)).WillOnce(testing::Return(data::Blob{'0'})); - EXPECT_CALL(cache_, getSuccessor(bookBase, kSEQ)) + EXPECT_CALL(cache_, get(deletedObj.key, kSeq)).WillOnce(testing::Return(data::Blob{'0'})); + EXPECT_CALL(cache_, getSuccessor(bookBase, kSeq)) .WillRepeatedly(testing::Return(LedgerObject{.key = deletedObj.key, .blob = {}})); EXPECT_CALL( - *backend_, writeSuccessor(uint256ToString(bookBase), kSEQ, uint256ToString(deletedObj.key)) + *backend_, writeSuccessor(uint256ToString(bookBase), kSeq, uint256ToString(deletedObj.key)) ); ext_.onLedgerData(data); @@ -348,18 +348,18 @@ TEST_F(SuccessorExtTests, OnLedgerDataWithDeletedObjectAndWithCachedPredecessorA }); EXPECT_CALL(cache_, isFull()).WillRepeatedly(testing::Return(true)); - EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSEQ)); + EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSeq)); - EXPECT_CALL(cache_, getPredecessor(createdObj.key, kSEQ)) + EXPECT_CALL(cache_, getPredecessor(createdObj.key, kSeq)) .WillOnce(testing::Return(data::LedgerObject{.key = predKey, .blob = {}})); - EXPECT_CALL(cache_, getSuccessor(createdObj.key, kSEQ)) + EXPECT_CALL(cache_, getSuccessor(createdObj.key, kSeq)) .WillOnce(testing::Return(data::LedgerObject{.key = succKey, .blob = {}})); EXPECT_CALL( - *backend_, writeSuccessor(uint256ToString(predKey), kSEQ, uint256ToString(createdObj.key)) + *backend_, writeSuccessor(uint256ToString(predKey), kSeq, uint256ToString(createdObj.key)) ); EXPECT_CALL( - *backend_, writeSuccessor(uint256ToString(createdObj.key), kSEQ, uint256ToString(succKey)) + *backend_, writeSuccessor(uint256ToString(createdObj.key), kSeq, uint256ToString(succKey)) ); ext_.onLedgerData(data); @@ -378,14 +378,14 @@ TEST_F(SuccessorExtTests, OnLedgerDataWithCreatedObjectAndIncludedSuccessors) auto const succ = util::createSuccessor(); data.successors = {succ, succ, succ}; - EXPECT_CALL(*backend_, writeSuccessor(auto{succ.bookBase}, kSEQ, auto{succ.firstBook})) + EXPECT_CALL(*backend_, writeSuccessor(auto{succ.bookBase}, kSeq, auto{succ.firstBook})) .Times(data.successors->size()); EXPECT_CALL( - *backend_, writeSuccessor(auto{createdObj.predecessor}, kSEQ, auto{createdObj.keyRaw}) + *backend_, writeSuccessor(auto{createdObj.predecessor}, kSeq, auto{createdObj.keyRaw}) ); EXPECT_CALL( - *backend_, writeSuccessor(auto{createdObj.keyRaw}, kSEQ, auto{createdObj.successor}) + *backend_, writeSuccessor(auto{createdObj.keyRaw}, kSeq, auto{createdObj.successor}) ); ext_.onLedgerData(data); @@ -402,16 +402,16 @@ TEST_F(SuccessorExtTests, OnLedgerDataWithDeletedObjectAndIncludedSuccessorsWith util::createObject(Object::ModType::Modified), }); auto succ = util::createSuccessor(); - succ.firstBook = {}; // empty will be transformed into kLAST_KEY + succ.firstBook = {}; // empty will be transformed into kLastKey data.successors = {succ, succ}; EXPECT_CALL( - *backend_, writeSuccessor(auto{succ.bookBase}, kSEQ, uint256ToString(data::kLAST_KEY)) + *backend_, writeSuccessor(auto{succ.bookBase}, kSeq, uint256ToString(data::kLastKey)) ) .Times(data.successors->size()); EXPECT_CALL( - *backend_, writeSuccessor(auto{deletedObj.predecessor}, kSEQ, auto{deletedObj.successor}) + *backend_, writeSuccessor(auto{deletedObj.predecessor}, kSeq, auto{deletedObj.successor}) ); ext_.onLedgerData(data); @@ -422,19 +422,19 @@ TEST_F(SuccessorExtTests, OnInitialDataWithSuccessorsButNotBookDirAndNoSuccessor using namespace etl::model; auto const firstKey = - ripple::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960C"); + xrpl::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960C"); auto const secondKey = - ripple::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960E"); + xrpl::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960E"); auto const data = createInitialTestData({firstKey, secondKey}); - auto successorChain = std::queue(); + auto successorChain = std::queue(); successorChain.push(firstKey); successorChain.push(secondKey); [[maybe_unused]] testing::Sequence const inSeq; EXPECT_CALL(cache_, isFull()).WillOnce(testing::Return(true)); - EXPECT_CALL(cache_, getSuccessor(testing::_, kSEQ)) + EXPECT_CALL(cache_, getSuccessor(testing::_, kSeq)) .Times(3) .InSequence(inSeq) .WillRepeatedly([&](auto&&, auto&&) -> std::optional { @@ -447,17 +447,15 @@ TEST_F(SuccessorExtTests, OnInitialDataWithSuccessorsButNotBookDirAndNoSuccessor }); EXPECT_CALL( - *backend_, - writeSuccessor(uint256ToString(data::kFIRST_KEY), kSEQ, uint256ToString(firstKey)) + *backend_, writeSuccessor(uint256ToString(data::kFirstKey), kSeq, uint256ToString(firstKey)) ); EXPECT_CALL( - *backend_, - writeSuccessor(uint256ToString(secondKey), kSEQ, uint256ToString(data::kLAST_KEY)) + *backend_, writeSuccessor(uint256ToString(secondKey), kSeq, uint256ToString(data::kLastKey)) ); // NOLINTBEGIN(bugprone-unchecked-optional-access) for (auto const& key : *data.edgeKeys) { - EXPECT_CALL(cache_, getSuccessor(*ripple::uint256::fromVoidChecked(key), kSEQ)) + EXPECT_CALL(cache_, getSuccessor(*xrpl::uint256::fromVoidChecked(key), kSeq)) .InSequence(inSeq) .WillOnce(testing::Return(std::nullopt)); } @@ -471,19 +469,19 @@ TEST_F(SuccessorExtTests, OnInitialDataWithSuccessorsButNotBookDirAndSuccessorsF using namespace etl::model; auto const firstKey = - ripple::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960C"); + xrpl::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960C"); auto const secondKey = - ripple::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960E"); + xrpl::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960E"); auto const data = createInitialTestData({firstKey, secondKey}); - auto successorChain = std::queue(); + auto successorChain = std::queue(); successorChain.push(firstKey); successorChain.push(secondKey); [[maybe_unused]] testing::Sequence const inSeq; EXPECT_CALL(cache_, isFull()).WillOnce(testing::Return(true)); - EXPECT_CALL(cache_, getSuccessor(testing::_, kSEQ)) + EXPECT_CALL(cache_, getSuccessor(testing::_, kSeq)) .Times(3) .InSequence(inSeq) .WillRepeatedly([&](auto&&, auto&&) -> std::optional { @@ -496,20 +494,18 @@ TEST_F(SuccessorExtTests, OnInitialDataWithSuccessorsButNotBookDirAndSuccessorsF }); EXPECT_CALL( - *backend_, - writeSuccessor(uint256ToString(data::kFIRST_KEY), kSEQ, uint256ToString(firstKey)) + *backend_, writeSuccessor(uint256ToString(data::kFirstKey), kSeq, uint256ToString(firstKey)) ); EXPECT_CALL( - *backend_, - writeSuccessor(uint256ToString(secondKey), kSEQ, uint256ToString(data::kLAST_KEY)) + *backend_, writeSuccessor(uint256ToString(secondKey), kSeq, uint256ToString(data::kLastKey)) ); // NOLINTBEGIN(bugprone-unchecked-optional-access) for (auto const& key : *data.edgeKeys) { - EXPECT_CALL(cache_, getSuccessor(*ripple::uint256::fromVoidChecked(key), kSEQ)) + EXPECT_CALL(cache_, getSuccessor(*xrpl::uint256::fromVoidChecked(key), kSeq)) .InSequence(inSeq) .WillOnce(testing::Return(data::LedgerObject{.key = firstKey, .blob = {}})); - EXPECT_CALL(*backend_, writeSuccessor(auto{key}, kSEQ, uint256ToString(firstKey))); + EXPECT_CALL(*backend_, writeSuccessor(auto{key}, kSeq, uint256ToString(firstKey))); } // NOLINTEND(bugprone-unchecked-optional-access) @@ -521,12 +517,12 @@ TEST_F(SuccessorExtTests, OnInitialDataWithSuccessorsAndBookDirAndSuccessorsForE using namespace etl::model; auto const firstKey = - ripple::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960C"); + xrpl::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960C"); auto const secondKey = - ripple::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960E"); + xrpl::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960E"); auto const data = createInitialTestData({firstKey, secondKey}); - auto successorChain = std::queue(); + auto successorChain = std::queue(); successorChain.push(firstKey); successorChain.push(secondKey); @@ -536,7 +532,7 @@ TEST_F(SuccessorExtTests, OnInitialDataWithSuccessorsAndBookDirAndSuccessorsForE [[maybe_unused]] testing::Sequence const inSeq; EXPECT_CALL(cache_, isFull()).WillOnce(testing::Return(true)); - EXPECT_CALL(cache_, getSuccessor(testing::_, kSEQ)) + EXPECT_CALL(cache_, getSuccessor(testing::_, kSeq)) .Times(3) .InSequence(inSeq) .WillRepeatedly([&](auto&&, auto&&) -> std::optional { @@ -549,29 +545,27 @@ TEST_F(SuccessorExtTests, OnInitialDataWithSuccessorsAndBookDirAndSuccessorsForE }); EXPECT_CALL( - *backend_, - writeSuccessor(uint256ToString(data::kFIRST_KEY), kSEQ, uint256ToString(firstKey)) + *backend_, writeSuccessor(uint256ToString(data::kFirstKey), kSeq, uint256ToString(firstKey)) ); EXPECT_CALL( - *backend_, - writeSuccessor(uint256ToString(secondKey), kSEQ, uint256ToString(data::kLAST_KEY)) + *backend_, writeSuccessor(uint256ToString(secondKey), kSeq, uint256ToString(data::kLastKey)) ); - EXPECT_CALL(cache_, get(bookBase, kSEQ)).WillRepeatedly(testing::Return(std::nullopt)); - EXPECT_CALL(cache_, getSuccessor(bookBase, kSEQ)) + EXPECT_CALL(cache_, get(bookBase, kSeq)).WillRepeatedly(testing::Return(std::nullopt)); + EXPECT_CALL(cache_, getSuccessor(bookBase, kSeq)) .WillRepeatedly( testing::Return(data::LedgerObject{.key = firstKey, .blob = data::Blob{'1'}}) ); EXPECT_CALL( - *backend_, writeSuccessor(uint256ToString(bookBase), kSEQ, testing::_) + *backend_, writeSuccessor(uint256ToString(bookBase), kSeq, testing::_) ); // Called once because firstKey returned repeatedly above // NOLINTBEGIN(bugprone-unchecked-optional-access) for (auto const& key : *data.edgeKeys) { - EXPECT_CALL(cache_, getSuccessor(*ripple::uint256::fromVoidChecked(key), kSEQ)) + EXPECT_CALL(cache_, getSuccessor(*xrpl::uint256::fromVoidChecked(key), kSeq)) .InSequence(inSeq) .WillOnce(testing::Return(data::LedgerObject{.key = firstKey, .blob = {'1'}})); - EXPECT_CALL(*backend_, writeSuccessor(auto{key}, kSEQ, uint256ToString(firstKey))) + EXPECT_CALL(*backend_, writeSuccessor(auto{key}, kSeq, uint256ToString(firstKey))) .InSequence(inSeq); } // NOLINTEND(bugprone-unchecked-optional-access) @@ -602,11 +596,11 @@ TEST_F(SuccessorExtTests, OnInitialObjectsWithEmptyLastKey) std::string lk = lastKey; for (auto const& obj : data) { if (not lk.empty()) - EXPECT_CALL(*backend_, writeSuccessor(std::move(lk), kSEQ, uint256ToString(obj.key))); + EXPECT_CALL(*backend_, writeSuccessor(std::move(lk), kSeq, uint256ToString(obj.key))); lk = uint256ToString(obj.key); } - ext_.onInitialObjects(kSEQ, data, lastKey); + ext_.onInitialObjects(kSeq, data, lastKey); } TEST_F(SuccessorExtTests, OnInitialObjectsWithNonEmptyLastKey) @@ -614,7 +608,7 @@ TEST_F(SuccessorExtTests, OnInitialObjectsWithNonEmptyLastKey) using namespace etl::model; auto const lastKey = uint256ToString( - ripple::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960D") + xrpl::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960D") ); auto const data = std::vector{ util::createObject( @@ -633,11 +627,11 @@ TEST_F(SuccessorExtTests, OnInitialObjectsWithNonEmptyLastKey) std::string lk = lastKey; for (auto const& obj : data) { - EXPECT_CALL(*backend_, writeSuccessor(std::move(lk), kSEQ, uint256ToString(obj.key))); + EXPECT_CALL(*backend_, writeSuccessor(std::move(lk), kSeq, uint256ToString(obj.key))); lk = uint256ToString(obj.key); } - ext_.onInitialObjects(kSEQ, data, lastKey); + ext_.onInitialObjects(kSeq, data, lastKey); } struct SuccessorExtAssertTests : common::util::WithMockAssert, SuccessorExtTests {}; @@ -654,18 +648,18 @@ TEST_F(SuccessorExtAssertTests, OnLedgerDataWithDeletedObjectAssertsIfGetDeleted }); EXPECT_CALL(cache_, isFull()).WillRepeatedly(testing::Return(true)); - EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSEQ)); + EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSeq)); - EXPECT_CALL(cache_, getPredecessor(deletedObj.key, kSEQ)) + EXPECT_CALL(cache_, getPredecessor(deletedObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); - EXPECT_CALL(cache_, getSuccessor(deletedObj.key, kSEQ)) + EXPECT_CALL(cache_, getSuccessor(deletedObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); EXPECT_CALL( *backend_, - writeSuccessor(uint256ToString(data::kFIRST_KEY), kSEQ, uint256ToString(data::kLAST_KEY)) + writeSuccessor(uint256ToString(data::kFirstKey), kSeq, uint256ToString(data::kLastKey)) ); - EXPECT_CALL(cache_, getDeleted(deletedObj.key, kSEQ - 1)) + EXPECT_CALL(cache_, getDeleted(deletedObj.key, kSeq - 1)) .WillRepeatedly(testing::Return(std::nullopt)); EXPECT_CLIO_ASSERT_FAIL({ ext_.onLedgerData(data); }); @@ -687,24 +681,24 @@ TEST_F( auto const bookBase = getBookBase(createdObj.key); EXPECT_CALL(cache_, isFull()).WillRepeatedly(testing::Return(true)); - EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSEQ)); + EXPECT_CALL(cache_, latestLedgerSequence()).WillRepeatedly(testing::Return(kSeq)); - EXPECT_CALL(cache_, getPredecessor(createdObj.key, kSEQ)) + EXPECT_CALL(cache_, getPredecessor(createdObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); - EXPECT_CALL(cache_, getSuccessor(createdObj.key, kSEQ)) + EXPECT_CALL(cache_, getSuccessor(createdObj.key, kSeq)) .WillRepeatedly(testing::Return(std::nullopt)); EXPECT_CALL( *backend_, - writeSuccessor(uint256ToString(data::kFIRST_KEY), kSEQ, uint256ToString(createdObj.key)) + writeSuccessor(uint256ToString(data::kFirstKey), kSeq, uint256ToString(createdObj.key)) ); EXPECT_CALL( *backend_, - writeSuccessor(uint256ToString(createdObj.key), kSEQ, uint256ToString(data::kLAST_KEY)) + writeSuccessor(uint256ToString(createdObj.key), kSeq, uint256ToString(data::kLastKey)) ); - EXPECT_CALL(cache_, get(createdObj.key, kSEQ)).WillOnce(testing::Return(data::Blob{'0'})); - EXPECT_CALL(cache_, getSuccessor(bookBase, kSEQ)).WillOnce(testing::Return(std::nullopt)); + EXPECT_CALL(cache_, get(createdObj.key, kSeq)).WillOnce(testing::Return(data::Blob{'0'})); + EXPECT_CALL(cache_, getSuccessor(bookBase, kSeq)).WillOnce(testing::Return(std::nullopt)); EXPECT_CLIO_ASSERT_FAIL({ ext_.onLedgerData(data); }); } @@ -737,9 +731,9 @@ TEST_F(SuccessorExtAssertTests, OnInitialDataIsFullWithEdgeKeysButHasObjects) using namespace etl::model; auto const firstKey = - ripple::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960C"); + xrpl::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960C"); auto const secondKey = - ripple::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960E"); + xrpl::uint256("B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960E"); auto data = createInitialTestData({firstKey, secondKey}); data.objects = {util::createObject()}; diff --git a/tests/unit/feed/BookChangesFeedTests.cpp b/tests/unit/feed/BookChangesFeedTests.cpp index 7731d937b..336b41ef2 100644 --- a/tests/unit/feed/BookChangesFeedTests.cpp +++ b/tests/unit/feed/BookChangesFeedTests.cpp @@ -15,11 +15,11 @@ using namespace data; namespace { -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kACCOUNT1 = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kCURRENCY = "0158415500000000C1F76FF6ECB0BAC600000000"; -constexpr auto kISSUER = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kAccount1 = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kCurrency = "0158415500000000C1F76FF6ECB0BAC600000000"; +constexpr auto kIssuer = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; } // namespace @@ -31,18 +31,17 @@ TEST_F(FeedBookChangeTest, Pub) testFeedPtr->sub(sessionPtr); EXPECT_EQ(testFeedPtr->count(), 1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 32); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 32); auto transactions = std::vector{}; auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - ripple::STObject const metaObj = - createMetaDataForBookChange(kCURRENCY, kISSUER, 22, 1, 3, 3, 1); + xrpl::STObject const metaObj = createMetaDataForBookChange(kCurrency, kIssuer, 22, 1, 3, 3, 1); trans1.metadata = metaObj.getSerializer().peekData(); transactions.push_back(trans1); - static constexpr auto kBOOK_CHANGE_PUBLISH = + static constexpr auto kBookChangePublish = R"JSON({ "type": "bookChanges", "ledger_index": 32, @@ -62,7 +61,7 @@ TEST_F(FeedBookChangeTest, Pub) ] })JSON"; - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kBOOK_CHANGE_PUBLISH))).Times(1); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kBookChangePublish))).Times(1); testFeedPtr->pub(ledgerHeader, transactions); testFeedPtr->unsub(sessionPtr); diff --git a/tests/unit/feed/ForwardFeedTests.cpp b/tests/unit/feed/ForwardFeedTests.cpp index 676e630dd..162f00e36 100644 --- a/tests/unit/feed/ForwardFeedTests.cpp +++ b/tests/unit/feed/ForwardFeedTests.cpp @@ -7,15 +7,12 @@ #include #include -#include - using namespace feed::impl; -namespace json = boost::json; using namespace util::prometheus; namespace { -constexpr auto kFEED = R"JSON({"test": "test"})JSON"; +constexpr auto kFeed = R"JSON({"test": "test"})JSON"; } // namespace @@ -35,8 +32,8 @@ TEST_F(FeedForwardTest, Pub) testFeedPtr->sub(sessionPtr); EXPECT_EQ(testFeedPtr->count(), 1); - auto const json = json::parse(kFEED).as_object(); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kFEED))).Times(1); + auto const json = boost::json::parse(kFeed).as_object(); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kFeed))).Times(1); testFeedPtr->pub(json); testFeedPtr->unsub(sessionPtr); @@ -51,8 +48,8 @@ TEST_F(FeedForwardTest, AutoDisconnect) testFeedPtr->sub(sessionPtr); EXPECT_EQ(testFeedPtr->count(), 1); - auto const json = json::parse(kFEED).as_object(); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kFEED))); + auto const json = boost::json::parse(kFeed).as_object(); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kFeed))); testFeedPtr->pub(json); slot(sessionPtr.get()); diff --git a/tests/unit/feed/LedgerFeedTests.cpp b/tests/unit/feed/LedgerFeedTests.cpp index f389e74d0..97740cf35 100644 --- a/tests/unit/feed/LedgerFeedTests.cpp +++ b/tests/unit/feed/LedgerFeedTests.cpp @@ -12,11 +12,10 @@ #include namespace { -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; } // namespace using namespace feed::impl; -namespace json = boost::json; using namespace testing; using FeedLedgerTest = FeedBaseTest; @@ -24,7 +23,7 @@ using FeedLedgerTest = FeedBaseTest; TEST_F(FeedLedgerTest, SubPub) { backend_->setRange(10, 30); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(testing::Return(ledgerHeader)); auto const feeBlob = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); @@ -33,7 +32,7 @@ TEST_F(FeedLedgerTest, SubPub) // Information about the ledgers on hand and current fee schedule. This // includes the same fields as a ledger stream message, except that it omits // the type and txn_count fields - static constexpr auto kLEDGER_RESPONSE = + static constexpr auto kLedgerResponse = R"JSON({ "validated_ledgers": "10-30", "ledger_index": 30, @@ -49,12 +48,12 @@ TEST_F(FeedLedgerTest, SubPub) EXPECT_CALL(*mockSessionPtr, onDisconnect); auto res = testFeedPtr->sub(yield, backend_, sessionPtr, networkID); // check the response - EXPECT_EQ(res, json::parse(kLEDGER_RESPONSE)); + EXPECT_EQ(res, boost::json::parse(kLedgerResponse)); }); ioContext.run(); EXPECT_EQ(testFeedPtr->count(), 1); - static constexpr auto kLEDGER_PUB = + static constexpr auto kLedgerPub = R"JSON({ "type": "ledgerClosed", "ledger_index": 31, @@ -69,9 +68,9 @@ TEST_F(FeedLedgerTest, SubPub) })JSON"; // test publish - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kLEDGER_PUB))).Times(1); - auto const ledgerHeader2 = createLedgerHeader(kLEDGER_HASH, 31); - auto fee2 = ripple::Fees(); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kLedgerPub))).Times(1); + auto const ledgerHeader2 = createLedgerHeader(kLedgerHash, 31); + auto fee2 = xrpl::Fees(); fee2.reserve = 10; testFeedPtr->pub(ledgerHeader2, fee2, "10-31", 8, networkID); @@ -85,12 +84,12 @@ TEST_F(FeedLedgerTest, SubPub) TEST_F(FeedLedgerTest, AutoDisconnect) { backend_->setRange(10, 30); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(testing::Return(ledgerHeader)); auto const feeBlob = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); EXPECT_CALL(*backend_, doFetchLedgerObject).WillOnce(testing::Return(feeBlob)); - static constexpr auto kLEDGER_RESPONSE = + static constexpr auto kLedgerResponse = R"JSON({ "validated_ledgers": "10-30", "ledger_index": 30, @@ -109,7 +108,7 @@ TEST_F(FeedLedgerTest, AutoDisconnect) util::spawn(ioContext, [this](boost::asio::yield_context yield) { auto res = testFeedPtr->sub(yield, backend_, sessionPtr, networkID); // check the response - EXPECT_EQ(res, json::parse(kLEDGER_RESPONSE)); + EXPECT_EQ(res, boost::json::parse(kLedgerResponse)); }); ioContext.run(); @@ -122,8 +121,8 @@ TEST_F(FeedLedgerTest, AutoDisconnect) EXPECT_EQ(testFeedPtr->count(), 0); - auto const ledgerHeader2 = createLedgerHeader(kLEDGER_HASH, 31); - auto fee2 = ripple::Fees(); + auto const ledgerHeader2 = createLedgerHeader(kLedgerHash, 31); + auto fee2 = xrpl::Fees(); fee2.reserve = 10; // no error testFeedPtr->pub(ledgerHeader2, fee2, "10-31", 8, networkID); diff --git a/tests/unit/feed/ProposedTransactionFeedTests.cpp b/tests/unit/feed/ProposedTransactionFeedTests.cpp index 96095caa2..6db3e4151 100644 --- a/tests/unit/feed/ProposedTransactionFeedTests.cpp +++ b/tests/unit/feed/ProposedTransactionFeedTests.cpp @@ -17,10 +17,10 @@ namespace { -constexpr auto kACCOUNT1 = "rh1HPuRVsYYvThxG2Bs1MfjmrVC73S16Fb"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kACCOUNT3 = "r92yNeoiCdwULRbjh6cUBEbD71iHcqe1hE"; -constexpr auto kDUMMY_TRANSACTION = +constexpr auto kAccount1 = "rh1HPuRVsYYvThxG2Bs1MfjmrVC73S16Fb"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kAccount3 = "r92yNeoiCdwULRbjh6cUBEbD71iHcqe1hE"; +constexpr auto kDummyTransaction = R"JSON({ "transaction": { "Account": "rh1HPuRVsYYvThxG2Bs1MfjmrVC73S16Fb", @@ -37,7 +37,7 @@ constexpr auto kDUMMY_TRANSACTION = })JSON"; // Expected v2 format: "transaction" renamed to "tx_json", "hash" moved to top level -constexpr auto kDUMMY_TRANSACTION_V2 = +constexpr auto kDummyTransactionV2 = R"JSON({ "hash": "F44393295DB860C6860769C16F5B23887762F09F87A8D1174E0FCFF9E7247F07", "tx_json": { @@ -56,7 +56,6 @@ constexpr auto kDUMMY_TRANSACTION_V2 = } // namespace using namespace feed::impl; -namespace json = boost::json; using namespace util::prometheus; using FeedProposedTransactionTest = FeedBaseTest; @@ -67,44 +66,44 @@ TEST_F(FeedProposedTransactionTest, ProposedTransaction) testFeedPtr->sub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubcount(), 1); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDUMMY_TRANSACTION))); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDummyTransaction))); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); testFeedPtr->unsub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubcount(), 0); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); } TEST_F(FeedProposedTransactionTest, AccountProposedTransaction) { - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 1); web::SubscriptionContextPtr const sessionIdle = std::make_shared(); - auto const accountIdle = getAccountIdWithString(kACCOUNT3); + auto const accountIdle = getAccountIdWithString(kAccount3); EXPECT_CALL(*dynamic_cast(sessionIdle.get()), onDisconnect); testFeedPtr->sub(accountIdle, sessionIdle); EXPECT_EQ(testFeedPtr->accountSubCount(), 2); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDUMMY_TRANSACTION))); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDummyTransaction))); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); // unsub testFeedPtr->unsub(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 1); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); } TEST_F(FeedProposedTransactionTest, SubStreamAndAccount) { - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr, onDisconnect).Times(2); testFeedPtr->sub(account, sessionPtr); @@ -112,48 +111,48 @@ TEST_F(FeedProposedTransactionTest, SubStreamAndAccount) EXPECT_EQ(testFeedPtr->accountSubCount(), 1); EXPECT_EQ(testFeedPtr->transactionSubcount(), 1); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDUMMY_TRANSACTION))).Times(2); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDummyTransaction))).Times(2); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); // unsub testFeedPtr->unsub(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 0); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDUMMY_TRANSACTION))); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDummyTransaction))); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); // unsub transaction testFeedPtr->unsub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubcount(), 0); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); } TEST_F(FeedProposedTransactionTest, AccountProposedTransactionDuplicate) { - auto const account = getAccountIdWithString(kACCOUNT1); - auto const account2 = getAccountIdWithString(kACCOUNT2); + auto const account = getAccountIdWithString(kAccount1); + auto const account2 = getAccountIdWithString(kAccount2); EXPECT_CALL(*mockSessionPtr, onDisconnect).Times(2); testFeedPtr->sub(account, sessionPtr); testFeedPtr->sub(account2, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 2); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDUMMY_TRANSACTION))); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDummyTransaction))); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); // unsub account1 testFeedPtr->unsub(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 1); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDUMMY_TRANSACTION))); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDummyTransaction))); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); // unsub account2 testFeedPtr->unsub(account2, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 0); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); } TEST_F(FeedProposedTransactionTest, Count) @@ -164,7 +163,7 @@ TEST_F(FeedProposedTransactionTest, Count) testFeedPtr->sub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubcount(), 1); - auto const account1 = getAccountIdWithString(kACCOUNT1); + auto const account1 = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(account1, sessionPtr); @@ -178,7 +177,7 @@ TEST_F(FeedProposedTransactionTest, Count) testFeedPtr->sub(sessionPtr2); EXPECT_EQ(testFeedPtr->transactionSubcount(), 2); - auto const account2 = getAccountIdWithString(kACCOUNT2); + auto const account2 = getAccountIdWithString(kAccount2); EXPECT_CALL(*dynamic_cast(sessionPtr2.get()), onDisconnect); testFeedPtr->sub(account2, sessionPtr2); @@ -215,7 +214,7 @@ TEST_F(FeedProposedTransactionTest, AutoDisconnect) testFeedPtr->sub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubcount(), 1); - auto const account1 = getAccountIdWithString(kACCOUNT1); + auto const account1 = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(account1, sessionPtr); @@ -234,7 +233,7 @@ TEST_F(FeedProposedTransactionTest, AutoDisconnect) testFeedPtr->sub(sessionPtr2); EXPECT_EQ(testFeedPtr->transactionSubcount(), 2); - auto const account2 = getAccountIdWithString(kACCOUNT2); + auto const account2 = getAccountIdWithString(kAccount2); EXPECT_CALL(*mockSessionPtr2, onDisconnect); testFeedPtr->sub(account2, sessionPtr2); @@ -263,26 +262,26 @@ TEST_F(FeedProposedTransactionTest, ProposedTransactionV2) EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(sessionPtr); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDUMMY_TRANSACTION_V2))); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDummyTransactionV2))); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); testFeedPtr->unsub(sessionPtr); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); } TEST_F(FeedProposedTransactionTest, AccountProposedTransactionV2) { - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(2u)); EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(account, sessionPtr); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDUMMY_TRANSACTION_V2))); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDummyTransactionV2))); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); testFeedPtr->unsub(account, sessionPtr); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); } TEST_F(FeedProposedTransactionTest, MixedVersionSubscribers) @@ -297,15 +296,15 @@ TEST_F(FeedProposedTransactionTest, MixedVersionSubscribers) EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1u)); EXPECT_CALL(*mockSessionV2Ptr, apiSubversion).WillOnce(testing::Return(2u)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDUMMY_TRANSACTION))); - EXPECT_CALL(*mockSessionV2Ptr, send(sharedStringJsonEq(kDUMMY_TRANSACTION_V2))); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDummyTransaction))); + EXPECT_CALL(*mockSessionV2Ptr, send(sharedStringJsonEq(kDummyTransactionV2))); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); } TEST_F(FeedProposedTransactionTest, AccountProposedTransactionDuplicateV2) { - auto const account = getAccountIdWithString(kACCOUNT1); - auto const account2 = getAccountIdWithString(kACCOUNT2); + auto const account = getAccountIdWithString(kAccount1); + auto const account2 = getAccountIdWithString(kAccount2); EXPECT_CALL(*mockSessionPtr, onDisconnect).Times(2); testFeedPtr->sub(account, sessionPtr); @@ -313,13 +312,13 @@ TEST_F(FeedProposedTransactionTest, AccountProposedTransactionDuplicateV2) // Both accounts are affected; v2 subscriber should receive the message only once (dedup) EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(2u)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDUMMY_TRANSACTION_V2))); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDummyTransactionV2))); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); } TEST_F(FeedProposedTransactionTest, SubStreamAndAccountV2) { - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr, onDisconnect).Times(2); testFeedPtr->sub(account, sessionPtr); @@ -327,8 +326,8 @@ TEST_F(FeedProposedTransactionTest, SubStreamAndAccountV2) // Subscribed to both stream and account: receives message twice (matches v1 behaviour) EXPECT_CALL(*mockSessionPtr, apiSubversion).WillRepeatedly(testing::Return(2u)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDUMMY_TRANSACTION_V2))).Times(2); - testFeedPtr->pub(json::parse(kDUMMY_TRANSACTION).get_object()); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kDummyTransactionV2))).Times(2); + testFeedPtr->pub(boost::json::parse(kDummyTransaction).get_object()); } struct ProposedTransactionFeedMockPrometheusTest : WithMockPrometheus, SyncExecutionCtxFixture { @@ -355,7 +354,7 @@ TEST_F(ProposedTransactionFeedMockPrometheusTest, subUnsub) testFeedPtr_->sub(sessionPtr_); testFeedPtr_->unsub(sessionPtr_); - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr_, onDisconnect); testFeedPtr_->sub(account, sessionPtr_); testFeedPtr_->unsub(account, sessionPtr_); @@ -380,7 +379,7 @@ TEST_F(ProposedTransactionFeedMockPrometheusTest, AutoDisconnect) }); testFeedPtr_->sub(sessionPtr_); - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr_, onDisconnect).WillOnce([&sessionOnDisconnectSlots](auto slot) { sessionOnDisconnectSlots.push_back(slot); }); diff --git a/tests/unit/feed/SingleFeedBaseTests.cpp b/tests/unit/feed/SingleFeedBaseTests.cpp index e30dba2f2..cc365ddac 100644 --- a/tests/unit/feed/SingleFeedBaseTests.cpp +++ b/tests/unit/feed/SingleFeedBaseTests.cpp @@ -13,7 +13,7 @@ #include namespace { -constexpr auto kFEED = R"JSON({"test": "test"})JSON"; +constexpr auto kFeed = R"JSON({"test": "test"})JSON"; } // namespace using namespace feed::impl; @@ -64,24 +64,24 @@ using SingleFeedBaseTest = FeedBaseTest; TEST_F(SingleFeedBaseTest, Test) { EXPECT_CALL(*mockSessionPtr, onDisconnect); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kFEED))); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kFeed))); testFeedPtr->sub(sessionPtr); EXPECT_EQ(testFeedPtr->count(), 1); - testFeedPtr->pub(kFEED); + testFeedPtr->pub(kFeed); testFeedPtr->unsub(sessionPtr); EXPECT_EQ(testFeedPtr->count(), 0); - testFeedPtr->pub(kFEED); + testFeedPtr->pub(kFeed); } TEST_F(SingleFeedBaseTest, TestAutoDisconnect) { web::SubscriptionContextInterface::OnDisconnectSlot slot; EXPECT_CALL(*mockSessionPtr, onDisconnect).WillOnce(testing::SaveArg<0>(&slot)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kFEED))); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kFeed))); testFeedPtr->sub(sessionPtr); EXPECT_EQ(testFeedPtr->count(), 1); - testFeedPtr->pub(kFEED); + testFeedPtr->pub(kFeed); slot(sessionPtr.get()); sessionPtr.reset(); diff --git a/tests/unit/feed/SubscriptionManagerTests.cpp b/tests/unit/feed/SubscriptionManagerTests.cpp index 328bdb9c4..f7b9b7c65 100644 --- a/tests/unit/feed/SubscriptionManagerTests.cpp +++ b/tests/unit/feed/SubscriptionManagerTests.cpp @@ -31,15 +31,14 @@ namespace { -constexpr auto kACCOUNT1 = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kCURRENCY = "0158415500000000C1F76FF6ECB0BAC600000000"; -constexpr auto kISSUER = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kAccount1 = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kCurrency = "0158415500000000C1F76FF6ECB0BAC600000000"; +constexpr auto kIssuer = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; } // namespace -namespace json = boost::json; using namespace feed; using namespace feed::impl; using namespace data; @@ -78,13 +77,13 @@ TEST_F(SubscriptionManagerAsyncTest, MultipleThreadCtx) EXPECT_CALL(*sessionPtr_, onDisconnect); subscriptionManagerPtr_->subValidation(session_); - static constexpr auto kJSON_MANIFEST = R"JSON({"manifest": "test"})JSON"; - static constexpr auto kJSON_VALIDATION = R"JSON({"validation": "test"})JSON"; + static constexpr auto kJsonManifest = R"JSON({"manifest": "test"})JSON"; + static constexpr auto kJsonValidation = R"JSON({"validation": "test"})JSON"; EXPECT_CALL(*sessionPtr_, send(testing::_)).Times(testing::AtMost(2)); - subscriptionManagerPtr_->forwardManifest(json::parse(kJSON_MANIFEST).get_object()); - subscriptionManagerPtr_->forwardValidation(json::parse(kJSON_VALIDATION).get_object()); + subscriptionManagerPtr_->forwardManifest(boost::json::parse(kJsonManifest).get_object()); + subscriptionManagerPtr_->forwardValidation(boost::json::parse(kJsonValidation).get_object()); } TEST_F(SubscriptionManagerAsyncTest, MultipleThreadCtxSessionDieEarly) @@ -98,16 +97,16 @@ TEST_F(SubscriptionManagerAsyncTest, MultipleThreadCtxSessionDieEarly) session_.reset(); subscriptionManagerPtr_->forwardManifest( - json::parse(R"JSON({"manifest": "test"})JSON").get_object() + boost::json::parse(R"JSON({"manifest": "test"})JSON").get_object() ); subscriptionManagerPtr_->forwardValidation( - json::parse(R"JSON({"validation": "test"})JSON").get_object() + boost::json::parse(R"JSON({"validation": "test"})JSON").get_object() ); } TEST_F(SubscriptionManagerTest, ReportCurrentSubscriber) { - static constexpr auto kREPORT_RETURN = + static constexpr auto kReportReturn = R"JSON({ "ledger": 0, "transactions": 2, @@ -145,16 +144,16 @@ TEST_F(SubscriptionManagerTest, ReportCurrentSubscriber) subscriptionManagerPtr_->subTransactions(session2); subscriptionManagerPtr_->subValidation(session1); subscriptionManagerPtr_->subValidation(session2); - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); subscriptionManagerPtr_->subAccount(account, session1); subscriptionManagerPtr_->subAccount(account, session2); subscriptionManagerPtr_->subProposedAccount(account, session1); subscriptionManagerPtr_->subProposedAccount(account, session2); - auto const issue1 = getIssue(kCURRENCY, kISSUER); - ripple::Book const book{ripple::xrpIssue(), issue1, std::nullopt}; + auto const issue1 = getIssue(kCurrency, kIssuer); + xrpl::Book const book{xrpl::xrpIssue(), issue1, std::nullopt}; subscriptionManagerPtr_->subBook(book, session1); subscriptionManagerPtr_->subBook(book, session2); - EXPECT_EQ(subscriptionManagerPtr_->report(), json::parse(kREPORT_RETURN)); + EXPECT_EQ(subscriptionManagerPtr_->report(), boost::json::parse(kReportReturn)); // count down when unsub manually subscriptionManagerPtr_->unsubBookChanges(session1); @@ -167,10 +166,10 @@ TEST_F(SubscriptionManagerTest, ReportCurrentSubscriber) subscriptionManagerPtr_->unsubBook(book, session1); // try to unsub an account which is not subscribed - auto const account2 = getAccountIdWithString(kACCOUNT2); + auto const account2 = getAccountIdWithString(kAccount2); subscriptionManagerPtr_->unsubAccount(account2, session1); subscriptionManagerPtr_->unsubProposedAccount(account2, session1); - auto checkResult = [](json::object reportReturn, int result) { + auto checkResult = [](boost::json::object reportReturn, int result) { EXPECT_EQ(reportReturn["book_changes"], result); EXPECT_EQ(reportReturn["validations"], result); EXPECT_EQ(reportReturn["transactions_proposed"], result); @@ -192,28 +191,28 @@ TEST_F(SubscriptionManagerTest, ReportCurrentSubscriber) TEST_F(SubscriptionManagerTest, ManifestTest) { - static constexpr auto kDUMMY_MANIFEST = R"JSON({"manifest": "test"})JSON"; + static constexpr auto kDummyManifest = R"JSON({"manifest": "test"})JSON"; EXPECT_CALL(*sessionPtr_, onDisconnect); - EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kDUMMY_MANIFEST))); + EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kDummyManifest))); subscriptionManagerPtr_->subManifest(session_); - subscriptionManagerPtr_->forwardManifest(json::parse(kDUMMY_MANIFEST).get_object()); + subscriptionManagerPtr_->forwardManifest(boost::json::parse(kDummyManifest).get_object()); - EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kDUMMY_MANIFEST))).Times(0); + EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kDummyManifest))).Times(0); subscriptionManagerPtr_->unsubManifest(session_); - subscriptionManagerPtr_->forwardManifest(json::parse(kDUMMY_MANIFEST).get_object()); + subscriptionManagerPtr_->forwardManifest(boost::json::parse(kDummyManifest).get_object()); } TEST_F(SubscriptionManagerTest, ValidationTest) { - static constexpr auto kDUMMY = R"JSON({"validation": "test"})JSON"; + static constexpr auto kDummy = R"JSON({"validation": "test"})JSON"; EXPECT_CALL(*sessionPtr_, onDisconnect); - EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kDUMMY))); + EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kDummy))); subscriptionManagerPtr_->subValidation(session_); - subscriptionManagerPtr_->forwardValidation(json::parse(kDUMMY).get_object()); + subscriptionManagerPtr_->forwardValidation(boost::json::parse(kDummy).get_object()); - EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kDUMMY))).Times(0); + EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kDummy))).Times(0); subscriptionManagerPtr_->unsubValidation(session_); - subscriptionManagerPtr_->forwardValidation(json::parse(kDUMMY).get_object()); + subscriptionManagerPtr_->forwardValidation(boost::json::parse(kDummy).get_object()); } TEST_F(SubscriptionManagerTest, BookChangesTest) @@ -222,17 +221,16 @@ TEST_F(SubscriptionManagerTest, BookChangesTest) subscriptionManagerPtr_->subBookChanges(session_); EXPECT_EQ(subscriptionManagerPtr_->report()["book_changes"], 1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 32); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 32); auto transactions = std::vector{}; auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - ripple::STObject const metaObj = - createMetaDataForBookChange(kCURRENCY, kISSUER, 22, 1, 3, 3, 1); + xrpl::STObject const metaObj = createMetaDataForBookChange(kCurrency, kIssuer, 22, 1, 3, 3, 1); trans1.metadata = metaObj.getSerializer().peekData(); transactions.push_back(trans1); - static constexpr auto kBOOK_CHANGE_PUBLISH = + static constexpr auto kBookChangePublish = R"JSON({ "type": "bookChanges", "ledger_index": 32, @@ -251,7 +249,7 @@ TEST_F(SubscriptionManagerTest, BookChangesTest) } ] })JSON"; - EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kBOOK_CHANGE_PUBLISH))); + EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kBookChangePublish))); subscriptionManagerPtr_->pubBookChanges(ledgerHeader, transactions); @@ -264,7 +262,7 @@ TEST_F(SubscriptionManagerTest, LedgerTest) backend_->setRange(10, 30); subscriptionManagerPtr_->setNetworkID(networkID_); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(testing::Return(ledgerHeader)); auto const feeBlob = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); @@ -273,7 +271,7 @@ TEST_F(SubscriptionManagerTest, LedgerTest) // Information about the ledgers on hand and current fee schedule. This // includes the same fields as a ledger stream message, except that it omits // the type and txn_count fields - static constexpr auto kLEDGER_RESPONSE = + static constexpr auto kLedgerResponse = R"JSON({ "validated_ledgers": "10-30", "ledger_index": 30, @@ -289,16 +287,16 @@ TEST_F(SubscriptionManagerTest, LedgerTest) EXPECT_CALL(*sessionPtr_, onDisconnect); auto const res = subscriptionManagerPtr_->subLedger(yield, session_); // check the response - EXPECT_EQ(res, json::parse(kLEDGER_RESPONSE)); + EXPECT_EQ(res, boost::json::parse(kLedgerResponse)); }); ctx.run(); EXPECT_EQ(subscriptionManagerPtr_->report()["ledger"], 1); // test publish - auto const ledgerHeader2 = createLedgerHeader(kLEDGER_HASH, 31); - auto fee2 = ripple::Fees(); + auto const ledgerHeader2 = createLedgerHeader(kLedgerHash, 31); + auto fee2 = xrpl::Fees(); fee2.reserve = 10; - static constexpr auto kLEDGER_PUB = + static constexpr auto kLedgerPub = R"JSON({ "type": "ledgerClosed", "ledger_index": 31, @@ -311,7 +309,7 @@ TEST_F(SubscriptionManagerTest, LedgerTest) "txn_count": 8, "network_id": 123 })JSON"; - EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kLEDGER_PUB))); + EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kLedgerPub))); subscriptionManagerPtr_->pubLedger(ledgerHeader2, fee2, "10-31", 8); // test unsub @@ -321,9 +319,9 @@ TEST_F(SubscriptionManagerTest, LedgerTest) TEST_F(SubscriptionManagerTest, TransactionTest) { - auto const issue1 = getIssue(kCURRENCY, kISSUER); - auto const account = getAccountIdWithString(kISSUER); - ripple::Book const book{ripple::xrpIssue(), issue1, std::nullopt}; + auto const issue1 = getIssue(kCurrency, kIssuer); + auto const account = getAccountIdWithString(kIssuer); + xrpl::Book const book{xrpl::xrpIssue(), issue1, std::nullopt}; EXPECT_CALL(*sessionPtr_, onDisconnect).Times(3); subscriptionManagerPtr_->subBook(book, session_); subscriptionManagerPtr_->subTransactions(session_); @@ -332,15 +330,15 @@ TEST_F(SubscriptionManagerTest, TransactionTest) EXPECT_EQ(subscriptionManagerPtr_->report()["transactions"], 1); EXPECT_EQ(subscriptionManagerPtr_->report()["books"], 1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - auto obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + auto obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - auto const metaObj = createMetaDataForBookChange(kCURRENCY, kISSUER, 22, 3, 1, 1, 3); + auto const metaObj = createMetaDataForBookChange(kCurrency, kIssuer, 22, 3, 1, 1, 3); trans1.metadata = metaObj.getSerializer().peekData(); - static constexpr auto kORDERBOOK_PUBLISH = + static constexpr auto kOrderbookPublish = R"JSON({ "transaction": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -393,7 +391,7 @@ TEST_F(SubscriptionManagerTest, TransactionTest) "close_time_iso": "2000-01-01T00:00:00Z", "engine_result_message": "The transaction was applied. Only final in a validated ledger." })JSON"; - EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kORDERBOOK_PUBLISH))).Times(3); + EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kOrderbookPublish))).Times(3); EXPECT_CALL(*sessionPtr_, apiSubversion).Times(3).WillRepeatedly(testing::Return(1)); subscriptionManagerPtr_->pubTransaction(trans1, ledgerHeader); @@ -407,21 +405,21 @@ TEST_F(SubscriptionManagerTest, TransactionTest) TEST_F(SubscriptionManagerTest, ProposedTransactionTest) { - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*sessionPtr_, onDisconnect).Times(4); subscriptionManagerPtr_->subProposedAccount(account, session_); subscriptionManagerPtr_->subProposedTransactions(session_); EXPECT_EQ(subscriptionManagerPtr_->report()["accounts_proposed"], 1); EXPECT_EQ(subscriptionManagerPtr_->report()["transactions_proposed"], 1); - static constexpr auto kDUMMY_TRANSACTION = + static constexpr auto kDummyTransaction = R"JSON({ "transaction": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "Destination": "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun" } })JSON"; - static constexpr auto kORDERBOOK_PUBLISH = + static constexpr auto kOrderbookPublish = R"JSON({ "transaction": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -474,19 +472,19 @@ TEST_F(SubscriptionManagerTest, ProposedTransactionTest) "close_time_iso": "2000-01-01T00:00:00Z", "engine_result_message": "The transaction was applied. Only final in a validated ledger." })JSON"; - EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kDUMMY_TRANSACTION))).Times(2); - EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kORDERBOOK_PUBLISH))).Times(2); + EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kDummyTransaction))).Times(2); + EXPECT_CALL(*sessionPtr_, send(sharedStringJsonEq(kOrderbookPublish))).Times(2); subscriptionManagerPtr_->forwardProposedTransaction( - json::parse(kDUMMY_TRANSACTION).get_object() + boost::json::parse(kDummyTransaction).get_object() ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - auto obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + auto obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - auto const metaObj = createMetaDataForBookChange(kCURRENCY, kACCOUNT1, 22, 3, 1, 1, 3); + auto const metaObj = createMetaDataForBookChange(kCurrency, kAccount1, 22, 3, 1, 1, 3); trans1.metadata = metaObj.getSerializer().peekData(); EXPECT_CALL(*sessionPtr_, apiSubversion).Times(2).WillRepeatedly(testing::Return(1)); subscriptionManagerPtr_->pubTransaction(trans1, ledgerHeader); @@ -508,13 +506,13 @@ TEST_F(SubscriptionManagerTest, DuplicateResponseSubTxAndProposedTx) EXPECT_CALL(*sessionPtr_, send(testing::_)).Times(2); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - auto obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + auto obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - auto const metaObj = createMetaDataForBookChange(kCURRENCY, kACCOUNT1, 22, 3, 1, 1, 3); + auto const metaObj = createMetaDataForBookChange(kCurrency, kAccount1, 22, 3, 1, 1, 3); trans1.metadata = metaObj.getSerializer().peekData(); EXPECT_CALL(*sessionPtr_, apiSubversion).Times(2).WillRepeatedly(testing::Return(1)); subscriptionManagerPtr_->pubTransaction(trans1, ledgerHeader); @@ -527,7 +525,7 @@ TEST_F(SubscriptionManagerTest, DuplicateResponseSubTxAndProposedTx) TEST_F(SubscriptionManagerTest, NoDuplicateResponseSubAccountAndProposedAccount) { - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*sessionPtr_, onDisconnect).Times(3); subscriptionManagerPtr_->subProposedAccount(account, session_); subscriptionManagerPtr_->subAccount(account, session_); @@ -536,13 +534,13 @@ TEST_F(SubscriptionManagerTest, NoDuplicateResponseSubAccountAndProposedAccount) EXPECT_CALL(*sessionPtr_, send(testing::_)); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - auto obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + auto obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - auto const metaObj = createMetaDataForBookChange(kCURRENCY, kACCOUNT1, 22, 3, 1, 1, 3); + auto const metaObj = createMetaDataForBookChange(kCurrency, kAccount1, 22, 3, 1, 1, 3); trans1.metadata = metaObj.getSerializer().peekData(); EXPECT_CALL(*sessionPtr_, apiSubversion).WillRepeatedly(testing::Return(1)); subscriptionManagerPtr_->pubTransaction(trans1, ledgerHeader); diff --git a/tests/unit/feed/TransactionFeedTests.cpp b/tests/unit/feed/TransactionFeedTests.cpp index 6a0e4ada1..d1956f790 100644 --- a/tests/unit/feed/TransactionFeedTests.cpp +++ b/tests/unit/feed/TransactionFeedTests.cpp @@ -31,18 +31,18 @@ using namespace data; namespace { -constexpr auto kACCOUNT1 = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kCURRENCY = "0158415500000000C1F76FF6ECB0BAC600000000"; -constexpr auto kISSUER = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; -constexpr auto kTXN_ID = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kAMM_ACCOUNT = "rnW8FAPgpQgA6VoESnVrUVJHBdq9QAtRZs"; -constexpr auto kLPTOKEN_CURRENCY = "037C35306B24AAB7FF90848206E003279AA47090"; -constexpr auto kNETWORK_ID = 0u; -constexpr auto kNFT_MINT_ID = "000B013A95F14B0044F78A264E41713C64B5F89242540EE208C3098E00000D65"; +constexpr auto kAccount1 = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kCurrency = "0158415500000000C1F76FF6ECB0BAC600000000"; +constexpr auto kIssuer = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; +constexpr auto kTxnId = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kAmmAccount = "rnW8FAPgpQgA6VoESnVrUVJHBdq9QAtRZs"; +constexpr auto kLptokenCurrency = "037C35306B24AAB7FF90848206E003279AA47090"; +constexpr auto kNetworkId = 0u; +constexpr auto kNftMintId = "000B013A95F14B0044F78A264E41713C64B5F89242540EE208C3098E00000D65"; -constexpr auto kTRAN_V1 = +constexpr auto kTranV1 = R"JSON({ "transaction": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -93,7 +93,7 @@ constexpr auto kTRAN_V1 = "engine_result_message": "The transaction was applied. Only final in a validated ledger." })JSON"; -constexpr auto kTRAN_V2 = +constexpr auto kTranV2 = R"JSON({ "tx_json": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -143,7 +143,7 @@ constexpr auto kTRAN_V2 = "engine_result_message": "The transaction was applied. Only final in a validated ledger." })JSON"; -constexpr auto kNFT_MINT_TRAN_V1 = +constexpr auto kNftMintTranV1 = R"JSON({ "transaction": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -218,21 +218,21 @@ TEST_F(FeedTransactionTest, SubTransactionV1) testFeedPtr->sub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubCount(), 1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - trans1.metadata = createPaymentTransactionMetaObject(kACCOUNT1, kACCOUNT2, 110, 30, 22) + trans1.metadata = createPaymentTransactionMetaObject(kAccount1, kAccount2, 110, 30, 22) .getSerializer() .peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V1))); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV1))); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(sessionPtr); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); EXPECT_EQ(testFeedPtr->transactionSubCount(), 0); } @@ -242,21 +242,21 @@ TEST_F(FeedTransactionTest, SubTransactionForProposedTx) testFeedPtr->subProposed(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubCount(), 0); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - trans1.metadata = createPaymentTransactionMetaObject(kACCOUNT1, kACCOUNT2, 110, 30, 22) + trans1.metadata = createPaymentTransactionMetaObject(kAccount1, kAccount2, 110, 30, 22) .getSerializer() .peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V1))); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV1))); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsubProposed(sessionPtr); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubTransactionV2) @@ -265,156 +265,156 @@ TEST_F(FeedTransactionTest, SubTransactionV2) testFeedPtr->sub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubCount(), 1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - trans1.metadata = createPaymentTransactionMetaObject(kACCOUNT1, kACCOUNT2, 110, 30, 22) + trans1.metadata = createPaymentTransactionMetaObject(kAccount1, kAccount2, 110, 30, 22) .getSerializer() .peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(2)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V2))); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV2))); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubCount(), 0); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubAccountV1) { - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - trans1.metadata = createPaymentTransactionMetaObject(kACCOUNT1, kACCOUNT2, 110, 30, 22) + trans1.metadata = createPaymentTransactionMetaObject(kAccount1, kAccount2, 110, 30, 22) .getSerializer() .peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V1))); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV1))); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 0); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubForProposedAccount) { - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->subProposed(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 0); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - trans1.metadata = createPaymentTransactionMetaObject(kACCOUNT1, kACCOUNT2, 110, 30, 22) + trans1.metadata = createPaymentTransactionMetaObject(kAccount1, kAccount2, 110, 30, 22) .getSerializer() .peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V1))); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV1))); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsubProposed(account, sessionPtr); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubAccountV2) { - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - trans1.metadata = createPaymentTransactionMetaObject(kACCOUNT1, kACCOUNT2, 110, 30, 22) + trans1.metadata = createPaymentTransactionMetaObject(kAccount1, kAccount2, 110, 30, 22) .getSerializer() .peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(2)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V2))); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV2))); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 0); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubBothTransactionAndAccount) { - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr, onDisconnect).Times(2); testFeedPtr->sub(account, sessionPtr); testFeedPtr->sub(sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 1); EXPECT_EQ(testFeedPtr->transactionSubCount(), 1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - trans1.metadata = createPaymentTransactionMetaObject(kACCOUNT1, kACCOUNT2, 110, 30, 22) + trans1.metadata = createPaymentTransactionMetaObject(kAccount1, kAccount2, 110, 30, 22) .getSerializer() .peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).Times(2).WillRepeatedly(testing::Return(2)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V2))).Times(2); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV2))).Times(2); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 0); testFeedPtr->unsub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubCount(), 0); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubBookV1) { - auto const issue1 = getIssue(kCURRENCY, kISSUER); - ripple::Book const book{ripple::xrpIssue(), issue1, std::nullopt}; + auto const issue1 = getIssue(kCurrency, kIssuer); + xrpl::Book const book{xrpl::xrpIssue(), issue1, std::nullopt}; EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(book, sessionPtr); EXPECT_EQ(testFeedPtr->bookSubCount(), 1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - auto obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + auto obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - auto metaObj = createMetaDataForBookChange(kCURRENCY, kISSUER, 22, 3, 1, 1, 3); + auto metaObj = createMetaDataForBookChange(kCurrency, kIssuer, 22, 3, 1, 1, 3); trans1.metadata = metaObj.getSerializer().peekData(); - static constexpr auto kORDERBOOK_PUBLISH = + static constexpr auto kOrderbookPublish = R"JSON({ "transaction": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -469,14 +469,14 @@ TEST_F(FeedTransactionTest, SubBookV1) })JSON"; EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kORDERBOOK_PUBLISH))).Times(1); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kOrderbookPublish))).Times(1); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); // trigger by offer cancel meta data - metaObj = createMetaDataForCancelOffer(kCURRENCY, kISSUER, 22, 3, 1); + metaObj = createMetaDataForCancelOffer(kCurrency, kIssuer, 22, 3, 1); trans1.metadata = metaObj.getSerializer().peekData(); - static constexpr auto kORDERBOOK_CANCEL_PUBLISH = + static constexpr auto kOrderbookCancelPublish = R"JSON({ "transaction": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -523,11 +523,11 @@ TEST_F(FeedTransactionTest, SubBookV1) })JSON"; EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kORDERBOOK_CANCEL_PUBLISH))).Times(1); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kOrderbookCancelPublish))).Times(1); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); // trigger by offer create meta data - static constexpr auto kORDERBOOK_CREATE_PUBLISH = + static constexpr auto kOrderbookCreatePublish = R"JSON({ "transaction": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -572,38 +572,38 @@ TEST_F(FeedTransactionTest, SubBookV1) "close_time_iso": "2000-01-01T00:00:00Z", "engine_result_message": "The transaction was applied. Only final in a validated ledger." })JSON"; - metaObj = createMetaDataForCreateOffer(kCURRENCY, kISSUER, 22, 3, 1); + metaObj = createMetaDataForCreateOffer(kCurrency, kIssuer, 22, 3, 1); trans1.metadata = metaObj.getSerializer().peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kORDERBOOK_CREATE_PUBLISH))).Times(1); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kOrderbookCreatePublish))).Times(1); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(book, sessionPtr); EXPECT_EQ(testFeedPtr->bookSubCount(), 0); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubBookV2) { - auto const issue1 = getIssue(kCURRENCY, kISSUER); - ripple::Book const book{ripple::xrpIssue(), issue1, std::nullopt}; + auto const issue1 = getIssue(kCurrency, kIssuer); + xrpl::Book const book{xrpl::xrpIssue(), issue1, std::nullopt}; EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(book, sessionPtr); EXPECT_EQ(testFeedPtr->bookSubCount(), 1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - auto obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + auto obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - auto const metaObj = createMetaDataForBookChange(kCURRENCY, kISSUER, 22, 3, 1, 1, 3); + auto const metaObj = createMetaDataForBookChange(kCurrency, kIssuer, 22, 3, 1, 1, 3); trans1.metadata = metaObj.getSerializer().peekData(); - static constexpr auto kORDERBOOK_PUBLISH = + static constexpr auto kOrderbookPublish = R"JSON({ "tx_json": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -657,91 +657,91 @@ TEST_F(FeedTransactionTest, SubBookV2) })JSON"; EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(2)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kORDERBOOK_PUBLISH))).Times(1); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kOrderbookPublish))).Times(1); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(book, sessionPtr); EXPECT_EQ(testFeedPtr->bookSubCount(), 0); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, TransactionContainsBothAccountsSubed) { - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(account, sessionPtr); - auto const account2 = getAccountIdWithString(kACCOUNT2); + auto const account2 = getAccountIdWithString(kAccount2); EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(account2, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 2); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - trans1.metadata = createPaymentTransactionMetaObject(kACCOUNT1, kACCOUNT2, 110, 30, 22) + trans1.metadata = createPaymentTransactionMetaObject(kAccount1, kAccount2, 110, 30, 22) .getSerializer() .peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(2)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V2))).Times(1); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV2))).Times(1); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 1); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(2)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V2))).Times(1); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV2))).Times(1); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(account2, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 0); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubAccountRepeatWithDifferentVersion) { - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(account, sessionPtr); - auto const account2 = getAccountIdWithString(kACCOUNT2); + auto const account2 = getAccountIdWithString(kAccount2); EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(account2, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 2); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - trans1.metadata = createPaymentTransactionMetaObject(kACCOUNT1, kACCOUNT2, 110, 30, 22) + trans1.metadata = createPaymentTransactionMetaObject(kAccount1, kAccount2, 110, 30, 22) .getSerializer() .peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(2)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V2))).Times(1); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV2))).Times(1); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 1); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(2)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V2))).Times(1); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV2))).Times(1); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(account2, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 0); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubTransactionRepeatWithDifferentVersion) @@ -754,23 +754,23 @@ TEST_F(FeedTransactionTest, SubTransactionRepeatWithDifferentVersion) testFeedPtr->sub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubCount(), 1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - trans1.metadata = createPaymentTransactionMetaObject(kACCOUNT1, kACCOUNT2, 110, 30, 22) + trans1.metadata = createPaymentTransactionMetaObject(kAccount1, kAccount2, 110, 30, 22) .getSerializer() .peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(2)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V2))).Times(1); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV2))).Times(1); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubCount(), 0); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubRepeat) @@ -795,8 +795,8 @@ TEST_F(FeedTransactionTest, SubRepeat) testFeedPtr->unsub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubCount(), 0); - auto const account = getAccountIdWithString(kACCOUNT1); - auto const account2 = getAccountIdWithString(kACCOUNT2); + auto const account = getAccountIdWithString(kAccount1); + auto const account2 = getAccountIdWithString(kAccount2); EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(account, sessionPtr); @@ -816,8 +816,8 @@ TEST_F(FeedTransactionTest, SubRepeat) testFeedPtr->unsub(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 0); - auto const issue1 = getIssue(kCURRENCY, kISSUER); - ripple::Book const book{ripple::xrpIssue(), issue1, std::nullopt}; + auto const issue1 = getIssue(kCurrency, kIssuer); + xrpl::Book const book{xrpl::xrpIssue(), issue1, std::nullopt}; EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(book, sessionPtr); @@ -840,39 +840,39 @@ TEST_F(FeedTransactionTest, PubTransactionWithOwnerFund) EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(sessionPtr); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = - createCreateOfferTransactionObject(kACCOUNT1, 1, 32, kCURRENCY, kISSUER, 1, 3); + xrpl::STObject const obj = + createCreateOfferTransactionObject(kAccount1, 1, 32, kCurrency, kIssuer, 1, 3); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - ripple::STArray const metaArray{0}; - ripple::STObject metaObj(ripple::sfTransactionMetaData); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 22); + xrpl::STArray const metaArray{0}; + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 22); trans1.metadata = metaObj.getSerializer().peekData(); - ripple::STObject line(ripple::sfIndexes); - line.setFieldU16(ripple::sfLedgerEntryType, ripple::ltRIPPLE_STATE); - line.setFieldAmount(ripple::sfLowLimit, ripple::STAmount(10, false)); - line.setFieldAmount(ripple::sfHighLimit, ripple::STAmount(100, false)); - line.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{kTXN_ID}); - line.setFieldU32(ripple::sfPreviousTxnLgrSeq, 3); - line.setFieldU32(ripple::sfFlags, 0); - auto const issue2 = getIssue(kCURRENCY, kISSUER); - line.setFieldAmount(ripple::sfBalance, ripple::STAmount(issue2, 100)); + xrpl::STObject line(xrpl::sfIndexes); + line.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltRIPPLE_STATE); + line.setFieldAmount(xrpl::sfLowLimit, xrpl::STAmount(10, false)); + line.setFieldAmount(xrpl::sfHighLimit, xrpl::STAmount(100, false)); + line.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{kTxnId}); + line.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 3); + line.setFieldU32(xrpl::sfFlags, 0); + auto const issue2 = getIssue(kCurrency, kIssuer); + line.setFieldAmount(xrpl::sfBalance, xrpl::STAmount(issue2, 100)); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); - auto const issueAccount = getAccountIdWithString(kISSUER); - auto const kk = ripple::keylet::account(issueAccount).key; + auto const issueAccount = getAccountIdWithString(kIssuer); + auto const kk = xrpl::keylet::account(issueAccount).key; ON_CALL(*backend_, doFetchLedgerObject(testing::_, testing::_, testing::_)) .WillByDefault(testing::Return(line.getSerializer().peekData())); - ripple::STObject const accountRoot = createAccountRootObject(kISSUER, 0, 1, 10, 2, kTXN_ID, 3); + xrpl::STObject const accountRoot = createAccountRootObject(kIssuer, 0, 1, 10, 2, kTxnId, 3); ON_CALL(*backend_, doFetchLedgerObject(kk, testing::_, testing::_)) .WillByDefault(testing::Return(accountRoot.getSerializer().peekData())); - static constexpr auto kTRANSACTION_FOR_OWNER_FUND = + static constexpr auto kTransactionForOwnerFund = R"JSON({ "transaction": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -908,7 +908,7 @@ TEST_F(FeedTransactionTest, PubTransactionWithOwnerFund) })JSON"; EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRANSACTION_FOR_OWNER_FUND))).Times(1); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTransactionForOwnerFund))).Times(1); EXPECT_CALL( *mockAmendmentCenterPtr_, isEnabled(testing::_, Amendments::fixFrozenLPTokenTransfer, testing::_) @@ -918,7 +918,7 @@ TEST_F(FeedTransactionTest, PubTransactionWithOwnerFund) isEnabled(testing::_, Amendments::fixFrozenLPTokenTransfer, testing::_) ) .WillByDefault(testing::Return(false)); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, PublishesNFTokenMintTx) @@ -926,23 +926,23 @@ TEST_F(FeedTransactionTest, PublishesNFTokenMintTx) EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(sessionPtr); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); // Creates an NFTokenMint transaction - auto const trans = createMintNftTxWithMetadata(kACCOUNT1, 1, 12, 123, kNFT_MINT_ID); + auto const trans = createMintNftTxWithMetadata(kAccount1, 1, 12, 123, kNftMintId); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kNFT_MINT_TRAN_V1))); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kNftMintTranV1))); - testFeedPtr->pub(trans, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubCount(), 0); - testFeedPtr->pub(trans, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } -static constexpr auto kTRAN_FROZEN = +static constexpr auto kTranFrozen = R"JSON({ "transaction": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -982,40 +982,40 @@ TEST_F(FeedTransactionTest, PubTransactionOfferCreationFrozenLine) EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(sessionPtr); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = - createCreateOfferTransactionObject(kACCOUNT1, 1, 32, kCURRENCY, kISSUER, 1, 3); + xrpl::STObject const obj = + createCreateOfferTransactionObject(kAccount1, 1, 32, kCurrency, kIssuer, 1, 3); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - ripple::STArray const metaArray{0}; - ripple::STObject metaObj(ripple::sfTransactionMetaData); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 22); + xrpl::STArray const metaArray{0}; + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 22); trans1.metadata = metaObj.getSerializer().peekData(); - ripple::STObject line(ripple::sfIndexes); - line.setFieldU16(ripple::sfLedgerEntryType, ripple::ltRIPPLE_STATE); - line.setFieldAmount(ripple::sfLowLimit, ripple::STAmount(10, false)); - line.setFieldAmount(ripple::sfHighLimit, ripple::STAmount(100, false)); - line.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{kTXN_ID}); - line.setFieldU32(ripple::sfPreviousTxnLgrSeq, 3); - line.setFieldU32(ripple::sfFlags, ripple::lsfHighFreeze); - line.setFieldAmount(ripple::sfBalance, ripple::STAmount(getIssue(kCURRENCY, kISSUER), 100)); + xrpl::STObject line(xrpl::sfIndexes); + line.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltRIPPLE_STATE); + line.setFieldAmount(xrpl::sfLowLimit, xrpl::STAmount(10, false)); + line.setFieldAmount(xrpl::sfHighLimit, xrpl::STAmount(100, false)); + line.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{kTxnId}); + line.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 3); + line.setFieldU32(xrpl::sfFlags, xrpl::lsfHighFreeze); + line.setFieldAmount(xrpl::sfBalance, xrpl::STAmount(getIssue(kCurrency, kIssuer), 100)); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); - auto const issueAccount = getAccountIdWithString(kISSUER); - auto const kk = ripple::keylet::account(issueAccount).key; + auto const issueAccount = getAccountIdWithString(kIssuer); + auto const kk = xrpl::keylet::account(issueAccount).key; ON_CALL(*backend_, doFetchLedgerObject(testing::_, testing::_, testing::_)) .WillByDefault(testing::Return(line.getSerializer().peekData())); - ripple::STObject const accountRoot = createAccountRootObject(kISSUER, 0, 1, 10, 2, kTXN_ID, 3); + xrpl::STObject const accountRoot = createAccountRootObject(kIssuer, 0, 1, 10, 2, kTxnId, 3); ON_CALL(*backend_, doFetchLedgerObject(kk, testing::_, testing::_)) .WillByDefault(testing::Return(accountRoot.getSerializer().peekData())); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_FROZEN))).Times(1); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranFrozen))).Times(1); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubTransactionOfferCreationGlobalFrozen) @@ -1023,46 +1023,46 @@ TEST_F(FeedTransactionTest, SubTransactionOfferCreationGlobalFrozen) EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(sessionPtr); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = - createCreateOfferTransactionObject(kACCOUNT1, 1, 32, kCURRENCY, kISSUER, 1, 3); + xrpl::STObject const obj = + createCreateOfferTransactionObject(kAccount1, 1, 32, kCurrency, kIssuer, 1, 3); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - ripple::STArray const metaArray{0}; - ripple::STObject metaObj(ripple::sfTransactionMetaData); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 22); + xrpl::STArray const metaArray{0}; + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 22); trans1.metadata = metaObj.getSerializer().peekData(); - ripple::STObject line(ripple::sfIndexes); - line.setFieldU16(ripple::sfLedgerEntryType, ripple::ltRIPPLE_STATE); - line.setFieldAmount(ripple::sfLowLimit, ripple::STAmount(10, false)); - line.setFieldAmount(ripple::sfHighLimit, ripple::STAmount(100, false)); - line.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{kTXN_ID}); - line.setFieldU32(ripple::sfPreviousTxnLgrSeq, 3); - line.setFieldU32(ripple::sfFlags, ripple::lsfHighFreeze); - auto const issueAccount = getAccountIdWithString(kISSUER); - line.setFieldAmount(ripple::sfBalance, ripple::STAmount(getIssue(kCURRENCY, kISSUER), 100)); + xrpl::STObject line(xrpl::sfIndexes); + line.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltRIPPLE_STATE); + line.setFieldAmount(xrpl::sfLowLimit, xrpl::STAmount(10, false)); + line.setFieldAmount(xrpl::sfHighLimit, xrpl::STAmount(100, false)); + line.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{kTxnId}); + line.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 3); + line.setFieldU32(xrpl::sfFlags, xrpl::lsfHighFreeze); + auto const issueAccount = getAccountIdWithString(kIssuer); + line.setFieldAmount(xrpl::sfBalance, xrpl::STAmount(getIssue(kCurrency, kIssuer), 100)); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - auto const kk = ripple::keylet::account(issueAccount).key; + auto const kk = xrpl::keylet::account(issueAccount).key; ON_CALL(*backend_, doFetchLedgerObject(testing::_, testing::_, testing::_)) .WillByDefault(testing::Return(line.getSerializer().peekData())); - ripple::STObject const accountRoot = - createAccountRootObject(kISSUER, ripple::lsfGlobalFreeze, 1, 10, 2, kTXN_ID, 3); + xrpl::STObject const accountRoot = + createAccountRootObject(kIssuer, xrpl::lsfGlobalFreeze, 1, 10, 2, kTxnId, 3); ON_CALL(*backend_, doFetchLedgerObject(kk, testing::_, testing::_)) .WillByDefault(testing::Return(accountRoot.getSerializer().peekData())); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_FROZEN))).Times(1); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranFrozen))).Times(1); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubBothProposedAndValidatedAccount) { - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(account, sessionPtr); @@ -1071,24 +1071,24 @@ TEST_F(FeedTransactionTest, SubBothProposedAndValidatedAccount) testFeedPtr->subProposed(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - trans1.metadata = createPaymentTransactionMetaObject(kACCOUNT1, kACCOUNT2, 110, 30, 22) + trans1.metadata = createPaymentTransactionMetaObject(kAccount1, kAccount2, 110, 30, 22) .getSerializer() .peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V1))).Times(1); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV1))).Times(1); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(account, sessionPtr); testFeedPtr->unsubProposed(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 0); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubBothProposedAndValidated) @@ -1100,22 +1100,22 @@ TEST_F(FeedTransactionTest, SubBothProposedAndValidated) testFeedPtr->subProposed(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubCount(), 1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - trans1.metadata = createPaymentTransactionMetaObject(kACCOUNT1, kACCOUNT2, 110, 30, 22) + trans1.metadata = createPaymentTransactionMetaObject(kAccount1, kAccount2, 110, 30, 22) .getSerializer() .peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).Times(2).WillRepeatedly(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V1))).Times(2); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV1))).Times(2); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(sessionPtr); testFeedPtr->unsubProposed(sessionPtr); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubProposedDisconnect) @@ -1124,46 +1124,46 @@ TEST_F(FeedTransactionTest, SubProposedDisconnect) testFeedPtr->subProposed(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubCount(), 0); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - trans1.metadata = createPaymentTransactionMetaObject(kACCOUNT1, kACCOUNT2, 110, 30, 22) + trans1.metadata = createPaymentTransactionMetaObject(kAccount1, kAccount2, 110, 30, 22) .getSerializer() .peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V1))).Times(1); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV1))).Times(1); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); sessionPtr.reset(); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, SubProposedAccountDisconnect) { - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->subProposed(account, sessionPtr); EXPECT_EQ(testFeedPtr->accountSubCount(), 0); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - trans1.metadata = createPaymentTransactionMetaObject(kACCOUNT1, kACCOUNT2, 110, 30, 22) + trans1.metadata = createPaymentTransactionMetaObject(kAccount1, kAccount2, 110, 30, 22) .getSerializer() .peekData(); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRAN_V1))).Times(1); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTranV1))).Times(1); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); sessionPtr.reset(); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } // This test exercises `accountHold` for amendment fixFrozenLPTokenTransfer, so that the output @@ -1173,45 +1173,45 @@ TEST_F(FeedTransactionTest, PubTransactionWithOwnerFundFrozenLPToken) EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(sessionPtr); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = - createCreateOfferTransactionObject(kACCOUNT1, 1, 32, kLPTOKEN_CURRENCY, kAMM_ACCOUNT, 1, 3); + xrpl::STObject const obj = + createCreateOfferTransactionObject(kAccount1, 1, 32, kLptokenCurrency, kAmmAccount, 1, 3); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - ripple::STArray const metaArray{0}; - ripple::STObject metaObj(ripple::sfTransactionMetaData); - metaObj.setFieldArray(ripple::sfAffectedNodes, metaArray); - metaObj.setFieldU8(ripple::sfTransactionResult, ripple::tesSUCCESS); - metaObj.setFieldU32(ripple::sfTransactionIndex, 22); + xrpl::STArray const metaArray{0}; + xrpl::STObject metaObj(xrpl::sfTransactionMetaData); + metaObj.setFieldArray(xrpl::sfAffectedNodes, metaArray); + metaObj.setFieldU8(xrpl::sfTransactionResult, xrpl::tesSUCCESS); + metaObj.setFieldU32(xrpl::sfTransactionIndex, 22); trans1.metadata = metaObj.getSerializer().peekData(); - ripple::STObject line(ripple::sfIndexes); - line.setFieldU16(ripple::sfLedgerEntryType, ripple::ltRIPPLE_STATE); - line.setFieldAmount(ripple::sfLowLimit, ripple::STAmount(10, false)); - line.setFieldAmount(ripple::sfHighLimit, ripple::STAmount(100, false)); - line.setFieldH256(ripple::sfPreviousTxnID, ripple::uint256{kTXN_ID}); - line.setFieldU32(ripple::sfPreviousTxnLgrSeq, 3); - line.setFieldU32(ripple::sfFlags, 0); - auto const issue2 = getIssue(kLPTOKEN_CURRENCY, kAMM_ACCOUNT); - line.setFieldAmount(ripple::sfBalance, ripple::STAmount(issue2, 100)); + xrpl::STObject line(xrpl::sfIndexes); + line.setFieldU16(xrpl::sfLedgerEntryType, xrpl::ltRIPPLE_STATE); + line.setFieldAmount(xrpl::sfLowLimit, xrpl::STAmount(10, false)); + line.setFieldAmount(xrpl::sfHighLimit, xrpl::STAmount(100, false)); + line.setFieldH256(xrpl::sfPreviousTxnID, xrpl::uint256{kTxnId}); + line.setFieldU32(xrpl::sfPreviousTxnLgrSeq, 3); + line.setFieldU32(xrpl::sfFlags, 0); + auto const issue2 = getIssue(kLptokenCurrency, kAmmAccount); + line.setFieldAmount(xrpl::sfBalance, xrpl::STAmount(issue2, 100)); EXPECT_CALL(*backend_, doFetchLedgerObject(testing::_, testing::_, testing::_)) .Times(2) .WillRepeatedly(testing::Return(line.getSerializer().peekData())); - auto const ammID = ripple::uint256{54321}; + auto const ammID = xrpl::uint256{54321}; // create an amm account because in `accountHolds` checks for the ammID - auto const ammAccount = getAccountIdWithString(kAMM_ACCOUNT); - auto const kk = ripple::keylet::account(ammAccount).key; - ripple::STObject const ammAccountRoot = - createAccountRootObject(kAMM_ACCOUNT, 0, 1, 10, 2, kTXN_ID, 3, 0, ammID); + auto const ammAccount = getAccountIdWithString(kAmmAccount); + auto const kk = xrpl::keylet::account(ammAccount).key; + xrpl::STObject const ammAccountRoot = + createAccountRootObject(kAmmAccount, 0, 1, 10, 2, kTxnId, 3, 0, ammID); EXPECT_CALL(*backend_, doFetchLedgerObject(kk, testing::_, testing::_)) .Times(2) .WillRepeatedly(testing::Return(ammAccountRoot.getSerializer().peekData())); - static constexpr auto kTRANSACTION_FOR_OWNER_FUND = + static constexpr auto kTransactionForOwnerFund = R"JSON({ "transaction": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -1247,7 +1247,7 @@ TEST_F(FeedTransactionTest, PubTransactionWithOwnerFundFrozenLPToken) })JSON"; EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTRANSACTION_FOR_OWNER_FUND))).Times(1); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kTransactionForOwnerFund))).Times(1); EXPECT_CALL( *mockAmendmentCenterPtr_, @@ -1255,30 +1255,29 @@ TEST_F(FeedTransactionTest, PubTransactionWithOwnerFundFrozenLPToken) ) .WillOnce(testing::Return(true)); - auto const ammObj = createAmmObject( - kAMM_ACCOUNT, "XRP", ripple::toBase58(ripple::xrpAccount()), kCURRENCY, kISSUER - ); + auto const ammObj = + createAmmObject(kAmmAccount, "XRP", xrpl::toBase58(xrpl::xrpAccount()), kCurrency, kIssuer); EXPECT_CALL( - *backend_, doFetchLedgerObject(ripple::keylet::amm(ammID).key, testing::_, testing::_) + *backend_, doFetchLedgerObject(xrpl::keylet::amm(ammID).key, testing::_, testing::_) ) .WillOnce(testing::Return(ammObj.getSerializer().peekData())); // create the issuer account that enacted global freeze - auto const issuerAccount = getAccountIdWithString(kISSUER); - ripple::STObject const issuerAccountRoot = - createAccountRootObject(kISSUER, 4194304, 1, 10, 2, kTXN_ID, 3); + auto const issuerAccount = getAccountIdWithString(kIssuer); + xrpl::STObject const issuerAccountRoot = + createAccountRootObject(kIssuer, 4194304, 1, 10, 2, kTxnId, 3); EXPECT_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(issuerAccount).key, testing::_, testing::_) + doFetchLedgerObject(xrpl::keylet::account(issuerAccount).key, testing::_, testing::_) ) .WillOnce(testing::Return(issuerAccountRoot.getSerializer().peekData())); - testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans1, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, PublishesMPTokenIssuanceCreateTx) { - constexpr auto kMPTOKEN_ISSUANCE_CREATE_TRAN_V1 = + constexpr auto kMptokenIssuanceCreateTranV1 = R"JSON({ "transaction": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -1330,23 +1329,23 @@ TEST_F(FeedTransactionTest, PublishesMPTokenIssuanceCreateTx) testFeedPtr->sub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubCount(), 1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); - auto const trans = createMPTIssuanceCreateTxWithMetadata(kACCOUNT1, 12, 1); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); + auto const trans = createMPTIssuanceCreateTxWithMetadata(kAccount1, 12, 1); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kMPTOKEN_ISSUANCE_CREATE_TRAN_V1))); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kMptokenIssuanceCreateTranV1))); - testFeedPtr->pub(trans, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(sessionPtr); EXPECT_EQ(testFeedPtr->transactionSubCount(), 0); - testFeedPtr->pub(trans, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } TEST_F(FeedTransactionTest, PublishesMPTokenAuthorizeTx) { - constexpr auto kMPTOKEN_AUTHORIZE_TRAN_V1 = + constexpr auto kMptokenAuthorizeTranV1 = R"JSON({ "transaction": { "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -1390,18 +1389,18 @@ TEST_F(FeedTransactionTest, PublishesMPTokenAuthorizeTx) EXPECT_CALL(*mockSessionPtr, onDisconnect); testFeedPtr->sub(sessionPtr); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 33); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 33); // The issuance ID that this transaction is authorizing - auto const mptIssuanceID = ripple::makeMptID(1, getAccountIdWithString(kACCOUNT1)); - auto const trans = createMPTokenAuthorizeTxWithMetadata(kACCOUNT1, mptIssuanceID, 15, 5); + auto const mptIssuanceID = xrpl::makeMptID(1, getAccountIdWithString(kAccount1)); + auto const trans = createMPTokenAuthorizeTxWithMetadata(kAccount1, mptIssuanceID, 15, 5); EXPECT_CALL(*mockSessionPtr, apiSubversion).WillOnce(testing::Return(1)); - EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kMPTOKEN_AUTHORIZE_TRAN_V1))); + EXPECT_CALL(*mockSessionPtr, send(sharedStringJsonEq(kMptokenAuthorizeTranV1))); - testFeedPtr->pub(trans, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); testFeedPtr->unsub(sessionPtr); - testFeedPtr->pub(trans, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNETWORK_ID); + testFeedPtr->pub(trans, ledgerHeader, backend_, mockAmendmentCenterPtr_, kNetworkId); } struct TransactionFeedMockPrometheusTest : WithMockPrometheus, SyncExecutionCtxFixture { @@ -1429,13 +1428,13 @@ TEST_F(TransactionFeedMockPrometheusTest, subUnsub) testFeedPtr_->sub(sessionPtr_); testFeedPtr_->unsub(sessionPtr_); - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); EXPECT_CALL(*mockSessionPtr_, onDisconnect); testFeedPtr_->sub(account, sessionPtr_); testFeedPtr_->unsub(account, sessionPtr_); - auto const issue1 = getIssue(kCURRENCY, kISSUER); - ripple::Book const book{ripple::xrpIssue(), issue1, std::nullopt}; + auto const issue1 = getIssue(kCurrency, kIssuer); + xrpl::Book const book{xrpl::xrpIssue(), issue1, std::nullopt}; EXPECT_CALL(*mockSessionPtr_, onDisconnect); testFeedPtr_->sub(book, sessionPtr_); testFeedPtr_->unsub(book, sessionPtr_); @@ -1464,11 +1463,11 @@ TEST_F(TransactionFeedMockPrometheusTest, AutoDisconnect) }); testFeedPtr_->sub(sessionPtr_); - auto const account = getAccountIdWithString(kACCOUNT1); + auto const account = getAccountIdWithString(kAccount1); testFeedPtr_->sub(account, sessionPtr_); - auto const issue1 = getIssue(kCURRENCY, kISSUER); - ripple::Book const book{ripple::xrpIssue(), issue1, std::nullopt}; + auto const issue1 = getIssue(kCurrency, kIssuer); + xrpl::Book const book{xrpl::xrpIssue(), issue1, std::nullopt}; testFeedPtr_->sub(book, sessionPtr_); // Emulate onDisconnect signal is called diff --git a/tests/unit/migration/cassandra/SpecTests.cpp b/tests/unit/migration/cassandra/SpecTests.cpp index da69e1a91..5d5e89a20 100644 --- a/tests/unit/migration/cassandra/SpecTests.cpp +++ b/tests/unit/migration/cassandra/SpecTests.cpp @@ -10,8 +10,8 @@ class Empty {}; struct SimpleTestTable { using Row = std::tuple; - static constexpr char const* kPARTITION_KEY = "key"; - static constexpr char const* kTABLE_NAME = "test"; + static constexpr char const* kPartitionKey = "key"; + static constexpr char const* kTableName = "test"; }; } // namespace TEST(MigrationSpec, TableSpec) diff --git a/tests/unit/rpc/APIVersionTests.cpp b/tests/unit/rpc/APIVersionTests.cpp index 83d65b667..85aeb0ad9 100644 --- a/tests/unit/rpc/APIVersionTests.cpp +++ b/tests/unit/rpc/APIVersionTests.cpp @@ -8,52 +8,53 @@ namespace { -constexpr auto kDEFAULT_API_VERSION = 5u; -constexpr auto kMIN_API_VERSION = 2u; -constexpr auto kMAX_API_VERSION = 10u; +constexpr auto kDefaultApiVersion = 5u; +constexpr auto kMinApiVersion = 2u; +constexpr auto kMaxApiVersion = 10u; } // namespace using namespace util::config; using namespace rpc::impl; -namespace json = boost::json; class RPCAPIVersionTest : public virtual ::testing::Test { protected: - ProductionAPIVersionParser parser_{kDEFAULT_API_VERSION, kMIN_API_VERSION, kMAX_API_VERSION}; + ProductionAPIVersionParser parser_{kDefaultApiVersion, kMinApiVersion, kMaxApiVersion}; }; TEST_F(RPCAPIVersionTest, ReturnsDefaultVersionIfNotSpecified) { - auto ver = parser_.parse(json::parse("{}").as_object()); + auto ver = parser_.parse(boost::json::parse("{}").as_object()); EXPECT_TRUE(ver); - EXPECT_EQ(ver.value(), kDEFAULT_API_VERSION); + EXPECT_EQ(ver.value(), kDefaultApiVersion); } TEST_F(RPCAPIVersionTest, ReturnsErrorIfVersionHigherThanMaxSupported) { - auto ver = parser_.parse(json::parse(R"JSON({"api_version": 11})JSON").as_object()); + auto ver = parser_.parse(boost::json::parse(R"JSON({"api_version": 11})JSON").as_object()); EXPECT_FALSE(ver); } TEST_F(RPCAPIVersionTest, ReturnsErrorIfVersionLowerThanMinSupported) { - auto ver = parser_.parse(json::parse(R"JSON({"api_version": 1})JSON").as_object()); + auto ver = parser_.parse(boost::json::parse(R"JSON({"api_version": 1})JSON").as_object()); EXPECT_FALSE(ver); } TEST_F(RPCAPIVersionTest, ReturnsErrorOnWrongType) { { - auto ver = parser_.parse(json::parse(R"JSON({"api_version": null})JSON").as_object()); + auto ver = + parser_.parse(boost::json::parse(R"JSON({"api_version": null})JSON").as_object()); EXPECT_FALSE(ver); } { - auto ver = parser_.parse(json::parse(R"JSON({"api_version": "5"})JSON").as_object()); + auto ver = parser_.parse(boost::json::parse(R"JSON({"api_version": "5"})JSON").as_object()); EXPECT_FALSE(ver); } { - auto ver = parser_.parse(json::parse(R"JSON({"api_version": "wrong"})JSON").as_object()); + auto ver = + parser_.parse(boost::json::parse(R"JSON({"api_version": "wrong"})JSON").as_object()); EXPECT_FALSE(ver); } } @@ -61,17 +62,17 @@ TEST_F(RPCAPIVersionTest, ReturnsErrorOnWrongType) TEST_F(RPCAPIVersionTest, ReturnsParsedVersionIfAllPreconditionsAreMet) { { - auto ver = parser_.parse(json::parse(R"JSON({"api_version": 2})JSON").as_object()); + auto ver = parser_.parse(boost::json::parse(R"JSON({"api_version": 2})JSON").as_object()); EXPECT_TRUE(ver); EXPECT_EQ(ver.value(), 2u); } { - auto ver = parser_.parse(json::parse(R"JSON({"api_version": 10})JSON").as_object()); + auto ver = parser_.parse(boost::json::parse(R"JSON({"api_version": 10})JSON").as_object()); EXPECT_TRUE(ver); EXPECT_EQ(ver.value(), 10u); } { - auto ver = parser_.parse(json::parse(R"JSON({"api_version": 5})JSON").as_object()); + auto ver = parser_.parse(boost::json::parse(R"JSON({"api_version": 5})JSON").as_object()); EXPECT_TRUE(ver); EXPECT_EQ(ver.value(), 5u); } @@ -80,41 +81,46 @@ TEST_F(RPCAPIVersionTest, ReturnsParsedVersionIfAllPreconditionsAreMet) TEST_F(RPCAPIVersionTest, GetsValuesFromConfigCorrectly) { ClioConfigDefinition const cfg{ - {"api_version.min", ConfigValue{ConfigType::Integer}.defaultValue(kMIN_API_VERSION)}, - {"api_version.max", ConfigValue{ConfigType::Integer}.defaultValue(kMAX_API_VERSION)}, - {"api_version.default", ConfigValue{ConfigType::Integer}.defaultValue(kDEFAULT_API_VERSION)} + {"api_version.min", ConfigValue{ConfigType::Integer}.defaultValue(kMinApiVersion)}, + {"api_version.max", ConfigValue{ConfigType::Integer}.defaultValue(kMaxApiVersion)}, + {"api_version.default", ConfigValue{ConfigType::Integer}.defaultValue(kDefaultApiVersion)} }; ProductionAPIVersionParser const configuredParser{cfg.getObject("api_version")}; { - auto ver = configuredParser.parse(json::parse(R"JSON({"api_version": 2})JSON").as_object()); + auto ver = + configuredParser.parse(boost::json::parse(R"JSON({"api_version": 2})JSON").as_object()); EXPECT_TRUE(ver); EXPECT_EQ(ver.value(), 2u); } { - auto ver = - configuredParser.parse(json::parse(R"JSON({"api_version": 10})JSON").as_object()); + auto ver = configuredParser.parse( + boost::json::parse(R"JSON({"api_version": 10})JSON").as_object() + ); EXPECT_TRUE(ver); EXPECT_EQ(ver.value(), 10u); } { - auto ver = configuredParser.parse(json::parse(R"JSON({"api_version": 5})JSON").as_object()); + auto ver = + configuredParser.parse(boost::json::parse(R"JSON({"api_version": 5})JSON").as_object()); EXPECT_TRUE(ver); EXPECT_EQ(ver.value(), 5u); } { - auto ver = configuredParser.parse(json::parse(R"JSON({})JSON").as_object()); + auto ver = configuredParser.parse(boost::json::parse(R"JSON({})JSON").as_object()); EXPECT_TRUE(ver); - EXPECT_EQ(ver.value(), kDEFAULT_API_VERSION); + EXPECT_EQ(ver.value(), kDefaultApiVersion); + } + { + auto ver = configuredParser.parse( + boost::json::parse(R"JSON({"api_version": 11})JSON").as_object() + ); + EXPECT_FALSE(ver); } { auto ver = - configuredParser.parse(json::parse(R"JSON({"api_version": 11})JSON").as_object()); - EXPECT_FALSE(ver); - } - { - auto ver = configuredParser.parse(json::parse(R"JSON({"api_version": 1})JSON").as_object()); + configuredParser.parse(boost::json::parse(R"JSON({"api_version": 1})JSON").as_object()); EXPECT_FALSE(ver); } } diff --git a/tests/unit/rpc/AmendmentsTests.cpp b/tests/unit/rpc/AmendmentsTests.cpp index 1d08c113e..6dd320ca6 100644 --- a/tests/unit/rpc/AmendmentsTests.cpp +++ b/tests/unit/rpc/AmendmentsTests.cpp @@ -9,7 +9,7 @@ TEST(RPCAmendmentsTest, GenerateAmendmentId) { // https://xrpl.org/known-amendments.html#disallowincoming refer to the published id EXPECT_EQ( - ripple::uint256("47C3002ABA31628447E8E9A8B315FAA935CE30183F9A9B86845E469CA2CDC3DF"), + xrpl::uint256("47C3002ABA31628447E8E9A8B315FAA935CE30183F9A9B86845E469CA2CDC3DF"), Amendments::GetAmendmentId("DisallowIncoming") ); } diff --git a/tests/unit/rpc/BaseTests.cpp b/tests/unit/rpc/BaseTests.cpp index d2d2a74af..0c09ea4aa 100644 --- a/tests/unit/rpc/BaseTests.cpp +++ b/tests/unit/rpc/BaseTests.cpp @@ -28,20 +28,18 @@ using namespace rpc::validation; using namespace rpc::meta; using namespace rpc::modifiers; -namespace json = boost::json; - class RPCBaseTest : public virtual ::testing::Test {}; TEST_F(RPCBaseTest, CheckTypeString) { - auto const jString = json::value("a string"); + auto const jString = boost::json::value("a string"); ASSERT_TRUE(checkType(jString)); ASSERT_FALSE(checkType(jString)); } TEST_F(RPCBaseTest, CheckTypeUint) { - auto const jUint = json::value(123u); + auto const jUint = boost::json::value(123u); ASSERT_TRUE(checkType(jUint)); ASSERT_TRUE(checkType(jUint)); ASSERT_FALSE(checkType(jUint)); @@ -49,12 +47,12 @@ TEST_F(RPCBaseTest, CheckTypeUint) TEST_F(RPCBaseTest, CheckTypeInt) { - auto jInt = json::value(123); + auto jInt = boost::json::value(123); ASSERT_TRUE(checkType(jInt)); ASSERT_TRUE(checkType(jInt)); ASSERT_FALSE(checkType(jInt)); - jInt = json::value(-123); + jInt = boost::json::value(-123); ASSERT_TRUE(checkType(jInt)); ASSERT_FALSE(checkType(jInt)); // Unsigned can't be negative ASSERT_FALSE(checkType(jInt)); @@ -62,14 +60,14 @@ TEST_F(RPCBaseTest, CheckTypeInt) TEST_F(RPCBaseTest, CheckTypeBool) { - auto const jBool = json::value(true); + auto const jBool = boost::json::value(true); ASSERT_TRUE(checkType(jBool)); ASSERT_FALSE(checkType(jBool)); } TEST_F(RPCBaseTest, CheckTypeDouble) { - auto const jDouble = json::value(0.123); + auto const jDouble = boost::json::value(0.123); ASSERT_TRUE(checkType(jDouble)); ASSERT_TRUE(checkType(jDouble)); ASSERT_FALSE(checkType(jDouble)); @@ -77,50 +75,50 @@ TEST_F(RPCBaseTest, CheckTypeDouble) TEST_F(RPCBaseTest, CheckTypeArray) { - auto const jArr = json::value({1, 2, 3}); - ASSERT_TRUE(checkType(jArr)); + auto const jArr = boost::json::value({1, 2, 3}); + ASSERT_TRUE(checkType(jArr)); ASSERT_FALSE(checkType(jArr)); } TEST_F(RPCBaseTest, CheckTypeAndClampValueUnchanged) { - auto jUint = json::value(123u); + auto jUint = boost::json::value(123u); ASSERT_TRUE(checkTypeAndClamp(jUint)); ASSERT_EQ(jUint.as_uint64(), 123u); ASSERT_TRUE(checkTypeAndClamp(jUint)); ASSERT_EQ(jUint.as_uint64(), 123u); - auto jInt = json::value(123); + auto jInt = boost::json::value(123); ASSERT_TRUE(checkTypeAndClamp(jInt)); ASSERT_EQ(jInt.as_int64(), 123); ASSERT_TRUE(checkTypeAndClamp(jInt)); ASSERT_EQ(jInt.as_int64(), 123); - jInt = json::value(-123); + jInt = boost::json::value(-123); ASSERT_TRUE(checkTypeAndClamp(jInt)); ASSERT_EQ(jInt.as_int64(), -123); } TEST_F(RPCBaseTest, CheckTypeAndClampInvalidValues) { - auto jInt = json::value(-123); + auto jInt = boost::json::value(-123); ASSERT_FALSE(checkTypeAndClamp(jInt)); // Unsigned can't be negative } TEST_F(RPCBaseTest, CheckTypeAndClampOverflow) { - auto jBigUint = json::value(std::numeric_limits::max()); + auto jBigUint = boost::json::value(std::numeric_limits::max()); ASSERT_TRUE(checkTypeAndClamp(jBigUint)); ASSERT_EQ(jBigUint.as_uint64(), std::numeric_limits::max()); - auto jBigInt = json::value(std::numeric_limits::max()); + auto jBigInt = boost::json::value(std::numeric_limits::max()); ASSERT_TRUE(checkTypeAndClamp(jBigInt)); ASSERT_EQ(jBigInt.as_int64(), std::numeric_limits::max()); } TEST_F(RPCBaseTest, CheckTypeAndClampUnderflow) { - auto jLowInt = json::value(std::numeric_limits::min()); + auto jLowInt = boost::json::value(std::numeric_limits::min()); ASSERT_TRUE(checkTypeAndClamp(jLowInt)); ASSERT_EQ(jLowInt.as_int64(), std::numeric_limits::min()); } @@ -133,10 +131,10 @@ TEST_F(RPCBaseTest, TypeValidator) {"str", Type{}}, {"double", Type{}}, {"bool", Type{}}, - {"arr", Type{}}, + {"arr", Type{}}, }; - auto passingInput = json::parse(R"JSON({ + auto passingInput = boost::json::parse(R"JSON({ "uint": 123, "int": 321, "str": "a string", @@ -147,27 +145,27 @@ TEST_F(RPCBaseTest, TypeValidator) ASSERT_TRUE(spec.process(passingInput)); { - auto failingInput = json::parse(R"JSON({ "uint": "a string" })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "uint": "a string" })JSON"); ASSERT_FALSE(spec.process(failingInput)); } { - auto failingInput = json::parse(R"JSON({ "int": "a string" })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "int": "a string" })JSON"); ASSERT_FALSE(spec.process(failingInput)); } { - auto failingInput = json::parse(R"JSON({ "str": 1234 })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "str": 1234 })JSON"); ASSERT_FALSE(spec.process(failingInput)); } { - auto failingInput = json::parse(R"JSON({ "double": "a string" })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "double": "a string" })JSON"); ASSERT_FALSE(spec.process(failingInput)); } { - auto failingInput = json::parse(R"JSON({ "bool": "a string" })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "bool": "a string" })JSON"); ASSERT_FALSE(spec.process(failingInput)); } { - auto failingInput = json::parse(R"JSON({ "arr": "a string" })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "arr": "a string" })JSON"); ASSERT_FALSE(spec.process(failingInput)); } } @@ -179,13 +177,13 @@ TEST_F(RPCBaseTest, TypeValidatorMultipleTypes) {"test", Type{}}, }; - auto passingInput = json::parse(R"JSON({ "test": "1234" })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "test": "1234" })JSON"); ASSERT_TRUE(spec.process(passingInput)); - auto passingInput2 = json::parse(R"JSON({ "test": 1234 })JSON"); + auto passingInput2 = boost::json::parse(R"JSON({ "test": 1234 })JSON"); ASSERT_TRUE(spec.process(passingInput2)); - auto failingInput = json::parse(R"JSON({ "test": true })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "test": true })JSON"); ASSERT_FALSE(spec.process(failingInput)); } @@ -195,13 +193,13 @@ TEST_F(RPCBaseTest, RequiredValidator) {"required", Required{}}, }; - auto passingInput = json::parse(R"JSON({ "required": "present" })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "required": "present" })JSON"); ASSERT_TRUE(spec.process(passingInput)); - auto passingInput2 = json::parse(R"JSON({ "required": true })JSON"); + auto passingInput2 = boost::json::parse(R"JSON({ "required": true })JSON"); ASSERT_TRUE(spec.process(passingInput2)); - auto failingInput = json::parse(R"JSON({})JSON"); + auto failingInput = boost::json::parse(R"JSON({})JSON"); ASSERT_FALSE(spec.process(failingInput)); } @@ -211,19 +209,19 @@ TEST_F(RPCBaseTest, BetweenValidator) {"amount", Between{10u, 20u}}, }; - auto passingInput = json::parse(R"JSON({ "amount": 15 })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "amount": 15 })JSON"); ASSERT_TRUE(spec.process(passingInput)); - auto passingInput2 = json::parse(R"JSON({ "amount": 10 })JSON"); + auto passingInput2 = boost::json::parse(R"JSON({ "amount": 10 })JSON"); ASSERT_TRUE(spec.process(passingInput2)); - auto passingInput3 = json::parse(R"JSON({ "amount": 20 })JSON"); + auto passingInput3 = boost::json::parse(R"JSON({ "amount": 20 })JSON"); ASSERT_TRUE(spec.process(passingInput3)); - auto failingInput = json::parse(R"JSON({ "amount": 9 })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "amount": 9 })JSON"); ASSERT_FALSE(spec.process(failingInput)); - auto failingInput2 = json::parse(R"JSON({ "amount": 21 })JSON"); + auto failingInput2 = boost::json::parse(R"JSON({ "amount": 21 })JSON"); ASSERT_FALSE(spec.process(failingInput2)); } @@ -233,13 +231,13 @@ TEST_F(RPCBaseTest, MinValidator) {"amount", Min{6}}, }; - auto passingInput = json::parse(R"JSON({ "amount": 7 })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "amount": 7 })JSON"); ASSERT_TRUE(spec.process(passingInput)); - auto passingInput2 = json::parse(R"JSON({ "amount": 6 })JSON"); + auto passingInput2 = boost::json::parse(R"JSON({ "amount": 6 })JSON"); ASSERT_TRUE(spec.process(passingInput2)); - auto failingInput = json::parse(R"JSON({ "amount": 5 })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "amount": 5 })JSON"); ASSERT_FALSE(spec.process(failingInput)); } @@ -251,7 +249,7 @@ TEST_F(RPCBaseTest, MinValidatorAfterType) {"amount3", Type{}, Min{std::numeric_limits::min()}}, }; - auto bigInput = json::parse( + auto bigInput = boost::json::parse( R"JSON({ "amount": 9999999999, "amount2": 9999999999, "amount3": -9999999999 })JSON" ); ASSERT_TRUE(spec.process(bigInput)); // type check clamps to type's max/min value @@ -263,13 +261,13 @@ TEST_F(RPCBaseTest, MaxValidator) {"amount", Max{6}}, }; - auto passingInput = json::parse(R"JSON({ "amount": 5 })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "amount": 5 })JSON"); ASSERT_TRUE(spec.process(passingInput)); - auto passingInput2 = json::parse(R"JSON({ "amount": 6 })JSON"); + auto passingInput2 = boost::json::parse(R"JSON({ "amount": 6 })JSON"); ASSERT_TRUE(spec.process(passingInput2)); - auto failingInput = json::parse(R"JSON({ "amount": 7 })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "amount": 7 })JSON"); ASSERT_FALSE(spec.process(failingInput)); } @@ -281,7 +279,7 @@ TEST_F(RPCBaseTest, MaxValidatorAfterType) {"amount3", Type{}, Max{std::numeric_limits::min()}}, }; - auto bigInput = json::parse( + auto bigInput = boost::json::parse( R"JSON({ "amount": 9999999999, "amount2": 9999999999, "amount3": -9999999999 })JSON" ); ASSERT_TRUE(spec.process(bigInput)); // type check clamps to type's min/max value @@ -293,13 +291,13 @@ TEST_F(RPCBaseTest, OneOfValidator) {"currency", OneOf{"XRP", "USD"}}, }; - auto passingInput = json::parse(R"JSON({ "currency": "XRP" })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "currency": "XRP" })JSON"); ASSERT_TRUE(spec.process(passingInput)); - auto passingInput2 = json::parse(R"JSON({ "currency": "USD" })JSON"); + auto passingInput2 = boost::json::parse(R"JSON({ "currency": "USD" })JSON"); ASSERT_TRUE(spec.process(passingInput2)); - auto failingInput = json::parse(R"JSON({ "currency": "PRX" })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "currency": "PRX" })JSON"); ASSERT_FALSE(spec.process(failingInput)); } @@ -309,10 +307,10 @@ TEST_F(RPCBaseTest, EqualToValidator) {"exact", EqualTo{"CaseSensitive"}}, }; - auto passingInput = json::parse(R"JSON({ "exact": "CaseSensitive" })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "exact": "CaseSensitive" })JSON"); ASSERT_TRUE(spec.process(passingInput)); - auto failingInput = json::parse(R"JSON({ "exact": "Different" })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "exact": "Different" })JSON"); ASSERT_FALSE(spec.process(failingInput)); } @@ -321,7 +319,7 @@ TEST_F(RPCBaseTest, ArrayAtValidator) auto spec = RpcSpec{ {"arr", Required{}, - Type{}, + Type{}, ValidateArrayAt{ 0, { @@ -338,16 +336,17 @@ TEST_F(RPCBaseTest, ArrayAtValidator) }; // clang-format on - auto passingInput = json::parse(R"JSON({ "arr": [{"limit": 42}] })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "arr": [{"limit": 42}] })JSON"); ASSERT_TRUE(spec.process(passingInput)); - auto failingInput = json::parse(R"JSON({ "arr": [{"limit": "not int"}] })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "arr": [{"limit": "not int"}] })JSON"); ASSERT_FALSE(spec.process(failingInput)); - failingInput = json::parse(R"JSON({ "arr": [{"limit": 42}], "arr2": "not array type" })JSON"); + failingInput = + boost::json::parse(R"JSON({ "arr": [{"limit": 42}], "arr2": "not array type" })JSON"); ASSERT_FALSE(spec.process(failingInput)); - failingInput = json::parse(R"JSON({ "arr": [] })JSON"); + failingInput = boost::json::parse(R"JSON({ "arr": [] })JSON"); ASSERT_FALSE(spec.process(failingInput)); } @@ -356,42 +355,43 @@ TEST_F(RPCBaseTest, IfTypeValidator) auto spec = RpcSpec{ {"mix", Required{}, - Type{}, - IfType{ + Type{}, + IfType{ Section{{"limit", Required{}, Type{}, Between{0, 100}}}, Section{{"limit2", Required{}, Type{}, Between{0, 100}}} }, IfType{CustomValidators::uint256HexStringValidator}}, {"mix2", Section{{"limit", Required{}, Type{}, Between{0, 100}}}, - Type{}}, + Type{}}, }; // if json object pass - auto passingInput = json::parse(R"JSON({ "mix": {"limit": 42, "limit2": 22} })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "mix": {"limit": 42, "limit2": 22} })JSON"); ASSERT_TRUE(spec.process(passingInput)); // if string pass - passingInput = json::parse( + passingInput = boost::json::parse( R"JSON({ "mix": "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC" })JSON" ); ASSERT_TRUE(spec.process(passingInput)); // if json object fail at first requirement - auto failingInput = json::parse(R"JSON({ "mix": {"limit": "not int"} })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "mix": {"limit": "not int"} })JSON"); ASSERT_FALSE(spec.process(failingInput)); // if json object fail at second requirement - failingInput = json::parse(R"JSON({ "mix": {"limit": 22, "limit2": "y"} })JSON"); + failingInput = boost::json::parse(R"JSON({ "mix": {"limit": 22, "limit2": "y"} })JSON"); ASSERT_FALSE(spec.process(failingInput)); // if string fail - failingInput = json::parse(R"JSON({ "mix": "not hash" })JSON"); + failingInput = boost::json::parse(R"JSON({ "mix": "not hash" })JSON"); ASSERT_FALSE(spec.process(failingInput)); // type check fail - failingInput = json::parse(R"JSON({ "mix": 1213 })JSON"); + failingInput = boost::json::parse(R"JSON({ "mix": 1213 })JSON"); ASSERT_FALSE(spec.process(failingInput)); - failingInput = json::parse(R"JSON({ "mix": {"limit": 42, "limit2": 22}, "mix2": 1213 })JSON"); + failingInput = + boost::json::parse(R"JSON({ "mix": {"limit": 42, "limit2": 22}, "mix2": 1213 })JSON"); ASSERT_FALSE(spec.process(failingInput)); } @@ -401,32 +401,32 @@ TEST_F(RPCBaseTest, WithCustomError) {"transaction", WithCustomError{ CustomValidators::uint256HexStringValidator, - rpc::Status{ripple::rpcBAD_FEATURE, "MyCustomError"} + rpc::Status{xrpl::RpcBadFeature, "MyCustomError"} }}, {"other", WithCustomError{ - Type{}, rpc::Status{ripple::rpcALREADY_MULTISIG, "MyCustomError2"} + Type{}, rpc::Status{xrpl::RpcAlreadyMultisig, "MyCustomError2"} }} }; - auto passingInput = json::parse( + auto passingInput = boost::json::parse( R"JSON({ "transaction": "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC", "other": "1"})JSON" ); ASSERT_TRUE(spec.process(passingInput)); - auto failingInput = json::parse( + auto failingInput = boost::json::parse( R"JSON({ "transaction": "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515B"})JSON" ); auto err = spec.process(failingInput); ASSERT_FALSE(err); ASSERT_EQ(err.error().message, "MyCustomError"); - ASSERT_EQ(err.error(), ripple::rpcBAD_FEATURE); + ASSERT_EQ(err.error(), xrpl::RpcBadFeature); - failingInput = json::parse(R"JSON({ "other": 1})JSON"); + failingInput = boost::json::parse(R"JSON({ "other": 1})JSON"); err = spec.process(failingInput); ASSERT_FALSE(err); ASSERT_EQ(err.error().message, "MyCustomError2"); - ASSERT_EQ(err.error(), ripple::rpcALREADY_MULTISIG); + ASSERT_EQ(err.error(), xrpl::RpcAlreadyMultisig); } TEST_F(RPCBaseTest, TimeFormatValidator) @@ -435,51 +435,53 @@ TEST_F(RPCBaseTest, TimeFormatValidator) {"date", TimeFormatValidator{"%Y-%m-%dT%H:%M:%SZ"}}, }; - auto passingInput = json::parse(R"JSON({ "date": "2023-01-01T00:00:00Z" })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "date": "2023-01-01T00:00:00Z" })JSON"); EXPECT_TRUE(spec.process(passingInput)); - passingInput = json::parse("123"); + passingInput = boost::json::parse("123"); EXPECT_TRUE(spec.process(passingInput)); // key not exists - passingInput = json::parse(R"JSON({ "date1": "2023-01-01T00:00:00Z" })JSON"); + passingInput = boost::json::parse(R"JSON({ "date1": "2023-01-01T00:00:00Z" })JSON"); EXPECT_TRUE(spec.process(passingInput)); - auto failingInput = json::parse(R"JSON({ "date": "2023-01-01-00:00:00" })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "date": "2023-01-01-00:00:00" })JSON"); auto err = spec.process(failingInput); EXPECT_FALSE(err); - EXPECT_EQ(err.error(), ripple::rpcINVALID_PARAMS); + EXPECT_EQ(err.error(), xrpl::RpcInvalidParams); - failingInput = json::parse(R"JSON({ "date": "01-01-2024T00:00:00" })JSON"); + failingInput = boost::json::parse(R"JSON({ "date": "01-01-2024T00:00:00" })JSON"); EXPECT_FALSE(spec.process(failingInput)); - failingInput = json::parse(R"JSON({ "date": "2024-01-01T29:00:00" })JSON"); + failingInput = boost::json::parse(R"JSON({ "date": "2024-01-01T29:00:00" })JSON"); EXPECT_FALSE(spec.process(failingInput)); - failingInput = json::parse(R"JSON({ "date": "" })JSON"); + failingInput = boost::json::parse(R"JSON({ "date": "" })JSON"); EXPECT_FALSE(spec.process(failingInput)); - failingInput = json::parse(R"JSON({ "date": 1 })JSON"); + failingInput = boost::json::parse(R"JSON({ "date": 1 })JSON"); err = spec.process(failingInput); EXPECT_FALSE(err); - EXPECT_EQ(err.error(), ripple::rpcINVALID_PARAMS); + EXPECT_EQ(err.error(), xrpl::RpcInvalidParams); } TEST_F(RPCBaseTest, CustomValidator) { - auto customFormatCheck = - CustomValidator{[](json::value const& value, std::string_view /* key */) -> MaybeError { + auto customFormatCheck = CustomValidator{ + [](boost::json::value const& value, std::string_view /* key */) -> MaybeError { return value.as_string().size() == 34 ? MaybeError{} : Error{rpc::Status{"Uh oh"}}; - }}; + } + }; auto spec = RpcSpec{ {"taker", customFormatCheck}, }; - auto passingInput = json::parse(R"JSON({ "taker": "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59" })JSON"); + auto passingInput = + boost::json::parse(R"JSON({ "taker": "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59" })JSON"); ASSERT_TRUE(spec.process(passingInput)); - auto failingInput = json::parse(R"JSON({ "taker": "wrongformat" })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "taker": "wrongformat" })JSON"); ASSERT_FALSE(spec.process(failingInput)); } @@ -490,13 +492,13 @@ TEST_F(RPCBaseTest, NotSupported) {"getter", NotSupported{}}, }; - auto passingInput = json::parse(R"JSON({ "taker": 2 })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "taker": 2 })JSON"); ASSERT_TRUE(spec.process(passingInput)); - auto failingInput = json::parse(R"JSON({ "taker": 123 })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "taker": 123 })JSON"); ASSERT_FALSE(spec.process(failingInput)); - failingInput = json::parse(R"JSON({ "taker": 2, "getter": 2 })JSON"); + failingInput = boost::json::parse(R"JSON({ "taker": 2, "getter": 2 })JSON"); ASSERT_FALSE(spec.process(failingInput)); } @@ -505,21 +507,21 @@ TEST_F(RPCBaseTest, LedgerIndexValidator) auto spec = RpcSpec{ {"ledgerIndex", CustomValidators::ledgerIndexValidator}, }; - auto passingInput = json::parse(R"JSON({ "ledgerIndex": "validated" })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "ledgerIndex": "validated" })JSON"); ASSERT_TRUE(spec.process(passingInput)); - passingInput = json::parse(R"JSON({ "ledgerIndex": "256" })JSON"); + passingInput = boost::json::parse(R"JSON({ "ledgerIndex": "256" })JSON"); ASSERT_TRUE(spec.process(passingInput)); - passingInput = json::parse(R"JSON({ "ledgerIndex": 256 })JSON"); + passingInput = boost::json::parse(R"JSON({ "ledgerIndex": 256 })JSON"); ASSERT_TRUE(spec.process(passingInput)); - auto failingInput = json::parse(R"JSON({ "ledgerIndex": "wrongformat" })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "ledgerIndex": "wrongformat" })JSON"); auto err = spec.process(failingInput); ASSERT_FALSE(err); ASSERT_EQ(err.error().message, "ledgerIndexMalformed"); - failingInput = json::parse(R"JSON({ "ledgerIndex": true })JSON"); + failingInput = boost::json::parse(R"JSON({ "ledgerIndex": true })JSON"); err = spec.process(failingInput); ASSERT_FALSE(err); ASSERT_EQ(err.error().message, "ledgerIndexMalformed"); @@ -530,25 +532,27 @@ TEST_F(RPCBaseTest, AccountValidator) auto spec = RpcSpec{ {"account", CustomValidators::accountValidator}, }; - auto failingInput = json::parse(R"JSON({ "account": 256 })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "account": 256 })JSON"); ASSERT_FALSE(spec.process(failingInput)); - failingInput = json::parse(R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jp" })JSON"); + failingInput = + boost::json::parse(R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jp" })JSON"); ASSERT_FALSE(spec.process(failingInput)); - failingInput = json::parse( + failingInput = boost::json::parse( R"JSON({ "account": "02000000000000000000000000000000000000000000000000000000000000000" })JSON" ); ASSERT_FALSE(spec.process(failingInput)); - failingInput = json::parse(R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jp?" })JSON"); + failingInput = + boost::json::parse(R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jp?" })JSON"); ASSERT_FALSE(spec.process(failingInput)); auto passingInput = - json::parse(R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn" })JSON"); + boost::json::parse(R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn" })JSON"); ASSERT_TRUE(spec.process(passingInput)); - passingInput = json::parse( + passingInput = boost::json::parse( R"JSON({ "account": "020000000000000000000000000000000000000000000000000000000000000000" })JSON" ); ASSERT_TRUE(spec.process(passingInput)); @@ -559,22 +563,24 @@ TEST_F(RPCBaseTest, AccountBase58Validator) auto spec = RpcSpec{ {"account", CustomValidators::accountBase58Validator}, }; - auto failingInput = json::parse(R"JSON({ "account": 256 })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "account": 256 })JSON"); ASSERT_FALSE(spec.process(failingInput)); - failingInput = json::parse(R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jp" })JSON"); + failingInput = + boost::json::parse(R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jp" })JSON"); ASSERT_FALSE(spec.process(failingInput)); - failingInput = json::parse( + failingInput = boost::json::parse( R"JSON({ "account": "020000000000000000000000000000000000000000000000000000000000000000" })JSON" ); ASSERT_FALSE(spec.process(failingInput)); - failingInput = json::parse(R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jp?" })JSON"); + failingInput = + boost::json::parse(R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jp?" })JSON"); ASSERT_FALSE(spec.process(failingInput)); auto passingInput = - json::parse(R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn" })JSON"); + boost::json::parse(R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn" })JSON"); ASSERT_TRUE(spec.process(passingInput)); } @@ -583,16 +589,16 @@ TEST_F(RPCBaseTest, AccountMarkerValidator) auto spec = RpcSpec{ {"marker", CustomValidators::accountMarkerValidator}, }; - auto failingInput = json::parse(R"JSON({ "marker": 256 })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "marker": 256 })JSON"); ASSERT_FALSE(spec.process(failingInput)); - failingInput = json::parse(R"JSON({ "marker": "testtest" })JSON"); + failingInput = boost::json::parse(R"JSON({ "marker": "testtest" })JSON"); ASSERT_FALSE(spec.process(failingInput)); - failingInput = json::parse(R"JSON({ "marker": "ABAB1234:1H" })JSON"); + failingInput = boost::json::parse(R"JSON({ "marker": "ABAB1234:1H" })JSON"); ASSERT_FALSE(spec.process(failingInput)); - auto passingInput = json::parse(R"JSON({ "account": "ABAB1234:123" })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "account": "ABAB1234:123" })JSON"); ASSERT_TRUE(spec.process(passingInput)); } @@ -600,16 +606,17 @@ TEST_F(RPCBaseTest, Uint160HexStringValidator) { auto const spec = RpcSpec{{"marker", CustomValidators::uint160HexStringValidator}}; auto passingInput = - json::parse(R"JSON({ "marker": "F609A18102218C75767209946A77523CBD97E225"})JSON"); + boost::json::parse(R"JSON({ "marker": "F609A18102218C75767209946A77523CBD97E225"})JSON"); ASSERT_TRUE(spec.process(passingInput)); - auto failingInput = json::parse(R"JSON({ "marker": 160})JSON"); + auto failingInput = boost::json::parse(R"JSON({ "marker": 160})JSON"); auto err = spec.process(failingInput); ASSERT_FALSE(err); ASSERT_EQ(err.error().message, "markerNotString"); - failingInput = - json::parse(R"JSON({ "marker": "F609A18102218C75767209946A77523CBD97E2253515BC"})JSON"); + failingInput = boost::json::parse( + R"JSON({ "marker": "F609A18102218C75767209946A77523CBD97E2253515BC"})JSON" + ); err = spec.process(failingInput); ASSERT_FALSE(err); ASSERT_EQ(err.error().message, "markerMalformed"); @@ -618,17 +625,17 @@ TEST_F(RPCBaseTest, Uint160HexStringValidator) TEST_F(RPCBaseTest, Uint192HexStringValidator) { auto const spec = RpcSpec{{"mpt_issuance_id", CustomValidators::uint192HexStringValidator}}; - auto passingInput = json::parse( + auto passingInput = boost::json::parse( R"JSON({ "mpt_issuance_id": "0000012F27A9DE73EAA1E8831FA253E19030A17E2D038198"})JSON" ); ASSERT_TRUE(spec.process(passingInput)); - auto failingInput = json::parse(R"JSON({ "mpt_issuance_id": 192})JSON"); + auto failingInput = boost::json::parse(R"JSON({ "mpt_issuance_id": 192})JSON"); auto err = spec.process(failingInput); ASSERT_FALSE(err); ASSERT_EQ(err.error().message, "mpt_issuance_idNotString"); - failingInput = json::parse( + failingInput = boost::json::parse( R"JSON({ "mpt_issuance_id": "0000012F27A9DE73EAA1E8831FA253E19030A17E2D038198983515BC"})JSON" ); err = spec.process(failingInput); @@ -639,17 +646,17 @@ TEST_F(RPCBaseTest, Uint192HexStringValidator) TEST_F(RPCBaseTest, Uint256HexStringValidator) { auto const spec = RpcSpec{{"transaction", CustomValidators::uint256HexStringValidator}}; - auto passingInput = json::parse( + auto passingInput = boost::json::parse( R"JSON({ "transaction": "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"})JSON" ); ASSERT_TRUE(spec.process(passingInput)); - auto failingInput = json::parse(R"JSON({ "transaction": 256})JSON"); + auto failingInput = boost::json::parse(R"JSON({ "transaction": 256})JSON"); auto err = spec.process(failingInput); ASSERT_FALSE(err); ASSERT_EQ(err.error().message, "transactionNotString"); - failingInput = json::parse( + failingInput = boost::json::parse( R"JSON({ "transaction": "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC"})JSON" ); err = spec.process(failingInput); @@ -660,28 +667,29 @@ TEST_F(RPCBaseTest, Uint256HexStringValidator) TEST_F(RPCBaseTest, CurrencyValidator) { auto const spec = RpcSpec{{"currency", CustomValidators::currencyValidator}}; - auto passingInput = json::parse(R"JSON({ "currency": "GBP"})JSON"); + auto passingInput = boost::json::parse(R"JSON({ "currency": "GBP"})JSON"); ASSERT_TRUE(spec.process(passingInput)); passingInput = - json::parse(R"JSON({ "currency": "0158415500000000C1F76FF6ECB0BAC600000000"})JSON"); + boost::json::parse(R"JSON({ "currency": "0158415500000000C1F76FF6ECB0BAC600000000"})JSON"); ASSERT_TRUE(spec.process(passingInput)); passingInput = - json::parse(R"JSON({ "currency": "0158415500000000c1f76ff6ecb0bac600000000"})JSON"); + boost::json::parse(R"JSON({ "currency": "0158415500000000c1f76ff6ecb0bac600000000"})JSON"); ASSERT_TRUE(spec.process(passingInput)); for (auto const& currency : {"[]<", ">()", "{}|", "?!@", "#$%", "^&*"}) { - passingInput = json::parse(fmt::format(R"JSON({{ "currency": "{}" }})JSON", currency)); + passingInput = + boost::json::parse(fmt::format(R"JSON({{ "currency": "{}" }})JSON", currency)); ASSERT_TRUE(spec.process(passingInput)); } - auto failingInput = json::parse(R"JSON({ "currency": 256})JSON"); + auto failingInput = boost::json::parse(R"JSON({ "currency": 256})JSON"); auto err = spec.process(failingInput); ASSERT_FALSE(err); ASSERT_EQ(err.error().message, "currencyNotString"); - failingInput = json::parse(R"JSON({ "currency": "12314"})JSON"); + failingInput = boost::json::parse(R"JSON({ "currency": "12314"})JSON"); err = spec.process(failingInput); ASSERT_FALSE(err); ASSERT_EQ(err.error().message, "malformedCurrency"); @@ -690,16 +698,18 @@ TEST_F(RPCBaseTest, CurrencyValidator) TEST_F(RPCBaseTest, IssuerValidator) { auto const spec = RpcSpec{{"issuer", CustomValidators::issuerValidator}}; - auto passingInput = json::parse(R"JSON({ "issuer": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"})JSON"); + auto passingInput = + boost::json::parse(R"JSON({ "issuer": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"})JSON"); ASSERT_TRUE(spec.process(passingInput)); - auto failingInput = json::parse(R"JSON({ "issuer": 256})JSON"); + auto failingInput = boost::json::parse(R"JSON({ "issuer": 256})JSON"); auto err = spec.process(failingInput); ASSERT_FALSE(err); ASSERT_EQ(err.error().message, "issuerNotString"); - failingInput = - json::parse(fmt::format(R"JSON({{ "issuer": "{}"}})JSON", toBase58(ripple::noAccount()))); + failingInput = boost::json::parse( + fmt::format(R"JSON({{ "issuer": "{}"}})JSON", toBase58(xrpl::noAccount())) + ); err = spec.process(failingInput); ASSERT_FALSE(err); } @@ -707,7 +717,7 @@ TEST_F(RPCBaseTest, IssuerValidator) TEST_F(RPCBaseTest, SubscribeStreamValidator) { auto const spec = RpcSpec{{"streams", CustomValidators::subscribeStreamValidator}}; - auto passingInput = json::parse( + auto passingInput = boost::json::parse( R"JSON({ "streams": [ "ledger", @@ -722,15 +732,15 @@ TEST_F(RPCBaseTest, SubscribeStreamValidator) ); ASSERT_TRUE(spec.process(passingInput)); - auto failingInput = json::parse(R"JSON({ "streams": 256})JSON"); + auto failingInput = boost::json::parse(R"JSON({ "streams": 256})JSON"); auto err = spec.process(failingInput); ASSERT_FALSE(err); - failingInput = json::parse(R"JSON({ "streams": ["test"]})JSON"); + failingInput = boost::json::parse(R"JSON({ "streams": ["test"]})JSON"); err = spec.process(failingInput); ASSERT_FALSE(err); - failingInput = json::parse(R"JSON({ "streams": [123]})JSON"); + failingInput = boost::json::parse(R"JSON({ "streams": [123]})JSON"); err = spec.process(failingInput); ASSERT_FALSE(err); } @@ -738,20 +748,20 @@ TEST_F(RPCBaseTest, SubscribeStreamValidator) TEST_F(RPCBaseTest, SubscribeAccountsValidator) { auto const spec = RpcSpec{{"accounts", CustomValidators::subscribeAccountsValidator}}; - auto passingInput = json::parse( + auto passingInput = boost::json::parse( R"JSON({ "accounts": ["rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"]})JSON" ); ASSERT_TRUE(spec.process(passingInput)); - auto failingInput = json::parse(R"JSON({ "accounts": 256})JSON"); + auto failingInput = boost::json::parse(R"JSON({ "accounts": 256})JSON"); auto err = spec.process(failingInput); ASSERT_FALSE(err); - failingInput = json::parse(R"JSON({ "accounts": ["test"]})JSON"); + failingInput = boost::json::parse(R"JSON({ "accounts": ["test"]})JSON"); err = spec.process(failingInput); ASSERT_FALSE(err); - failingInput = json::parse(R"JSON({ "accounts": [123]})JSON"); + failingInput = boost::json::parse(R"JSON({ "accounts": [123]})JSON"); err = spec.process(failingInput); ASSERT_FALSE(err); } @@ -762,14 +772,14 @@ TEST_F(RPCBaseTest, ClampingModifier) {"amount", Clamp{10u, 20u}}, }; - auto passingInput = json::parse(R"JSON({ "amount": 15 })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "amount": 15 })JSON"); ASSERT_TRUE(spec.process(passingInput)); - auto passingInput2 = json::parse(R"JSON({ "amount": 5 })JSON"); + auto passingInput2 = boost::json::parse(R"JSON({ "amount": 5 })JSON"); ASSERT_TRUE(spec.process(passingInput2)); ASSERT_EQ(passingInput2.at("amount").as_uint64(), 10u); // clamped - auto passingInput3 = json::parse(R"JSON({ "amount": 25 })JSON"); + auto passingInput3 = boost::json::parse(R"JSON({ "amount": 25 })JSON"); ASSERT_TRUE(spec.process(passingInput3)); ASSERT_EQ(passingInput3.at("amount").as_uint64(), 20u); // clamped } @@ -780,18 +790,18 @@ TEST_F(RPCBaseTest, ToLowerModifier) {"str", ToLower{}}, }; - auto passingInput = json::parse(R"JSON({ "str": "TesT" })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "str": "TesT" })JSON"); ASSERT_TRUE(spec.process(passingInput)); ASSERT_EQ(passingInput.at("str").as_string(), "test"); - auto passingInput2 = json::parse(R"JSON({ "str2": "TesT" })JSON"); + auto passingInput2 = boost::json::parse(R"JSON({ "str2": "TesT" })JSON"); ASSERT_TRUE(spec.process(passingInput2)); // no str no problem - auto passingInput3 = json::parse(R"JSON({ "str": "already lower case" })JSON"); + auto passingInput3 = boost::json::parse(R"JSON({ "str": "already lower case" })JSON"); ASSERT_TRUE(spec.process(passingInput3)); ASSERT_EQ(passingInput3.at("str").as_string(), "already lower case"); - auto passingInput4 = json::parse(R"JSON({ "str": "" })JSON"); + auto passingInput4 = boost::json::parse(R"JSON({ "str": "" })JSON"); ASSERT_TRUE(spec.process(passingInput4)); // empty str no problem ASSERT_EQ(passingInput4.at("str").as_string(), ""); } @@ -802,29 +812,30 @@ TEST_F(RPCBaseTest, ToNumberModifier) {"str", ToNumber{}}, }; - auto passingInput = json::parse(R"JSON({ "str": [] })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "str": [] })JSON"); ASSERT_TRUE(spec.process(passingInput)); - passingInput = json::parse(R"JSON({ "str2": "TesT" })JSON"); + passingInput = boost::json::parse(R"JSON({ "str2": "TesT" })JSON"); ASSERT_TRUE(spec.process(passingInput)); - passingInput = json::parse(R"JSON([])JSON"); + passingInput = boost::json::parse(R"JSON([])JSON"); ASSERT_TRUE(spec.process(passingInput)); - passingInput = json::parse(R"JSON({ "str": "123" })JSON"); + passingInput = boost::json::parse(R"JSON({ "str": "123" })JSON"); ASSERT_TRUE(spec.process(passingInput)); ASSERT_EQ(passingInput.at("str").as_int64(), 123); - auto failingInput = json::parse(R"JSON({ "str": "ok" })JSON"); + auto failingInput = boost::json::parse(R"JSON({ "str": "ok" })JSON"); ASSERT_FALSE(spec.process(failingInput)); - failingInput = json::parse(R"JSON({ "str": "123.123" })JSON"); + failingInput = boost::json::parse(R"JSON({ "str": "123.123" })JSON"); ASSERT_FALSE(spec.process(failingInput)); } TEST_F(RPCBaseTest, CustomModifier) { - testing::StrictMock> + testing::StrictMock< + testing::MockFunction> mockModifier; auto const customModifier = CustomModifier{mockModifier.AsStdFunction()}; auto const spec = RpcSpec{ @@ -832,13 +843,13 @@ TEST_F(RPCBaseTest, CustomModifier) }; EXPECT_CALL(mockModifier, Call).WillOnce(testing::Return(MaybeError{})); - auto passingInput = json::parse(R"JSON({ "str": "sss" })JSON"); + auto passingInput = boost::json::parse(R"JSON({ "str": "sss" })JSON"); ASSERT_TRUE(spec.process(passingInput)); - passingInput = json::parse(R"JSON({ "strNotExist": 123 })JSON"); + passingInput = boost::json::parse(R"JSON({ "strNotExist": 123 })JSON"); ASSERT_TRUE(spec.process(passingInput)); // not a json object - passingInput = json::parse(R"JSON([])JSON"); + passingInput = boost::json::parse(R"JSON([])JSON"); ASSERT_TRUE(spec.process(passingInput)); } diff --git a/tests/unit/rpc/ErrorTests.cpp b/tests/unit/rpc/ErrorTests.cpp index 1e1ee2d0d..2f7866254 100644 --- a/tests/unit/rpc/ErrorTests.cpp +++ b/tests/unit/rpc/ErrorTests.cpp @@ -48,18 +48,18 @@ check( TEST(RPCErrorsTest, StatusAsBool) { - // Only rpcSUCCESS status should return false - EXPECT_FALSE(Status{RippledError::rpcSUCCESS}); + // Only RpcSuccess status should return false + EXPECT_FALSE(Status{RippledError::RpcSuccess}); // true should be returned for any error state, we just test a few CombinedError const errors[]{ - RippledError::rpcINVALID_PARAMS, - RippledError::rpcUNKNOWN_COMMAND, - RippledError::rpcTOO_BUSY, - RippledError::rpcNO_NETWORK, - RippledError::rpcWRONG_NETWORK, - RippledError::rpcACT_MALFORMED, - RippledError::rpcBAD_MARKET, + RippledError::RpcInvalidParams, + RippledError::RpcUnknownCommand, + RippledError::RpcTooBusy, + RippledError::RpcNoNetwork, + RippledError::RpcWrongNetwork, + RippledError::RpcActMalformed, + RippledError::RpcBadMarket, ClioError::RpcMalformedCurrency, }; @@ -69,21 +69,21 @@ TEST(RPCErrorsTest, StatusAsBool) TEST(RPCErrorsTest, StatusEquals) { - EXPECT_EQ(Status{RippledError::rpcUNKNOWN}, Status{RippledError::rpcUNKNOWN}); - EXPECT_NE(Status{RippledError::rpcUNKNOWN}, Status{RippledError::rpcINTERNAL}); + EXPECT_EQ(Status{RippledError::RpcUnknown}, Status{RippledError::RpcUnknown}); + EXPECT_NE(Status{RippledError::RpcUnknown}, Status{RippledError::RpcInternal}); } TEST(RPCErrorsTest, SuccessToJSON) { - auto const status = Status{RippledError::rpcSUCCESS}; - check(makeError(status), "unknown", RippledError::rpcSUCCESS, "An unknown error code."); + auto const status = Status{RippledError::RpcSuccess}; + check(makeError(status), "unknown", RippledError::RpcSuccess, "An unknown error code."); } TEST(RPCErrorsTest, RippledErrorToJSON) { - auto const status = Status{RippledError::rpcINVALID_PARAMS}; + auto const status = Status{RippledError::RpcInvalidParams}; check( - makeError(status), "invalidParams", RippledError::rpcINVALID_PARAMS, "Invalid parameters." + makeError(status), "invalidParams", RippledError::RpcInvalidParams, "Invalid parameters." ); } @@ -95,14 +95,14 @@ TEST(RPCErrorsTest, RippledErrorFromStringToJSON) TEST(RPCErrorsTest, RippledErrorToJSONCustomMessage) { - auto const status = Status{RippledError::rpcINVALID_PARAMS, "custom"}; - check(makeError(status), "invalidParams", RippledError::rpcINVALID_PARAMS, "custom"); + auto const status = Status{RippledError::RpcInvalidParams, "custom"}; + check(makeError(status), "invalidParams", RippledError::RpcInvalidParams, "custom"); } TEST(RPCErrorsTest, RippledErrorToJSONCustomStrCodeAndMessage) { - auto const status = Status{RippledError::rpcINVALID_PARAMS, "customCode", "customMessage"}; - check(makeError(status), "customCode", RippledError::rpcINVALID_PARAMS, "customMessage"); + auto const status = Status{RippledError::RpcInvalidParams, "customCode", "customMessage"}; + check(makeError(status), "customCode", RippledError::RpcInvalidParams, "customMessage"); } TEST(RPCErrorsTest, ClioErrorToJSON) @@ -170,7 +170,7 @@ INSTANTIATE_TEST_SUITE_P( "https://xrpl.org/docs/references/http-websocket-apis/ and update your request." } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(WarningCodeTest, WarningToJSON) @@ -223,7 +223,7 @@ INSTANTIATE_TEST_SUITE_P( }, StatusStreamTestBundle{ .testName = "StatusWithRippledError", - .status = Status{RippledError::rpcSUCCESS}, + .status = Status{RippledError::RpcSuccess}, .expectedOutput = "Code: 0, Message: An unknown error code." }, StatusStreamTestBundle{ @@ -244,7 +244,7 @@ INSTANTIATE_TEST_SUITE_P( }, StatusStreamTestBundle{ .testName = "StatusWithRippledErrorAndMessage", - .status = Status{RippledError::rpcSUCCESS, "test message."}, + .status = Status{RippledError::RpcSuccess, "test message."}, .expectedOutput = "Code: 0, Message: test message." }, StatusStreamTestBundle{ @@ -264,5 +264,5 @@ INSTANTIATE_TEST_SUITE_P( "Code: 7003, Error: invalidResponse, Message: Rippled returned an invalid response." } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); diff --git a/tests/unit/rpc/ForwardingProxyTests.cpp b/tests/unit/rpc/ForwardingProxyTests.cpp index 7fa73e96a..396bfb5eb 100644 --- a/tests/unit/rpc/ForwardingProxyTests.cpp +++ b/tests/unit/rpc/ForwardingProxyTests.cpp @@ -26,10 +26,9 @@ using namespace rpc; using namespace testing; using namespace util::config; -namespace json = boost::json; namespace { -constexpr auto kCLIENT_IP = "127.0.0.1"; +constexpr auto kClientIp = "127.0.0.1"; } // namespace class RPCForwardingProxyTest : public HandlerBaseTest { @@ -255,7 +254,7 @@ INSTANTIATE_TEST_CASE_P( ShouldForwardTest, ShouldForwardParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(ShouldForwardParameterTest, Test) @@ -264,7 +263,7 @@ TEST_P(ShouldForwardParameterTest, Test) auto const rawHandlerProviderPtr = handlerProvider_.get(); auto const apiVersion = testBundle.apiVersion; auto const method = testBundle.method; - auto const params = json::parse(testBundle.testJson); + auto const params = boost::json::parse(testBundle.testJson); ON_CALL(*rawHandlerProviderPtr, isClioOnly(_)) .WillByDefault(Return(testBundle.mockedIsClioOnly)); @@ -279,7 +278,7 @@ TEST_P(ShouldForwardParameterTest, Test) nullptr, tagFactory_, data::LedgerRange{}, - kCLIENT_IP, + kClientIp, testBundle.isAdmin, }; @@ -294,16 +293,14 @@ TEST_F(RPCForwardingProxyTest, ForwardCallsBalancerWithCorrectParams) auto const rawBalancerPtr = loadBalancer_.get(); auto const apiVersion = 2u; auto const method = "submit"; - auto const params = json::parse(R"JSON({"test": true})JSON"); - auto const forwarded = json::parse(R"JSON({"test": true, "command": "submit"})JSON"); + auto const params = boost::json::parse(R"JSON({"test": true})JSON"); + auto const forwarded = boost::json::parse(R"JSON({"test": true, "command": "submit"})JSON"); EXPECT_CALL( *rawBalancerPtr, - forwardToRippled( - forwarded.as_object(), std::make_optional(kCLIENT_IP), true, _ - ) + forwardToRippled(forwarded.as_object(), std::make_optional(kClientIp), true, _) ) - .WillOnce(Return(json::object{})); + .WillOnce(Return(boost::json::object{})); EXPECT_CALL(*rawHandlerProviderPtr, contains(method)).WillOnce(Return(true)); @@ -318,7 +315,7 @@ TEST_F(RPCForwardingProxyTest, ForwardCallsBalancerWithCorrectParams) nullptr, tagFactory_, data::LedgerRange{}, - kCLIENT_IP, + kClientIp, true, }; @@ -334,14 +331,12 @@ TEST_F(RPCForwardingProxyTest, ForwardingFailYieldsErrorStatus) auto const rawBalancerPtr = loadBalancer_.get(); auto const apiVersion = 2u; auto const method = "submit"; - auto const params = json::parse(R"JSON({"test": true})JSON"); - auto const forwarded = json::parse(R"JSON({"test": true, "command": "submit"})JSON"); + auto const params = boost::json::parse(R"JSON({"test": true})JSON"); + auto const forwarded = boost::json::parse(R"JSON({"test": true, "command": "submit"})JSON"); EXPECT_CALL( *rawBalancerPtr, - forwardToRippled( - forwarded.as_object(), std::make_optional(kCLIENT_IP), true, _ - ) + forwardToRippled(forwarded.as_object(), std::make_optional(kClientIp), true, _) ) .WillOnce(Return(std::unexpected{rpc::ClioError::EtlInvalidResponse})); @@ -358,7 +353,7 @@ TEST_F(RPCForwardingProxyTest, ForwardingFailYieldsErrorStatus) nullptr, tagFactory_, data::LedgerRange{}, - kCLIENT_IP, + kClientIp, true, }; diff --git a/tests/unit/rpc/JsonBoolTests.cpp b/tests/unit/rpc/JsonBoolTests.cpp index 21b932fec..95a546cb3 100644 --- a/tests/unit/rpc/JsonBoolTests.cpp +++ b/tests/unit/rpc/JsonBoolTests.cpp @@ -9,7 +9,6 @@ #include using namespace rpc; -namespace json = boost::json; using namespace testing; struct JsonBoolTestsCaseBundle { @@ -71,13 +70,13 @@ INSTANTIATE_TEST_CASE_P( JsonBoolCheckGroup, JsonBoolTests, ValuesIn(JsonBoolTests::generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(JsonBoolTests, Parse) { auto const testBundle = GetParam(); - auto const jv = json::parse(testBundle.json).as_object(); + auto const jv = boost::json::parse(testBundle.json).as_object(); ASSERT_TRUE(jv.contains("test_bool")); EXPECT_EQ(testBundle.expectedBool, value_to(jv.at("test_bool")).value); } diff --git a/tests/unit/rpc/RPCEngineTests.cpp b/tests/unit/rpc/RPCEngineTests.cpp index 538226294..57ffaa0d8 100644 --- a/tests/unit/rpc/RPCEngineTests.cpp +++ b/tests/unit/rpc/RPCEngineTests.cpp @@ -39,12 +39,11 @@ using namespace data; using namespace rpc; using namespace util; -namespace json = boost::json; using namespace testing; using namespace util::config; namespace { -constexpr auto kFORWARD_REPLY = R"JSON({ +constexpr auto kForwardReply = R"JSON({ "result": { "status": "success", "forwarded": true @@ -120,7 +119,7 @@ generateTestValuesForParametersTest() .isUnknownCmd = neverCalled, .handlerReturnError = false, .status = rpc::Status{}, - .response = boost::json::parse(kFORWARD_REPLY).as_object()}, + .response = boost::json::parse(kForwardReply).as_object()}, {.testName = "ForwardAdminCmd", .isAdmin = false, .method = "ledger", @@ -129,7 +128,7 @@ generateTestValuesForParametersTest() .isTooBusy = neverCalled, .isUnknownCmd = neverCalled, .handlerReturnError = false, - .status = rpc::Status{RippledError::rpcNO_PERMISSION}, + .status = rpc::Status{RippledError::RpcNoPermission}, .response = std::nullopt}, {.testName = "BackendTooBusy", .isAdmin = false, @@ -139,7 +138,7 @@ generateTestValuesForParametersTest() .isTooBusy = true, .isUnknownCmd = neverCalled, .handlerReturnError = false, - .status = rpc::Status{RippledError::rpcTOO_BUSY}, + .status = rpc::Status{RippledError::RpcTooBusy}, .response = std::nullopt}, {.testName = "HandlerUnknown", .isAdmin = false, @@ -149,7 +148,7 @@ generateTestValuesForParametersTest() .isTooBusy = false, .isUnknownCmd = true, .handlerReturnError = false, - .status = rpc::Status{RippledError::rpcUNKNOWN_COMMAND}, + .status = rpc::Status{RippledError::RpcUnknownCommand}, .response = std::nullopt}, {.testName = "HandlerReturnError", .isAdmin = false, @@ -178,7 +177,7 @@ INSTANTIATE_TEST_CASE_P( RPCEngineFlow, RPCEngineFlowParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(RPCEngineFlowParameterTest, Test) @@ -199,7 +198,7 @@ TEST_P(RPCEngineFlowParameterTest, Test) EXPECT_CALL(*mockLoadBalancerPtr_, forwardToRippled) .WillOnce(Return( std::expected( - json::parse(kFORWARD_REPLY).as_object() + boost::json::parse(kForwardReply).as_object() ) )); EXPECT_CALL(*handlerProvider, contains).WillOnce(Return(true)); @@ -282,7 +281,7 @@ TEST_F(RPCEngineTest, ThrowDatabaseError) auto const res = engine->buildResponse(ctx); ASSERT_FALSE(res.response.has_value()); - EXPECT_EQ(res.response.error(), Status{RippledError::rpcTOO_BUSY}); + EXPECT_EQ(res.response.error(), Status{RippledError::RpcTooBusy}); }); } @@ -314,7 +313,7 @@ TEST_F(RPCEngineTest, ThrowException) auto const res = engine->buildResponse(ctx); ASSERT_FALSE(res.response.has_value()); - EXPECT_EQ(res.response.error(), Status{RippledError::rpcINTERNAL}); + EXPECT_EQ(res.response.error(), Status{RippledError::RpcInternal}); }); } @@ -394,13 +393,13 @@ INSTANTIATE_TEST_CASE_P( RPCEngineCache, RPCEngineCacheParameterTest, ValuesIn(generateCacheTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(RPCEngineCacheParameterTest, Test) { auto const& testParam = GetParam(); - auto const json = ConfigFileJson{json::parse(testParam.config).as_object()}; + auto const json = ConfigFileJson{boost::json::parse(testParam.config).as_object()}; auto cfgCache{generateDefaultRPCEngineConfig()}; auto const errors = cfgCache.parse(json); @@ -418,17 +417,19 @@ TEST_P(RPCEngineCacheParameterTest, Test) handlerProvider ); int callTime = 2; + auto const bareParams = boost::json::object{}; EXPECT_CALL(*handlerProvider, isClioOnly).Times(callTime).WillRepeatedly(Return(false)); if (testParam.expectedCacheEnabled) { + // Cache hit on second call: handler only invoked once. EXPECT_CALL(*backend_, isTooBusy).WillOnce(Return(false)); EXPECT_CALL(*handlerProvider, getHandler) - .WillOnce(Return(AnyHandler{tests::common::HandlerFake{}})); + .WillOnce(Return(AnyHandler{tests::common::NoInputHandlerFake{}})); } else { EXPECT_CALL(*backend_, isTooBusy).Times(callTime).WillRepeatedly(Return(false)); EXPECT_CALL(*handlerProvider, getHandler) .Times(callTime) - .WillRepeatedly(Return(AnyHandler{tests::common::HandlerFake{}})); + .WillRepeatedly(Return(AnyHandler{tests::common::NoInputHandlerFake{}})); } while (callTime-- != 0) { @@ -437,7 +438,7 @@ TEST_P(RPCEngineCacheParameterTest, Test) yield, method, 1, - boost::json::parse(R"JSON({"hello": "world", "limit": 50})JSON").as_object(), + bareParams, nullptr, tagFactory, LedgerRange{.minSequence = 0, .maxSequence = 30}, @@ -449,7 +450,63 @@ TEST_P(RPCEngineCacheParameterTest, Test) ASSERT_TRUE(res.response.has_value()); EXPECT_EQ( res.response.value(), - boost::json::parse(R"JSON({ "computed": "world_50"})JSON").as_object() + boost::json::parse(R"JSON({"computed": "test"})JSON").as_object() + ); + }); + } +} + +TEST_F(RPCEngineTest, NonBareRequestBypassesCache) +{ + auto const cfgCache = ClioConfigDefinition{ + {"server.max_queue_size", ConfigValue{ConfigType::Integer}.defaultValue(2)}, + {"workers", + ConfigValue{ConfigType::Integer}.defaultValue(4).withConstraint(gValidateUint16)}, + {"rpc.cache_timeout", + ConfigValue{ConfigType::Double}.defaultValue(10.0).withConstraint(gValidatePositiveDouble)} + }; + + auto const notAdmin = false; + auto const method = "server_info"; + std::shared_ptr> engine = RPCEngine::makeRPCEngine( + cfgCache, + backend_, + mockLoadBalancerPtr_, + dosGuard, + queue, + *mockCountersPtr_, + handlerProvider + ); + + auto const nonBareParams = + boost::json::parse(R"JSON({"hello": "world", "limit": 50})JSON").as_object(); + + int callTime = 2; + EXPECT_CALL(*handlerProvider, isClioOnly).Times(callTime).WillRepeatedly(Return(false)); + EXPECT_CALL(*backend_, isTooBusy).Times(callTime).WillRepeatedly(Return(false)); + EXPECT_CALL(*handlerProvider, getHandler) + .Times(callTime) + .WillRepeatedly(Return(AnyHandler{tests::common::HandlerFake{}})); + + while (callTime-- != 0) { + runSpawn([&](auto yield) { + auto const ctx = web::Context( + yield, + method, + 1, + nonBareParams, + nullptr, + tagFactory, + LedgerRange{.minSequence = 0, .maxSequence = 30}, + "127.0.0.2", + notAdmin + ); + + auto const res = engine->buildResponse(ctx); + ASSERT_TRUE(res.response.has_value()); + EXPECT_EQ( + res.response.value(), + boost::json::parse(R"JSON({"computed": "world_50"})JSON").as_object() ); }); } diff --git a/tests/unit/rpc/RPCHelpersTests.cpp b/tests/unit/rpc/RPCHelpersTests.cpp index 3b2fa2010..779eb3219 100644 --- a/tests/unit/rpc/RPCHelpersTests.cpp +++ b/tests/unit/rpc/RPCHelpersTests.cpp @@ -53,17 +53,17 @@ using namespace testing; namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kINDEX1 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kINDEX2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; -constexpr auto kTXN_ID = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kLEDGER_SEQ_OBJECT = 50; -constexpr auto kCURRENCY = "0158415500000000C1F76FF6ECB0BAC600000000"; -constexpr auto kAMM_ACCOUNT = "rnW8FAPgpQgA6VoESnVrUVJHBdq9QAtRZs"; -constexpr auto kISSUER = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; -constexpr auto kLPTOKEN_CURRENCY = "037C35306B24AAB7FF90848206E003279AA47090"; -constexpr auto kAMM_ID = 54321; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kIndex1 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kIndex2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; +constexpr auto kTxnId = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kLedgerSeqObject = 50; +constexpr auto kCurrency = "0158415500000000C1F76FF6ECB0BAC600000000"; +constexpr auto kAmmAccount = "rnW8FAPgpQgA6VoESnVrUVJHBdq9QAtRZs"; +constexpr auto kIssuer = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; +constexpr auto kLptokenCurrency = "037C35306B24AAB7FF90848206E003279AA47090"; +constexpr auto kAmmId = 54321; } // namespace @@ -83,12 +83,12 @@ protected: TEST_F(RPCHelpersTest, TraverseOwnedNodesMarkerInvalidIndexNotHex) { util::spawn(ctx_, [this](boost::asio::yield_context yield) { - auto account = getAccountIdWithString(kACCOUNT); + auto account = getAccountIdWithString(kAccount); auto ret = traverseOwnedNodes(*backend_, account, 9, 10, "nothex,10", yield, [](auto) { }); EXPECT_FALSE(ret.has_value()); - EXPECT_EQ(ret.error(), ripple::rpcINVALID_PARAMS); + EXPECT_EQ(ret.error(), xrpl::RpcInvalidParams); EXPECT_EQ(ret.error().message, "Malformed cursor."); }); ctx_.run(); @@ -97,12 +97,12 @@ TEST_F(RPCHelpersTest, TraverseOwnedNodesMarkerInvalidIndexNotHex) TEST_F(RPCHelpersTest, TraverseOwnedNodesMarkerInvalidPageNotInt) { util::spawn(ctx_, [this](boost::asio::yield_context yield) { - auto account = getAccountIdWithString(kACCOUNT); + auto account = getAccountIdWithString(kAccount); auto ret = traverseOwnedNodes(*backend_, account, 9, 10, "nothex,abc", yield, [](auto) { }); EXPECT_FALSE(ret.has_value()); - EXPECT_EQ(ret.error(), ripple::rpcINVALID_PARAMS); + EXPECT_EQ(ret.error(), xrpl::RpcInvalidParams); EXPECT_EQ(ret.error().message, "Malformed cursor."); }); ctx_.run(); @@ -111,20 +111,20 @@ TEST_F(RPCHelpersTest, TraverseOwnedNodesMarkerInvalidPageNotInt) // limit = 10, return 2 objects TEST_F(RPCHelpersTest, TraverseOwnedNodesNoInputMarker) { - auto account = getAccountIdWithString(kACCOUNT); - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto owneDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); // return owner index - ripple::STObject const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); + xrpl::STObject const ownerDir = + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); // return two payment channel objects std::vector bbs; - ripple::STObject const channel1 = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); + xrpl::STObject const channel1 = + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); bbs.push_back(channel1.getSerializer().peekData()); bbs.push_back(channel1.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); @@ -145,25 +145,25 @@ TEST_F(RPCHelpersTest, TraverseOwnedNodesNoInputMarker) // limit = 10, return 10 objects and marker TEST_F(RPCHelpersTest, TraverseOwnedNodesNoInputMarkerReturnSamePageMarker) { - auto account = getAccountIdWithString(kACCOUNT); - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto owneDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); std::vector bbs; int objectsCount = 11; - ripple::STObject const channel1 = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); - std::vector indexes; + xrpl::STObject const channel1 = + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); + std::vector indexes; while (objectsCount != 0) { // return owner index - indexes.emplace_back(kINDEX1); + indexes.emplace_back(kIndex1); bbs.push_back(channel1.getSerializer().peekData()); objectsCount--; } - ripple::STObject ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); - ownerDir.setFieldU64(ripple::sfIndexNext, 99); + xrpl::STObject ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); + ownerDir.setFieldU64(xrpl::sfIndexNext, 99); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -175,7 +175,7 @@ TEST_F(RPCHelpersTest, TraverseOwnedNodesNoInputMarkerReturnSamePageMarker) auto ret = traverseOwnedNodes(*backend_, account, 9, 10, {}, yield, [&](auto) { count++; }); EXPECT_TRUE(ret.has_value()); EXPECT_EQ(count, 10); - EXPECT_EQ(ret.value().toString(), fmt::format("{},0", kINDEX1)); + EXPECT_EQ(ret.value().toString(), fmt::format("{},0", kIndex1)); }); ctx_.run(); } @@ -183,23 +183,23 @@ TEST_F(RPCHelpersTest, TraverseOwnedNodesNoInputMarkerReturnSamePageMarker) // 10 objects per page, limit is 15, return the second page as marker TEST_F(RPCHelpersTest, TraverseOwnedNodesNoInputMarkerReturnOtherPageMarker) { - auto account = getAccountIdWithString(kACCOUNT); - auto ownerDirKk = ripple::keylet::ownerDir(account).key; - static constexpr auto kNEXT_PAGE = 99; - static constexpr auto kLIMIT = 15; - auto ownerDir2Kk = ripple::keylet::page(ripple::keylet::ownerDir(account), kNEXT_PAGE).key; + auto account = getAccountIdWithString(kAccount); + auto ownerDirKk = xrpl::keylet::ownerDir(account).key; + static constexpr auto kNextPage = 99; + static constexpr auto kLimit = 15; + auto ownerDir2Kk = xrpl::keylet::page(xrpl::keylet::ownerDir(account), kNextPage).key; EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); std::vector bbs; int objectsCount = 10; - ripple::STObject const channel1 = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); - std::vector indexes; + xrpl::STObject const channel1 = + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); + std::vector indexes; while (objectsCount != 0) { // return owner index - indexes.emplace_back(kINDEX1); + indexes.emplace_back(kIndex1); objectsCount--; } objectsCount = 15; @@ -208,14 +208,14 @@ TEST_F(RPCHelpersTest, TraverseOwnedNodesNoInputMarkerReturnOtherPageMarker) objectsCount--; } - ripple::STObject ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); - ownerDir.setFieldU64(ripple::sfIndexNext, kNEXT_PAGE); + xrpl::STObject ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); + ownerDir.setFieldU64(xrpl::sfIndexNext, kNextPage); // first page 's next page is 99 ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); - ripple::STObject ownerDir2 = createOwnerDirLedgerObject(indexes, kINDEX1); + xrpl::STObject ownerDir2 = createOwnerDirLedgerObject(indexes, kIndex1); // second page's next page is 0 - ownerDir2.setFieldU64(ripple::sfIndexNext, 0); + ownerDir2.setFieldU64(xrpl::sfIndexNext, 0); ON_CALL(*backend_, doFetchLedgerObject(ownerDir2Kk, testing::_, testing::_)) .WillByDefault(Return(ownerDir2.getSerializer().peekData())); @@ -225,10 +225,10 @@ TEST_F(RPCHelpersTest, TraverseOwnedNodesNoInputMarkerReturnOtherPageMarker) util::spawn(ctx_, [&, this](boost::asio::yield_context yield) { auto count = 0; auto ret = - traverseOwnedNodes(*backend_, account, 9, kLIMIT, {}, yield, [&](auto) { count++; }); + traverseOwnedNodes(*backend_, account, 9, kLimit, {}, yield, [&](auto) { count++; }); EXPECT_TRUE(ret.has_value()); - EXPECT_EQ(count, kLIMIT); - EXPECT_EQ(ret.value().toString(), fmt::format("{},{}", kINDEX1, kNEXT_PAGE)); + EXPECT_EQ(count, kLimit); + EXPECT_EQ(ret.value().toString(), fmt::format("{},{}", kIndex1, kNextPage)); }); ctx_.run(); } @@ -236,21 +236,21 @@ TEST_F(RPCHelpersTest, TraverseOwnedNodesNoInputMarkerReturnOtherPageMarker) // Send a valid marker TEST_F(RPCHelpersTest, TraverseOwnedNodesWithMarkerReturnSamePageMarker) { - auto account = getAccountIdWithString(kACCOUNT); - auto ownerDir2Kk = ripple::keylet::page(ripple::keylet::ownerDir(account), 99).key; - static constexpr auto kLIMIT = 8; - static constexpr auto kPAGE_NUM = 99; + auto account = getAccountIdWithString(kAccount); + auto ownerDir2Kk = xrpl::keylet::page(xrpl::keylet::ownerDir(account), 99).key; + static constexpr auto kLimit = 8; + static constexpr auto kPageNum = 99; EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); std::vector bbs; int objectsCount = 10; - ripple::STObject const channel1 = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); - std::vector indexes; + xrpl::STObject const channel1 = + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); + std::vector indexes; while (objectsCount != 0) { // return owner index - indexes.emplace_back(kINDEX1); + indexes.emplace_back(kIndex1); objectsCount--; } objectsCount = 10; @@ -259,8 +259,8 @@ TEST_F(RPCHelpersTest, TraverseOwnedNodesWithMarkerReturnSamePageMarker) objectsCount--; } - ripple::STObject ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); - ownerDir.setFieldU64(ripple::sfIndexNext, 0); + xrpl::STObject ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); + ownerDir.setFieldU64(xrpl::sfIndexNext, 0); // return ownerdir when search by marker ON_CALL(*backend_, doFetchLedgerObject(ownerDir2Kk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -274,14 +274,14 @@ TEST_F(RPCHelpersTest, TraverseOwnedNodesWithMarkerReturnSamePageMarker) *backend_, account, 9, - kLIMIT, - fmt::format("{},{}", kINDEX1, kPAGE_NUM), + kLimit, + fmt::format("{},{}", kIndex1, kPageNum), yield, [&](auto) { count++; } ); EXPECT_TRUE(ret.has_value()); - EXPECT_EQ(count, kLIMIT); - EXPECT_EQ(ret.value().toString(), fmt::format("{},{}", kINDEX1, kPAGE_NUM)); + EXPECT_EQ(count, kLimit); + EXPECT_EQ(ret.value().toString(), fmt::format("{},{}", kIndex1, kPageNum)); }); ctx_.run(); } @@ -290,23 +290,23 @@ TEST_F(RPCHelpersTest, TraverseOwnedNodesWithMarkerReturnSamePageMarker) // return invalid params error TEST_F(RPCHelpersTest, TraverseOwnedNodesWithUnexistingIndexMarker) { - auto account = getAccountIdWithString(kACCOUNT); - auto ownerDir2Kk = ripple::keylet::page(ripple::keylet::ownerDir(account), 99).key; - static constexpr auto kLIMIT = 8; - static constexpr auto kPAGE_NUM = 99; + auto account = getAccountIdWithString(kAccount); + auto ownerDir2Kk = xrpl::keylet::page(xrpl::keylet::ownerDir(account), 99).key; + static constexpr auto kLimit = 8; + static constexpr auto kPageNum = 99; EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); int objectsCount = 10; - ripple::STObject const channel1 = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); - std::vector indexes; + xrpl::STObject const channel1 = + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); + std::vector indexes; while (objectsCount != 0) { // return owner index - indexes.emplace_back(kINDEX1); + indexes.emplace_back(kIndex1); objectsCount--; } - ripple::STObject ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); - ownerDir.setFieldU64(ripple::sfIndexNext, 0); + xrpl::STObject ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); + ownerDir.setFieldU64(xrpl::sfIndexNext, 0); // return ownerdir when search by marker ON_CALL(*backend_, doFetchLedgerObject(ownerDir2Kk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -317,13 +317,13 @@ TEST_F(RPCHelpersTest, TraverseOwnedNodesWithUnexistingIndexMarker) *backend_, account, 9, - kLIMIT, - fmt::format("{},{}", kINDEX2, kPAGE_NUM), + kLimit, + fmt::format("{},{}", kIndex2, kPageNum), yield, [&](auto) { count++; } ); EXPECT_FALSE(ret.has_value()); - EXPECT_EQ(ret.error(), ripple::rpcINVALID_PARAMS); + EXPECT_EQ(ret.error(), xrpl::RpcInvalidParams); EXPECT_EQ(ret.error().message, "Invalid marker."); }); ctx_.run(); @@ -422,13 +422,13 @@ TEST_F(RPCHelpersTest, DeliverMaxAliasV1) TEST_F(RPCHelpersTest, DeliverMaxAliasV2) { - constexpr auto kJSON = R"JSON({ + constexpr auto kJson = R"JSON({ "TransactionType": "Payment", "Amount": { "test": "test" } })JSON"; - auto req = boost::json::parse(kJSON).as_object(); + auto req = boost::json::parse(kJson).as_object(); insertDeliverMaxAlias(req, 2); EXPECT_EQ( @@ -446,14 +446,14 @@ TEST_F(RPCHelpersTest, DeliverMaxAliasV2) TEST_F(RPCHelpersTest, LedgerHeaderJson) { - auto const ledgerHeader = createLedgerHeader(kINDEX1, 30); + auto const ledgerHeader = createLedgerHeader(kIndex1, 30); auto const binJson = toJson(ledgerHeader, true, 1u); - constexpr auto kEXPECT_BIN = R"JSON({ + constexpr auto kExpectBin = R"JSON({ "ledger_data": "0000001E000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "closed": true })JSON"; - EXPECT_EQ(binJson, boost::json::parse(kEXPECT_BIN)); + EXPECT_EQ(binJson, boost::json::parse(kExpectBin)); auto const expectJson = fmt::format( R"JSON({{ @@ -470,7 +470,7 @@ TEST_F(RPCHelpersTest, LedgerHeaderJson) "transaction_hash": "0000000000000000000000000000000000000000000000000000000000000000", "closed": true }})JSON", - kINDEX1, + kIndex1, 30 ); auto json = toJson(ledgerHeader, false, 1u); @@ -481,7 +481,7 @@ TEST_F(RPCHelpersTest, LedgerHeaderJson) TEST_F(RPCHelpersTest, LedgerHeaderJsonV2) { - auto const ledgerHeader = createLedgerHeader(kINDEX1, 30); + auto const ledgerHeader = createLedgerHeader(kIndex1, 30); auto const expectJson = fmt::format( R"JSON({{ @@ -498,7 +498,7 @@ TEST_F(RPCHelpersTest, LedgerHeaderJsonV2) "transaction_hash": "0000000000000000000000000000000000000000000000000000000000000000", "closed": true }})JSON", - kINDEX1, + kIndex1, 30 ); auto json = toJson(ledgerHeader, false, 2u); @@ -509,7 +509,7 @@ TEST_F(RPCHelpersTest, LedgerHeaderJsonV2) TEST_F(RPCHelpersTest, TransactionAndMetadataBinaryJsonV1) { - auto const txMeta = createAcceptNftBuyerOfferTxWithMetadata(kACCOUNT, 30, 1, kINDEX1, kINDEX2); + auto const txMeta = createAcceptNftBuyerOfferTxWithMetadata(kAccount, 30, 1, kIndex1, kIndex2); auto const json = toJsonWithBinaryTx(txMeta, 1); EXPECT_TRUE(json.contains(JS(tx_blob))); EXPECT_TRUE(json.contains(JS(meta))); @@ -517,7 +517,7 @@ TEST_F(RPCHelpersTest, TransactionAndMetadataBinaryJsonV1) TEST_F(RPCHelpersTest, TransactionAndMetadataBinaryJsonV2) { - auto const txMeta = createAcceptNftBuyerOfferTxWithMetadata(kACCOUNT, 30, 1, kINDEX1, kINDEX2); + auto const txMeta = createAcceptNftBuyerOfferTxWithMetadata(kAccount, 30, 1, kIndex1, kIndex2); auto const json = toJsonWithBinaryTx(txMeta, 2); EXPECT_TRUE(json.contains(JS(tx_blob))); EXPECT_TRUE(json.contains(JS(meta_blob))); @@ -525,15 +525,15 @@ TEST_F(RPCHelpersTest, TransactionAndMetadataBinaryJsonV2) TEST_F(RPCHelpersTest, ParseIssue) { - constexpr auto kJSON = R"JSON({ + constexpr auto kJson = R"JSON({ "issuer": "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun", "currency": "JPY" })JSON"; - auto issue = parseIssue(boost::json::parse(kJSON).as_object()); - EXPECT_TRUE(issue.account == getAccountIdWithString(kACCOUNT2)); + auto issue = parseIssue(boost::json::parse(kJson).as_object()); + EXPECT_TRUE(issue.account == getAccountIdWithString(kAccount2)); issue = parseIssue(boost::json::parse(R"JSON({"currency": "XRP"})JSON").as_object()); - EXPECT_TRUE(ripple::isXRP(issue.currency)); + EXPECT_TRUE(xrpl::isXRP(issue.currency)); EXPECT_THROW( parseIssue(boost::json::parse(R"JSON({"currency": 2})JSON").as_object()), std::runtime_error @@ -544,11 +544,11 @@ TEST_F(RPCHelpersTest, ParseIssue) std::runtime_error ); - constexpr auto kJSON2 = R"JSON({ + constexpr auto kJson2 = R"JSON({ "issuer": "abcd", "currency": "JPY" })JSON"; - EXPECT_THROW(parseIssue(boost::json::parse(kJSON2).as_object()), std::runtime_error); + EXPECT_THROW(parseIssue(boost::json::parse(kJson2).as_object()), std::runtime_error); EXPECT_THROW( parseIssue( @@ -561,245 +561,245 @@ TEST_F(RPCHelpersTest, ParseIssue) TEST_F(RPCHelpersTest, FetchAndCheckAnyFlagExists_BlobDoesNotExist) { - auto const account = getAccountIdWithString(kACCOUNT); - auto const issuerKey = ripple::keylet::account(account); + auto const account = getAccountIdWithString(kAccount); + auto const issuerKey = xrpl::keylet::account(account); // returns empty blob - ON_CALL(*backend_, doFetchLedgerObject(issuerKey.key, kLEDGER_SEQ_OBJECT, _)) + ON_CALL(*backend_, doFetchLedgerObject(issuerKey.key, kLedgerSeqObject, _)) .WillByDefault(Return(std::optional{})); runSpawn([&](boost::asio::yield_context yield) { // return false: blob doesn't exist EXPECT_FALSE(fetchAndCheckAnyFlagsExists( - *backend_, kLEDGER_SEQ_OBJECT, issuerKey, {ripple::lsfHighDeepFreeze}, yield + *backend_, kLedgerSeqObject, issuerKey, {xrpl::lsfHighDeepFreeze}, yield )); }); } TEST_F(RPCHelpersTest, FetchAndCheckAnyFlagExists_AccountWithCorrectFlag) { - auto const account = getAccountIdWithString(kACCOUNT); - auto const issuerKey = ripple::keylet::account(account); + auto const account = getAccountIdWithString(kAccount); + auto const issuerKey = xrpl::keylet::account(account); // create account with highDeepFreeze Flag auto const accountObject = - createAccountRootObject(kACCOUNT, ripple::lsfHighDeepFreeze, 1, 10, 2, kTXN_ID, 3); + createAccountRootObject(kAccount, xrpl::lsfHighDeepFreeze, 1, 10, 2, kTxnId, 3); - ON_CALL(*backend_, doFetchLedgerObject(issuerKey.key, kLEDGER_SEQ_OBJECT, _)) + ON_CALL(*backend_, doFetchLedgerObject(issuerKey.key, kLedgerSeqObject, _)) .WillByDefault(Return(accountObject.getSerializer().peekData())); runSpawn([&](boost::asio::yield_context yield) { // returns true: accountObject has the highDeepFreeze flag EXPECT_TRUE(fetchAndCheckAnyFlagsExists( - *backend_, kLEDGER_SEQ_OBJECT, issuerKey, {ripple::lsfHighDeepFreeze}, yield + *backend_, kLedgerSeqObject, issuerKey, {xrpl::lsfHighDeepFreeze}, yield )); }); } TEST_F(RPCHelpersTest, FetchAndCheckAnyFlagExists_TrustLineIsFrozenAndCheckFreezeFlag) { - auto const account = getAccountIdWithString(kACCOUNT); - auto const issuerKey = ripple::keylet::account(account); + auto const account = getAccountIdWithString(kAccount); + auto const issuerKey = xrpl::keylet::account(account); // create account with lowDeepFreeze Flag auto const accountObject = - createAccountRootObject(kACCOUNT, ripple::lsfLowDeepFreeze, 1, 10, 2, kTXN_ID, 3); + createAccountRootObject(kAccount, xrpl::lsfLowDeepFreeze, 1, 10, 2, kTxnId, 3); - ON_CALL(*backend_, doFetchLedgerObject(issuerKey.key, kLEDGER_SEQ_OBJECT, _)) + ON_CALL(*backend_, doFetchLedgerObject(issuerKey.key, kLedgerSeqObject, _)) .WillByDefault(Return(accountObject.getSerializer().peekData())); runSpawn([&](boost::asio::yield_context yield) { // returns false: accountObject has the lowDeepFreeze flag EXPECT_FALSE(fetchAndCheckAnyFlagsExists( - *backend_, kLEDGER_SEQ_OBJECT, issuerKey, {ripple::lsfHighDeepFreeze}, yield + *backend_, kLedgerSeqObject, issuerKey, {xrpl::lsfHighDeepFreeze}, yield )); }); } TEST_F(RPCHelpersTest, isGlobalFrozen_AccountIsGlobalFrozen) { - auto const account = getAccountIdWithString(kACCOUNT); - auto const issuerKey = ripple::keylet::account(account); + auto const account = getAccountIdWithString(kAccount); + auto const issuerKey = xrpl::keylet::account(account); auto const accountObject = - createAccountRootObject(kACCOUNT, ripple::lsfGlobalFreeze, 1, 10, 2, kTXN_ID, 3); + createAccountRootObject(kAccount, xrpl::lsfGlobalFreeze, 1, 10, 2, kTxnId, 3); - ON_CALL(*backend_, doFetchLedgerObject(issuerKey.key, kLEDGER_SEQ_OBJECT, _)) + ON_CALL(*backend_, doFetchLedgerObject(issuerKey.key, kLedgerSeqObject, _)) .WillByDefault(Return(accountObject.getSerializer().peekData())); runSpawn([&](boost::asio::yield_context yield) { // returns false: accountObject has the lowDeepFreeze flag - EXPECT_TRUE(isGlobalFrozen(*backend_, kLEDGER_SEQ_OBJECT, account, yield)); + EXPECT_TRUE(isGlobalFrozen(*backend_, kLedgerSeqObject, account, yield)); }); } TEST_F(RPCHelpersTest, isDeepFrozen_TrustLineIsDeepFrozen) { - auto const account = getAccountIdWithString(kACCOUNT); - auto const account2 = getAccountIdWithString(kACCOUNT2); + auto const account = getAccountIdWithString(kAccount); + auto const account2 = getAccountIdWithString(kAccount2); // create a trustline between account and account2 and is deep frozen auto const trustLineKey = - ripple::keylet::line(account, account2, ripple::Currency{kCURRENCY}).key; + xrpl::keylet::trustLine(account, account2, xrpl::Currency{kCurrency}).key; auto const trustlineDeepFrozen = createRippleStateLedgerObject( - "USD", kACCOUNT, 8, kACCOUNT, 1000, kACCOUNT2, 2000, kINDEX1, 2, ripple::lsfLowDeepFreeze + "USD", kAccount, 8, kAccount, 1000, kAccount2, 2000, kIndex1, 2, xrpl::lsfLowDeepFreeze ); - ON_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLEDGER_SEQ_OBJECT, _)) + ON_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLedgerSeqObject, _)) .WillByDefault(Return(trustlineDeepFrozen.getSerializer().peekData())); runSpawn([&](boost::asio::yield_context yield) { EXPECT_TRUE(isDeepFrozen( - *backend_, kLEDGER_SEQ_OBJECT, account, ripple::Currency{kCURRENCY}, account2, yield + *backend_, kLedgerSeqObject, account, xrpl::Currency{kCurrency}, account2, yield )); }); } TEST_F(RPCHelpersTest, isDeepFrozen_TrustLineIsNotDeepFrozen) { - auto const account = getAccountIdWithString(kACCOUNT); - auto const account2 = getAccountIdWithString(kACCOUNT2); + auto const account = getAccountIdWithString(kAccount); + auto const account2 = getAccountIdWithString(kAccount2); // create a trustline between account and account2 that is frozen (NOT DeepFrozen) auto const trustLineKey = - ripple::keylet::line(account, account2, ripple::Currency{kCURRENCY}).key; + xrpl::keylet::trustLine(account, account2, xrpl::Currency{kCurrency}).key; auto const trustlineFrozen = createRippleStateLedgerObject( - "USD", kACCOUNT, 8, kACCOUNT, 1000, kACCOUNT2, 2000, kINDEX1, 2, ripple::lsfLowFreeze + "USD", kAccount, 8, kAccount, 1000, kAccount2, 2000, kIndex1, 2, xrpl::lsfLowFreeze ); - ON_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLEDGER_SEQ_OBJECT, _)) + ON_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLedgerSeqObject, _)) .WillByDefault(Return(trustlineFrozen.getSerializer().peekData())); runSpawn([&](boost::asio::yield_context yield) { EXPECT_FALSE(isDeepFrozen( - *backend_, kLEDGER_SEQ_OBJECT, account, ripple::Currency{kCURRENCY}, account2, yield + *backend_, kLedgerSeqObject, account, xrpl::Currency{kCurrency}, account2, yield )); }); } TEST_F(RPCHelpersTest, isDeepFrozen_IssuerAndAccountIsSameWillNotBeDeepFrozen) { - auto const account = getAccountIdWithString(kACCOUNT); - auto const issuer = getAccountIdWithString(kACCOUNT2); + auto const account = getAccountIdWithString(kAccount); + auto const issuer = getAccountIdWithString(kAccount2); auto const trustLineKey = - ripple::keylet::line(account, issuer, ripple::Currency{kCURRENCY}).key; + xrpl::keylet::trustLine(account, issuer, xrpl::Currency{kCurrency}).key; auto const trustlineDeepFrozen = createRippleStateLedgerObject( - "USD", kACCOUNT, 8, kACCOUNT, 1000, kACCOUNT2, 2000, kINDEX1, 2, ripple::lsfLowDeepFreeze + "USD", kAccount, 8, kAccount, 1000, kAccount2, 2000, kIndex1, 2, xrpl::lsfLowDeepFreeze ); - ON_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLEDGER_SEQ_OBJECT, _)) + ON_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLedgerSeqObject, _)) .WillByDefault(Return(trustlineDeepFrozen.getSerializer().peekData())); runSpawn([&](boost::asio::yield_context yield) { // both accounts are same so trustline is not deep frozen EXPECT_FALSE(isDeepFrozen( - *backend_, kLEDGER_SEQ_OBJECT, account, ripple::Currency{kCURRENCY}, account, yield + *backend_, kLedgerSeqObject, account, xrpl::Currency{kCurrency}, account, yield )); }); } TEST_F(RPCHelpersTest, isFrozen_IssuerAccountIsGlobalFrozen) { - auto const account = getAccountIdWithString(kACCOUNT); - auto const issuer = getAccountIdWithString(kACCOUNT2); + auto const account = getAccountIdWithString(kAccount); + auto const issuer = getAccountIdWithString(kAccount2); auto const accountObject = - createAccountRootObject(kACCOUNT2, ripple::lsfGlobalFreeze, 1, 10, 2, kTXN_ID, 3); - auto const issuerKey = ripple::keylet::account(issuer).key; + createAccountRootObject(kAccount2, xrpl::lsfGlobalFreeze, 1, 10, 2, kTxnId, 3); + auto const issuerKey = xrpl::keylet::account(issuer).key; - ON_CALL(*backend_, doFetchLedgerObject(issuerKey, kLEDGER_SEQ_OBJECT, _)) + ON_CALL(*backend_, doFetchLedgerObject(issuerKey, kLedgerSeqObject, _)) .WillByDefault(Return(accountObject.getSerializer().peekData())); runSpawn([&](boost::asio::yield_context yield) { - EXPECT_TRUE(isFrozen( - *backend_, kLEDGER_SEQ_OBJECT, account, ripple::Currency{kCURRENCY}, issuer, yield - )); + EXPECT_TRUE( + isFrozen(*backend_, kLedgerSeqObject, account, xrpl::Currency{kCurrency}, issuer, yield) + ); }); } TEST_F(RPCHelpersTest, isFrozen_IssuerAndAccountIsSameWillNotBeFrozen) { - auto const account = getAccountIdWithString(kACCOUNT); - auto const issuer = getAccountIdWithString(kACCOUNT2); + auto const account = getAccountIdWithString(kAccount); + auto const issuer = getAccountIdWithString(kAccount2); auto const trustLineKey = - ripple::keylet::line(account, issuer, ripple::Currency{kCURRENCY}).key; + xrpl::keylet::trustLine(account, issuer, xrpl::Currency{kCurrency}).key; auto const trustlineDeepFrozen = createRippleStateLedgerObject( - "USD", kACCOUNT, 8, kACCOUNT, 1000, kACCOUNT2, 2000, kINDEX1, 2, ripple::lsfHighFreeze + "USD", kAccount, 8, kAccount, 1000, kAccount2, 2000, kIndex1, 2, xrpl::lsfHighFreeze ); - ON_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLEDGER_SEQ_OBJECT, _)) + ON_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLedgerSeqObject, _)) .WillByDefault(Return(trustlineDeepFrozen.getSerializer().peekData())); runSpawn([&](boost::asio::yield_context yield) { EXPECT_FALSE(isFrozen( - *backend_, kLEDGER_SEQ_OBJECT, account, ripple::Currency{kCURRENCY}, account, yield + *backend_, kLedgerSeqObject, account, xrpl::Currency{kCurrency}, account, yield )); }); } TEST_F(RPCHelpersTest, isFrozen_IssuerTrustLineIsFrozen) { - auto const account = getAccountIdWithString(kACCOUNT); - auto const issuer = getAccountIdWithString(kACCOUNT2); - ripple::Currency const currency{kCURRENCY}; + auto const account = getAccountIdWithString(kAccount); + auto const issuer = getAccountIdWithString(kAccount2); + xrpl::Currency const currency{kCurrency}; - auto const trustLineKey = ripple::keylet::line(account, issuer, currency).key; + auto const trustLineKey = xrpl::keylet::trustLine(account, issuer, currency).key; // issuer is higher than account, so the correct flag to set is High freeze auto const trustlineFrozen = createRippleStateLedgerObject( - "USD", kACCOUNT, 8, kACCOUNT, 1000, kACCOUNT2, 2000, kINDEX1, 2, ripple::lsfHighFreeze + "USD", kAccount, 8, kAccount, 1000, kAccount2, 2000, kIndex1, 2, xrpl::lsfHighFreeze ); - ON_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLEDGER_SEQ_OBJECT, _)) + ON_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLedgerSeqObject, _)) .WillByDefault(Return(trustlineFrozen.getSerializer().peekData())); runSpawn([&](boost::asio::yield_context yield) { - EXPECT_TRUE(isFrozen(*backend_, kLEDGER_SEQ_OBJECT, account, currency, issuer, yield)); + EXPECT_TRUE(isFrozen(*backend_, kLedgerSeqObject, account, currency, issuer, yield)); }); } TEST_F(RPCHelpersTest, isFrozen_IssuerWithLowFreezeIsNotFrozen) { - auto const account = getAccountIdWithString(kACCOUNT); - auto const issuer = getAccountIdWithString(kACCOUNT2); - ripple::Currency const currency{kCURRENCY}; + auto const account = getAccountIdWithString(kAccount); + auto const issuer = getAccountIdWithString(kAccount2); + xrpl::Currency const currency{kCurrency}; - auto const trustLineKey = ripple::keylet::line(account, issuer, currency).key; + auto const trustLineKey = xrpl::keylet::trustLine(account, issuer, currency).key; // issuer is higher than account, but the flag set here is low freeze auto const trustlineFrozen = createRippleStateLedgerObject( - "USD", kACCOUNT, 8, kACCOUNT, 1000, kACCOUNT2, 2000, kINDEX1, 2, ripple::lsfLowFreeze + "USD", kAccount, 8, kAccount, 1000, kAccount2, 2000, kIndex1, 2, xrpl::lsfLowFreeze ); - ON_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLEDGER_SEQ_OBJECT, _)) + ON_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLedgerSeqObject, _)) .WillByDefault(Return(trustlineFrozen.getSerializer().peekData())); runSpawn([&](boost::asio::yield_context yield) { - EXPECT_FALSE(isFrozen(*backend_, kLEDGER_SEQ_OBJECT, account, currency, issuer, yield)); + EXPECT_FALSE(isFrozen(*backend_, kLedgerSeqObject, account, currency, issuer, yield)); }); } TEST_F(RPCHelpersTest, AccountHolds_TrustLineNotfrozen) { - auto const account = getAccountIdWithString(kACCOUNT); - auto const issuer = getAccountIdWithString(kACCOUNT2); - ripple::Currency const currency{kCURRENCY}; + auto const account = getAccountIdWithString(kAccount); + auto const issuer = getAccountIdWithString(kAccount2); + xrpl::Currency const currency{kCurrency}; - auto const trustLineKey = ripple::keylet::line(account, issuer, currency).key; + auto const trustLineKey = xrpl::keylet::trustLine(account, issuer, currency).key; auto const trustLine = createRippleStateLedgerObject( - kCURRENCY, kACCOUNT2, 500, kACCOUNT, 1000, kACCOUNT2, 1000, kTXN_ID, 1, 0 + kCurrency, kAccount2, 500, kAccount, 1000, kAccount2, 1000, kTxnId, 1, 0 ); - EXPECT_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLEDGER_SEQ_OBJECT, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLedgerSeqObject, _)) .WillOnce(Return(trustLine.getSerializer().peekData())); runSpawn([&](boost::asio::yield_context yield) { auto const result = accountHolds( *backend_, *mockAmendmentCenterPtr_, - kLEDGER_SEQ_OBJECT, + kLedgerSeqObject, account, currency, issuer, @@ -807,27 +807,27 @@ TEST_F(RPCHelpersTest, AccountHolds_TrustLineNotfrozen) yield ); // Check issuer has a balance of 500 - EXPECT_EQ(result, ripple::STAmount(getIssue(kCURRENCY, kACCOUNT2), 500)); + EXPECT_EQ(result, xrpl::STAmount(getIssue(kCurrency, kAccount2), 500)); }); } TEST_F(RPCHelpersTest, AccountHolds_NoTrustLine) { - auto const account = getAccountIdWithString(kACCOUNT); - auto const issuer = getAccountIdWithString(kACCOUNT2); - ripple::Currency const currency{kCURRENCY}; + auto const account = getAccountIdWithString(kAccount); + auto const issuer = getAccountIdWithString(kAccount2); + xrpl::Currency const currency{kCurrency}; - auto const key = ripple::keylet::line(account, issuer, currency).key; + auto const key = xrpl::keylet::trustLine(account, issuer, currency).key; // return no trustline found - EXPECT_CALL(*backend_, doFetchLedgerObject(key, kLEDGER_SEQ_OBJECT, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(key, kLedgerSeqObject, _)) .WillOnce(Return(std::nullopt)); runSpawn([&](boost::asio::yield_context yield) { auto const result = accountHolds( *backend_, *mockAmendmentCenterPtr_, - kLEDGER_SEQ_OBJECT, + kLedgerSeqObject, account, currency, issuer, @@ -835,70 +835,61 @@ TEST_F(RPCHelpersTest, AccountHolds_NoTrustLine) yield ); // balance is 0 as trustline is frozen - EXPECT_EQ(result, ripple::STAmount(getIssue(kCURRENCY, kACCOUNT2), 0)); + EXPECT_EQ(result, xrpl::STAmount(getIssue(kCurrency, kAccount2), 0)); }); } TEST_F(RPCHelpersTest, AccountHolds_TrustLineButFrozen) { - auto const account = getAccountIdWithString(kACCOUNT); - auto const issuer = getAccountIdWithString(kACCOUNT2); - ripple::Currency const currency{kCURRENCY}; + auto const account = getAccountIdWithString(kAccount); + auto const issuer = getAccountIdWithString(kAccount2); + xrpl::Currency const currency{kCurrency}; // balance of 500, but trustline is frozen - auto const trustLineKey = ripple::keylet::line(account, issuer, currency).key; + auto const trustLineKey = xrpl::keylet::trustLine(account, issuer, currency).key; auto const trustLine = createRippleStateLedgerObject( - kCURRENCY, - kACCOUNT2, - 500, - kACCOUNT, - 1000, - kACCOUNT2, - 1000, - kTXN_ID, - 1, - ripple::lsfHighFreeze + kCurrency, kAccount2, 500, kAccount, 1000, kAccount2, 1000, kTxnId, 1, xrpl::lsfHighFreeze ); - ON_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLEDGER_SEQ_OBJECT, _)) + ON_CALL(*backend_, doFetchLedgerObject(trustLineKey, kLedgerSeqObject, _)) .WillByDefault(Return(trustLine.getSerializer().peekData())); runSpawn([&](boost::asio::yield_context yield) { auto const result = accountHolds( *backend_, *mockAmendmentCenterPtr_, - kLEDGER_SEQ_OBJECT, + kLedgerSeqObject, account, currency, issuer, true, yield ); - EXPECT_EQ(result, ripple::STAmount(getIssue(kCURRENCY, kACCOUNT2), 0)); + EXPECT_EQ(result, xrpl::STAmount(getIssue(kCurrency, kAccount2), 0)); }); } TEST_F(RPCHelpersTest, AccountHoldsFixLPTAmendmentDisabled) { - auto ammAccount = getAccountIdWithString(kAMM_ACCOUNT); - auto account = getAccountIdWithString(kACCOUNT); + auto ammAccount = getAccountIdWithString(kAmmAccount); + auto account = getAccountIdWithString(kAccount); auto const lptRippleState = createRippleStateLedgerObject( - kLPTOKEN_CURRENCY, kAMM_ACCOUNT, 100, kACCOUNT, 100, kAMM_ACCOUNT, 100, kTXN_ID, 3 + kLptokenCurrency, kAmmAccount, 100, kAccount, 100, kAmmAccount, 100, kTxnId, 3 ); auto const lptRippleStateKk = - ripple::keylet::line(ammAccount, account, ripple::to_currency(kLPTOKEN_CURRENCY)).key; + xrpl::keylet::trustLine(ammAccount, account, xrpl::toCurrency(kLptokenCurrency)).key; // trustline fetched twice. once in accountHolds and once in isFrozen EXPECT_CALL(*backend_, doFetchLedgerObject(lptRippleStateKk, testing::_, testing::_)) .Times(2) .WillRepeatedly(Return(lptRippleState.getSerializer().peekData())); - auto const ammID = ripple::uint256{kAMM_ID}; - auto const ammAccountKk = ripple::keylet::account(ammAccount).key; + auto const ammID = xrpl::uint256{kAmmId}; + auto const ammAccountKk = xrpl::keylet::account(ammAccount).key; auto const ammAccountRoot = - createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2, 0, ammID); + createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2, 0, ammID); EXPECT_CALL(*backend_, doFetchLedgerObject(ammAccountKk, testing::_, testing::_)) .WillOnce(Return(ammAccountRoot.getSerializer().peekData())); @@ -915,7 +906,7 @@ TEST_F(RPCHelpersTest, AccountHoldsFixLPTAmendmentDisabled) *mockAmendmentCenterPtr_, 0, account, - ripple::to_currency(kLPTOKEN_CURRENCY), + xrpl::toCurrency(kLptokenCurrency), ammAccount, true, yield @@ -927,14 +918,14 @@ TEST_F(RPCHelpersTest, AccountHoldsFixLPTAmendmentDisabled) TEST_F(RPCHelpersTest, AccountHoldsLPTokenNotAMMAccount) { - auto account = getAccountIdWithString(kACCOUNT); - auto account2 = getAccountIdWithString(kACCOUNT2); + auto account = getAccountIdWithString(kAccount); + auto account2 = getAccountIdWithString(kAccount2); auto const usdRippleState = createRippleStateLedgerObject( - "USD", kACCOUNT2, 100, kACCOUNT, 100, kACCOUNT2, 100, kTXN_ID, 3 + "USD", kAccount2, 100, kAccount, 100, kAccount2, 100, kTxnId, 3 ); auto const usdRippleStateKk = - ripple::keylet::line(account2, account, ripple::to_currency("USD")).key; + xrpl::keylet::trustLine(account2, account, xrpl::toCurrency("USD")).key; // trustline fetched twice. once in accountHolds and once in isFrozen EXPECT_CALL(*backend_, doFetchLedgerObject(usdRippleStateKk, testing::_, testing::_)) @@ -947,8 +938,8 @@ TEST_F(RPCHelpersTest, AccountHoldsLPTokenNotAMMAccount) ) .WillOnce(Return(true)); - auto const account2Kk = ripple::keylet::account(account2).key; - auto const account2Root = createAccountRootObject(kACCOUNT2, 0, 2, 200, 2, kINDEX1, 2, 0); + auto const account2Kk = xrpl::keylet::account(account2).key; + auto const account2Root = createAccountRootObject(kAccount2, 0, 2, 200, 2, kIndex1, 2, 0); EXPECT_CALL(*backend_, doFetchLedgerObject(account2Kk, testing::_, testing::_)) .Times(2) @@ -960,7 +951,7 @@ TEST_F(RPCHelpersTest, AccountHoldsLPTokenNotAMMAccount) *mockAmendmentCenterPtr_, 0, account, - ripple::to_currency("USD"), + xrpl::toCurrency("USD"), account2, true, yield @@ -972,15 +963,15 @@ TEST_F(RPCHelpersTest, AccountHoldsLPTokenNotAMMAccount) TEST_F(RPCHelpersTest, AccountHoldsLPTokenAsset1Frozen) { - auto ammAccount = getAccountIdWithString(kAMM_ACCOUNT); - auto account = getAccountIdWithString(kACCOUNT); - auto issuer = getAccountIdWithString(kISSUER); + auto ammAccount = getAccountIdWithString(kAmmAccount); + auto account = getAccountIdWithString(kAccount); + auto issuer = getAccountIdWithString(kIssuer); auto const lptRippleState = createRippleStateLedgerObject( - kLPTOKEN_CURRENCY, kAMM_ACCOUNT, 100, kACCOUNT, 100, kAMM_ACCOUNT, 100, kTXN_ID, 3 + kLptokenCurrency, kAmmAccount, 100, kAccount, 100, kAmmAccount, 100, kTxnId, 3 ); auto const lptRippleStateKk = - ripple::keylet::line(ammAccount, account, ripple::to_currency(kLPTOKEN_CURRENCY)).key; + xrpl::keylet::trustLine(ammAccount, account, xrpl::toCurrency(kLptokenCurrency)).key; // trustline fetched twice. once in accountHolds and once in isFrozen EXPECT_CALL(*backend_, doFetchLedgerObject(lptRippleStateKk, testing::_, testing::_)) @@ -993,28 +984,27 @@ TEST_F(RPCHelpersTest, AccountHoldsLPTokenAsset1Frozen) ) .WillOnce(Return(true)); - auto const ammID = ripple::uint256{kAMM_ID}; - auto const ammAccountKk = ripple::keylet::account(ammAccount).key; + auto const ammID = xrpl::uint256{kAmmId}; + auto const ammAccountKk = xrpl::keylet::account(ammAccount).key; auto const ammAccountRoot = - createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2, 0, ammID); + createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2, 0, ammID); // accountroot fetched twice, once in isFrozen, once in accountHolds EXPECT_CALL(*backend_, doFetchLedgerObject(ammAccountKk, testing::_, testing::_)) .Times(2) .WillRepeatedly(Return(ammAccountRoot.getSerializer().peekData())); - auto const amm = createAmmObject( - kAMM_ACCOUNT, "USD", kISSUER, "XRP", ripple::toBase58(ripple::xrpAccount()) - ); + auto const amm = + createAmmObject(kAmmAccount, "USD", kIssuer, "XRP", xrpl::toBase58(xrpl::xrpAccount())); EXPECT_CALL( - *backend_, doFetchLedgerObject(ripple::keylet::amm(ammID).key, testing::_, testing::_) + *backend_, doFetchLedgerObject(xrpl::keylet::amm(ammID).key, testing::_, testing::_) ) .Times(1) .WillOnce(Return(amm.getSerializer().peekData())); - auto const issuerKk = ripple::keylet::account(issuer).key; + auto const issuerKk = xrpl::keylet::account(issuer).key; auto const issuerAccountRoot = - createAccountRootObject(kISSUER, ripple::lsfGlobalFreeze, 2, 200, 2, kINDEX1, 2, 0); + createAccountRootObject(kIssuer, xrpl::lsfGlobalFreeze, 2, 200, 2, kIndex1, 2, 0); EXPECT_CALL(*backend_, doFetchLedgerObject(issuerKk, testing::_, testing::_)) .WillOnce(Return(issuerAccountRoot.getSerializer().peekData())); @@ -1024,7 +1014,7 @@ TEST_F(RPCHelpersTest, AccountHoldsLPTokenAsset1Frozen) *mockAmendmentCenterPtr_, 0, account, - ripple::to_currency(kLPTOKEN_CURRENCY), + xrpl::toCurrency(kLptokenCurrency), ammAccount, true, yield @@ -1036,15 +1026,15 @@ TEST_F(RPCHelpersTest, AccountHoldsLPTokenAsset1Frozen) TEST_F(RPCHelpersTest, AccountHoldsLPTokenAsset2Frozen) { - auto ammAccount = getAccountIdWithString(kAMM_ACCOUNT); - auto account = getAccountIdWithString(kACCOUNT); - auto issuer = getAccountIdWithString(kISSUER); + auto ammAccount = getAccountIdWithString(kAmmAccount); + auto account = getAccountIdWithString(kAccount); + auto issuer = getAccountIdWithString(kIssuer); auto const lptRippleState = createRippleStateLedgerObject( - kLPTOKEN_CURRENCY, kAMM_ACCOUNT, 100, kACCOUNT, 100, kAMM_ACCOUNT, 100, kTXN_ID, 3 + kLptokenCurrency, kAmmAccount, 100, kAccount, 100, kAmmAccount, 100, kTxnId, 3 ); auto const lptRippleStateKk = - ripple::keylet::line(ammAccount, account, ripple::to_currency(kLPTOKEN_CURRENCY)).key; + xrpl::keylet::trustLine(ammAccount, account, xrpl::toCurrency(kLptokenCurrency)).key; // trustline fetched twice. once in accountHolds and once in isFrozen EXPECT_CALL(*backend_, doFetchLedgerObject(lptRippleStateKk, testing::_, testing::_)).Times(2); @@ -1057,27 +1047,26 @@ TEST_F(RPCHelpersTest, AccountHoldsLPTokenAsset2Frozen) ) .WillOnce(testing::Return(true)); - auto const ammID = ripple::uint256{kAMM_ID}; - auto const ammAccountKk = ripple::keylet::account(ammAccount).key; + auto const ammID = xrpl::uint256{kAmmId}; + auto const ammAccountKk = xrpl::keylet::account(ammAccount).key; auto const ammAccountRoot = - createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2, 0, ammID); + createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2, 0, ammID); // accountroot fetched twice, once in isFrozen, once in accountHolds EXPECT_CALL(*backend_, doFetchLedgerObject(ammAccountKk, testing::_, testing::_)) .Times(2) .WillRepeatedly(Return(ammAccountRoot.getSerializer().peekData())); - auto const amm = createAmmObject( - kAMM_ACCOUNT, "XRP", ripple::toBase58(ripple::xrpAccount()), "USD", kISSUER - ); + auto const amm = + createAmmObject(kAmmAccount, "XRP", xrpl::toBase58(xrpl::xrpAccount()), "USD", kIssuer); EXPECT_CALL( - *backend_, doFetchLedgerObject(ripple::keylet::amm(ammID).key, testing::_, testing::_) + *backend_, doFetchLedgerObject(xrpl::keylet::amm(ammID).key, testing::_, testing::_) ) .WillOnce(Return(amm.getSerializer().peekData())); - auto const issuerKk = ripple::keylet::account(issuer).key; + auto const issuerKk = xrpl::keylet::account(issuer).key; auto const issuerAccountRoot = - createAccountRootObject(kISSUER, ripple::lsfGlobalFreeze, 2, 200, 2, kINDEX1, 2, 0); + createAccountRootObject(kIssuer, xrpl::lsfGlobalFreeze, 2, 200, 2, kIndex1, 2, 0); EXPECT_CALL(*backend_, doFetchLedgerObject(issuerKk, testing::_, testing::_)) .WillOnce(Return(issuerAccountRoot.getSerializer().peekData())); @@ -1087,7 +1076,7 @@ TEST_F(RPCHelpersTest, AccountHoldsLPTokenAsset2Frozen) *mockAmendmentCenterPtr_, 0, account, - ripple::to_currency(kLPTOKEN_CURRENCY), + xrpl::toCurrency(kLptokenCurrency), ammAccount, true, yield @@ -1099,15 +1088,15 @@ TEST_F(RPCHelpersTest, AccountHoldsLPTokenAsset2Frozen) TEST_F(RPCHelpersTest, AccountHoldsLPTokenUnfrozen) { - auto ammAccount = getAccountIdWithString(kAMM_ACCOUNT); - auto account = getAccountIdWithString(kACCOUNT); - auto issuer = getAccountIdWithString(kISSUER); + auto ammAccount = getAccountIdWithString(kAmmAccount); + auto account = getAccountIdWithString(kAccount); + auto issuer = getAccountIdWithString(kIssuer); auto const lptRippleState = createRippleStateLedgerObject( - kLPTOKEN_CURRENCY, kAMM_ACCOUNT, 100, kACCOUNT, 100, kAMM_ACCOUNT, 100, kTXN_ID, 3 + kLptokenCurrency, kAmmAccount, 100, kAccount, 100, kAmmAccount, 100, kTxnId, 3 ); auto const lptRippleStateKk = - ripple::keylet::line(ammAccount, account, ripple::to_currency(kLPTOKEN_CURRENCY)).key; + xrpl::keylet::trustLine(ammAccount, account, xrpl::toCurrency(kLptokenCurrency)).key; // trustline fetched twice. once in accountHolds and once in isFrozen EXPECT_CALL(*backend_, doFetchLedgerObject(lptRippleStateKk, testing::_, testing::_)) @@ -1120,33 +1109,32 @@ TEST_F(RPCHelpersTest, AccountHoldsLPTokenUnfrozen) ) .WillOnce(Return(true)); - auto const ammID = ripple::uint256{kAMM_ID}; - auto const ammAccountKk = ripple::keylet::account(ammAccount).key; + auto const ammID = xrpl::uint256{kAmmId}; + auto const ammAccountKk = xrpl::keylet::account(ammAccount).key; auto const ammAccountRoot = - createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2, 0, ammID); + createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2, 0, ammID); // accountroot fetched twice, once in isFrozen, once in accountHolds EXPECT_CALL(*backend_, doFetchLedgerObject(ammAccountKk, testing::_, testing::_)) .Times(2) .WillRepeatedly(Return(ammAccountRoot.getSerializer().peekData())); - auto const amm = createAmmObject( - kAMM_ACCOUNT, "XRP", ripple::toBase58(ripple::xrpAccount()), "USD", kISSUER - ); + auto const amm = + createAmmObject(kAmmAccount, "XRP", xrpl::toBase58(xrpl::xrpAccount()), "USD", kIssuer); EXPECT_CALL( - *backend_, doFetchLedgerObject(ripple::keylet::amm(ammID).key, testing::_, testing::_) + *backend_, doFetchLedgerObject(xrpl::keylet::amm(ammID).key, testing::_, testing::_) ) .WillOnce(Return(amm.getSerializer().peekData())); - auto const issuerKk = ripple::keylet::account(issuer).key; - auto const issuerAccountRoot = createAccountRootObject(kISSUER, 0, 2, 200, 2, kINDEX1, 2, 0); + auto const issuerKk = xrpl::keylet::account(issuer).key; + auto const issuerAccountRoot = createAccountRootObject(kIssuer, 0, 2, 200, 2, kIndex1, 2, 0); EXPECT_CALL(*backend_, doFetchLedgerObject(issuerKk, testing::_, testing::_)) .WillOnce(Return(issuerAccountRoot.getSerializer().peekData())); auto const usdRippleState = - createRippleStateLedgerObject("USD", kISSUER, 100, kACCOUNT, 100, kISSUER, 100, kTXN_ID, 3); + createRippleStateLedgerObject("USD", kIssuer, 100, kAccount, 100, kIssuer, 100, kTxnId, 3); auto const usdRippleStateKk = - ripple::keylet::line(issuer, account, ripple::to_currency("USD")).key; + xrpl::keylet::trustLine(issuer, account, xrpl::toCurrency("USD")).key; EXPECT_CALL(*backend_, doFetchLedgerObject(usdRippleStateKk, testing::_, testing::_)) .WillOnce(Return(usdRippleState.getSerializer().peekData())); @@ -1157,7 +1145,7 @@ TEST_F(RPCHelpersTest, AccountHoldsLPTokenUnfrozen) *mockAmendmentCenterPtr_, 0, account, - ripple::to_currency(kLPTOKEN_CURRENCY), + xrpl::toCurrency(kLptokenCurrency), ammAccount, true, yield @@ -1380,7 +1368,7 @@ INSTANTIATE_TEST_CASE_P( IsAdminCmdTest, IsAdminCmdParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(IsAdminCmdParameterTest, Test) @@ -1465,5 +1453,5 @@ INSTANTIATE_TEST_SUITE_P( true } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); diff --git a/tests/unit/rpc/WorkQueueTests.cpp b/tests/unit/rpc/WorkQueueTests.cpp index 64fde5703..872280534 100644 --- a/tests/unit/rpc/WorkQueueTests.cpp +++ b/tests/unit/rpc/WorkQueueTests.cpp @@ -47,10 +47,10 @@ struct WorkQueueTest : WithPrometheus, RPCWorkQueueTestBase { TEST_F(WorkQueueTest, WhitelistedExecutionCountAddsUp) { - static constexpr auto kTOTAL = 512u; + static constexpr auto kTotal = 512u; std::atomic_uint32_t executeCount = 0u; - for (auto i = 0u; i < kTOTAL; ++i) { + for (auto i = 0u; i < kTotal; ++i) { queue.postCoro( [&executeCount](auto /* yield */) { ++executeCount; }, /* isWhiteListed = */ true ); @@ -60,21 +60,21 @@ TEST_F(WorkQueueTest, WhitelistedExecutionCountAddsUp) auto const report = queue.report(); - EXPECT_EQ(executeCount, kTOTAL); - EXPECT_EQ(report.at("queued"), kTOTAL); + EXPECT_EQ(executeCount, kTotal); + EXPECT_EQ(report.at("queued"), kTotal); EXPECT_EQ(report.at("current_queue_size"), 0); EXPECT_EQ(report.at("max_queue_size"), 2); } TEST_F(WorkQueueTest, NonWhitelistedPreventSchedulingAtQueueLimitExceeded) { - static constexpr auto kTOTAL = 3u; + static constexpr auto kTotal = 3u; auto unblocked = false; std::mutex mtx; std::condition_variable cv; - for (auto i = 0u; i < kTOTAL; ++i) { + for (auto i = 0u; i < kTotal; ++i) { auto res = queue.postCoro( [&](auto /* yield */) { std::unique_lock lk{mtx}; @@ -83,7 +83,7 @@ TEST_F(WorkQueueTest, NonWhitelistedPreventSchedulingAtQueueLimitExceeded) /* isWhiteListed = */ false ); - if (i == kTOTAL - 1) { + if (i == kTotal - 1) { EXPECT_FALSE(res); std::unique_lock const lk{mtx}; @@ -100,7 +100,7 @@ TEST_F(WorkQueueTest, NonWhitelistedPreventSchedulingAtQueueLimitExceeded) struct WorkQueueDelayedStartTest : WithPrometheus { WorkQueue queue{ - WorkQueue::kDONT_START_PROCESSING_TAG, + WorkQueue::kDontStartProcessingTag, /* numWorkers = */ 1, /* maxSize = */ 100 }; @@ -129,7 +129,7 @@ TEST_F(WorkQueueDelayedStartTest, WaitTimeIncludesDelayBeforeStartProcessing) struct WorkQueuePriorityTest : WithPrometheus { WorkQueue queue{ - WorkQueue::kDONT_START_PROCESSING_TAG, + WorkQueue::kDontStartProcessingTag, /* numWorkers = */ 1, /* maxSize = */ 100 }; @@ -137,11 +137,11 @@ struct WorkQueuePriorityTest : WithPrometheus { TEST_F(WorkQueuePriorityTest, HighPriorityTasks) { - static constexpr auto kTOTAL = 10; + static constexpr auto kTotal = 10; std::vector executionOrder; std::mutex mtx; - for (int i = 0; i < kTOTAL; ++i) { + for (int i = 0; i < kTotal; ++i) { queue.postCoro( [&](auto) { std::scoped_lock const lock(mtx); @@ -278,7 +278,7 @@ TEST_F(WorkQueueDeathTest, DISABLED_ExecuteTaskAssertsWhenQueueIsEmpty) EXPECT_DEATH( { WorkQueue queue( - WorkQueue::kDONT_START_PROCESSING_TAG, /* numWorkers = */ 1, /* maxSize = */ 2 + WorkQueue::kDontStartProcessingTag, /* numWorkers = */ 1, /* maxSize = */ 2 ); queue.startProcessing(); // the actual queue is empty which will lead to assertion // failure diff --git a/tests/unit/rpc/common/impl/HandlerProviderTests.cpp b/tests/unit/rpc/common/impl/HandlerProviderTests.cpp index ae2d6de3d..22bd4cb00 100644 --- a/tests/unit/rpc/common/impl/HandlerProviderTests.cpp +++ b/tests/unit/rpc/common/impl/HandlerProviderTests.cpp @@ -24,15 +24,15 @@ struct ProductionHandlerProviderTest : util::prometheus::WithPrometheus, MockBac util::config::ClioConfigDefinition config{ {"api_version.default", util::config::ConfigValue{util::config::ConfigType::Integer}.defaultValue( - rpc::kAPI_VERSION_DEFAULT + rpc::kApiVersionDefault )}, {"api_version.min", util::config::ConfigValue{util::config::ConfigType::Integer}.defaultValue( - rpc::kAPI_VERSION_MIN + rpc::kApiVersionMin )}, {"api_version.max", util::config::ConfigValue{util::config::ConfigType::Integer}.defaultValue( - rpc::kAPI_VERSION_MAX + rpc::kApiVersionMax )}, }; StrictMockSubscriptionManagerSharedPtr subscriptionManagerMock; diff --git a/tests/unit/rpc/handlers/AMMInfoTests.cpp b/tests/unit/rpc/handlers/AMMInfoTests.cpp index b8c9348d4..4e139a3cb 100644 --- a/tests/unit/rpc/handlers/AMMInfoTests.cpp +++ b/tests/unit/rpc/handlers/AMMInfoTests.cpp @@ -27,21 +27,20 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kSEQ = 30; -constexpr auto kWRONG_AMM_ACCOUNT = "000S7XL6nxRAi7JcbJcn1Na179oF300000"; -constexpr auto kAMM_ACCOUNT = "rLcS7XL6nxRAi7JcbJcn1Na179oF3vdfbh"; -constexpr auto kAMM_ACCOUNT2 = "rnW8FAPgpQgA6VoESnVrUVJHBdq9QAtRZs"; -constexpr auto kLP_ISSUE_CURRENCY = "03930D02208264E2E40EC1B0C09E4DB96EE197B1"; -constexpr auto kNOTFOUND_ACCOUNT = "rBdLS7RVLqkPwnWQCT2bC6HJd6xGoBizq8"; -constexpr auto kAMM_ID = 54321; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kINDEX1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; -constexpr auto kINDEX2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kSeq = 30; +constexpr auto kWrongAmmAccount = "000S7XL6nxRAi7JcbJcn1Na179oF300000"; +constexpr auto kAmmAccount = "rLcS7XL6nxRAi7JcbJcn1Na179oF3vdfbh"; +constexpr auto kAmmAccounT2 = "rnW8FAPgpQgA6VoESnVrUVJHBdq9QAtRZs"; +constexpr auto kLpIssueCurrency = "03930D02208264E2E40EC1B0C09E4DB96EE197B1"; +constexpr auto kNotfoundAccount = "rBdLS7RVLqkPwnWQCT2bC6HJd6xGoBizq8"; +constexpr auto kAmmId = 54321; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kIndex1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; +constexpr auto kIndex2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; } // namespace @@ -130,7 +129,7 @@ INSTANTIATE_TEST_CASE_P( RPCAMMInfoGroup1, AMMInfoParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(AMMInfoParameterTest, InvalidParams) @@ -138,7 +137,7 @@ TEST_P(AMMInfoParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); @@ -150,10 +149,10 @@ TEST_P(AMMInfoParameterTest, InvalidParams) TEST_F(RPCAMMInfoHandlerTest, AccountNotFound) { - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, 30); - auto const missingAccountKey = getAccountKey(kNOTFOUND_ACCOUNT); - auto const accountRoot = createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2); - auto const accountKey = getAccountKey(kAMM_ACCOUNT); + auto const lgrInfo = createLedgerHeader(kLedgerHash, 30); + auto const missingAccountKey = getAccountKey(kNotfoundAccount); + auto const accountRoot = createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2); + auto const accountKey = getAccountKey(kAmmAccount); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); ON_CALL(*backend_, doFetchLedgerObject(missingAccountKey, testing::_, testing::_)) @@ -161,20 +160,20 @@ TEST_F(RPCAMMInfoHandlerTest, AccountNotFound) ON_CALL(*backend_, doFetchLedgerObject(accountKey, testing::_, testing::_)) .WillByDefault(Return(accountRoot.getSerializer().peekData())); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}", "account": "{}" }})JSON", - kAMM_ACCOUNT, - kNOTFOUND_ACCOUNT + kAmmAccount, + kNotfoundAccount ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -185,22 +184,22 @@ TEST_F(RPCAMMInfoHandlerTest, AccountNotFound) TEST_F(RPCAMMInfoHandlerTest, AMMAccountNotExist) { - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, 30); + auto const lgrInfo = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); ON_CALL(*backend_, doFetchLedgerObject).WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}" }})JSON", - kWRONG_AMM_ACCOUNT + kWrongAmmAccount ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "actMalformed"); @@ -210,22 +209,22 @@ TEST_F(RPCAMMInfoHandlerTest, AMMAccountNotExist) TEST_F(RPCAMMInfoHandlerTest, AMMAccountNotInDBIsMalformed) { - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, 30); + auto const lgrInfo = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); ON_CALL(*backend_, doFetchLedgerObject).WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}" }})JSON", - kAMM_ACCOUNT + kAmmAccount ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -236,25 +235,25 @@ TEST_F(RPCAMMInfoHandlerTest, AMMAccountNotInDBIsMalformed) TEST_F(RPCAMMInfoHandlerTest, AMMAccountNotFoundMissingAmmField) { - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, 30); - auto const accountRoot = createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const lgrInfo = createLedgerHeader(kLedgerHash, 30); + auto const accountRoot = createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); ON_CALL(*backend_, doFetchLedgerObject) .WillByDefault(Return(accountRoot.getSerializer().peekData())); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}" }})JSON", - kAMM_ACCOUNT + kAmmAccount ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -265,16 +264,16 @@ TEST_F(RPCAMMInfoHandlerTest, AMMAccountNotFoundMissingAmmField) TEST_F(RPCAMMInfoHandlerTest, AMMAccountAmmBlobNotFound) { - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, 30); - auto const accountKey = getAccountKey(kAMM_ACCOUNT); - auto const ammId = ripple::uint256{kAMM_ID}; - auto const ammKeylet = ripple::keylet::amm(ammId); + auto const lgrInfo = createLedgerHeader(kLedgerHash, 30); + auto const accountKey = getAccountKey(kAmmAccount); + auto const ammId = xrpl::uint256{kAmmId}; + auto const ammKeylet = xrpl::keylet::amm(ammId); - auto accountRoot = createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto accountRoot = createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2); auto ammObj = createAmmObject( - kAMM_ACCOUNT2, "XRP", ripple::toBase58(ripple::xrpAccount()), "JPY", kAMM_ACCOUNT2 + kAmmAccounT2, "XRP", xrpl::toBase58(xrpl::xrpAccount()), "JPY", kAmmAccounT2 ); - accountRoot.setFieldH256(ripple::sfAMMID, ripple::uint256{kAMM_ID}); + accountRoot.setFieldH256(xrpl::sfAMMID, xrpl::uint256{kAmmId}); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); ON_CALL(*backend_, doFetchLedgerObject(accountKey, testing::_, testing::_)) @@ -282,18 +281,18 @@ TEST_F(RPCAMMInfoHandlerTest, AMMAccountAmmBlobNotFound) ON_CALL(*backend_, doFetchLedgerObject(ammKeylet.key, testing::_, testing::_)) .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}" }})JSON", - kAMM_ACCOUNT + kAmmAccount ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -304,17 +303,17 @@ TEST_F(RPCAMMInfoHandlerTest, AMMAccountAmmBlobNotFound) TEST_F(RPCAMMInfoHandlerTest, AMMAccountAccBlobNotFound) { - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, 30); - auto const accountKey = getAccountKey(kAMM_ACCOUNT); - auto const account2Key = getAccountKey(kAMM_ACCOUNT2); - auto const ammId = ripple::uint256{kAMM_ID}; - auto const ammKeylet = ripple::keylet::amm(ammId); + auto const lgrInfo = createLedgerHeader(kLedgerHash, 30); + auto const accountKey = getAccountKey(kAmmAccount); + auto const account2Key = getAccountKey(kAmmAccounT2); + auto const ammId = xrpl::uint256{kAmmId}; + auto const ammKeylet = xrpl::keylet::amm(ammId); - auto accountRoot = createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto accountRoot = createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2); auto const ammObj = createAmmObject( - kAMM_ACCOUNT2, "XRP", ripple::toBase58(ripple::xrpAccount()), "JPY", kAMM_ACCOUNT2 + kAmmAccounT2, "XRP", xrpl::toBase58(xrpl::xrpAccount()), "JPY", kAmmAccounT2 ); - accountRoot.setFieldH256(ripple::sfAMMID, ammId); + accountRoot.setFieldH256(xrpl::sfAMMID, ammId); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); ON_CALL(*backend_, doFetchLedgerObject(accountKey, testing::_, testing::_)) @@ -324,18 +323,18 @@ TEST_F(RPCAMMInfoHandlerTest, AMMAccountAccBlobNotFound) ON_CALL(*backend_, doFetchLedgerObject(account2Key, testing::_, testing::_)) .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}" }})JSON", - kAMM_ACCOUNT + kAmmAccount ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -346,25 +345,25 @@ TEST_F(RPCAMMInfoHandlerTest, AMMAccountAccBlobNotFound) TEST_F(RPCAMMInfoHandlerTest, HappyPathMinimalFirstXRPNoTrustline) { - auto const account1 = getAccountIdWithString(kAMM_ACCOUNT); - auto const account2 = getAccountIdWithString(kAMM_ACCOUNT2); - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, kSEQ); - auto const ammKey = ripple::uint256{kAMM_ID}; - auto const ammKeylet = ripple::keylet::amm(ammKey); - auto const feesKey = ripple::keylet::fees().key; + auto const account1 = getAccountIdWithString(kAmmAccount); + auto const account2 = getAccountIdWithString(kAmmAccounT2); + auto const lgrInfo = createLedgerHeader(kLedgerHash, kSeq); + auto const ammKey = xrpl::uint256{kAmmId}; + auto const ammKeylet = xrpl::keylet::amm(ammKey); + auto const feesKey = xrpl::keylet::feeSettings().key; auto const issue2LineKey = - ripple::keylet::line(account1, account2, ripple::to_currency("JPY")).key; + xrpl::keylet::trustLine(account1, account2, xrpl::toCurrency("JPY")).key; - auto accountRoot = createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto accountRoot = createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2); auto ammObj = createAmmObject( - kAMM_ACCOUNT, + kAmmAccount, "XRP", - ripple::toBase58(ripple::xrpAccount()), + xrpl::toBase58(xrpl::xrpAccount()), "JPY", - kAMM_ACCOUNT2, - kLP_ISSUE_CURRENCY + kAmmAccounT2, + kLpIssueCurrency ); - accountRoot.setFieldH256(ripple::sfAMMID, ammKey); + accountRoot.setFieldH256(xrpl::sfAMMID, ammKey); auto const feesObj = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); @@ -374,23 +373,23 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathMinimalFirstXRPNoTrustline) .WillByDefault(Return(accountRoot.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(ammKeylet.key, testing::_, testing::_)) .WillByDefault(Return(ammObj.getSerializer().peekData())); - ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSEQ, _)).WillByDefault(Return(feesObj)); - ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSeq, _)).WillByDefault(Return(feesObj)); + ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSeq, _)) .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}" }})JSON", - kAMM_ACCOUNT + kAmmAccount ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); - auto expectedResult = json::parse( + auto const output = handler.process(kInput, Context{yield}); + auto expectedResult = boost::json::parse( fmt::format( R"JSON({{ "amm": {{ @@ -413,12 +412,12 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathMinimalFirstXRPNoTrustline) "ledger_hash": "{}", "validated": true }})JSON", - kLP_ISSUE_CURRENCY, - kAMM_ACCOUNT, + kLpIssueCurrency, + kAmmAccount, "JPY", - kAMM_ACCOUNT2, - kAMM_ACCOUNT, - kLEDGER_HASH + kAmmAccounT2, + kAmmAccount, + kLedgerHash ) ); @@ -429,31 +428,31 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathMinimalFirstXRPNoTrustline) TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAccount) { - auto const account1 = getAccountIdWithString(kAMM_ACCOUNT); - auto const account2 = getAccountIdWithString(kAMM_ACCOUNT2); - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, kSEQ); - auto const ammKey = ripple::uint256{kAMM_ID}; - auto const ammKeylet = ripple::keylet::amm(ammKey); - auto const feesKey = ripple::keylet::fees().key; + auto const account1 = getAccountIdWithString(kAmmAccount); + auto const account2 = getAccountIdWithString(kAmmAccounT2); + auto const lgrInfo = createLedgerHeader(kLedgerHash, kSeq); + auto const ammKey = xrpl::uint256{kAmmId}; + auto const ammKeylet = xrpl::keylet::amm(ammKey); + auto const feesKey = xrpl::keylet::feeSettings().key; auto const issue2LineKey = - ripple::keylet::line(account2, account1, ripple::to_currency("JPY")).key; + xrpl::keylet::trustLine(account2, account1, xrpl::toCurrency("JPY")).key; - auto accountRoot = createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2); - accountRoot.setFieldH256(ripple::sfAMMID, ammKey); - auto const account2Root = createAccountRootObject(kAMM_ACCOUNT2, 0, 2, 300, 2, kINDEX1, 2); + auto accountRoot = createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2); + accountRoot.setFieldH256(xrpl::sfAMMID, ammKey); + auto const account2Root = createAccountRootObject(kAmmAccounT2, 0, 2, 300, 2, kIndex1, 2); auto const ammObj = createAmmObject( - kAMM_ACCOUNT2, + kAmmAccounT2, "XRP", - ripple::toBase58(ripple::xrpAccount()), + xrpl::toBase58(xrpl::xrpAccount()), "JPY", - kAMM_ACCOUNT, - kLP_ISSUE_CURRENCY + kAmmAccount, + kLpIssueCurrency ); auto const lptCurrency = createLptCurrency("XRP", "JPY"); - auto const accountHoldsKeylet = ripple::keylet::line(account2, account2, lptCurrency); + auto const accountHoldsKeylet = xrpl::keylet::trustLine(account2, account2, lptCurrency); auto const feesObj = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); auto const trustline = createRippleStateLedgerObject( - kLP_ISSUE_CURRENCY, kAMM_ACCOUNT, 12, kAMM_ACCOUNT2, 1000, kAMM_ACCOUNT, 2000, kINDEX1, 2 + kLpIssueCurrency, kAmmAccount, 12, kAmmAccounT2, 1000, kAmmAccount, 2000, kIndex1, 2 ); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); @@ -463,27 +462,27 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAccount) .WillByDefault(Return(account2Root.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(ammKeylet.key, testing::_, testing::_)) .WillByDefault(Return(ammObj.getSerializer().peekData())); - ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSEQ, _)).WillByDefault(Return(feesObj)); - ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSeq, _)).WillByDefault(Return(feesObj)); + ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSeq, _)) .WillByDefault(Return(std::optional{})); - ON_CALL(*backend_, doFetchLedgerObject(accountHoldsKeylet.key, kSEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(accountHoldsKeylet.key, kSeq, _)) .WillByDefault(Return(trustline.getSerializer().peekData())); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}", "account": "{}" }})JSON", - kAMM_ACCOUNT, - kAMM_ACCOUNT2 + kAmmAccount, + kAmmAccounT2 ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); - auto const expectedResult = json::parse( + auto const output = handler.process(kInput, Context{yield}); + auto const expectedResult = boost::json::parse( fmt::format( R"JSON({{ "amm": {{ @@ -506,12 +505,12 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAccount) "ledger_hash": "{}", "validated": true }})JSON", - kLP_ISSUE_CURRENCY, - kAMM_ACCOUNT2, + kLpIssueCurrency, + kAmmAccounT2, "JPY", - kAMM_ACCOUNT, - kAMM_ACCOUNT2, - kLEDGER_HASH + kAmmAccount, + kAmmAccounT2, + kLedgerHash ) ); @@ -522,25 +521,25 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAccount) TEST_F(RPCAMMInfoHandlerTest, HappyPathMinimalSecondXRPNoTrustline) { - auto const account1 = getAccountIdWithString(kAMM_ACCOUNT); - auto const account2 = getAccountIdWithString(kAMM_ACCOUNT2); - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, kSEQ); - auto const ammKey = ripple::uint256{kAMM_ID}; - auto const ammKeylet = ripple::keylet::amm(ammKey); - auto const feesKey = ripple::keylet::fees().key; + auto const account1 = getAccountIdWithString(kAmmAccount); + auto const account2 = getAccountIdWithString(kAmmAccounT2); + auto const lgrInfo = createLedgerHeader(kLedgerHash, kSeq); + auto const ammKey = xrpl::uint256{kAmmId}; + auto const ammKeylet = xrpl::keylet::amm(ammKey); + auto const feesKey = xrpl::keylet::feeSettings().key; auto const issue2LineKey = - ripple::keylet::line(account1, account2, ripple::to_currency("JPY")).key; + xrpl::keylet::trustLine(account1, account2, xrpl::toCurrency("JPY")).key; - auto accountRoot = createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto accountRoot = createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2); auto ammObj = createAmmObject( - kAMM_ACCOUNT, + kAmmAccount, "JPY", - kAMM_ACCOUNT2, + kAmmAccounT2, "XRP", - ripple::toBase58(ripple::xrpAccount()), - kLP_ISSUE_CURRENCY + xrpl::toBase58(xrpl::xrpAccount()), + kLpIssueCurrency ); - accountRoot.setFieldH256(ripple::sfAMMID, ammKey); + accountRoot.setFieldH256(xrpl::sfAMMID, ammKey); auto const feesObj = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); @@ -550,23 +549,23 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathMinimalSecondXRPNoTrustline) .WillByDefault(Return(accountRoot.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(ammKeylet.key, testing::_, testing::_)) .WillByDefault(Return(ammObj.getSerializer().peekData())); - ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSEQ, _)).WillByDefault(Return(feesObj)); - ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSeq, _)).WillByDefault(Return(feesObj)); + ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSeq, _)) .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}" }})JSON", - kAMM_ACCOUNT + kAmmAccount ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); - auto const expectedResult = json::parse( + auto const output = handler.process(kInput, Context{yield}); + auto const expectedResult = boost::json::parse( fmt::format( R"JSON({{ "amm": {{ @@ -589,12 +588,12 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathMinimalSecondXRPNoTrustline) "ledger_hash": "{}", "validated": true }})JSON", - kLP_ISSUE_CURRENCY, - kAMM_ACCOUNT, + kLpIssueCurrency, + kAmmAccount, "JPY", - kAMM_ACCOUNT2, - kAMM_ACCOUNT, - kLEDGER_HASH + kAmmAccounT2, + kAmmAccount, + kLedgerHash ) ); @@ -605,20 +604,19 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathMinimalSecondXRPNoTrustline) TEST_F(RPCAMMInfoHandlerTest, HappyPathNonXRPNoTrustlines) { - auto const account1 = getAccountIdWithString(kAMM_ACCOUNT); - auto const account2 = getAccountIdWithString(kAMM_ACCOUNT2); - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, kSEQ); - auto const ammKey = ripple::uint256{kAMM_ID}; - auto const ammKeylet = ripple::keylet::amm(ammKey); - auto const feesKey = ripple::keylet::fees().key; + auto const account1 = getAccountIdWithString(kAmmAccount); + auto const account2 = getAccountIdWithString(kAmmAccounT2); + auto const lgrInfo = createLedgerHeader(kLedgerHash, kSeq); + auto const ammKey = xrpl::uint256{kAmmId}; + auto const ammKeylet = xrpl::keylet::amm(ammKey); + auto const feesKey = xrpl::keylet::feeSettings().key; auto const issue2LineKey = - ripple::keylet::line(account1, account2, ripple::to_currency("JPY")).key; + xrpl::keylet::trustLine(account1, account2, xrpl::toCurrency("JPY")).key; - auto accountRoot = createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2); - auto ammObj = createAmmObject( - kAMM_ACCOUNT, "USD", kAMM_ACCOUNT, "JPY", kAMM_ACCOUNT2, kLP_ISSUE_CURRENCY - ); - accountRoot.setFieldH256(ripple::sfAMMID, ammKey); + auto accountRoot = createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2); + auto ammObj = + createAmmObject(kAmmAccount, "USD", kAmmAccount, "JPY", kAmmAccounT2, kLpIssueCurrency); + accountRoot.setFieldH256(xrpl::sfAMMID, ammKey); auto const feesObj = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); @@ -628,23 +626,23 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathNonXRPNoTrustlines) .WillByDefault(Return(accountRoot.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(ammKeylet.key, testing::_, testing::_)) .WillByDefault(Return(ammObj.getSerializer().peekData())); - ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSEQ, _)).WillByDefault(Return(feesObj)); - ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSeq, _)).WillByDefault(Return(feesObj)); + ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSeq, _)) .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}" }})JSON", - kAMM_ACCOUNT + kAmmAccount ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); - auto const expectedResult = json::parse( + auto const output = handler.process(kInput, Context{yield}); + auto const expectedResult = boost::json::parse( fmt::format( R"JSON({{ "amm": {{ @@ -672,14 +670,14 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathNonXRPNoTrustlines) "ledger_hash": "{}", "validated": true }})JSON", - kLP_ISSUE_CURRENCY, - kAMM_ACCOUNT, + kLpIssueCurrency, + kAmmAccount, "USD", - kAMM_ACCOUNT, + kAmmAccount, "JPY", - kAMM_ACCOUNT2, - kAMM_ACCOUNT, - kLEDGER_HASH + kAmmAccounT2, + kAmmAccount, + kLedgerHash ) ); @@ -690,48 +688,47 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathNonXRPNoTrustlines) TEST_F(RPCAMMInfoHandlerTest, HappyPathFrozen) { - auto const account1 = getAccountIdWithString(kAMM_ACCOUNT); - auto const account2 = getAccountIdWithString(kAMM_ACCOUNT2); - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, kSEQ); - auto const ammKey = ripple::uint256{kAMM_ID}; - auto const ammKeylet = ripple::keylet::amm(ammKey); - auto const feesKey = ripple::keylet::fees().key; + auto const account1 = getAccountIdWithString(kAmmAccount); + auto const account2 = getAccountIdWithString(kAmmAccounT2); + auto const lgrInfo = createLedgerHeader(kLedgerHash, kSeq); + auto const ammKey = xrpl::uint256{kAmmId}; + auto const ammKeylet = xrpl::keylet::amm(ammKey); + auto const feesKey = xrpl::keylet::feeSettings().key; auto const issue1LineKey = - ripple::keylet::line(account1, account1, ripple::to_currency("USD")).key; + xrpl::keylet::trustLine(account1, account1, xrpl::toCurrency("USD")).key; auto const issue2LineKey = - ripple::keylet::line(account1, account2, ripple::to_currency("JPY")).key; + xrpl::keylet::trustLine(account1, account2, xrpl::toCurrency("JPY")).key; - auto accountRoot = createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2); - auto ammObj = createAmmObject( - kAMM_ACCOUNT, "USD", kAMM_ACCOUNT, "JPY", kAMM_ACCOUNT2, kLP_ISSUE_CURRENCY - ); - accountRoot.setFieldH256(ripple::sfAMMID, ammKey); + auto accountRoot = createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2); + auto ammObj = + createAmmObject(kAmmAccount, "USD", kAmmAccount, "JPY", kAmmAccounT2, kLpIssueCurrency); + accountRoot.setFieldH256(xrpl::sfAMMID, ammKey); auto const feesObj = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); // note: frozen flag will not be used for trustline1 because issuer == account auto const trustline1BalanceFrozen = createRippleStateLedgerObject( "USD", - kAMM_ACCOUNT, + kAmmAccount, 8, - kAMM_ACCOUNT, + kAmmAccount, 1000, - kAMM_ACCOUNT2, + kAmmAccounT2, 2000, - kINDEX1, + kIndex1, 2, - ripple::lsfGlobalFreeze + xrpl::lsfGlobalFreeze ); auto const trustline2BalanceFrozen = createRippleStateLedgerObject( "JPY", - kAMM_ACCOUNT, + kAmmAccount, 12, - kAMM_ACCOUNT2, + kAmmAccounT2, 1000, - kAMM_ACCOUNT, + kAmmAccount, 2000, - kINDEX1, + kIndex1, 2, - ripple::lsfGlobalFreeze + xrpl::lsfGlobalFreeze ); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); @@ -741,25 +738,25 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathFrozen) .WillByDefault(Return(accountRoot.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(ammKeylet.key, testing::_, testing::_)) .WillByDefault(Return(ammObj.getSerializer().peekData())); - ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSEQ, _)).WillByDefault(Return(feesObj)); - ON_CALL(*backend_, doFetchLedgerObject(issue1LineKey, kSEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSeq, _)).WillByDefault(Return(feesObj)); + ON_CALL(*backend_, doFetchLedgerObject(issue1LineKey, kSeq, _)) .WillByDefault(Return(trustline1BalanceFrozen.getSerializer().peekData())); - ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSeq, _)) .WillByDefault(Return(trustline2BalanceFrozen.getSerializer().peekData())); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}" }})JSON", - kAMM_ACCOUNT + kAmmAccount ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); - auto const expectedResult = json::parse( + auto const output = handler.process(kInput, Context{yield}); + auto const expectedResult = boost::json::parse( fmt::format( R"JSON({{ "amm": {{ @@ -787,14 +784,14 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathFrozen) "ledger_hash": "{}", "validated": true }})JSON", - kLP_ISSUE_CURRENCY, - kAMM_ACCOUNT, + kLpIssueCurrency, + kAmmAccount, "USD", - kAMM_ACCOUNT, + kAmmAccount, "JPY", - kAMM_ACCOUNT2, - kAMM_ACCOUNT, - kLEDGER_HASH + kAmmAccounT2, + kAmmAccount, + kLedgerHash ) ); @@ -805,50 +802,49 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathFrozen) TEST_F(RPCAMMInfoHandlerTest, HappyPathFrozenIssuer) { - auto const account1 = getAccountIdWithString(kAMM_ACCOUNT); - auto const account2 = getAccountIdWithString(kAMM_ACCOUNT2); - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, kSEQ); - auto const ammKey = ripple::uint256{kAMM_ID}; - auto const ammKeylet = ripple::keylet::amm(ammKey); - auto const feesKey = ripple::keylet::fees().key; + auto const account1 = getAccountIdWithString(kAmmAccount); + auto const account2 = getAccountIdWithString(kAmmAccounT2); + auto const lgrInfo = createLedgerHeader(kLedgerHash, kSeq); + auto const ammKey = xrpl::uint256{kAmmId}; + auto const ammKeylet = xrpl::keylet::amm(ammKey); + auto const feesKey = xrpl::keylet::feeSettings().key; auto const issue1LineKey = - ripple::keylet::line(account1, account1, ripple::to_currency("USD")).key; + xrpl::keylet::trustLine(account1, account1, xrpl::toCurrency("USD")).key; auto const issue2LineKey = - ripple::keylet::line(account1, account2, ripple::to_currency("JPY")).key; + xrpl::keylet::trustLine(account1, account2, xrpl::toCurrency("JPY")).key; // asset1 will be frozen because flag set here auto accountRoot = - createAccountRootObject(kAMM_ACCOUNT, ripple::lsfGlobalFreeze, 2, 200, 2, kINDEX1, 2); - auto ammObj = createAmmObject( - kAMM_ACCOUNT, "USD", kAMM_ACCOUNT, "JPY", kAMM_ACCOUNT2, kLP_ISSUE_CURRENCY - ); - accountRoot.setFieldH256(ripple::sfAMMID, ammKey); + createAccountRootObject(kAmmAccount, xrpl::lsfGlobalFreeze, 2, 200, 2, kIndex1, 2); + auto ammObj = + createAmmObject(kAmmAccount, "USD", kAmmAccount, "JPY", kAmmAccounT2, kLpIssueCurrency); + accountRoot.setFieldH256(xrpl::sfAMMID, ammKey); auto const feesObj = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); // note: frozen flag will not be used for trustline1 because issuer == account auto const trustline1BalanceFrozen = createRippleStateLedgerObject( "USD", - kAMM_ACCOUNT, + kAmmAccount, 8, - kAMM_ACCOUNT, + kAmmAccount, 1000, - kAMM_ACCOUNT2, + kAmmAccounT2, 2000, - kINDEX1, + kIndex1, 2, - ripple::lsfGlobalFreeze + xrpl::lsfGlobalFreeze ); auto const trustline2BalanceFrozen = createRippleStateLedgerObject( "JPY", - kAMM_ACCOUNT, + kAmmAccount, 12, - kAMM_ACCOUNT2, + kAmmAccounT2, 1000, - kAMM_ACCOUNT, + kAmmAccount, 2000, - kINDEX1, + kIndex1, 2, - ripple::lsfGlobalFreeze + xrpl::lsfGlobalFreeze ); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); @@ -858,25 +854,25 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathFrozenIssuer) .WillByDefault(Return(accountRoot.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(ammKeylet.key, testing::_, testing::_)) .WillByDefault(Return(ammObj.getSerializer().peekData())); - ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSEQ, _)).WillByDefault(Return(feesObj)); - ON_CALL(*backend_, doFetchLedgerObject(issue1LineKey, kSEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSeq, _)).WillByDefault(Return(feesObj)); + ON_CALL(*backend_, doFetchLedgerObject(issue1LineKey, kSeq, _)) .WillByDefault(Return(trustline1BalanceFrozen.getSerializer().peekData())); - ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSeq, _)) .WillByDefault(Return(trustline2BalanceFrozen.getSerializer().peekData())); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}" }})JSON", - kAMM_ACCOUNT + kAmmAccount ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); - auto const expectedResult = json::parse( + auto const output = handler.process(kInput, Context{yield}); + auto const expectedResult = boost::json::parse( fmt::format( R"JSON({{ "amm": {{ @@ -904,14 +900,14 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathFrozenIssuer) "ledger_hash": "{}", "validated": true }})JSON", - kLP_ISSUE_CURRENCY, - kAMM_ACCOUNT, + kLpIssueCurrency, + kAmmAccount, "USD", - kAMM_ACCOUNT, + kAmmAccount, "JPY", - kAMM_ACCOUNT2, - kAMM_ACCOUNT, - kLEDGER_HASH + kAmmAccounT2, + kAmmAccount, + kLedgerHash ) ); @@ -922,28 +918,28 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathFrozenIssuer) TEST_F(RPCAMMInfoHandlerTest, HappyPathWithTrustline) { - auto const account1 = getAccountIdWithString(kAMM_ACCOUNT); - auto const account2 = getAccountIdWithString(kAMM_ACCOUNT2); - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, kSEQ); - auto const ammKey = ripple::uint256{kAMM_ID}; - auto const ammKeylet = ripple::keylet::amm(ammKey); - auto const feesKey = ripple::keylet::fees().key; + auto const account1 = getAccountIdWithString(kAmmAccount); + auto const account2 = getAccountIdWithString(kAmmAccounT2); + auto const lgrInfo = createLedgerHeader(kLedgerHash, kSeq); + auto const ammKey = xrpl::uint256{kAmmId}; + auto const ammKeylet = xrpl::keylet::amm(ammKey); + auto const feesKey = xrpl::keylet::feeSettings().key; auto const issue2LineKey = - ripple::keylet::line(account1, account2, ripple::to_currency("JPY")).key; + xrpl::keylet::trustLine(account1, account2, xrpl::toCurrency("JPY")).key; - auto accountRoot = createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto accountRoot = createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2); auto ammObj = createAmmObject( - kAMM_ACCOUNT, + kAmmAccount, "XRP", - ripple::toBase58(ripple::xrpAccount()), + xrpl::toBase58(xrpl::xrpAccount()), "JPY", - kAMM_ACCOUNT2, - kLP_ISSUE_CURRENCY + kAmmAccounT2, + kLpIssueCurrency ); - accountRoot.setFieldH256(ripple::sfAMMID, ammKey); + accountRoot.setFieldH256(xrpl::sfAMMID, ammKey); auto const feesObj = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); auto const trustlineBalance = createRippleStateLedgerObject( - "JPY", kAMM_ACCOUNT2, -8, kAMM_ACCOUNT, 1000, kAMM_ACCOUNT2, 2000, kINDEX2, 2, 0 + "JPY", kAmmAccounT2, -8, kAmmAccount, 1000, kAmmAccounT2, 2000, kIndex2, 2, 0 ); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); @@ -953,23 +949,23 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithTrustline) .WillByDefault(Return(accountRoot.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(ammKeylet.key, testing::_, testing::_)) .WillByDefault(Return(ammObj.getSerializer().peekData())); - ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSEQ, _)).WillByDefault(Return(feesObj)); - ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSeq, _)).WillByDefault(Return(feesObj)); + ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSeq, _)) .WillByDefault(Return(trustlineBalance.getSerializer().peekData())); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}" }})JSON", - kAMM_ACCOUNT + kAmmAccount ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); - auto expectedResult = json::parse( + auto const output = handler.process(kInput, Context{yield}); + auto expectedResult = boost::json::parse( fmt::format( R"JSON({{ "amm": {{ @@ -992,12 +988,12 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithTrustline) "ledger_hash": "{}", "validated": true }})JSON", - kLP_ISSUE_CURRENCY, - kAMM_ACCOUNT, + kLpIssueCurrency, + kAmmAccount, "JPY", - kAMM_ACCOUNT2, - kAMM_ACCOUNT, - kLEDGER_HASH + kAmmAccounT2, + kAmmAccount, + kLedgerHash ) ); @@ -1008,30 +1004,30 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithTrustline) TEST_F(RPCAMMInfoHandlerTest, HappyPathWithVoteSlots) { - auto const account1 = getAccountIdWithString(kAMM_ACCOUNT); - auto const account2 = getAccountIdWithString(kAMM_ACCOUNT2); - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, kSEQ); - auto const ammKey = ripple::uint256{kAMM_ID}; - auto const ammKeylet = ripple::keylet::amm(ammKey); - auto const feesKey = ripple::keylet::fees().key; + auto const account1 = getAccountIdWithString(kAmmAccount); + auto const account2 = getAccountIdWithString(kAmmAccounT2); + auto const lgrInfo = createLedgerHeader(kLedgerHash, kSeq); + auto const ammKey = xrpl::uint256{kAmmId}; + auto const ammKeylet = xrpl::keylet::amm(ammKey); + auto const feesKey = xrpl::keylet::feeSettings().key; auto const issue2LineKey = - ripple::keylet::line(account1, account2, ripple::to_currency("JPY")).key; + xrpl::keylet::trustLine(account1, account2, xrpl::toCurrency("JPY")).key; - auto accountRoot = createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto accountRoot = createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2); auto ammObj = createAmmObject( - kAMM_ACCOUNT, + kAmmAccount, "XRP", - ripple::toBase58(ripple::xrpAccount()), + xrpl::toBase58(xrpl::xrpAccount()), "JPY", - kAMM_ACCOUNT2, - kLP_ISSUE_CURRENCY + kAmmAccounT2, + kLpIssueCurrency ); ammAddVoteSlot(ammObj, account1, 2, 4); ammAddVoteSlot(ammObj, account2, 4, 2); - accountRoot.setFieldH256(ripple::sfAMMID, ammKey); + accountRoot.setFieldH256(xrpl::sfAMMID, ammKey); auto const feesObj = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); auto const trustlineBalance = createRippleStateLedgerObject( - "JPY", kAMM_ACCOUNT2, -8, kAMM_ACCOUNT, 1000, kAMM_ACCOUNT2, 2000, kINDEX2, 2, 0 + "JPY", kAmmAccounT2, -8, kAmmAccount, 1000, kAmmAccounT2, 2000, kIndex2, 2, 0 ); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); @@ -1041,23 +1037,23 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithVoteSlots) .WillByDefault(Return(accountRoot.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(ammKeylet.key, testing::_, testing::_)) .WillByDefault(Return(ammObj.getSerializer().peekData())); - ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSEQ, _)).WillByDefault(Return(feesObj)); - ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSeq, _)).WillByDefault(Return(feesObj)); + ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSeq, _)) .WillByDefault(Return(trustlineBalance.getSerializer().peekData())); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}" }})JSON", - kAMM_ACCOUNT + kAmmAccount ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); - auto expectedResult = json::parse( + auto const output = handler.process(kInput, Context{yield}); + auto expectedResult = boost::json::parse( fmt::format( R"JSON({{ "amm": {{ @@ -1092,14 +1088,14 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithVoteSlots) "ledger_hash": "{}", "validated": true }})JSON", - kLP_ISSUE_CURRENCY, - kAMM_ACCOUNT, + kLpIssueCurrency, + kAmmAccount, "JPY", - kAMM_ACCOUNT2, - kAMM_ACCOUNT, - kAMM_ACCOUNT, - kAMM_ACCOUNT2, - kLEDGER_HASH + kAmmAccounT2, + kAmmAccount, + kAmmAccount, + kAmmAccounT2, + kLedgerHash ) ); @@ -1110,37 +1106,37 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithVoteSlots) TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAuctionSlot) { - auto const account1 = getAccountIdWithString(kAMM_ACCOUNT); - auto const account2 = getAccountIdWithString(kAMM_ACCOUNT2); - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, kSEQ); - auto const ammKey = ripple::uint256{kAMM_ID}; - auto const ammKeylet = ripple::keylet::amm(ammKey); - auto const feesKey = ripple::keylet::fees().key; + auto const account1 = getAccountIdWithString(kAmmAccount); + auto const account2 = getAccountIdWithString(kAmmAccounT2); + auto const lgrInfo = createLedgerHeader(kLedgerHash, kSeq); + auto const ammKey = xrpl::uint256{kAmmId}; + auto const ammKeylet = xrpl::keylet::amm(ammKey); + auto const feesKey = xrpl::keylet::feeSettings().key; auto const issue2LineKey = - ripple::keylet::line(account1, account2, ripple::to_currency("JPY")).key; + xrpl::keylet::trustLine(account1, account2, xrpl::toCurrency("JPY")).key; - auto accountRoot = createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto accountRoot = createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2); auto ammObj = createAmmObject( - kAMM_ACCOUNT, + kAmmAccount, "XRP", - ripple::toBase58(ripple::xrpAccount()), + xrpl::toBase58(xrpl::xrpAccount()), "JPY", - kAMM_ACCOUNT2, - kLP_ISSUE_CURRENCY + kAmmAccounT2, + kLpIssueCurrency ); ammSetAuctionSlot( ammObj, account2, - ripple::amountFromString(ripple::xrpIssue(), "100"), + xrpl::amountFromString(xrpl::xrpIssue(), "100"), 2, 25 * 3600, {account1, account2} ); - accountRoot.setFieldH256(ripple::sfAMMID, ammKey); + accountRoot.setFieldH256(xrpl::sfAMMID, ammKey); auto const feesObj = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); auto const trustlineBalance = createRippleStateLedgerObject( - "JPY", kAMM_ACCOUNT2, -8, kAMM_ACCOUNT, 1000, kAMM_ACCOUNT2, 2000, kINDEX2, 2, 0 + "JPY", kAmmAccounT2, -8, kAmmAccount, 1000, kAmmAccounT2, 2000, kIndex2, 2, 0 ); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); @@ -1150,23 +1146,23 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAuctionSlot) .WillByDefault(Return(accountRoot.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(ammKeylet.key, testing::_, testing::_)) .WillByDefault(Return(ammObj.getSerializer().peekData())); - ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSEQ, _)).WillByDefault(Return(feesObj)); - ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(feesKey, kSeq, _)).WillByDefault(Return(feesObj)); + ON_CALL(*backend_, doFetchLedgerObject(issue2LineKey, kSeq, _)) .WillByDefault(Return(trustlineBalance.getSerializer().peekData())); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "amm_account": "{}" }})JSON", - kAMM_ACCOUNT + kAmmAccount ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); - auto expectedResult = json::parse( + auto const output = handler.process(kInput, Context{yield}); + auto expectedResult = boost::json::parse( fmt::format( R"JSON({{ "amm": {{ @@ -1204,15 +1200,15 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAuctionSlot) "ledger_hash": "{}", "validated": true }})JSON", - kLP_ISSUE_CURRENCY, - kAMM_ACCOUNT, + kLpIssueCurrency, + kAmmAccount, "JPY", - kAMM_ACCOUNT2, - kAMM_ACCOUNT, - kAMM_ACCOUNT2, - kAMM_ACCOUNT, - kAMM_ACCOUNT2, - kLEDGER_HASH + kAmmAccounT2, + kAmmAccount, + kAmmAccounT2, + kAmmAccount, + kAmmAccounT2, + kLedgerHash ) ); @@ -1223,27 +1219,26 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAuctionSlot) TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAssetsMatchingInputOrder) { - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, kSEQ); - auto const account1 = getAccountIdWithString(kAMM_ACCOUNT); - auto const account2 = getAccountIdWithString(kAMM_ACCOUNT2); - auto const issue1 = ripple::Issue(ripple::to_currency("JPY"), account1); - auto const issue2 = ripple::Issue(ripple::to_currency("USD"), account2); - auto const ammKeylet = ripple::keylet::amm(issue1, issue2); + auto const lgrInfo = createLedgerHeader(kLedgerHash, kSeq); + auto const account1 = getAccountIdWithString(kAmmAccount); + auto const account2 = getAccountIdWithString(kAmmAccounT2); + auto const issue1 = xrpl::Issue(xrpl::toCurrency("JPY"), account1); + auto const issue2 = xrpl::Issue(xrpl::toCurrency("USD"), account2); + auto const ammKeylet = xrpl::keylet::amm(issue1, issue2); - auto accountRoot = createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2); - auto ammObj = createAmmObject( - kAMM_ACCOUNT, "JPY", kAMM_ACCOUNT, "USD", kAMM_ACCOUNT2, kLP_ISSUE_CURRENCY - ); - auto const auctionIssue = ripple::Issue{ripple::Currency{kLP_ISSUE_CURRENCY}, account1}; + auto accountRoot = createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2); + auto ammObj = + createAmmObject(kAmmAccount, "JPY", kAmmAccount, "USD", kAmmAccounT2, kLpIssueCurrency); + auto const auctionIssue = xrpl::Issue{xrpl::Currency{kLpIssueCurrency}, account1}; ammSetAuctionSlot( ammObj, account2, - ripple::amountFromString(auctionIssue, "100"), + xrpl::amountFromString(auctionIssue, "100"), 2, 25 * 3600, {account1, account2} ); - accountRoot.setFieldH256(ripple::sfAMMID, ammKeylet.key); + accountRoot.setFieldH256(xrpl::sfAMMID, ammKeylet.key); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); ON_CALL(*backend_, doFetchLedgerObject(getAccountKey(account1), testing::_, testing::_)) @@ -1253,7 +1248,7 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAssetsMatchingInputOrder) ON_CALL(*backend_, doFetchLedgerObject(ammKeylet.key, testing::_, testing::_)) .WillByDefault(Return(ammObj.getSerializer().peekData())); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "asset": {{ @@ -1265,15 +1260,15 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAssetsMatchingInputOrder) "issuer": "{}" }} }})JSON", - kAMM_ACCOUNT, - kAMM_ACCOUNT2 + kAmmAccount, + kAmmAccounT2 ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); - auto expectedResult = json::parse( + auto const output = handler.process(kInput, Context{yield}); + auto expectedResult = boost::json::parse( fmt::format( R"JSON({{ "amm": {{ @@ -1320,19 +1315,19 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAssetsMatchingInputOrder) "ledger_hash": "{}", "validated": true }})JSON", - kLP_ISSUE_CURRENCY, - kAMM_ACCOUNT, + kLpIssueCurrency, + kAmmAccount, "JPY", - kAMM_ACCOUNT, + kAmmAccount, "USD", - kAMM_ACCOUNT2, - kAMM_ACCOUNT, - kLP_ISSUE_CURRENCY, - kAMM_ACCOUNT, - kAMM_ACCOUNT2, - kAMM_ACCOUNT, - kAMM_ACCOUNT2, - kLEDGER_HASH + kAmmAccounT2, + kAmmAccount, + kLpIssueCurrency, + kAmmAccount, + kAmmAccounT2, + kAmmAccount, + kAmmAccounT2, + kLedgerHash ) ); @@ -1343,28 +1338,27 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAssetsMatchingInputOrder) TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAssetsPreservesInputOrder) { - auto const lgrInfo = createLedgerHeader(kLEDGER_HASH, kSEQ); - auto const account1 = getAccountIdWithString(kAMM_ACCOUNT); - auto const account2 = getAccountIdWithString(kAMM_ACCOUNT2); - auto const issue1 = ripple::Issue(ripple::to_currency("USD"), account1); - auto const issue2 = ripple::Issue(ripple::to_currency("JPY"), account2); - auto const ammKeylet = ripple::keylet::amm(issue1, issue2); + auto const lgrInfo = createLedgerHeader(kLedgerHash, kSeq); + auto const account1 = getAccountIdWithString(kAmmAccount); + auto const account2 = getAccountIdWithString(kAmmAccounT2); + auto const issue1 = xrpl::Issue(xrpl::toCurrency("USD"), account1); + auto const issue2 = xrpl::Issue(xrpl::toCurrency("JPY"), account2); + auto const ammKeylet = xrpl::keylet::amm(issue1, issue2); // Note: order in the AMM object is different from the input - auto ammObj = createAmmObject( - kAMM_ACCOUNT, "JPY", kAMM_ACCOUNT, "USD", kAMM_ACCOUNT2, kLP_ISSUE_CURRENCY - ); - auto accountRoot = createAccountRootObject(kAMM_ACCOUNT, 0, 2, 200, 2, kINDEX1, 2); - auto const auctionIssue = ripple::Issue{ripple::Currency{kLP_ISSUE_CURRENCY}, account1}; + auto ammObj = + createAmmObject(kAmmAccount, "JPY", kAmmAccount, "USD", kAmmAccounT2, kLpIssueCurrency); + auto accountRoot = createAccountRootObject(kAmmAccount, 0, 2, 200, 2, kIndex1, 2); + auto const auctionIssue = xrpl::Issue{xrpl::Currency{kLpIssueCurrency}, account1}; ammSetAuctionSlot( ammObj, account2, - ripple::amountFromString(auctionIssue, "100"), + xrpl::amountFromString(auctionIssue, "100"), 2, 25 * 3600, {account1, account2} ); - accountRoot.setFieldH256(ripple::sfAMMID, ammKeylet.key); + accountRoot.setFieldH256(xrpl::sfAMMID, ammKeylet.key); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(lgrInfo)); ON_CALL(*backend_, doFetchLedgerObject(getAccountKey(account1), testing::_, testing::_)) @@ -1374,7 +1368,7 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAssetsPreservesInputOrder) ON_CALL(*backend_, doFetchLedgerObject(ammKeylet.key, testing::_, testing::_)) .WillByDefault(Return(ammObj.getSerializer().peekData())); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "asset": {{ @@ -1386,15 +1380,15 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAssetsPreservesInputOrder) "issuer": "{}" }} }})JSON", - kAMM_ACCOUNT, - kAMM_ACCOUNT2 + kAmmAccount, + kAmmAccounT2 ) ); auto const handler = AnyHandler{AMMInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); - auto expectedResult = json::parse( + auto const output = handler.process(kInput, Context{yield}); + auto expectedResult = boost::json::parse( fmt::format( R"JSON({{ "amm": {{ @@ -1441,19 +1435,19 @@ TEST_F(RPCAMMInfoHandlerTest, HappyPathWithAssetsPreservesInputOrder) "ledger_hash": "{}", "validated": true }})JSON", - kLP_ISSUE_CURRENCY, - kAMM_ACCOUNT, + kLpIssueCurrency, + kAmmAccount, "USD", - kAMM_ACCOUNT, + kAmmAccount, "JPY", - kAMM_ACCOUNT2, - kAMM_ACCOUNT, - kLP_ISSUE_CURRENCY, - kAMM_ACCOUNT, - kAMM_ACCOUNT2, - kAMM_ACCOUNT, - kAMM_ACCOUNT2, - kLEDGER_HASH + kAmmAccounT2, + kAmmAccount, + kLpIssueCurrency, + kAmmAccount, + kAmmAccounT2, + kAmmAccount, + kAmmAccounT2, + kLedgerHash ) ); diff --git a/tests/unit/rpc/handlers/AccountChannelsTests.cpp b/tests/unit/rpc/handlers/AccountChannelsTests.cpp index 9a517199d..513413938 100644 --- a/tests/unit/rpc/handlers/AccountChannelsTests.cpp +++ b/tests/unit/rpc/handlers/AccountChannelsTests.cpp @@ -23,18 +23,17 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kACCOUNT3 = "rB9BMzh27F3Q6a5FtGPDayQoCCEdiRdqcK"; -constexpr auto kINDEX1 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kINDEX2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; -constexpr auto kTXN_ID = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kAccount3 = "rB9BMzh27F3Q6a5FtGPDayQoCCEdiRdqcK"; +constexpr auto kIndex1 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kIndex2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; +constexpr auto kTxnId = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; } // namespace @@ -49,13 +48,13 @@ TEST_F(RPCAccountChannelsHandlerTest, LimitNotInt) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountChannelsHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": "t" }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -70,13 +69,13 @@ TEST_F(RPCAccountChannelsHandlerTest, LimitNegative) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountChannelsHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": -1 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -91,13 +90,13 @@ TEST_F(RPCAccountChannelsHandlerTest, LimitZero) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountChannelsHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 0 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -112,14 +111,14 @@ TEST_F(RPCAccountChannelsHandlerTest, NonHexLedgerHash) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountChannelsHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 10, "ledger_hash": "xxx" }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -135,14 +134,14 @@ TEST_F(RPCAccountChannelsHandlerTest, NonStringLedgerHash) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountChannelsHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 10, "ledger_hash": 123 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -158,14 +157,14 @@ TEST_F(RPCAccountChannelsHandlerTest, InvalidLedgerIndexString) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountChannelsHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 10, "ledger_index": "notvalidated" }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -181,13 +180,13 @@ TEST_F(RPCAccountChannelsHandlerTest, MarkerNotString) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountChannelsHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": 9 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -206,13 +205,13 @@ TEST_F(RPCAccountChannelsHandlerTest, InvalidMarker) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountChannelsHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": "123invalid" }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -224,13 +223,13 @@ TEST_F(RPCAccountChannelsHandlerTest, InvalidMarker) }); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountChannelsHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": 401 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -246,7 +245,7 @@ TEST_F(RPCAccountChannelsHandlerTest, AccountInvalidFormat) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountChannelsHandler{backend_}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jp" })JSON"); auto const output = handler.process(input, Context{yield}); @@ -262,7 +261,7 @@ TEST_F(RPCAccountChannelsHandlerTest, AccountNotString) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountChannelsHandler{backend_}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "account": 12 })JSON"); auto const output = handler.process(input, Context{yield}); @@ -278,18 +277,18 @@ TEST_F(RPCAccountChannelsHandlerTest, AccountNotString) TEST_F(RPCAccountChannelsHandlerTest, NonExistLedgerViaLedgerHash) { // mock fetchLedgerByHash return empty - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { @@ -308,15 +307,15 @@ TEST_F(RPCAccountChannelsHandlerTest, NonExistLedgerViaLedgerStringIndex) { // mock fetchLedgerBySequence return empty ON_CALL(*backend_, fetchLedgerBySequence) - .WillByDefault(Return(std::optional{})); + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "4" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -333,15 +332,15 @@ TEST_F(RPCAccountChannelsHandlerTest, NonExistLedgerViaLedgerIntIndex) { // mock fetchLedgerBySequence return empty ON_CALL(*backend_, fetchLedgerBySequence) - .WillByDefault(Return(std::optional{})); + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": 4 }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -359,18 +358,18 @@ TEST_F(RPCAccountChannelsHandlerTest, NonExistLedgerViaLedgerIntIndex) TEST_F(RPCAccountChannelsHandlerTest, NonExistLedgerViaLedgerHash2) { // mock fetchLedgerByHash return ledger but seq is 31 > 30 - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 31); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, 31); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { @@ -389,13 +388,13 @@ TEST_F(RPCAccountChannelsHandlerTest, NonExistLedgerViaLedgerIndex2) // no need to check from db,call fetchLedgerBySequence 0 time // differ from previous logic EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(0); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "31" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -411,21 +410,21 @@ TEST_F(RPCAccountChannelsHandlerTest, NonExistLedgerViaLedgerIndex2) // error case account not exist TEST_F(RPCAccountChannelsHandlerTest, NonExistAccount) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // fetch account object return empty ON_CALL(*backend_, doFetchLedgerObject).WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { @@ -441,7 +440,7 @@ TEST_F(RPCAccountChannelsHandlerTest, NonExistAccount) // normal case when only provide account TEST_F(RPCAccountChannelsHandlerTest, DefaultParameterTest) { - static constexpr auto kCORRECT_OUTPUT = R"JSON({ + static constexpr auto kCorrectOutput = R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -471,21 +470,21 @@ TEST_F(RPCAccountChannelsHandlerTest, DefaultParameterTest) ] })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account ON_CALL(*backend_, doFetchLedgerObject(accountKk, testing::_, testing::_)) .WillByDefault(Return(fake)); // return owner index containing 2 indexes - ripple::STObject const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); + xrpl::STObject const ownerDir = + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -493,58 +492,58 @@ TEST_F(RPCAccountChannelsHandlerTest, DefaultParameterTest) // return two payment channel objects std::vector bbs; - ripple::STObject const channel1 = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); + xrpl::STObject const channel1 = + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); bbs.push_back(channel1.getSerializer().peekData()); bbs.push_back(channel1.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { auto handler = AnyHandler{AccountChannelsHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(kCORRECT_OUTPUT), *output.result); + EXPECT_EQ(boost::json::parse(kCorrectOutput), *output.result); }); } // normal case : limit is used TEST_F(RPCAccountChannelsHandlerTest, UseLimit) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(3); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account ON_CALL(*backend_, doFetchLedgerObject(accountKk, testing::_, testing::_)) .WillByDefault(Return(fake)); // return owner index - std::vector indexes; + std::vector indexes; std::vector bbs; auto repetitions = 50; while ((repetitions--) != 0) { - indexes.emplace_back(kINDEX1); - ripple::STObject const channel = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); + indexes.emplace_back(kIndex1); + xrpl::STObject const channel = + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); bbs.push_back(channel.getSerializer().peekData()); } - ripple::STObject ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); + xrpl::STObject ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); // it should not appear in return marker,marker is the current page - ownerDir.setFieldU64(ripple::sfIndexNext, 99); + ownerDir.setFieldU64(xrpl::sfIndexNext, 99); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(7); @@ -554,13 +553,13 @@ TEST_F(RPCAccountChannelsHandlerTest, UseLimit) runSpawn([this](auto yield) { auto handler = AnyHandler{AccountChannelsHandler{this->backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 20 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -575,13 +574,13 @@ TEST_F(RPCAccountChannelsHandlerTest, UseLimit) runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountChannelsHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 9 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -590,13 +589,13 @@ TEST_F(RPCAccountChannelsHandlerTest, UseLimit) runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountChannelsHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 401 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -607,41 +606,41 @@ TEST_F(RPCAccountChannelsHandlerTest, UseLimit) // normal case : destination is used TEST_F(RPCAccountChannelsHandlerTest, UseDestination) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account ON_CALL(*backend_, doFetchLedgerObject(accountKk, testing::_, testing::_)) .WillByDefault(Return(fake)); // return owner index - std::vector indexes; + std::vector indexes; std::vector bbs; // 10 pay channel to Account2 auto repetitions = 10; while ((repetitions--) != 0) { - indexes.emplace_back(kINDEX1); - ripple::STObject const channel = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); + indexes.emplace_back(kIndex1); + xrpl::STObject const channel = + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); bbs.push_back(channel.getSerializer().peekData()); } // 20 pay channel to Account3 repetitions = 20; while ((repetitions--) != 0) { - indexes.emplace_back(kINDEX1); - ripple::STObject const channel = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT3, 100, 10, 32, kTXN_ID, 28); + indexes.emplace_back(kIndex1); + xrpl::STObject const channel = + createPaymentChannelLedgerObject(kAccount, kAccount3, 100, 10, 32, kTxnId, 28); bbs.push_back(channel.getSerializer().peekData()); } - ripple::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); + xrpl::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); @@ -649,15 +648,15 @@ TEST_F(RPCAccountChannelsHandlerTest, UseDestination) ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 30, "destination_account": "{}" }})JSON", - kACCOUNT, - kACCOUNT3 + kAccount, + kAccount3 ) ); runSpawn([&, this](auto yield) { @@ -671,30 +670,30 @@ TEST_F(RPCAccountChannelsHandlerTest, UseDestination) // normal case : but the lines is empty TEST_F(RPCAccountChannelsHandlerTest, EmptyChannel) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account ON_CALL(*backend_, doFetchLedgerObject(accountKk, testing::_, testing::_)) .WillByDefault(Return(fake)); // return owner index - ripple::STObject const ownerDir = createOwnerDirLedgerObject({}, kINDEX1); + xrpl::STObject const ownerDir = createOwnerDirLedgerObject({}, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -708,7 +707,7 @@ TEST_F(RPCAccountChannelsHandlerTest, EmptyChannel) // Return expiration cancel_offer source_tag destination_tag when available TEST_F(RPCAccountChannelsHandlerTest, OptionalResponseField) { - static constexpr auto kCORRECT_OUTPUT = R"JSON({ + static constexpr auto kCorrectOutput = R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -746,21 +745,21 @@ TEST_F(RPCAccountChannelsHandlerTest, OptionalResponseField) ] })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account ON_CALL(*backend_, doFetchLedgerObject(accountKk, testing::_, testing::_)) .WillByDefault(Return(fake)); // return owner index - ripple::STObject const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); + xrpl::STObject const ownerDir = + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -768,42 +767,42 @@ TEST_F(RPCAccountChannelsHandlerTest, OptionalResponseField) // return two payment channel objects std::vector bbs; - ripple::STObject channel1 = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); - channel1.setFieldU32(ripple::sfExpiration, 100); - channel1.setFieldU32(ripple::sfCancelAfter, 200); - channel1.setFieldU32(ripple::sfSourceTag, 300); - channel1.setFieldU32(ripple::sfDestinationTag, 400); + xrpl::STObject channel1 = + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); + channel1.setFieldU32(xrpl::sfExpiration, 100); + channel1.setFieldU32(xrpl::sfCancelAfter, 200); + channel1.setFieldU32(xrpl::sfSourceTag, 300); + channel1.setFieldU32(xrpl::sfDestinationTag, 400); bbs.push_back(channel1.getSerializer().peekData()); bbs.push_back(channel1.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { auto handler = AnyHandler{AccountChannelsHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(kCORRECT_OUTPUT), *output.result); + EXPECT_EQ(boost::json::parse(kCorrectOutput), *output.result); }); } // normal case : test marker output correct TEST_F(RPCAccountChannelsHandlerTest, MarkerOutput) { - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto ownerDirKk = ripple::keylet::ownerDir(account).key; - static constexpr auto kNEXT_PAGE = 99; - static constexpr auto kLIMIT = 15; - auto ownerDir2Kk = ripple::keylet::page(ripple::keylet::ownerDir(account), kNEXT_PAGE).key; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto ownerDirKk = xrpl::keylet::ownerDir(account).key; + static constexpr auto kNextPage = 99; + static constexpr auto kLimit = 15; + auto ownerDir2Kk = xrpl::keylet::page(xrpl::keylet::ownerDir(account), kNextPage).key; + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something @@ -813,14 +812,14 @@ TEST_F(RPCAccountChannelsHandlerTest, MarkerOutput) EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); std::vector bbs; - ripple::STObject const channel1 = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); + xrpl::STObject const channel1 = + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); // owner dir contains 10 indexes int objectsCount = 10; - std::vector indexes; + std::vector indexes; while (objectsCount != 0) { // return owner index - indexes.emplace_back(kINDEX1); + indexes.emplace_back(kIndex1); objectsCount--; } // return 15 objects @@ -830,28 +829,28 @@ TEST_F(RPCAccountChannelsHandlerTest, MarkerOutput) objectsCount--; } - ripple::STObject ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); - ownerDir.setFieldU64(ripple::sfIndexNext, kNEXT_PAGE); + xrpl::STObject ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); + ownerDir.setFieldU64(xrpl::sfIndexNext, kNextPage); // first page 's next page is 99 ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); - ripple::STObject ownerDir2 = createOwnerDirLedgerObject(indexes, kINDEX1); + xrpl::STObject ownerDir2 = createOwnerDirLedgerObject(indexes, kIndex1); // second page's next page is 0 - ownerDir2.setFieldU64(ripple::sfIndexNext, 0); + ownerDir2.setFieldU64(xrpl::sfIndexNext, 0); ON_CALL(*backend_, doFetchLedgerObject(ownerDir2Kk, testing::_, testing::_)) .WillByDefault(Return(ownerDir2.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - kLIMIT + kAccount, + kLimit ) ); runSpawn([&, this](auto yield) { @@ -860,7 +859,7 @@ TEST_F(RPCAccountChannelsHandlerTest, MarkerOutput) ASSERT_TRUE(output); EXPECT_EQ( boost::json::value_to(output.result->as_object().at("marker")), - fmt::format("{},{}", kINDEX1, kNEXT_PAGE) + fmt::format("{},{}", kIndex1, kNextPage) ); EXPECT_EQ(output.result->as_object().at("channels").as_array().size(), 15); }); @@ -869,12 +868,12 @@ TEST_F(RPCAccountChannelsHandlerTest, MarkerOutput) // normal case : handler marker correctly TEST_F(RPCAccountChannelsHandlerTest, MarkerInput) { - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - static constexpr auto kNEXT_PAGE = 99; - static constexpr auto kLIMIT = 15; - auto ownerDirKk = ripple::keylet::page(ripple::keylet::ownerDir(account), kNEXT_PAGE).key; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + static constexpr auto kNextPage = 99; + static constexpr auto kLimit = 15; + auto ownerDirKk = xrpl::keylet::page(xrpl::keylet::ownerDir(account), kNextPage).key; + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something @@ -884,36 +883,36 @@ TEST_F(RPCAccountChannelsHandlerTest, MarkerInput) EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); std::vector bbs; - ripple::STObject const channel1 = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); - int objectsCount = kLIMIT; - std::vector indexes; + xrpl::STObject const channel1 = + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); + int objectsCount = kLimit; + std::vector indexes; while (objectsCount != 0) { // return owner index - indexes.emplace_back(kINDEX1); + indexes.emplace_back(kIndex1); bbs.push_back(channel1.getSerializer().peekData()); objectsCount--; } - ripple::STObject ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); - ownerDir.setFieldU64(ripple::sfIndexNext, 0); + xrpl::STObject ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); + ownerDir.setFieldU64(xrpl::sfIndexNext, 0); ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {}, "marker": "{},{}" }})JSON", - kACCOUNT, - kLIMIT, - kINDEX1, - kNEXT_PAGE + kAccount, + kLimit, + kIndex1, + kNextPage ) ); runSpawn([&, this](auto yield) { @@ -923,27 +922,27 @@ TEST_F(RPCAccountChannelsHandlerTest, MarkerInput) EXPECT_TRUE(output.result->as_object().if_contains("marker") == nullptr); // the first item is the marker itself, so the result will have limit-1 // items - EXPECT_EQ(output.result->as_object().at("channels").as_array().size(), kLIMIT - 1); + EXPECT_EQ(output.result->as_object().at("channels").as_array().size(), kLimit - 1); }); } TEST_F(RPCAccountChannelsHandlerTest, LimitLessThanMin) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account ON_CALL(*backend_, doFetchLedgerObject(accountKk, testing::_, testing::_)) .WillByDefault(Return(fake)); // return owner index containing 2 indexes - ripple::STObject const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); + xrpl::STObject const ownerDir = + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -951,21 +950,21 @@ TEST_F(RPCAccountChannelsHandlerTest, LimitLessThanMin) // return two payment channel objects std::vector bbs; - ripple::STObject const channel1 = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); + xrpl::STObject const channel1 = + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); bbs.push_back(channel1.getSerializer().peekData()); bbs.push_back(channel1.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountChannelsHandler::kLIMIT_MIN - 1 + kAccount, + AccountChannelsHandler::kLimitMin - 1 ) ); runSpawn([&, this](auto yield) { @@ -974,28 +973,28 @@ TEST_F(RPCAccountChannelsHandlerTest, LimitLessThanMin) ASSERT_TRUE(output); EXPECT_EQ(output.result->as_object().at("channels").as_array().size(), 2); EXPECT_EQ( - output.result->as_object().at("limit").as_uint64(), AccountChannelsHandler::kLIMIT_MIN + output.result->as_object().at("limit").as_uint64(), AccountChannelsHandler::kLimitMin ); }); } TEST_F(RPCAccountChannelsHandlerTest, LimitMoreThanMax) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account ON_CALL(*backend_, doFetchLedgerObject(accountKk, testing::_, testing::_)) .WillByDefault(Return(fake)); // return owner index containing 2 indexes - ripple::STObject const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); + xrpl::STObject const ownerDir = + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -1003,21 +1002,21 @@ TEST_F(RPCAccountChannelsHandlerTest, LimitMoreThanMax) // return two payment channel objects std::vector bbs; - ripple::STObject const channel1 = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); + xrpl::STObject const channel1 = + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); bbs.push_back(channel1.getSerializer().peekData()); bbs.push_back(channel1.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountChannelsHandler::kLIMIT_MAX + 1 + kAccount, + AccountChannelsHandler::kLimitMax + 1 ) ); runSpawn([&, this](auto yield) { @@ -1026,7 +1025,7 @@ TEST_F(RPCAccountChannelsHandlerTest, LimitMoreThanMax) ASSERT_TRUE(output); EXPECT_EQ(output.result->as_object().at("channels").as_array().size(), 2); EXPECT_EQ( - output.result->as_object().at("limit").as_uint64(), AccountChannelsHandler::kLIMIT_MAX + output.result->as_object().at("limit").as_uint64(), AccountChannelsHandler::kLimitMax ); }); } diff --git a/tests/unit/rpc/handlers/AccountCurrenciesTests.cpp b/tests/unit/rpc/handlers/AccountCurrenciesTests.cpp index 614d739ce..8220331d5 100644 --- a/tests/unit/rpc/handlers/AccountCurrenciesTests.cpp +++ b/tests/unit/rpc/handlers/AccountCurrenciesTests.cpp @@ -24,17 +24,15 @@ using namespace rpc; using namespace data; using namespace testing; -namespace json = boost::json; - namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kISSUER = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kINDEX1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; -constexpr auto kINDEX2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kTXN_ID = "E3FE6EA3D48F0C2B639448020EA4F03D4F4F8FFDB243A852A0F59177921B4879"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kIssuer = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kIndex1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; +constexpr auto kIndex2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kTxnId = "E3FE6EA3D48F0C2B639448020EA4F03D4F4F8FFDB243A852A0F59177921B4879"; } // namespace @@ -47,24 +45,24 @@ struct RPCAccountCurrenciesHandlerTest : HandlerBaseTest { TEST_F(RPCAccountCurrenciesHandlerTest, AccountNotExist) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); ON_CALL(*backend_, doFetchLedgerObject).WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountCurrenciesHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "actNotFound"); @@ -77,19 +75,19 @@ TEST_F(RPCAccountCurrenciesHandlerTest, LedgerNonExistViaIntSequence) EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return empty ledgerHeader ON_CALL(*backend_, fetchLedgerBySequence(30, _)) - .WillByDefault(Return(std::optional{})); + .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountCurrenciesHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -99,26 +97,26 @@ TEST_F(RPCAccountCurrenciesHandlerTest, LedgerNonExistViaIntSequence) TEST_F(RPCAccountCurrenciesHandlerTest, LedgerNonExistViaStringSequence) { - constexpr auto kSEQ = 12; + constexpr auto kSeq = 12; EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return empty ledgerHeader ON_CALL(*backend_, fetchLedgerBySequence(12, _)) - .WillByDefault(Return(std::optional{})); + .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "{}" }})JSON", - kACCOUNT, - kSEQ + kAccount, + kSeq ) ); auto const handler = AnyHandler{AccountCurrenciesHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -130,22 +128,22 @@ TEST_F(RPCAccountCurrenciesHandlerTest, LedgerNonExistViaHash) { EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // return empty ledgerHeader - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); auto const handler = AnyHandler{AccountCurrenciesHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -155,7 +153,7 @@ TEST_F(RPCAccountCurrenciesHandlerTest, LedgerNonExistViaHash) TEST_F(RPCAccountCurrenciesHandlerTest, DefaultParameter) { - static constexpr auto kOUTPUT = R"JSON({ + static constexpr auto kOutput = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, "validated": true, @@ -170,18 +168,18 @@ TEST_F(RPCAccountCurrenciesHandlerTest, DefaultParameter) })JSON"; // return valid ledgerHeader - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence(30, _)).WillByDefault(Return(ledgerHeader)); // return valid account - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); auto const ownerDir = createOwnerDirLedgerObject( - {ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}, ripple::uint256{kINDEX2}}, kINDEX1 + {xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}, xrpl::uint256{kIndex2}}, kIndex1 ); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); @@ -189,17 +187,17 @@ TEST_F(RPCAccountCurrenciesHandlerTest, DefaultParameter) // Account can receive USD 10 from Account2 and send USD 20 to Account2, now // the balance is 100, Account can only send USD to Account2 auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); // Account2 can receive JPY 10 from Account and send JPY 20 to Account, now // the balance is 100, Account2 can only send JPY to Account auto const line2 = createRippleStateLedgerObject( - "JPY", kISSUER, 100, kACCOUNT2, 10, kACCOUNT, 20, kTXN_ID, 123, 0 + "JPY", kIssuer, 100, kAccount2, 10, kAccount, 20, kTxnId, 123, 0 ); // Account can receive EUR 10 from Account and send EUR 20 to Account2, now // the balance is 8, Account can receive/send EUR to/from Account2 auto const line3 = createRippleStateLedgerObject( - "EUR", kISSUER, 8, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "EUR", kIssuer, 8, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); std::vector bbs; bbs.push_back(line1.getSerializer().peekData()); @@ -208,60 +206,60 @@ TEST_F(RPCAccountCurrenciesHandlerTest, DefaultParameter) ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountCurrenciesHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kOUTPUT)); + EXPECT_EQ(*output.result, boost::json::parse(kOutput)); }); } TEST_F(RPCAccountCurrenciesHandlerTest, RequestViaLegderHash) { // return valid ledgerHeader - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); // return valid account - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - auto const ownerDir = createOwnerDirLedgerObject({ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; + auto const ownerDir = createOwnerDirLedgerObject({xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); std::vector bbs; auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); bbs.push_back(line1.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); auto const handler = AnyHandler{AccountCurrenciesHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); }); } @@ -270,40 +268,40 @@ TEST_F(RPCAccountCurrenciesHandlerTest, RequestViaLegderSeq) { auto const ledgerSeq = 29; // return valid ledgerHeader - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, ledgerSeq); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, ledgerSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence(ledgerSeq, _)).WillByDefault(Return(ledgerHeader)); // return valid account - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, ledgerSeq, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - auto const ownerDir = createOwnerDirLedgerObject({ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; + auto const ownerDir = createOwnerDirLedgerObject({xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, ledgerSeq, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); std::vector bbs; auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); bbs.push_back(line1.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": {} }})JSON", - kACCOUNT, + kAccount, ledgerSeq ) ); auto const handler = AnyHandler{AccountCurrenciesHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), ledgerSeq); }); diff --git a/tests/unit/rpc/handlers/AccountInfoTests.cpp b/tests/unit/rpc/handlers/AccountInfoTests.cpp index cc471dd7d..481e2c705 100644 --- a/tests/unit/rpc/handlers/AccountInfoTests.cpp +++ b/tests/unit/rpc/handlers/AccountInfoTests.cpp @@ -26,16 +26,15 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT1 = "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kINDEX1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount1 = "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kIndex1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; } // namespace @@ -129,7 +128,7 @@ INSTANTIATE_TEST_CASE_P( RPCAccountInfoGroup1, AccountInfoParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(AccountInfoParameterTest, InvalidParams) @@ -137,7 +136,7 @@ TEST_P(AccountInfoParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{.yield = yield, .apiVersion = 2}); ASSERT_FALSE(output); @@ -149,7 +148,7 @@ TEST_P(AccountInfoParameterTest, InvalidParams) TEST_F(AccountInfoParameterTest, ApiV1SignerListIsNotBool) { - static constexpr auto kREQ_JSON = R"JSON( + static constexpr auto kReqJson = R"JSON( {"ident": "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun", "signer_lists": 1} )JSON"; @@ -157,7 +156,7 @@ TEST_F(AccountInfoParameterTest, ApiV1SignerListIsNotBool) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse(kREQ_JSON); + auto const req = boost::json::parse(kReqJson); auto const output = handler.process(req, Context{.yield = yield, .apiVersion = 1}); ASSERT_FALSE(output); @@ -171,20 +170,20 @@ TEST_F(RPCAccountInfoHandlerTest, LedgerNonExistViaIntSequence) { // return empty ledgerHeader EXPECT_CALL(*backend_, fetchLedgerBySequence(30, _)) - .WillOnce(Return(std::optional{})); + .WillOnce(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": 30 }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -197,18 +196,18 @@ TEST_F(RPCAccountInfoHandlerTest, LedgerNonExistViaStringSequence) // return empty ledgerHeader EXPECT_CALL(*backend_, fetchLedgerBySequence(30, _)).WillOnce(Return(std::nullopt)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "30" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -219,22 +218,22 @@ TEST_F(RPCAccountInfoHandlerTest, LedgerNonExistViaStringSequence) TEST_F(RPCAccountInfoHandlerTest, LedgerNonExistViaHash) { // return empty ledgerHeader - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillOnce(Return(std::optional{})); + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillOnce(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -244,23 +243,23 @@ TEST_F(RPCAccountInfoHandlerTest, LedgerNonExistViaHash) TEST_F(RPCAccountInfoHandlerTest, AccountNotExist) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); ON_CALL(*backend_, doFetchLedgerObject).WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, doFetchLedgerObject); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "actNotFound"); @@ -270,7 +269,7 @@ TEST_F(RPCAccountInfoHandlerTest, AccountNotExist) TEST_F(RPCAccountInfoHandlerTest, AccountInvalid) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); // return a valid ledger object but not account root @@ -278,17 +277,17 @@ TEST_F(RPCAccountInfoHandlerTest, AccountInvalid) .WillByDefault(Return(createLegacyFeeSettingBlob(1, 2, 3, 4, 0))); EXPECT_CALL(*backend_, doFetchLedgerObject); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "dbDeserialization"); @@ -298,15 +297,15 @@ TEST_F(RPCAccountInfoHandlerTest, AccountInvalid) TEST_F(RPCAccountInfoHandlerTest, SignerListsInvalid) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const accountRoot = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const accountRoot = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) .WillByDefault(Return(accountRoot.getSerializer().peekData())); - auto signersKey = ripple::keylet::signers(account).key; + auto signersKey = xrpl::keylet::signerList(account).key; ON_CALL(*backend_, doFetchLedgerObject(signersKey, 30, _)) .WillByDefault(Return(createLegacyFeeSettingBlob(1, 2, 3, 4, 0))); EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(_, Amendments::DisallowIncoming, _)) @@ -317,18 +316,18 @@ TEST_F(RPCAccountInfoHandlerTest, SignerListsInvalid) .WillOnce(Return(false)); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "signer_lists": true }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "dbDeserialization"); @@ -393,25 +392,25 @@ TEST_F(RPCAccountInfoHandlerTest, SignerListsTrueV2) "ledger_index": 30, "validated": true }})JSON", - kACCOUNT, - kINDEX1, - kACCOUNT1, - kACCOUNT2, - kLEDGER_HASH + kAccount, + kIndex1, + kAccount1, + kAccount2, + kLedgerHash ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const accountRoot = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const accountRoot = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) .WillByDefault(Return(accountRoot.getSerializer().peekData())); - auto signersKey = ripple::keylet::signers(account).key; + auto signersKey = xrpl::keylet::signerList(account).key; ON_CALL(*backend_, doFetchLedgerObject(signersKey, 30, _)) .WillByDefault( - Return(createSignerLists({{kACCOUNT1, 1}, {kACCOUNT2, 1}}).getSerializer().peekData()) + Return(createSignerLists({{kAccount1, 1}, {kAccount2, 1}}).getSerializer().peekData()) ); EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(_, Amendments::DisallowIncoming, _)) .WillOnce(Return(false)); @@ -421,20 +420,20 @@ TEST_F(RPCAccountInfoHandlerTest, SignerListsTrueV2) .WillOnce(Return(false)); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "signer_lists": true }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{.yield = yield, .apiVersion = 2}); + auto const output = handler.process(kInput, Context{.yield = yield, .apiVersion = 2}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(expectedOutput)); + EXPECT_EQ(*output.result, boost::json::parse(expectedOutput)); }); } @@ -495,25 +494,25 @@ TEST_F(RPCAccountInfoHandlerTest, SignerListsTrueV1) "ledger_index": 30, "validated": true }})JSON", - kACCOUNT, - kINDEX1, - kACCOUNT1, - kACCOUNT2, - kLEDGER_HASH + kAccount, + kIndex1, + kAccount1, + kAccount2, + kLedgerHash ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const accountRoot = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const accountRoot = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) .WillByDefault(Return(accountRoot.getSerializer().peekData())); - auto signersKey = ripple::keylet::signers(account).key; + auto signersKey = xrpl::keylet::signerList(account).key; ON_CALL(*backend_, doFetchLedgerObject(signersKey, 30, _)) .WillByDefault( - Return(createSignerLists({{kACCOUNT1, 1}, {kACCOUNT2, 1}}).getSerializer().peekData()) + Return(createSignerLists({{kAccount1, 1}, {kAccount2, 1}}).getSerializer().peekData()) ); EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(_, Amendments::DisallowIncoming, _)) .WillOnce(Return(false)); @@ -523,20 +522,20 @@ TEST_F(RPCAccountInfoHandlerTest, SignerListsTrueV1) .WillOnce(Return(false)); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "signer_lists": true }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{.yield = yield, .apiVersion = 1}); + auto const output = handler.process(kInput, Context{.yield = yield, .apiVersion = 1}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(expectedOutput)); + EXPECT_EQ(*output.result, boost::json::parse(expectedOutput)); }); } @@ -571,25 +570,25 @@ TEST_F(RPCAccountInfoHandlerTest, Flags) "ledger_index": 30, "validated": true }})JSON", - kACCOUNT, - kINDEX1, - kLEDGER_HASH + kAccount, + kIndex1, + kLedgerHash ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; auto const accountRoot = createAccountRootObject( - kACCOUNT, - ripple::lsfDefaultRipple | ripple::lsfGlobalFreeze | ripple::lsfRequireDestTag | - ripple::lsfRequireAuth | ripple::lsfDepositAuth | ripple::lsfDisableMaster | - ripple::lsfDisallowXRP | ripple::lsfNoFreeze | ripple::lsfPasswordSpent, + kAccount, + xrpl::lsfDefaultRipple | xrpl::lsfGlobalFreeze | xrpl::lsfRequireDestTag | + xrpl::lsfRequireAuth | xrpl::lsfDepositAuth | xrpl::lsfDisableMaster | + xrpl::lsfDisallowXRP | xrpl::lsfNoFreeze | xrpl::lsfPasswordSpent, 2, 200, 2, - kINDEX1, + kIndex1, 2 ); ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) @@ -602,30 +601,30 @@ TEST_F(RPCAccountInfoHandlerTest, Flags) .WillOnce(Return(false)); EXPECT_CALL(*backend_, doFetchLedgerObject); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(expectedOutput)); + EXPECT_EQ(*output.result, boost::json::parse(expectedOutput)); }); } TEST_F(RPCAccountInfoHandlerTest, IdentAndSignerListsFalse) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const accountRoot = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const accountRoot = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) .WillByDefault(Return(accountRoot.getSerializer().peekData())); EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(_, Amendments::DisallowIncoming, _)) @@ -636,17 +635,17 @@ TEST_F(RPCAccountInfoHandlerTest, IdentAndSignerListsFalse) .WillOnce(Return(false)); EXPECT_CALL(*backend_, doFetchLedgerObject); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "ident": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_FALSE(output.result->as_object().contains("signer_lists")); }); @@ -654,12 +653,12 @@ TEST_F(RPCAccountInfoHandlerTest, IdentAndSignerListsFalse) TEST_F(RPCAccountInfoHandlerTest, EmptySignerLists) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const accountRoot = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const accountRoot = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) .WillByDefault(Return(accountRoot.getSerializer().peekData())); EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(_, Amendments::DisallowIncoming, _)) @@ -669,27 +668,27 @@ TEST_F(RPCAccountInfoHandlerTest, EmptySignerLists) EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(_, Amendments::TokenEscrow, _)) .WillOnce(Return(false)); - auto signersKey = ripple::keylet::signers(account).key; + auto signersKey = xrpl::keylet::signerList(account).key; ON_CALL(*backend_, doFetchLedgerObject(signersKey, 30, _)) .WillByDefault(Return(std::optional{})); // Once for signer object, once for keylet EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "signer_lists": true }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{.yield = yield, .apiVersion = 2}); + auto const output = handler.process(kInput, Context{.yield = yield, .apiVersion = 2}); ASSERT_TRUE(output); auto const& resultObj = output.result->as_object(); @@ -736,27 +735,27 @@ TEST_F(RPCAccountInfoHandlerTest, DisallowIncoming) "ledger_index": 30, "validated": true }})JSON", - kACCOUNT, - kINDEX1, - kLEDGER_HASH + kAccount, + kIndex1, + kLedgerHash ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; auto const accountRoot = createAccountRootObject( - kACCOUNT, - ripple::lsfDefaultRipple | ripple::lsfGlobalFreeze | ripple::lsfRequireDestTag | - ripple::lsfRequireAuth | ripple::lsfDepositAuth | ripple::lsfDisableMaster | - ripple::lsfDisallowXRP | ripple::lsfNoFreeze | ripple::lsfPasswordSpent | - ripple::lsfDisallowIncomingNFTokenOffer | ripple::lsfDisallowIncomingCheck | - ripple::lsfDisallowIncomingPayChan | ripple::lsfDisallowIncomingTrustline, + kAccount, + xrpl::lsfDefaultRipple | xrpl::lsfGlobalFreeze | xrpl::lsfRequireDestTag | + xrpl::lsfRequireAuth | xrpl::lsfDepositAuth | xrpl::lsfDisableMaster | + xrpl::lsfDisallowXRP | xrpl::lsfNoFreeze | xrpl::lsfPasswordSpent | + xrpl::lsfDisallowIncomingNFTokenOffer | xrpl::lsfDisallowIncomingCheck | + xrpl::lsfDisallowIncomingPayChan | xrpl::lsfDisallowIncomingTrustline, 2, 200, 2, - kINDEX1, + kIndex1, 2 ); ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) @@ -769,19 +768,19 @@ TEST_F(RPCAccountInfoHandlerTest, DisallowIncoming) .WillOnce(Return(false)); EXPECT_CALL(*backend_, doFetchLedgerObject); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(expectedOutput)); + EXPECT_EQ(*output.result, boost::json::parse(expectedOutput)); }); } @@ -818,27 +817,27 @@ TEST_F(RPCAccountInfoHandlerTest, AmendmentsEnabled) "ledger_index": 30, "validated": true }})JSON", - kACCOUNT, - kINDEX1, - kLEDGER_HASH + kAccount, + kIndex1, + kLedgerHash ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; auto const accountRoot = createAccountRootObject( - kACCOUNT, - ripple::lsfDefaultRipple | ripple::lsfGlobalFreeze | ripple::lsfRequireDestTag | - ripple::lsfRequireAuth | ripple::lsfDepositAuth | ripple::lsfDisableMaster | - ripple::lsfDisallowXRP | ripple::lsfNoFreeze | ripple::lsfPasswordSpent | - ripple::lsfAllowTrustLineClawback | ripple::lsfAllowTrustLineLocking, + kAccount, + xrpl::lsfDefaultRipple | xrpl::lsfGlobalFreeze | xrpl::lsfRequireDestTag | + xrpl::lsfRequireAuth | xrpl::lsfDepositAuth | xrpl::lsfDisableMaster | + xrpl::lsfDisallowXRP | xrpl::lsfNoFreeze | xrpl::lsfPasswordSpent | + xrpl::lsfAllowTrustLineClawback | xrpl::lsfAllowTrustLineLocking, 2, 200, 2, - kINDEX1, + kIndex1, 2 ); ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) @@ -851,29 +850,29 @@ TEST_F(RPCAccountInfoHandlerTest, AmendmentsEnabled) .WillOnce(Return(true)); EXPECT_CALL(*backend_, doFetchLedgerObject); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountInfoHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(expectedOutput)); + EXPECT_EQ(*output.result, boost::json::parse(expectedOutput)); }); } TEST(RPCAccountInfoHandlerSpecTest, DeprecatedFields) { boost::json::value const json{ - {"account", kACCOUNT}, - {"ident", kACCOUNT}, + {"account", kAccount}, + {"ident", kAccount}, {"ledger_index", 30}, - {"ledger_hash", kLEDGER_HASH}, + {"ledger_hash", kLedgerHash}, {"ledger", "some"}, {"strict", true} }; diff --git a/tests/unit/rpc/handlers/AccountLinesTests.cpp b/tests/unit/rpc/handlers/AccountLinesTests.cpp index f4fd6500f..d473349cf 100644 --- a/tests/unit/rpc/handlers/AccountLinesTests.cpp +++ b/tests/unit/rpc/handlers/AccountLinesTests.cpp @@ -26,18 +26,17 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kACCOUNT3 = "rB9BMzh27F3Q6a5FtGPDayQoCCEdiRdqcK"; -constexpr auto kINDEX1 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kINDEX2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; -constexpr auto kTXN_ID = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kAccount3 = "rB9BMzh27F3Q6a5FtGPDayQoCCEdiRdqcK"; +constexpr auto kIndex1 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kIndex2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; +constexpr auto kTxnId = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; } // namespace @@ -57,14 +56,14 @@ TEST_F(RPCAccountLinesHandlerTest, NonHexLedgerHash) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 10, "ledger_hash": "xxx" }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -80,14 +79,14 @@ TEST_F(RPCAccountLinesHandlerTest, NonStringLedgerHash) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 10, "ledger_hash": 123 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -103,14 +102,14 @@ TEST_F(RPCAccountLinesHandlerTest, InvalidLedgerIndexString) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 10, "ledger_index": "notvalidated" }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -126,13 +125,13 @@ TEST_F(RPCAccountLinesHandlerTest, MarkerNotString) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": 9 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -151,13 +150,13 @@ TEST_F(RPCAccountLinesHandlerTest, InvalidMarker) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": "123invalid" }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -169,13 +168,13 @@ TEST_F(RPCAccountLinesHandlerTest, InvalidMarker) }); runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": 401 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -191,7 +190,7 @@ TEST_F(RPCAccountLinesHandlerTest, AccountInvalidFormat) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jp" })JSON" @@ -209,7 +208,7 @@ TEST_F(RPCAccountLinesHandlerTest, AccountNotString) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( R"JSON({ "account": 12 })JSON" @@ -227,7 +226,7 @@ TEST_F(RPCAccountLinesHandlerTest, PeerInvalidFormat) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "peer": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jp" @@ -245,7 +244,7 @@ TEST_F(RPCAccountLinesHandlerTest, PeerNotString) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "peer": 12 @@ -264,7 +263,7 @@ TEST_F(RPCAccountLinesHandlerTest, LimitNotInt) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "limit": "t" @@ -282,7 +281,7 @@ TEST_F(RPCAccountLinesHandlerTest, LimitNegative) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "limit": -1 @@ -300,7 +299,7 @@ TEST_F(RPCAccountLinesHandlerTest, LimitZero) { runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "limit": 0 @@ -318,18 +317,18 @@ TEST_F(RPCAccountLinesHandlerTest, LimitZero) TEST_F(RPCAccountLinesHandlerTest, NonExistLedgerViaLedgerHash) { // mock fetchLedgerByHash return empty - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { @@ -348,15 +347,15 @@ TEST_F(RPCAccountLinesHandlerTest, NonExistLedgerViaLedgerStringIndex) { // mock fetchLedgerBySequence return empty ON_CALL(*backend_, fetchLedgerBySequence) - .WillByDefault(Return(std::optional{})); + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "4" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -373,15 +372,15 @@ TEST_F(RPCAccountLinesHandlerTest, NonExistLedgerViaLedgerIntIndex) { // mock fetchLedgerBySequence return empty ON_CALL(*backend_, fetchLedgerBySequence) - .WillByDefault(Return(std::optional{})); + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": 4 }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -399,18 +398,18 @@ TEST_F(RPCAccountLinesHandlerTest, NonExistLedgerViaLedgerIntIndex) TEST_F(RPCAccountLinesHandlerTest, NonExistLedgerViaLedgerHash2) { // mock fetchLedgerByHash return ledger but seq is 31 > 30 - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 31); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, 31); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { @@ -429,13 +428,13 @@ TEST_F(RPCAccountLinesHandlerTest, NonExistLedgerViaLedgerIndex2) // no need to check from db, call fetchLedgerBySequence 0 time // differ from previous logic EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(0); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "31" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -451,21 +450,21 @@ TEST_F(RPCAccountLinesHandlerTest, NonExistLedgerViaLedgerIndex2) // error case account not exist TEST_F(RPCAccountLinesHandlerTest, NonExistAccount) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // fetch account object return empty ON_CALL(*backend_, doFetchLedgerObject).WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { @@ -481,21 +480,21 @@ TEST_F(RPCAccountLinesHandlerTest, NonExistAccount) // normal case when only provide account TEST_F(RPCAccountLinesHandlerTest, DefaultParameterTest) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account ON_CALL(*backend_, doFetchLedgerObject(accountKk, testing::_, testing::_)) .WillByDefault(Return(fake)); // return owner index containing 2 indexes - ripple::STObject const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); + xrpl::STObject const ownerDir = + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -504,10 +503,10 @@ TEST_F(RPCAccountLinesHandlerTest, DefaultParameterTest) // return two trust lines std::vector bbs; auto const line1 = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); auto const line2 = createRippleStateLedgerObject( - "USD", kACCOUNT, 10, kACCOUNT2, 100, kACCOUNT, 200, kTXN_ID, 123 + "USD", kAccount, 10, kAccount2, 100, kAccount, 200, kTxnId, 123 ); bbs.push_back(line1.getSerializer().peekData()); bbs.push_back(line2.getSerializer().peekData()); @@ -515,12 +514,12 @@ TEST_F(RPCAccountLinesHandlerTest, DefaultParameterTest) EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); runSpawn([this](auto yield) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const correctOutput = @@ -555,40 +554,40 @@ TEST_F(RPCAccountLinesHandlerTest, DefaultParameterTest) auto handler = AnyHandler{AccountLinesHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(correctOutput), *output.result); + EXPECT_EQ(boost::json::parse(correctOutput), *output.result); }); } // normal case : limit is used TEST_F(RPCAccountLinesHandlerTest, UseLimit) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(3); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account ON_CALL(*backend_, doFetchLedgerObject(accountKk, testing::_, testing::_)) .WillByDefault(Return(fake)); // return owner index - std::vector indexes; + std::vector indexes; std::vector bbs; auto repetitions = 50; while ((repetitions--) != 0) { - indexes.emplace_back(kINDEX1); + indexes.emplace_back(kIndex1); auto const line = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); bbs.push_back(line.getSerializer().peekData()); } - ripple::STObject ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); + xrpl::STObject ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); // it should not appear in return marker,marker is the current page - ownerDir.setFieldU64(ripple::sfIndexNext, 99); + ownerDir.setFieldU64(xrpl::sfIndexNext, 99); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(7); @@ -598,13 +597,13 @@ TEST_F(RPCAccountLinesHandlerTest, UseLimit) runSpawn([this](auto yield) { auto handler = AnyHandler{AccountLinesHandler{this->backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 20 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -619,13 +618,13 @@ TEST_F(RPCAccountLinesHandlerTest, UseLimit) runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 9 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -634,13 +633,13 @@ TEST_F(RPCAccountLinesHandlerTest, UseLimit) runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountLinesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 401 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{yield}); @@ -651,28 +650,28 @@ TEST_F(RPCAccountLinesHandlerTest, UseLimit) // normal case : destination is used TEST_F(RPCAccountLinesHandlerTest, UseDestination) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account ON_CALL(*backend_, doFetchLedgerObject(accountKk, testing::_, testing::_)) .WillByDefault(Return(fake)); // return owner index - std::vector indexes; + std::vector indexes; std::vector bbs; // 10 lines to Account2 auto repetitions = 10; while ((repetitions--) != 0) { - indexes.emplace_back(kINDEX1); + indexes.emplace_back(kIndex1); auto const line = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); bbs.push_back(line.getSerializer().peekData()); } @@ -680,14 +679,14 @@ TEST_F(RPCAccountLinesHandlerTest, UseDestination) // 20 lines to Account3 repetitions = 20; while ((repetitions--) != 0) { - indexes.emplace_back(kINDEX1); + indexes.emplace_back(kIndex1); auto const line = createRippleStateLedgerObject( - "USD", kACCOUNT3, 10, kACCOUNT, 100, kACCOUNT3, 200, kTXN_ID, 123 + "USD", kAccount3, 10, kAccount, 100, kAccount3, 200, kTxnId, 123 ); bbs.push_back(line.getSerializer().peekData()); } - ripple::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); + xrpl::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); @@ -695,15 +694,15 @@ TEST_F(RPCAccountLinesHandlerTest, UseDestination) ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 30, "peer": "{}" }})JSON", - kACCOUNT, - kACCOUNT3 + kAccount, + kAccount3 ) ); runSpawn([&, this](auto yield) { @@ -717,30 +716,30 @@ TEST_F(RPCAccountLinesHandlerTest, UseDestination) // normal case : but the lines is empty TEST_F(RPCAccountLinesHandlerTest, EmptyChannel) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account ON_CALL(*backend_, doFetchLedgerObject(accountKk, testing::_, testing::_)) .WillByDefault(Return(fake)); // return owner index - ripple::STObject const ownerDir = createOwnerDirLedgerObject({}, kINDEX1); + xrpl::STObject const ownerDir = createOwnerDirLedgerObject({}, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -753,7 +752,7 @@ TEST_F(RPCAccountLinesHandlerTest, EmptyChannel) TEST_F(RPCAccountLinesHandlerTest, OptionalResponseFieldWithDeepFreeze) { - static constexpr auto kCORRECT_OUTPUT = R"JSON({ + static constexpr auto kCorrectOutput = R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -789,13 +788,13 @@ TEST_F(RPCAccountLinesHandlerTest, OptionalResponseFieldWithDeepFreeze) ] })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account @@ -803,8 +802,8 @@ TEST_F(RPCAccountLinesHandlerTest, OptionalResponseFieldWithDeepFreeze) .WillByDefault(Return(fake)); // return owner index - ripple::STObject const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); + xrpl::STObject const ownerDir = + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -813,44 +812,44 @@ TEST_F(RPCAccountLinesHandlerTest, OptionalResponseFieldWithDeepFreeze) // return few trust lines std::vector bbs; auto line1 = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 0 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 0 ); - line1.setFlag(ripple::lsfHighAuth); - line1.setFlag(ripple::lsfHighNoRipple); - line1.setFlag(ripple::lsfHighFreeze); - line1.setFlag(ripple::lsfHighDeepFreeze); + line1.setFlag(xrpl::lsfHighAuth); + line1.setFlag(xrpl::lsfHighNoRipple); + line1.setFlag(xrpl::lsfHighFreeze); + line1.setFlag(xrpl::lsfHighDeepFreeze); bbs.push_back(line1.getSerializer().peekData()); auto line2 = createRippleStateLedgerObject( - "USD", kACCOUNT2, 20, kACCOUNT, 200, kACCOUNT2, 400, kTXN_ID, 0 + "USD", kAccount2, 20, kAccount, 200, kAccount2, 400, kTxnId, 0 ); - line2.setFlag(ripple::lsfLowAuth); - line2.setFlag(ripple::lsfLowNoRipple); - line2.setFlag(ripple::lsfLowFreeze); - line2.setFlag(ripple::lsfLowDeepFreeze); + line2.setFlag(xrpl::lsfLowAuth); + line2.setFlag(xrpl::lsfLowNoRipple); + line2.setFlag(xrpl::lsfLowFreeze); + line2.setFlag(xrpl::lsfLowDeepFreeze); bbs.push_back(line2.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { auto handler = AnyHandler{AccountLinesHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(kCORRECT_OUTPUT), *output.result); + EXPECT_EQ(boost::json::parse(kCorrectOutput), *output.result); }); } TEST_F(RPCAccountLinesHandlerTest, FrozenTrustLineResponse) { - static constexpr auto kCORRECT_OUTPUT = R"JSON({ + static constexpr auto kCorrectOutput = R"JSON({ "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -882,13 +881,13 @@ TEST_F(RPCAccountLinesHandlerTest, FrozenTrustLineResponse) ] })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account @@ -896,8 +895,8 @@ TEST_F(RPCAccountLinesHandlerTest, FrozenTrustLineResponse) .WillByDefault(Return(fake)); // return owner index - ripple::STObject const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); + xrpl::STObject const ownerDir = + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -905,46 +904,46 @@ TEST_F(RPCAccountLinesHandlerTest, FrozenTrustLineResponse) // return few trust lines std::vector bbs; auto line1 = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 0 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 0 ); - line1.setFlag(ripple::lsfHighAuth); - line1.setFlag(ripple::lsfHighFreeze); + line1.setFlag(xrpl::lsfHighAuth); + line1.setFlag(xrpl::lsfHighFreeze); bbs.push_back(line1.getSerializer().peekData()); auto line2 = createRippleStateLedgerObject( - "USD", kACCOUNT2, 20, kACCOUNT, 200, kACCOUNT2, 400, kTXN_ID, 0 + "USD", kAccount2, 20, kAccount, 200, kAccount2, 400, kTxnId, 0 ); - line2.setFlag(ripple::lsfLowAuth); - line2.setFlag(ripple::lsfLowFreeze); + line2.setFlag(xrpl::lsfLowAuth); + line2.setFlag(xrpl::lsfLowFreeze); bbs.push_back(line2.getSerializer().peekData()); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { auto handler = AnyHandler{AccountLinesHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(kCORRECT_OUTPUT), *output.result); + EXPECT_EQ(boost::json::parse(kCorrectOutput), *output.result); }); } // normal case : test marker output correct TEST_F(RPCAccountLinesHandlerTest, MarkerOutput) { - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto ownerDirKk = ripple::keylet::ownerDir(account).key; - static constexpr auto kNEXT_PAGE = 99; - static constexpr auto kLIMIT = 15; - auto ownerDir2Kk = ripple::keylet::page(ripple::keylet::ownerDir(account), kNEXT_PAGE).key; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto ownerDirKk = xrpl::keylet::ownerDir(account).key; + static constexpr auto kNextPage = 99; + static constexpr auto kLimit = 15; + auto ownerDir2Kk = xrpl::keylet::page(xrpl::keylet::ownerDir(account), kNextPage).key; + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something @@ -955,15 +954,15 @@ TEST_F(RPCAccountLinesHandlerTest, MarkerOutput) std::vector bbs; auto line = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 0 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 0 ); // owner dir contains 10 indexes int objectsCount = 10; - std::vector indexes; + std::vector indexes; while (objectsCount != 0) { // return owner index - indexes.emplace_back(kINDEX1); + indexes.emplace_back(kIndex1); objectsCount--; } // return 15 objects @@ -973,28 +972,28 @@ TEST_F(RPCAccountLinesHandlerTest, MarkerOutput) objectsCount--; } - ripple::STObject ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); - ownerDir.setFieldU64(ripple::sfIndexNext, kNEXT_PAGE); + xrpl::STObject ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); + ownerDir.setFieldU64(xrpl::sfIndexNext, kNextPage); // first page's next page is 99 ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); - ripple::STObject ownerDir2 = createOwnerDirLedgerObject(indexes, kINDEX1); + xrpl::STObject ownerDir2 = createOwnerDirLedgerObject(indexes, kIndex1); // second page's next page is 0 - ownerDir2.setFieldU64(ripple::sfIndexNext, 0); + ownerDir2.setFieldU64(xrpl::sfIndexNext, 0); ON_CALL(*backend_, doFetchLedgerObject(ownerDir2Kk, testing::_, testing::_)) .WillByDefault(Return(ownerDir2.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - kLIMIT + kAccount, + kLimit ) ); runSpawn([&, this](auto yield) { @@ -1003,7 +1002,7 @@ TEST_F(RPCAccountLinesHandlerTest, MarkerOutput) ASSERT_TRUE(output); EXPECT_EQ( boost::json::value_to(output.result->as_object().at("marker")), - fmt::format("{},{}", kINDEX1, kNEXT_PAGE) + fmt::format("{},{}", kIndex1, kNextPage) ); EXPECT_EQ(output.result->as_object().at("lines").as_array().size(), 15); }); @@ -1012,12 +1011,12 @@ TEST_F(RPCAccountLinesHandlerTest, MarkerOutput) // normal case : handler marker correctly TEST_F(RPCAccountLinesHandlerTest, MarkerInput) { - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - static constexpr auto kNEXT_PAGE = 99; - static constexpr auto kLIMIT = 15; - auto ownerDirKk = ripple::keylet::page(ripple::keylet::ownerDir(account), kNEXT_PAGE).key; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + static constexpr auto kNextPage = 99; + static constexpr auto kLimit = 15; + auto ownerDirKk = xrpl::keylet::page(xrpl::keylet::ownerDir(account), kNextPage).key; + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something @@ -1028,36 +1027,36 @@ TEST_F(RPCAccountLinesHandlerTest, MarkerInput) std::vector bbs; auto const line = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 0 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 0 ); - int objectsCount = kLIMIT; - std::vector indexes; + int objectsCount = kLimit; + std::vector indexes; while (objectsCount != 0) { // return owner index - indexes.emplace_back(kINDEX1); + indexes.emplace_back(kIndex1); bbs.push_back(line.getSerializer().peekData()); objectsCount--; } - ripple::STObject ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); - ownerDir.setFieldU64(ripple::sfIndexNext, 0); + xrpl::STObject ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); + ownerDir.setFieldU64(xrpl::sfIndexNext, 0); ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {}, "marker": "{},{}" }})JSON", - kACCOUNT, - kLIMIT, - kINDEX1, - kNEXT_PAGE + kAccount, + kLimit, + kIndex1, + kNextPage ) ); runSpawn([&, this](auto yield) { @@ -1067,27 +1066,27 @@ TEST_F(RPCAccountLinesHandlerTest, MarkerInput) EXPECT_TRUE(output.result->as_object().if_contains("marker") == nullptr); // the first item is the marker itself, so the result will have limit-1 // items - EXPECT_EQ(output.result->as_object().at("lines").as_array().size(), kLIMIT - 1); + EXPECT_EQ(output.result->as_object().at("lines").as_array().size(), kLimit - 1); }); } TEST_F(RPCAccountLinesHandlerTest, LimitLessThanMin) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account ON_CALL(*backend_, doFetchLedgerObject(accountKk, testing::_, testing::_)) .WillByDefault(Return(fake)); // return owner index containing 2 indexes - ripple::STObject const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); + xrpl::STObject const ownerDir = + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -1096,10 +1095,10 @@ TEST_F(RPCAccountLinesHandlerTest, LimitLessThanMin) // return two trust lines std::vector bbs; auto const line1 = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); auto const line2 = createRippleStateLedgerObject( - "USD", kACCOUNT, 10, kACCOUNT2, 100, kACCOUNT, 200, kTXN_ID, 123 + "USD", kAccount, 10, kAccount2, 100, kAccount, 200, kTxnId, 123 ); bbs.push_back(line1.getSerializer().peekData()); bbs.push_back(line2.getSerializer().peekData()); @@ -1107,14 +1106,14 @@ TEST_F(RPCAccountLinesHandlerTest, LimitLessThanMin) EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); runSpawn([this](auto yield) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountLinesHandler::kLIMIT_MIN - 1 + kAccount, + AccountLinesHandler::kLimitMin - 1 ) ); auto const correctOutput = fmt::format( @@ -1145,33 +1144,33 @@ TEST_F(RPCAccountLinesHandlerTest, LimitLessThanMin) }} ] }})JSON", - AccountLinesHandler::kLIMIT_MIN + AccountLinesHandler::kLimitMin ); auto handler = AnyHandler{AccountLinesHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(correctOutput), *output.result); + EXPECT_EQ(boost::json::parse(correctOutput), *output.result); }); } TEST_F(RPCAccountLinesHandlerTest, LimitMoreThanMax) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch account object return something - auto account = getAccountIdWithString(kACCOUNT); - auto accountKk = ripple::keylet::account(account).key; - auto owneDirKk = ripple::keylet::ownerDir(account).key; + auto account = getAccountIdWithString(kAccount); + auto accountKk = xrpl::keylet::account(account).key; + auto owneDirKk = xrpl::keylet::ownerDir(account).key; auto fake = Blob{'f', 'a', 'k', 'e'}; // return a non empty account ON_CALL(*backend_, doFetchLedgerObject(accountKk, testing::_, testing::_)) .WillByDefault(Return(fake)); // return owner index containing 2 indexes - ripple::STObject const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); + xrpl::STObject const ownerDir = + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -1180,10 +1179,10 @@ TEST_F(RPCAccountLinesHandlerTest, LimitMoreThanMax) // return two trust lines std::vector bbs; auto const line1 = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); auto const line2 = createRippleStateLedgerObject( - "USD", kACCOUNT, 10, kACCOUNT2, 100, kACCOUNT, 200, kTXN_ID, 123 + "USD", kAccount, 10, kAccount2, 100, kAccount, 200, kTxnId, 123 ); bbs.push_back(line1.getSerializer().peekData()); bbs.push_back(line2.getSerializer().peekData()); @@ -1191,14 +1190,14 @@ TEST_F(RPCAccountLinesHandlerTest, LimitMoreThanMax) EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); runSpawn([this](auto yield) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountLinesHandler::kLIMIT_MAX + 1 + kAccount, + AccountLinesHandler::kLimitMax + 1 ) ); auto const correctOutput = fmt::format( @@ -1229,13 +1228,13 @@ TEST_F(RPCAccountLinesHandlerTest, LimitMoreThanMax) }} ] }})JSON", - AccountLinesHandler::kLIMIT_MAX + AccountLinesHandler::kLimitMax ); auto handler = AnyHandler{AccountLinesHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(correctOutput), *output.result); + EXPECT_EQ(boost::json::parse(correctOutput), *output.result); }); } diff --git a/tests/unit/rpc/handlers/AccountMPTokenIssuancesTests.cpp b/tests/unit/rpc/handlers/AccountMPTokenIssuancesTests.cpp index 1421c5086..4ec2575ff 100644 --- a/tests/unit/rpc/handlers/AccountMPTokenIssuancesTests.cpp +++ b/tests/unit/rpc/handlers/AccountMPTokenIssuancesTests.cpp @@ -21,6 +21,7 @@ #include #include +#include #include #include #include @@ -29,63 +30,60 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kISSUANCE_INDEX1 = - "A6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kISSUANCE_INDEX2 = - "B6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kIssuanceIndeX1 = "A6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kIssuanceIndeX2 = "B6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; // unique values for issuance1 -constexpr uint64_t kISSUANCE1_MAX_AMOUNT = 10000; -constexpr uint64_t kISSUANCE1_OUTSTANDING_AMOUNT = 5000; -constexpr uint8_t kISSUANCE1_ASSET_SCALE = 2; -constexpr uint16_t kISSUANCE1_TRANSFER_FEE = 10; +constexpr uint64_t kIssuancE1MaxAmount = 10000; +constexpr uint64_t kIssuancE1OutstandingAmount = 5000; +constexpr uint8_t kIssuancE1AssetScale = 2; +constexpr uint16_t kIssuancE1TransferFee = 10; // unique values for issuance2 -constexpr uint64_t kISSUANCE2_MAX_AMOUNT = 20000; -constexpr uint64_t kISSUANCE2_OUTSTANDING_AMOUNT = 800; -constexpr uint64_t kISSUANCE2_LOCKED_AMOUNT = 100; -constexpr uint16_t kISSUANCE2_TRANSFER_FEE = 5; -constexpr auto kISSUANCE2_METADATA = "test-meta"; -constexpr auto kISSUANCE2_METADATA_HEX = "746573742D6D657461"; -constexpr auto kISSUANCE2_DOMAIN_ID_HEX = +constexpr uint64_t kIssuancE2MaxAmount = 20000; +constexpr uint64_t kIssuancE2OutstandingAmount = 800; +constexpr uint64_t kIssuancE2LockedAmount = 100; +constexpr uint16_t kIssuancE2TransferFee = 5; +constexpr auto kIssuancE2Metadata = "test-meta"; +constexpr auto kIssuancE2MetadataHex = "746573742D6D657461"; +constexpr auto kIssuancE2DomainIdHex = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; // define expected JSON for mpt issuances -auto const kISSUANCE_OUT1 = fmt::format( +auto const kIssuanceOuT1 = fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "issuer": "{}", "sequence": 1, - "maximum_amount": {}, - "outstanding_amount": {}, + "maximum_amount": "{}", + "outstanding_amount": "{}", "asset_scale": {}, "mpt_can_escrow": true, "mpt_can_trade": true, "mpt_require_auth": true, "mpt_can_transfer": true }})JSON", - kISSUANCE_INDEX1, - kACCOUNT, - kISSUANCE1_MAX_AMOUNT, - kISSUANCE1_OUTSTANDING_AMOUNT, - kISSUANCE1_ASSET_SCALE + kIssuanceIndeX1, + kAccount, + kIssuancE1MaxAmount, + kIssuancE1OutstandingAmount, + kIssuancE1AssetScale ); -auto const kISSUANCE_OUT2 = fmt::format( +auto const kIssuanceOuT2 = fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "issuer": "{}", "sequence": 2, - "maximum_amount": {}, - "outstanding_amount": {}, - "locked_amount": {}, + "maximum_amount": "{}", + "outstanding_amount": "{}", + "locked_amount": "{}", "transfer_fee": {}, "mptoken_metadata": "{}", "domain_id": "{}", @@ -93,14 +91,14 @@ auto const kISSUANCE_OUT2 = fmt::format( "mpt_locked": true, "mpt_can_clawback": true }})JSON", - kISSUANCE_INDEX2, - kACCOUNT, - kISSUANCE2_MAX_AMOUNT, - kISSUANCE2_OUTSTANDING_AMOUNT, - kISSUANCE2_LOCKED_AMOUNT, - kISSUANCE2_TRANSFER_FEE, - kISSUANCE2_METADATA_HEX, - kISSUANCE2_DOMAIN_ID_HEX + kIssuanceIndeX2, + kAccount, + kIssuancE2MaxAmount, + kIssuancE2OutstandingAmount, + kIssuancE2LockedAmount, + kIssuancE2TransferFee, + kIssuancE2MetadataHex, + kIssuancE2DomainIdHex ); } // namespace @@ -130,26 +128,26 @@ generateTestValuesForInvalidParamsTest() return std::vector{ {.testName = "NonHexLedgerHash", .testJson = - fmt::format(R"JSON({{ "account": "{}", "ledger_hash": "xxx" }})JSON", kACCOUNT), + fmt::format(R"JSON({{ "account": "{}", "ledger_hash": "xxx" }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "ledger_hashMalformed"}, {.testName = "NonStringLedgerHash", - .testJson = fmt::format(R"JSON({{ "account": "{}", "ledger_hash": 123 }})JSON", kACCOUNT), + .testJson = fmt::format(R"JSON({{ "account": "{}", "ledger_hash": 123 }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "ledger_hashNotString"}, {.testName = "InvalidLedgerIndexString", .testJson = fmt::format( - R"JSON({{ "account": "{}", "ledger_index": "notvalidated" }})JSON", kACCOUNT + R"JSON({{ "account": "{}", "ledger_index": "notvalidated" }})JSON", kAccount ), .expectedError = "invalidParams", .expectedErrorMessage = "ledgerIndexMalformed"}, {.testName = "MarkerNotString", - .testJson = fmt::format(R"JSON({{ "account": "{}", "marker": 9 }})JSON", kACCOUNT), + .testJson = fmt::format(R"JSON({{ "account": "{}", "marker": 9 }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "markerNotString"}, {.testName = "InvalidMarkerContent", .testJson = - fmt::format(R"JSON({{ "account": "{}", "marker": "123invalid" }})JSON", kACCOUNT), + fmt::format(R"JSON({{ "account": "{}", "marker": "123invalid" }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "Malformed cursor."}, {.testName = "AccountMissing", @@ -165,19 +163,19 @@ generateTestValuesForInvalidParamsTest() .expectedError = "actMalformed", .expectedErrorMessage = "Account malformed."}, {.testName = "LimitNotInteger", - .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": "t" }})JSON", kACCOUNT), + .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": "t" }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "Invalid parameters."}, {.testName = "LimitNegative", - .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": -1 }})JSON", kACCOUNT), + .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": -1 }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "Invalid parameters."}, {.testName = "LimitZero", - .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": 0 }})JSON", kACCOUNT), + .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": 0 }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "Invalid parameters."}, {.testName = "LimitTypeInvalid", - .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": true }})JSON", kACCOUNT), + .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": true }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "Invalid parameters."} }; @@ -187,7 +185,7 @@ INSTANTIATE_TEST_SUITE_P( RPCAccountMPTokenIssuancesInvalidParamsGroup, AccountMPTokenIssuancesParameterTest, ValuesIn(generateTestValuesForInvalidParamsTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); // test invalid params bundle @@ -196,7 +194,7 @@ TEST_P(AccountMPTokenIssuancesParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{backend_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); @@ -210,17 +208,17 @@ TEST_P(AccountMPTokenIssuancesParameterTest, InvalidParams) TEST_F(RPCAccountMPTokenIssuancesHandlerTest, NonExistLedgerViaLedgerHash) { // mock fetchLedgerByHash return empty - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillOnce(Return(std::optional{})); + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillOnce(Return(std::optional{})); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -239,15 +237,15 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, NonExistLedgerViaLedgerStringIndex { // mock fetchLedgerBySequence return empty EXPECT_CALL(*backend_, fetchLedgerBySequence) - .WillOnce(Return(std::optional{})); + .WillOnce(Return(std::optional{})); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "4" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -265,15 +263,15 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, NonExistLedgerViaLedgerIntIndex) { // mock fetchLedgerBySequence return empty EXPECT_CALL(*backend_, fetchLedgerBySequence) - .WillOnce(Return(std::optional{})); + .WillOnce(Return(std::optional{})); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": 4 }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -289,17 +287,17 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, NonExistLedgerViaLedgerIntIndex) // ledger not found via hash (seq > max) TEST_F(RPCAccountMPTokenIssuancesHandlerTest, LedgerSeqOutOfRangeByHash) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 31); - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 31); + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillOnce(Return(ledgerHeader)); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { @@ -316,13 +314,13 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, LedgerSeqOutOfRangeByHash) TEST_F(RPCAccountMPTokenIssuancesHandlerTest, LedgerSeqOutOfRangeByIndex) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(0); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "31" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -338,20 +336,20 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, LedgerSeqOutOfRangeByIndex) // account not exist TEST_F(RPCAccountMPTokenIssuancesHandlerTest, NonExistAccount) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillOnce(Return(ledgerHeader)); // fetch account object return empty EXPECT_CALL(*backend_, doFetchLedgerObject).WillOnce(Return(std::optional{})); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { @@ -367,50 +365,50 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, NonExistAccount) // fetch mptoken issuances via account successfully TEST_F(RPCAccountMPTokenIssuancesHandlerTest, DefaultParameters) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); // return non-empty account - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const owneDirKk = ripple::keylet::ownerDir(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); // return two mptoken issuance objects - ripple::STObject const ownerDir = createOwnerDirLedgerObject( - {ripple::uint256{kISSUANCE_INDEX1}, ripple::uint256{kISSUANCE_INDEX2}}, kISSUANCE_INDEX1 + xrpl::STObject const ownerDir = createOwnerDirLedgerObject( + {xrpl::uint256{kIssuanceIndeX1}, xrpl::uint256{kIssuanceIndeX2}}, kIssuanceIndeX1 ); - ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, _, _)) + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); // mocking mptoken issuance ledger objects auto const bbs = std::vector{ createMptIssuanceObject( - kACCOUNT, + kAccount, 1, std::nullopt, - ripple::lsfMPTCanTrade | ripple::lsfMPTRequireAuth | ripple::lsfMPTCanTransfer | - ripple::lsfMPTCanEscrow, - kISSUANCE1_OUTSTANDING_AMOUNT, + xrpl::lsfMPTCanTrade | xrpl::lsfMPTRequireAuth | xrpl::lsfMPTCanTransfer | + xrpl::lsfMPTCanEscrow, + kIssuancE1OutstandingAmount, std::nullopt, - kISSUANCE1_ASSET_SCALE, - kISSUANCE1_MAX_AMOUNT + kIssuancE1AssetScale, + kIssuancE1MaxAmount ) .getSerializer() .peekData(), createMptIssuanceObject( - kACCOUNT, + kAccount, 2, - kISSUANCE2_METADATA, - ripple::lsfMPTLocked | ripple::lsfMPTCanLock | ripple::lsfMPTCanClawback, - kISSUANCE2_OUTSTANDING_AMOUNT, - kISSUANCE2_TRANSFER_FEE, + kIssuancE2Metadata, + xrpl::lsfMPTLocked | xrpl::lsfMPTCanLock | xrpl::lsfMPTCanClawback, + kIssuancE2OutstandingAmount, + kIssuancE2TransferFee, std::nullopt, - kISSUANCE2_MAX_AMOUNT, - kISSUANCE2_LOCKED_AMOUNT, - kISSUANCE2_DOMAIN_ID_HEX + kIssuancE2MaxAmount, + kIssuancE2LockedAmount, + kIssuancE2DomainIdHex ) .getSerializer() .peekData() @@ -431,61 +429,62 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, DefaultParameters) {} ] }})JSON", - kACCOUNT, - kLEDGER_HASH, - AccountMPTokenIssuancesHandler::kLIMIT_DEFAULT, - kISSUANCE_OUT1, - kISSUANCE_OUT2 + kAccount, + kLedgerHash, + AccountMPTokenIssuancesHandler::kLimitDefault, + kIssuanceOuT1, + kIssuanceOuT2 ); - auto const input = json::parse(fmt::format(R"JSON({{"account": "{}"}})JSON", kACCOUNT)); + auto const input = + boost::json::parse(fmt::format(R"JSON({{"account": "{}"}})JSON", kAccount)); auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(expected), *output.result); + EXPECT_EQ(boost::json::parse(expected), *output.result); }); } TEST_F(RPCAccountMPTokenIssuancesHandlerTest, UseLimit) { - constexpr int kLIMIT = 20; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + constexpr int kLimit = 20; + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const owneDirKk = ripple::keylet::ownerDir(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - auto const indexes = std::vector(50, ripple::uint256{kISSUANCE_INDEX1}); + auto const indexes = std::vector(50, xrpl::uint256{kIssuanceIndeX1}); auto const bbs = [&]() { std::vector v; v.reserve(50); for (int i = 0; i < 50; ++i) { - v.push_back(createMptIssuanceObject(kACCOUNT, i).getSerializer().peekData()); + v.push_back(createMptIssuanceObject(kAccount, i).getSerializer().peekData()); } return v; }(); - ripple::STObject ownerDir = createOwnerDirLedgerObject(indexes, kISSUANCE_INDEX1); - ownerDir.setFieldU64(ripple::sfIndexNext, 99); - ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, _, _)) + xrpl::STObject ownerDir = createOwnerDirLedgerObject(indexes, kIssuanceIndeX1); + ownerDir.setFieldU64(xrpl::sfIndexNext, 99); + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(7); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(3); - runSpawn([this, kLIMIT](auto yield) { - auto const input = json::parse( + runSpawn([this, kLimit](auto yield) { + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - kLIMIT + kAccount, + kLimit ) ); @@ -494,100 +493,99 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, UseLimit) ASSERT_TRUE(output); auto const resultJson = output.result->as_object(); - EXPECT_EQ(resultJson.at("mpt_issuances").as_array().size(), kLIMIT); + EXPECT_EQ(resultJson.at("mpt_issuances").as_array().size(), kLimit); ASSERT_TRUE(resultJson.contains("marker")); EXPECT_THAT(boost::json::value_to(resultJson.at("marker")), EndsWith(",0")); }); runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountMPTokenIssuancesHandler::kLIMIT_MIN - 1 + kAccount, + AccountMPTokenIssuancesHandler::kLimitMin - 1 ) ); auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ( output.result->as_object().at("limit").as_uint64(), - AccountMPTokenIssuancesHandler::kLIMIT_MIN + AccountMPTokenIssuancesHandler::kLimitMin ); }); runSpawn([this](auto yield) { auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountMPTokenIssuancesHandler::kLIMIT_MAX + 1 + kAccount, + AccountMPTokenIssuancesHandler::kLimitMax + 1 ) ); auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ( output.result->as_object().at("limit").as_uint64(), - AccountMPTokenIssuancesHandler::kLIMIT_MAX + AccountMPTokenIssuancesHandler::kLimitMax ); }); } TEST_F(RPCAccountMPTokenIssuancesHandlerTest, MarkerOutput) { - constexpr auto kNEXT_PAGE = 99; - constexpr auto kLIMIT = 15; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + constexpr auto kNextPage = 99; + constexpr auto kLimit = 15; + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; - auto const ownerDir2Kk = - ripple::keylet::page(ripple::keylet::ownerDir(account), kNEXT_PAGE).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; + auto const ownerDir2Kk = xrpl::keylet::page(xrpl::keylet::ownerDir(account), kNextPage).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); - auto const indexes = std::vector(10, ripple::uint256{kISSUANCE_INDEX1}); + auto const indexes = std::vector(10, xrpl::uint256{kIssuanceIndeX1}); auto const bbs = [&]() { std::vector v; - v.reserve(kLIMIT); - for (int i = 0; i < kLIMIT; ++i) { - v.push_back(createMptIssuanceObject(kACCOUNT, i).getSerializer().peekData()); + v.reserve(kLimit); + for (int i = 0; i < kLimit; ++i) { + v.push_back(createMptIssuanceObject(kAccount, i).getSerializer().peekData()); } return v; }(); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); // mock the first directory page - ripple::STObject ownerDir1 = createOwnerDirLedgerObject(indexes, kISSUANCE_INDEX1); - ownerDir1.setFieldU64(ripple::sfIndexNext, kNEXT_PAGE); + xrpl::STObject ownerDir1 = createOwnerDirLedgerObject(indexes, kIssuanceIndeX1); + ownerDir1.setFieldU64(xrpl::sfIndexNext, kNextPage); ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillByDefault(Return(ownerDir1.getSerializer().peekData())); // mock the second directory page - ripple::STObject ownerDir2 = createOwnerDirLedgerObject(indexes, kISSUANCE_INDEX2); - ownerDir2.setFieldU64(ripple::sfIndexNext, 0); + xrpl::STObject ownerDir2 = createOwnerDirLedgerObject(indexes, kIssuanceIndeX2); + ownerDir2.setFieldU64(xrpl::sfIndexNext, 0); ON_CALL(*backend_, doFetchLedgerObject(ownerDir2Kk, _, _)) .WillByDefault(Return(ownerDir2.getSerializer().peekData())); - runSpawn([this, kLIMIT, kNEXT_PAGE](auto yield) { - auto const input = json::parse( + runSpawn([this, kLimit, kNextPage](auto yield) { + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - kLIMIT + kAccount, + kLimit ) ); auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{this->backend_}}; @@ -596,56 +594,56 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, MarkerOutput) auto const& resultJson = output.result->as_object(); EXPECT_EQ( boost::json::value_to(resultJson.at("marker")), - fmt::format("{},{}", kISSUANCE_INDEX1, kNEXT_PAGE) + fmt::format("{},{}", kIssuanceIndeX1, kNextPage) ); - EXPECT_EQ(resultJson.at("mpt_issuances").as_array().size(), kLIMIT); + EXPECT_EQ(resultJson.at("mpt_issuances").as_array().size(), kLimit); }); } TEST_F(RPCAccountMPTokenIssuancesHandlerTest, MarkerInput) { - constexpr auto kNEXT_PAGE = 99; - constexpr auto kLIMIT = 15; + constexpr auto kNextPage = 99; + constexpr auto kLimit = 15; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const ownerDirKk = ripple::keylet::page(ripple::keylet::ownerDir(account), kNEXT_PAGE).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::page(xrpl::keylet::ownerDir(account), kNextPage).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); - auto const indexes = std::vector(kLIMIT, ripple::uint256{kISSUANCE_INDEX1}); + auto const indexes = std::vector(kLimit, xrpl::uint256{kIssuanceIndeX1}); auto const bbs = [&]() { std::vector v; - v.reserve(kLIMIT); - for (int i = 0; i < kLIMIT; ++i) { - v.push_back(createMptIssuanceObject(kACCOUNT, i).getSerializer().peekData()); + v.reserve(kLimit); + for (int i = 0; i < kLimit; ++i) { + v.push_back(createMptIssuanceObject(kAccount, i).getSerializer().peekData()); } return v; }(); - ripple::STObject ownerDir = createOwnerDirLedgerObject(indexes, kISSUANCE_INDEX1); - ownerDir.setFieldU64(ripple::sfIndexNext, 0); + xrpl::STObject ownerDir = createOwnerDirLedgerObject(indexes, kIssuanceIndeX1); + ownerDir.setFieldU64(xrpl::sfIndexNext, 0); ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - runSpawn([this, kLIMIT, kNEXT_PAGE](auto yield) { - auto const input = json::parse( + runSpawn([this, kLimit, kNextPage](auto yield) { + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {}, "marker": "{},{}" }})JSON", - kACCOUNT, - kLIMIT, - kISSUANCE_INDEX1, - kNEXT_PAGE + kAccount, + kLimit, + kIssuanceIndeX1, + kNextPage ) ); auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{this->backend_}}; @@ -654,53 +652,53 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, MarkerInput) auto const& resultJson = output.result->as_object(); EXPECT_TRUE(resultJson.if_contains("marker") == nullptr); - EXPECT_EQ(resultJson.at("mpt_issuances").as_array().size(), kLIMIT - 1); + EXPECT_EQ(resultJson.at("mpt_issuances").as_array().size(), kLimit - 1); }); } TEST_F(RPCAccountMPTokenIssuancesHandlerTest, LimitLessThanMin) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const owneDirKk = ripple::keylet::ownerDir(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - ripple::STObject const ownerDir = createOwnerDirLedgerObject( - {ripple::uint256{kISSUANCE_INDEX1}, ripple::uint256{kISSUANCE_INDEX2}}, kISSUANCE_INDEX1 + xrpl::STObject const ownerDir = createOwnerDirLedgerObject( + {xrpl::uint256{kIssuanceIndeX1}, xrpl::uint256{kIssuanceIndeX2}}, kIssuanceIndeX1 ); - EXPECT_CALL(*backend_, doFetchLedgerObject(owneDirKk, _, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); auto const bbs = std::vector{ createMptIssuanceObject( - kACCOUNT, + kAccount, 1, std::nullopt, - ripple::lsfMPTCanTrade | ripple::lsfMPTRequireAuth | ripple::lsfMPTCanTransfer | - ripple::lsfMPTCanEscrow, - kISSUANCE1_OUTSTANDING_AMOUNT, + xrpl::lsfMPTCanTrade | xrpl::lsfMPTRequireAuth | xrpl::lsfMPTCanTransfer | + xrpl::lsfMPTCanEscrow, + kIssuancE1OutstandingAmount, std::nullopt, - kISSUANCE1_ASSET_SCALE, - kISSUANCE1_MAX_AMOUNT + kIssuancE1AssetScale, + kIssuancE1MaxAmount ) .getSerializer() .peekData(), createMptIssuanceObject( - kACCOUNT, + kAccount, 2, - kISSUANCE2_METADATA, - ripple::lsfMPTLocked | ripple::lsfMPTCanLock | ripple::lsfMPTCanClawback, - kISSUANCE2_OUTSTANDING_AMOUNT, - kISSUANCE2_TRANSFER_FEE, + kIssuancE2Metadata, + xrpl::lsfMPTLocked | xrpl::lsfMPTCanLock | xrpl::lsfMPTCanClawback, + kIssuancE2OutstandingAmount, + kIssuancE2TransferFee, std::nullopt, - kISSUANCE2_MAX_AMOUNT, - kISSUANCE2_LOCKED_AMOUNT, - kISSUANCE2_DOMAIN_ID_HEX + kIssuancE2MaxAmount, + kIssuancE2LockedAmount, + kIssuancE2DomainIdHex ) .getSerializer() .peekData() @@ -709,14 +707,14 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, LimitLessThanMin) EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); runSpawn([this](auto yield) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountMPTokenIssuancesHandler::kLIMIT_MIN - 1 + kAccount, + AccountMPTokenIssuancesHandler::kLimitMin - 1 ) ); @@ -732,63 +730,63 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, LimitLessThanMin) {} ] }})JSON", - kACCOUNT, - kLEDGER_HASH, - AccountMPTokenIssuancesHandler::kLIMIT_MIN, - kISSUANCE_OUT1, - kISSUANCE_OUT2 + kAccount, + kLedgerHash, + AccountMPTokenIssuancesHandler::kLimitMin, + kIssuanceOuT1, + kIssuanceOuT2 ); auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(correctOutput), *output.result); + EXPECT_EQ(boost::json::parse(correctOutput), *output.result); }); } TEST_F(RPCAccountMPTokenIssuancesHandlerTest, LimitMoreThanMax) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const owneDirKk = ripple::keylet::ownerDir(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - ripple::STObject const ownerDir = createOwnerDirLedgerObject( - {ripple::uint256{kISSUANCE_INDEX1}, ripple::uint256{kISSUANCE_INDEX2}}, kISSUANCE_INDEX1 + xrpl::STObject const ownerDir = createOwnerDirLedgerObject( + {xrpl::uint256{kIssuanceIndeX1}, xrpl::uint256{kIssuanceIndeX2}}, kIssuanceIndeX1 ); - EXPECT_CALL(*backend_, doFetchLedgerObject(owneDirKk, _, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); auto const bbs = std::vector{ createMptIssuanceObject( - kACCOUNT, + kAccount, 1, std::nullopt, - ripple::lsfMPTCanTrade | ripple::lsfMPTRequireAuth | ripple::lsfMPTCanTransfer | - ripple::lsfMPTCanEscrow, - kISSUANCE1_OUTSTANDING_AMOUNT, + xrpl::lsfMPTCanTrade | xrpl::lsfMPTRequireAuth | xrpl::lsfMPTCanTransfer | + xrpl::lsfMPTCanEscrow, + kIssuancE1OutstandingAmount, std::nullopt, - kISSUANCE1_ASSET_SCALE, - kISSUANCE1_MAX_AMOUNT + kIssuancE1AssetScale, + kIssuancE1MaxAmount ) .getSerializer() .peekData(), createMptIssuanceObject( - kACCOUNT, + kAccount, 2, - kISSUANCE2_METADATA, - ripple::lsfMPTLocked | ripple::lsfMPTCanLock | ripple::lsfMPTCanClawback, - kISSUANCE2_OUTSTANDING_AMOUNT, - kISSUANCE2_TRANSFER_FEE, + kIssuancE2Metadata, + xrpl::lsfMPTLocked | xrpl::lsfMPTCanLock | xrpl::lsfMPTCanClawback, + kIssuancE2OutstandingAmount, + kIssuancE2TransferFee, std::nullopt, - kISSUANCE2_MAX_AMOUNT, - kISSUANCE2_LOCKED_AMOUNT, - kISSUANCE2_DOMAIN_ID_HEX + kIssuancE2MaxAmount, + kIssuancE2LockedAmount, + kIssuancE2DomainIdHex ) .getSerializer() .peekData() @@ -797,14 +795,14 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, LimitMoreThanMax) EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); runSpawn([this](auto yield) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountMPTokenIssuancesHandler::kLIMIT_MAX + 1 + kAccount, + AccountMPTokenIssuancesHandler::kLimitMax + 1 ) ); @@ -820,42 +818,42 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, LimitMoreThanMax) {} ] }})JSON", - kACCOUNT, - kLEDGER_HASH, - AccountMPTokenIssuancesHandler::kLIMIT_MAX, - kISSUANCE_OUT1, - kISSUANCE_OUT2 + kAccount, + kLedgerHash, + AccountMPTokenIssuancesHandler::kLimitMax, + kIssuanceOuT1, + kIssuanceOuT2 ); auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(correctOutput), *output.result); + EXPECT_EQ(boost::json::parse(correctOutput), *output.result); }); } TEST_F(RPCAccountMPTokenIssuancesHandlerTest, EmptyResult) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const owneDirKk = ripple::keylet::ownerDir(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - ripple::STObject const ownerDir = createOwnerDirLedgerObject({}, kISSUANCE_INDEX1); - EXPECT_CALL(*backend_, doFetchLedgerObject(owneDirKk, _, _)) + xrpl::STObject const ownerDir = createOwnerDirLedgerObject({}, kIssuanceIndeX1); + EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); runSpawn([this](auto yield) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{this->backend_}}; @@ -865,39 +863,130 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, EmptyResult) }); } -TEST_F(RPCAccountMPTokenIssuancesHandlerTest, MutableFlags) +// Regression test: UInt64 amount fields must be serialized as base-10 JSON strings (as xrpld +// does) so that values greater than 2^53 are not silently rounded by JSON parsers backed by +// IEEE-754 doubles. 2^53 itself is still exactly representable as a double, but it must be emitted +// as a string like every other amount so the wire format stays consistent regardless of magnitude. +struct AccountMPTokenIssuancesAmountSerializationTestCaseBundle { + std::string testName; + uint64_t maxAmount; + uint64_t outstandingAmount; + uint64_t lockedAmount; +}; + +struct AccountMPTokenIssuancesAmountSerializationTest + : RPCAccountMPTokenIssuancesHandlerTest, + WithParamInterface {}; + +INSTANTIATE_TEST_SUITE_P( + RPCAccountMPTokenIssuancesAmountSerializationGroup, + AccountMPTokenIssuancesAmountSerializationTest, + ValuesIn( + std::vector{ + {.testName = "LargeAmounts", + .maxAmount = static_cast(std::pow(2, 63)) - 1, // max MPT amount + .outstandingAmount = static_cast(std::pow(2, 53)) + 1, + .lockedAmount = static_cast(std::pow(2, 53)) + + 12345}, // odd value above 2^53 + {.testName = "ExactDoubleBoundary", + .maxAmount = static_cast(std::pow(2, 53)), + .outstandingAmount = static_cast(std::pow(2, 53)), + .lockedAmount = static_cast(std::pow(2, 53))} + } + ), + tests::util::kNameGenerator +); + +TEST_P(AccountMPTokenIssuancesAmountSerializationTest, SerializedAsStrings) { - uint32_t const mutableFlags1 = ripple::lsmfMPTCanMutateCanLock | - ripple::lsmfMPTCanMutateRequireAuth | ripple::lsmfMPTCanMutateCanEscrow | - ripple::lsmfMPTCanMutateCanTrade; + auto const testBundle = GetParam(); - uint32_t const mutableFlags2 = ripple::lsmfMPTCanMutateCanTransfer | - ripple::lsmfMPTCanMutateCanClawback | ripple::lsmfMPTCanMutateMetadata | - ripple::lsmfMPTCanMutateTransferFee; - - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const owneDirKk = ripple::keylet::ownerDir(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - ripple::STObject const ownerDir = createOwnerDirLedgerObject( - {ripple::uint256{kISSUANCE_INDEX1}, ripple::uint256{kISSUANCE_INDEX2}}, kISSUANCE_INDEX1 + xrpl::STObject const ownerDir = + createOwnerDirLedgerObject({xrpl::uint256{kIssuanceIndeX1}}, kIssuanceIndeX1); + EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) + .WillOnce(Return(ownerDir.getSerializer().peekData())); + + xrpl::STObject const mptIssuance = createMptIssuanceObject( + kAccount, + 1, + std::nullopt, + xrpl::lsfMPTCanLock, + testBundle.outstandingAmount, + std::nullopt, + std::nullopt, + testBundle.maxAmount, + testBundle.lockedAmount ); - EXPECT_CALL(*backend_, doFetchLedgerObject(owneDirKk, _, _)) + auto const bbs = std::vector{mptIssuance.getSerializer().peekData()}; + EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); + + runSpawn([&, this](auto yield) { + auto const input = + boost::json::parse(fmt::format(R"JSON({{"account": "{}"}})JSON", kAccount)); + auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{this->backend_}}; + auto const output = handler.process(input, Context{yield}); + ASSERT_TRUE(output); + + auto const& issuances = output.result->as_object().at("mpt_issuances").as_array(); + ASSERT_EQ(issuances.size(), 1); + auto const& issuance = issuances[0].as_object(); + + ASSERT_TRUE(issuance.at("maximum_amount").is_string()); + EXPECT_EQ(issuance.at("maximum_amount").as_string(), std::to_string(testBundle.maxAmount)); + ASSERT_TRUE(issuance.at("outstanding_amount").is_string()); + EXPECT_EQ( + issuance.at("outstanding_amount").as_string(), + std::to_string(testBundle.outstandingAmount) + ); + ASSERT_TRUE(issuance.at("locked_amount").is_string()); + EXPECT_EQ( + issuance.at("locked_amount").as_string(), std::to_string(testBundle.lockedAmount) + ); + }); +} + +TEST_F(RPCAccountMPTokenIssuancesHandlerTest, MutableFlags) +{ + uint32_t const mutableFlags1 = xrpl::lsmfMPTCanEnableCanLock | + xrpl::lsmfMPTCanEnableRequireAuth | xrpl::lsmfMPTCanEnableCanEscrow | + xrpl::lsmfMPTCanEnableCanTrade; + + uint32_t const mutableFlags2 = xrpl::lsmfMPTCanEnableCanTransfer | + xrpl::lsmfMPTCanEnableCanClawback | xrpl::lsmfMPTCanMutateMetadata | + xrpl::lsmfMPTCanMutateTransferFee; + + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); + EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); + + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) + .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); + + xrpl::STObject const ownerDir = createOwnerDirLedgerObject( + {xrpl::uint256{kIssuanceIndeX1}, xrpl::uint256{kIssuanceIndeX2}}, kIssuanceIndeX1 + ); + EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); auto const bbs = std::vector{ createMptIssuanceObject( - kACCOUNT, + kAccount, 3, std::nullopt, - ripple::lsfMPTCanTransfer, - kISSUANCE1_OUTSTANDING_AMOUNT, - kISSUANCE1_TRANSFER_FEE, + xrpl::lsfMPTCanTransfer, + kIssuancE1OutstandingAmount, + kIssuancE1TransferFee, std::nullopt, std::nullopt, std::nullopt, @@ -908,12 +997,12 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, MutableFlags) .peekData(), createMptIssuanceObject( - kACCOUNT, + kAccount, 5, - kISSUANCE2_METADATA, - ripple::lsfMPTCanTransfer, - kISSUANCE2_OUTSTANDING_AMOUNT, - kISSUANCE2_TRANSFER_FEE, + kIssuancE2Metadata, + xrpl::lsfMPTCanTransfer, + kIssuancE2OutstandingAmount, + kIssuancE2TransferFee, std::nullopt, std::nullopt, std::nullopt, @@ -927,12 +1016,12 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, MutableFlags) EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); runSpawn([this](auto yield) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); @@ -948,7 +1037,7 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, MutableFlags) "mpt_issuance_id": "{}", "issuer": "{}", "sequence": 3, - "outstanding_amount": {}, + "outstanding_amount": "{}", "transfer_fee": {}, "mpt_can_transfer": true, "mpt_can_mutate_can_lock": true, @@ -960,7 +1049,7 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, MutableFlags) "mpt_issuance_id": "{}", "issuer": "{}", "sequence": 5, - "outstanding_amount": {}, + "outstanding_amount": "{}", "transfer_fee": {}, "mptoken_metadata": "{}", "mpt_can_transfer": true, @@ -971,23 +1060,23 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, MutableFlags) }} ] }})JSON", - kACCOUNT, - kLEDGER_HASH, - kISSUANCE_INDEX1, - kACCOUNT, - kISSUANCE1_OUTSTANDING_AMOUNT, - kISSUANCE1_TRANSFER_FEE, - kISSUANCE_INDEX2, - kACCOUNT, - kISSUANCE2_OUTSTANDING_AMOUNT, - kISSUANCE2_TRANSFER_FEE, - kISSUANCE2_METADATA_HEX + kAccount, + kLedgerHash, + kIssuanceIndeX1, + kAccount, + kIssuancE1OutstandingAmount, + kIssuancE1TransferFee, + kIssuanceIndeX2, + kAccount, + kIssuancE2OutstandingAmount, + kIssuancE2TransferFee, + kIssuancE2MetadataHex ); auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(correctOutput), *output.result); + EXPECT_EQ(boost::json::parse(correctOutput), *output.result); }); } @@ -1004,22 +1093,20 @@ static auto generateSingleFlagTests() { return std::vector{ - {.testName = "Locked", .flag = ripple::lsfMPTLocked, .expectedJsonKey = "mpt_locked"}, - {.testName = "CanLock", .flag = ripple::lsfMPTCanLock, .expectedJsonKey = "mpt_can_lock"}, + {.testName = "Locked", .flag = xrpl::lsfMPTLocked, .expectedJsonKey = "mpt_locked"}, + {.testName = "CanLock", .flag = xrpl::lsfMPTCanLock, .expectedJsonKey = "mpt_can_lock"}, {.testName = "RequireAuth", - .flag = ripple::lsfMPTRequireAuth, + .flag = xrpl::lsfMPTRequireAuth, .expectedJsonKey = "mpt_require_auth"}, {.testName = "CanEscrow", - .flag = ripple::lsfMPTCanEscrow, + .flag = xrpl::lsfMPTCanEscrow, .expectedJsonKey = "mpt_can_escrow"}, - {.testName = "CanTrade", - .flag = ripple::lsfMPTCanTrade, - .expectedJsonKey = "mpt_can_trade"}, + {.testName = "CanTrade", .flag = xrpl::lsfMPTCanTrade, .expectedJsonKey = "mpt_can_trade"}, {.testName = "CanTransfer", - .flag = ripple::lsfMPTCanTransfer, + .flag = xrpl::lsfMPTCanTransfer, .expectedJsonKey = "mpt_can_transfer"}, {.testName = "CanClawback", - .flag = ripple::lsfMPTCanClawback, + .flag = xrpl::lsfMPTCanClawback, .expectedJsonKey = "mpt_can_clawback"}, }; } @@ -1028,41 +1115,41 @@ INSTANTIATE_TEST_SUITE_P( RPCAccountMPTokenIssuancesImmutableFlagsGroup, AccountMPTokenIssuancesImmutableFlagsTest, ValuesIn(generateSingleFlagTests()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(AccountMPTokenIssuancesImmutableFlagsTest, SingleFlag) { auto const testParams = GetParam(); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const owneDirKk = ripple::keylet::ownerDir(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - ripple::STObject const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kISSUANCE_INDEX1}}, kISSUANCE_INDEX1); - EXPECT_CALL(*backend_, doFetchLedgerObject(owneDirKk, _, _)) + xrpl::STObject const ownerDir = + createOwnerDirLedgerObject({xrpl::uint256{kIssuanceIndeX1}}, kIssuanceIndeX1); + EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); auto const bbs = - std::vector{createMptIssuanceObject(kACCOUNT, 1, std::nullopt, testParams.flag, 0) + std::vector{createMptIssuanceObject(kAccount, 1, std::nullopt, testParams.flag, 0) .getSerializer() .peekData()}; EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); runSpawn([this, &testParams](auto yield) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{this->backend_}}; @@ -1093,28 +1180,28 @@ generateSingleMutableFlagTests() { return std::vector{ {.testName = "CanMutateCanLock", - .mutableFlag = ripple::lsmfMPTCanMutateCanLock, + .mutableFlag = xrpl::lsmfMPTCanEnableCanLock, .expectedJsonKey = "mpt_can_mutate_can_lock"}, {.testName = "CanMutateRequireAuth", - .mutableFlag = ripple::lsmfMPTCanMutateRequireAuth, + .mutableFlag = xrpl::lsmfMPTCanEnableRequireAuth, .expectedJsonKey = "mpt_can_mutate_require_auth"}, {.testName = "CanMutateCanEscrow", - .mutableFlag = ripple::lsmfMPTCanMutateCanEscrow, + .mutableFlag = xrpl::lsmfMPTCanEnableCanEscrow, .expectedJsonKey = "mpt_can_mutate_can_escrow"}, {.testName = "CanMutateCanTrade", - .mutableFlag = ripple::lsmfMPTCanMutateCanTrade, + .mutableFlag = xrpl::lsmfMPTCanEnableCanTrade, .expectedJsonKey = "mpt_can_mutate_can_trade"}, {.testName = "CanMutateCanTransfer", - .mutableFlag = ripple::lsmfMPTCanMutateCanTransfer, + .mutableFlag = xrpl::lsmfMPTCanEnableCanTransfer, .expectedJsonKey = "mpt_can_mutate_can_transfer"}, {.testName = "CanMutateCanClawback", - .mutableFlag = ripple::lsmfMPTCanMutateCanClawback, + .mutableFlag = xrpl::lsmfMPTCanEnableCanClawback, .expectedJsonKey = "mpt_can_mutate_can_clawback"}, {.testName = "CanMutateMetadata", - .mutableFlag = ripple::lsmfMPTCanMutateMetadata, + .mutableFlag = xrpl::lsmfMPTCanMutateMetadata, .expectedJsonKey = "mpt_can_mutate_metadata"}, {.testName = "CanMutateTransferFee", - .mutableFlag = ripple::lsmfMPTCanMutateTransferFee, + .mutableFlag = xrpl::lsmfMPTCanMutateTransferFee, .expectedJsonKey = "mpt_can_mutate_transfer_fee"}, }; } @@ -1123,29 +1210,29 @@ INSTANTIATE_TEST_SUITE_P( RPCAccountMPTokenIssuancesMutableFlagsGroup, AccountMPTokenIssuancesMutableFlagsTest, ValuesIn(generateSingleMutableFlagTests()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(AccountMPTokenIssuancesMutableFlagsTest, SingleMutableFlag) { auto const testParams = GetParam(); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const owneDirKk = ripple::keylet::ownerDir(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - ripple::STObject const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kISSUANCE_INDEX1}}, kISSUANCE_INDEX1); - EXPECT_CALL(*backend_, doFetchLedgerObject(owneDirKk, _, _)) + xrpl::STObject const ownerDir = + createOwnerDirLedgerObject({xrpl::uint256{kIssuanceIndeX1}}, kIssuanceIndeX1); + EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); auto const bbs = std::vector{createMptIssuanceObject( - kACCOUNT, + kAccount, 1, std::nullopt, 0, @@ -1163,12 +1250,12 @@ TEST_P(AccountMPTokenIssuancesMutableFlagsTest, SingleMutableFlag) EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); runSpawn([this, &testParams](auto yield) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{this->backend_}}; diff --git a/tests/unit/rpc/handlers/AccountMPTokensTests.cpp b/tests/unit/rpc/handlers/AccountMPTokensTests.cpp index eb9e19955..8c56dbd8a 100644 --- a/tests/unit/rpc/handlers/AccountMPTokensTests.cpp +++ b/tests/unit/rpc/handlers/AccountMPTokensTests.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -27,50 +28,49 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kISSUANCE_ID_HEX = "00080000B43A1A953EADDB3314A73523789947C752044C49"; -constexpr auto kTOKEN_INDEX1 = "A6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kTOKEN_INDEX2 = "B6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kIssuanceIdHex = "00080000B43A1A953EADDB3314A73523789947C752044C49"; +constexpr auto kTokenIndeX1 = "A6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kTokenIndeX2 = "B6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; -constexpr uint64_t kTOKEN1_AMOUNT = 500; -constexpr uint64_t kTOKEN1_LOCKED_AMOUNT = 50; -constexpr uint64_t kTOKEN2_AMOUNT = 250; +constexpr uint64_t kTokeN1Amount = 500; +constexpr uint64_t kTokeN1LockedAmount = 50; +constexpr uint64_t kTokeN2Amount = 250; // define expected JSON for mptokens -auto const kTOKEN_OUT1 = fmt::format( +auto const kTokenOuT1 = fmt::format( R"JSON({{ "mpt_id": "{}", "account": "{}", "mpt_issuance_id": "{}", - "mpt_amount": {}, - "locked_amount": {}, + "mpt_amount": "{}", + "locked_amount": "{}", "mpt_locked": true }})JSON", - kTOKEN_INDEX1, - kACCOUNT, - kISSUANCE_ID_HEX, - kTOKEN1_AMOUNT, - kTOKEN1_LOCKED_AMOUNT + kTokenIndeX1, + kAccount, + kIssuanceIdHex, + kTokeN1Amount, + kTokeN1LockedAmount ); -auto const kTOKEN_OUT2 = fmt::format( +auto const kTokenOuT2 = fmt::format( R"JSON({{ "mpt_id": "{}", "account": "{}", "mpt_issuance_id": "{}", - "mpt_amount": {}, + "mpt_amount": "{}", "mpt_authorized": true }})JSON", - kTOKEN_INDEX2, - kACCOUNT, - kISSUANCE_ID_HEX, - kTOKEN2_AMOUNT + kTokenIndeX2, + kAccount, + kIssuanceIdHex, + kTokeN2Amount ); } // namespace @@ -99,26 +99,26 @@ generateTestValuesForInvalidParamsTest() return std::vector{ {.testName = "NonHexLedgerHash", .testJson = - fmt::format(R"JSON({{ "account": "{}", "ledger_hash": "xxx" }})JSON", kACCOUNT), + fmt::format(R"JSON({{ "account": "{}", "ledger_hash": "xxx" }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "ledger_hashMalformed"}, {.testName = "NonStringLedgerHash", - .testJson = fmt::format(R"JSON({{ "account": "{}", "ledger_hash": 123 }})JSON", kACCOUNT), + .testJson = fmt::format(R"JSON({{ "account": "{}", "ledger_hash": 123 }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "ledger_hashNotString"}, {.testName = "InvalidLedgerIndexString", .testJson = fmt::format( - R"JSON({{ "account": "{}", "ledger_index": "notvalidated" }})JSON", kACCOUNT + R"JSON({{ "account": "{}", "ledger_index": "notvalidated" }})JSON", kAccount ), .expectedError = "invalidParams", .expectedErrorMessage = "ledgerIndexMalformed"}, {.testName = "MarkerNotString", - .testJson = fmt::format(R"JSON({{ "account": "{}", "marker": 9 }})JSON", kACCOUNT), + .testJson = fmt::format(R"JSON({{ "account": "{}", "marker": 9 }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "markerNotString"}, {.testName = "InvalidMarkerContent", .testJson = - fmt::format(R"JSON({{ "account": "{}", "marker": "123invalid" }})JSON", kACCOUNT), + fmt::format(R"JSON({{ "account": "{}", "marker": "123invalid" }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "Malformed cursor."}, {.testName = "AccountMissing", @@ -135,19 +135,19 @@ generateTestValuesForInvalidParamsTest() .expectedError = "actMalformed", .expectedErrorMessage = "Account malformed."}, {.testName = "LimitNotInteger", - .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": "t" }})JSON", kACCOUNT), + .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": "t" }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "Invalid parameters."}, {.testName = "LimitNegative", - .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": -1 }})JSON", kACCOUNT), + .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": -1 }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "Invalid parameters."}, {.testName = "LimitZero", - .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": 0 }})JSON", kACCOUNT), + .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": 0 }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "Invalid parameters."}, {.testName = "LimitTypeInvalid", - .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": true }})JSON", kACCOUNT), + .testJson = fmt::format(R"JSON({{ "account": "{}", "limit": true }})JSON", kAccount), .expectedError = "invalidParams", .expectedErrorMessage = "Invalid parameters."} }; @@ -157,7 +157,7 @@ INSTANTIATE_TEST_SUITE_P( RPCAccountMPTokensInvalidParamsGroup, AccountMPTokensParameterTest, ValuesIn(generateTestValuesForInvalidParamsTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); // test invalid params bundle @@ -166,7 +166,7 @@ TEST_P(AccountMPTokensParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountMPTokensHandler{backend_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -178,17 +178,17 @@ TEST_P(AccountMPTokensParameterTest, InvalidParams) TEST_F(RPCAccountMPTokensHandlerTest, NonExistLedgerViaLedgerHash) { // mock fetchLedgerByHash to return empty - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillOnce(Return(std::optional{})); + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillOnce(Return(std::optional{})); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { @@ -206,15 +206,15 @@ TEST_F(RPCAccountMPTokensHandlerTest, NonExistLedgerViaLedgerStringIndex) { // mock fetchLedgerBySequence to return empty EXPECT_CALL(*backend_, fetchLedgerBySequence) - .WillOnce(Return(std::optional{})); + .WillOnce(Return(std::optional{})); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "4" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -231,15 +231,15 @@ TEST_F(RPCAccountMPTokensHandlerTest, NonExistLedgerViaLedgerIntIndex) { // mock fetchLedgerBySequence to return empty EXPECT_CALL(*backend_, fetchLedgerBySequence) - .WillOnce(Return(std::optional{})); + .WillOnce(Return(std::optional{})); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": 4 }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -254,18 +254,18 @@ TEST_F(RPCAccountMPTokensHandlerTest, NonExistLedgerViaLedgerIntIndex) TEST_F(RPCAccountMPTokensHandlerTest, LedgerSeqOutOfRangeByHash) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 31); - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 31); + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillOnce(Return(ledgerHeader)); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { @@ -283,13 +283,13 @@ TEST_F(RPCAccountMPTokensHandlerTest, LedgerSeqOutOfRangeByIndex) { // No need to check from db, call fetchLedgerBySequence 0 times EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(0); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "31" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -304,20 +304,20 @@ TEST_F(RPCAccountMPTokensHandlerTest, LedgerSeqOutOfRangeByIndex) TEST_F(RPCAccountMPTokensHandlerTest, NonExistAccount) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillOnce(Return(ledgerHeader)); // fetch account object return empty EXPECT_CALL(*backend_, doFetchLedgerObject).WillOnce(Return(std::optional{})); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); @@ -333,37 +333,37 @@ TEST_F(RPCAccountMPTokensHandlerTest, NonExistAccount) TEST_F(RPCAccountMPTokensHandlerTest, DefaultParameters) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const owneDirKk = ripple::keylet::ownerDir(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - ripple::STObject const ownerDir = createOwnerDirLedgerObject( - {ripple::uint256{kTOKEN_INDEX1}, ripple::uint256{kTOKEN_INDEX2}}, kTOKEN_INDEX1 + xrpl::STObject const ownerDir = createOwnerDirLedgerObject( + {xrpl::uint256{kTokenIndeX1}, xrpl::uint256{kTokenIndeX2}}, kTokenIndeX1 ); - ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, _, _)) + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); auto const bbs = std::vector{ createMpTokenObject( - kACCOUNT, - ripple::uint192(kISSUANCE_ID_HEX), - kTOKEN1_AMOUNT, - ripple::lsfMPTLocked, - kTOKEN1_LOCKED_AMOUNT + kAccount, + xrpl::uint192(kIssuanceIdHex), + kTokeN1Amount, + xrpl::lsfMPTLocked, + kTokeN1LockedAmount ) .getSerializer() .peekData(), createMpTokenObject( - kACCOUNT, - ripple::uint192(kISSUANCE_ID_HEX), - kTOKEN2_AMOUNT, - ripple::lsfMPTAuthorized, + kAccount, + xrpl::uint192(kIssuanceIdHex), + kTokeN2Amount, + xrpl::lsfMPTAuthorized, std::nullopt ) .getSerializer() @@ -385,39 +385,40 @@ TEST_F(RPCAccountMPTokensHandlerTest, DefaultParameters) {} ] }})JSON", - kACCOUNT, - kLEDGER_HASH, - AccountMPTokensHandler::kLIMIT_DEFAULT, - kTOKEN_OUT1, - kTOKEN_OUT2 + kAccount, + kLedgerHash, + AccountMPTokensHandler::kLimitDefault, + kTokenOuT1, + kTokenOuT2 ); - auto const input = json::parse(fmt::format(R"JSON({{"account": "{}"}})JSON", kACCOUNT)); + auto const input = + boost::json::parse(fmt::format(R"JSON({{"account": "{}"}})JSON", kAccount)); auto const handler = AnyHandler{AccountMPTokensHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(expected), *output.result); + EXPECT_EQ(boost::json::parse(expected), *output.result); }); } TEST_F(RPCAccountMPTokensHandlerTest, UseLimit) { - constexpr int kLIMIT = 20; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + constexpr int kLimit = 20; + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const owneDirKk = ripple::keylet::ownerDir(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - auto const indexes = std::vector(50, ripple::uint256{kTOKEN_INDEX1}); + auto const indexes = std::vector(50, xrpl::uint256{kTokenIndeX1}); auto const bbs = [&]() { std::vector v; v.reserve(50); for (int i = 0; i < 50; ++i) { v.push_back( - createMpTokenObject(kACCOUNT, ripple::uint192(kISSUANCE_ID_HEX), i, 0, std::nullopt) + createMpTokenObject(kAccount, xrpl::uint192(kIssuanceIdHex), i, 0, std::nullopt) .getSerializer() .peekData() ); @@ -425,24 +426,24 @@ TEST_F(RPCAccountMPTokensHandlerTest, UseLimit) return v; }(); - ripple::STObject ownerDir = createOwnerDirLedgerObject(indexes, kTOKEN_INDEX1); - ownerDir.setFieldU64(ripple::sfIndexNext, 99); - ON_CALL(*backend_, doFetchLedgerObject(owneDirKk, _, _)) + xrpl::STObject ownerDir = createOwnerDirLedgerObject(indexes, kTokenIndeX1); + ownerDir.setFieldU64(xrpl::sfIndexNext, 99); + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(7); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(3); - runSpawn([this, kLIMIT](auto yield) { - auto const input = json::parse( + runSpawn([this, kLimit](auto yield) { + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - kLIMIT + kAccount, + kLimit ) ); @@ -451,20 +452,20 @@ TEST_F(RPCAccountMPTokensHandlerTest, UseLimit) ASSERT_TRUE(output); auto const resultJson = output.result->as_object(); - EXPECT_EQ(resultJson.at("mptokens").as_array().size(), kLIMIT); + EXPECT_EQ(resultJson.at("mptokens").as_array().size(), kLimit); ASSERT_TRUE(resultJson.contains("marker")); EXPECT_THAT(boost::json::value_to(resultJson.at("marker")), EndsWith(",0")); }); runSpawn([this](auto yield) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountMPTokensHandler::kLIMIT_MIN - 1 + kAccount, + AccountMPTokensHandler::kLimitMin - 1 ) ); @@ -472,19 +473,19 @@ TEST_F(RPCAccountMPTokensHandlerTest, UseLimit) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ( - output.result->as_object().at("limit").as_uint64(), AccountMPTokensHandler::kLIMIT_MIN + output.result->as_object().at("limit").as_uint64(), AccountMPTokensHandler::kLimitMin ); }); runSpawn([this](auto yield) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountMPTokensHandler::kLIMIT_MAX + 1 + kAccount, + AccountMPTokensHandler::kLimitMax + 1 ) ); @@ -492,32 +493,31 @@ TEST_F(RPCAccountMPTokensHandlerTest, UseLimit) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ( - output.result->as_object().at("limit").as_uint64(), AccountMPTokensHandler::kLIMIT_MAX + output.result->as_object().at("limit").as_uint64(), AccountMPTokensHandler::kLimitMax ); }); } TEST_F(RPCAccountMPTokensHandlerTest, MarkerOutput) { - constexpr auto kNEXT_PAGE = 99; - constexpr auto kLIMIT = 15; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + constexpr auto kNextPage = 99; + constexpr auto kLimit = 15; + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; - auto const ownerDir2Kk = - ripple::keylet::page(ripple::keylet::ownerDir(account), kNEXT_PAGE).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; + auto const ownerDir2Kk = xrpl::keylet::page(xrpl::keylet::ownerDir(account), kNextPage).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); auto const bbs = [&]() { std::vector v; - v.reserve(kLIMIT); - for (int i = 0; i < kLIMIT; ++i) { + v.reserve(kLimit); + for (int i = 0; i < kLimit; ++i) { v.push_back( - createMpTokenObject(kACCOUNT, ripple::uint192(kISSUANCE_ID_HEX), i, 0, std::nullopt) + createMpTokenObject(kAccount, xrpl::uint192(kIssuanceIdHex), i, 0, std::nullopt) .getSerializer() .peekData() ); @@ -526,66 +526,66 @@ TEST_F(RPCAccountMPTokensHandlerTest, MarkerOutput) }(); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - std::vector indexes1; + std::vector indexes1; indexes1.reserve(10); for (int i = 0; i < 10; ++i) { - indexes1.emplace_back(kTOKEN_INDEX1); + indexes1.emplace_back(kTokenIndeX1); } - ripple::STObject ownerDir1 = createOwnerDirLedgerObject(indexes1, kTOKEN_INDEX1); - ownerDir1.setFieldU64(ripple::sfIndexNext, kNEXT_PAGE); + xrpl::STObject ownerDir1 = createOwnerDirLedgerObject(indexes1, kTokenIndeX1); + ownerDir1.setFieldU64(xrpl::sfIndexNext, kNextPage); ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillByDefault(Return(ownerDir1.getSerializer().peekData())); - ripple::STObject ownerDir2 = createOwnerDirLedgerObject(indexes1, kTOKEN_INDEX2); - ownerDir2.setFieldU64(ripple::sfIndexNext, 0); + xrpl::STObject ownerDir2 = createOwnerDirLedgerObject(indexes1, kTokenIndeX2); + ownerDir2.setFieldU64(xrpl::sfIndexNext, 0); ON_CALL(*backend_, doFetchLedgerObject(ownerDir2Kk, _, _)) .WillByDefault(Return(ownerDir2.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); - runSpawn([this, kLIMIT, kNEXT_PAGE](auto yield) { - auto const input = json::parse( + runSpawn([this, kLimit, kNextPage](auto yield) { + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - kLIMIT + kAccount, + kLimit ) ); auto const handler = AnyHandler{AccountMPTokensHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); auto const& resultJson = output.result->as_object(); - EXPECT_EQ(resultJson.at("mptokens").as_array().size(), kLIMIT); + EXPECT_EQ(resultJson.at("mptokens").as_array().size(), kLimit); EXPECT_EQ( boost::json::value_to(resultJson.at("marker")), - fmt::format("{},{}", kTOKEN_INDEX1, kNEXT_PAGE) + fmt::format("{},{}", kTokenIndeX1, kNextPage) ); }); } TEST_F(RPCAccountMPTokensHandlerTest, MarkerInput) { - constexpr auto kNEXT_PAGE = 99; - constexpr auto kLIMIT = 15; + constexpr auto kNextPage = 99; + constexpr auto kLimit = 15; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - auto const ownerDirKk = ripple::keylet::page(ripple::keylet::ownerDir(account), kNEXT_PAGE).key; + auto const ownerDirKk = xrpl::keylet::page(xrpl::keylet::ownerDir(account), kNextPage).key; - auto const indexes = std::vector(kLIMIT, ripple::uint256{kTOKEN_INDEX1}); + auto const indexes = std::vector(kLimit, xrpl::uint256{kTokenIndeX1}); auto const bbs = [&]() { std::vector v; - v.reserve(kLIMIT); - for (int i = 0; i < kLIMIT; ++i) { + v.reserve(kLimit); + for (int i = 0; i < kLimit; ++i) { v.push_back( - createMpTokenObject(kACCOUNT, ripple::uint192(kISSUANCE_ID_HEX), i, 0, std::nullopt) + createMpTokenObject(kAccount, xrpl::uint192(kIssuanceIdHex), i, 0, std::nullopt) .getSerializer() .peekData() ); @@ -593,26 +593,26 @@ TEST_F(RPCAccountMPTokensHandlerTest, MarkerInput) return v; }(); - ripple::STObject ownerDir = createOwnerDirLedgerObject(indexes, kTOKEN_INDEX1); - ownerDir.setFieldU64(ripple::sfIndexNext, 0); + xrpl::STObject ownerDir = createOwnerDirLedgerObject(indexes, kTokenIndeX1); + ownerDir.setFieldU64(xrpl::sfIndexNext, 0); ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - runSpawn([this, kLIMIT, kNEXT_PAGE](auto yield) { - auto const input = json::parse( + runSpawn([this, kLimit, kNextPage](auto yield) { + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {}, "marker": "{},{}" }})JSON", - kACCOUNT, - kLIMIT, - kTOKEN_INDEX1, - kNEXT_PAGE + kAccount, + kLimit, + kTokenIndeX1, + kNextPage ) ); auto const handler = AnyHandler{AccountMPTokensHandler{this->backend_}}; @@ -620,43 +620,43 @@ TEST_F(RPCAccountMPTokensHandlerTest, MarkerInput) ASSERT_TRUE(output); auto const& resultJson = output.result->as_object(); EXPECT_TRUE(resultJson.if_contains("marker") == nullptr); - EXPECT_EQ(resultJson.at("mptokens").as_array().size(), kLIMIT - 1); + EXPECT_EQ(resultJson.at("mptokens").as_array().size(), kLimit - 1); }); } TEST_F(RPCAccountMPTokensHandlerTest, LimitLessThanMin) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const owneDirKk = ripple::keylet::ownerDir(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - ripple::STObject const ownerDir = createOwnerDirLedgerObject( - {ripple::uint256{kTOKEN_INDEX1}, ripple::uint256{kTOKEN_INDEX2}}, kTOKEN_INDEX1 + xrpl::STObject const ownerDir = createOwnerDirLedgerObject( + {xrpl::uint256{kTokenIndeX1}, xrpl::uint256{kTokenIndeX2}}, kTokenIndeX1 ); - EXPECT_CALL(*backend_, doFetchLedgerObject(owneDirKk, _, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); auto const bbs = std::vector{ createMpTokenObject( - kACCOUNT, - ripple::uint192(kISSUANCE_ID_HEX), - kTOKEN1_AMOUNT, - ripple::lsfMPTLocked, - kTOKEN1_LOCKED_AMOUNT + kAccount, + xrpl::uint192(kIssuanceIdHex), + kTokeN1Amount, + xrpl::lsfMPTLocked, + kTokeN1LockedAmount ) .getSerializer() .peekData(), createMpTokenObject( - kACCOUNT, - ripple::uint192(kISSUANCE_ID_HEX), - kTOKEN2_AMOUNT, - ripple::lsfMPTAuthorized, + kAccount, + xrpl::uint192(kIssuanceIdHex), + kTokeN2Amount, + xrpl::lsfMPTAuthorized, std::nullopt ) .getSerializer() @@ -666,14 +666,14 @@ TEST_F(RPCAccountMPTokensHandlerTest, LimitLessThanMin) EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); runSpawn([this](auto yield) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountMPTokensHandler::kLIMIT_MIN - 1 + kAccount, + AccountMPTokensHandler::kLimitMin - 1 ) ); @@ -689,53 +689,53 @@ TEST_F(RPCAccountMPTokensHandlerTest, LimitLessThanMin) {} ] }})JSON", - kACCOUNT, - kLEDGER_HASH, - AccountMPTokensHandler::kLIMIT_MIN, - kTOKEN_OUT1, - kTOKEN_OUT2 + kAccount, + kLedgerHash, + AccountMPTokensHandler::kLimitMin, + kTokenOuT1, + kTokenOuT2 ); auto const handler = AnyHandler{AccountMPTokensHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(correctOutput), *output.result); + EXPECT_EQ(boost::json::parse(correctOutput), *output.result); }); } TEST_F(RPCAccountMPTokensHandlerTest, LimitMoreThanMax) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const owneDirKk = ripple::keylet::ownerDir(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - ripple::STObject const ownerDir = createOwnerDirLedgerObject( - {ripple::uint256{kTOKEN_INDEX1}, ripple::uint256{kTOKEN_INDEX2}}, kTOKEN_INDEX1 + xrpl::STObject const ownerDir = createOwnerDirLedgerObject( + {xrpl::uint256{kTokenIndeX1}, xrpl::uint256{kTokenIndeX2}}, kTokenIndeX1 ); - EXPECT_CALL(*backend_, doFetchLedgerObject(owneDirKk, _, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); auto const bbs = std::vector{ createMpTokenObject( - kACCOUNT, - ripple::uint192(kISSUANCE_ID_HEX), - kTOKEN1_AMOUNT, - ripple::lsfMPTLocked, - kTOKEN1_LOCKED_AMOUNT + kAccount, + xrpl::uint192(kIssuanceIdHex), + kTokeN1Amount, + xrpl::lsfMPTLocked, + kTokeN1LockedAmount ) .getSerializer() .peekData(), createMpTokenObject( - kACCOUNT, - ripple::uint192(kISSUANCE_ID_HEX), - kTOKEN2_AMOUNT, - ripple::lsfMPTAuthorized, + kAccount, + xrpl::uint192(kIssuanceIdHex), + kTokeN2Amount, + xrpl::lsfMPTAuthorized, std::nullopt ) .getSerializer() @@ -745,14 +745,14 @@ TEST_F(RPCAccountMPTokensHandlerTest, LimitMoreThanMax) EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); runSpawn([this](auto yield) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountMPTokensHandler::kLIMIT_MAX + 1 + kAccount, + AccountMPTokensHandler::kLimitMax + 1 ) ); @@ -768,42 +768,42 @@ TEST_F(RPCAccountMPTokensHandlerTest, LimitMoreThanMax) {} ] }})JSON", - kACCOUNT, - kLEDGER_HASH, - AccountMPTokensHandler::kLIMIT_MAX, - kTOKEN_OUT1, - kTOKEN_OUT2 + kAccount, + kLedgerHash, + AccountMPTokensHandler::kLimitMax, + kTokenOuT1, + kTokenOuT2 ); auto const handler = AnyHandler{AccountMPTokensHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(correctOutput), *output.result); + EXPECT_EQ(boost::json::parse(correctOutput), *output.result); }); } TEST_F(RPCAccountMPTokensHandlerTest, EmptyResult) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - auto const owneDirKk = ripple::keylet::ownerDir(account).key; + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - ripple::STObject const ownerDir = createOwnerDirLedgerObject({}, kTOKEN_INDEX1); - EXPECT_CALL(*backend_, doFetchLedgerObject(owneDirKk, _, _)) + xrpl::STObject const ownerDir = createOwnerDirLedgerObject({}, kTokenIndeX1); + EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); runSpawn([this](auto yield) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountMPTokensHandler{this->backend_}}; @@ -812,3 +812,79 @@ TEST_F(RPCAccountMPTokensHandlerTest, EmptyResult) EXPECT_EQ(output.result->as_object().at("mptokens").as_array().size(), 0); }); } + +// Regression test: UInt64 amount fields must be serialized as base-10 JSON strings (as xrpld +// does) so that values greater than 2^53 are not silently rounded by JSON parsers backed by +// IEEE-754 doubles. 2^53 itself is still exactly representable as a double, but it must be emitted +// as a string like every other amount so the wire format stays consistent regardless of magnitude. +struct AccountMPTokensAmountSerializationTestCaseBundle { + std::string testName; + uint64_t mptAmount; + uint64_t lockedAmount; +}; + +struct AccountMPTokensAmountSerializationTest + : RPCAccountMPTokensHandlerTest, + WithParamInterface {}; + +INSTANTIATE_TEST_SUITE_P( + RPCAccountMPTokensAmountSerializationGroup, + AccountMPTokensAmountSerializationTest, + ValuesIn( + std::vector{ + {.testName = "LargeAmounts", + .mptAmount = static_cast(std::pow(2, 63)) - 1, // max MPT amount + .lockedAmount = static_cast(std::pow(2, 53)) + 1}, + {.testName = "ExactDoubleBoundary", + .mptAmount = static_cast(std::pow(2, 53)), + .lockedAmount = static_cast(std::pow(2, 53))} + } + ), + tests::util::kNameGenerator +); + +TEST_P(AccountMPTokensAmountSerializationTest, SerializedAsStrings) +{ + auto const testBundle = GetParam(); + + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); + EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); + + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, _, _)) + .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); + + xrpl::STObject const ownerDir = + createOwnerDirLedgerObject({xrpl::uint256{kTokenIndeX1}}, kTokenIndeX1); + EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, _, _)) + .WillOnce(Return(ownerDir.getSerializer().peekData())); + + xrpl::STObject const mptoken = createMpTokenObject( + kAccount, + xrpl::uint192(kIssuanceIdHex), + testBundle.mptAmount, + xrpl::lsfMPTLocked, + testBundle.lockedAmount + ); + auto const bbs = std::vector{mptoken.getSerializer().peekData()}; + EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); + + runSpawn([&, this](auto yield) { + auto const input = + boost::json::parse(fmt::format(R"JSON({{"account": "{}"}})JSON", kAccount)); + auto const handler = AnyHandler{AccountMPTokensHandler{this->backend_}}; + auto const output = handler.process(input, Context{yield}); + ASSERT_TRUE(output); + + auto const& mptokens = output.result->as_object().at("mptokens").as_array(); + ASSERT_EQ(mptokens.size(), 1); + auto const& token = mptokens[0].as_object(); + + ASSERT_TRUE(token.at("mpt_amount").is_string()); + EXPECT_EQ(token.at("mpt_amount").as_string(), std::to_string(testBundle.mptAmount)); + ASSERT_TRUE(token.at("locked_amount").is_string()); + EXPECT_EQ(token.at("locked_amount").as_string(), std::to_string(testBundle.lockedAmount)); + }); +} diff --git a/tests/unit/rpc/handlers/AccountNFTsTests.cpp b/tests/unit/rpc/handlers/AccountNFTsTests.cpp index d59046140..5a5389e47 100644 --- a/tests/unit/rpc/handlers/AccountNFTsTests.cpp +++ b/tests/unit/rpc/handlers/AccountNFTsTests.cpp @@ -23,30 +23,29 @@ namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kTOKEN_ID = "000827103B94ECBB7BF0A0A6ED62B3607801A27B65F4679F4AD1D4850000C0EA"; -constexpr auto kISSUER = "raSsG8F6KePke7sqw2MXYZ3mu7p68GvFma"; -constexpr auto kSERIAL = 49386; -constexpr auto kTAX_ON = 0; -constexpr auto kFLAG = 8; -constexpr auto kTXN_ID = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kPAGE = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; -constexpr auto kINVALID_PAGE = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FCAAA"; -constexpr auto kMAX_SEQ = 30; -constexpr auto kMIN_SEQ = 10; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kTokenId = "000827103B94ECBB7BF0A0A6ED62B3607801A27B65F4679F4AD1D4850000C0EA"; +constexpr auto kIssuer = "raSsG8F6KePke7sqw2MXYZ3mu7p68GvFma"; +constexpr auto kSerial = 49386; +constexpr auto kTaxOn = 0; +constexpr auto kFlag = 8; +constexpr auto kTxnId = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kPage = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; +constexpr auto kInvalidPage = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FCAAA"; +constexpr auto kMaxSeq = 30; +constexpr auto kMinSeq = 10; } // namespace using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; struct RPCAccountNFTsHandlerTest : HandlerBaseTest { RPCAccountNFTsHandlerTest() { - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); } }; @@ -144,7 +143,7 @@ INSTANTIATE_TEST_CASE_P( RPCAccountNFTsGroup1, AccountNFTParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(AccountNFTParameterTest, InvalidParams) @@ -152,7 +151,7 @@ TEST_P(AccountNFTParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountNFTsHandler{backend_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -165,22 +164,22 @@ TEST_F(RPCAccountNFTsHandlerTest, LedgerNotFoundViaHash) { EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // return empty ledgerHeader - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); auto const handler = AnyHandler{AccountNFTsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -190,26 +189,26 @@ TEST_F(RPCAccountNFTsHandlerTest, LedgerNotFoundViaHash) TEST_F(RPCAccountNFTsHandlerTest, LedgerNotFoundViaStringIndex) { - constexpr auto kSEQ = 12; + constexpr auto kSeq = 12; EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return empty ledgerHeader - ON_CALL(*backend_, fetchLedgerBySequence(kSEQ, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerBySequence(kSeq, _)) + .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "{}" }})JSON", - kACCOUNT, - kSEQ + kAccount, + kSeq ) ); auto const handler = AnyHandler{AccountNFTsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -219,26 +218,26 @@ TEST_F(RPCAccountNFTsHandlerTest, LedgerNotFoundViaStringIndex) TEST_F(RPCAccountNFTsHandlerTest, LedgerNotFoundViaIntIndex) { - constexpr auto kSEQ = 12; + constexpr auto kSeq = 12; EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return empty ledgerHeader - ON_CALL(*backend_, fetchLedgerBySequence(kSEQ, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerBySequence(kSeq, _)) + .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": {} }})JSON", - kACCOUNT, - kSEQ + kAccount, + kSeq ) ); auto const handler = AnyHandler{AccountNFTsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -248,24 +247,24 @@ TEST_F(RPCAccountNFTsHandlerTest, LedgerNotFoundViaIntIndex) TEST_F(RPCAccountNFTsHandlerTest, AccountNotFound) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); ON_CALL(*backend_, doFetchLedgerObject).WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountNFTsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "actNotFound"); @@ -275,7 +274,7 @@ TEST_F(RPCAccountNFTsHandlerTest, AccountNotFound) TEST_F(RPCAccountNFTsHandlerTest, NormalPath) { - static auto const kEXPECTED_OUTPUT = fmt::format( + static auto const kExpectedOutput = fmt::format( R"JSON({{ "ledger_hash": "{}", "ledger_index": 30, @@ -294,119 +293,119 @@ TEST_F(RPCAccountNFTsHandlerTest, NormalPath) ], "limit": 100 }})JSON", - kLEDGER_HASH, - kACCOUNT, - kTOKEN_ID, - kFLAG, - kISSUER, - kTAX_ON, - kSERIAL + kLedgerHash, + kAccount, + kTokenId, + kFlag, + kIssuer, + kTaxOn, + kSerial ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const accountObject = createAccountRootObject(kACCOUNT, 0, 1, 10, 2, kTXN_ID, 3); - auto const accountID = getAccountIdWithString(kACCOUNT); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::account(accountID).key, 30, _)) + auto const accountObject = createAccountRootObject(kAccount, 0, 1, 10, 2, kTxnId, 3); + auto const accountID = getAccountIdWithString(kAccount); + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::account(accountID).key, 30, _)) .WillByDefault(Return(accountObject.getSerializer().peekData())); - auto const firstPage = ripple::keylet::nftpage_max(accountID).key; + auto const firstPage = xrpl::keylet::nftokenPageMax(accountID).key; auto const pageObject = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, std::nullopt + std::vector{std::make_pair(kTokenId, "www.ok.com")}, std::nullopt ); ON_CALL(*backend_, doFetchLedgerObject(firstPage, 30, _)) .WillByDefault(Return(pageObject.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountNFTsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUTPUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOutput)); }); } TEST_F(RPCAccountNFTsHandlerTest, Limit) { - static constexpr auto kLIMIT = 20; + static constexpr auto kLimit = 20; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const accountObject = createAccountRootObject(kACCOUNT, 0, 1, 10, 2, kTXN_ID, 3); - auto const accountID = getAccountIdWithString(kACCOUNT); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::account(accountID).key, 30, _)) + auto const accountObject = createAccountRootObject(kAccount, 0, 1, 10, 2, kTxnId, 3); + auto const accountID = getAccountIdWithString(kAccount); + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::account(accountID).key, 30, _)) .WillByDefault(Return(accountObject.getSerializer().peekData())); - auto const firstPage = ripple::keylet::nftpage_max(accountID).key; + auto const firstPage = xrpl::keylet::nftokenPageMax(accountID).key; auto const pageObject = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, firstPage + std::vector{std::make_pair(kTokenId, "www.ok.com")}, firstPage ); ON_CALL(*backend_, doFetchLedgerObject(firstPage, 30, _)) .WillByDefault(Return(pageObject.getSerializer().peekData())); - EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1 + kLIMIT); + EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1 + kLimit); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - kLIMIT + kAccount, + kLimit ) ); auto const handler = AnyHandler{AccountNFTsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result->as_object().at("account_nfts").as_array().size(), 20); - EXPECT_EQ(output.result->as_object().at("marker").as_string(), ripple::strHex(firstPage)); + EXPECT_EQ(output.result->as_object().at("marker").as_string(), xrpl::strHex(firstPage)); }); } TEST_F(RPCAccountNFTsHandlerTest, Marker) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const accountObject = createAccountRootObject(kACCOUNT, 0, 1, 10, 2, kTXN_ID, 3); - auto const accountID = getAccountIdWithString(kACCOUNT); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::account(accountID).key, 30, _)) + auto const accountObject = createAccountRootObject(kAccount, 0, 1, 10, 2, kTxnId, 3); + auto const accountID = getAccountIdWithString(kAccount); + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::account(accountID).key, 30, _)) .WillByDefault(Return(accountObject.getSerializer().peekData())); auto const pageObject = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, std::nullopt + std::vector{std::make_pair(kTokenId, "www.ok.com")}, std::nullopt ); - ON_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kPAGE}, 30, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kPage}, 30, _)) .WillByDefault(Return(pageObject.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": "{}" }})JSON", - kACCOUNT, - kPAGE + kAccount, + kPage ) ); auto const handler = AnyHandler{AccountNFTsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result->as_object().at("account_nfts").as_array().size(), 1); }); @@ -414,28 +413,28 @@ TEST_F(RPCAccountNFTsHandlerTest, Marker) TEST_F(RPCAccountNFTsHandlerTest, InvalidMarker) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const accountObject = createAccountRootObject(kACCOUNT, 0, 1, 10, 2, kTXN_ID, 3); - auto const accountID = getAccountIdWithString(kACCOUNT); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::account(accountID).key, 30, _)) + auto const accountObject = createAccountRootObject(kAccount, 0, 1, 10, 2, kTxnId, 3); + auto const accountID = getAccountIdWithString(kAccount); + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::account(accountID).key, 30, _)) .WillByDefault(Return(accountObject.getSerializer().peekData())); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": "{}" }})JSON", - kACCOUNT, - kINVALID_PAGE + kAccount, + kInvalidPage ) ); auto const handler = AnyHandler{AccountNFTsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "invalidParams"); @@ -447,26 +446,26 @@ TEST_F(RPCAccountNFTsHandlerTest, InvalidMarker) TEST_F(RPCAccountNFTsHandlerTest, AccountWithNoNFT) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const accountObject = createAccountRootObject(kACCOUNT, 0, 1, 10, 2, kTXN_ID, 3); - auto const accountID = getAccountIdWithString(kACCOUNT); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::account(accountID).key, 30, _)) + auto const accountObject = createAccountRootObject(kAccount, 0, 1, 10, 2, kTxnId, 3); + auto const accountID = getAccountIdWithString(kAccount); + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::account(accountID).key, 30, _)) .WillByDefault(Return(accountObject.getSerializer().peekData())); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountNFTsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result->as_object().at("account_nfts").as_array().size(), 0); }); @@ -474,35 +473,35 @@ TEST_F(RPCAccountNFTsHandlerTest, AccountWithNoNFT) TEST_F(RPCAccountNFTsHandlerTest, invalidPage) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const accountObject = createAccountRootObject(kACCOUNT, 0, 1, 10, 2, kTXN_ID, 3); - auto const accountID = getAccountIdWithString(kACCOUNT); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::account(accountID).key, 30, _)) + auto const accountObject = createAccountRootObject(kAccount, 0, 1, 10, 2, kTxnId, 3); + auto const accountID = getAccountIdWithString(kAccount); + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::account(accountID).key, 30, _)) .WillByDefault(Return(accountObject.getSerializer().peekData())); auto const pageObject = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, std::nullopt + std::vector{std::make_pair(kTokenId, "www.ok.com")}, std::nullopt ); - ON_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kPAGE}, 30, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kPage}, 30, _)) .WillByDefault(Return(accountObject.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": "{}" }})JSON", - kACCOUNT, - kPAGE + kAccount, + kPage ) ); auto const handler = AnyHandler{AccountNFTsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "invalidParams"); @@ -514,7 +513,7 @@ TEST_F(RPCAccountNFTsHandlerTest, invalidPage) TEST_F(RPCAccountNFTsHandlerTest, LimitLessThanMin) { - static auto const kEXPECTED_OUTPUT = fmt::format( + static auto const kExpectedOutput = fmt::format( R"JSON({{ "ledger_hash": "{}", "ledger_index": 30, @@ -533,54 +532,54 @@ TEST_F(RPCAccountNFTsHandlerTest, LimitLessThanMin) ], "limit": {} }})JSON", - kLEDGER_HASH, - kACCOUNT, - kTOKEN_ID, - kFLAG, - kISSUER, - kTAX_ON, - kSERIAL, - AccountNFTsHandler::kLIMIT_MIN + kLedgerHash, + kAccount, + kTokenId, + kFlag, + kIssuer, + kTaxOn, + kSerial, + AccountNFTsHandler::kLimitMin ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const accountObject = createAccountRootObject(kACCOUNT, 0, 1, 10, 2, kTXN_ID, 3); - auto const accountID = getAccountIdWithString(kACCOUNT); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::account(accountID).key, 30, _)) + auto const accountObject = createAccountRootObject(kAccount, 0, 1, 10, 2, kTxnId, 3); + auto const accountID = getAccountIdWithString(kAccount); + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::account(accountID).key, 30, _)) .WillByDefault(Return(accountObject.getSerializer().peekData())); - auto const firstPage = ripple::keylet::nftpage_max(accountID).key; + auto const firstPage = xrpl::keylet::nftokenPageMax(accountID).key; auto const pageObject = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, std::nullopt + std::vector{std::make_pair(kTokenId, "www.ok.com")}, std::nullopt ); ON_CALL(*backend_, doFetchLedgerObject(firstPage, 30, _)) .WillByDefault(Return(pageObject.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountNFTsHandler::kLIMIT_MIN - 1 + kAccount, + AccountNFTsHandler::kLimitMin - 1 ) ); auto const handler = AnyHandler{AccountNFTsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUTPUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOutput)); }); } TEST_F(RPCAccountNFTsHandlerTest, LimitMoreThanMax) { - static auto const kEXPECTED_OUTPUT = fmt::format( + static auto const kExpectedOutput = fmt::format( R"JSON({{ "ledger_hash": "{}", "ledger_index": 30, @@ -599,47 +598,47 @@ TEST_F(RPCAccountNFTsHandlerTest, LimitMoreThanMax) ], "limit": {} }})JSON", - kLEDGER_HASH, - kACCOUNT, - kTOKEN_ID, - kFLAG, - kISSUER, - kTAX_ON, - kSERIAL, - AccountNFTsHandler::kLIMIT_MAX + kLedgerHash, + kAccount, + kTokenId, + kFlag, + kIssuer, + kTaxOn, + kSerial, + AccountNFTsHandler::kLimitMax ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const accountObject = createAccountRootObject(kACCOUNT, 0, 1, 10, 2, kTXN_ID, 3); - auto const accountID = getAccountIdWithString(kACCOUNT); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::account(accountID).key, 30, _)) + auto const accountObject = createAccountRootObject(kAccount, 0, 1, 10, 2, kTxnId, 3); + auto const accountID = getAccountIdWithString(kAccount); + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::account(accountID).key, 30, _)) .WillByDefault(Return(accountObject.getSerializer().peekData())); - auto const firstPage = ripple::keylet::nftpage_max(accountID).key; + auto const firstPage = xrpl::keylet::nftokenPageMax(accountID).key; auto const pageObject = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, std::nullopt + std::vector{std::make_pair(kTokenId, "www.ok.com")}, std::nullopt ); ON_CALL(*backend_, doFetchLedgerObject(firstPage, 30, _)) .WillByDefault(Return(pageObject.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountNFTsHandler::kLIMIT_MAX + 1 + kAccount, + AccountNFTsHandler::kLimitMax + 1 ) ); auto const handler = AnyHandler{AccountNFTsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUTPUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOutput)); }); } diff --git a/tests/unit/rpc/handlers/AccountObjectsTests.cpp b/tests/unit/rpc/handlers/AccountObjectsTests.cpp index dfeabe82e..9de0dc2ac 100644 --- a/tests/unit/rpc/handlers/AccountObjectsTests.cpp +++ b/tests/unit/rpc/handlers/AccountObjectsTests.cpp @@ -30,27 +30,26 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kISSUER = "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kINDEX1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; -constexpr auto kTXN_ID = "E3FE6EA3D48F0C2B639448020EA4F03D4F4F8FFDB243A852A0F59177921B4879"; -constexpr auto kTOKEN_ID = "000827103B94ECBB7BF0A0A6ED62B3607801A27B65F4679F4AD1D4850000C0EA"; -constexpr auto kMAX_SEQ = 30; -constexpr auto kMIN_SEQ = 10; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kIssuer = "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kIndex1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; +constexpr auto kTxnId = "E3FE6EA3D48F0C2B639448020EA4F03D4F4F8FFDB243A852A0F59177921B4879"; +constexpr auto kTokenId = "000827103B94ECBB7BF0A0A6ED62B3607801A27B65F4679F4AD1D4850000C0EA"; +constexpr auto kMaxSeq = 30; +constexpr auto kMinSeq = 10; } // namespace struct RPCAccountObjectsHandlerTest : HandlerBaseTest { RPCAccountObjectsHandlerTest() { - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); } }; @@ -191,7 +190,7 @@ INSTANTIATE_TEST_CASE_P( RPCAccountObjectsGroup1, AccountObjectsParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(AccountObjectsParameterTest, InvalidParams) @@ -199,7 +198,7 @@ TEST_P(AccountObjectsParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -211,21 +210,21 @@ TEST_P(AccountObjectsParameterTest, InvalidParams) TEST_F(RPCAccountObjectsHandlerTest, LedgerNonExistViaIntSequence) { // return empty ledgerHeader - EXPECT_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ, _)) - .WillOnce(Return(std::optional{})); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kMaxSeq, _)) + .WillOnce(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": 30 }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -236,20 +235,20 @@ TEST_F(RPCAccountObjectsHandlerTest, LedgerNonExistViaIntSequence) TEST_F(RPCAccountObjectsHandlerTest, LedgerNonExistViaStringSequence) { // return empty ledgerHeader - EXPECT_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ, _)).WillOnce(Return(std::nullopt)); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kMaxSeq, _)).WillOnce(Return(std::nullopt)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "30" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -260,22 +259,22 @@ TEST_F(RPCAccountObjectsHandlerTest, LedgerNonExistViaStringSequence) TEST_F(RPCAccountObjectsHandlerTest, LedgerNonExistViaHash) { // return empty ledgerHeader - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillOnce(Return(std::optional{})); + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillOnce(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -285,22 +284,22 @@ TEST_F(RPCAccountObjectsHandlerTest, LedgerNonExistViaHash) TEST_F(RPCAccountObjectsHandlerTest, AccountNotExist) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); EXPECT_CALL(*backend_, doFetchLedgerObject).WillOnce(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "actNotFound"); @@ -310,7 +309,7 @@ TEST_F(RPCAccountObjectsHandlerTest, AccountNotExist) TEST_F(RPCAccountObjectsHandlerTest, DefaultParameterNoNFTFound) { - static constexpr auto kEXPECTED_OUT = R"JSON({ + static constexpr auto kExpectedOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, "validated": true, @@ -342,118 +341,118 @@ TEST_F(RPCAccountObjectsHandlerTest, DefaultParameterNoNFTFound) ] })JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - auto const ownerDir = createOwnerDirLedgerObject({ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + auto const ownerDir = createOwnerDirLedgerObject({xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft null - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)).WillOnce(Return(std::nullopt)); std::vector bbs; auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); bbs.push_back(line1.getSerializer().peekData()); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCAccountObjectsHandlerTest, Limit) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - static constexpr auto kLIMIT = 10; - auto count = kLIMIT * 2; + static constexpr auto kLimit = 10; + auto count = kLimit * 2; // put 20 items in owner dir, but only return 10 auto const ownerDir = - createOwnerDirLedgerObject(std::vector(count, ripple::uint256{kINDEX1}), kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + createOwnerDirLedgerObject(std::vector(count, xrpl::uint256{kIndex1}), kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft null - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)).WillOnce(Return(std::nullopt)); std::vector bbs; while (count-- != 0) { auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); bbs.push_back(line1.getSerializer().peekData()); } EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - kLIMIT + kAccount, + kLimit ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->as_object().at("account_objects").as_array().size(), kLIMIT); + EXPECT_EQ(output.result->as_object().at("account_objects").as_array().size(), kLimit); EXPECT_EQ( - output.result->as_object().at("marker").as_string(), fmt::format("{},{}", kINDEX1, 0) + output.result->as_object().at("marker").as_string(), fmt::format("{},{}", kIndex1, 0) ); }); } TEST_F(RPCAccountObjectsHandlerTest, Marker) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - static constexpr auto kLIMIT = 20; - static constexpr auto kPAGE = 2; - auto count = kLIMIT; + static constexpr auto kLimit = 20; + static constexpr auto kPage = 2; + auto count = kLimit; auto const ownerDir = - createOwnerDirLedgerObject(std::vector(count, ripple::uint256{kINDEX1}), kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - auto const hintIndex = ripple::keylet::page(ownerDirKk, kPAGE).key; + createOwnerDirLedgerObject(std::vector(count, xrpl::uint256{kIndex1}), kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + auto const hintIndex = xrpl::keylet::page(ownerDirKk, kPage).key; EXPECT_CALL(*backend_, doFetchLedgerObject(hintIndex, 30, _)) .Times(2) .WillRepeatedly(Return(ownerDir.getSerializer().peekData())); @@ -461,147 +460,147 @@ TEST_F(RPCAccountObjectsHandlerTest, Marker) std::vector bbs; while (count-- != 0) { auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); bbs.push_back(line1.getSerializer().peekData()); } EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": "{},{}" }})JSON", - kACCOUNT, - kINDEX1, - kPAGE + kAccount, + kIndex1, + kPage ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->as_object().at("account_objects").as_array().size(), kLIMIT - 1); + EXPECT_EQ(output.result->as_object().at("account_objects").as_array().size(), kLimit - 1); EXPECT_FALSE(output.result->as_object().contains("marker")); }); } TEST_F(RPCAccountObjectsHandlerTest, MultipleDirNoNFT) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - static constexpr auto kCOUNT = 10; - static constexpr auto kNEXTPAGE = 1; - auto cc = kCOUNT; - auto ownerDir = createOwnerDirLedgerObject(std::vector(cc, ripple::uint256{kINDEX1}), kINDEX1); + static constexpr auto kCount = 10; + static constexpr auto kNextpage = 1; + auto cc = kCount; + auto ownerDir = createOwnerDirLedgerObject(std::vector(cc, xrpl::uint256{kIndex1}), kIndex1); // set next page - ownerDir.setFieldU64(ripple::sfIndexNext, kNEXTPAGE); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; - auto const page1 = ripple::keylet::page(ownerDirKk, kNEXTPAGE).key; + ownerDir.setFieldU64(xrpl::sfIndexNext, kNextpage); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; + auto const page1 = xrpl::keylet::page(ownerDirKk, kNextpage).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject(page1, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft null - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)).WillOnce(Return(std::nullopt)); std::vector bbs; // 10 items per page, 2 pages - cc = kCOUNT * 2; + cc = kCount * 2; while (cc-- != 0) { auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); bbs.push_back(line1.getSerializer().peekData()); } EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - 2 * kCOUNT + kAccount, + 2 * kCount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->as_object().at("account_objects").as_array().size(), kCOUNT * 2); + EXPECT_EQ(output.result->as_object().at("account_objects").as_array().size(), kCount * 2); EXPECT_EQ( output.result->as_object().at("marker").as_string(), - fmt::format("{},{}", kINDEX1, kNEXTPAGE) + fmt::format("{},{}", kIndex1, kNextpage) ); }); } TEST_F(RPCAccountObjectsHandlerTest, TypeFilter) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft null - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)).WillOnce(Return(std::nullopt)); std::vector bbs; // put 1 state and 1 offer auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); auto const offer = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); bbs.push_back(line1.getSerializer().peekData()); bbs.push_back(offer.getSerializer().peekData()); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "type": "offer" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result->as_object().at("account_objects").as_array().size(), 1); }); @@ -609,50 +608,50 @@ TEST_F(RPCAccountObjectsHandlerTest, TypeFilter) TEST_F(RPCAccountObjectsHandlerTest, TypeFilterAmmType) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft null - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)).WillOnce(Return(std::nullopt)); std::vector bbs; // put 1 state and 1 amm auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); bbs.push_back(line1.getSerializer().peekData()); auto const ammObject = - createAmmObject(kACCOUNT, "XRP", toBase58(ripple::xrpAccount()), "JPY", kACCOUNT2); + createAmmObject(kAccount, "XRP", toBase58(xrpl::xrpAccount()), "JPY", kAccount2); bbs.push_back(ammObject.getSerializer().peekData()); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "type": "amm" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); auto const& accountObjects = output.result->as_object().at("account_objects").as_array(); ASSERT_EQ(accountObjects.size(), 1); @@ -662,56 +661,56 @@ TEST_F(RPCAccountObjectsHandlerTest, TypeFilterAmmType) TEST_F(RPCAccountObjectsHandlerTest, TypeFilterReturnEmpty) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft null - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)).WillOnce(Return(std::nullopt)); std::vector bbs; auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); auto const offer = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); bbs.push_back(line1.getSerializer().peekData()); bbs.push_back(offer.getSerializer().peekData()); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "type": "check" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result->as_object().at("account_objects").as_array().size(), 0); }); @@ -719,39 +718,39 @@ TEST_F(RPCAccountObjectsHandlerTest, TypeFilterReturnEmpty) TEST_F(RPCAccountObjectsHandlerTest, DeletionBlockersOnlyFilter) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); + auto const account = getAccountIdWithString(kAccount); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft null - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)).WillOnce(Return(std::nullopt)); auto const line = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); auto const channel = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); auto const offer = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); std::vector bbs; @@ -761,19 +760,19 @@ TEST_F(RPCAccountObjectsHandlerTest, DeletionBlockersOnlyFilter) EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "deletion_blockers_only": true }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result->as_object().at("account_objects").as_array().size(), 2); }); @@ -781,29 +780,29 @@ TEST_F(RPCAccountObjectsHandlerTest, DeletionBlockersOnlyFilter) TEST_F(RPCAccountObjectsHandlerTest, DeletionBlockersOnlyFilterWithTypeFilter) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft null - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)).WillOnce(Return(std::nullopt)); auto const line = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); auto const channel = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); std::vector bbs; bbs.push_back(line.getSerializer().peekData()); @@ -811,20 +810,20 @@ TEST_F(RPCAccountObjectsHandlerTest, DeletionBlockersOnlyFilterWithTypeFilter) EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "deletion_blockers_only": true, "type": "payment_channel" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result->as_object().at("account_objects").as_array().size(), 1); }); @@ -832,43 +831,43 @@ TEST_F(RPCAccountObjectsHandlerTest, DeletionBlockersOnlyFilterWithTypeFilter) TEST_F(RPCAccountObjectsHandlerTest, DeletionBlockersOnlyFilterEmptyResult) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft null - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)).WillOnce(Return(std::nullopt)); auto const offer1 = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); auto const offer2 = createOfferLedgerObject( - kACCOUNT, + kAccount, 20, 30, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); std::vector bbs; @@ -877,19 +876,19 @@ TEST_F(RPCAccountObjectsHandlerTest, DeletionBlockersOnlyFilterEmptyResult) EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "deletion_blockers_only": true }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result->as_object().at("account_objects").as_array().size(), 0); }); @@ -900,42 +899,42 @@ TEST_F( DeletionBlockersOnlyFilterWithIncompatibleTypeYieldsEmptyResult ) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft null - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)).WillOnce(Return(std::nullopt)); auto const offer1 = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); auto const offer2 = createOfferLedgerObject( - kACCOUNT, + kAccount, 20, 30, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); std::vector bbs; @@ -944,20 +943,20 @@ TEST_F( EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "deletion_blockers_only": true, "type": "offer" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result->as_object().at("account_objects").as_array().size(), 0); }); @@ -965,7 +964,7 @@ TEST_F( TEST_F(RPCAccountObjectsHandlerTest, NFTMixOtherObjects) { - static constexpr auto kEXPECTED_OUT = R"JSON({ + static constexpr auto kExpectedOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, "validated": true, @@ -1028,157 +1027,158 @@ TEST_F(RPCAccountObjectsHandlerTest, NFTMixOtherObjects) ] })JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - auto const ownerDir = createOwnerDirLedgerObject({ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + auto const ownerDir = createOwnerDirLedgerObject({xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft page 1 - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; auto const nftPage2KK = - ripple::keylet::nftpage(ripple::keylet::nftpage_min(account), ripple::uint256{kINDEX1}).key; + xrpl::keylet::nftokenPage(xrpl::keylet::nftokenPageMin(account), xrpl::uint256{kIndex1}) + .key; auto const nftpage1 = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, nftPage2KK + std::vector{std::make_pair(kTokenId, "www.ok.com")}, nftPage2KK ); EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)) .WillOnce(Return(nftpage1.getSerializer().peekData())); // nft page 2 , end auto const nftpage2 = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, std::nullopt + std::vector{std::make_pair(kTokenId, "www.ok.com")}, std::nullopt ); EXPECT_CALL(*backend_, doFetchLedgerObject(nftPage2KK, 30, _)) .WillOnce(Return(nftpage2.getSerializer().peekData())); std::vector bbs; auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); bbs.push_back(line1.getSerializer().peekData()); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCAccountObjectsHandlerTest, NFTReachLimitReturnMarker) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - auto current = ripple::keylet::nftpage_max(account).key; - std::string first{kINDEX1}; + auto current = xrpl::keylet::nftokenPageMax(account).key; + std::string first{kIndex1}; std::ranges::sort(first); for (auto i = 0; i < 10; i++) { std::ranges::next_permutation(first); - auto previous = ripple::keylet::nftpage( - ripple::keylet::nftpage_min(account), ripple::uint256{first.c_str()} + auto previous = xrpl::keylet::nftokenPage( + xrpl::keylet::nftokenPageMin(account), xrpl::uint256{first.c_str()} ) .key; auto const nftpage = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, previous + std::vector{std::make_pair(kTokenId, "www.ok.com")}, previous ); EXPECT_CALL(*backend_, doFetchLedgerObject(current, 30, _)) .WillOnce(Return(nftpage.getSerializer().peekData())); current = previous; } - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, + kAccount, 10 ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result.value().as_object().at("account_objects").as_array().size(), 10); EXPECT_EQ( output.result.value().as_object().at("marker").as_string(), - fmt::format("{},{}", ripple::strHex(current), std::numeric_limits::max()) + fmt::format("{},{}", xrpl::strHex(current), std::numeric_limits::max()) ); }); } TEST_F(RPCAccountObjectsHandlerTest, NFTReachLimitNoMarker) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - auto current = ripple::keylet::nftpage_max(account).key; - std::string first{kINDEX1}; + auto current = xrpl::keylet::nftokenPageMax(account).key; + std::string first{kIndex1}; std::ranges::sort(first); for (auto i = 0; i < 10; i++) { std::ranges::next_permutation(first); - auto previous = ripple::keylet::nftpage( - ripple::keylet::nftpage_min(account), ripple::uint256{first.c_str()} + auto previous = xrpl::keylet::nftokenPage( + xrpl::keylet::nftokenPageMin(account), xrpl::uint256{first.c_str()} ) .key; auto const nftpage = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, previous + std::vector{std::make_pair(kTokenId, "www.ok.com")}, previous ); EXPECT_CALL(*backend_, doFetchLedgerObject(current, 30, _)) .WillOnce(Return(nftpage.getSerializer().peekData())); current = previous; } auto const nftpage11 = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, std::nullopt + std::vector{std::make_pair(kTokenId, "www.ok.com")}, std::nullopt ); EXPECT_CALL(*backend_, doFetchLedgerObject(current, 30, _)) .WillOnce(Return(nftpage11.getSerializer().peekData())); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, + kAccount, 11 ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result.value().as_object().at("account_objects").as_array().size(), 11); //"0000000000000000000000000000000000000000000000000000000000000000,4294967295" @@ -1186,7 +1186,7 @@ TEST_F(RPCAccountObjectsHandlerTest, NFTReachLimitNoMarker) output.result.value().as_object().at("marker").as_string(), fmt::format( "{},{}", - ripple::strHex(ripple::uint256(beast::zero)), + xrpl::strHex(xrpl::uint256(beast::kZero)), std::numeric_limits::max() ) ); @@ -1195,61 +1195,61 @@ TEST_F(RPCAccountObjectsHandlerTest, NFTReachLimitNoMarker) TEST_F(RPCAccountObjectsHandlerTest, NFTMarker) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - std::string first{kINDEX1}; - auto current = ripple::keylet::nftpage( - ripple::keylet::nftpage_min(account), ripple::uint256{first.c_str()} + std::string first{kIndex1}; + auto current = xrpl::keylet::nftokenPage( + xrpl::keylet::nftokenPageMin(account), xrpl::uint256{first.c_str()} ) .key; auto const marker = current; std::ranges::sort(first); for (auto i = 0; i < 10; i++) { std::ranges::next_permutation(first); - auto previous = ripple::keylet::nftpage( - ripple::keylet::nftpage_min(account), ripple::uint256{first.c_str()} + auto previous = xrpl::keylet::nftokenPage( + xrpl::keylet::nftokenPageMin(account), xrpl::uint256{first.c_str()} ) .key; auto const nftpage = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, previous + std::vector{std::make_pair(kTokenId, "www.ok.com")}, previous ); EXPECT_CALL(*backend_, doFetchLedgerObject(current, 30, _)) .WillOnce(Return(nftpage.getSerializer().peekData())); current = previous; } auto const nftpage11 = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, std::nullopt + std::vector{std::make_pair(kTokenId, "www.ok.com")}, std::nullopt ); EXPECT_CALL(*backend_, doFetchLedgerObject(current, 30, _)) .WillOnce(Return(nftpage11.getSerializer().peekData())); auto const ownerDir = createOwnerDirLedgerObject( - {ripple::uint256{kINDEX1}, ripple::uint256{kINDEX1}, ripple::uint256{kINDEX1}}, kINDEX1 + {xrpl::uint256{kIndex1}, xrpl::uint256{kIndex1}, xrpl::uint256{kIndex1}}, kIndex1 ); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); auto const line = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); auto const channel = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); auto const offer = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); std::vector bbs; @@ -1259,21 +1259,21 @@ TEST_F(RPCAccountObjectsHandlerTest, NFTMarker) EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": "{},{}" }})JSON", - kACCOUNT, - ripple::strHex(marker), + kAccount, + xrpl::strHex(marker), std::numeric_limits::max() ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ( output.result.value().as_object().at("account_objects").as_array().size(), 11 + 3 @@ -1285,35 +1285,35 @@ TEST_F(RPCAccountObjectsHandlerTest, NFTMarker) // when limit reached, happen to be the end of NFT page list TEST_F(RPCAccountObjectsHandlerTest, NFTMarkerNoMoreNFT) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); auto const ownerDir = createOwnerDirLedgerObject( - {ripple::uint256{kINDEX1}, ripple::uint256{kINDEX1}, ripple::uint256{kINDEX1}}, kINDEX1 + {xrpl::uint256{kIndex1}, xrpl::uint256{kIndex1}, xrpl::uint256{kIndex1}}, kIndex1 ); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); auto const line = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); auto const channel = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); auto const offer = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); std::vector bbs; @@ -1323,21 +1323,21 @@ TEST_F(RPCAccountObjectsHandlerTest, NFTMarkerNoMoreNFT) EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": "{},{}" }})JSON", - kACCOUNT, - ripple::strHex(ripple::uint256{beast::zero}), + kAccount, + xrpl::strHex(xrpl::uint256{beast::kZero}), std::numeric_limits::max() ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result.value().as_object().at("account_objects").as_array().size(), 3); EXPECT_FALSE(output.result.value().as_object().contains("marker")); @@ -1346,29 +1346,29 @@ TEST_F(RPCAccountObjectsHandlerTest, NFTMarkerNoMoreNFT) TEST_F(RPCAccountObjectsHandlerTest, NFTMarkerNotInRange) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": "{},{}" }})JSON", - kACCOUNT, - kINDEX1, + kAccount, + kIndex1, std::numeric_limits::max() ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "invalidParams"); @@ -1378,34 +1378,34 @@ TEST_F(RPCAccountObjectsHandlerTest, NFTMarkerNotInRange) TEST_F(RPCAccountObjectsHandlerTest, NFTMarkerNotExist) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); // return null for this marker - auto const accountNftMax = ripple::keylet::nftpage_max(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountNftMax, kMAX_SEQ, _)) + auto const accountNftMax = xrpl::keylet::nftokenPageMax(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountNftMax, kMaxSeq, _)) .WillOnce(Return(std::nullopt)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": "{},{}" }})JSON", - kACCOUNT, - ripple::strHex(accountNftMax), + kAccount, + xrpl::strHex(accountNftMax), std::numeric_limits::max() ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "invalidParams"); @@ -1415,60 +1415,60 @@ TEST_F(RPCAccountObjectsHandlerTest, NFTMarkerNotExist) TEST_F(RPCAccountObjectsHandlerTest, NFTLimitAdjust) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - std::string first{kINDEX1}; - auto current = ripple::keylet::nftpage( - ripple::keylet::nftpage_min(account), ripple::uint256{first.c_str()} + std::string first{kIndex1}; + auto current = xrpl::keylet::nftokenPage( + xrpl::keylet::nftokenPageMin(account), xrpl::uint256{first.c_str()} ) .key; auto const marker = current; std::ranges::sort(first); for (auto i = 0; i < 10; i++) { std::ranges::next_permutation(first); - auto previous = ripple::keylet::nftpage( - ripple::keylet::nftpage_min(account), ripple::uint256{first.c_str()} + auto previous = xrpl::keylet::nftokenPage( + xrpl::keylet::nftokenPageMin(account), xrpl::uint256{first.c_str()} ) .key; auto const nftpage = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, previous + std::vector{std::make_pair(kTokenId, "www.ok.com")}, previous ); EXPECT_CALL(*backend_, doFetchLedgerObject(current, 30, _)) .WillOnce(Return(nftpage.getSerializer().peekData())); current = previous; } auto const nftpage11 = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, std::nullopt + std::vector{std::make_pair(kTokenId, "www.ok.com")}, std::nullopt ); EXPECT_CALL(*backend_, doFetchLedgerObject(current, 30, _)) .WillOnce(Return(nftpage11.getSerializer().peekData())); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); auto const line = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); auto const channel = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 10, 32, kTXN_ID, 28); + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 10, 32, kTxnId, 28); auto const offer = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); std::vector bbs; @@ -1478,35 +1478,35 @@ TEST_F(RPCAccountObjectsHandlerTest, NFTLimitAdjust) EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": "{},{}", "limit": 12 }})JSON", - kACCOUNT, - ripple::strHex(marker), + kAccount, + xrpl::strHex(marker), std::numeric_limits::max() ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result.value().as_object().at("account_objects").as_array().size(), 12); // marker not in NFT "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC,0" EXPECT_EQ( output.result.value().as_object().at("marker").as_string(), - fmt::format("{},{}", kINDEX1, 0) + fmt::format("{},{}", kIndex1, 0) ); }); } TEST_F(RPCAccountObjectsHandlerTest, FilterNFT) { - static constexpr auto kEXPECTED_OUT = R"JSON({ + static constexpr auto kExpectedOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, "validated": true, @@ -1547,118 +1547,119 @@ TEST_F(RPCAccountObjectsHandlerTest, FilterNFT) ] })JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - auto const ownerDir = createOwnerDirLedgerObject({ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + auto const ownerDir = createOwnerDirLedgerObject({xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft page 1 - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; auto const nftPage2KK = - ripple::keylet::nftpage(ripple::keylet::nftpage_min(account), ripple::uint256{kINDEX1}).key; + xrpl::keylet::nftokenPage(xrpl::keylet::nftokenPageMin(account), xrpl::uint256{kIndex1}) + .key; auto const nftpage1 = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, nftPage2KK + std::vector{std::make_pair(kTokenId, "www.ok.com")}, nftPage2KK ); EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)) .WillOnce(Return(nftpage1.getSerializer().peekData())); // nft page 2 , end auto const nftpage2 = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, std::nullopt + std::vector{std::make_pair(kTokenId, "www.ok.com")}, std::nullopt ); EXPECT_CALL(*backend_, doFetchLedgerObject(nftPage2KK, 30, _)) .WillOnce(Return(nftpage2.getSerializer().peekData())); std::vector bbs; auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); bbs.push_back(line1.getSerializer().peekData()); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "type": "nft_page" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCAccountObjectsHandlerTest, NFTZeroMarkerNotAffectOtherMarker) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - static constexpr auto kLIMIT = 10; - auto count = kLIMIT * 2; + static constexpr auto kLimit = 10; + auto count = kLimit * 2; // put 20 items in owner dir, but only return 10 auto const ownerDir = - createOwnerDirLedgerObject(std::vector(count, ripple::uint256{kINDEX1}), kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + createOwnerDirLedgerObject(std::vector(count, xrpl::uint256{kIndex1}), kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); std::vector bbs; while (count-- != 0) { auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); bbs.push_back(line1.getSerializer().peekData()); } EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {}, "marker": "{},{}" }})JSON", - kACCOUNT, - kLIMIT, - ripple::strHex(ripple::uint256{beast::zero}), + kAccount, + kLimit, + xrpl::strHex(xrpl::uint256{beast::kZero}), std::numeric_limits::max() ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->as_object().at("account_objects").as_array().size(), kLIMIT); + EXPECT_EQ(output.result->as_object().at("account_objects").as_array().size(), kLimit); EXPECT_EQ( - output.result->as_object().at("marker").as_string(), fmt::format("{},{}", kINDEX1, 0) + output.result->as_object().at("marker").as_string(), fmt::format("{},{}", kIndex1, 0) ); }); } TEST_F(RPCAccountObjectsHandlerTest, LimitLessThanMin) { - static auto const kEXPECTED_OUT = fmt::format( + static auto const kExpectedOut = fmt::format( R"JSON({{ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -1690,56 +1691,56 @@ TEST_F(RPCAccountObjectsHandlerTest, LimitLessThanMin) }} ] }})JSON", - AccountObjectsHandler::kLIMIT_MIN + AccountObjectsHandler::kLimitMin ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - auto const ownerDir = createOwnerDirLedgerObject({ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + auto const ownerDir = createOwnerDirLedgerObject({xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft null - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)).WillOnce(Return(std::nullopt)); std::vector bbs; auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); bbs.push_back(line1.getSerializer().peekData()); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountObjectsHandler::kLIMIT_MIN - 1 + kAccount, + AccountObjectsHandler::kLimitMin - 1 ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCAccountObjectsHandlerTest, LimitMoreThanMax) { - static auto const kEXPECTED_OUT = fmt::format( + static auto const kExpectedOut = fmt::format( R"JSON({{ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -1771,92 +1772,92 @@ TEST_F(RPCAccountObjectsHandlerTest, LimitMoreThanMax) }} ] }})JSON", - AccountObjectsHandler::kLIMIT_MAX + AccountObjectsHandler::kLimitMax ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - auto const ownerDir = createOwnerDirLedgerObject({ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + auto const ownerDir = createOwnerDirLedgerObject({xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft null - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)).WillOnce(Return(std::nullopt)); std::vector bbs; auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); bbs.push_back(line1.getSerializer().peekData()); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountObjectsHandler::kLIMIT_MAX + 1 + kAccount, + AccountObjectsHandler::kLimitMax + 1 ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCAccountObjectsHandlerTest, TypeFilterMPTIssuanceType) { - auto const ledgerinfo = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerinfo = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerinfo)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - auto const ownerDir = createOwnerDirLedgerObject({ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + auto const ownerDir = createOwnerDirLedgerObject({xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft null - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)).WillOnce(Return(std::nullopt)); std::vector bbs; // put 1 mpt issuance - auto const issuanceObject = createMptIssuanceObject(kACCOUNT, 2, "metadata"); + auto const issuanceObject = createMptIssuanceObject(kAccount, 2, "metadata"); bbs.push_back(issuanceObject.getSerializer().peekData()); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "type": "mpt_issuance" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); auto const& accountObjects = output.result->as_object().at("account_objects").as_array(); ASSERT_EQ(accountObjects.size(), 1); @@ -1865,51 +1866,51 @@ TEST_F(RPCAccountObjectsHandlerTest, TypeFilterMPTIssuanceType) // make sure mptID is synethetically parsed if object is mptIssuance EXPECT_EQ( accountObjects.front().at("mpt_issuance_id").as_string(), - ripple::to_string(ripple::makeMptID(2, getAccountIdWithString(kACCOUNT))) + xrpl::to_string(xrpl::makeMptID(2, getAccountIdWithString(kAccount))) ); }); } TEST_F(RPCAccountObjectsHandlerTest, TypeFilterMPTokenType) { - auto const ledgerinfo = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerinfo = createLedgerHeader(kLedgerHash, kMaxSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerinfo)); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKk = ripple::keylet::account(account).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMAX_SEQ, _)) + auto const account = getAccountIdWithString(kAccount); + auto const accountKk = xrpl::keylet::account(account).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, kMaxSeq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - auto const ownerDir = createOwnerDirLedgerObject({ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(account).key; + auto const ownerDir = createOwnerDirLedgerObject({xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, 30, _)) .WillOnce(Return(ownerDir.getSerializer().peekData())); // nft null - auto const nftMaxKK = ripple::keylet::nftpage_max(account).key; + auto const nftMaxKK = xrpl::keylet::nftokenPageMax(account).key; EXPECT_CALL(*backend_, doFetchLedgerObject(nftMaxKK, 30, _)).WillOnce(Return(std::nullopt)); std::vector bbs; // put 1 mpt issuance auto const mptokenObject = - createMpTokenObject(kACCOUNT, ripple::makeMptID(2, getAccountIdWithString(kACCOUNT))); + createMpTokenObject(kAccount, xrpl::makeMptID(2, getAccountIdWithString(kAccount))); bbs.push_back(mptokenObject.getSerializer().peekData()); EXPECT_CALL(*backend_, doFetchLedgerObjects).WillOnce(Return(bbs)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "type": "mptoken" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountObjectsHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); auto const& accountObjects = output.result->as_object().at("account_objects").as_array(); ASSERT_EQ(accountObjects.size(), 1); diff --git a/tests/unit/rpc/handlers/AccountOffersTests.cpp b/tests/unit/rpc/handlers/AccountOffersTests.cpp index fb14582ba..447968bd8 100644 --- a/tests/unit/rpc/handlers/AccountOffersTests.cpp +++ b/tests/unit/rpc/handlers/AccountOffersTests.cpp @@ -26,16 +26,15 @@ namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kINDEX1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kIndex1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; } // namespace using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; struct RPCAccountOffersHandlerTest : HandlerBaseTest { @@ -139,7 +138,7 @@ INSTANTIATE_TEST_CASE_P( RPCAccountOffersGroup1, AccountOfferParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(AccountOfferParameterTest, InvalidParams) @@ -147,7 +146,7 @@ TEST_P(AccountOfferParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountOffersHandler{backend_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -160,22 +159,22 @@ TEST_F(RPCAccountOffersHandlerTest, LedgerNotFoundViaHash) { EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // return empty ledgerHeader - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); auto const handler = AnyHandler{AccountOffersHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -185,26 +184,26 @@ TEST_F(RPCAccountOffersHandlerTest, LedgerNotFoundViaHash) TEST_F(RPCAccountOffersHandlerTest, LedgerNotFoundViaStringIndex) { - constexpr auto kSEQ = 12; + constexpr auto kSeq = 12; EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return empty ledgerHeader - ON_CALL(*backend_, fetchLedgerBySequence(kSEQ, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerBySequence(kSeq, _)) + .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "{}" }})JSON", - kACCOUNT, - kSEQ + kAccount, + kSeq ) ); auto const handler = AnyHandler{AccountOffersHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -214,26 +213,26 @@ TEST_F(RPCAccountOffersHandlerTest, LedgerNotFoundViaStringIndex) TEST_F(RPCAccountOffersHandlerTest, LedgerNotFoundViaIntIndex) { - constexpr auto kSEQ = 12; + constexpr auto kSeq = 12; EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return empty ledgerHeader - ON_CALL(*backend_, fetchLedgerBySequence(kSEQ, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerBySequence(kSeq, _)) + .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": {} }})JSON", - kACCOUNT, - kSEQ + kAccount, + kSeq ) ); auto const handler = AnyHandler{AccountOffersHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -243,24 +242,24 @@ TEST_F(RPCAccountOffersHandlerTest, LedgerNotFoundViaIntIndex) TEST_F(RPCAccountOffersHandlerTest, AccountNotFound) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); ON_CALL(*backend_, doFetchLedgerObject).WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountOffersHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "actNotFound"); @@ -291,166 +290,166 @@ TEST_F(RPCAccountOffersHandlerTest, DefaultParams) }} ] }})JSON", - kLEDGER_HASH, - kACCOUNT, - kACCOUNT2 + kLedgerHash, + kAccount, + kAccount2 ); - constexpr auto kLEDGER_SEQ = 30; + constexpr auto kLedgerSeq = 30; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kLEDGER_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kLedgerSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(accountKk, kLEDGER_SEQ, _)) + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(accountKk, kLedgerSeq, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - auto const ownerDir = createOwnerDirLedgerObject({ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kLEDGER_SEQ, _)) + auto const ownerDir = createOwnerDirLedgerObject({xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kLedgerSeq, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); std::vector bbs; auto offer = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); - offer.setFieldU32(ripple::sfExpiration, 123); + offer.setFieldU32(xrpl::sfExpiration, 123); bbs.push_back(offer.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountOffersHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(expectedOutput)); + EXPECT_EQ(*output.result, boost::json::parse(expectedOutput)); }); } TEST_F(RPCAccountOffersHandlerTest, Limit) { - constexpr auto kLEDGER_SEQ = 30; + constexpr auto kLedgerSeq = 30; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kLEDGER_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kLedgerSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(accountKk, kLEDGER_SEQ, _)) + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(accountKk, kLedgerSeq, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); auto const ownerDir = - createOwnerDirLedgerObject(std::vector{20, ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kLEDGER_SEQ, _)) + createOwnerDirLedgerObject(std::vector{20, xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kLedgerSeq, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); std::vector bbs; for (auto i = 0; i < 20; i++) { auto const offer = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); bbs.push_back(offer.getSerializer().peekData()); } ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": 10 }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{AccountOffersHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result->at("offers").as_array().size(), 10); - EXPECT_EQ(output.result->at("marker").as_string(), fmt::format("{},0", kINDEX1)); + EXPECT_EQ(output.result->at("marker").as_string(), fmt::format("{},0", kIndex1)); }); } TEST_F(RPCAccountOffersHandlerTest, Marker) { - constexpr auto kLEDGER_SEQ = 30; + constexpr auto kLedgerSeq = 30; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kLEDGER_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kLedgerSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(accountKk, kLEDGER_SEQ, _)) + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(accountKk, kLedgerSeq, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); auto const startPage = 2; auto const ownerDir = - createOwnerDirLedgerObject(std::vector{20, ripple::uint256{kINDEX1}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - auto const hintIndex = ripple::keylet::page(ownerDirKk, startPage).key; + createOwnerDirLedgerObject(std::vector{20, xrpl::uint256{kIndex1}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + auto const hintIndex = xrpl::keylet::page(ownerDirKk, startPage).key; - ON_CALL(*backend_, doFetchLedgerObject(hintIndex, kLEDGER_SEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(hintIndex, kLedgerSeq, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); std::vector bbs; for (auto i = 0; i < 20; i++) { auto const offer = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); bbs.push_back(offer.getSerializer().peekData()); } ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": "{},{}" }})JSON", - kACCOUNT, - kINDEX1, + kAccount, + kIndex1, startPage ) ); auto const handler = AnyHandler{AccountOffersHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result->at("offers").as_array().size(), 19); EXPECT_FALSE(output.result->as_object().contains("marker")); @@ -459,38 +458,38 @@ TEST_F(RPCAccountOffersHandlerTest, Marker) TEST_F(RPCAccountOffersHandlerTest, MarkerNotExists) { - constexpr auto kLEDGER_SEQ = 30; + constexpr auto kLedgerSeq = 30; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kLEDGER_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kLedgerSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(accountKk, kLEDGER_SEQ, _)) + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(accountKk, kLedgerSeq, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); auto const startPage = 2; - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - auto const hintIndex = ripple::keylet::page(ownerDirKk, startPage).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + auto const hintIndex = xrpl::keylet::page(ownerDirKk, startPage).key; - ON_CALL(*backend_, doFetchLedgerObject(hintIndex, kLEDGER_SEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(hintIndex, kLedgerSeq, _)) .WillByDefault(Return(std::nullopt)); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "marker": "{},{}" }})JSON", - kACCOUNT, - kINDEX1, + kAccount, + kIndex1, startPage ) ); auto const handler = AnyHandler{AccountOffersHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "invalidParams"); @@ -500,117 +499,117 @@ TEST_F(RPCAccountOffersHandlerTest, MarkerNotExists) TEST_F(RPCAccountOffersHandlerTest, LimitLessThanMin) { - constexpr auto kLEDGER_SEQ = 30; + constexpr auto kLedgerSeq = 30; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kLEDGER_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kLedgerSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(accountKk, kLEDGER_SEQ, _)) + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(accountKk, kLedgerSeq, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); auto const ownerDir = createOwnerDirLedgerObject( - std::vector{AccountOffersHandler::kLIMIT_MIN + 1, ripple::uint256{kINDEX1}}, kINDEX1 + std::vector{AccountOffersHandler::kLimitMin + 1, xrpl::uint256{kIndex1}}, kIndex1 ); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kLEDGER_SEQ, _)) + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kLedgerSeq, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); std::vector bbs; auto offer = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); - offer.setFieldU32(ripple::sfExpiration, 123); + offer.setFieldU32(xrpl::sfExpiration, 123); - bbs.reserve(AccountOffersHandler::kLIMIT_MIN + 1); - for (auto i = 0; i < AccountOffersHandler::kLIMIT_MIN + 1; i++) + bbs.reserve(AccountOffersHandler::kLimitMin + 1); + for (auto i = 0; i < AccountOffersHandler::kLimitMin + 1; i++) bbs.push_back(offer.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountOffersHandler::kLIMIT_MIN - 1 + kAccount, + AccountOffersHandler::kLimitMin - 1 ) ); auto const handler = AnyHandler{AccountOffersHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("offers").as_array().size(), AccountOffersHandler::kLIMIT_MIN); + EXPECT_EQ(output.result->at("offers").as_array().size(), AccountOffersHandler::kLimitMin); }); } TEST_F(RPCAccountOffersHandlerTest, LimitMoreThanMax) { - constexpr auto kLEDGER_SEQ = 30; + constexpr auto kLedgerSeq = 30; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kLEDGER_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kLedgerSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(accountKk, kLEDGER_SEQ, _)) + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(accountKk, kLedgerSeq, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); auto const ownerDir = createOwnerDirLedgerObject( - std::vector{AccountOffersHandler::kLIMIT_MAX + 1, ripple::uint256{kINDEX1}}, kINDEX1 + std::vector{AccountOffersHandler::kLimitMax + 1, xrpl::uint256{kIndex1}}, kIndex1 ); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kLEDGER_SEQ, _)) + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kLedgerSeq, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); std::vector bbs; auto offer = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT2, - toBase58(ripple::xrpAccount()), - kINDEX1 + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount2, + toBase58(xrpl::xrpAccount()), + kIndex1 ); - offer.setFieldU32(ripple::sfExpiration, 123); - bbs.reserve(AccountOffersHandler::kLIMIT_MAX + 1); - for (auto i = 0; i < AccountOffersHandler::kLIMIT_MAX + 1; i++) + offer.setFieldU32(xrpl::sfExpiration, 123); + bbs.reserve(AccountOffersHandler::kLimitMax + 1); + for (auto i = 0; i < AccountOffersHandler::kLimitMax + 1; i++) bbs.push_back(offer.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "limit": {} }})JSON", - kACCOUNT, - AccountOffersHandler::kLIMIT_MAX + 1 + kAccount, + AccountOffersHandler::kLimitMax + 1 ) ); auto const handler = AnyHandler{AccountOffersHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("offers").as_array().size(), AccountOffersHandler::kLIMIT_MAX); + EXPECT_EQ(output.result->at("offers").as_array().size(), AccountOffersHandler::kLimitMax); }); } diff --git a/tests/unit/rpc/handlers/AccountTxTests.cpp b/tests/unit/rpc/handlers/AccountTxTests.cpp index ed03794db..7709d08ce 100644 --- a/tests/unit/rpc/handlers/AccountTxTests.cpp +++ b/tests/unit/rpc/handlers/AccountTxTests.cpp @@ -23,27 +23,26 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kMIN_SEQ = 10; -constexpr auto kMAX_SEQ = 30; -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kNFT_ID = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DF"; -constexpr auto kNFT_ID2 = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DA"; -constexpr auto kNFT_ID3 = "15FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DF"; -constexpr auto kINDEX = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; +constexpr auto kMinSeq = 10; +constexpr auto kMaxSeq = 30; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kNftId = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DF"; +constexpr auto kNftID2 = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DA"; +constexpr auto kNftID3 = "15FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DF"; +constexpr auto kIndex = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; } // namespace struct RPCAccountTxHandlerTest : HandlerBaseTest { RPCAccountTxHandlerTest() { - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); } }; @@ -352,7 +351,7 @@ struct AccountTxParameterTest : public RPCAccountTxHandlerTest, "ledger_index_min": 11, "ledger_hash": "{}" }})JSON", - kLEDGER_HASH + kLedgerHash ), .expectedError = "invalidParams", .expectedErrorMessage = "containsLedgerSpecifierAndRange" @@ -366,7 +365,7 @@ struct AccountTxParameterTest : public RPCAccountTxHandlerTest, "ledger_index_min": 11, "ledger_hash": "{}" }})JSON", - kLEDGER_HASH + kLedgerHash ), .expectedError = std::nullopt, .expectedErrorMessage = std::nullopt, @@ -401,14 +400,14 @@ INSTANTIATE_TEST_CASE_P( RPCAccountTxGroup1, AccountTxParameterTest, ValuesIn(AccountTxParameterTest::generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(AccountTxParameterTest, CheckParams) { auto const& testBundle = GetParam(); - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); if (testBundle.expectedError.has_value()) { ASSERT_TRUE(testBundle.expectedErrorMessage.has_value()); @@ -440,21 +439,19 @@ genTransactions(uint32_t seq1, uint32_t seq2) { auto transactions = std::vector{}; auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = seq1; - ripple::STObject const metaObj = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, 22, 23); + xrpl::STObject const metaObj = createPaymentTransactionMetaObject(kAccount, kAccount2, 22, 23); trans1.metadata = metaObj.getSerializer().peekData(); trans1.date = 1; transactions.push_back(trans1); auto trans2 = TransactionAndMetadata(); - ripple::STObject const obj2 = createPaymentTransactionObject(kACCOUNT, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj2 = createPaymentTransactionObject(kAccount, kAccount2, 1, 1, 32); trans2.transaction = obj.getSerializer().peekData(); trans2.ledgerSequence = seq2; - ripple::STObject const metaObj2 = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, 22, 23); + xrpl::STObject const metaObj2 = createPaymentTransactionMetaObject(kAccount, kAccount2, 22, 23); trans2.metadata = metaObj2.getSerializer().peekData(); trans2.date = 2; transactions.push_back(trans2); @@ -466,24 +463,24 @@ genNFTTransactions(uint32_t seq) { auto transactions = std::vector{}; - auto trans1 = createMintNftTxWithMetadata(kACCOUNT, 1, 50, 123, kNFT_ID); + auto trans1 = createMintNftTxWithMetadata(kAccount, 1, 50, 123, kNftId); trans1.ledgerSequence = seq; trans1.date = 1; transactions.push_back(trans1); - auto trans2 = createAcceptNftBuyerOfferTxWithMetadata(kACCOUNT, 1, 50, kNFT_ID2, kINDEX); + auto trans2 = createAcceptNftBuyerOfferTxWithMetadata(kAccount, 1, 50, kNftID2, kIndex); trans2.ledgerSequence = seq; trans2.date = 2; transactions.push_back(trans2); auto trans3 = createCancelNftOffersTxWithMetadata( - kACCOUNT, 1, 50, std::vector{kNFT_ID2, kNFT_ID3} + kAccount, 1, 50, std::vector{kNftID2, kNftID3} ); trans3.ledgerSequence = seq; trans3.date = 3; transactions.push_back(trans3); - auto trans4 = createCreateNftOfferTxWithMetadata(kACCOUNT, 1, 50, kNFT_ID, 123, kNFT_ID2); + auto trans4 = createCreateNftOfferTxWithMetadata(kAccount, 1, 50, kNftId, 123, kNftID2); trans4.ledgerSequence = seq; trans4.date = 4; transactions.push_back(trans4); @@ -493,7 +490,7 @@ genNFTTransactions(uint32_t seq) TEST_F(RPCAccountTxHandlerTest, IndexSpecificForwardTrue) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchAccountTransactions).WillByDefault(Return(transCursor)); @@ -503,7 +500,7 @@ TEST_F(RPCAccountTxHandlerTest, IndexSpecificForwardTrue) testing::_, testing::_, true, - testing::Optional(testing::Eq(TransactionsCursor{kMIN_SEQ, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMinSeq, INT32_MAX})), testing::_ ) ); @@ -512,7 +509,7 @@ TEST_F(RPCAccountTxHandlerTest, IndexSpecificForwardTrue) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -520,19 +517,19 @@ TEST_F(RPCAccountTxHandlerTest, IndexSpecificForwardTrue) "ledger_index_max": {}, "forward": true }})JSON", - kACCOUNT, - kMIN_SEQ + 1, - kMAX_SEQ - 1 + kAccount, + kMinSeq + 1, + kMaxSeq - 1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("account").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ + 1); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ - 1); + EXPECT_EQ(output.result->at("account").as_string(), kAccount); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq + 1); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq - 1); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); EXPECT_FALSE(output.result->as_object().contains("limit")); @@ -541,7 +538,7 @@ TEST_F(RPCAccountTxHandlerTest, IndexSpecificForwardTrue) TEST_F(RPCAccountTxHandlerTest, IndexSpecificForwardFalse) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchAccountTransactions).WillByDefault(Return(transCursor)); @@ -551,7 +548,7 @@ TEST_F(RPCAccountTxHandlerTest, IndexSpecificForwardFalse) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ - 1, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq - 1, INT32_MAX})), testing::_ ) ); @@ -560,7 +557,7 @@ TEST_F(RPCAccountTxHandlerTest, IndexSpecificForwardFalse) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -568,19 +565,19 @@ TEST_F(RPCAccountTxHandlerTest, IndexSpecificForwardFalse) "ledger_index_max": {}, "forward": false }})JSON", - kACCOUNT, - kMIN_SEQ + 1, - kMAX_SEQ - 1 + kAccount, + kMinSeq + 1, + kMaxSeq - 1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("account").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ + 1); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ - 1); + EXPECT_EQ(output.result->at("account").as_string(), kAccount); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq + 1); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq - 1); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); EXPECT_FALSE(output.result->as_object().contains("limit")); @@ -589,7 +586,7 @@ TEST_F(RPCAccountTxHandlerTest, IndexSpecificForwardFalse) TEST_F(RPCAccountTxHandlerTest, IndexNotSpecificForwardTrue) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchAccountTransactions).WillByDefault(Return(transCursor)); @@ -599,7 +596,7 @@ TEST_F(RPCAccountTxHandlerTest, IndexNotSpecificForwardTrue) testing::_, testing::_, true, - testing::Optional(testing::Eq(TransactionsCursor{kMIN_SEQ - 1, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMinSeq - 1, INT32_MAX})), testing::_ ) ); @@ -608,7 +605,7 @@ TEST_F(RPCAccountTxHandlerTest, IndexNotSpecificForwardTrue) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -616,19 +613,19 @@ TEST_F(RPCAccountTxHandlerTest, IndexNotSpecificForwardTrue) "ledger_index_max": {}, "forward": true }})JSON", - kACCOUNT, + kAccount, -1, -1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("account").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ); + EXPECT_EQ(output.result->at("account").as_string(), kAccount); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); EXPECT_FALSE(output.result->as_object().contains("limit")); @@ -637,7 +634,7 @@ TEST_F(RPCAccountTxHandlerTest, IndexNotSpecificForwardTrue) TEST_F(RPCAccountTxHandlerTest, IndexNotSpecificForwardFalse) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchAccountTransactions).WillByDefault(Return(transCursor)); @@ -647,7 +644,7 @@ TEST_F(RPCAccountTxHandlerTest, IndexNotSpecificForwardFalse) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq, INT32_MAX})), testing::_ ) ); @@ -656,7 +653,7 @@ TEST_F(RPCAccountTxHandlerTest, IndexNotSpecificForwardFalse) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -664,19 +661,19 @@ TEST_F(RPCAccountTxHandlerTest, IndexNotSpecificForwardFalse) "ledger_index_max": {}, "forward": false }})JSON", - kACCOUNT, + kAccount, -1, -1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("account").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ); + EXPECT_EQ(output.result->at("account").as_string(), kAccount); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); EXPECT_FALSE(output.result->as_object().contains("limit")); @@ -685,7 +682,7 @@ TEST_F(RPCAccountTxHandlerTest, IndexNotSpecificForwardFalse) TEST_F(RPCAccountTxHandlerTest, BinaryTrue) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchAccountTransactions).WillByDefault(Return(transCursor)); @@ -695,14 +692,14 @@ TEST_F(RPCAccountTxHandlerTest, BinaryTrue) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq, INT32_MAX})), testing::_ ) ); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -710,19 +707,19 @@ TEST_F(RPCAccountTxHandlerTest, BinaryTrue) "ledger_index_max": {}, "binary": true }})JSON", - kACCOUNT, + kAccount, -1, -1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("account").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ); + EXPECT_EQ(output.result->at("account").as_string(), kAccount); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); EXPECT_EQ( @@ -747,7 +744,7 @@ TEST_F(RPCAccountTxHandlerTest, BinaryTrue) TEST_F(RPCAccountTxHandlerTest, BinaryTrueV2) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; EXPECT_CALL( @@ -756,7 +753,7 @@ TEST_F(RPCAccountTxHandlerTest, BinaryTrueV2) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq, INT32_MAX})), testing::_ ) ) @@ -764,7 +761,7 @@ TEST_F(RPCAccountTxHandlerTest, BinaryTrueV2) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -772,19 +769,19 @@ TEST_F(RPCAccountTxHandlerTest, BinaryTrueV2) "ledger_index_max": {}, "binary": true }})JSON", - kACCOUNT, + kAccount, -1, -1 ) ); - auto const output = handler.process(kINPUT, Context{.yield = yield, .apiVersion = 2u}); + auto const output = handler.process(kInput, Context{.yield = yield, .apiVersion = 2u}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("account").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ); + EXPECT_EQ(output.result->at("account").as_string(), kAccount); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); EXPECT_EQ( @@ -809,7 +806,7 @@ TEST_F(RPCAccountTxHandlerTest, BinaryTrueV2) TEST_F(RPCAccountTxHandlerTest, LimitAndMarker) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; EXPECT_CALL( @@ -828,7 +825,7 @@ TEST_F(RPCAccountTxHandlerTest, LimitAndMarker) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -838,20 +835,20 @@ TEST_F(RPCAccountTxHandlerTest, LimitAndMarker) "forward": false, "marker": {{"ledger": 10, "seq": 11}} }})JSON", - kACCOUNT, + kAccount, -1, -1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("account").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ); + EXPECT_EQ(output.result->at("account").as_string(), kAccount); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq); EXPECT_EQ(output.result->at("limit").as_uint64(), 2); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); }); @@ -859,7 +856,7 @@ TEST_F(RPCAccountTxHandlerTest, LimitAndMarker) TEST_F(RPCAccountTxHandlerTest, LimitIsCapped) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; EXPECT_CALL( @@ -870,7 +867,7 @@ TEST_F(RPCAccountTxHandlerTest, LimitIsCapped) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -879,24 +876,24 @@ TEST_F(RPCAccountTxHandlerTest, LimitIsCapped) "limit": 100000, "forward": false }})JSON", - kACCOUNT, + kAccount, -1, -1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("account").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ); - EXPECT_EQ(output.result->at("limit").as_uint64(), AccountTxHandler::kLIMIT_MAX); + EXPECT_EQ(output.result->at("account").as_string(), kAccount); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq); + EXPECT_EQ(output.result->at("limit").as_uint64(), AccountTxHandler::kLimitMax); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); }); } TEST_F(RPCAccountTxHandlerTest, LimitAllowedUpToCap) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; EXPECT_CALL( @@ -907,7 +904,7 @@ TEST_F(RPCAccountTxHandlerTest, LimitAllowedUpToCap) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -916,18 +913,18 @@ TEST_F(RPCAccountTxHandlerTest, LimitAllowedUpToCap) "limit": {}, "forward": false }})JSON", - kACCOUNT, + kAccount, -1, -1, - AccountTxHandler::kLIMIT_MAX - 1 + AccountTxHandler::kLimitMax - 1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("account").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ); - EXPECT_EQ(output.result->at("limit").as_uint64(), AccountTxHandler::kLIMIT_MAX - 1); + EXPECT_EQ(output.result->at("account").as_string(), kAccount); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq); + EXPECT_EQ(output.result->at("limit").as_uint64(), AccountTxHandler::kLimitMax - 1); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); }); } @@ -935,7 +932,7 @@ TEST_F(RPCAccountTxHandlerTest, LimitAllowedUpToCap) TEST_F(RPCAccountTxHandlerTest, SpecificLedgerIndex) { // adjust the order for forward->false - auto const transactions = genTransactions(kMAX_SEQ - 1, kMIN_SEQ + 1); + auto const transactions = genTransactions(kMaxSeq - 1, kMinSeq + 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchAccountTransactions).WillByDefault(Return(transCursor)); @@ -945,32 +942,32 @@ TEST_F(RPCAccountTxHandlerTest, SpecificLedgerIndex) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ - 1, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq - 1, INT32_MAX})), testing::_ ) ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ - 1); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ - 1, _)).WillOnce(Return(ledgerHeader)); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq - 1); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kMaxSeq - 1, _)).WillOnce(Return(ledgerHeader)); ON_CALL(*mockETLServicePtr_, getETLState).WillByDefault(Return(etl::ETLState{})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": {} }})JSON", - kACCOUNT, - kMAX_SEQ - 1 + kAccount, + kMaxSeq - 1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("account").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMAX_SEQ - 1); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ - 1); + EXPECT_EQ(output.result->at("account").as_string(), kAccount); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMaxSeq - 1); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq - 1); EXPECT_FALSE(output.result->as_object().contains("limit")); EXPECT_FALSE(output.result->as_object().contains("marker")); EXPECT_EQ(output.result->at("transactions").as_array().size(), 1); @@ -979,21 +976,21 @@ TEST_F(RPCAccountTxHandlerTest, SpecificLedgerIndex) TEST_F(RPCAccountTxHandlerTest, SpecificNonexistLedgerIntIndex) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ - 1, _)).WillOnce(Return(std::nullopt)); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kMaxSeq - 1, _)).WillOnce(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": {} }})JSON", - kACCOUNT, - kMAX_SEQ - 1 + kAccount, + kMaxSeq - 1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -1003,21 +1000,21 @@ TEST_F(RPCAccountTxHandlerTest, SpecificNonexistLedgerIntIndex) TEST_F(RPCAccountTxHandlerTest, SpecificNonexistLedgerStringIndex) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ - 1, _)).WillOnce(Return(std::nullopt)); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kMaxSeq - 1, _)).WillOnce(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "{}" }})JSON", - kACCOUNT, - kMAX_SEQ - 1 + kAccount, + kMaxSeq - 1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -1028,7 +1025,7 @@ TEST_F(RPCAccountTxHandlerTest, SpecificNonexistLedgerStringIndex) TEST_F(RPCAccountTxHandlerTest, SpecificLedgerHash) { // adjust the order for forward->false - auto const transactions = genTransactions(kMAX_SEQ - 1, kMIN_SEQ + 1); + auto const transactions = genTransactions(kMaxSeq - 1, kMinSeq + 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchAccountTransactions).WillByDefault(Return(transCursor)); @@ -1038,35 +1035,35 @@ TEST_F(RPCAccountTxHandlerTest, SpecificLedgerHash) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ - 1, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq - 1, INT32_MAX})), testing::_ ) ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ - 1); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq - 1); EXPECT_CALL(*backend_, fetchLedgerByHash); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); ON_CALL(*mockETLServicePtr_, getETLState).WillByDefault(Return(etl::ETLState{})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("account").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMAX_SEQ - 1); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ - 1); + EXPECT_EQ(output.result->at("account").as_string(), kAccount); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMaxSeq - 1); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq - 1); EXPECT_FALSE(output.result->as_object().contains("limit")); EXPECT_FALSE(output.result->as_object().contains("marker")); EXPECT_EQ(output.result->at("transactions").as_array().size(), 1); @@ -1076,7 +1073,7 @@ TEST_F(RPCAccountTxHandlerTest, SpecificLedgerHash) TEST_F(RPCAccountTxHandlerTest, SpecificLedgerIndexValidated) { // adjust the order for forward->false - auto const transactions = genTransactions(kMAX_SEQ, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMaxSeq, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchAccountTransactions).WillByDefault(Return(transCursor)); @@ -1086,32 +1083,32 @@ TEST_F(RPCAccountTxHandlerTest, SpecificLedgerIndexValidated) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq, INT32_MAX})), testing::_ ) ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ, _)).WillOnce(Return(ledgerHeader)); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kMaxSeq, _)).WillOnce(Return(ledgerHeader)); ON_CALL(*mockETLServicePtr_, getETLState).WillByDefault(Return(etl::ETLState{})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "validated" }})JSON", - kACCOUNT + kAccount ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("account").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMAX_SEQ); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ); + EXPECT_EQ(output.result->at("account").as_string(), kAccount); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMaxSeq); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq); EXPECT_FALSE(output.result->as_object().contains("limit")); EXPECT_FALSE(output.result->as_object().contains("marker")); EXPECT_EQ(output.result->at("transactions").as_array().size(), 1); @@ -1120,7 +1117,7 @@ TEST_F(RPCAccountTxHandlerTest, SpecificLedgerIndexValidated) TEST_F(RPCAccountTxHandlerTest, TxLessThanMinSeq) { - auto const transactions = genTransactions(kMAX_SEQ - 1, kMIN_SEQ + 1); + auto const transactions = genTransactions(kMaxSeq - 1, kMinSeq + 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchAccountTransactions).WillByDefault(Return(transCursor)); @@ -1130,7 +1127,7 @@ TEST_F(RPCAccountTxHandlerTest, TxLessThanMinSeq) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ - 1, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq - 1, INT32_MAX})), testing::_ ) ); @@ -1139,7 +1136,7 @@ TEST_F(RPCAccountTxHandlerTest, TxLessThanMinSeq) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -1147,16 +1144,16 @@ TEST_F(RPCAccountTxHandlerTest, TxLessThanMinSeq) "ledger_index_max": {}, "forward": false }})JSON", - kACCOUNT, - kMIN_SEQ + 2, - kMAX_SEQ - 1 + kAccount, + kMinSeq + 2, + kMaxSeq - 1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("account").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ + 2); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ - 1); + EXPECT_EQ(output.result->at("account").as_string(), kAccount); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq + 2); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq - 1); EXPECT_EQ(output.result->at("transactions").as_array().size(), 1); EXPECT_FALSE(output.result->as_object().contains("limit")); EXPECT_FALSE(output.result->as_object().contains("marker")); @@ -1165,7 +1162,7 @@ TEST_F(RPCAccountTxHandlerTest, TxLessThanMinSeq) TEST_F(RPCAccountTxHandlerTest, TxLargerThanMaxSeq) { - auto const transactions = genTransactions(kMAX_SEQ - 1, kMIN_SEQ + 1); + auto const transactions = genTransactions(kMaxSeq - 1, kMinSeq + 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchAccountTransactions).WillByDefault(Return(transCursor)); @@ -1175,7 +1172,7 @@ TEST_F(RPCAccountTxHandlerTest, TxLargerThanMaxSeq) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ - 2, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq - 2, INT32_MAX})), testing::_ ) ); @@ -1184,7 +1181,7 @@ TEST_F(RPCAccountTxHandlerTest, TxLargerThanMaxSeq) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -1192,21 +1189,21 @@ TEST_F(RPCAccountTxHandlerTest, TxLargerThanMaxSeq) "ledger_index_max": {}, "forward": false }})JSON", - kACCOUNT, - kMIN_SEQ + 1, - kMAX_SEQ - 2 + kAccount, + kMinSeq + 1, + kMaxSeq - 2 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("account").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ + 1); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ - 2); + EXPECT_EQ(output.result->at("account").as_string(), kAccount); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq + 1); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq - 2); EXPECT_EQ(output.result->at("transactions").as_array().size(), 1); EXPECT_FALSE(output.result->as_object().contains("limit")); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); }); } @@ -1389,7 +1386,7 @@ TEST_F(RPCAccountTxHandlerTest, NFTTxs_API_v1) } })JSON"; - auto const transactions = genNFTTransactions(kMIN_SEQ + 1); + auto const transactions = genNFTTransactions(kMinSeq + 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchAccountTransactions).WillByDefault(Return(transCursor)); @@ -1408,7 +1405,7 @@ TEST_F(RPCAccountTxHandlerTest, NFTTxs_API_v1) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -1417,14 +1414,14 @@ TEST_F(RPCAccountTxHandlerTest, NFTTxs_API_v1) "forward": false, "marker": {{"ledger": 10, "seq": 11}} }})JSON", - kACCOUNT, + kAccount, -1, -1 ) ); - auto const output = handler.process(kINPUT, Context{.yield = yield, .apiVersion = 1u}); + auto const output = handler.process(kInput, Context{.yield = yield, .apiVersion = 1u}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(out)); + EXPECT_EQ(*output.result, boost::json::parse(out)); }); } @@ -1613,7 +1610,7 @@ TEST_F(RPCAccountTxHandlerTest, NFTTxs_API_v2) } })JSON"; - auto const transactions = genNFTTransactions(kMIN_SEQ + 1); + auto const transactions = genNFTTransactions(kMinSeq + 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchAccountTransactions).WillByDefault(Return(transCursor)); @@ -1630,14 +1627,14 @@ TEST_F(RPCAccountTxHandlerTest, NFTTxs_API_v2) ON_CALL(*mockETLServicePtr_, getETLState).WillByDefault(Return(etl::ETLState{})); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 11); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 11); EXPECT_CALL(*backend_, fetchLedgerBySequence) .Times(transactions.size()) .WillRepeatedly(Return(ledgerHeader)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -1646,14 +1643,14 @@ TEST_F(RPCAccountTxHandlerTest, NFTTxs_API_v2) "forward": false, "marker": {{"ledger": 10, "seq": 11}} }})JSON", - kACCOUNT, + kAccount, -1, -1 ) ); - auto const output = handler.process(kINPUT, Context{.yield = yield, .apiVersion = 2u}); + auto const output = handler.process(kInput, Context{.yield = yield, .apiVersion = 2u}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(out)); + EXPECT_EQ(*output.result, boost::json::parse(out)); }); } @@ -1710,14 +1707,14 @@ TEST_F(RPCAccountTxHandlerTest, MPTTxs_API_v2) ], "validated": true }})JSON", - kACCOUNT, - kACCOUNT, - kLEDGER_HASH, - kACCOUNT + kAccount, + kAccount, + kLedgerHash, + kAccount ); - auto mptTx = createMPTIssuanceCreateTxWithMetadata(kACCOUNT, 50, 1); - mptTx.ledgerSequence = kMIN_SEQ + 1; + auto mptTx = createMPTIssuanceCreateTxWithMetadata(kAccount, 50, 1); + mptTx.ledgerSequence = kMinSeq + 1; mptTx.date = 1; auto transactions = std::vector{std::move(mptTx)}; @@ -1726,26 +1723,26 @@ TEST_F(RPCAccountTxHandlerTest, MPTTxs_API_v2) EXPECT_CALL(*backend_, fetchAccountTransactions).WillOnce(Return(transCursor)); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMIN_SEQ + 1); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kMIN_SEQ + 1, _)).WillOnce(Return(ledgerHeader)); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMinSeq + 1); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kMinSeq + 1, _)).WillOnce(Return(ledgerHeader)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index_min": {}, "ledger_index_max": {} }})JSON", - kACCOUNT, - kMIN_SEQ, - kMAX_SEQ + kAccount, + kMinSeq, + kMaxSeq ) ); - auto const output = handler.process(kINPUT, Context{.yield = yield, .apiVersion = 2u}); + auto const output = handler.process(kInput, Context{.yield = yield, .apiVersion = 2u}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(out)); + EXPECT_EQ(*output.result, boost::json::parse(out)); }); } @@ -2236,38 +2233,38 @@ INSTANTIATE_TEST_CASE_P( RPCAccountTxTransactionTypeTest, AccountTxTransactionTypeTest, ValuesIn(generateTransactionTypeTestValues()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(AccountTxTransactionTypeTest, SpecificTransactionType) { - auto const transactions = genTransactions(kMAX_SEQ, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMaxSeq, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchAccountTransactions).WillByDefault(Return(transCursor)); EXPECT_CALL( *backend_, fetchAccountTransactions( - _, _, false, Optional(Eq(TransactionsCursor{kMAX_SEQ, INT32_MAX})), _ + _, _, false, Optional(Eq(TransactionsCursor{kMaxSeq, INT32_MAX})), _ ) ); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); - ON_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ, _)).WillByDefault(Return(ledgerHeader)); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ, _)).Times(Between(1, 2)); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); + ON_CALL(*backend_, fetchLedgerBySequence(kMaxSeq, _)).WillByDefault(Return(ledgerHeader)); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kMaxSeq, _)).Times(Between(1, 2)); ON_CALL(*mockETLServicePtr_, getETLState).WillByDefault(Return(etl::ETLState{})); auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{AccountTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{.yield = yield, .apiVersion = testBundle.apiVersion}); EXPECT_TRUE(output); auto const transactions = output.result->at("transactions").as_array(); - auto const jsonObject = json::parse(testBundle.result); + auto const jsonObject = boost::json::parse(testBundle.result); EXPECT_EQ(jsonObject, transactions); }); } diff --git a/tests/unit/rpc/handlers/AllHandlerTests.cpp b/tests/unit/rpc/handlers/AllHandlerTests.cpp index ed3b2d696..85d42e87e 100644 --- a/tests/unit/rpc/handlers/AllHandlerTests.cpp +++ b/tests/unit/rpc/handlers/AllHandlerTests.cpp @@ -57,13 +57,12 @@ using ::testing::Types; using namespace rpc; using TestServerInfoHandler = BaseServerInfoHandler; -static constexpr auto kINDEX1 = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; -static constexpr auto kAMM_ACCOUNT = "rLcS7XL6nxRAi7JcbJcn1Na179oF3vdfbh"; -static constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -static constexpr auto kNFT_ID = "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004"; -static constexpr auto kCURRENCY = "0158415500000000C1F76FF6ECB0BAC600000000"; -static constexpr auto kVAULT_ID = - "61B03A6F8CEBD3AF9D8F696C3D0A9A9F0493B34BF6B5D93CF0BC009E6BA75303"; +static constexpr auto kIndex1 = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; +static constexpr auto kAmmAccount = "rLcS7XL6nxRAi7JcbJcn1Na179oF3vdfbh"; +static constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +static constexpr auto kNftId = "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004"; +static constexpr auto kCurrency = "0158415500000000C1F76FF6ECB0BAC600000000"; +static constexpr auto kVaultId = "61B03A6F8CEBD3AF9D8F696C3D0A9A9F0493B34BF6B5D93CF0BC009E6BA75303"; using AnyHandlerType = Types< AccountChannelsHandler, @@ -169,7 +168,7 @@ AccountInfoHandler::Input createInput() { AccountInfoHandler::Input input{}; - input.account = kACCOUNT; + input.account = kAccount; input.ident = "asdf"; return input; } @@ -179,7 +178,7 @@ AccountTxHandler::Input createInput() { AccountTxHandler::Input input{}; - input.account = kACCOUNT; + input.account = kAccount; return input; } @@ -188,7 +187,7 @@ AMMInfoHandler::Input createInput() { AMMInfoHandler::Input input{}; - input.ammAccount = getAccountIdWithString(kAMM_ACCOUNT); + input.ammAccount = getAccountIdWithString(kAmmAccount); return input; } @@ -197,10 +196,10 @@ BookOffersHandler::Input createInput() { BookOffersHandler::Input input{}; - input.paysCurrency = ripple::xrpCurrency(); - input.getsCurrency = ripple::Currency(kCURRENCY); - input.paysID = ripple::xrpAccount(); - input.getsID = getAccountIdWithString(kACCOUNT); + input.paysCurrency = xrpl::xrpCurrency(); + input.getsCurrency = xrpl::Currency(kCurrency); + input.paysID = xrpl::xrpAccount(); + input.getsID = getAccountIdWithString(kAccount); return input; } @@ -210,7 +209,7 @@ LedgerEntryHandler::Input createInput() { LedgerEntryHandler::Input input{}; - input.index = kINDEX1; + input.index = kIndex1; return input; } @@ -219,7 +218,7 @@ NFTBuyOffersHandler::Input createInput() { NFTBuyOffersHandler::Input input{}; - input.nftID = kNFT_ID; + input.nftID = kNftId; return input; } @@ -228,7 +227,7 @@ NFTInfoHandler::Input createInput() { NFTInfoHandler::Input input{}; - input.nftID = kNFT_ID; + input.nftID = kNftId; return input; } @@ -237,7 +236,7 @@ NFTSellOffersHandler::Input createInput() { NFTSellOffersHandler::Input input{}; - input.nftID = kNFT_ID; + input.nftID = kNftId; return input; } @@ -248,7 +247,7 @@ createInput() SubscribeHandler::Input input{}; input.books = std::vector{SubscribeHandler::OrderBook{ - .book = ripple::Book{}, .taker = kACCOUNT, .snapshot = true, .both = true + .book = xrpl::Book{}, .taker = kAccount, .snapshot = true, .both = true }}; return input; } @@ -258,7 +257,7 @@ VaultInfoHandler::Input createInput() { VaultInfoHandler::Input input{}; - input.vaultID = kVAULT_ID; + input.vaultID = kVaultId; return input; } diff --git a/tests/unit/rpc/handlers/BookChangesTests.cpp b/tests/unit/rpc/handlers/BookChangesTests.cpp index 7c8d42cb0..db7ff3af5 100644 --- a/tests/unit/rpc/handlers/BookChangesTests.cpp +++ b/tests/unit/rpc/handlers/BookChangesTests.cpp @@ -21,26 +21,25 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kCURRENCY = "0158415500000000C1F76FF6ECB0BAC600000000"; -constexpr auto kISSUER = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; -constexpr auto kACCOUNT1 = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kDOMAIN = "F10D0CC9A0F9A3CBF585B80BE09A186483668FDBDD39AA7E3370F3649CE134E5"; -constexpr auto kMAX_SEQ = 30; -constexpr auto kMIN_SEQ = 10; +constexpr auto kCurrency = "0158415500000000C1F76FF6ECB0BAC600000000"; +constexpr auto kIssuer = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; +constexpr auto kAccount1 = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kDomain = "F10D0CC9A0F9A3CBF585B80BE09A186483668FDBDD39AA7E3370F3649CE134E5"; +constexpr auto kMaxSeq = 30; +constexpr auto kMinSeq = 10; } // namespace struct RPCBookChangesHandlerTest : HandlerBaseTest { RPCBookChangesHandlerTest() { - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); } }; @@ -84,7 +83,7 @@ INSTANTIATE_TEST_CASE_P( RPCBookChangesGroup1, BookChangesParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(BookChangesParameterTest, InvalidParams) @@ -92,7 +91,7 @@ TEST_P(BookChangesParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{BookChangesHandler{backend_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -105,13 +104,13 @@ TEST_F(RPCBookChangesHandlerTest, LedgerNonExistViaIntSequence) { EXPECT_CALL(*backend_, fetchLedgerBySequence); // return empty ledgerHeader - ON_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerBySequence(kMaxSeq, _)) + .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse(R"JSON({"ledger_index": 30})JSON"); + static auto const kInput = boost::json::parse(R"JSON({"ledger_index": 30})JSON"); auto const handler = AnyHandler{BookChangesHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -123,12 +122,12 @@ TEST_F(RPCBookChangesHandlerTest, LedgerNonExistViaStringSequence) { EXPECT_CALL(*backend_, fetchLedgerBySequence); // return empty ledgerHeader - ON_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ, _)).WillByDefault(Return(std::nullopt)); + ON_CALL(*backend_, fetchLedgerBySequence(kMaxSeq, _)).WillByDefault(Return(std::nullopt)); - static auto const kINPUT = json::parse(R"JSON({"ledger_index": "30"})JSON"); + static auto const kInput = boost::json::parse(R"JSON({"ledger_index": "30"})JSON"); auto const handler = AnyHandler{BookChangesHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -139,20 +138,20 @@ TEST_F(RPCBookChangesHandlerTest, LedgerNonExistViaStringSequence) TEST_F(RPCBookChangesHandlerTest, LedgerNonExistViaHash) { // return empty ledgerHeader - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillOnce(Return(std::optional{})); + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillOnce(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "ledger_hash": "{}" }})JSON", - kLEDGER_HASH + kLedgerHash ) ); auto const handler = AnyHandler{BookChangesHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -162,7 +161,7 @@ TEST_F(RPCBookChangesHandlerTest, LedgerNonExistViaHash) TEST_F(RPCBookChangesHandlerTest, NormalPath) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "type": "bookChanges", "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", @@ -183,33 +182,31 @@ TEST_F(RPCBookChangesHandlerTest, NormalPath) ] })JSON"; - EXPECT_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kMAX_SEQ))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kMaxSeq, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kMaxSeq))); auto transactions = std::vector{}; auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - ripple::STObject const metaObj = - createMetaDataForBookChange(kCURRENCY, kISSUER, 22, 1, 3, 3, 1); + xrpl::STObject const metaObj = createMetaDataForBookChange(kCurrency, kIssuer, 22, 1, 3, 3, 1); trans1.metadata = metaObj.getSerializer().peekData(); transactions.push_back(trans1); - EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kMAX_SEQ, _)) - .WillOnce(Return(transactions)); + EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kMaxSeq, _)).WillOnce(Return(transactions)); auto const handler = AnyHandler{BookChangesHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(json::parse("{}"), Context{yield}); + auto const output = handler.process(boost::json::parse("{}"), Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCBookChangesHandlerTest, NormalPathWithDomain) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "type": "bookChanges", "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", @@ -231,26 +228,25 @@ TEST_F(RPCBookChangesHandlerTest, NormalPathWithDomain) ] })JSON"; - EXPECT_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kMAX_SEQ))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kMaxSeq, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kMaxSeq))); auto transactions = std::vector{}; auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT1, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount1, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = 32; - ripple::STObject const metaObj = - createMetaDataForBookChange(kCURRENCY, kISSUER, 22, 1, 3, 3, 1, kDOMAIN); + xrpl::STObject const metaObj = + createMetaDataForBookChange(kCurrency, kIssuer, 22, 1, 3, 3, 1, kDomain); trans1.metadata = metaObj.getSerializer().peekData(); transactions.push_back(trans1); - EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kMAX_SEQ, _)) - .WillOnce(Return(transactions)); + EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kMaxSeq, _)).WillOnce(Return(transactions)); auto const handler = AnyHandler{BookChangesHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(json::parse("{}"), Context{yield}); + auto const output = handler.process(boost::json::parse("{}"), Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } diff --git a/tests/unit/rpc/handlers/BookOffersTests.cpp b/tests/unit/rpc/handlers/BookOffersTests.cpp index 7cd97bd73..e90e411d5 100644 --- a/tests/unit/rpc/handlers/BookOffersTests.cpp +++ b/tests/unit/rpc/handlers/BookOffersTests.cpp @@ -34,22 +34,22 @@ namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kINDEX1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; -constexpr auto kINDEX2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kIndex1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; +constexpr auto kIndex2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kPAYS20_USD_GETS10_XRP_BOOK_DIR = +constexpr auto kPayS20UsdGetS10XrpBookDir = "43B83ADC452B85FCBADA6CAEAC5181C255A213630D58FFD455071AFD498D0000"; -constexpr auto kPAYS20_XRP_GETS10_USD_BOOK_DIR = +constexpr auto kPayS20XrpGetS10UsdBookDir = "7B1767D41DBCE79D9585CF9D0262A5FEC45E5206FF524F8B55071AFD498D0000"; -constexpr auto kTRANSFER_RATE_X2 = 2000000000; +constexpr auto kTransferRateX2 = 2000000000; -constexpr auto kDOMAIN = "F10D0CC9A0F9A3CBF585B80BE09A186483668FDBDD39AA7E3370F3649CE134E5"; +constexpr auto kDomain = "F10D0CC9A0F9A3CBF585B80BE09A186483668FDBDD39AA7E3370F3649CE134E5"; struct ParameterTestBundle { std::string testName; @@ -62,7 +62,6 @@ struct ParameterTestBundle { using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; struct RPCBookOffersHandlerTest : HandlerBaseTest { @@ -83,7 +82,8 @@ TEST_P(RPCBookOffersParameterTest, CheckError) auto bundle = GetParam(); auto const handler = AnyHandler{BookOffersHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](boost::asio::yield_context yield) { - auto const output = handler.process(json::parse(bundle.testJson), Context{.yield = yield}); + auto const output = + handler.process(boost::json::parse(bundle.testJson), Context{.yield = yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), bundle.expectedError); @@ -491,16 +491,16 @@ INSTANTIATE_TEST_SUITE_P( RPCBookOffersHandler, RPCBookOffersParameterTest, testing::ValuesIn(generateParameterBookOffersTestBundles()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); struct BookOffersNormalTestBundle { std::string testName; std::string inputJson; - std::map> mockedSuccessors; - std::map mockedLedgerObjects; + std::map> mockedSuccessors; + std::map mockedLedgerObjects; uint32_t ledgerObjectCalls; - std::vector mockedOffers; + std::vector mockedOffers; std::string expectedJson; uint32_t amendmentIsEnabledCalls = 0; }; @@ -515,7 +515,7 @@ TEST_P(RPCBookOffersNormalPathTest, CheckOutput) EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return valid ledgerHeader - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, seq); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, seq); ON_CALL(*backend_, fetchLedgerBySequence(seq, _)).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(_, Amendments::fixFrozenLPTokenTransfer, _)) @@ -547,94 +547,83 @@ TEST_P(RPCBookOffersNormalPathTest, CheckOutput) auto const handler = AnyHandler{BookOffersHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](boost::asio::yield_context yield) { - auto const output = handler.process(json::parse(bundle.inputJson), Context{.yield = yield}); + auto const output = + handler.process(boost::json::parse(bundle.inputJson), Context{.yield = yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result.value(), json::parse(bundle.expectedJson)); + EXPECT_EQ(output.result.value(), boost::json::parse(bundle.expectedJson)); }); } static auto generateNormalPathBookOffersTestBundles() { - auto const account = getAccountIdWithString(kACCOUNT); - auto const account2 = getAccountIdWithString(kACCOUNT2); + auto const account = getAccountIdWithString(kAccount); + auto const account2 = getAccountIdWithString(kAccount2); auto const frozenTrustLine = createRippleStateLedgerObject( - "USD", kACCOUNT, -8, kACCOUNT2, 1000, kACCOUNT, 2000, kINDEX1, 2, ripple::lsfLowFreeze + "USD", kAccount, -8, kAccount2, 1000, kAccount, 2000, kIndex1, 2, xrpl::lsfLowFreeze ); auto const gets10USDPays20XRPOffer = createOfferLedgerObject( - kACCOUNT2, + kAccount2, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT, - toBase58(ripple::xrpAccount()), - kPAYS20_XRP_GETS10_USD_BOOK_DIR + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount, + toBase58(xrpl::xrpAccount()), + kPayS20XrpGetS10UsdBookDir ); auto const gets10USDPays20XRPOwnerOffer = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT, - toBase58(ripple::xrpAccount()), - kPAYS20_XRP_GETS10_USD_BOOK_DIR + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount, + toBase58(xrpl::xrpAccount()), + kPayS20XrpGetS10UsdBookDir ); auto const gets10XRPPays20USDOffer = createOfferLedgerObject( - kACCOUNT2, + kAccount2, 10, 20, - ripple::to_string(ripple::xrpCurrency()), - ripple::to_string(ripple::to_currency("USD")), - toBase58(ripple::xrpAccount()), - kACCOUNT, - kPAYS20_USD_GETS10_XRP_BOOK_DIR + xrpl::to_string(xrpl::xrpCurrency()), + xrpl::to_string(xrpl::toCurrency("USD")), + toBase58(xrpl::xrpAccount()), + kAccount, + kPayS20UsdGetS10XrpBookDir ); auto const gets10XRPPays20USDOfferWithDomain = createOfferLedgerObject( - kACCOUNT2, + kAccount2, 10, 20, - ripple::to_string(ripple::xrpCurrency()), - ripple::to_string(ripple::to_currency("USD")), - toBase58(ripple::xrpAccount()), - kACCOUNT, - kPAYS20_USD_GETS10_XRP_BOOK_DIR, - kDOMAIN + xrpl::to_string(xrpl::xrpCurrency()), + xrpl::to_string(xrpl::toCurrency("USD")), + toBase58(xrpl::xrpAccount()), + kAccount, + kPayS20UsdGetS10XrpBookDir, + kDomain ); auto const getsXRPPaysUSDBook = getBookBase( rpc::parseBook( - ripple::to_currency("USD"), - account, - ripple::xrpCurrency(), - ripple::xrpAccount(), - std::nullopt + xrpl::toCurrency("USD"), account, xrpl::xrpCurrency(), xrpl::xrpAccount(), std::nullopt ) .value() ); auto const getsXRPPaysUSDBookWithDomain = getBookBase( rpc::parseBook( - ripple::to_currency("USD"), - account, - ripple::xrpCurrency(), - ripple::xrpAccount(), - kDOMAIN + xrpl::toCurrency("USD"), account, xrpl::xrpCurrency(), xrpl::xrpAccount(), kDomain ) .value() ); auto const getsUSDPaysXRPBook = getBookBase( rpc::parseBook( - ripple::xrpCurrency(), - ripple::xrpAccount(), - ripple::to_currency("USD"), - account, - std::nullopt + xrpl::xrpCurrency(), xrpl::xrpAccount(), xrpl::toCurrency("USD"), account, std::nullopt ) .value() ); @@ -649,7 +638,7 @@ generateNormalPathBookOffersTestBundles() "issuer": "{}" }} }})JSON", - kACCOUNT + kAccount ); auto const getsXRPPaysUSDInputJsonWithDomain = fmt::format( @@ -663,8 +652,8 @@ generateNormalPathBookOffersTestBundles() }}, "domain": "{}" }})JSON", - kACCOUNT, - kDOMAIN + kAccount, + kDomain ); auto const paysXRPGetsUSDInputJson = fmt::format( @@ -677,17 +666,17 @@ generateNormalPathBookOffersTestBundles() "issuer": "{}" }} }})JSON", - kACCOUNT + kAccount ); auto const feeLedgerObject = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); auto const trustline30Balance = createRippleStateLedgerObject( - "USD", kACCOUNT, -30, kACCOUNT2, 1000, kACCOUNT, 2000, kINDEX1, 2, 0 + "USD", kAccount, -30, kAccount2, 1000, kAccount, 2000, kIndex1, 2, 0 ); auto const trustline8Balance = createRippleStateLedgerObject( - "USD", kACCOUNT, -8, kACCOUNT2, 1000, kACCOUNT, 2000, kINDEX1, 2, 0 + "USD", kAccount, -8, kAccount2, 1000, kAccount, 2000, kIndex1, 2, 0 ); return std::vector{ @@ -696,35 +685,34 @@ generateNormalPathBookOffersTestBundles() .inputJson = getsXRPPaysUSDInputJson, // prepare offer dir index .mockedSuccessors = - std::map>{ - {getsXRPPaysUSDBook, ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}}, - {ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}, - std::optional{}} + std::map>{ + {getsXRPPaysUSDBook, xrpl::uint256{kPayS20UsdGetS10XrpBookDir}}, + {xrpl::uint256{kPayS20UsdGetS10XrpBookDir}, std::optional{}} }, .mockedLedgerObjects = - std::map{ + std::map{ // book dir object - {ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}, - createOwnerDirLedgerObject({ripple::uint256{kINDEX2}}, kINDEX1) + {xrpl::uint256{kPayS20UsdGetS10XrpBookDir}, + createOwnerDirLedgerObject({xrpl::uint256{kIndex2}}, kIndex1) .getSerializer() .peekData()}, // pays issuer account object - {ripple::keylet::account(account).key, - createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2) + {xrpl::keylet::account(account).key, + createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2) .getSerializer() .peekData()}, // owner account object - {ripple::keylet::account(account2).key, - createAccountRootObject(kACCOUNT2, 0, 2, 200, 2, kINDEX1, 2) + {xrpl::keylet::account(account2).key, + createAccountRootObject(kAccount2, 0, 2, 200, 2, kIndex1, 2) .getSerializer() .peekData()}, // fee settings: base ->3 inc->2, account2 has 2 objects ,total // reserve ->7 // owner_funds should be 193 - {ripple::keylet::fees().key, feeLedgerObject} + {xrpl::keylet::feeSettings().key, feeLedgerObject} }, .ledgerObjectCalls = 5, - .mockedOffers = std::vector{gets10XRPPays20USDOffer}, + .mockedOffers = std::vector{gets10XRPPays20USDOffer}, .expectedJson = fmt::format( R"JSON({{ "ledger_hash": "{}", @@ -752,8 +740,8 @@ generateNormalPathBookOffersTestBundles() }} ] }})JSON", - kLEDGER_HASH, - kACCOUNT2, + kLedgerHash, + kAccount2, 193, 2 ) @@ -763,35 +751,34 @@ generateNormalPathBookOffersTestBundles() .inputJson = getsXRPPaysUSDInputJson, // prepare offer dir index .mockedSuccessors = - std::map>{ - {getsXRPPaysUSDBook, ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}}, - {ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}, - std::optional{}} + std::map>{ + {getsXRPPaysUSDBook, xrpl::uint256{kPayS20UsdGetS10XrpBookDir}}, + {xrpl::uint256{kPayS20UsdGetS10XrpBookDir}, std::optional{}} }, .mockedLedgerObjects = - std::map{ + std::map{ // book dir object - {ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}, - createOwnerDirLedgerObject({ripple::uint256{kINDEX2}}, kINDEX1) + {xrpl::uint256{kPayS20UsdGetS10XrpBookDir}, + createOwnerDirLedgerObject({xrpl::uint256{kIndex2}}, kIndex1) .getSerializer() .peekData()}, // pays issuer account object - {ripple::keylet::account(account).key, - createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2) + {xrpl::keylet::account(account).key, + createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2) .getSerializer() .peekData()}, // owner account object, hold - {ripple::keylet::account(account2).key, - createAccountRootObject(kACCOUNT2, 0, 2, 5 + 7, 2, kINDEX1, 2) + {xrpl::keylet::account(account2).key, + createAccountRootObject(kAccount2, 0, 2, 5 + 7, 2, kIndex1, 2) .getSerializer() .peekData()}, // fee settings: base ->3 inc->2, account2 has 2 objects // ,total // reserve ->7 - {ripple::keylet::fees().key, feeLedgerObject} + {xrpl::keylet::feeSettings().key, feeLedgerObject} }, .ledgerObjectCalls = 5, - .mockedOffers = std::vector{gets10XRPPays20USDOffer}, + .mockedOffers = std::vector{gets10XRPPays20USDOffer}, .expectedJson = fmt::format( R"JSON({{ "ledger_hash": "{}", @@ -825,8 +812,8 @@ generateNormalPathBookOffersTestBundles() }} ] }})JSON", - kLEDGER_HASH, - kACCOUNT2, + kLedgerHash, + kAccount2, 5, 2 ) @@ -836,28 +823,25 @@ generateNormalPathBookOffersTestBundles() .inputJson = getsXRPPaysUSDInputJson, // prepare offer dir index .mockedSuccessors = - std::map>{ - {getsXRPPaysUSDBook, ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}}, - {ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}, - std::optional{}} + std::map>{ + {getsXRPPaysUSDBook, xrpl::uint256{kPayS20UsdGetS10XrpBookDir}}, + {xrpl::uint256{kPayS20UsdGetS10XrpBookDir}, std::optional{}} }, .mockedLedgerObjects = - std::map{ + std::map{ // book dir object - {ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}, - createOwnerDirLedgerObject({ripple::uint256{kINDEX2}}, kINDEX1) + {xrpl::uint256{kPayS20UsdGetS10XrpBookDir}, + createOwnerDirLedgerObject({xrpl::uint256{kIndex2}}, kIndex1) .getSerializer() .peekData()}, // pays issuer account object - {ripple::keylet::account(account).key, - createAccountRootObject( - kACCOUNT, ripple::lsfGlobalFreeze, 2, 200, 2, kINDEX1, 2 - ) + {xrpl::keylet::account(account).key, + createAccountRootObject(kAccount, xrpl::lsfGlobalFreeze, 2, 200, 2, kIndex1, 2) .getSerializer() .peekData()} }, .ledgerObjectCalls = 3, - .mockedOffers = std::vector{gets10XRPPays20USDOffer}, + .mockedOffers = std::vector{gets10XRPPays20USDOffer}, .expectedJson = fmt::format( R"JSON({{ "ledger_hash": "{}", @@ -891,8 +875,8 @@ generateNormalPathBookOffersTestBundles() }} ] }})JSON", - kLEDGER_HASH, - kACCOUNT2, + kLedgerHash, + kAccount2, 0, 2 ) @@ -902,29 +886,25 @@ generateNormalPathBookOffersTestBundles() .inputJson = getsXRPPaysUSDInputJsonWithDomain, // prepare offer dir index .mockedSuccessors = - std::map>{ - {getsXRPPaysUSDBookWithDomain, - ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}}, - {ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}, - std::optional{}} + std::map>{ + {getsXRPPaysUSDBookWithDomain, xrpl::uint256{kPayS20UsdGetS10XrpBookDir}}, + {xrpl::uint256{kPayS20UsdGetS10XrpBookDir}, std::optional{}} }, .mockedLedgerObjects = - std::map{ + std::map{ // book dir object - {ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}, - createOwnerDirLedgerObject({ripple::uint256{kINDEX2}}, kINDEX1) + {xrpl::uint256{kPayS20UsdGetS10XrpBookDir}, + createOwnerDirLedgerObject({xrpl::uint256{kIndex2}}, kIndex1) .getSerializer() .peekData()}, // pays issuer account object - {ripple::keylet::account(account).key, - createAccountRootObject( - kACCOUNT, ripple::lsfGlobalFreeze, 2, 200, 2, kINDEX1, 2 - ) + {xrpl::keylet::account(account).key, + createAccountRootObject(kAccount, xrpl::lsfGlobalFreeze, 2, 200, 2, kIndex1, 2) .getSerializer() .peekData()} }, .ledgerObjectCalls = 3, - .mockedOffers = std::vector{gets10XRPPays20USDOfferWithDomain}, + .mockedOffers = std::vector{gets10XRPPays20USDOfferWithDomain}, .expectedJson = fmt::format( R"JSON({{ "ledger_hash": "{}", @@ -959,8 +939,8 @@ generateNormalPathBookOffersTestBundles() }} ] }})JSON", - kLEDGER_HASH, - kACCOUNT2, + kLedgerHash, + kAccount2, 0, 2 ) @@ -970,28 +950,27 @@ generateNormalPathBookOffersTestBundles() .inputJson = paysXRPGetsUSDInputJson, // prepare offer dir index .mockedSuccessors = - std::map>{ - {getsUSDPaysXRPBook, ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}}, - {ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, - std::optional{}} + std::map>{ + {getsUSDPaysXRPBook, xrpl::uint256{kPayS20XrpGetS10UsdBookDir}}, + {xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, std::optional{}} }, .mockedLedgerObjects = - std::map{ + std::map{ // book dir object - {ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, - createOwnerDirLedgerObject({ripple::uint256{kINDEX2}}, kINDEX1) + {xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, + createOwnerDirLedgerObject({xrpl::uint256{kIndex2}}, kIndex1) .getSerializer() .peekData()}, // gets issuer account object - {ripple::keylet::account(account).key, + {xrpl::keylet::account(account).key, createAccountRootObject( - kACCOUNT, ripple::lsfGlobalFreeze, 2, 200, 2, kINDEX1, 2, kTRANSFER_RATE_X2 + kAccount, xrpl::lsfGlobalFreeze, 2, 200, 2, kIndex1, 2, kTransferRateX2 ) .getSerializer() .peekData()} }, .ledgerObjectCalls = 3, - .mockedOffers = std::vector{gets10USDPays20XRPOffer}, + .mockedOffers = std::vector{gets10USDPays20XRPOffer}, .expectedJson = fmt::format( R"JSON({{ "ledger_hash": "{}", @@ -1025,9 +1004,9 @@ generateNormalPathBookOffersTestBundles() }} ] }})JSON", - kLEDGER_HASH, - kACCOUNT2, - kPAYS20_XRP_GETS10_USD_BOOK_DIR, + kLedgerHash, + kAccount2, + kPayS20XrpGetS10UsdBookDir, 0, 2 ) @@ -1037,29 +1016,28 @@ generateNormalPathBookOffersTestBundles() .inputJson = paysXRPGetsUSDInputJson, // prepare offer dir index .mockedSuccessors = - std::map>{ - {getsUSDPaysXRPBook, ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}}, - {ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, - std::optional{}} + std::map>{ + {getsUSDPaysXRPBook, xrpl::uint256{kPayS20XrpGetS10UsdBookDir}}, + {xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, std::optional{}} }, .mockedLedgerObjects = - std::map{ + std::map{ // book dir object - {ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, - createOwnerDirLedgerObject({ripple::uint256{kINDEX2}}, kINDEX1) + {xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, + createOwnerDirLedgerObject({xrpl::uint256{kIndex2}}, kIndex1) .getSerializer() .peekData()}, // gets issuer account object, rate is 1/2 - {ripple::keylet::account(account).key, - createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2, kTRANSFER_RATE_X2) + {xrpl::keylet::account(account).key, + createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2, kTransferRateX2) .getSerializer() .peekData()}, // trust line between gets issuer and owner,owner has 8 USD - {ripple::keylet::line(account2, account, ripple::to_currency("USD")).key, + {xrpl::keylet::trustLine(account2, account, xrpl::toCurrency("USD")).key, trustline8Balance.getSerializer().peekData()}, }, .ledgerObjectCalls = 6, - .mockedOffers = std::vector{gets10USDPays20XRPOffer}, + .mockedOffers = std::vector{gets10USDPays20XRPOffer}, .expectedJson = fmt::format( R"JSON({{ "ledger_hash": "{}", @@ -1093,9 +1071,9 @@ generateNormalPathBookOffersTestBundles() }} ] }})JSON", - kLEDGER_HASH, - kACCOUNT2, - kPAYS20_XRP_GETS10_USD_BOOK_DIR, + kLedgerHash, + kAccount2, + kPayS20XrpGetS10UsdBookDir, 8, 2 ), @@ -1106,32 +1084,31 @@ generateNormalPathBookOffersTestBundles() .inputJson = paysXRPGetsUSDInputJson, // prepare offer dir index .mockedSuccessors = - std::map>{ - {getsUSDPaysXRPBook, ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}}, - {ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, - std::optional{}} + std::map>{ + {getsUSDPaysXRPBook, xrpl::uint256{kPayS20XrpGetS10UsdBookDir}}, + {xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, std::optional{}} }, .mockedLedgerObjects = - std::map{ + std::map{ // book dir object - {ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, + {xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, createOwnerDirLedgerObject( - {ripple::uint256{kINDEX2}, ripple::uint256{kINDEX2}}, kINDEX1 + {xrpl::uint256{kIndex2}, xrpl::uint256{kIndex2}}, kIndex1 ) .getSerializer() .peekData()}, // gets issuer account object - {ripple::keylet::account(account).key, - createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2, kTRANSFER_RATE_X2) + {xrpl::keylet::account(account).key, + createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2, kTransferRateX2) .getSerializer() .peekData()}, // trust line between gets issuer and owner,owner has 30 USD - {ripple::keylet::line(account2, account, ripple::to_currency("USD")).key, + {xrpl::keylet::trustLine(account2, account, xrpl::toCurrency("USD")).key, trustline30Balance.getSerializer().peekData()}, }, .ledgerObjectCalls = 6, .mockedOffers = - std::vector{ + std::vector{ // After offer1, balance is 30 - 2*10 = 10 gets10USDPays20XRPOffer, // offer2 not fully funded, balance is 10, rate is 2, so only @@ -1190,13 +1167,13 @@ generateNormalPathBookOffersTestBundles() }} ] }})JSON", - kLEDGER_HASH, - kACCOUNT2, - kPAYS20_XRP_GETS10_USD_BOOK_DIR, + kLedgerHash, + kAccount2, + kPayS20XrpGetS10UsdBookDir, 30, 2, - kACCOUNT2, - kPAYS20_XRP_GETS10_USD_BOOK_DIR, + kAccount2, + kPayS20XrpGetS10UsdBookDir, 2 ), .amendmentIsEnabledCalls = 1, @@ -1206,26 +1183,25 @@ generateNormalPathBookOffersTestBundles() .inputJson = paysXRPGetsUSDInputJson, // prepare offer dir index .mockedSuccessors = - std::map>{ - {getsUSDPaysXRPBook, ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}}, - {ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, - std::optional{}} + std::map>{ + {getsUSDPaysXRPBook, xrpl::uint256{kPayS20XrpGetS10UsdBookDir}}, + {xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, std::optional{}} }, .mockedLedgerObjects = - std::map{ + std::map{ // book dir object - {ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, - createOwnerDirLedgerObject({ripple::uint256{kINDEX2}}, kINDEX1) + {xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, + createOwnerDirLedgerObject({xrpl::uint256{kIndex2}}, kIndex1) .getSerializer() .peekData()}, // gets issuer account object, rate is 1/2 - {ripple::keylet::account(account).key, - createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2, kTRANSFER_RATE_X2) + {xrpl::keylet::account(account).key, + createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2, kTransferRateX2) .getSerializer() .peekData()}, }, .ledgerObjectCalls = 3, - .mockedOffers = std::vector{gets10USDPays20XRPOwnerOffer}, + .mockedOffers = std::vector{gets10USDPays20XRPOwnerOffer}, .expectedJson = fmt::format( R"JSON({{ "ledger_hash": "{}", @@ -1253,9 +1229,9 @@ generateNormalPathBookOffersTestBundles() }} ] }})JSON", - kLEDGER_HASH, - kACCOUNT, - kPAYS20_XRP_GETS10_USD_BOOK_DIR, + kLedgerHash, + kAccount, + kPayS20XrpGetS10UsdBookDir, 10, 2 ) @@ -1265,29 +1241,28 @@ generateNormalPathBookOffersTestBundles() .inputJson = paysXRPGetsUSDInputJson, // prepare offer dir index .mockedSuccessors = - std::map>{ - {getsUSDPaysXRPBook, ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}}, - {ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, - std::optional{}} + std::map>{ + {getsUSDPaysXRPBook, xrpl::uint256{kPayS20XrpGetS10UsdBookDir}}, + {xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, std::optional{}} }, .mockedLedgerObjects = - std::map{ + std::map{ // book dir object - {ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, - createOwnerDirLedgerObject({ripple::uint256{kINDEX2}}, kINDEX1) + {xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, + createOwnerDirLedgerObject({xrpl::uint256{kIndex2}}, kIndex1) .getSerializer() .peekData()}, // gets issuer account object, rate is 1/2 - {ripple::keylet::account(account).key, - createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2, kTRANSFER_RATE_X2) + {xrpl::keylet::account(account).key, + createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2, kTransferRateX2) .getSerializer() .peekData()}, // trust line between gets issuer and owner,owner has 8 USD - {ripple::keylet::line(account2, account, ripple::to_currency("USD")).key, + {xrpl::keylet::trustLine(account2, account, xrpl::toCurrency("USD")).key, frozenTrustLine.getSerializer().peekData()}, }, .ledgerObjectCalls = 6, - .mockedOffers = std::vector{gets10USDPays20XRPOffer}, + .mockedOffers = std::vector{gets10USDPays20XRPOffer}, .expectedJson = fmt::format( R"JSON({{ "ledger_hash": "{}", @@ -1321,9 +1296,9 @@ generateNormalPathBookOffersTestBundles() }} ] }})JSON", - kLEDGER_HASH, - kACCOUNT2, - kPAYS20_XRP_GETS10_USD_BOOK_DIR, + kLedgerHash, + kAccount2, + kPayS20XrpGetS10UsdBookDir, 0, 2 ), @@ -1333,35 +1308,27 @@ generateNormalPathBookOffersTestBundles() .inputJson = paysXRPGetsUSDInputJson, // prepare offer dir index .mockedSuccessors = - std::map>{ - {getsUSDPaysXRPBook, ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}}, - {ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, - std::optional{}} + std::map>{ + {getsUSDPaysXRPBook, xrpl::uint256{kPayS20XrpGetS10UsdBookDir}}, + {xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, std::optional{}} }, .mockedLedgerObjects = - std::map{ + std::map{ // book dir object - {ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, - createOwnerDirLedgerObject({ripple::uint256{kINDEX2}}, kINDEX1) + {xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, + createOwnerDirLedgerObject({xrpl::uint256{kIndex2}}, kIndex1) .getSerializer() .peekData()}, // gets issuer account object, is deep frozen so unfunded - {ripple::keylet::account(account).key, + {xrpl::keylet::account(account).key, createAccountRootObject( - kACCOUNT, - ripple::lsfLowDeepFreeze, - 2, - 200, - 2, - kINDEX1, - 2, - kTRANSFER_RATE_X2 + kAccount, xrpl::lsfLowDeepFreeze, 2, 200, 2, kIndex1, 2, kTransferRateX2 ) .getSerializer() .peekData()}, }, .ledgerObjectCalls = 4, - .mockedOffers = std::vector{gets10USDPays20XRPOffer}, + .mockedOffers = std::vector{gets10USDPays20XRPOffer}, .expectedJson = fmt::format( R"JSON({{ "ledger_hash": "{}", @@ -1395,9 +1362,9 @@ generateNormalPathBookOffersTestBundles() }} ] }})JSON", - kLEDGER_HASH, - kACCOUNT2, - kPAYS20_XRP_GETS10_USD_BOOK_DIR, + kLedgerHash, + kAccount2, + kPayS20XrpGetS10UsdBookDir, 0, 2 ) @@ -1407,38 +1374,30 @@ generateNormalPathBookOffersTestBundles() .inputJson = paysXRPGetsUSDInputJson, // prepare offer dir index .mockedSuccessors = - std::map>{ - {getsUSDPaysXRPBook, ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}}, - {ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, - std::optional{}} + std::map>{ + {getsUSDPaysXRPBook, xrpl::uint256{kPayS20XrpGetS10UsdBookDir}}, + {xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, std::optional{}} }, .mockedLedgerObjects = - std::map{ + std::map{ // book dir object - {ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, - createOwnerDirLedgerObject({ripple::uint256{kINDEX2}}, kINDEX1) + {xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, + createOwnerDirLedgerObject({xrpl::uint256{kIndex2}}, kIndex1) .getSerializer() .peekData()}, // gets issuer account object, is deep frozen so unfunded - {ripple::keylet::account(account).key, + {xrpl::keylet::account(account).key, createAccountRootObject( - kACCOUNT, - ripple::lsfLowDeepFreeze, - 2, - 200, - 2, - kINDEX1, - 2, - kTRANSFER_RATE_X2 + kAccount, xrpl::lsfLowDeepFreeze, 2, 200, 2, kIndex1, 2, kTransferRateX2 ) .getSerializer() .peekData()}, - {ripple::keylet::line(account2, account, ripple::to_currency("USD")).key, + {xrpl::keylet::trustLine(account2, account, xrpl::toCurrency("USD")).key, frozenTrustLine.getSerializer().peekData()}, }, .ledgerObjectCalls = 6, - .mockedOffers = std::vector{gets10USDPays20XRPOffer}, + .mockedOffers = std::vector{gets10USDPays20XRPOffer}, .expectedJson = fmt::format( R"JSON({{ "ledger_hash": "{}", @@ -1472,9 +1431,9 @@ generateNormalPathBookOffersTestBundles() }} ] }})JSON", - kLEDGER_HASH, - kACCOUNT2, - kPAYS20_XRP_GETS10_USD_BOOK_DIR, + kLedgerHash, + kAccount2, + kPayS20XrpGetS10UsdBookDir, 0, 2 ) @@ -1486,7 +1445,7 @@ INSTANTIATE_TEST_SUITE_P( RPCBookOffersHandler, RPCBookOffersNormalPathTest, testing::ValuesIn(generateNormalPathBookOffersTestBundles()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); // ledger not exist @@ -1495,9 +1454,9 @@ TEST_F(RPCBookOffersHandlerTest, LedgerNonExistViaIntSequence) EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return empty ledgerHeader ON_CALL(*backend_, fetchLedgerBySequence(30, _)) - .WillByDefault(Return(std::optional{})); + .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "ledger_index": 30, @@ -1509,12 +1468,12 @@ TEST_F(RPCBookOffersHandlerTest, LedgerNonExistViaIntSequence) "issuer": "{}" }} }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{BookOffersHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](boost::asio::yield_context yield) { - auto const output = handler.process(kINPUT, Context{.yield = yield}); + auto const output = handler.process(kInput, Context{.yield = yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -1527,9 +1486,9 @@ TEST_F(RPCBookOffersHandlerTest, LedgerNonExistViaSequence) EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return empty ledgerHeader ON_CALL(*backend_, fetchLedgerBySequence(30, _)) - .WillByDefault(Return(std::optional{})); + .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "ledger_index": "30", @@ -1541,12 +1500,12 @@ TEST_F(RPCBookOffersHandlerTest, LedgerNonExistViaSequence) "issuer": "{}" }} }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{BookOffersHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](boost::asio::yield_context yield) { - auto const output = handler.process(kINPUT, Context{.yield = yield}); + auto const output = handler.process(kInput, Context{.yield = yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -1558,10 +1517,10 @@ TEST_F(RPCBookOffersHandlerTest, LedgerNonExistViaHash) { EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // return empty ledgerHeader - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillByDefault(Return(std::optional{})); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "ledger_hash": "{}", @@ -1573,13 +1532,13 @@ TEST_F(RPCBookOffersHandlerTest, LedgerNonExistViaHash) "issuer": "{}" }} }})JSON", - kLEDGER_HASH, - kACCOUNT + kLedgerHash, + kAccount ) ); auto const handler = AnyHandler{BookOffersHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](boost::asio::yield_context yield) { - auto const output = handler.process(kINPUT, Context{.yield = yield}); + auto const output = handler.process(kInput, Context{.yield = yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -1593,69 +1552,63 @@ TEST_F(RPCBookOffersHandlerTest, Limit) EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return valid ledgerHeader - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, seq); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, seq); ON_CALL(*backend_, fetchLedgerBySequence(seq, _)).WillByDefault(Return(ledgerHeader)); - auto const issuer = getAccountIdWithString(kACCOUNT); + auto const issuer = getAccountIdWithString(kAccount); // return valid book dir EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(1); auto const getsXRPPaysUSDBook = getBookBase( rpc::parseBook( - ripple::to_currency("USD"), - issuer, - ripple::xrpCurrency(), - ripple::xrpAccount(), - std::nullopt + xrpl::toCurrency("USD"), issuer, xrpl::xrpCurrency(), xrpl::xrpAccount(), std::nullopt ) .value() ); ON_CALL(*backend_, doFetchSuccessorKey(getsXRPPaysUSDBook, seq, _)) - .WillByDefault(Return(ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR})); + .WillByDefault(Return(xrpl::uint256{kPayS20UsdGetS10XrpBookDir})); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(5); - auto const indexes = std::vector(10, ripple::uint256{kINDEX2}); + auto const indexes = std::vector(10, xrpl::uint256{kIndex2}); - ON_CALL( - *backend_, doFetchLedgerObject(ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}, seq, _) - ) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kPayS20UsdGetS10XrpBookDir}, seq, _)) .WillByDefault( - Return(createOwnerDirLedgerObject(indexes, kINDEX1).getSerializer().peekData()) + Return(createOwnerDirLedgerObject(indexes, kIndex1).getSerializer().peekData()) ); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, seq, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, seq, _) ) .WillByDefault(Return( - createAccountRootObject(kACCOUNT2, 0, 2, 200, 2, kINDEX1, 2).getSerializer().peekData() + createAccountRootObject(kAccount2, 0, 2, 200, 2, kIndex1, 2).getSerializer().peekData() )); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, seq, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, seq, _)) .WillByDefault(Return(createLegacyFeeSettingBlob(1, 2, 3, 4, 0))); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::account(issuer).key, seq, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::account(issuer).key, seq, _)) .WillByDefault( - Return(createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2, kTRANSFER_RATE_X2) + Return(createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2, kTransferRateX2) .getSerializer() .peekData()) ); auto const gets10XRPPays20USDOffer = createOfferLedgerObject( - kACCOUNT2, + kAccount2, 10, 20, - ripple::to_string(ripple::xrpCurrency()), - ripple::to_string(ripple::to_currency("USD")), - toBase58(ripple::xrpAccount()), - kACCOUNT, - kPAYS20_USD_GETS10_XRP_BOOK_DIR + xrpl::to_string(xrpl::xrpCurrency()), + xrpl::to_string(xrpl::toCurrency("USD")), + toBase58(xrpl::xrpAccount()), + kAccount, + kPayS20UsdGetS10XrpBookDir ); std::vector const bbs(10, gets10XRPPays20USDOffer.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "taker_gets": {{ @@ -1667,12 +1620,12 @@ TEST_F(RPCBookOffersHandlerTest, Limit) }}, "limit": 5 }})JSON", - kACCOUNT + kAccount ) ); auto const handler = AnyHandler{BookOffersHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](boost::asio::yield_context yield) { - auto const output = handler.process(kINPUT, Context{.yield = yield}); + auto const output = handler.process(kInput, Context{.yield = yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result.value().as_object().at("offers").as_array().size(), 5); }); @@ -1684,72 +1637,66 @@ TEST_F(RPCBookOffersHandlerTest, LimitMoreThanMax) EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return valid ledgerHeader - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, seq); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, seq); ON_CALL(*backend_, fetchLedgerBySequence(seq, _)).WillByDefault(Return(ledgerHeader)); - auto const issuer = getAccountIdWithString(kACCOUNT); + auto const issuer = getAccountIdWithString(kAccount); // return valid book dir EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(1); auto const getsXRPPaysUSDBook = getBookBase( rpc::parseBook( - ripple::to_currency("USD"), - issuer, - ripple::xrpCurrency(), - ripple::xrpAccount(), - std::nullopt + xrpl::toCurrency("USD"), issuer, xrpl::xrpCurrency(), xrpl::xrpAccount(), std::nullopt ) .value() ); ON_CALL(*backend_, doFetchSuccessorKey(getsXRPPaysUSDBook, seq, _)) - .WillByDefault(Return(ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR})); + .WillByDefault(Return(xrpl::uint256{kPayS20UsdGetS10XrpBookDir})); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(5); auto const indexes = - std::vector(BookOffersHandler::kLIMIT_MAX + 1, ripple::uint256{kINDEX2}); + std::vector(BookOffersHandler::kLimitMax + 1, xrpl::uint256{kIndex2}); - ON_CALL( - *backend_, doFetchLedgerObject(ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}, seq, _) - ) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kPayS20UsdGetS10XrpBookDir}, seq, _)) .WillByDefault( - Return(createOwnerDirLedgerObject(indexes, kINDEX1).getSerializer().peekData()) + Return(createOwnerDirLedgerObject(indexes, kIndex1).getSerializer().peekData()) ); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, seq, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, seq, _) ) .WillByDefault(Return( - createAccountRootObject(kACCOUNT2, 0, 2, 200, 2, kINDEX1, 2).getSerializer().peekData() + createAccountRootObject(kAccount2, 0, 2, 200, 2, kIndex1, 2).getSerializer().peekData() )); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, seq, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, seq, _)) .WillByDefault(Return(createLegacyFeeSettingBlob(1, 2, 3, 4, 0))); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::account(issuer).key, seq, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::account(issuer).key, seq, _)) .WillByDefault( - Return(createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2, kTRANSFER_RATE_X2) + Return(createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2, kTransferRateX2) .getSerializer() .peekData()) ); auto const gets10XRPPays20USDOffer = createOfferLedgerObject( - kACCOUNT2, + kAccount2, 10, 20, - ripple::to_string(ripple::xrpCurrency()), - ripple::to_string(ripple::to_currency("USD")), - toBase58(ripple::xrpAccount()), - kACCOUNT, - kPAYS20_USD_GETS10_XRP_BOOK_DIR + xrpl::to_string(xrpl::xrpCurrency()), + xrpl::to_string(xrpl::toCurrency("USD")), + toBase58(xrpl::xrpAccount()), + kAccount, + kPayS20UsdGetS10XrpBookDir ); std::vector const bbs( - BookOffersHandler::kLIMIT_MAX + 1, gets10XRPPays20USDOffer.getSerializer().peekData() + BookOffersHandler::kLimitMax + 1, gets10XRPPays20USDOffer.getSerializer().peekData() ); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "taker_gets": {{ @@ -1761,17 +1708,17 @@ TEST_F(RPCBookOffersHandlerTest, LimitMoreThanMax) }}, "limit": {} }})JSON", - kACCOUNT, - BookOffersHandler::kLIMIT_MAX + 1 + kAccount, + BookOffersHandler::kLimitMax + 1 ) ); auto const handler = AnyHandler{BookOffersHandler{backend_, mockAmendmentCenterPtr_}}; runSpawn([&](boost::asio::yield_context yield) { - auto const output = handler.process(kINPUT, Context{.yield = yield}); + auto const output = handler.process(kInput, Context{.yield = yield}); ASSERT_TRUE(output); EXPECT_EQ( output.result.value().as_object().at("offers").as_array().size(), - BookOffersHandler::kLIMIT_MAX + BookOffersHandler::kLimitMax ); }); } diff --git a/tests/unit/rpc/handlers/CredentialHelpersTests.cpp b/tests/unit/rpc/handlers/CredentialHelpersTests.cpp index 9a90974fc..07cf381b0 100644 --- a/tests/unit/rpc/handlers/CredentialHelpersTests.cpp +++ b/tests/unit/rpc/handlers/CredentialHelpersTests.cpp @@ -31,19 +31,19 @@ using namespace testing; namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kINDEX1 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kCREDENTIAL_ID = "c7a14f6b9d5d4a9cb9c223a61b8e5c7df58e8b7ad1c6b4f8e7a321fa4e5b4c9d"; -constexpr std::string_view kCREDENTIAL_TYPE = "credType"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kIndex1 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kCredentialId = "c7a14f6b9d5d4a9cb9c223a61b8e5c7df58e8b7ad1c6b4f8e7a321fa4e5b4c9d"; +constexpr std::string_view kCredentialType = "credType"; } // namespace TEST(CreateAuthCredentialsTest, UniqueCredentials) { - ripple::STArray credentials; - auto const cred1 = createCredentialObject(kACCOUNT, kACCOUNT2, kCREDENTIAL_TYPE); - auto const cred2 = createCredentialObject(kACCOUNT2, kACCOUNT, kCREDENTIAL_TYPE); + xrpl::STArray credentials; + auto const cred1 = createCredentialObject(kAccount, kAccount2, kCredentialType); + auto const cred2 = createCredentialObject(kAccount2, kAccount, kCredentialType); credentials.push_back(cred1); credentials.push_back(cred2); @@ -53,14 +53,14 @@ TEST(CreateAuthCredentialsTest, UniqueCredentials) // Validate that the result contains the correct set of credentials ASSERT_EQ(result.size(), 2); - auto const cred1Type = cred1.getFieldVL(ripple::sfCredentialType); - auto const cred2Type = cred2.getFieldVL(ripple::sfCredentialType); + auto const cred1Type = cred1.getFieldVL(xrpl::sfCredentialType); + auto const cred2Type = cred2.getFieldVL(xrpl::sfCredentialType); auto const expectedCred1 = std::make_pair( - cred1.getAccountID(ripple::sfIssuer), ripple::Slice{cred1Type.data(), cred1Type.size()} + cred1.getAccountID(xrpl::sfIssuer), xrpl::Slice{cred1Type.data(), cred1Type.size()} ); auto const expectedCred2 = std::make_pair( - cred2.getAccountID(ripple::sfIssuer), ripple::Slice{cred2Type.data(), cred2Type.size()} + cred2.getAccountID(xrpl::sfIssuer), xrpl::Slice{cred2Type.data(), cred2Type.size()} ); EXPECT_TRUE(result.count(expectedCred1)); @@ -71,28 +71,28 @@ TEST(ParseAuthorizeCredentialsTest, ValidCredentialsArray) { boost::json::array credentials; boost::json::object credential1; - credential1[JS(issuer)] = kACCOUNT; - credential1[JS(credential_type)] = ripple::strHex(kCREDENTIAL_TYPE); + credential1[JS(issuer)] = kAccount; + credential1[JS(credential_type)] = xrpl::strHex(kCredentialType); credentials.push_back(credential1); - ripple::STArray const parsedCredentials = credentials::parseAuthorizeCredentials(credentials); + xrpl::STArray const parsedCredentials = credentials::parseAuthorizeCredentials(credentials); ASSERT_EQ(parsedCredentials.size(), 1); - ripple::STObject const& cred = parsedCredentials[0]; - ASSERT_TRUE(cred.isFieldPresent(ripple::sfIssuer)); - ASSERT_TRUE(cred.isFieldPresent(ripple::sfCredentialType)); + xrpl::STObject const& cred = parsedCredentials[0]; + ASSERT_TRUE(cred.isFieldPresent(xrpl::sfIssuer)); + ASSERT_TRUE(cred.isFieldPresent(xrpl::sfCredentialType)); auto const expectedIssuer = - *ripple::parseBase58( // NOLINT(bugprone-unchecked-optional-access) + *xrpl::parseBase58( // NOLINT(bugprone-unchecked-optional-access) static_cast(credential1[JS(issuer)].as_string()) ); auto const expectedCredentialType = // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - *ripple::strUnHex(static_cast(credential1[JS(credential_type)].as_string())); + *xrpl::strUnHex(static_cast(credential1[JS(credential_type)].as_string())); - EXPECT_EQ(cred.getAccountID(ripple::sfIssuer), expectedIssuer); - EXPECT_EQ(cred.getFieldVL(ripple::sfCredentialType), expectedCredentialType); + EXPECT_EQ(cred.getAccountID(xrpl::sfIssuer), expectedIssuer); + EXPECT_EQ(cred.getFieldVL(xrpl::sfCredentialType), expectedCredentialType); } class CredentialHelperTest : public util::prometheus::WithPrometheus, @@ -101,16 +101,16 @@ class CredentialHelperTest : public util::prometheus::WithPrometheus, TEST_F(CredentialHelperTest, GetInvalidCredentialArray) { - boost::json::array credentialsArray = {kCREDENTIAL_ID}; - auto const info = createLedgerHeader(kINDEX1, 30); + boost::json::array credentialsArray = {kCredentialId}; + auto const info = createLedgerHeader(kIndex1, 30); util::spawn(ctx_, [&](boost::asio::yield_context yield) { auto const ret = credentials::fetchCredentialArray( - credentialsArray, getAccountIdWithString(kACCOUNT), *backend_, info, yield + credentialsArray, getAccountIdWithString(kAccount), *backend_, info, yield ); ASSERT_FALSE(ret.has_value()); auto const status = ret.error(); - EXPECT_EQ(status, RippledError::rpcBAD_CREDENTIALS); + EXPECT_EQ(status, RippledError::RpcBadCredentials); EXPECT_EQ(status.message, "credentials don't exist."); }); ctx_.run(); @@ -120,28 +120,27 @@ TEST_F(CredentialHelperTest, GetValidCredentialArray) { backend_->setRange(10, 30); - auto ledgerHeader = createLedgerHeader(kINDEX1, 30); + auto ledgerHeader = createLedgerHeader(kIndex1, 30); auto const credLedgerObject = - createCredentialObject(kACCOUNT, kACCOUNT2, kCREDENTIAL_TYPE, true); + createCredentialObject(kAccount, kAccount2, kCredentialType, true); ON_CALL(*backend_, doFetchLedgerObject(_, _, _)) .WillByDefault(Return(credLedgerObject.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); - boost::json::array credentialsArray = {kCREDENTIAL_ID}; + boost::json::array credentialsArray = {kCredentialId}; - ripple::STArray expectedAuthCreds; - ripple::STObject credential(ripple::sfCredential); - credential.setAccountID(ripple::sfIssuer, getAccountIdWithString(kACCOUNT2)); + xrpl::STArray expectedAuthCreds; + xrpl::STObject credential(xrpl::sfCredential); + credential.setAccountID(xrpl::sfIssuer, getAccountIdWithString(kAccount2)); credential.setFieldVL( - ripple::sfCredentialType, - ripple::Blob{std::begin(kCREDENTIAL_TYPE), std::end(kCREDENTIAL_TYPE)} + xrpl::sfCredentialType, xrpl::Blob{std::begin(kCredentialType), std::end(kCredentialType)} ); expectedAuthCreds.push_back(std::move(credential)); util::spawn(ctx_, [&](boost::asio::yield_context yield) { auto const result = credentials::fetchCredentialArray( - credentialsArray, getAccountIdWithString(kACCOUNT), *backend_, ledgerHeader, yield + credentialsArray, getAccountIdWithString(kAccount), *backend_, ledgerHeader, yield ); ASSERT_TRUE(result.has_value()); EXPECT_EQ(result.value(), expectedAuthCreds); diff --git a/tests/unit/rpc/handlers/DefaultProcessorTests.cpp b/tests/unit/rpc/handlers/DefaultProcessorTests.cpp index 800b52f0d..cb4066ec0 100644 --- a/tests/unit/rpc/handlers/DefaultProcessorTests.cpp +++ b/tests/unit/rpc/handlers/DefaultProcessorTests.cpp @@ -16,8 +16,6 @@ using namespace rpc; using namespace rpc::validation; using namespace tests::common; -namespace json = boost::json; - class RPCDefaultProcessorTest : public HandlerBaseTest {}; TEST_F(RPCDefaultProcessorTest, ValidInput) @@ -26,7 +24,7 @@ TEST_F(RPCDefaultProcessorTest, ValidInput) HandlerMock const handler; rpc::impl::DefaultProcessor const processor; - auto const input = json::parse(R"JSON({ "something": "works" })JSON"); + auto const input = boost::json::parse(R"JSON({ "something": "works" })JSON"); auto const spec = RpcSpec{{"something", Required{}}}; auto const data = InOutFake{"works"}; EXPECT_CALL(handler, spec(_)).WillOnce(ReturnRef(spec)); @@ -45,7 +43,7 @@ TEST_F(RPCDefaultProcessorTest, NoInputValidCall) rpc::impl::DefaultProcessor const processor; auto const data = InOutFake{"works"}; - auto const input = json::parse(R"JSON({})JSON"); + auto const input = boost::json::parse(R"JSON({})JSON"); EXPECT_CALL(handler, process(_)).WillOnce(Return(data)); auto const ret = processor(handler, input, Context{yield}); @@ -60,7 +58,7 @@ TEST_F(RPCDefaultProcessorTest, InvalidInput) HandlerMock const handler; rpc::impl::DefaultProcessor const processor; - auto const input = json::parse(R"JSON({ "other": "nope" })JSON"); + auto const input = boost::json::parse(R"JSON({ "other": "nope" })JSON"); auto const spec = RpcSpec{{"something", Required{}}}; EXPECT_CALL(handler, spec(_)).WillOnce(ReturnRef(spec)); diff --git a/tests/unit/rpc/handlers/DepositAuthorizedTests.cpp b/tests/unit/rpc/handlers/DepositAuthorizedTests.cpp index 5fe9909bf..457a3fd97 100644 --- a/tests/unit/rpc/handlers/DepositAuthorizedTests.cpp +++ b/tests/unit/rpc/handlers/DepositAuthorizedTests.cpp @@ -28,29 +28,27 @@ namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kINDEX1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; -constexpr auto kINDEX2 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515B1"; -constexpr auto kCREDENTIAL_HASH = - "F245428267E6177AEEFDD4FEA3533285712A4B1091CF82A7EA7BC39A62C3FB1A"; -constexpr std::string_view kCREDENTIAL_TYPE = "credType"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kIndex1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; +constexpr auto kIndex2 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515B1"; +constexpr auto kCredentialHash = "F245428267E6177AEEFDD4FEA3533285712A4B1091CF82A7EA7BC39A62C3FB1A"; +constexpr std::string_view kCredentialType = "credType"; -constexpr auto kRANGE_MIN = 10; -constexpr auto kRANGE_MAX = 30; +constexpr auto kRangeMin = 10; +constexpr auto kRangeMax = 30; } // namespace using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; struct RPCDepositAuthorizedTest : HandlerBaseTest { RPCDepositAuthorizedTest() { - backend_->setRange(kRANGE_MIN, kRANGE_MAX); + backend_->setRange(kRangeMin, kRangeMax); } }; @@ -196,7 +194,7 @@ INSTANTIATE_TEST_CASE_P( RPCDepositAuthorizedGroup, DepositAuthorizedParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(DepositAuthorizedParameterTest, InvalidParams) @@ -204,7 +202,7 @@ TEST_P(DepositAuthorizedParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{DepositAuthorizedHandler{backend_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); @@ -218,20 +216,20 @@ TEST_P(DepositAuthorizedParameterTest, InvalidParams) TEST_F(RPCDepositAuthorizedTest, LedgerNotExistViaIntSequence) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(std::nullopt)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{DepositAuthorizedHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", "destination_account": "{}", "ledger_index": {} }})JSON", - kACCOUNT, - kACCOUNT2, - kRANGE_MAX + kAccount, + kAccount2, + kRangeMax ) ); @@ -247,20 +245,20 @@ TEST_F(RPCDepositAuthorizedTest, LedgerNotExistViaIntSequence) TEST_F(RPCDepositAuthorizedTest, LedgerNotExistViaStringSequence) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(std::nullopt)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{DepositAuthorizedHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", "destination_account": "{}", "ledger_index": "{}" }})JSON", - kACCOUNT, - kACCOUNT2, - kRANGE_MAX + kAccount, + kAccount2, + kRangeMax ) ); @@ -276,21 +274,21 @@ TEST_F(RPCDepositAuthorizedTest, LedgerNotExistViaStringSequence) TEST_F(RPCDepositAuthorizedTest, LedgerNotExistViaHash) { EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{DepositAuthorizedHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", "destination_account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kACCOUNT2, - kLEDGER_HASH + kAccount, + kAccount2, + kLedgerHash ) ); @@ -305,25 +303,25 @@ TEST_F(RPCDepositAuthorizedTest, LedgerNotExistViaHash) TEST_F(RPCDepositAuthorizedTest, SourceAccountDoesNotExist) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); ON_CALL(*backend_, doFetchLedgerObject).WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", "destination_account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kACCOUNT2, - kLEDGER_HASH + kAccount, + kAccount2, + kLedgerHash ) ); @@ -341,33 +339,33 @@ TEST_F(RPCDepositAuthorizedTest, SourceAccountDoesNotExist) TEST_F(RPCDepositAuthorizedTest, DestinationAccountDoesNotExist) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const accountRoot = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const accountRoot = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); ON_CALL(*backend_, doFetchLedgerObject(_, _, _)) .WillByDefault(Return(accountRoot.getSerializer().peekData())); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, _, _) ) .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", "destination_account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kACCOUNT2, - kLEDGER_HASH + kAccount, + kAccount2, + kLedgerHash ) ); @@ -385,7 +383,7 @@ TEST_F(RPCDepositAuthorizedTest, DestinationAccountDoesNotExist) TEST_F(RPCDepositAuthorizedTest, AccountsAreEqual) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -395,27 +393,27 @@ TEST_F(RPCDepositAuthorizedTest, AccountsAreEqual) "destination_account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn" })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const accountRoot = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const accountRoot = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); ON_CALL(*backend_, doFetchLedgerObject) .WillByDefault(Return(accountRoot.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", "destination_account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kACCOUNT, - kLEDGER_HASH + kAccount, + kAccount, + kLedgerHash ) ); @@ -424,13 +422,13 @@ TEST_F(RPCDepositAuthorizedTest, AccountsAreEqual) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCDepositAuthorizedTest, DifferentAccountsNoDepositAuthFlag) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -440,37 +438,37 @@ TEST_F(RPCDepositAuthorizedTest, DifferentAccountsNoDepositAuthFlag) "destination_account": "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun" })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const account1Root = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); - auto const account2Root = createAccountRootObject(kACCOUNT2, 0, 2, 200, 2, kINDEX2, 2); + auto const account1Root = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); + auto const account2Root = createAccountRootObject(kAccount2, 0, 2, 200, 2, kIndex2, 2); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount)).key, _, _) ) .WillByDefault(Return(account1Root.getSerializer().peekData())); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, _, _) ) .WillByDefault(Return(account2Root.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", "destination_account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kACCOUNT2, - kLEDGER_HASH + kAccount, + kAccount2, + kLedgerHash ) ); @@ -479,13 +477,13 @@ TEST_F(RPCDepositAuthorizedTest, DifferentAccountsNoDepositAuthFlag) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCDepositAuthorizedTest, DifferentAccountsWithDepositAuthFlagReturnsFalse) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -495,39 +493,39 @@ TEST_F(RPCDepositAuthorizedTest, DifferentAccountsWithDepositAuthFlagReturnsFals "destination_account": "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun" })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const account1Root = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const account1Root = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); auto const account2Root = - createAccountRootObject(kACCOUNT2, ripple::lsfDepositAuth, 2, 200, 2, kINDEX2, 2); + createAccountRootObject(kAccount2, xrpl::lsfDepositAuth, 2, 200, 2, kIndex2, 2); ON_CALL(*backend_, doFetchLedgerObject(_, _, _)).WillByDefault(Return(std::nullopt)); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount)).key, _, _) ) .WillByDefault(Return(account1Root.getSerializer().peekData())); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, _, _) ) .WillByDefault(Return(account2Root.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", "destination_account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kACCOUNT2, - kLEDGER_HASH + kAccount, + kAccount2, + kLedgerHash ) ); @@ -536,13 +534,13 @@ TEST_F(RPCDepositAuthorizedTest, DifferentAccountsWithDepositAuthFlagReturnsFals auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCDepositAuthorizedTest, DifferentAccountsWithDepositAuthFlagReturnsTrue) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -552,40 +550,40 @@ TEST_F(RPCDepositAuthorizedTest, DifferentAccountsWithDepositAuthFlagReturnsTrue "destination_account": "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun" })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const account1Root = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const account1Root = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); auto const account2Root = - createAccountRootObject(kACCOUNT2, ripple::lsfDepositAuth, 2, 200, 2, kINDEX2, 2); + createAccountRootObject(kAccount2, xrpl::lsfDepositAuth, 2, 200, 2, kIndex2, 2); ON_CALL(*backend_, doFetchLedgerObject(_, _, _)) .WillByDefault(Return(std::optional{{1, 2, 3}})); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount)).key, _, _) ) .WillByDefault(Return(account1Root.getSerializer().peekData())); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, _, _) ) .WillByDefault(Return(account2Root.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", "destination_account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kACCOUNT2, - kLEDGER_HASH + kAccount, + kAccount2, + kLedgerHash ) ); @@ -594,13 +592,13 @@ TEST_F(RPCDepositAuthorizedTest, DifferentAccountsWithDepositAuthFlagReturnsTrue auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCDepositAuthorizedTest, CredentialAcceptedAndNotExpiredReturnsTrue) { - static auto const kEXPECTED_OUT = fmt::format( + static auto const kExpectedOut = fmt::format( R"JSON({{ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -610,22 +608,22 @@ TEST_F(RPCDepositAuthorizedTest, CredentialAcceptedAndNotExpiredReturnsTrue) "destination_account": "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun", "credentials": ["{}"] }})JSON", - kCREDENTIAL_HASH // CREDENTIALHASH should match credentialIndex + kCredentialHash // CREDENTIALHASH should match credentialIndex ); - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillOnce(Return(ledgerHeader)); - auto const account1Root = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const account1Root = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); auto const account2Root = - createAccountRootObject(kACCOUNT2, ripple::lsfDepositAuth, 2, 200, 2, kINDEX2, 2); - auto const credential = createCredentialObject(kACCOUNT, kACCOUNT2, kCREDENTIAL_TYPE); - auto const credentialIndex = ripple::keylet::credential( - getAccountIdWithString(kACCOUNT), - getAccountIdWithString(kACCOUNT2), - ripple::Slice(kCREDENTIAL_TYPE.data(), kCREDENTIAL_TYPE.size()) + createAccountRootObject(kAccount2, xrpl::lsfDepositAuth, 2, 200, 2, kIndex2, 2); + auto const credential = createCredentialObject(kAccount, kAccount2, kCredentialType); + auto const credentialIndex = xrpl::keylet::credential( + getAccountIdWithString(kAccount), + getAccountIdWithString(kAccount2), + xrpl::Slice(kCredentialType.data(), kCredentialType.size()) ) .key; @@ -633,19 +631,19 @@ TEST_F(RPCDepositAuthorizedTest, CredentialAcceptedAndNotExpiredReturnsTrue) .WillByDefault(Return(std::optional{{1, 2, 3}})); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount)).key, _, _) ) .WillByDefault(Return(account1Root.getSerializer().peekData())); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, _, _) ) .WillByDefault(Return(account2Root.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(credentialIndex, _, _)) .WillByDefault(Return(credential.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(4); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", @@ -653,10 +651,10 @@ TEST_F(RPCDepositAuthorizedTest, CredentialAcceptedAndNotExpiredReturnsTrue) "ledger_hash": "{}", "credentials": ["{}"] }})JSON", - kACCOUNT, - kACCOUNT2, - kLEDGER_HASH, - ripple::strHex(credentialIndex) + kAccount, + kAccount2, + kLedgerHash, + xrpl::strHex(credentialIndex) ) ); @@ -665,25 +663,25 @@ TEST_F(RPCDepositAuthorizedTest, CredentialAcceptedAndNotExpiredReturnsTrue) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCDepositAuthorizedTest, CredentialNotAuthorizedReturnsFalse) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillOnce(Return(ledgerHeader)); - auto const account1Root = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const account1Root = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); auto const account2Root = - createAccountRootObject(kACCOUNT2, ripple::lsfDepositAuth, 2, 200, 2, kINDEX2, 2); - auto const credential = createCredentialObject(kACCOUNT, kACCOUNT2, kCREDENTIAL_TYPE, false); - auto const credentialIndex = ripple::keylet::credential( - getAccountIdWithString(kACCOUNT), - getAccountIdWithString(kACCOUNT2), - ripple::Slice(kCREDENTIAL_TYPE.data(), kCREDENTIAL_TYPE.size()) + createAccountRootObject(kAccount2, xrpl::lsfDepositAuth, 2, 200, 2, kIndex2, 2); + auto const credential = createCredentialObject(kAccount, kAccount2, kCredentialType, false); + auto const credentialIndex = xrpl::keylet::credential( + getAccountIdWithString(kAccount), + getAccountIdWithString(kAccount2), + xrpl::Slice(kCredentialType.data(), kCredentialType.size()) ) .key; @@ -691,12 +689,12 @@ TEST_F(RPCDepositAuthorizedTest, CredentialNotAuthorizedReturnsFalse) .WillByDefault(Return(std::optional{{1, 2, 3}})); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount)).key, _, _) ) .WillByDefault(Return(account1Root.getSerializer().peekData())); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, _, _) ) .WillByDefault(Return(account2Root.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(credentialIndex, _, _)) @@ -704,7 +702,7 @@ TEST_F(RPCDepositAuthorizedTest, CredentialNotAuthorizedReturnsFalse) EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", @@ -712,10 +710,10 @@ TEST_F(RPCDepositAuthorizedTest, CredentialNotAuthorizedReturnsFalse) "ledger_hash": "{}", "credentials": ["{}"] }})JSON", - kACCOUNT, - kACCOUNT2, - kLEDGER_HASH, - ripple::strHex(credentialIndex) + kAccount, + kAccount2, + kLedgerHash, + xrpl::strHex(credentialIndex) ) ); @@ -732,26 +730,26 @@ TEST_F(RPCDepositAuthorizedTest, CredentialNotAuthorizedReturnsFalse) TEST_F(RPCDepositAuthorizedTest, CredentialExpiredReturnsFalse) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 100); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30, 100); // set parent close time to 500 seconds - ledgerHeader.parentCloseTime = ripple::NetClock::time_point{std::chrono::seconds{500}}; + ledgerHeader.parentCloseTime = xrpl::NetClock::time_point{std::chrono::seconds{500}}; - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillOnce(Return(ledgerHeader)); - auto const account1Root = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const account1Root = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); auto const account2Root = - createAccountRootObject(kACCOUNT2, ripple::lsfDepositAuth, 2, 200, 2, kINDEX2, 2); + createAccountRootObject(kAccount2, xrpl::lsfDepositAuth, 2, 200, 2, kIndex2, 2); // credential expire time is 23 seconds, so credential will fail auto const expiredCredential = - createCredentialObject(kACCOUNT, kACCOUNT2, kCREDENTIAL_TYPE, true, 23); + createCredentialObject(kAccount, kAccount2, kCredentialType, true, 23); - auto const credentialIndex = ripple::keylet::credential( - getAccountIdWithString(kACCOUNT), - getAccountIdWithString(kACCOUNT2), - ripple::Slice(kCREDENTIAL_TYPE.data(), kCREDENTIAL_TYPE.size()) + auto const credentialIndex = xrpl::keylet::credential( + getAccountIdWithString(kAccount), + getAccountIdWithString(kAccount2), + xrpl::Slice(kCredentialType.data(), kCredentialType.size()) ) .key; @@ -759,12 +757,12 @@ TEST_F(RPCDepositAuthorizedTest, CredentialExpiredReturnsFalse) .WillByDefault(Return(std::optional{{1, 2, 3}})); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount)).key, _, _) ) .WillByDefault(Return(account1Root.getSerializer().peekData())); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, _, _) ) .WillByDefault(Return(account2Root.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(credentialIndex, _, _)) @@ -772,7 +770,7 @@ TEST_F(RPCDepositAuthorizedTest, CredentialExpiredReturnsFalse) EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", @@ -780,10 +778,10 @@ TEST_F(RPCDepositAuthorizedTest, CredentialExpiredReturnsFalse) "ledger_hash": "{}", "credentials": ["{}"] }})JSON", - kACCOUNT, - kACCOUNT2, - kLEDGER_HASH, - ripple::strHex(credentialIndex) + kAccount, + kAccount2, + kLedgerHash, + xrpl::strHex(credentialIndex) ) ); @@ -800,19 +798,19 @@ TEST_F(RPCDepositAuthorizedTest, CredentialExpiredReturnsFalse) TEST_F(RPCDepositAuthorizedTest, DuplicateCredentialsReturnsFalse) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 34); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30, 34); - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillOnce(Return(ledgerHeader)); - auto const account1Root = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const account1Root = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); auto const account2Root = - createAccountRootObject(kACCOUNT2, ripple::lsfDepositAuth, 2, 200, 2, kINDEX2, 2); - auto const credential = createCredentialObject(kACCOUNT, kACCOUNT2, kCREDENTIAL_TYPE); - auto const credentialIndex = ripple::keylet::credential( - getAccountIdWithString(kACCOUNT), - getAccountIdWithString(kACCOUNT2), - ripple::Slice(kCREDENTIAL_TYPE.data(), kCREDENTIAL_TYPE.size()) + createAccountRootObject(kAccount2, xrpl::lsfDepositAuth, 2, 200, 2, kIndex2, 2); + auto const credential = createCredentialObject(kAccount, kAccount2, kCredentialType); + auto const credentialIndex = xrpl::keylet::credential( + getAccountIdWithString(kAccount), + getAccountIdWithString(kAccount2), + xrpl::Slice(kCredentialType.data(), kCredentialType.size()) ) .key; @@ -820,12 +818,12 @@ TEST_F(RPCDepositAuthorizedTest, DuplicateCredentialsReturnsFalse) .WillByDefault(Return(std::optional{{1, 2, 3}})); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount)).key, _, _) ) .WillByDefault(Return(account1Root.getSerializer().peekData())); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, _, _) ) .WillByDefault(Return(account2Root.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(credentialIndex, _, _)) @@ -833,7 +831,7 @@ TEST_F(RPCDepositAuthorizedTest, DuplicateCredentialsReturnsFalse) EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", @@ -841,11 +839,11 @@ TEST_F(RPCDepositAuthorizedTest, DuplicateCredentialsReturnsFalse) "ledger_hash": "{}", "credentials": ["{}", "{}"] }})JSON", - kACCOUNT, - kACCOUNT2, - kLEDGER_HASH, - ripple::strHex(credentialIndex), - ripple::strHex(credentialIndex) + kAccount, + kAccount2, + kLedgerHash, + xrpl::strHex(credentialIndex), + xrpl::strHex(credentialIndex) ) ); @@ -862,31 +860,31 @@ TEST_F(RPCDepositAuthorizedTest, DuplicateCredentialsReturnsFalse) TEST_F(RPCDepositAuthorizedTest, NoElementsInCredentialsReturnsFalse) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 34); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30, 34); - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillOnce(Return(ledgerHeader)); - auto const account1Root = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const account1Root = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); auto const account2Root = - createAccountRootObject(kACCOUNT2, ripple::lsfDepositAuth, 2, 200, 2, kINDEX2, 2); + createAccountRootObject(kAccount2, xrpl::lsfDepositAuth, 2, 200, 2, kIndex2, 2); ON_CALL(*backend_, doFetchLedgerObject(_, _, _)) .WillByDefault(Return(std::optional{{1, 2, 3}})); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount)).key, _, _) ) .WillByDefault(Return(account1Root.getSerializer().peekData())); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, _, _) ) .WillByDefault(Return(account2Root.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", @@ -894,9 +892,9 @@ TEST_F(RPCDepositAuthorizedTest, NoElementsInCredentialsReturnsFalse) "ledger_hash": "{}", "credentials": [] }})JSON", - kACCOUNT, - kACCOUNT2, - kLEDGER_HASH + kAccount, + kAccount2, + kLedgerHash ) ); @@ -913,19 +911,19 @@ TEST_F(RPCDepositAuthorizedTest, NoElementsInCredentialsReturnsFalse) TEST_F(RPCDepositAuthorizedTest, MoreThanMaxNumberOfCredentialsReturnsFalse) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 34); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30, 34); - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillOnce(Return(ledgerHeader)); - auto const account1Root = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const account1Root = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); auto const account2Root = - createAccountRootObject(kACCOUNT2, ripple::lsfDepositAuth, 2, 200, 2, kINDEX2, 2); - auto const credential = createCredentialObject(kACCOUNT, kACCOUNT2, kCREDENTIAL_TYPE); - auto const credentialIndex = ripple::keylet::credential( - getAccountIdWithString(kACCOUNT), - getAccountIdWithString(kACCOUNT2), - ripple::Slice(kCREDENTIAL_TYPE.data(), kCREDENTIAL_TYPE.size()) + createAccountRootObject(kAccount2, xrpl::lsfDepositAuth, 2, 200, 2, kIndex2, 2); + auto const credential = createCredentialObject(kAccount, kAccount2, kCredentialType); + auto const credentialIndex = xrpl::keylet::credential( + getAccountIdWithString(kAccount), + getAccountIdWithString(kAccount2), + xrpl::Slice(kCredentialType.data(), kCredentialType.size()) ) .key; @@ -933,12 +931,12 @@ TEST_F(RPCDepositAuthorizedTest, MoreThanMaxNumberOfCredentialsReturnsFalse) .WillByDefault(Return(std::optional{{1, 2, 3}})); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount)).key, _, _) ) .WillByDefault(Return(account1Root.getSerializer().peekData())); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, _, _) ) .WillByDefault(Return(account2Root.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(credentialIndex, _, _)) @@ -946,9 +944,9 @@ TEST_F(RPCDepositAuthorizedTest, MoreThanMaxNumberOfCredentialsReturnsFalse) EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); - std::vector credentials(9, ripple::strHex(credentialIndex)); + std::vector credentials(9, xrpl::strHex(credentialIndex)); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", @@ -956,9 +954,9 @@ TEST_F(RPCDepositAuthorizedTest, MoreThanMaxNumberOfCredentialsReturnsFalse) "ledger_hash": "{}", "credentials": [{}] }})JSON", - kACCOUNT, - kACCOUNT2, - kLEDGER_HASH, + kAccount, + kAccount2, + kLedgerHash, fmt::join( credentials | std::views::transform([](std::string const& cred) { return fmt::format("\"{}\"", cred); @@ -981,21 +979,21 @@ TEST_F(RPCDepositAuthorizedTest, MoreThanMaxNumberOfCredentialsReturnsFalse) TEST_F(RPCDepositAuthorizedTest, DifferentSubjectAccountForCredentialReturnsFalse) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillOnce(Return(ledgerHeader)); - auto const account1Root = createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2); + auto const account1Root = createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2); auto const account2Root = - createAccountRootObject(kACCOUNT2, ripple::lsfDepositAuth, 2, 200, 2, kINDEX2, 2); + createAccountRootObject(kAccount2, xrpl::lsfDepositAuth, 2, 200, 2, kIndex2, 2); // reverse the subject and issuer account. Now subject is Account2 - auto const credential = createCredentialObject(kACCOUNT2, kACCOUNT, kCREDENTIAL_TYPE); - auto const credentialIndex = ripple::keylet::credential( - getAccountIdWithString(kACCOUNT2), - getAccountIdWithString(kACCOUNT), - ripple::Slice(kCREDENTIAL_TYPE.data(), kCREDENTIAL_TYPE.size()) + auto const credential = createCredentialObject(kAccount2, kAccount, kCredentialType); + auto const credentialIndex = xrpl::keylet::credential( + getAccountIdWithString(kAccount2), + getAccountIdWithString(kAccount), + xrpl::Slice(kCredentialType.data(), kCredentialType.size()) ) .key; @@ -1003,19 +1001,19 @@ TEST_F(RPCDepositAuthorizedTest, DifferentSubjectAccountForCredentialReturnsFals .WillByDefault(Return(std::optional{{1, 2, 3}})); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount)).key, _, _) ) .WillByDefault(Return(account1Root.getSerializer().peekData())); ON_CALL( *backend_, - doFetchLedgerObject(ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, _, _) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, _, _) ) .WillByDefault(Return(account2Root.getSerializer().peekData())); ON_CALL(*backend_, doFetchLedgerObject(credentialIndex, _, _)) .WillByDefault(Return(credential.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "source_account": "{}", @@ -1023,10 +1021,10 @@ TEST_F(RPCDepositAuthorizedTest, DifferentSubjectAccountForCredentialReturnsFals "ledger_hash": "{}", "credentials": ["{}"] }})JSON", - kACCOUNT, - kACCOUNT2, - kLEDGER_HASH, - ripple::strHex(credentialIndex) + kAccount, + kAccount2, + kLedgerHash, + xrpl::strHex(credentialIndex) ) ); diff --git a/tests/unit/rpc/handlers/FeatureTests.cpp b/tests/unit/rpc/handlers/FeatureTests.cpp index 3483da0cd..36a576861 100644 --- a/tests/unit/rpc/handlers/FeatureTests.cpp +++ b/tests/unit/rpc/handlers/FeatureTests.cpp @@ -24,18 +24,18 @@ using namespace data; namespace { -constexpr auto kRANGE_MIN = 10; -constexpr auto kRANGE_MAX = 30; -constexpr auto kSEQ = 30; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kAPI_VERSION = 2; +constexpr auto kRangeMin = 10; +constexpr auto kRangeMax = 30; +constexpr auto kSeq = 30; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kApiVersion = 2; } // namespace struct RPCFeatureHandlerTest : HandlerBaseTest { RPCFeatureHandlerTest() { - backend_->setRange(kRANGE_MIN, kRANGE_MAX); + backend_->setRange(kRangeMin, kRangeMax); } protected: @@ -146,7 +146,7 @@ INSTANTIATE_TEST_CASE_P( RPCFeatureGroup1, RPCFeatureHandlerParamTest, testing::ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(RPCFeatureHandlerParamTest, InvalidParams) @@ -156,7 +156,7 @@ TEST_P(RPCFeatureHandlerParamTest, InvalidParams) auto const handler = AnyHandler{FeatureHandler{backend_, mockAmendmentCenterPtr_}}; auto const req = boost::json::parse(testBundle.testJson); auto const output = - handler.process(req, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + handler.process(req, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -167,7 +167,7 @@ TEST_P(RPCFeatureHandlerParamTest, InvalidParams) TEST_F(RPCFeatureHandlerTest, LedgerNotExistViaIntSequence) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, testing::_)) + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, testing::_)) .WillOnce(testing::Return(std::nullopt)); runSpawn([&, this](auto yield) { @@ -177,7 +177,7 @@ TEST_F(RPCFeatureHandlerTest, LedgerNotExistViaIntSequence) R"JSON({{ "ledger_index": {} }})JSON", - kRANGE_MAX + kRangeMax ) ); auto const output = handler.process(req, Context{yield}); @@ -190,7 +190,7 @@ TEST_F(RPCFeatureHandlerTest, LedgerNotExistViaIntSequence) TEST_F(RPCFeatureHandlerTest, LedgerNotExistViaStringSequence) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, testing::_)) + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, testing::_)) .WillOnce(testing::Return(std::nullopt)); runSpawn([&, this](auto yield) { @@ -200,7 +200,7 @@ TEST_F(RPCFeatureHandlerTest, LedgerNotExistViaStringSequence) R"JSON({{ "ledger_index": "{}" }})JSON", - kRANGE_MAX + kRangeMax ) ); auto const output = handler.process(req, Context{yield}); @@ -213,7 +213,7 @@ TEST_F(RPCFeatureHandlerTest, LedgerNotExistViaStringSequence) TEST_F(RPCFeatureHandlerTest, LedgerNotExistViaHash) { - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, testing::_)) + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, testing::_)) .WillOnce(testing::Return(std::nullopt)); runSpawn([&, this](auto yield) { @@ -223,7 +223,7 @@ TEST_F(RPCFeatureHandlerTest, LedgerNotExistViaHash) R"JSON({{ "ledger_hash": "{}" }})JSON", - kLEDGER_HASH + kLedgerHash ) ); auto const output = handler.process(req, Context{yield}); @@ -273,10 +273,10 @@ TEST_F(RPCFeatureHandlerTest, SuccessPathViaNameWithSingleSupportedAndEnabledRes auto const enabled = std::vector{true}; EXPECT_CALL(*mockAmendmentCenterPtr_, getAll).WillOnce(testing::ReturnRef(all)); - EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(testing::_, keys, kSEQ)) + EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(testing::_, keys, kSeq)) .WillOnce(testing::Return(enabled)); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(testing::Return(ledgerHeader)); auto const expectedOutput = fmt::format( @@ -290,8 +290,8 @@ TEST_F(RPCFeatureHandlerTest, SuccessPathViaNameWithSingleSupportedAndEnabledRes "ledger_index": {}, "validated": true }})JSON", - kLEDGER_HASH, - kSEQ + kLedgerHash, + kSeq ); runSpawn([this, &expectedOutput](auto yield) { @@ -325,10 +325,10 @@ TEST_F(RPCFeatureHandlerTest, SuccessPathViaHashWithSingleResult) auto const enabled = std::vector{true}; EXPECT_CALL(*mockAmendmentCenterPtr_, getAll).WillOnce(testing::ReturnRef(all)); - EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(testing::_, keys, kSEQ)) + EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(testing::_, keys, kSeq)) .WillOnce(testing::Return(enabled)); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(testing::Return(ledgerHeader)); auto const expectedOutput = fmt::format( @@ -342,8 +342,8 @@ TEST_F(RPCFeatureHandlerTest, SuccessPathViaHashWithSingleResult) "ledger_index": {}, "validated": true }})JSON", - kLEDGER_HASH, - kSEQ + kLedgerHash, + kSeq ); runSpawn([this, &expectedOutput](auto yield) { @@ -371,7 +371,7 @@ TEST_F(RPCFeatureHandlerTest, BadFeaturePath) auto const keys = std::vector{"nonexistent"}; EXPECT_CALL(*mockAmendmentCenterPtr_, getAll).WillOnce(testing::ReturnRef(all)); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(testing::Return(ledgerHeader)); runSpawn([this](auto yield) { @@ -391,7 +391,7 @@ TEST_F(RPCFeatureHandlerTest, BadFeaturePath) TEST_F(RPCFeatureHandlerTest, DeletedLibXRPLAmendmentQueryByNameReturnsSupportedFalse) { auto const ownerPaysFeeKey = - ripple::to_string(data::Amendment::getAmendmentId(Amendments::OwnerPaysFee)); + xrpl::to_string(data::Amendment::getAmendmentId(Amendments::OwnerPaysFee)); auto const all = std::vector{{ .name = Amendments::OwnerPaysFee, .feature = data::Amendment::getAmendmentId(Amendments::OwnerPaysFee), @@ -403,10 +403,10 @@ TEST_F(RPCFeatureHandlerTest, DeletedLibXRPLAmendmentQueryByNameReturnsSupported auto const enabled = std::vector{false}; EXPECT_CALL(*mockAmendmentCenterPtr_, getAll).WillOnce(testing::ReturnRef(all)); - EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(testing::_, keys, kSEQ)) + EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(testing::_, keys, kSeq)) .WillOnce(testing::Return(enabled)); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(testing::Return(ledgerHeader)); auto const expectedOutput = fmt::format( @@ -421,8 +421,8 @@ TEST_F(RPCFeatureHandlerTest, DeletedLibXRPLAmendmentQueryByNameReturnsSupported "validated": true }})JSON", ownerPaysFeeKey, - kLEDGER_HASH, - kSEQ + kLedgerHash, + kSeq ); runSpawn([this, &expectedOutput](auto yield) { @@ -439,7 +439,7 @@ TEST_F(RPCFeatureHandlerTest, DeletedLibXRPLAmendmentQueryByNameReturnsSupported TEST_F(RPCFeatureHandlerTest, DeletedLibXRPLAmendmentQueryByHashReturnsSupportedFalse) { auto const ownerPaysFeeKey = - ripple::to_string(data::Amendment::getAmendmentId(Amendments::OwnerPaysFee)); + xrpl::to_string(data::Amendment::getAmendmentId(Amendments::OwnerPaysFee)); auto const all = std::vector{{ .name = Amendments::OwnerPaysFee, .feature = data::Amendment::getAmendmentId(Amendments::OwnerPaysFee), @@ -451,10 +451,10 @@ TEST_F(RPCFeatureHandlerTest, DeletedLibXRPLAmendmentQueryByHashReturnsSupported auto const enabled = std::vector{true}; EXPECT_CALL(*mockAmendmentCenterPtr_, getAll).WillOnce(testing::ReturnRef(all)); - EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(testing::_, keys, kSEQ)) + EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(testing::_, keys, kSeq)) .WillOnce(testing::Return(enabled)); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(testing::Return(ledgerHeader)); auto const expectedOutput = fmt::format( @@ -469,8 +469,8 @@ TEST_F(RPCFeatureHandlerTest, DeletedLibXRPLAmendmentQueryByHashReturnsSupported "validated": true }})JSON", ownerPaysFeeKey, - kLEDGER_HASH, - kSEQ + kLedgerHash, + kSeq ); runSpawn([this, &ownerPaysFeeKey, &expectedOutput](auto yield) { @@ -506,10 +506,10 @@ TEST_F(RPCFeatureHandlerTest, SuccessPathWithMultipleResults) auto const enabled = std::vector{true, false}; EXPECT_CALL(*mockAmendmentCenterPtr_, getAll).WillOnce(testing::ReturnRef(all)); - EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(testing::_, keys, kSEQ)) + EXPECT_CALL(*mockAmendmentCenterPtr_, isEnabled(testing::_, keys, kSeq)) .WillOnce(testing::Return(enabled)); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(testing::Return(ledgerHeader)); auto const amendments = createAmendmentsObject( @@ -534,8 +534,8 @@ TEST_F(RPCFeatureHandlerTest, SuccessPathWithMultipleResults) "ledger_index": {}, "validated": true }})JSON", - kLEDGER_HASH, - kSEQ + kLedgerHash, + kSeq ); runSpawn([this, &expectedOutput](auto yield) { diff --git a/tests/unit/rpc/handlers/GatewayBalancesTests.cpp b/tests/unit/rpc/handlers/GatewayBalancesTests.cpp index 0e946aec3..dfe62fdb5 100644 --- a/tests/unit/rpc/handlers/GatewayBalancesTests.cpp +++ b/tests/unit/rpc/handlers/GatewayBalancesTests.cpp @@ -28,20 +28,19 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kACCOUNT3 = "raHGBERMka3KZsfpTQUAtumxmvpqhFLyrk"; -constexpr auto kISSUER = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kINDEX1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; -constexpr auto kINDEX2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kTXN_ID = "E3FE6EA3D48F0C2B639448020EA4F03D4F4F8FFDB243A852A0F59177921B4879"; -constexpr auto kAPI_VERSION = 2; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kAccount3 = "raHGBERMka3KZsfpTQUAtumxmvpqhFLyrk"; +constexpr auto kIssuer = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kIndex1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; +constexpr auto kIndex2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kTxnId = "E3FE6EA3D48F0C2B639448020EA4F03D4F4F8FFDB243A852A0F59177921B4879"; +constexpr auto kApiVersion = 2; struct ParameterTestBundle { std::string testName; @@ -68,7 +67,8 @@ TEST_P(ParameterTest, CheckError) auto const handler = AnyHandler{GatewayBalancesHandler{backend_}}; runSpawn([&](auto yield) { auto const output = handler.process( - json::parse(bundle.testJson), Context{.yield = yield, .apiVersion = bundle.apiVersion} + boost::json::parse(bundle.testJson), + Context{.yield = yield, .apiVersion = bundle.apiVersion} ); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -111,7 +111,7 @@ generateParameterTestBundles() "account": "{}", "ledger_index": "meh" }})JSON", - kACCOUNT + kAccount ), .expectedError = "invalidParams", .expectedErrorMessage = "ledgerIndexMalformed" @@ -123,7 +123,7 @@ generateParameterTestBundles() "account": "{}", "ledger_hash": "meh" }})JSON", - kACCOUNT + kAccount ), .expectedError = "invalidParams", .expectedErrorMessage = "ledger_hashMalformed" @@ -135,7 +135,7 @@ generateParameterTestBundles() "account": "{}", "ledger_hash": 12 }})JSON", - kACCOUNT + kAccount ), .expectedError = "invalidParams", .expectedErrorMessage = "ledger_hashNotString" @@ -147,7 +147,7 @@ generateParameterTestBundles() "account": "{}", "hotwallet": 12 }})JSON", - kACCOUNT + kAccount ), .expectedError = "invalidHotWallet", .expectedErrorMessage = "hotwalletNotStringOrArray" @@ -159,7 +159,7 @@ generateParameterTestBundles() "account": "{}", "hotwallet": [12] }})JSON", - kACCOUNT + kAccount ), .expectedError = "invalidHotWallet", .expectedErrorMessage = "hotwalletMalformed" @@ -171,7 +171,7 @@ generateParameterTestBundles() "account": "{}", "hotwallet": ["12"] }})JSON", - kACCOUNT + kAccount ), .expectedError = "invalidHotWallet", .expectedErrorMessage = "hotwalletMalformed" @@ -183,7 +183,7 @@ generateParameterTestBundles() "account": "{}", "hotwallet": "12" }})JSON", - kACCOUNT + kAccount ), .expectedError = "invalidHotWallet", .expectedErrorMessage = "hotwalletMalformed" @@ -195,11 +195,11 @@ generateParameterTestBundles() "account": "{}", "hotwallet": 12 }})JSON", - kACCOUNT + kAccount ), .expectedError = "invalidParams", .expectedErrorMessage = "hotwalletNotStringOrArray", - .apiVersion = kAPI_VERSION + .apiVersion = kApiVersion }, ParameterTestBundle{ .testName = "WalletsNotStringAccountV2", @@ -208,11 +208,11 @@ generateParameterTestBundles() "account": "{}", "hotwallet": [12] }})JSON", - kACCOUNT + kAccount ), .expectedError = "invalidParams", .expectedErrorMessage = "hotwalletMalformed", - .apiVersion = kAPI_VERSION + .apiVersion = kApiVersion }, ParameterTestBundle{ .testName = "WalletsInvalidAccountV2", @@ -221,11 +221,11 @@ generateParameterTestBundles() "account": "{}", "hotwallet": ["12"] }})JSON", - kACCOUNT + kAccount ), .expectedError = "invalidParams", .expectedErrorMessage = "hotwalletMalformed", - .apiVersion = kAPI_VERSION + .apiVersion = kApiVersion }, ParameterTestBundle{ .testName = "WalletInvalidAccountV2", @@ -234,11 +234,11 @@ generateParameterTestBundles() "account": "{}", "hotwallet": "12" }})JSON", - kACCOUNT + kAccount ), .expectedError = "invalidParams", .expectedErrorMessage = "hotwalletMalformed", - .apiVersion = kAPI_VERSION + .apiVersion = kApiVersion }, }; } @@ -247,7 +247,7 @@ INSTANTIATE_TEST_SUITE_P( RPCGatewayBalancesHandler, ParameterTest, testing::ValuesIn(generateParameterTestBundles()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_F(RPCGatewayBalancesHandlerTest, LedgerNotFoundViaStringIndex) @@ -255,18 +255,18 @@ TEST_F(RPCGatewayBalancesHandlerTest, LedgerNotFoundViaStringIndex) auto const seq = 123; EXPECT_CALL(*backend_, fetchLedgerBySequence(seq, _)) - .WillOnce(Return(std::optional{})); + .WillOnce(Return(std::optional{})); auto const handler = AnyHandler{GatewayBalancesHandler{backend_}}; runSpawn([&](auto yield) { auto const output = handler.process( - json::parse( + boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": "{}" }})JSON", - kACCOUNT, + kAccount, seq ) ), @@ -284,18 +284,18 @@ TEST_F(RPCGatewayBalancesHandlerTest, LedgerNotFoundViaIntIndex) auto const seq = 123; EXPECT_CALL(*backend_, fetchLedgerBySequence(seq, _)) - .WillOnce(Return(std::optional{})); + .WillOnce(Return(std::optional{})); auto const handler = AnyHandler{GatewayBalancesHandler{backend_}}; runSpawn([&](auto yield) { auto const output = handler.process( - json::parse( + boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_index": {} }})JSON", - kACCOUNT, + kAccount, seq ) ), @@ -310,20 +310,20 @@ TEST_F(RPCGatewayBalancesHandlerTest, LedgerNotFoundViaIntIndex) TEST_F(RPCGatewayBalancesHandlerTest, LedgerNotFoundViaHash) { - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillOnce(Return(std::optional{})); + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillOnce(Return(std::optional{})); auto const handler = AnyHandler{GatewayBalancesHandler{backend_}}; runSpawn([&](auto yield) { auto const output = handler.process( - json::parse( + boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ), Context{yield} @@ -339,22 +339,22 @@ TEST_F(RPCGatewayBalancesHandlerTest, AccountNotFound) { auto const seq = 300; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, seq); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, seq); EXPECT_CALL(*backend_, fetchLedgerBySequence(seq, _)).WillOnce(Return(ledgerHeader)); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, seq, _)) .WillOnce(Return(std::optional{})); auto const handler = AnyHandler{GatewayBalancesHandler{backend_}}; runSpawn([&](auto yield) { auto const output = handler.process( - json::parse( + boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ), Context{yield} @@ -368,8 +368,8 @@ TEST_F(RPCGatewayBalancesHandlerTest, AccountNotFound) struct NormalTestBundle { std::string testName; - ripple::STObject mockedDir; - std::vector mockedObjects; + xrpl::STObject mockedDir; + std::vector mockedObjects; std::string expectedJson; std::string hotwallet; }; @@ -383,17 +383,17 @@ TEST_P(NormalPathTest, CheckOutput) auto const seq = 300; // return valid ledgerHeader - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, seq); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, seq); EXPECT_CALL(*backend_, fetchLedgerBySequence(seq, _)).WillOnce(Return(ledgerHeader)); // return valid account - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, seq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); // return valid owner dir - auto const ownerDir = createOwnerDirLedgerObject({ripple::uint256{kINDEX2}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; + auto const ownerDir = createOwnerDirLedgerObject({xrpl::uint256{kIndex2}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, seq, _)) .WillOnce(Return(bundle.mockedDir.getSerializer().peekData())); @@ -406,20 +406,20 @@ TEST_P(NormalPathTest, CheckOutput) auto const handler = AnyHandler{GatewayBalancesHandler{backend_}}; runSpawn([&](auto yield) { auto const output = handler.process( - json::parse( + boost::json::parse( fmt::format( R"JSON({{ "account": "{}", {} }})JSON", - kACCOUNT, + kAccount, bundle.hotwallet ) ), Context{yield} ); ASSERT_TRUE(output); - EXPECT_EQ(output.result.value(), json::parse(bundle.expectedJson)); + EXPECT_EQ(output.result.value(), boost::json::parse(bundle.expectedJson)); }); } @@ -427,50 +427,49 @@ static auto generateNormalPathTestBundles() { auto frozenState = createRippleStateLedgerObject( - "JPY", kISSUER, -50, kACCOUNT, 10, kACCOUNT3, 20, kTXN_ID, 123 + "JPY", kIssuer, -50, kAccount, 10, kAccount3, 20, kTxnId, 123 ); - frozenState.setFieldU32(ripple::sfFlags, ripple::lsfLowFreeze); + frozenState.setFieldU32(xrpl::sfFlags, xrpl::lsfLowFreeze); - auto overflowState = createRippleStateLedgerObject( - "JPY", kISSUER, 50, kACCOUNT, 10, kACCOUNT3, 20, kTXN_ID, 123 - ); + auto overflowState = + createRippleStateLedgerObject("JPY", kIssuer, 50, kAccount, 10, kAccount3, 20, kTxnId, 123); int64_t const min64 = -9922966390934554; overflowState.setFieldAmount( - ripple::sfBalance, ripple::STAmount(getIssue("JPY", kISSUER), min64, 80) + xrpl::sfBalance, xrpl::STAmount(getIssue("JPY", kIssuer), min64, 80) ); return std::vector{ NormalTestBundle{ .testName = "AllBranches", .mockedDir = createOwnerDirLedgerObject( - {ripple::uint256{kINDEX2}, - ripple::uint256{kINDEX2}, - ripple::uint256{kINDEX2}, - ripple::uint256{kINDEX2}, - ripple::uint256{kINDEX2}, - ripple::uint256{kINDEX2}}, - kINDEX1 + {xrpl::uint256{kIndex2}, + xrpl::uint256{kIndex2}, + xrpl::uint256{kIndex2}, + xrpl::uint256{kIndex2}, + xrpl::uint256{kIndex2}, + xrpl::uint256{kIndex2}}, + kIndex1 ), .mockedObjects = std::vector{ // hotwallet createRippleStateLedgerObject( - "USD", kISSUER, -10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kIssuer, -10, kAccount, 100, kAccount2, 200, kTxnId, 123 ), // hotwallet createRippleStateLedgerObject( - "CNY", kISSUER, -20, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "CNY", kIssuer, -20, kAccount, 100, kAccount2, 200, kTxnId, 123 ), // positive balance -> asset createRippleStateLedgerObject( - "EUR", kISSUER, 30, kACCOUNT, 100, kACCOUNT3, 200, kTXN_ID, 123 + "EUR", kIssuer, 30, kAccount, 100, kAccount3, 200, kTxnId, 123 ), // positive balance -> asset createRippleStateLedgerObject( - "JPY", kISSUER, 40, kACCOUNT, 100, kACCOUNT3, 200, kTXN_ID, 123 + "JPY", kIssuer, 40, kAccount, 100, kAccount3, 200, kTxnId, 123 ), // obligation createRippleStateLedgerObject( - "JPY", kISSUER, -50, kACCOUNT, 10, kACCOUNT3, 20, kTXN_ID, 123 + "JPY", kIssuer, -50, kAccount, 10, kAccount3, 20, kTxnId, 123 ), frozenState @@ -516,18 +515,18 @@ generateNormalPathTestBundles() "ledger_index": 300, "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652" }})JSON", - kACCOUNT2, - kACCOUNT3, - kACCOUNT3, - kACCOUNT + kAccount2, + kAccount3, + kAccount3, + kAccount ), - .hotwallet = fmt::format(R"("hotwallet": "{}")", kACCOUNT2) + .hotwallet = fmt::format(R"("hotwallet": "{}")", kAccount2) }, NormalTestBundle{ .testName = "NoHotwallet", - .mockedDir = createOwnerDirLedgerObject({ripple::uint256{kINDEX2}}, kINDEX1), + .mockedDir = createOwnerDirLedgerObject({xrpl::uint256{kIndex2}}, kIndex1), .mockedObjects = std::vector{createRippleStateLedgerObject( - "JPY", kISSUER, -50, kACCOUNT, 10, kACCOUNT3, 20, kTXN_ID, 123 + "JPY", kIssuer, -50, kAccount, 10, kAccount3, 20, kTxnId, 123 )}, .expectedJson = fmt::format( R"JSON({{ @@ -538,14 +537,14 @@ generateNormalPathTestBundles() "ledger_index": 300, "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652" }})JSON", - kACCOUNT + kAccount ), .hotwallet = R"("ledger_index" : "validated")" }, NormalTestBundle{ .testName = "ObligationOverflow", .mockedDir = createOwnerDirLedgerObject( - {ripple::uint256{kINDEX2}, ripple::uint256{kINDEX2}}, kINDEX1 + {xrpl::uint256{kIndex2}, xrpl::uint256{kIndex2}}, kIndex1 ), .mockedObjects = std::vector{overflowState, overflowState}, .expectedJson = fmt::format( @@ -557,34 +556,34 @@ generateNormalPathTestBundles() "ledger_index": 300, "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652" }})JSON", - kACCOUNT + kAccount ), .hotwallet = R"("ledger_index" : "validated")" }, NormalTestBundle{ .testName = "HighID", .mockedDir = createOwnerDirLedgerObject( - {ripple::uint256{kINDEX2}, - ripple::uint256{kINDEX2}, - ripple::uint256{kINDEX2}, - ripple::uint256{kINDEX2}}, - kINDEX1 + {xrpl::uint256{kIndex2}, + xrpl::uint256{kIndex2}, + xrpl::uint256{kIndex2}, + xrpl::uint256{kIndex2}}, + kIndex1 ), .mockedObjects = std::vector{ // hotwallet createRippleStateLedgerObject( - "USD", kISSUER, 10, kACCOUNT2, 100, kACCOUNT, 200, kTXN_ID, 123 + "USD", kIssuer, 10, kAccount2, 100, kAccount, 200, kTxnId, 123 ), // hotwallet createRippleStateLedgerObject( - "CNY", kISSUER, 20, kACCOUNT2, 100, kACCOUNT, 200, kTXN_ID, 123 + "CNY", kIssuer, 20, kAccount2, 100, kAccount, 200, kTxnId, 123 ), createRippleStateLedgerObject( - "EUR", kISSUER, 30, kACCOUNT3, 100, kACCOUNT, 200, kTXN_ID, 123 + "EUR", kIssuer, 30, kAccount3, 100, kAccount, 200, kTxnId, 123 ), createRippleStateLedgerObject( - "JPY", kISSUER, -50, kACCOUNT3, 10, kACCOUNT, 20, kTXN_ID, 123 + "JPY", kIssuer, -50, kAccount3, 10, kAccount, 20, kTxnId, 123 ) }, .expectedJson = fmt::format( @@ -616,28 +615,27 @@ generateNormalPathTestBundles() "ledger_index": 300, "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652" }})JSON", - kACCOUNT2, - kACCOUNT3, - kACCOUNT + kAccount2, + kAccount3, + kAccount ), - .hotwallet = fmt::format(R"("hotwallet": "{}")", kACCOUNT2) + .hotwallet = fmt::format(R"("hotwallet": "{}")", kAccount2) }, NormalTestBundle{ .testName = "HotWalletArray", .mockedDir = createOwnerDirLedgerObject( - {ripple::uint256{kINDEX2}, ripple::uint256{kINDEX2}, ripple::uint256{kINDEX2}}, - kINDEX1 + {xrpl::uint256{kIndex2}, xrpl::uint256{kIndex2}, xrpl::uint256{kIndex2}}, kIndex1 ), .mockedObjects = std::vector{ createRippleStateLedgerObject( - "USD", kISSUER, -10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kIssuer, -10, kAccount, 100, kAccount2, 200, kTxnId, 123 ), createRippleStateLedgerObject( - "CNY", kISSUER, -20, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "CNY", kIssuer, -20, kAccount, 100, kAccount2, 200, kTxnId, 123 ), createRippleStateLedgerObject( - "EUR", kISSUER, -30, kACCOUNT, 100, kACCOUNT3, 200, kTXN_ID, 123 + "EUR", kIssuer, -30, kAccount, 100, kAccount3, 200, kTxnId, 123 ) }, @@ -665,11 +663,11 @@ generateNormalPathTestBundles() "ledger_index": 300, "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652" }})JSON", - kACCOUNT3, - kACCOUNT2, - kACCOUNT + kAccount3, + kAccount2, + kAccount ), - .hotwallet = fmt::format(R"("hotwallet": ["{}", "{}"])", kACCOUNT2, kACCOUNT3) + .hotwallet = fmt::format(R"("hotwallet": ["{}", "{}"])", kAccount2, kAccount3) }, }; } @@ -678,13 +676,13 @@ INSTANTIATE_TEST_SUITE_P( RPCGatewayBalancesHandler, NormalPathTest, testing::ValuesIn(generateNormalPathTestBundles()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); struct EscrowTestBundle { std::string testName; - ripple::STObject mockedDir; - std::vector mockedObjects; + xrpl::STObject mockedDir; + std::vector mockedObjects; std::string expectedJson; }; @@ -696,14 +694,14 @@ TEST_P(EscrowTest, CheckEscrowOutput) auto const& bundle = GetParam(); auto const seq = 300; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, seq); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, seq); EXPECT_CALL(*backend_, fetchLedgerBySequence(seq, _)).WillOnce(Return(ledgerHeader)); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; EXPECT_CALL(*backend_, doFetchLedgerObject(accountKk, seq, _)) .WillOnce(Return(Blob{'f', 'a', 'k', 'e'})); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; EXPECT_CALL(*backend_, doFetchLedgerObject(ownerDirKk, seq, _)) .WillOnce(Return(bundle.mockedDir.getSerializer().peekData())); @@ -716,18 +714,18 @@ TEST_P(EscrowTest, CheckEscrowOutput) auto const handler = AnyHandler{GatewayBalancesHandler{backend_}}; runSpawn([&](auto yield) { auto const output = handler.process( - json::parse( + boost::json::parse( fmt::format( R"JSON({{ "account": "{}" }})JSON", - kACCOUNT + kAccount ) ), Context{yield} ); ASSERT_TRUE(output); - EXPECT_EQ(output.result.value(), json::parse(bundle.expectedJson)); + EXPECT_EQ(output.result.value(), boost::json::parse(bundle.expectedJson)); }); } @@ -735,21 +733,21 @@ static auto generateEscrowTestBundles() { // Escrow with 100 XRP - auto escrow1 = createEscrowLedgerObject(kACCOUNT, kACCOUNT2); - escrow1.setFieldAmount(ripple::sfAmount, ripple::STAmount(100, false)); + auto escrow1 = createEscrowLedgerObject(kAccount, kAccount2); + escrow1.setFieldAmount(xrpl::sfAmount, xrpl::STAmount(100, false)); // Escrow with 200 XRP - auto escrow2 = createEscrowLedgerObject(kACCOUNT, kACCOUNT3); - escrow2.setFieldAmount(ripple::sfAmount, ripple::STAmount(200, false)); + auto escrow2 = createEscrowLedgerObject(kAccount, kAccount3); + escrow2.setFieldAmount(xrpl::sfAmount, xrpl::STAmount(200, false)); // Escrow with a non-XRP currency - auto escrow3 = createEscrowLedgerObject(kACCOUNT, kACCOUNT2); - escrow3.setFieldAmount(ripple::sfAmount, ripple::STAmount(getIssue("USD", kISSUER), 50)); + auto escrow3 = createEscrowLedgerObject(kAccount, kAccount2); + escrow3.setFieldAmount(xrpl::sfAmount, xrpl::STAmount(getIssue("USD", kIssuer), 50)); return std::vector{ EscrowTestBundle{ .testName = "SingleEscrowXRP", - .mockedDir = createOwnerDirLedgerObject({ripple::uint256{kINDEX2}}, kINDEX1), + .mockedDir = createOwnerDirLedgerObject({xrpl::uint256{kIndex2}}, kIndex1), .mockedObjects = std::vector{escrow1}, .expectedJson = fmt::format( R"JSON({{ @@ -758,14 +756,14 @@ generateEscrowTestBundles() "ledger_index": 300, "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) }, EscrowTestBundle{ .testName = "MultipleEscrowXRP", .mockedDir = createOwnerDirLedgerObject( - {ripple::uint256{kINDEX2}, ripple::uint256{kINDEX2}}, kINDEX1 + {xrpl::uint256{kIndex2}, xrpl::uint256{kIndex2}}, kIndex1 ), .mockedObjects = std::vector{escrow1, escrow2}, .expectedJson = fmt::format( @@ -775,13 +773,13 @@ generateEscrowTestBundles() "ledger_index": 300, "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) }, EscrowTestBundle{ .testName = "EscrowNonXRP", - .mockedDir = createOwnerDirLedgerObject({ripple::uint256{kINDEX2}}, kINDEX1), + .mockedDir = createOwnerDirLedgerObject({xrpl::uint256{kIndex2}}, kIndex1), .mockedObjects = std::vector{escrow3}, .expectedJson = fmt::format( R"JSON({{ @@ -790,15 +788,14 @@ generateEscrowTestBundles() "ledger_index": 300, "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) }, EscrowTestBundle{ .testName = "EscrowMixedCurrencies", .mockedDir = createOwnerDirLedgerObject( - {ripple::uint256{kINDEX2}, ripple::uint256{kINDEX2}, ripple::uint256{kINDEX2}}, - kINDEX1 + {xrpl::uint256{kIndex2}, xrpl::uint256{kIndex2}, xrpl::uint256{kIndex2}}, kIndex1 ), .mockedObjects = std::vector{escrow1, escrow2, escrow3}, .expectedJson = fmt::format( @@ -808,8 +805,8 @@ generateEscrowTestBundles() "ledger_index": 300, "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) } }; @@ -819,5 +816,5 @@ INSTANTIATE_TEST_SUITE_P( RPCGatewayBalancesHandler, EscrowTest, testing::ValuesIn(generateEscrowTestBundles()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); diff --git a/tests/unit/rpc/handlers/GetAggregatePriceTests.cpp b/tests/unit/rpc/handlers/GetAggregatePriceTests.cpp index e0e12e642..4a0855082 100644 --- a/tests/unit/rpc/handlers/GetAggregatePriceTests.cpp +++ b/tests/unit/rpc/handlers/GetAggregatePriceTests.cpp @@ -24,18 +24,17 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kRANGE_MIN = 10; -constexpr auto kRANGE_MAX = 30; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kTX1 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kTX2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; -constexpr auto kINDEX = "13F1A95D7AAB7108D5CE7EEAF504B2894B8C674E6D68499076441C4837282BF8"; +constexpr auto kRangeMin = 10; +constexpr auto kRangeMax = 30; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kTx1 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kTx2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; +constexpr auto kIndex = "13F1A95D7AAB7108D5CE7EEAF504B2894B8C674E6D68499076441C4837282BF8"; void mockLedgerObject( @@ -53,17 +52,17 @@ mockLedgerObject( "70726F7669646572", 64u, time, - ripple::Blob(8, 'a'), - ripple::Blob(8, 'a'), - kRANGE_MAX - 4, - ripple::uint256{tx}, - createPriceDataSeries({createOraclePriceData( - price, ripple::to_currency("USD"), ripple::to_currency("XRP"), scale - )}) + xrpl::Blob(8, 'a'), + xrpl::Blob(8, 'a'), + kRangeMax - 4, + xrpl::uint256{tx}, + createPriceDataSeries( + {createOraclePriceData(price, xrpl::toCurrency("USD"), xrpl::toCurrency("XRP"), scale)} + ) ); - auto const oracleIndex = ripple::keylet::oracle(getAccountIdWithString(account), docId).key; - EXPECT_CALL(backend, doFetchLedgerObject(oracleIndex, kRANGE_MAX, _)) + auto const oracleIndex = xrpl::keylet::oracle(getAccountIdWithString(account), docId).key; + EXPECT_CALL(backend, doFetchLedgerObject(oracleIndex, kRangeMax, _)) .WillOnce(Return(oracleObject.getSerializer().peekData())); } }; // namespace @@ -72,7 +71,7 @@ class RPCGetAggregatePriceHandlerTest : public HandlerBaseTest { protected: RPCGetAggregatePriceHandlerTest() { - backend_->setRange(kRANGE_MIN, kRANGE_MAX); + backend_->setRange(kRangeMin, kRangeMax); } }; @@ -378,7 +377,7 @@ INSTANTIATE_TEST_CASE_P( RPCGetAggregatePriceGroup1, GetAggregatePriceParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(GetAggregatePriceParameterTest, InvalidParams) @@ -386,7 +385,7 @@ TEST_P(GetAggregatePriceParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -397,7 +396,7 @@ TEST_P(GetAggregatePriceParameterTest, InvalidParams) TEST_F(RPCGetAggregatePriceHandlerTest, OverOraclesMax) { - auto req = json::parse( + auto req = boost::json::parse( R"JSON({ "base_asset": "USD", "quote_asset": "XRP", @@ -408,7 +407,7 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OverOraclesMax) for (auto i = 0; i < maxOracles + 1; ++i) { req.at("oracles").as_array().push_back( - json::object{ + boost::json::object{ {"account", "rGh1VZCRBJY6rJiaFpD4LZtyHiuCkC8aeD"}, {"oracle_document_id", 2} } ); @@ -425,9 +424,9 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OverOraclesMax) TEST_F(RPCGetAggregatePriceHandlerTest, LedgerNotFound) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillOnce(Return(std::nullopt)); - constexpr auto kDOCUMENT_ID = 1; - auto const req = json::parse( + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillOnce(Return(std::nullopt)); + constexpr auto kDocumentId = 1; + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "USD", @@ -439,8 +438,8 @@ TEST_F(RPCGetAggregatePriceHandlerTest, LedgerNotFound) }} ] }})JSON", - kACCOUNT, - kDOCUMENT_ID + kAccount, + kDocumentId ) ); auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; @@ -455,14 +454,14 @@ TEST_F(RPCGetAggregatePriceHandlerTest, LedgerNotFound) TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntrySinglePriceData) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - constexpr auto kDOCUMENT_ID = 1; - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID, kTX1, 1e3, 2); // 10 + constexpr auto kDocumentId = 1; + mockLedgerObject(*backend_, kAccount, kDocumentId, kTx1, 1e3, 2); // 10 auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "USD", @@ -474,12 +473,12 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntrySinglePriceData) }} ] }})JSON", - kACCOUNT, - kDOCUMENT_ID + kAccount, + kDocumentId ) ); - auto const expected = json::parse( + auto const expected = boost::json::parse( fmt::format( R"JSON({{ "entire_set": {{ @@ -493,8 +492,8 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntrySinglePriceData) "ledger_hash": "{}", "validated": true }})JSON", - kRANGE_MAX, - kLEDGER_HASH + kRangeMax, + kLedgerHash ) ); runSpawn([&](auto yield) { @@ -506,14 +505,14 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntrySinglePriceData) TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryStrOracleDocumentId) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - constexpr auto kDOCUMENT_ID = 1; - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID, kTX1, 1e3, 2); // 10 + constexpr auto kDocumentId = 1; + mockLedgerObject(*backend_, kAccount, kDocumentId, kTx1, 1e3, 2); // 10 auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "USD", @@ -525,12 +524,12 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryStrOracleDocumentId) }} ] }})JSON", - kACCOUNT, - kDOCUMENT_ID + kAccount, + kDocumentId ) ); - auto const expected = json::parse( + auto const expected = boost::json::parse( fmt::format( R"JSON({{ "entire_set": {{ @@ -544,8 +543,8 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryStrOracleDocumentId) "ledger_hash": "{}", "validated": true }})JSON", - kRANGE_MAX, - kLEDGER_HASH + kRangeMax, + kLedgerHash ) ); runSpawn([&](auto yield) { @@ -557,14 +556,14 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryStrOracleDocumentId) TEST_F(RPCGetAggregatePriceHandlerTest, PreviousTxNotFound) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - constexpr auto kDOCUMENT_ID = 1; - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID, kTX1, 1e3, 2); // 10 + constexpr auto kDocumentId = 1; + mockLedgerObject(*backend_, kAccount, kDocumentId, kTx1, 1e3, 2); // 10 auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "JPY", @@ -576,12 +575,12 @@ TEST_F(RPCGetAggregatePriceHandlerTest, PreviousTxNotFound) }} ] }})JSON", - kACCOUNT, - kDOCUMENT_ID + kAccount, + kDocumentId ) ); - auto const expected = json::parse( + auto const expected = boost::json::parse( fmt::format( R"JSON({{ "entire_set": {{ @@ -595,8 +594,8 @@ TEST_F(RPCGetAggregatePriceHandlerTest, PreviousTxNotFound) "ledger_hash": "{}", "validated": true }})JSON", - kRANGE_MAX, - kLEDGER_HASH + kRangeMax, + kLedgerHash ) ); runSpawn([&](auto yield) { @@ -610,29 +609,29 @@ TEST_F(RPCGetAggregatePriceHandlerTest, PreviousTxNotFound) TEST_F(RPCGetAggregatePriceHandlerTest, NewLedgerObjectHasNoPricePair) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - constexpr auto kDOCUMENT_ID = 1; - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID, kTX1, 1e3, 2); // 10 + constexpr auto kDocumentId = 1; + mockLedgerObject(*backend_, kAccount, kDocumentId, kTx1, 1e3, 2); // 10 - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256(kTX1), _)) + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256(kTx1), _)) .WillRepeatedly(Return(createOracleSetTxWithMetadata( - kACCOUNT, - kRANGE_MAX, + kAccount, + kRangeMax, 123, 1, 4321u, - createPriceDataSeries({createOraclePriceData( - 1e3, ripple::to_currency("EUR"), ripple::to_currency("XRP"), 2 - )}), - kINDEX, + createPriceDataSeries( + {createOraclePriceData(1e3, xrpl::toCurrency("EUR"), xrpl::toCurrency("XRP"), 2)} + ), + kIndex, true, - kTX2 + kTx2 ))); auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "JPY", @@ -644,12 +643,12 @@ TEST_F(RPCGetAggregatePriceHandlerTest, NewLedgerObjectHasNoPricePair) }} ] }})JSON", - kACCOUNT, - kDOCUMENT_ID + kAccount, + kDocumentId ) ); - auto const expected = json::parse( + auto const expected = boost::json::parse( fmt::format( R"JSON({{ "entire_set": {{ @@ -663,8 +662,8 @@ TEST_F(RPCGetAggregatePriceHandlerTest, NewLedgerObjectHasNoPricePair) "ledger_hash": "{}", "validated": true }})JSON", - kRANGE_MAX, - kLEDGER_HASH + kRangeMax, + kLedgerHash ) ); runSpawn([&](auto yield) { @@ -679,18 +678,18 @@ TEST_F(RPCGetAggregatePriceHandlerTest, NewLedgerObjectHasNoPricePair) // median is the middle value of a set of numbers when there are odd number of price TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryMultipleOraclesOdd) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - constexpr auto kDOCUMENT_ID1 = 1; - constexpr auto kDOCUMENT_ID2 = 2; - constexpr auto kDOCUMENT_ID3 = 3; - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID1, kTX1, 1e3, 2); // 10 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID2, kTX1, 2e3, 2); // 20 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID3, kTX1, 3e3, 1); // 300 + constexpr auto kDocumentID1 = 1; + constexpr auto kDocumentID2 = 2; + constexpr auto kDocumentID3 = 3; + mockLedgerObject(*backend_, kAccount, kDocumentID1, kTx1, 1e3, 2); // 10 + mockLedgerObject(*backend_, kAccount, kDocumentID2, kTx1, 2e3, 2); // 20 + mockLedgerObject(*backend_, kAccount, kDocumentID3, kTx1, 3e3, 1); // 300 auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "USD", @@ -710,16 +709,16 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryMultipleOraclesOdd) }} ] }})JSON", - kACCOUNT, - kDOCUMENT_ID1, - kACCOUNT, - kDOCUMENT_ID2, - kACCOUNT, - kDOCUMENT_ID3 + kAccount, + kDocumentID1, + kAccount, + kDocumentID2, + kAccount, + kDocumentID3 ) ); - auto const expected = json::parse( + auto const expected = boost::json::parse( fmt::format( R"JSON({{ "entire_set": {{ @@ -733,8 +732,8 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryMultipleOraclesOdd) "ledger_hash": "{}", "validated": true }})JSON", - kRANGE_MAX, - kLEDGER_HASH + kRangeMax, + kLedgerHash ) ); runSpawn([&](auto yield) { @@ -747,20 +746,20 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryMultipleOraclesOdd) // median is the middle value of a set of numbers when there are odd number of price TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryMultipleOraclesEven) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - constexpr auto kDOCUMENT_ID1 = 1; - constexpr auto kDOCUMENT_ID2 = 2; - constexpr auto kDOCUMENT_ID3 = 3; - constexpr auto kDOCUMENT_ID4 = 4; - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID1, kTX1, 1e3, 2); // 10 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID2, kTX1, 2e3, 2); // 20 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID4, kTX1, 4e2, 1); // 40 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID3, kTX1, 3e3, 1); // 300 + constexpr auto kDocumentID1 = 1; + constexpr auto kDocumentID2 = 2; + constexpr auto kDocumentID3 = 3; + constexpr auto kDocumentID4 = 4; + mockLedgerObject(*backend_, kAccount, kDocumentID1, kTx1, 1e3, 2); // 10 + mockLedgerObject(*backend_, kAccount, kDocumentID2, kTx1, 2e3, 2); // 20 + mockLedgerObject(*backend_, kAccount, kDocumentID4, kTx1, 4e2, 1); // 40 + mockLedgerObject(*backend_, kAccount, kDocumentID3, kTx1, 3e3, 1); // 300 auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "USD", @@ -784,18 +783,18 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryMultipleOraclesEven) }} ] }})JSON", - kACCOUNT, - kDOCUMENT_ID1, - kACCOUNT, - kDOCUMENT_ID2, - kACCOUNT, - kDOCUMENT_ID3, - kACCOUNT, - kDOCUMENT_ID4 + kAccount, + kDocumentID1, + kAccount, + kDocumentID2, + kAccount, + kDocumentID3, + kAccount, + kDocumentID4 ) ); - auto const expected = json::parse( + auto const expected = boost::json::parse( fmt::format( R"JSON({{ "entire_set": {{ @@ -809,8 +808,8 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryMultipleOraclesEven) "ledger_hash": "{}", "validated": true }})JSON", - kRANGE_MAX, - kLEDGER_HASH + kRangeMax, + kLedgerHash ) ); runSpawn([&](auto yield) { @@ -822,22 +821,22 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryMultipleOraclesEven) TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryTrim) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); // prepare 4 prices, when trim is 25, the lowest(documentId1) and highest(documentId3) price // will be removed - constexpr auto kDOCUMENT_ID1 = 1; - constexpr auto kDOCUMENT_ID2 = 2; - constexpr auto kDOCUMENT_ID3 = 3; - constexpr auto kDOCUMENT_ID4 = 4; - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID1, kTX1, 1e3, 2); // 10 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID2, kTX1, 2e3, 2); // 20 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID4, kTX1, 4e2, 1); // 40 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID3, kTX1, 3e3, 1); // 300 + constexpr auto kDocumentID1 = 1; + constexpr auto kDocumentID2 = 2; + constexpr auto kDocumentID3 = 3; + constexpr auto kDocumentID4 = 4; + mockLedgerObject(*backend_, kAccount, kDocumentID1, kTx1, 1e3, 2); // 10 + mockLedgerObject(*backend_, kAccount, kDocumentID2, kTx1, 2e3, 2); // 20 + mockLedgerObject(*backend_, kAccount, kDocumentID4, kTx1, 4e2, 1); // 40 + mockLedgerObject(*backend_, kAccount, kDocumentID3, kTx1, 3e3, 1); // 300 auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "USD", @@ -863,18 +862,18 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryTrim) ] }})JSON", 25, - kACCOUNT, - kDOCUMENT_ID1, - kACCOUNT, - kDOCUMENT_ID2, - kACCOUNT, - kDOCUMENT_ID3, - kACCOUNT, - kDOCUMENT_ID4 + kAccount, + kDocumentID1, + kAccount, + kDocumentID2, + kAccount, + kDocumentID3, + kAccount, + kDocumentID4 ) ); - auto const expected = json::parse( + auto const expected = boost::json::parse( fmt::format( R"JSON({{ "entire_set": {{ @@ -893,8 +892,8 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryTrim) "ledger_hash": "{}", "validated": true }})JSON", - kRANGE_MAX, - kLEDGER_HASH + kRangeMax, + kLedgerHash ) ); runSpawn([&](auto yield) { @@ -906,17 +905,17 @@ TEST_F(RPCGetAggregatePriceHandlerTest, OracleLedgerEntryTrim) TEST_F(RPCGetAggregatePriceHandlerTest, NoOracleEntryFound) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - constexpr auto kDOCUMENT_ID = 1; + constexpr auto kDocumentId = 1; auto const oracleIndex = - ripple::keylet::oracle(getAccountIdWithString(kACCOUNT), kDOCUMENT_ID).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(oracleIndex, kRANGE_MAX, _)) + xrpl::keylet::oracle(getAccountIdWithString(kAccount), kDocumentId).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(oracleIndex, kRangeMax, _)) .WillOnce(Return(std::nullopt)); auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "USD", @@ -928,8 +927,8 @@ TEST_F(RPCGetAggregatePriceHandlerTest, NoOracleEntryFound) }} ] }})JSON", - kACCOUNT, - kDOCUMENT_ID + kAccount, + kDocumentId ) ); @@ -944,14 +943,14 @@ TEST_F(RPCGetAggregatePriceHandlerTest, NoOracleEntryFound) TEST_F(RPCGetAggregatePriceHandlerTest, NoMatchAssetPair) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - constexpr auto kDOCUMENT_ID = 1; - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID, kTX1, 1e3, 2); // 10 + constexpr auto kDocumentId = 1; + mockLedgerObject(*backend_, kAccount, kDocumentId, kTx1, 1e3, 2); // 10 auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "JPY", @@ -963,8 +962,8 @@ TEST_F(RPCGetAggregatePriceHandlerTest, NoMatchAssetPair) }} ] }})JSON", - kACCOUNT, - kDOCUMENT_ID + kAccount, + kDocumentId ) ); @@ -979,24 +978,24 @@ TEST_F(RPCGetAggregatePriceHandlerTest, NoMatchAssetPair) TEST_F(RPCGetAggregatePriceHandlerTest, TimeThresholdIsZero) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - constexpr auto kDOCUMENT_ID1 = 1; - constexpr auto kDOCUMENT_ID2 = 2; - constexpr auto kDOCUMENT_ID3 = 3; - constexpr auto kDOCUMENT_ID4 = 4; - constexpr auto kTIMESTAMP1 = 1711461384u; - constexpr auto kTIMESTAMP2 = 1711461383u; - constexpr auto kTIMESTAMP3 = 1711461382u; - constexpr auto kTIMESTAMP4 = 1711461381u; - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID1, kTX1, 1e3, 2, kTIMESTAMP1); // 10 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID2, kTX1, 2e3, 2, kTIMESTAMP2); // 20 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID4, kTX1, 4e2, 1, kTIMESTAMP3); // 40 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID3, kTX1, 3e3, 1, kTIMESTAMP4); // 300 + constexpr auto kDocumentID1 = 1; + constexpr auto kDocumentID2 = 2; + constexpr auto kDocumentID3 = 3; + constexpr auto kDocumentID4 = 4; + constexpr auto kTimestamp1 = 1711461384u; + constexpr auto kTimestamp2 = 1711461383u; + constexpr auto kTimestamp3 = 1711461382u; + constexpr auto kTimestamp4 = 1711461381u; + mockLedgerObject(*backend_, kAccount, kDocumentID1, kTx1, 1e3, 2, kTimestamp1); // 10 + mockLedgerObject(*backend_, kAccount, kDocumentID2, kTx1, 2e3, 2, kTimestamp2); // 20 + mockLedgerObject(*backend_, kAccount, kDocumentID4, kTx1, 4e2, 1, kTimestamp3); // 40 + mockLedgerObject(*backend_, kAccount, kDocumentID3, kTx1, 3e3, 1, kTimestamp4); // 300 auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "USD", @@ -1022,18 +1021,18 @@ TEST_F(RPCGetAggregatePriceHandlerTest, TimeThresholdIsZero) ] }})JSON", 0, - kACCOUNT, - kDOCUMENT_ID1, - kACCOUNT, - kDOCUMENT_ID2, - kACCOUNT, - kDOCUMENT_ID3, - kACCOUNT, - kDOCUMENT_ID4 + kAccount, + kDocumentID1, + kAccount, + kDocumentID2, + kAccount, + kDocumentID3, + kAccount, + kDocumentID4 ) ); - auto const expected = json::parse( + auto const expected = boost::json::parse( fmt::format( R"JSON({{ "entire_set": {{ @@ -1047,9 +1046,9 @@ TEST_F(RPCGetAggregatePriceHandlerTest, TimeThresholdIsZero) "ledger_hash": "{}", "validated": true }})JSON", - kTIMESTAMP1, - kRANGE_MAX, - kLEDGER_HASH + kTimestamp1, + kRangeMax, + kLedgerHash ) ); runSpawn([&](auto yield) { @@ -1061,24 +1060,24 @@ TEST_F(RPCGetAggregatePriceHandlerTest, TimeThresholdIsZero) TEST_F(RPCGetAggregatePriceHandlerTest, ValidTimeThreshold) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - constexpr auto kDOCUMENT_ID1 = 1; - constexpr auto kDOCUMENT_ID2 = 2; - constexpr auto kDOCUMENT_ID3 = 3; - constexpr auto kDOCUMENT_ID4 = 4; - constexpr auto kTIMESTAMP1 = 1711461384u; - constexpr auto kTIMESTAMP2 = 1711461383u; - constexpr auto kTIMESTAMP3 = 1711461382u; - constexpr auto kTIMESTAMP4 = 1711461381u; - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID1, kTX1, 1e3, 2, kTIMESTAMP1); // 10 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID2, kTX1, 2e3, 2, kTIMESTAMP2); // 20 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID4, kTX1, 4e2, 1, kTIMESTAMP3); // 40 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID3, kTX1, 3e3, 1, kTIMESTAMP4); // 300 + constexpr auto kDocumentID1 = 1; + constexpr auto kDocumentID2 = 2; + constexpr auto kDocumentID3 = 3; + constexpr auto kDocumentID4 = 4; + constexpr auto kTimestamp1 = 1711461384u; + constexpr auto kTimestamp2 = 1711461383u; + constexpr auto kTimestamp3 = 1711461382u; + constexpr auto kTimestamp4 = 1711461381u; + mockLedgerObject(*backend_, kAccount, kDocumentID1, kTx1, 1e3, 2, kTimestamp1); // 10 + mockLedgerObject(*backend_, kAccount, kDocumentID2, kTx1, 2e3, 2, kTimestamp2); // 20 + mockLedgerObject(*backend_, kAccount, kDocumentID4, kTx1, 4e2, 1, kTimestamp3); // 40 + mockLedgerObject(*backend_, kAccount, kDocumentID3, kTx1, 3e3, 1, kTimestamp4); // 300 auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "USD", @@ -1103,19 +1102,19 @@ TEST_F(RPCGetAggregatePriceHandlerTest, ValidTimeThreshold) }} ] }})JSON", - kTIMESTAMP1 - kTIMESTAMP2, - kACCOUNT, - kDOCUMENT_ID1, - kACCOUNT, - kDOCUMENT_ID2, - kACCOUNT, - kDOCUMENT_ID3, - kACCOUNT, - kDOCUMENT_ID4 + kTimestamp1 - kTimestamp2, + kAccount, + kDocumentID1, + kAccount, + kDocumentID2, + kAccount, + kDocumentID3, + kAccount, + kDocumentID4 ) ); - auto const expected = json::parse( + auto const expected = boost::json::parse( fmt::format( R"JSON({{ "entire_set": {{ @@ -1129,9 +1128,9 @@ TEST_F(RPCGetAggregatePriceHandlerTest, ValidTimeThreshold) "ledger_hash": "{}", "validated": true }})JSON", - kTIMESTAMP1, - kRANGE_MAX, - kLEDGER_HASH + kTimestamp1, + kRangeMax, + kLedgerHash ) ); runSpawn([&](auto yield) { @@ -1143,24 +1142,24 @@ TEST_F(RPCGetAggregatePriceHandlerTest, ValidTimeThreshold) TEST_F(RPCGetAggregatePriceHandlerTest, TimeThresholdTooLong) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - constexpr auto kDOCUMENT_ID1 = 1; - constexpr auto kDOCUMENT_ID2 = 2; - constexpr auto kDOCUMENT_ID3 = 3; - constexpr auto kDOCUMENT_ID4 = 4; - constexpr auto kTIMESTAMP1 = 1711461384u; - constexpr auto kTIMESTAMP2 = 1711461383u; - constexpr auto kTIMESTAMP3 = 1711461382u; - constexpr auto kTIMESTAMP4 = 1711461381u; - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID1, kTX1, 1e3, 2, kTIMESTAMP1); // 10 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID2, kTX1, 2e3, 2, kTIMESTAMP2); // 20 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID4, kTX1, 4e2, 1, kTIMESTAMP3); // 40 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID3, kTX1, 3e3, 1, kTIMESTAMP4); // 300 + constexpr auto kDocumentID1 = 1; + constexpr auto kDocumentID2 = 2; + constexpr auto kDocumentID3 = 3; + constexpr auto kDocumentID4 = 4; + constexpr auto kTimestamp1 = 1711461384u; + constexpr auto kTimestamp2 = 1711461383u; + constexpr auto kTimestamp3 = 1711461382u; + constexpr auto kTimestamp4 = 1711461381u; + mockLedgerObject(*backend_, kAccount, kDocumentID1, kTx1, 1e3, 2, kTimestamp1); // 10 + mockLedgerObject(*backend_, kAccount, kDocumentID2, kTx1, 2e3, 2, kTimestamp2); // 20 + mockLedgerObject(*backend_, kAccount, kDocumentID4, kTx1, 4e2, 1, kTimestamp3); // 40 + mockLedgerObject(*backend_, kAccount, kDocumentID3, kTx1, 3e3, 1, kTimestamp4); // 300 auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "USD", @@ -1185,19 +1184,19 @@ TEST_F(RPCGetAggregatePriceHandlerTest, TimeThresholdTooLong) }} ] }})JSON", - kTIMESTAMP1 + 1, - kACCOUNT, - kDOCUMENT_ID1, - kACCOUNT, - kDOCUMENT_ID2, - kACCOUNT, - kDOCUMENT_ID3, - kACCOUNT, - kDOCUMENT_ID4 + kTimestamp1 + 1, + kAccount, + kDocumentID1, + kAccount, + kDocumentID2, + kAccount, + kDocumentID3, + kAccount, + kDocumentID4 ) ); - auto const expected = json::parse( + auto const expected = boost::json::parse( fmt::format( R"JSON({{ "entire_set": {{ @@ -1211,8 +1210,8 @@ TEST_F(RPCGetAggregatePriceHandlerTest, TimeThresholdTooLong) "ledger_hash": "{}", "validated": true }})JSON", - kRANGE_MAX, - kLEDGER_HASH + kRangeMax, + kLedgerHash ) ); runSpawn([&](auto yield) { @@ -1224,24 +1223,24 @@ TEST_F(RPCGetAggregatePriceHandlerTest, TimeThresholdTooLong) TEST_F(RPCGetAggregatePriceHandlerTest, TimeThresholdIncludeOldest) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - constexpr auto kDOCUMENT_ID1 = 1; - constexpr auto kDOCUMENT_ID2 = 2; - constexpr auto kDOCUMENT_ID3 = 3; - constexpr auto kDOCUMENT_ID4 = 4; - constexpr auto kTIMESTAMP1 = 1711461384u; - constexpr auto kTIMESTAMP2 = 1711461383u; - constexpr auto kTIMESTAMP3 = 1711461382u; - constexpr auto kTIMESTAMP4 = 1711461381u; - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID1, kTX1, 1e3, 2, kTIMESTAMP1); // 10 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID2, kTX1, 2e3, 2, kTIMESTAMP2); // 20 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID4, kTX1, 4e2, 1, kTIMESTAMP3); // 40 - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID3, kTX1, 3e3, 1, kTIMESTAMP4); // 300 + constexpr auto kDocumentID1 = 1; + constexpr auto kDocumentID2 = 2; + constexpr auto kDocumentID3 = 3; + constexpr auto kDocumentID4 = 4; + constexpr auto kTimestamp1 = 1711461384u; + constexpr auto kTimestamp2 = 1711461383u; + constexpr auto kTimestamp3 = 1711461382u; + constexpr auto kTimestamp4 = 1711461381u; + mockLedgerObject(*backend_, kAccount, kDocumentID1, kTx1, 1e3, 2, kTimestamp1); // 10 + mockLedgerObject(*backend_, kAccount, kDocumentID2, kTx1, 2e3, 2, kTimestamp2); // 20 + mockLedgerObject(*backend_, kAccount, kDocumentID4, kTx1, 4e2, 1, kTimestamp3); // 40 + mockLedgerObject(*backend_, kAccount, kDocumentID3, kTx1, 3e3, 1, kTimestamp4); // 300 auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "USD", @@ -1266,19 +1265,19 @@ TEST_F(RPCGetAggregatePriceHandlerTest, TimeThresholdIncludeOldest) }} ] }})JSON", - kTIMESTAMP4 - kTIMESTAMP1, - kACCOUNT, - kDOCUMENT_ID1, - kACCOUNT, - kDOCUMENT_ID2, - kACCOUNT, - kDOCUMENT_ID3, - kACCOUNT, - kDOCUMENT_ID4 + kTimestamp4 - kTimestamp1, + kAccount, + kDocumentID1, + kAccount, + kDocumentID2, + kAccount, + kDocumentID3, + kAccount, + kDocumentID4 ) ); - auto const expected = json::parse( + auto const expected = boost::json::parse( fmt::format( R"JSON({{ "entire_set": {{ @@ -1292,8 +1291,8 @@ TEST_F(RPCGetAggregatePriceHandlerTest, TimeThresholdIncludeOldest) "ledger_hash": "{}", "validated": true }})JSON", - kRANGE_MAX, - kLEDGER_HASH + kRangeMax, + kLedgerHash ) ); runSpawn([&](auto yield) { @@ -1306,31 +1305,31 @@ TEST_F(RPCGetAggregatePriceHandlerTest, TimeThresholdIncludeOldest) // When the price pair is not available in the current oracle, trace back to previous transactions TEST_F(RPCGetAggregatePriceHandlerTest, FromTx) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - constexpr auto kDOCUMENT_ID = 1; + constexpr auto kDocumentId = 1; auto const oracleIndex = - ripple::keylet::oracle(getAccountIdWithString(kACCOUNT), kDOCUMENT_ID).key; - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID, kTX1, 1e3, 2); // 10 + xrpl::keylet::oracle(getAccountIdWithString(kAccount), kDocumentId).key; + mockLedgerObject(*backend_, kAccount, kDocumentId, kTx1, 1e3, 2); // 10 // return a tx which contains NewFields - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256(kTX1), _)) + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256(kTx1), _)) .WillOnce(Return(createOracleSetTxWithMetadata( - kACCOUNT, - kRANGE_MAX, + kAccount, + kRangeMax, 123, 1, 4321u, - createPriceDataSeries({createOraclePriceData( - 1e3, ripple::to_currency("JPY"), ripple::to_currency("XRP"), 2 - )}), - ripple::to_string(oracleIndex), + createPriceDataSeries( + {createOraclePriceData(1e3, xrpl::toCurrency("JPY"), xrpl::toCurrency("XRP"), 2)} + ), + xrpl::to_string(oracleIndex), false, - kTX1 + kTx1 ))); auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "JPY", @@ -1342,12 +1341,12 @@ TEST_F(RPCGetAggregatePriceHandlerTest, FromTx) }} ] }})JSON", - kACCOUNT, - kDOCUMENT_ID + kAccount, + kDocumentId ) ); - auto const expected = json::parse( + auto const expected = boost::json::parse( fmt::format( R"JSON({{ "entire_set": {{ @@ -1361,8 +1360,8 @@ TEST_F(RPCGetAggregatePriceHandlerTest, FromTx) "ledger_hash": "{}", "validated": true }})JSON", - kRANGE_MAX, - kLEDGER_HASH + kRangeMax, + kLedgerHash ) ); runSpawn([&](auto yield) { @@ -1373,46 +1372,46 @@ TEST_F(RPCGetAggregatePriceHandlerTest, FromTx) } TEST_F(RPCGetAggregatePriceHandlerTest, NotFoundInTxHistory) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - constexpr auto kDOCUMENT_ID = 1; + constexpr auto kDocumentId = 1; auto const oracleIndex = - ripple::keylet::oracle(getAccountIdWithString(kACCOUNT), kDOCUMENT_ID).key; - mockLedgerObject(*backend_, kACCOUNT, kDOCUMENT_ID, kTX1, 1e3, 2); // 10 + xrpl::keylet::oracle(getAccountIdWithString(kAccount), kDocumentId).key; + mockLedgerObject(*backend_, kAccount, kDocumentId, kTx1, 1e3, 2); // 10 - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256(kTX1), _)) + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256(kTx1), _)) .WillOnce(Return(createOracleSetTxWithMetadata( - kACCOUNT, - kRANGE_MAX, + kAccount, + kRangeMax, 123, 1, 4321u, - createPriceDataSeries({createOraclePriceData( - 1e3, ripple::to_currency("EUR"), ripple::to_currency("XRP"), 2 - )}), - ripple::to_string(oracleIndex), + createPriceDataSeries( + {createOraclePriceData(1e3, xrpl::toCurrency("EUR"), xrpl::toCurrency("XRP"), 2)} + ), + xrpl::to_string(oracleIndex), false, - kTX2 + kTx2 ))); - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256(kTX2), _)) + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256(kTx2), _)) .WillRepeatedly(Return(createOracleSetTxWithMetadata( - kACCOUNT, - kRANGE_MAX, + kAccount, + kRangeMax, 123, 1, 4321u, - createPriceDataSeries({createOraclePriceData( - 1e3, ripple::to_currency("EUR"), ripple::to_currency("XRP"), 2 - )}), - ripple::to_string(oracleIndex), + createPriceDataSeries( + {createOraclePriceData(1e3, xrpl::toCurrency("EUR"), xrpl::toCurrency("XRP"), 2)} + ), + xrpl::to_string(oracleIndex), false, - kTX2 + kTx2 ))); auto const handler = AnyHandler{GetAggregatePriceHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "base_asset": "JPY", @@ -1424,8 +1423,8 @@ TEST_F(RPCGetAggregatePriceHandlerTest, NotFoundInTxHistory) }} ] }})JSON", - kACCOUNT, - kDOCUMENT_ID + kAccount, + kDocumentId ) ); diff --git a/tests/unit/rpc/handlers/LedgerDataTests.cpp b/tests/unit/rpc/handlers/LedgerDataTests.cpp index c18cdef7b..5e3255ee7 100644 --- a/tests/unit/rpc/handlers/LedgerDataTests.cpp +++ b/tests/unit/rpc/handlers/LedgerDataTests.cpp @@ -23,27 +23,26 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kRANGE_MIN = 10; -constexpr auto kRANGE_MAX = 30; -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kINDEX1 = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; -constexpr auto kINDEX2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; -constexpr auto kTXN_ID = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F0DD"; -constexpr auto kAPI_VERSION = 2; +constexpr auto kRangeMin = 10; +constexpr auto kRangeMax = 30; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kIndex1 = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; +constexpr auto kIndex2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; +constexpr auto kTxnId = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F0DD"; +constexpr auto kApiVersion = 2; } // namespace struct RPCLedgerDataHandlerTest : HandlerBaseTest { RPCLedgerDataHandlerTest() { - backend_->setRange(kRANGE_MIN, kRANGE_MAX); + backend_->setRange(kRangeMin, kRangeMax); } }; @@ -144,7 +143,7 @@ INSTANTIATE_TEST_CASE_P( RPCLedgerDataGroup1, LedgerDataParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(LedgerDataParameterTest, InvalidParams) @@ -152,7 +151,7 @@ TEST_P(LedgerDataParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -164,16 +163,16 @@ TEST_P(LedgerDataParameterTest, InvalidParams) TEST_F(RPCLedgerDataHandlerTest, LedgerNotExistViaIntSequence) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(std::nullopt)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "ledger_index": {} }})JSON", - kRANGE_MAX + kRangeMax ) ); auto const output = handler.process(req, Context{yield}); @@ -187,16 +186,16 @@ TEST_F(RPCLedgerDataHandlerTest, LedgerNotExistViaIntSequence) TEST_F(RPCLedgerDataHandlerTest, LedgerNotExistViaStringSequence) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(std::nullopt)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "ledger_index": "{}" }})JSON", - kRANGE_MAX + kRangeMax ) ); auto const output = handler.process(req, Context{yield}); @@ -210,17 +209,17 @@ TEST_F(RPCLedgerDataHandlerTest, LedgerNotExistViaStringSequence) TEST_F(RPCLedgerDataHandlerTest, LedgerNotExistViaHash) { EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "ledger_hash": "{}" }})JSON", - kLEDGER_HASH + kLedgerHash ) ); auto const output = handler.process(req, Context{yield}); @@ -234,21 +233,21 @@ TEST_F(RPCLedgerDataHandlerTest, LedgerNotExistViaHash) TEST_F(RPCLedgerDataHandlerTest, MarkerNotExist) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillByDefault(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillByDefault(Return(createLedgerHeader(kLedgerHash, kRangeMax))); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); - ON_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax, _)) .WillByDefault(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "marker": "{}" }})JSON", - kINDEX1 + kIndex1 ) ); auto const output = handler.process(req, Context{yield}); @@ -261,7 +260,7 @@ TEST_F(RPCLedgerDataHandlerTest, MarkerNotExist) TEST_F(RPCLedgerDataHandlerTest, NoMarker) { - static auto const kLEDGER_EXPECTED = R"JSON({ + static auto const kLedgerExpected = R"JSON({ "account_hash": "0000000000000000000000000000000000000000000000000000000000000000", "close_flags": 0, "close_time": 0, @@ -277,7 +276,7 @@ TEST_F(RPCLedgerDataHandlerTest, NoMarker) })JSON"; EXPECT_CALL(*backend_, fetchLedgerBySequence) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); // when 'type' not specified, default to all the types auto limitLine = 5; @@ -285,18 +284,18 @@ TEST_F(RPCLedgerDataHandlerTest, NoMarker) std::vector bbs; EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(limitLine + limitTicket); - ON_CALL(*backend_, doFetchSuccessorKey(_, kRANGE_MAX, _)) - .WillByDefault(Return(ripple::uint256{kINDEX2})); + ON_CALL(*backend_, doFetchSuccessorKey(_, kRangeMax, _)) + .WillByDefault(Return(xrpl::uint256{kIndex2})); while ((limitLine--) != 0) { auto const line = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); bbs.push_back(line.getSerializer().peekData()); } while ((limitTicket--) != 0) { - auto const ticket = createTicketLedgerObject(kACCOUNT, limitTicket); + auto const ticket = createTicketLedgerObject(kAccount, limitTicket); bbs.push_back(ticket.getSerializer().peekData()); } @@ -304,7 +303,7 @@ TEST_F(RPCLedgerDataHandlerTest, NoMarker) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse(R"JSON({"limit": 10})JSON"); + auto const req = boost::json::parse(R"JSON({"limit": 10})JSON"); auto output = handler.process(req, Context{yield}); ASSERT_TRUE(output); EXPECT_TRUE(output.result->as_object().contains("ledger")); @@ -312,17 +311,17 @@ TEST_F(RPCLedgerDataHandlerTest, NoMarker) // Note: the format of "close_time_human" depends on the platform and might differ per // platform. It is however guaranteed to be consistent on the same platform. EXPECT_EQ(output.result->as_object().at("ledger").as_object().erase("close_time_human"), 1); - EXPECT_EQ(output.result->as_object().at("ledger"), json::parse(kLEDGER_EXPECTED)); - EXPECT_EQ(output.result->as_object().at("marker").as_string(), kINDEX2); + EXPECT_EQ(output.result->as_object().at("ledger"), boost::json::parse(kLedgerExpected)); + EXPECT_EQ(output.result->as_object().at("marker").as_string(), kIndex2); EXPECT_EQ(output.result->as_object().at("state").as_array().size(), 10); - EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLEDGER_HASH); - EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRANGE_MAX); + EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLedgerHash); + EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRangeMax); }); } TEST_F(RPCLedgerDataHandlerTest, Version2) { - static auto const kLEDGER_EXPECTED = R"JSON({ + static auto const kLedgerExpected = R"JSON({ "account_hash": "0000000000000000000000000000000000000000000000000000000000000000", "close_flags": 0, "close_time": 0, @@ -338,7 +337,7 @@ TEST_F(RPCLedgerDataHandlerTest, Version2) })JSON"; EXPECT_CALL(*backend_, fetchLedgerBySequence) - .WillOnce(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + .WillOnce(Return(createLedgerHeader(kLedgerHash, kRangeMax))); // When 'type' not specified, default to all the types auto limitLine = 5; @@ -346,18 +345,18 @@ TEST_F(RPCLedgerDataHandlerTest, Version2) std::vector bbs; EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(limitLine + limitTicket); - ON_CALL(*backend_, doFetchSuccessorKey(_, kRANGE_MAX, _)) - .WillByDefault(Return(ripple::uint256{kINDEX2})); + ON_CALL(*backend_, doFetchSuccessorKey(_, kRangeMax, _)) + .WillByDefault(Return(xrpl::uint256{kIndex2})); while ((limitLine--) != 0) { auto const line = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); bbs.push_back(line.getSerializer().peekData()); } while ((limitTicket--) != 0) { - auto const ticket = createTicketLedgerObject(kACCOUNT, limitTicket); + auto const ticket = createTicketLedgerObject(kAccount, limitTicket); bbs.push_back(ticket.getSerializer().peekData()); } @@ -365,21 +364,21 @@ TEST_F(RPCLedgerDataHandlerTest, Version2) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse(R"JSON({"limit": 10})JSON"); - auto output = handler.process(req, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + auto const req = boost::json::parse(R"JSON({"limit": 10})JSON"); + auto output = handler.process(req, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_TRUE(output); EXPECT_TRUE(output.result->as_object().contains("ledger")); // Note: the format of "close_time_human" depends on the platform and might differ per // platform. It is however guaranteed to be consistent on the same platform. EXPECT_EQ(output.result->as_object().at("ledger").as_object().erase("close_time_human"), 1); - EXPECT_EQ(output.result->as_object().at("ledger"), json::parse(kLEDGER_EXPECTED)); + EXPECT_EQ(output.result->as_object().at("ledger"), boost::json::parse(kLedgerExpected)); }); } TEST_F(RPCLedgerDataHandlerTest, TypeFilter) { - static auto const kLEDGER_EXPECTED = R"JSON({ + static auto const kLedgerExpected = R"JSON({ "account_hash": "0000000000000000000000000000000000000000000000000000000000000000", "close_flags": 0, "close_time": 0, @@ -395,26 +394,26 @@ TEST_F(RPCLedgerDataHandlerTest, TypeFilter) })JSON"; EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillByDefault(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillByDefault(Return(createLedgerHeader(kLedgerHash, kRangeMax))); auto limitLine = 5; auto limitTicket = 5; std::vector bbs; EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(limitLine + limitTicket); - ON_CALL(*backend_, doFetchSuccessorKey(_, kRANGE_MAX, _)) - .WillByDefault(Return(ripple::uint256{kINDEX2})); + ON_CALL(*backend_, doFetchSuccessorKey(_, kRangeMax, _)) + .WillByDefault(Return(xrpl::uint256{kIndex2})); while ((limitLine--) != 0) { auto const line = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); bbs.push_back(line.getSerializer().peekData()); } while ((limitTicket--) != 0) { - auto const ticket = createTicketLedgerObject(kACCOUNT, limitTicket); + auto const ticket = createTicketLedgerObject(kAccount, limitTicket); bbs.push_back(ticket.getSerializer().peekData()); } @@ -423,7 +422,7 @@ TEST_F(RPCLedgerDataHandlerTest, TypeFilter) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse(R"JSON({ + auto const req = boost::json::parse(R"JSON({ "limit": 10, "type": "state" })JSON"); @@ -435,17 +434,17 @@ TEST_F(RPCLedgerDataHandlerTest, TypeFilter) // Note: the format of "close_time_human" depends on the platform and might differ per // platform. It is however guaranteed to be consistent on the same platform. EXPECT_EQ(output.result->as_object().at("ledger").as_object().erase("close_time_human"), 1); - EXPECT_EQ(output.result->as_object().at("ledger"), json::parse(kLEDGER_EXPECTED)); - EXPECT_EQ(output.result->as_object().at("marker").as_string(), kINDEX2); + EXPECT_EQ(output.result->as_object().at("ledger"), boost::json::parse(kLedgerExpected)); + EXPECT_EQ(output.result->as_object().at("marker").as_string(), kIndex2); EXPECT_EQ(output.result->as_object().at("state").as_array().size(), 5); - EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLEDGER_HASH); - EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRANGE_MAX); + EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLedgerHash); + EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRangeMax); }); } TEST_F(RPCLedgerDataHandlerTest, TypeFilterAMM) { - static auto const kLEDGER_EXPECTED = R"JSON({ + static auto const kLedgerExpected = R"JSON({ "account_hash": "0000000000000000000000000000000000000000000000000000000000000000", "close_flags": 0, "close_time": 0, @@ -461,25 +460,25 @@ TEST_F(RPCLedgerDataHandlerTest, TypeFilterAMM) })JSON"; EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillByDefault(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillByDefault(Return(createLedgerHeader(kLedgerHash, kRangeMax))); auto limitLine = 5; std::vector bbs; EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(limitLine + 1); - ON_CALL(*backend_, doFetchSuccessorKey(_, kRANGE_MAX, _)) - .WillByDefault(Return(ripple::uint256{kINDEX2})); + ON_CALL(*backend_, doFetchSuccessorKey(_, kRangeMax, _)) + .WillByDefault(Return(xrpl::uint256{kIndex2})); while ((limitLine--) != 0) { auto const line = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); bbs.push_back(line.getSerializer().peekData()); } auto const amm = - createAmmObject(kACCOUNT, "XRP", ripple::toBase58(ripple::xrpAccount()), "JPY", kACCOUNT2); + createAmmObject(kAccount, "XRP", xrpl::toBase58(xrpl::xrpAccount()), "JPY", kAccount2); bbs.push_back(amm.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); @@ -487,7 +486,7 @@ TEST_F(RPCLedgerDataHandlerTest, TypeFilterAMM) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse(R"JSON({ + auto const req = boost::json::parse(R"JSON({ "limit": 6, "type": "amm" })JSON"); @@ -499,17 +498,17 @@ TEST_F(RPCLedgerDataHandlerTest, TypeFilterAMM) // Note: the format of "close_time_human" depends on the platform and might differ per // platform. It is however guaranteed to be consistent on the same platform. EXPECT_EQ(output.result->as_object().at("ledger").as_object().erase("close_time_human"), 1); - EXPECT_EQ(output.result->as_object().at("ledger"), json::parse(kLEDGER_EXPECTED)); - EXPECT_EQ(output.result->as_object().at("marker").as_string(), kINDEX2); + EXPECT_EQ(output.result->as_object().at("ledger"), boost::json::parse(kLedgerExpected)); + EXPECT_EQ(output.result->as_object().at("marker").as_string(), kIndex2); EXPECT_EQ(output.result->as_object().at("state").as_array().size(), 1); - EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLEDGER_HASH); - EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRANGE_MAX); + EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLedgerHash); + EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRangeMax); }); } TEST_F(RPCLedgerDataHandlerTest, OutOfOrder) { - static auto const kLEDGER_EXPECTED = R"JSON({ + static auto const kLedgerExpected = R"JSON({ "account_hash": "0000000000000000000000000000000000000000000000000000000000000000", "close_flags": 0, "close_time": 0, @@ -525,20 +524,20 @@ TEST_F(RPCLedgerDataHandlerTest, OutOfOrder) })JSON"; EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillByDefault(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillByDefault(Return(createLedgerHeader(kLedgerHash, kRangeMax))); // page end // marker return seq std::vector bbs; EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(2); - ON_CALL(*backend_, doFetchSuccessorKey(kFIRST_KEY, kRANGE_MAX, _)) - .WillByDefault(Return(ripple::uint256{kINDEX2})); - ON_CALL(*backend_, doFetchSuccessorKey(ripple::uint256{kINDEX2}, kRANGE_MAX, _)) + ON_CALL(*backend_, doFetchSuccessorKey(kFirstKey, kRangeMax, _)) + .WillByDefault(Return(xrpl::uint256{kIndex2})); + ON_CALL(*backend_, doFetchSuccessorKey(xrpl::uint256{kIndex2}, kRangeMax, _)) .WillByDefault(Return(std::nullopt)); auto const line = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); bbs.push_back(line.getSerializer().peekData()); @@ -547,29 +546,29 @@ TEST_F(RPCLedgerDataHandlerTest, OutOfOrder) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse(R"JSON({"limit": 10, "out_of_order": true})JSON"); + auto const req = boost::json::parse(R"JSON({"limit": 10, "out_of_order": true})JSON"); auto output = handler.process(req, Context{yield}); ASSERT_TRUE(output); EXPECT_TRUE(output.result->as_object().contains("ledger")); EXPECT_EQ(output.result->as_object().at("ledger").as_object().erase("close_time_human"), 1); - EXPECT_EQ(output.result->as_object().at("ledger"), json::parse(kLEDGER_EXPECTED)); - EXPECT_EQ(output.result->as_object().at("marker").as_uint64(), kRANGE_MAX); + EXPECT_EQ(output.result->as_object().at("ledger"), boost::json::parse(kLedgerExpected)); + EXPECT_EQ(output.result->as_object().at("marker").as_uint64(), kRangeMax); EXPECT_EQ(output.result->as_object().at("state").as_array().size(), 1); - EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLEDGER_HASH); - EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRANGE_MAX); + EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLedgerHash); + EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRangeMax); }); } TEST_F(RPCLedgerDataHandlerTest, Marker) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillByDefault(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillByDefault(Return(createLedgerHeader(kLedgerHash, kRangeMax))); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); - ON_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax, _)) .WillByDefault(Return(createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ) .getSerializer() .peekData())); @@ -577,14 +576,14 @@ TEST_F(RPCLedgerDataHandlerTest, Marker) auto limit = 10; std::vector bbs; EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(limit); - ON_CALL(*backend_, doFetchSuccessorKey(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) - .WillByDefault(Return(ripple::uint256{kINDEX2})); - ON_CALL(*backend_, doFetchSuccessorKey(ripple::uint256{kINDEX2}, kRANGE_MAX, _)) - .WillByDefault(Return(ripple::uint256{kINDEX2})); + ON_CALL(*backend_, doFetchSuccessorKey(xrpl::uint256{kIndex1}, kRangeMax, _)) + .WillByDefault(Return(xrpl::uint256{kIndex2})); + ON_CALL(*backend_, doFetchSuccessorKey(xrpl::uint256{kIndex2}, kRangeMax, _)) + .WillByDefault(Return(xrpl::uint256{kIndex2})); while ((limit--) != 0) { auto const line = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); bbs.push_back(line.getSerializer().peekData()); } @@ -594,30 +593,30 @@ TEST_F(RPCLedgerDataHandlerTest, Marker) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "limit": 10, "marker": "{}" }})JSON", - kINDEX1 + kIndex1 ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); EXPECT_FALSE(output.result->as_object().contains("ledger")); - EXPECT_EQ(output.result->as_object().at("marker").as_string(), kINDEX2); + EXPECT_EQ(output.result->as_object().at("marker").as_string(), kIndex2); EXPECT_EQ(output.result->as_object().at("state").as_array().size(), 10); - EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLEDGER_HASH); - EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRANGE_MAX); + EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLedgerHash); + EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRangeMax); }); } TEST_F(RPCLedgerDataHandlerTest, DiffMarker) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillByDefault(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillByDefault(Return(createLedgerHeader(kLedgerHash, kRangeMax))); auto limit = 10; std::vector los; @@ -627,36 +626,36 @@ TEST_F(RPCLedgerDataHandlerTest, DiffMarker) while ((limit--) != 0) { auto const line = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); bbs.push_back(line.getSerializer().peekData()); los.emplace_back( - LedgerObject{.key = ripple::uint256{kINDEX2}, .blob = Blob{}} + LedgerObject{.key = xrpl::uint256{kIndex2}, .blob = Blob{}} ); // NOLINT(modernize-use-emplace) } - ON_CALL(*backend_, fetchLedgerDiff(kRANGE_MAX, _)).WillByDefault(Return(los)); + ON_CALL(*backend_, fetchLedgerDiff(kRangeMax, _)).WillByDefault(Return(los)); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "limit": 10, "marker": {}, "out_of_order": true }})JSON", - kRANGE_MAX + kRangeMax ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); EXPECT_FALSE(output.result->as_object().contains("ledger")); EXPECT_EQ(output.result->as_object().at("state").as_array().size(), 10); - EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLEDGER_HASH); - EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRANGE_MAX); + EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLedgerHash); + EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRangeMax); EXPECT_FALSE(output.result->as_object().at("cache_full").as_bool()); }); } @@ -664,19 +663,19 @@ TEST_F(RPCLedgerDataHandlerTest, DiffMarker) TEST_F(RPCLedgerDataHandlerTest, Binary) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillByDefault(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillByDefault(Return(createLedgerHeader(kLedgerHash, kRangeMax))); auto limit = 10; std::vector bbs; EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(limit); - ON_CALL(*backend_, doFetchSuccessorKey(_, kRANGE_MAX, _)) - .WillByDefault(Return(ripple::uint256{kINDEX2})); + ON_CALL(*backend_, doFetchSuccessorKey(_, kRangeMax, _)) + .WillByDefault(Return(xrpl::uint256{kIndex2})); while ((limit--) != 0) { auto const line = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); bbs.push_back(line.getSerializer().peekData()); } @@ -686,7 +685,7 @@ TEST_F(RPCLedgerDataHandlerTest, Binary) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "limit": 10, "binary": true @@ -698,27 +697,27 @@ TEST_F(RPCLedgerDataHandlerTest, Binary) EXPECT_TRUE(output.result->as_object().at("ledger").as_object().contains("ledger_data")); EXPECT_TRUE(output.result->as_object().at("ledger").as_object().at("closed").as_bool()); EXPECT_EQ(output.result->as_object().at("state").as_array().size(), 10); - EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLEDGER_HASH); - EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRANGE_MAX); + EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLedgerHash); + EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRangeMax); }); } TEST_F(RPCLedgerDataHandlerTest, BinaryLimitMoreThanMax) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillByDefault(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillByDefault(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - auto limit = LedgerDataHandler::kLIMIT_BINARY + 1; + auto limit = LedgerDataHandler::kLimitBinary + 1; std::vector bbs; - EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(LedgerDataHandler::kLIMIT_BINARY); - ON_CALL(*backend_, doFetchSuccessorKey(_, kRANGE_MAX, _)) - .WillByDefault(Return(ripple::uint256{kINDEX2})); + EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(LedgerDataHandler::kLimitBinary); + ON_CALL(*backend_, doFetchSuccessorKey(_, kRangeMax, _)) + .WillByDefault(Return(xrpl::uint256{kIndex2})); while ((limit--) != 0u) { auto const line = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); bbs.push_back(line.getSerializer().peekData()); } @@ -728,13 +727,13 @@ TEST_F(RPCLedgerDataHandlerTest, BinaryLimitMoreThanMax) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "limit": {}, "binary": true }})JSON", - LedgerDataHandler::kLIMIT_BINARY + 1 + LedgerDataHandler::kLimitBinary + 1 ) ); auto const output = handler.process(req, Context{yield}); @@ -744,29 +743,29 @@ TEST_F(RPCLedgerDataHandlerTest, BinaryLimitMoreThanMax) EXPECT_TRUE(output.result->as_object().at("ledger").as_object().at("closed").as_bool()); EXPECT_EQ( output.result->as_object().at("state").as_array().size(), - LedgerDataHandler::kLIMIT_BINARY + LedgerDataHandler::kLimitBinary ); - EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLEDGER_HASH); - EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRANGE_MAX); + EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLedgerHash); + EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRangeMax); }); } TEST_F(RPCLedgerDataHandlerTest, JsonLimitMoreThanMax) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillByDefault(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillByDefault(Return(createLedgerHeader(kLedgerHash, kRangeMax))); - auto limit = LedgerDataHandler::kLIMIT_JSON + 1; + auto limit = LedgerDataHandler::kLimitJson + 1; std::vector bbs; - EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(LedgerDataHandler::kLIMIT_JSON); - ON_CALL(*backend_, doFetchSuccessorKey(_, kRANGE_MAX, _)) - .WillByDefault(Return(ripple::uint256{kINDEX2})); + EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(LedgerDataHandler::kLimitJson); + ON_CALL(*backend_, doFetchSuccessorKey(_, kRangeMax, _)) + .WillByDefault(Return(xrpl::uint256{kIndex2})); while ((limit--) != 0u) { auto const line = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); bbs.push_back(line.getSerializer().peekData()); } @@ -776,13 +775,13 @@ TEST_F(RPCLedgerDataHandlerTest, JsonLimitMoreThanMax) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "limit": {}, "binary": false }})JSON", - LedgerDataHandler::kLIMIT_JSON + 1 + LedgerDataHandler::kLimitJson + 1 ) ); auto const output = handler.process(req, Context{yield}); @@ -790,25 +789,25 @@ TEST_F(RPCLedgerDataHandlerTest, JsonLimitMoreThanMax) EXPECT_TRUE(output.result->as_object().contains("ledger")); EXPECT_TRUE(output.result->as_object().at("ledger").as_object().at("closed").as_bool()); EXPECT_EQ( - output.result->as_object().at("state").as_array().size(), LedgerDataHandler::kLIMIT_JSON + output.result->as_object().at("state").as_array().size(), LedgerDataHandler::kLimitJson ); - EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLEDGER_HASH); - EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRANGE_MAX); + EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLedgerHash); + EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRangeMax); }); } TEST_F(RPCLedgerDataHandlerTest, TypeFilterMPTIssuance) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillByDefault(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillByDefault(Return(createLedgerHeader(kLedgerHash, kRangeMax))); std::vector bbs; EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(1); - ON_CALL(*backend_, doFetchSuccessorKey(_, kRANGE_MAX, _)) - .WillByDefault(Return(ripple::uint256{kINDEX2})); + ON_CALL(*backend_, doFetchSuccessorKey(_, kRangeMax, _)) + .WillByDefault(Return(xrpl::uint256{kIndex2})); - auto const issuance = createMptIssuanceObject(kACCOUNT, 2, "metadata"); + auto const issuance = createMptIssuanceObject(kAccount, 2, "metadata"); bbs.push_back(issuance.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); @@ -816,7 +815,7 @@ TEST_F(RPCLedgerDataHandlerTest, TypeFilterMPTIssuance) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse(R"JSON({ + auto const req = boost::json::parse(R"JSON({ "limit": 1, "type": "mpt_issuance" })JSON"); @@ -825,9 +824,9 @@ TEST_F(RPCLedgerDataHandlerTest, TypeFilterMPTIssuance) ASSERT_TRUE(output); EXPECT_TRUE(output.result->as_object().contains("ledger")); EXPECT_EQ(output.result->as_object().at("state").as_array().size(), 1); - EXPECT_EQ(output.result->as_object().at("marker").as_string(), kINDEX2); - EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLEDGER_HASH); - EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRANGE_MAX); + EXPECT_EQ(output.result->as_object().at("marker").as_string(), kIndex2); + EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLedgerHash); + EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRangeMax); auto const& objects = output.result->as_object().at("state").as_array(); EXPECT_EQ(objects.front().at("LedgerEntryType").as_string(), "MPTokenIssuance"); @@ -835,7 +834,7 @@ TEST_F(RPCLedgerDataHandlerTest, TypeFilterMPTIssuance) // make sure mptID is synethetically parsed if object is mptIssuance EXPECT_EQ( objects.front().at("mpt_issuance_id").as_string(), - ripple::to_string(ripple::makeMptID(2, getAccountIdWithString(kACCOUNT))) + xrpl::to_string(xrpl::makeMptID(2, getAccountIdWithString(kAccount))) ); }); } @@ -843,16 +842,16 @@ TEST_F(RPCLedgerDataHandlerTest, TypeFilterMPTIssuance) TEST_F(RPCLedgerDataHandlerTest, TypeFilterMPToken) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) - .WillByDefault(Return(createLedgerHeader(kLEDGER_HASH, kRANGE_MAX))); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) + .WillByDefault(Return(createLedgerHeader(kLedgerHash, kRangeMax))); std::vector bbs; EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(1); - ON_CALL(*backend_, doFetchSuccessorKey(_, kRANGE_MAX, _)) - .WillByDefault(Return(ripple::uint256{kINDEX2})); + ON_CALL(*backend_, doFetchSuccessorKey(_, kRangeMax, _)) + .WillByDefault(Return(xrpl::uint256{kIndex2})); auto const mptoken = - createMpTokenObject(kACCOUNT, ripple::makeMptID(2, getAccountIdWithString(kACCOUNT))); + createMpTokenObject(kAccount, xrpl::makeMptID(2, getAccountIdWithString(kAccount))); bbs.push_back(mptoken.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); @@ -860,7 +859,7 @@ TEST_F(RPCLedgerDataHandlerTest, TypeFilterMPToken) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerDataHandler{backend_}}; - auto const req = json::parse(R"JSON({ + auto const req = boost::json::parse(R"JSON({ "limit": 1, "type": "mptoken" })JSON"); @@ -869,9 +868,9 @@ TEST_F(RPCLedgerDataHandlerTest, TypeFilterMPToken) ASSERT_TRUE(output); EXPECT_TRUE(output.result->as_object().contains("ledger")); EXPECT_EQ(output.result->as_object().at("state").as_array().size(), 1); - EXPECT_EQ(output.result->as_object().at("marker").as_string(), kINDEX2); - EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLEDGER_HASH); - EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRANGE_MAX); + EXPECT_EQ(output.result->as_object().at("marker").as_string(), kIndex2); + EXPECT_EQ(output.result->as_object().at("ledger_hash").as_string(), kLedgerHash); + EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), kRangeMax); auto const& objects = output.result->as_object().at("state").as_array(); EXPECT_EQ(objects.front().at("LedgerEntryType").as_string(), "MPToken"); diff --git a/tests/unit/rpc/handlers/LedgerEntryTests.cpp b/tests/unit/rpc/handlers/LedgerEntryTests.cpp index 9598266d1..5a7e66c4f 100644 --- a/tests/unit/rpc/handlers/LedgerEntryTests.cpp +++ b/tests/unit/rpc/handlers/LedgerEntryTests.cpp @@ -40,29 +40,28 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kINDEX1 = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kACCOUNT3 = "rhzcyub9SbyZ4YF1JYskN5rLrTDUuLZG6D"; -constexpr auto kRANGE_MIN = 10; -constexpr auto kRANGE_MAX = 30; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kTOKEN_ID = "000827103B94ECBB7BF0A0A6ED62B3607801A27B65F4679F4AD1D4850000C0EA"; -constexpr auto kNFT_ID = "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004"; -constexpr auto kTXN_ID = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; -constexpr auto kCREDENTIAL_TYPE = "4B5943"; +constexpr auto kIndex1 = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kAccount3 = "rhzcyub9SbyZ4YF1JYskN5rLrTDUuLZG6D"; +constexpr auto kRangeMin = 10; +constexpr auto kRangeMax = 30; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kTokenId = "000827103B94ECBB7BF0A0A6ED62B3607801A27B65F4679F4AD1D4850000C0EA"; +constexpr auto kNftId = "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004"; +constexpr auto kTxnId = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; +constexpr auto kCredentialType = "4B5943"; } // namespace struct RPCLedgerEntryTest : HandlerBaseTest { RPCLedgerEntryTest() { - backend_->setRange(kRANGE_MIN, kRANGE_MAX); + backend_->setRange(kRangeMin, kRangeMax); } }; @@ -197,7 +196,7 @@ generateTestValuesForParametersTest() "authorized": 123 }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "invalidParams", .expectedErrorMessage = "authorizedNotString" @@ -212,7 +211,7 @@ generateTestValuesForParametersTest() "authorized_credentials": "asdf" }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "authorized_credentials not array" @@ -227,7 +226,7 @@ generateTestValuesForParametersTest() "authorized_credentials": ["C2F2A19C8D0D893D18F18FDCFE13A3ECB41767E48422DF07F2455CDA08FDF09B"] }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedAuthorizedCredentials", .expectedErrorMessage = "authorized_credentials elements in array are not objects." @@ -241,7 +240,7 @@ generateTestValuesForParametersTest() "owner": "{}" }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Must have one of authorized or authorized_credentials." @@ -262,10 +261,10 @@ generateTestValuesForParametersTest() ] }} }})JSON", - kACCOUNT, - kACCOUNT2, - kACCOUNT3, - kCREDENTIAL_TYPE + kAccount, + kAccount2, + kAccount3, + kCredentialType ), .expectedError = "malformedRequest", .expectedErrorMessage = "Must have one of authorized or authorized_credentials." @@ -281,7 +280,7 @@ generateTestValuesForParametersTest() ] }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedAuthorizedCredentials", .expectedErrorMessage = "Requires at least one element in authorized_credentials array." @@ -300,8 +299,8 @@ generateTestValuesForParametersTest() ] }} }})JSON", - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount2 ), .expectedError = "malformedAuthorizedCredentials", .expectedErrorMessage = "Field 'CredentialType' is required but missing." @@ -320,8 +319,8 @@ generateTestValuesForParametersTest() ] }} }})JSON", - kACCOUNT, - kCREDENTIAL_TYPE + kAccount, + kCredentialType ), .expectedError = "malformedAuthorizedCredentials", .expectedErrorMessage = "Field 'Issuer' is required but missing." @@ -341,8 +340,8 @@ generateTestValuesForParametersTest() ] }} }})JSON", - kACCOUNT, - kCREDENTIAL_TYPE + kAccount, + kCredentialType ), .expectedError = "malformedAuthorizedCredentials", .expectedErrorMessage = "issuer NotString" @@ -362,8 +361,8 @@ generateTestValuesForParametersTest() ] }} }})JSON", - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount2 ), .expectedError = "malformedAuthorizedCredentials", .expectedErrorMessage = "credential_type NotString" @@ -383,8 +382,8 @@ generateTestValuesForParametersTest() ] }} }})JSON", - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount2 ), .expectedError = "malformedAuthorizedCredentials", .expectedErrorMessage = "credential_type NotHexString" @@ -404,8 +403,8 @@ generateTestValuesForParametersTest() ] }} }})JSON", - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount2 ), .expectedError = "malformedAuthorizedCredentials", .expectedErrorMessage = "credential_type is empty" @@ -429,11 +428,11 @@ generateTestValuesForParametersTest() ] }} }})JSON", - kACCOUNT, - kACCOUNT2, - kCREDENTIAL_TYPE, - kACCOUNT2, - kCREDENTIAL_TYPE + kAccount, + kAccount2, + kCredentialType, + kAccount2, + kCredentialType ), .expectedError = "malformedAuthorizedCredentials", .expectedErrorMessage = "duplicates in credentials." @@ -499,7 +498,7 @@ generateTestValuesForParametersTest() "ticket_seq": "123" }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -565,7 +564,7 @@ generateTestValuesForParametersTest() "seq": "123" }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -631,7 +630,7 @@ generateTestValuesForParametersTest() "seq": "123" }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -674,7 +673,7 @@ generateTestValuesForParametersTest() "accounts": ["{}"] }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "invalidParams", .expectedErrorMessage = "malformedAccounts" @@ -689,8 +688,8 @@ generateTestValuesForParametersTest() "currency": "USD" }} }})JSON", - kACCOUNT, - kACCOUNT + kAccount, + kAccount ), .expectedError = "invalidParams", .expectedErrorMessage = "malformedAccounts" @@ -705,7 +704,7 @@ generateTestValuesForParametersTest() "currency": "USD" }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "invalidParams", .expectedErrorMessage = "malformedAccounts" @@ -720,7 +719,7 @@ generateTestValuesForParametersTest() "currency": "USD" }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedAddress", .expectedErrorMessage = "malformedAddresses" @@ -735,8 +734,8 @@ generateTestValuesForParametersTest() "currency": "XXXX" }} }})JSON", - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount2 ), .expectedError = "malformedCurrency", .expectedErrorMessage = "malformedCurrency" @@ -751,8 +750,8 @@ generateTestValuesForParametersTest() "currency": 123 }} }})JSON", - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount2 ), .expectedError = "invalidParams", .expectedErrorMessage = "currencyNotString" @@ -838,8 +837,8 @@ generateTestValuesForParametersTest() "owner": "{}" }} }})JSON", - kINDEX1, - kACCOUNT + kIndex1, + kAccount ), .expectedError = "invalidParams", .expectedErrorMessage = "mayNotSpecifyBothDirRootAndOwner" @@ -854,7 +853,7 @@ generateTestValuesForParametersTest() "sub_index": "not int" }} }})JSON", - kINDEX1 + kIndex1 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -902,7 +901,7 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -920,7 +919,7 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -937,7 +936,7 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -954,7 +953,7 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -972,7 +971,7 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -990,7 +989,7 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1010,7 +1009,7 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1030,7 +1029,7 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1050,7 +1049,7 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1071,8 +1070,8 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT + kAccount, + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1091,7 +1090,7 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1112,10 +1111,10 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, + kAccount, + kAccount, "JPY", - kACCOUNT2 + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1137,11 +1136,11 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, - kACCOUNT, + kAccount, + kAccount, + kAccount, 1, - kACCOUNT2 + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1163,9 +1162,9 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, - kACCOUNT, + kAccount, + kAccount, + kAccount, "JPY", 2 ), @@ -1186,9 +1185,9 @@ generateTestValuesForParametersTest() "IssuingChainIssue": 1 }} }})JSON", - kACCOUNT, - kACCOUNT, - kACCOUNT + kAccount, + kAccount, + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1210,10 +1209,10 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, + kAccount, + kAccount, "JPY", - kACCOUNT2 + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1235,10 +1234,10 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, + kAccount, + kAccount, "JPY", - kACCOUNT2 + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1260,9 +1259,9 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, - kACCOUNT, + kAccount, + kAccount, + kAccount, "JPY" ), .expectedError = "malformedRequest", @@ -1285,10 +1284,10 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, - kACCOUNT2, - kACCOUNT2 + kAccount, + kAccount, + kAccount2, + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1311,11 +1310,11 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, - kACCOUNT2, - kACCOUNT2, - kACCOUNT2 + kAccount, + kAccount, + kAccount2, + kAccount2, + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1336,9 +1335,9 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount, + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1360,10 +1359,10 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT2, - kACCOUNT2, - kACCOUNT2 + kAccount, + kAccount2, + kAccount2, + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1384,9 +1383,9 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount, + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1405,10 +1404,10 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount, + kAccount, + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1427,10 +1426,10 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount, + kAccount, + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1442,7 +1441,7 @@ generateTestValuesForParametersTest() "bridge_account": "{}", "bridge": "invalid" }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1471,10 +1470,10 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, + kAccount, + kAccount, "JPY", - kACCOUNT2 + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1495,9 +1494,9 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, + kAccount, "JPY", - kACCOUNT2 + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1515,8 +1514,8 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT + kAccount, + kAccount ), .expectedError = "malformedRequest", @@ -1539,9 +1538,9 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, + kAccount, "JPY", - kACCOUNT2 + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1562,8 +1561,8 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, + kAccount, + kAccount, "JPY" ), .expectedError = "malformedRequest", @@ -1593,10 +1592,10 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, + kAccount, + kAccount, "JPY", - kACCOUNT2 + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1617,9 +1616,9 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, + kAccount, "JPY", - kACCOUNT2 + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1637,8 +1636,8 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT + kAccount, + kAccount ), .expectedError = "malformedRequest", @@ -1661,9 +1660,9 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, + kAccount, "JPY", - kACCOUNT2 + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1684,8 +1683,8 @@ generateTestValuesForParametersTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, + kAccount, + kAccount, "JPY" ), .expectedError = "malformedRequest", @@ -1699,7 +1698,7 @@ generateTestValuesForParametersTest() "account": "{}" }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1713,7 +1712,7 @@ generateTestValuesForParametersTest() "oracle_document_id": -1 }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedDocumentID", .expectedErrorMessage = "Malformed oracle_document_id." @@ -1727,7 +1726,7 @@ generateTestValuesForParametersTest() "oracle_document_id": "invalid" }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedDocumentID", .expectedErrorMessage = "Malformed oracle_document_id." @@ -1741,7 +1740,7 @@ generateTestValuesForParametersTest() "oracle_document_id": 3.21 }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedDocumentID", .expectedErrorMessage = "Malformed oracle_document_id." @@ -1755,7 +1754,7 @@ generateTestValuesForParametersTest() "oracle_document_id": {{}} }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedDocumentID", .expectedErrorMessage = "Malformed oracle_document_id." @@ -1769,7 +1768,7 @@ generateTestValuesForParametersTest() "oracle_document_id": [] }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedDocumentID", .expectedErrorMessage = "Malformed oracle_document_id." @@ -1783,7 +1782,7 @@ generateTestValuesForParametersTest() "oracle_document_id": null }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedDocumentID", .expectedErrorMessage = "Malformed oracle_document_id." @@ -1922,7 +1921,7 @@ generateTestValuesForParametersTest() "issuer": ["{}"] }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1969,7 +1968,7 @@ generateTestValuesForParametersTest() "account": "{}" }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1984,8 +1983,8 @@ generateTestValuesForParametersTest() "credential_type": 1234 }} }})JSON", - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -1999,8 +1998,8 @@ generateTestValuesForParametersTest() "credential_type": "1234" }} }})JSON", - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -2058,7 +2057,7 @@ generateTestValuesForParametersTest() R"JSON({{ "permissioned_domain": {{ "account": "{}" }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request.", @@ -2069,7 +2068,7 @@ generateTestValuesForParametersTest() R"JSON({{ "permissioned_domain": {{ "account": "{}", "seq": -1 }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request.", @@ -2199,7 +2198,7 @@ generateTestValuesForParametersTest() "seq": "notAnInteger" }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request.", @@ -2259,7 +2258,7 @@ generateTestValuesForParametersTest() R"JSON({{ "loan": {{ "loan_broker_id": "{}" }} }})JSON", - kINDEX1 + kIndex1 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request.", @@ -2273,7 +2272,7 @@ generateTestValuesForParametersTest() "loan_seq": "notAnInteger" }} }})JSON", - kINDEX1 + kIndex1 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request.", @@ -2299,7 +2298,7 @@ generateTestValuesForParametersTest() "loan_seq": -200 }} }})JSON", - kINDEX1 + kIndex1 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request.", @@ -2330,7 +2329,7 @@ generateTestValuesForParametersTest() "authorize": "{}" }} }})JSON", - kACCOUNT2 + kAccount2 ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -2344,7 +2343,7 @@ generateTestValuesForParametersTest() "authorize": "{}" }} }})JSON", - kACCOUNT2 + kAccount2 ), .expectedError = "malformedAddress", .expectedErrorMessage = "Malformed address." @@ -2358,7 +2357,7 @@ generateTestValuesForParametersTest() "authorize": "{}" }} }})JSON", - kACCOUNT2 + kAccount2 ), .expectedError = "malformedAddress", .expectedErrorMessage = "Malformed address." @@ -2371,7 +2370,7 @@ generateTestValuesForParametersTest() "account": "{}" }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedRequest", .expectedErrorMessage = "Malformed request." @@ -2385,7 +2384,7 @@ generateTestValuesForParametersTest() "authorize": 123 }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedAddress", .expectedErrorMessage = "Malformed address." @@ -2399,7 +2398,7 @@ generateTestValuesForParametersTest() "authorize": "invalid_address" }} }})JSON", - kACCOUNT + kAccount ), .expectedError = "malformedAddress", .expectedErrorMessage = "Malformed address." @@ -2411,7 +2410,7 @@ INSTANTIATE_TEST_CASE_P( RPCLedgerEntryGroup1, LedgerEntryParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(LedgerEntryParameterTest, InvalidParams) @@ -2419,7 +2418,7 @@ TEST_P(LedgerEntryParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); @@ -2466,7 +2465,7 @@ TEST_P(IndexTest, InvalidIndexUint256) auto const index = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "{}": "invalid" @@ -2488,7 +2487,7 @@ TEST_P(IndexTest, InvalidIndexNotString) auto const index = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "{}": 123 @@ -2507,23 +2506,23 @@ TEST_P(IndexTest, InvalidIndexNotString) TEST_F(RPCLedgerEntryTest, LedgerEntryNotFound) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) .WillRepeatedly(Return(ledgerHeader)); // return null for ledger entry - auto const key = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(key, kRANGE_MAX, _)) + auto const key = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; + EXPECT_CALL(*backend_, doFetchLedgerObject(key, kRangeMax, _)) .WillRepeatedly(Return(std::optional{})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "account_root": "{}" }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(req, Context{yield}); @@ -2536,8 +2535,8 @@ TEST_F(RPCLedgerEntryTest, LedgerEntryNotFound) struct NormalPathTestBundle { std::string testName; std::string testJson; - ripple::uint256 expectedIndex; - ripple::STObject mockedEntity; + xrpl::uint256 expectedIndex; + xrpl::STObject mockedEntity; }; struct RPCLedgerEntryNormalPathTest : public RPCLedgerEntryTest, @@ -2546,10 +2545,10 @@ struct RPCLedgerEntryNormalPathTest : public RPCLedgerEntryTest, static auto generateTestValuesForNormalPathTest() { - auto account1 = getAccountIdWithString(kACCOUNT); - auto account2 = getAccountIdWithString(kACCOUNT2); - ripple::Currency currency; - ripple::to_currency(currency, "USD"); + auto account1 = getAccountIdWithString(kAccount); + auto account2 = getAccountIdWithString(kAccount2); + xrpl::Currency currency; + xrpl::toCurrency(currency, "USD"); return std::vector{ NormalPathTestBundle{ @@ -2559,11 +2558,11 @@ generateTestValuesForNormalPathTest() "binary": true, "index": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256{kINDEX1}, + .expectedIndex = xrpl::uint256{kIndex1}, .mockedEntity = - createAccountRootObject(kACCOUNT2, ripple::lsfGlobalFreeze, 1, 10, 2, kINDEX1, 3) + createAccountRootObject(kAccount2, xrpl::lsfGlobalFreeze, 1, 10, 2, kIndex1, 3) }, NormalPathTestBundle{ .testName = "Payment_channel", @@ -2572,11 +2571,11 @@ generateTestValuesForNormalPathTest() "binary": true, "payment_channel": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256{kINDEX1}, + .expectedIndex = xrpl::uint256{kIndex1}, .mockedEntity = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 200, 300, kINDEX1, 400) + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 200, 300, kIndex1, 400) }, NormalPathTestBundle{ .testName = "Nft_page", @@ -2585,11 +2584,11 @@ generateTestValuesForNormalPathTest() "binary": true, "nft_page": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256{kINDEX1}, + .expectedIndex = xrpl::uint256{kIndex1}, .mockedEntity = createNftTokenPage( - std::vector{std::make_pair(kTOKEN_ID, "www.ok.com")}, + std::vector{std::make_pair(kTokenId, "www.ok.com")}, std::nullopt ) }, @@ -2600,10 +2599,10 @@ generateTestValuesForNormalPathTest() "binary": true, "check": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256{kINDEX1}, - .mockedEntity = createCheckLedgerObject(kACCOUNT, kACCOUNT2) + .expectedIndex = xrpl::uint256{kIndex1}, + .mockedEntity = createCheckLedgerObject(kAccount, kAccount2) }, NormalPathTestBundle{ .testName = "DirectoryIndex", @@ -2612,11 +2611,11 @@ generateTestValuesForNormalPathTest() "binary": true, "directory": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256{kINDEX1}, + .expectedIndex = xrpl::uint256{kIndex1}, .mockedEntity = createOwnerDirLedgerObject( - std::vector{ripple::uint256{kINDEX1}}, kINDEX1 + std::vector{xrpl::uint256{kIndex1}}, kIndex1 ) }, NormalPathTestBundle{ @@ -2626,18 +2625,18 @@ generateTestValuesForNormalPathTest() "binary": true, "offer": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256{kINDEX1}, + .expectedIndex = xrpl::uint256{kIndex1}, .mockedEntity = createOfferLedgerObject( - kACCOUNT, + kAccount, 100, 200, "USD", "XRP", - kACCOUNT2, - ripple::toBase58(ripple::xrpAccount()), - kINDEX1 + kAccount2, + xrpl::toBase58(xrpl::xrpAccount()), + kIndex1 ) }, NormalPathTestBundle{ @@ -2647,10 +2646,10 @@ generateTestValuesForNormalPathTest() "binary": true, "escrow": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256{kINDEX1}, - .mockedEntity = createEscrowLedgerObject(kACCOUNT, kACCOUNT2) + .expectedIndex = xrpl::uint256{kIndex1}, + .mockedEntity = createEscrowLedgerObject(kAccount, kAccount2) }, NormalPathTestBundle{ .testName = "TicketIndex", @@ -2659,10 +2658,10 @@ generateTestValuesForNormalPathTest() "binary": true, "ticket": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256{kINDEX1}, - .mockedEntity = createTicketLedgerObject(kACCOUNT, 0) + .expectedIndex = xrpl::uint256{kIndex1}, + .mockedEntity = createTicketLedgerObject(kAccount, 0) }, NormalPathTestBundle{ .testName = "DepositPreauthIndex", @@ -2671,10 +2670,10 @@ generateTestValuesForNormalPathTest() "binary": true, "deposit_preauth": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256{kINDEX1}, - .mockedEntity = createDepositPreauthLedgerObjectByAuth(kACCOUNT, kACCOUNT2) + .expectedIndex = xrpl::uint256{kIndex1}, + .mockedEntity = createDepositPreauthLedgerObjectByAuth(kAccount, kAccount2) }, NormalPathTestBundle{ .testName = "AccountRoot", @@ -2683,10 +2682,10 @@ generateTestValuesForNormalPathTest() "binary": true, "account_root": "{}" }})JSON", - kACCOUNT + kAccount ), - .expectedIndex = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key, - .mockedEntity = createAccountRootObject(kACCOUNT, 0, 1, 1, 1, kINDEX1, 1) + .expectedIndex = xrpl::keylet::account(getAccountIdWithString(kAccount)).key, + .mockedEntity = createAccountRootObject(kAccount, 0, 1, 1, 1, kIndex1, 1) }, NormalPathTestBundle{ .testName = "DID", @@ -2695,10 +2694,10 @@ generateTestValuesForNormalPathTest() "binary": true, "did": "{}" }})JSON", - kACCOUNT + kAccount ), - .expectedIndex = ripple::keylet::did(getAccountIdWithString(kACCOUNT)).key, - .mockedEntity = createDidObject(kACCOUNT, "mydocument", "myURI", "mydata") + .expectedIndex = xrpl::keylet::did(getAccountIdWithString(kAccount)).key, + .mockedEntity = createDidObject(kAccount, "mydocument", "myURI", "mydata") }, NormalPathTestBundle{ .testName = "DirectoryViaDirRoot", @@ -2710,11 +2709,11 @@ generateTestValuesForNormalPathTest() "sub_index": 2 }} }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::keylet::page(ripple::uint256{kINDEX1}, 2).key, + .expectedIndex = xrpl::keylet::page(xrpl::uint256{kIndex1}, 2).key, .mockedEntity = createOwnerDirLedgerObject( - std::vector{ripple::uint256{kINDEX1}}, kINDEX1 + std::vector{xrpl::uint256{kIndex1}}, kIndex1 ) }, NormalPathTestBundle{ @@ -2727,11 +2726,11 @@ generateTestValuesForNormalPathTest() "sub_index": 2 }} }})JSON", - kACCOUNT + kAccount ), - .expectedIndex = ripple::keylet::page(ripple::keylet::ownerDir(account1), 2).key, + .expectedIndex = xrpl::keylet::page(xrpl::keylet::ownerDir(account1), 2).key, .mockedEntity = createOwnerDirLedgerObject( - std::vector{ripple::uint256{kINDEX1}}, kINDEX1 + std::vector{xrpl::uint256{kIndex1}}, kIndex1 ) }, NormalPathTestBundle{ @@ -2743,12 +2742,12 @@ generateTestValuesForNormalPathTest() "owner": "{}" }} }})JSON", - kACCOUNT + kAccount ), // default sub_index is 0 - .expectedIndex = ripple::keylet::page(ripple::keylet::ownerDir(account1), 0).key, + .expectedIndex = xrpl::keylet::page(xrpl::keylet::ownerDir(account1), 0).key, .mockedEntity = createOwnerDirLedgerObject( - std::vector{ripple::uint256{kINDEX1}}, kINDEX1 + std::vector{xrpl::uint256{kIndex1}}, kIndex1 ) }, NormalPathTestBundle{ @@ -2761,10 +2760,10 @@ generateTestValuesForNormalPathTest() "seq": 1 }} }})JSON", - kACCOUNT + kAccount ), - .expectedIndex = ripple::keylet::escrow(account1, 1).key, - .mockedEntity = createEscrowLedgerObject(kACCOUNT, kACCOUNT2) + .expectedIndex = xrpl::keylet::escrow(account1, 1).key, + .mockedEntity = createEscrowLedgerObject(kAccount, kAccount2) }, NormalPathTestBundle{ .testName = "DepositPreauthByAuth", @@ -2776,11 +2775,11 @@ generateTestValuesForNormalPathTest() "authorized": "{}" }} }})JSON", - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount2 ), - .expectedIndex = ripple::keylet::depositPreauth(account1, account2).key, - .mockedEntity = createDepositPreauthLedgerObjectByAuth(kACCOUNT, kACCOUNT2) + .expectedIndex = xrpl::keylet::depositPreauth(account1, account2).key, + .mockedEntity = createDepositPreauthLedgerObjectByAuth(kAccount, kAccount2) }, NormalPathTestBundle{ .testName = "DepositPreauthByAuthCredentials", @@ -2797,20 +2796,20 @@ generateTestValuesForNormalPathTest() ] }} }})JSON", - kACCOUNT, - kACCOUNT2, - kCREDENTIAL_TYPE + kAccount, + kAccount2, + kCredentialType ), - .expectedIndex = ripple::keylet::depositPreauth( + .expectedIndex = xrpl::keylet::depositPreauth( account1, credentials::createAuthCredentials(createAuthCredentialArray( - std::vector{kACCOUNT2}, - std::vector{kCREDENTIAL_TYPE} + std::vector{kAccount2}, + std::vector{kCredentialType} )) ) .key, .mockedEntity = createDepositPreauthLedgerObjectByAuthCredentials( - kACCOUNT, kACCOUNT2, kCREDENTIAL_TYPE + kAccount, kAccount2, kCredentialType ) }, NormalPathTestBundle{ @@ -2824,22 +2823,22 @@ generateTestValuesForNormalPathTest() "credential_type": "{}" }} }})JSON", - kACCOUNT, - kACCOUNT2, - kCREDENTIAL_TYPE + kAccount, + kAccount2, + kCredentialType ), - .expectedIndex = ripple::keylet::credential( + .expectedIndex = xrpl::keylet::credential( account1, account2, - ripple::Slice( + xrpl::Slice( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::strUnHex(kCREDENTIAL_TYPE)->data(), + xrpl::strUnHex(kCredentialType)->data(), // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::strUnHex(kCREDENTIAL_TYPE)->size() + xrpl::strUnHex(kCredentialType)->size() ) ) .key, - .mockedEntity = createCredentialObject(kACCOUNT, kACCOUNT2, kCREDENTIAL_TYPE) + .mockedEntity = createCredentialObject(kAccount, kAccount2, kCredentialType) }, NormalPathTestBundle{ .testName = "RippleState", @@ -2851,12 +2850,12 @@ generateTestValuesForNormalPathTest() "currency": "USD" }} }})JSON", - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount2 ), - .expectedIndex = ripple::keylet::line(account1, account2, currency).key, + .expectedIndex = xrpl::keylet::trustLine(account1, account2, currency).key, .mockedEntity = createRippleStateLedgerObject( - "USD", kACCOUNT2, 100, kACCOUNT, 10, kACCOUNT2, 20, kINDEX1, 123, 0 + "USD", kAccount2, 100, kAccount, 10, kAccount2, 20, kIndex1, 123, 0 ) }, NormalPathTestBundle{ @@ -2869,10 +2868,10 @@ generateTestValuesForNormalPathTest() "ticket_seq": 2 }} }})JSON", - kACCOUNT + kAccount ), - .expectedIndex = ripple::getTicketIndex(account1, 2), - .mockedEntity = createTicketLedgerObject(kACCOUNT, 0) + .expectedIndex = xrpl::getTicketIndex(account1, 2), + .mockedEntity = createTicketLedgerObject(kAccount, 0) }, NormalPathTestBundle{ .testName = "Offer", @@ -2884,18 +2883,18 @@ generateTestValuesForNormalPathTest() "seq": 2 }} }})JSON", - kACCOUNT + kAccount ), - .expectedIndex = ripple::keylet::offer(account1, 2).key, + .expectedIndex = xrpl::keylet::offer(account1, 2).key, .mockedEntity = createOfferLedgerObject( - kACCOUNT, + kAccount, 100, 200, "USD", "XRP", - kACCOUNT2, - ripple::toBase58(ripple::xrpAccount()), - kINDEX1 + kAccount2, + xrpl::toBase58(xrpl::xrpAccount()), + kIndex1 ) }, NormalPathTestBundle{ @@ -2905,11 +2904,11 @@ generateTestValuesForNormalPathTest() "binary": true, "amm": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256{kINDEX1}, + .expectedIndex = xrpl::uint256{kIndex1}, .mockedEntity = createAmmObject( - kACCOUNT, "XRP", ripple::toBase58(ripple::xrpAccount()), "JPY", kACCOUNT2 + kAccount, "XRP", xrpl::toBase58(xrpl::xrpAccount()), "JPY", kAccount2 ) }, NormalPathTestBundle{ @@ -2928,15 +2927,15 @@ generateTestValuesForNormalPathTest() }} }})JSON", "JPY", - kACCOUNT2 + kAccount2 ), - .expectedIndex = ripple::keylet::amm( - getIssue("XRP", ripple::toBase58(ripple::xrpAccount())), - getIssue("JPY", kACCOUNT2) - ) - .key, + .expectedIndex = + xrpl::keylet::amm( + getIssue("XRP", xrpl::toBase58(xrpl::xrpAccount())), getIssue("JPY", kAccount2) + ) + .key, .mockedEntity = createAmmObject( - kACCOUNT, "XRP", ripple::toBase58(ripple::xrpAccount()), "JPY", kACCOUNT2 + kAccount, "XRP", xrpl::toBase58(xrpl::xrpAccount()), "JPY", kAccount2 ) }, NormalPathTestBundle{ @@ -2957,22 +2956,22 @@ generateTestValuesForNormalPathTest() }} }} }})JSON", - kACCOUNT, - kACCOUNT, - kACCOUNT2, - kACCOUNT3 + kAccount, + kAccount, + kAccount2, + kAccount3 ), - .expectedIndex = ripple::keylet::bridge( - ripple::STXChainBridge( - getAccountIdWithString(kACCOUNT), - ripple::xrpIssue(), - getAccountIdWithString(kACCOUNT2), - getIssue("JPY", kACCOUNT3) + .expectedIndex = xrpl::keylet::bridge( + xrpl::STXChainBridge( + getAccountIdWithString(kAccount), + xrpl::xrpIssue(), + getAccountIdWithString(kAccount2), + getIssue("JPY", kAccount3) ), - ripple::STXChainBridge::ChainType::locking + xrpl::STXChainBridge::ChainType::Locking ) .key, - .mockedEntity = createBridgeObject(kACCOUNT, kACCOUNT, kACCOUNT2, "JPY", kACCOUNT3) + .mockedEntity = createBridgeObject(kAccount, kAccount, kAccount2, "JPY", kAccount3) }, NormalPathTestBundle{ .testName = "BridgeIssuing", @@ -2992,22 +2991,22 @@ generateTestValuesForNormalPathTest() }} }} }})JSON", - kACCOUNT2, - kACCOUNT, - kACCOUNT2, - kACCOUNT3 + kAccount2, + kAccount, + kAccount2, + kAccount3 ), - .expectedIndex = ripple::keylet::bridge( - ripple::STXChainBridge( - getAccountIdWithString(kACCOUNT), - ripple::xrpIssue(), - getAccountIdWithString(kACCOUNT2), - getIssue("JPY", kACCOUNT3) + .expectedIndex = xrpl::keylet::bridge( + xrpl::STXChainBridge( + getAccountIdWithString(kAccount), + xrpl::xrpIssue(), + getAccountIdWithString(kAccount2), + getIssue("JPY", kAccount3) ), - ripple::STXChainBridge::ChainType::issuing + xrpl::STXChainBridge::ChainType::Issuing ) .key, - .mockedEntity = createBridgeObject(kACCOUNT, kACCOUNT, kACCOUNT2, "JPY", kACCOUNT3) + .mockedEntity = createBridgeObject(kAccount, kAccount, kAccount2, "JPY", kAccount3) }, NormalPathTestBundle{ .testName = "XChainOwnedClaimId", @@ -3027,22 +3026,22 @@ generateTestValuesForNormalPathTest() "xchain_owned_claim_id": 10 }} }})JSON", - kACCOUNT, - kACCOUNT2, - kACCOUNT3 + kAccount, + kAccount2, + kAccount3 ), - .expectedIndex = ripple::keylet::xChainClaimID( - ripple::STXChainBridge( - getAccountIdWithString(kACCOUNT), - ripple::xrpIssue(), - getAccountIdWithString(kACCOUNT2), - getIssue("JPY", kACCOUNT3) + .expectedIndex = xrpl::keylet::xChainClaimID( + xrpl::STXChainBridge( + getAccountIdWithString(kAccount), + xrpl::xrpIssue(), + getAccountIdWithString(kAccount2), + getIssue("JPY", kAccount3) ), 10 ) .key, .mockedEntity = createChainOwnedClaimIdObject( - kACCOUNT, kACCOUNT, kACCOUNT2, "JPY", kACCOUNT3, kACCOUNT + kAccount, kAccount, kAccount2, "JPY", kAccount3, kAccount ) }, NormalPathTestBundle{ @@ -3063,22 +3062,22 @@ generateTestValuesForNormalPathTest() "xchain_owned_create_account_claim_id": 10 }} }})JSON", - kACCOUNT, - kACCOUNT2, - kACCOUNT3 + kAccount, + kAccount2, + kAccount3 ), - .expectedIndex = ripple::keylet::xChainCreateAccountClaimID( - ripple::STXChainBridge( - getAccountIdWithString(kACCOUNT), - ripple::xrpIssue(), - getAccountIdWithString(kACCOUNT2), - getIssue("JPY", kACCOUNT3) + .expectedIndex = xrpl::keylet::xChainCreateAccountClaimID( + xrpl::STXChainBridge( + getAccountIdWithString(kAccount), + xrpl::xrpIssue(), + getAccountIdWithString(kAccount2), + getIssue("JPY", kAccount3) ), 10 ) .key, .mockedEntity = createChainOwnedClaimIdObject( - kACCOUNT, kACCOUNT, kACCOUNT2, "JPY", kACCOUNT3, kACCOUNT + kAccount, kAccount, kAccount2, "JPY", kAccount3, kAccount ) }, NormalPathTestBundle{ @@ -3091,20 +3090,20 @@ generateTestValuesForNormalPathTest() "oracle_document_id": 1 }} }})JSON", - kACCOUNT + kAccount ), - .expectedIndex = ripple::keylet::oracle(getAccountIdWithString(kACCOUNT), 1).key, + .expectedIndex = xrpl::keylet::oracle(getAccountIdWithString(kAccount), 1).key, .mockedEntity = createOracleObject( - kACCOUNT, + kAccount, "70726F7669646572", 32u, 1234u, - ripple::Blob(8, 's'), - ripple::Blob(8, 's'), - kRANGE_MAX - 2, - ripple::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"}, + xrpl::Blob(8, 's'), + xrpl::Blob(8, 's'), + kRangeMax - 2, + xrpl::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"}, createPriceDataSeries({createOraclePriceData( - 2e4, ripple::to_currency("XRP"), ripple::to_currency("USD"), 3 + 2e4, xrpl::toCurrency("XRP"), xrpl::toCurrency("USD"), 3 )}) ) }, @@ -3118,20 +3117,20 @@ generateTestValuesForNormalPathTest() "oracle_document_id": "1" }} }})JSON", - kACCOUNT + kAccount ), - .expectedIndex = ripple::keylet::oracle(getAccountIdWithString(kACCOUNT), 1).key, + .expectedIndex = xrpl::keylet::oracle(getAccountIdWithString(kAccount), 1).key, .mockedEntity = createOracleObject( - kACCOUNT, + kAccount, "70726F7669646572", 32u, 1234u, - ripple::Blob(8, 's'), - ripple::Blob(8, 's'), - kRANGE_MAX - 2, - ripple::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"}, + xrpl::Blob(8, 's'), + xrpl::Blob(8, 's'), + kRangeMax - 2, + xrpl::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"}, createPriceDataSeries({createOraclePriceData( - 2e4, ripple::to_currency("XRP"), ripple::to_currency("USD"), 3 + 2e4, xrpl::toCurrency("XRP"), xrpl::toCurrency("USD"), 3 )}) ) }, @@ -3142,20 +3141,20 @@ generateTestValuesForNormalPathTest() "binary": true, "oracle": "{}" }})JSON", - ripple::to_string(ripple::keylet::oracle(getAccountIdWithString(kACCOUNT), 1).key) + xrpl::to_string(xrpl::keylet::oracle(getAccountIdWithString(kAccount), 1).key) ), - .expectedIndex = ripple::keylet::oracle(getAccountIdWithString(kACCOUNT), 1).key, + .expectedIndex = xrpl::keylet::oracle(getAccountIdWithString(kAccount), 1).key, .mockedEntity = createOracleObject( - kACCOUNT, + kAccount, "70726F7669646572", 64u, 4321u, - ripple::Blob(8, 'a'), - ripple::Blob(8, 'a'), - kRANGE_MAX - 4, - ripple::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"}, + xrpl::Blob(8, 'a'), + xrpl::Blob(8, 'a'), + kRangeMax - 4, + xrpl::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"}, createPriceDataSeries({createOraclePriceData( - 1e3, ripple::to_currency("USD"), ripple::to_currency("XRP"), 2 + 1e3, xrpl::toCurrency("USD"), xrpl::toCurrency("XRP"), 2 )}) ) }, @@ -3166,10 +3165,10 @@ generateTestValuesForNormalPathTest() "binary": true, "mpt_issuance": "{}" }})JSON", - ripple::to_string(ripple::makeMptID(2, account1)) + xrpl::to_string(xrpl::makeMptID(2, account1)) ), - .expectedIndex = ripple::keylet::mptIssuance(ripple::makeMptID(2, account1)).key, - .mockedEntity = createMptIssuanceObject(kACCOUNT, 2, "metadata") + .expectedIndex = xrpl::keylet::mptokenIssuance(xrpl::makeMptID(2, account1)).key, + .mockedEntity = createMptIssuanceObject(kAccount, 2, "metadata") }, NormalPathTestBundle{ .testName = "MPTokenViaIndex", @@ -3178,10 +3177,10 @@ generateTestValuesForNormalPathTest() "binary": true, "mptoken": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256{kINDEX1}, - .mockedEntity = createMpTokenObject(kACCOUNT, ripple::makeMptID(2, account1)) + .expectedIndex = xrpl::uint256{kIndex1}, + .mockedEntity = createMpTokenObject(kAccount, xrpl::makeMptID(2, account1)) }, NormalPathTestBundle{ .testName = "MPTokenViaObject", @@ -3193,11 +3192,11 @@ generateTestValuesForNormalPathTest() "mpt_issuance_id": "{}" }} }})JSON", - kACCOUNT, - ripple::to_string(ripple::makeMptID(2, account1)) + kAccount, + xrpl::to_string(xrpl::makeMptID(2, account1)) ), - .expectedIndex = ripple::keylet::mptoken(ripple::makeMptID(2, account1), account1).key, - .mockedEntity = createMpTokenObject(kACCOUNT, ripple::makeMptID(2, account1)) + .expectedIndex = xrpl::keylet::mptoken(xrpl::makeMptID(2, account1), account1).key, + .mockedEntity = createMpTokenObject(kAccount, xrpl::makeMptID(2, account1)) }, NormalPathTestBundle{ .testName = "PermissionedDomainViaString", @@ -3206,12 +3205,11 @@ generateTestValuesForNormalPathTest() "binary": true, "permissioned_domain": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256(kINDEX1), - .mockedEntity = createPermissionedDomainObject( - kACCOUNT, kINDEX1, kRANGE_MAX, 0, ripple::uint256{0}, 0 - ) + .expectedIndex = xrpl::uint256(kIndex1), + .mockedEntity = + createPermissionedDomainObject(kAccount, kIndex1, kRangeMax, 0, xrpl::uint256{0}, 0) }, NormalPathTestBundle{ .testName = "PermissionedDomainViaObject", @@ -3223,18 +3221,17 @@ generateTestValuesForNormalPathTest() "seq": {} }} }})JSON", - kACCOUNT, - kRANGE_MAX + kAccount, + kRangeMax ), - .expectedIndex = ripple::keylet::permissionedDomain( + .expectedIndex = xrpl::keylet::permissionedDomain( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - *ripple::parseBase58(kACCOUNT), - kRANGE_MAX + *xrpl::parseBase58(kAccount), + kRangeMax ) .key, - .mockedEntity = createPermissionedDomainObject( - kACCOUNT, kINDEX1, kRANGE_MAX, 0, ripple::uint256{0}, 0 - ) + .mockedEntity = + createPermissionedDomainObject(kAccount, kIndex1, kRangeMax, 0, xrpl::uint256{0}, 0) }, NormalPathTestBundle{ .testName = "CreateVaultObjectByHexString", @@ -3243,18 +3240,18 @@ generateTestValuesForNormalPathTest() "binary": true, "vault": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256(kINDEX1), + .expectedIndex = xrpl::uint256(kIndex1), .mockedEntity = createVault( - kACCOUNT, - kACCOUNT, - kRANGE_MAX, + kAccount, + kAccount, + kRangeMax, "XRP", - ripple::toBase58(ripple::xrpAccount()), - ripple::uint192(0), + xrpl::toBase58(xrpl::xrpAccount()), + xrpl::uint192(0), 0, - ripple::uint256{0}, + xrpl::uint256{0}, 0 ) }, @@ -3268,22 +3265,21 @@ generateTestValuesForNormalPathTest() "seq": {} }} }})JSON", - kACCOUNT, - kRANGE_MAX + kAccount, + kRangeMax ), .expectedIndex = // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::keylet::vault(*ripple::parseBase58(kACCOUNT), kRANGE_MAX) - .key, + xrpl::keylet::vault(*xrpl::parseBase58(kAccount), kRangeMax).key, .mockedEntity = createVault( - kACCOUNT, - kACCOUNT, - kRANGE_MAX, + kAccount, + kAccount, + kRangeMax, "XRP", - ripple::toBase58(ripple::xrpAccount()), - ripple::uint192(0), + xrpl::toBase58(xrpl::xrpAccount()), + xrpl::uint192(0), 0, - ripple::uint256{0}, + xrpl::uint256{0}, 0 ) }, @@ -3294,11 +3290,11 @@ generateTestValuesForNormalPathTest() "binary": true, "loan_broker": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256(kINDEX1), + .expectedIndex = xrpl::uint256(kIndex1), .mockedEntity = createLoanBroker( - kACCOUNT, kACCOUNT, kRANGE_MAX, ripple::uint256{kINDEX1}, 1, ripple::uint256{0}, 0 + kAccount, kAccount, kRangeMax, xrpl::uint256{kIndex1}, 1, xrpl::uint256{0}, 0 ) }, NormalPathTestBundle{ @@ -3311,17 +3307,17 @@ generateTestValuesForNormalPathTest() "seq": {} }} }})JSON", - kACCOUNT, - kRANGE_MAX + kAccount, + kRangeMax ), - .expectedIndex = ripple::keylet::loanbroker( + .expectedIndex = xrpl::keylet::loanBroker( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - *ripple::parseBase58(kACCOUNT), - kRANGE_MAX + *xrpl::parseBase58(kAccount), + kRangeMax ) .key, .mockedEntity = createLoanBroker( - kACCOUNT, kACCOUNT, kRANGE_MAX, ripple::uint256{kINDEX1}, 1, ripple::uint256{0}, 0 + kAccount, kAccount, kRangeMax, xrpl::uint256{kIndex1}, 1, xrpl::uint256{0}, 0 ) }, NormalPathTestBundle{ @@ -3331,11 +3327,11 @@ generateTestValuesForNormalPathTest() "binary": true, "loan": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256(kINDEX1), + .expectedIndex = xrpl::uint256(kIndex1), .mockedEntity = createLoan( - kACCOUNT, ripple::uint256{kINDEX1}, 1, 1000, 86400, 100, ripple::uint256{0}, 0 + kAccount, xrpl::uint256{kIndex1}, 1, 1000, 86400, 100, xrpl::uint256{0}, 0 ) }, NormalPathTestBundle{ @@ -3348,11 +3344,11 @@ generateTestValuesForNormalPathTest() "loan_seq": 1 }} }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::keylet::loan(ripple::uint256{kINDEX1}, 1).key, + .expectedIndex = xrpl::keylet::loan(xrpl::uint256{kIndex1}, 1).key, .mockedEntity = createLoan( - kACCOUNT, ripple::uint256{kINDEX1}, 1, 1000, 86400, 100, ripple::uint256{0}, 0 + kAccount, xrpl::uint256{kIndex1}, 1, 1000, 86400, 100, xrpl::uint256{0}, 0 ) }, NormalPathTestBundle{ @@ -3362,11 +3358,11 @@ generateTestValuesForNormalPathTest() "binary": true, "delegate": "{}" }})JSON", - kINDEX1 + kIndex1 ), - .expectedIndex = ripple::uint256{kINDEX1}, + .expectedIndex = xrpl::uint256{kIndex1}, .mockedEntity = - createDelegateObject(kACCOUNT, kACCOUNT2, kINDEX1, 0, ripple::uint256{0}, 0) + createDelegateObject(kAccount, kAccount2, kIndex1, 0, xrpl::uint256{0}, 0) }, NormalPathTestBundle{ .testName = "DelegateViaObject", @@ -3378,15 +3374,15 @@ generateTestValuesForNormalPathTest() "authorize": "{}" }} }})JSON", - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount2 ), - .expectedIndex = ripple::keylet::delegate( - getAccountIdWithString(kACCOUNT), getAccountIdWithString(kACCOUNT2) + .expectedIndex = xrpl::keylet::delegate( + getAccountIdWithString(kAccount), getAccountIdWithString(kAccount2) ) .key, .mockedEntity = - createDelegateObject(kACCOUNT, kACCOUNT2, kINDEX1, 0, ripple::uint256{0}, 0) + createDelegateObject(kAccount, kAccount2, kIndex1, 0, xrpl::uint256{0}, 0) }, }; } @@ -3395,7 +3391,7 @@ INSTANTIATE_TEST_CASE_P( RPCLedgerEntryGroup2, RPCLedgerEntryNormalPathTest, ValuesIn(generateTestValuesForNormalPathTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); // Test for normal path @@ -3404,27 +3400,27 @@ TEST_P(RPCLedgerEntryNormalPathTest, NormalPath) { auto const testBundle = GetParam(); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) .WillRepeatedly(Return(ledgerHeader)); - EXPECT_CALL(*backend_, doFetchLedgerObject(testBundle.expectedIndex, kRANGE_MAX, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(testBundle.expectedIndex, kRangeMax, _)) .WillRepeatedly(Return(testBundle.mockedEntity.getSerializer().peekData())); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); auto const& outputJson = output.result.value(); - EXPECT_EQ(outputJson.at("ledger_hash").as_string(), kLEDGER_HASH); - EXPECT_EQ(outputJson.at("ledger_index").as_uint64(), kRANGE_MAX); + EXPECT_EQ(outputJson.at("ledger_hash").as_string(), kLedgerHash); + EXPECT_EQ(outputJson.at("ledger_index").as_uint64(), kRangeMax); EXPECT_EQ( outputJson.at("node_binary").as_string(), - ripple::strHex(testBundle.mockedEntity.getSerializer().peekData()) + xrpl::strHex(testBundle.mockedEntity.getSerializer().peekData()) ); EXPECT_EQ( - ripple::uint256(boost::json::value_to(outputJson.at("index")).data()), + xrpl::uint256(boost::json::value_to(outputJson.at("index")).data()), testBundle.expectedIndex ); }); @@ -3433,7 +3429,7 @@ TEST_P(RPCLedgerEntryNormalPathTest, NormalPath) // this testcase will test the deserialization of ledger entry TEST_F(RPCLedgerEntryTest, BinaryFalse) { - static constexpr auto kOUT = R"JSON({ + static constexpr auto kOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, "validated": true, @@ -3454,58 +3450,58 @@ TEST_F(RPCLedgerEntryTest, BinaryFalse) } })JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) .WillRepeatedly(Return(ledgerHeader)); // return valid ledger entry which can be deserialized auto const ledgerEntry = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 200, 300, kINDEX1, 400); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 200, 300, kIndex1, 400); + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax, _)) .WillRepeatedly(Return(ledgerEntry.getSerializer().peekData())); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "payment_channel": "{}" }})JSON", - kINDEX1 + kIndex1 ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kOUT)); + EXPECT_EQ(*output.result, boost::json::parse(kOut)); }); } TEST_F(RPCLedgerEntryTest, Vault_BinaryFalse) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) .WillRepeatedly(Return(ledgerHeader)); boost::json::object const entry; auto const vault = createVault( - kACCOUNT, - kACCOUNT, - kRANGE_MAX, + kAccount, + kAccount, + kRangeMax, "XRP", - ripple::toBase58(ripple::xrpAccount()), - ripple::uint192(0), + xrpl::toBase58(xrpl::xrpAccount()), + xrpl::uint192(0), 0, - ripple::uint256{1}, + xrpl::uint256{1}, 0 ); auto const vaultKey = // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - ripple::keylet::vault(*ripple::parseBase58(kACCOUNT), kRANGE_MAX).key; + xrpl::keylet::vault(*xrpl::parseBase58(kAccount), kRangeMax).key; - ripple::STLedgerEntry const sle{ - ripple::SerialIter{ + xrpl::STLedgerEntry const sle{ + xrpl::SerialIter{ vault.getSerializer().peekData().data(), vault.getSerializer().peekData().size() }, vaultKey @@ -3516,7 +3512,7 @@ TEST_F(RPCLedgerEntryTest, Vault_BinaryFalse) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "binary": false, @@ -3525,39 +3521,39 @@ TEST_F(RPCLedgerEntryTest, Vault_BinaryFalse) "seq": {} }} }})JSON", - kACCOUNT, - kRANGE_MAX + kAccount, + kRangeMax ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("node").at("Owner").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("node").at("Sequence").as_int64(), kRANGE_MAX); + EXPECT_EQ(output.result->at("node").at("Owner").as_string(), kAccount); + EXPECT_EQ(output.result->at("node").at("Sequence").as_int64(), kRangeMax); }); } TEST_F(RPCLedgerEntryTest, LoanBroker_BinaryFalse) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) .WillRepeatedly(Return(ledgerHeader)); boost::json::object const entry; auto const loanBroker = createLoanBroker( - kACCOUNT, kACCOUNT, kRANGE_MAX, ripple::uint256{kINDEX1}, 1, ripple::uint256{1}, 0 + kAccount, kAccount, kRangeMax, xrpl::uint256{kIndex1}, 1, xrpl::uint256{1}, 0 ); - auto const loanBrokerKey = ripple::keylet::loanbroker( + auto const loanBrokerKey = xrpl::keylet::loanBroker( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - *ripple::parseBase58(kACCOUNT), - kRANGE_MAX + *xrpl::parseBase58(kAccount), + kRangeMax ) .key; - ripple::STLedgerEntry const sle{ - ripple::SerialIter{ + xrpl::STLedgerEntry const sle{ + xrpl::SerialIter{ loanBroker.getSerializer().peekData().data(), loanBroker.getSerializer().peekData().size() }, @@ -3569,7 +3565,7 @@ TEST_F(RPCLedgerEntryTest, LoanBroker_BinaryFalse) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "binary": false, @@ -3578,40 +3574,40 @@ TEST_F(RPCLedgerEntryTest, LoanBroker_BinaryFalse) "seq": {} }} }})JSON", - kACCOUNT, - kRANGE_MAX + kAccount, + kRangeMax ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("node").at("Owner").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("node").at("Sequence").as_int64(), kRANGE_MAX); + EXPECT_EQ(output.result->at("node").at("Owner").as_string(), kAccount); + EXPECT_EQ(output.result->at("node").at("Sequence").as_int64(), kRangeMax); EXPECT_EQ(output.result->at("node").at("LoanSequence").as_int64(), 1); }); } TEST_F(RPCLedgerEntryTest, Loan_BinaryFalse) { - static constexpr auto kLOAN_SEQ = 1; - static constexpr auto kSTART_DATE = 1000; - static constexpr auto kPAYMENT_INTERVAL = 86400; - static constexpr auto kINTEREST_RATE = 100; + static constexpr auto kLoanSeq = 1; + static constexpr auto kStartDate = 1000; + static constexpr auto kPaymentInterval = 86400; + static constexpr auto kInterestRate = 100; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) .WillRepeatedly(Return(ledgerHeader)); boost::json::object const entry; auto const loan = createLoan( - kACCOUNT, - ripple::uint256{kINDEX1}, - kLOAN_SEQ, - kSTART_DATE, - kPAYMENT_INTERVAL, - kINTEREST_RATE, - ripple::uint256{1}, + kAccount, + xrpl::uint256{kIndex1}, + kLoanSeq, + kStartDate, + kPaymentInterval, + kInterestRate, + xrpl::uint256{1}, 0 ); @@ -3620,7 +3616,7 @@ TEST_F(RPCLedgerEntryTest, Loan_BinaryFalse) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "binary": false, @@ -3629,40 +3625,40 @@ TEST_F(RPCLedgerEntryTest, Loan_BinaryFalse) "loan_seq": {} }} }})JSON", - kINDEX1, - kLOAN_SEQ + kIndex1, + kLoanSeq ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("node").at("Borrower").as_string(), kACCOUNT); - EXPECT_EQ(output.result->at("node").at("LoanSequence").as_int64(), kLOAN_SEQ); - EXPECT_EQ(output.result->at("node").at("StartDate").as_int64(), kSTART_DATE); - EXPECT_EQ(output.result->at("node").at("PaymentInterval").as_int64(), kPAYMENT_INTERVAL); + EXPECT_EQ(output.result->at("node").at("Borrower").as_string(), kAccount); + EXPECT_EQ(output.result->at("node").at("LoanSequence").as_int64(), kLoanSeq); + EXPECT_EQ(output.result->at("node").at("StartDate").as_int64(), kStartDate); + EXPECT_EQ(output.result->at("node").at("PaymentInterval").as_int64(), kPaymentInterval); }); } TEST_F(RPCLedgerEntryTest, UnexpectedLedgerType) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) .WillRepeatedly(Return(ledgerHeader)); // return valid ledger entry which can be deserialized auto const ledgerEntry = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 200, 300, kINDEX1, 400); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 200, 300, kIndex1, 400); + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax, _)) .WillRepeatedly(Return(ledgerEntry.getSerializer().peekData())); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "check": "{}" }})JSON", - kINDEX1 + kIndex1 ) ); auto const output = handler.process(req, Context{yield}); @@ -3674,19 +3670,19 @@ TEST_F(RPCLedgerEntryTest, UnexpectedLedgerType) TEST_F(RPCLedgerEntryTest, LedgerNotExistViaIntSequence) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) .WillRepeatedly(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "check": "{}", "ledger_index": {} }})JSON", - kINDEX1, - kRANGE_MAX + kIndex1, + kRangeMax ) ); auto const output = handler.process(req, Context{yield}); @@ -3699,19 +3695,19 @@ TEST_F(RPCLedgerEntryTest, LedgerNotExistViaIntSequence) TEST_F(RPCLedgerEntryTest, LedgerNotExistViaStringSequence) { - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) .WillRepeatedly(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "check": "{}", "ledger_index": "{}" }})JSON", - kINDEX1, - kRANGE_MAX + kIndex1, + kRangeMax ) ); auto const output = handler.process(req, Context{yield}); @@ -3724,19 +3720,19 @@ TEST_F(RPCLedgerEntryTest, LedgerNotExistViaStringSequence) TEST_F(RPCLedgerEntryTest, LedgerNotExistViaHash) { - EXPECT_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + EXPECT_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillRepeatedly(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "check": "{}", "ledger_hash": "{}" }})JSON", - kINDEX1, - kLEDGER_HASH + kIndex1, + kLedgerHash ) ); auto const output = handler.process(req, Context{yield}); @@ -3751,7 +3747,7 @@ TEST_F(RPCLedgerEntryTest, InvalidEntryTypeVersion2) { runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse(R"JSON({})JSON"); + auto const req = boost::json::parse(R"JSON({})JSON"); auto const output = handler.process(req, Context{.yield = yield, .apiVersion = 2}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -3764,7 +3760,7 @@ TEST_F(RPCLedgerEntryTest, InvalidEntryTypeVersion1) { runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse(R"JSON({})JSON"); + auto const req = boost::json::parse(R"JSON({})JSON"); auto const output = handler.process(req, Context{.yield = yield, .apiVersion = 1}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -3795,7 +3791,7 @@ TEST(RPCLedgerEntrySpecTest, DeprecatedFields) // Expected Result: same as BinaryFalse TEST_F(RPCLedgerEntryTest, BinaryFalseIncludeDeleted) { - static constexpr auto kOUT = R"JSON({ + static constexpr auto kOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, "validated": true, @@ -3817,29 +3813,29 @@ TEST_F(RPCLedgerEntryTest, BinaryFalseIncludeDeleted) })JSON"; // return valid ledgerinfo - auto const ledgerinfo = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillRepeatedly(Return(ledgerinfo)); + auto const ledgerinfo = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillRepeatedly(Return(ledgerinfo)); // return valid ledger entry which can be deserialized auto const ledgerEntry = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 200, 300, kINDEX1, 400); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 200, 300, kIndex1, 400); + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax, _)) .WillRepeatedly(Return(ledgerEntry.getSerializer().peekData())); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "index": "{}", "include_deleted": true }})JSON", - kINDEX1 + kIndex1 ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kOUT)); + EXPECT_EQ(*output.result, boost::json::parse(kOut)); }); } @@ -3847,7 +3843,7 @@ TEST_F(RPCLedgerEntryTest, BinaryFalseIncludeDeleted) // Expected Result: return the latest object that is not deleted TEST_F(RPCLedgerEntryTest, LedgerEntryDeleted) { - static constexpr auto kOUT = R"JSON({ + static constexpr auto kOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, "validated": true, @@ -3866,30 +3862,30 @@ TEST_F(RPCLedgerEntryTest, LedgerEntryDeleted) "index": "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD" } })JSON"; - auto const ledgerinfo = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillRepeatedly(Return(ledgerinfo)); + auto const ledgerinfo = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillRepeatedly(Return(ledgerinfo)); // return valid ledger entry which can be deserialized - auto const offer = createNftBuyOffer(kNFT_ID, kACCOUNT); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) + auto const offer = createNftBuyOffer(kNftId, kAccount); + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax, _)) .WillOnce(Return(std::optional{})); - EXPECT_CALL(*backend_, doFetchLedgerObjectSeq(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) - .WillOnce(Return(uint32_t{kRANGE_MAX})); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX - 1, _)) + EXPECT_CALL(*backend_, doFetchLedgerObjectSeq(xrpl::uint256{kIndex1}, kRangeMax, _)) + .WillOnce(Return(uint32_t{kRangeMax})); + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax - 1, _)) .WillOnce(Return(offer.getSerializer().peekData())); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "index": "{}", "include_deleted": true }})JSON", - kINDEX1 + kIndex1 ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kOUT)); + EXPECT_EQ(*output.result, boost::json::parse(kOut)); }); } @@ -3897,24 +3893,24 @@ TEST_F(RPCLedgerEntryTest, LedgerEntryDeleted) // Expected Result: return entryNotFound error TEST_F(RPCLedgerEntryTest, LedgerEntryNotExist) { - auto const ledgerinfo = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillRepeatedly(Return(ledgerinfo)); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) + auto const ledgerinfo = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillRepeatedly(Return(ledgerinfo)); + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax, _)) .WillOnce(Return(std::optional{})); - EXPECT_CALL(*backend_, doFetchLedgerObjectSeq(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) - .WillOnce(Return(uint32_t{kRANGE_MAX})); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX - 1, _)) + EXPECT_CALL(*backend_, doFetchLedgerObjectSeq(xrpl::uint256{kIndex1}, kRangeMax, _)) + .WillOnce(Return(uint32_t{kRangeMax})); + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax - 1, _)) .WillOnce(Return(std::optional{})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "index": "{}", "include_deleted": true }})JSON", - kINDEX1 + kIndex1 ) ); auto const output = handler.process(req, Context{yield}); @@ -3929,7 +3925,7 @@ TEST_F(RPCLedgerEntryTest, LedgerEntryNotExist) // Expected Result: same as BinaryFalse TEST_F(RPCLedgerEntryTest, BinaryFalseIncludeDeleteFalse) { - static constexpr auto kOUT = R"JSON({ + static constexpr auto kOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, "validated": true, @@ -3951,29 +3947,29 @@ TEST_F(RPCLedgerEntryTest, BinaryFalseIncludeDeleteFalse) })JSON"; // return valid ledgerinfo - auto const ledgerinfo = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillRepeatedly(Return(ledgerinfo)); + auto const ledgerinfo = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillRepeatedly(Return(ledgerinfo)); // return valid ledger entry which can be deserialized auto const ledgerEntry = - createPaymentChannelLedgerObject(kACCOUNT, kACCOUNT2, 100, 200, 300, kINDEX1, 400); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) + createPaymentChannelLedgerObject(kAccount, kAccount2, 100, 200, 300, kIndex1, 400); + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax, _)) .WillRepeatedly(Return(ledgerEntry.getSerializer().peekData())); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "payment_channel": "{}", "include_deleted": false }})JSON", - kINDEX1 + kIndex1 ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kOUT)); + EXPECT_EQ(*output.result, boost::json::parse(kOut)); }); } @@ -3981,7 +3977,7 @@ TEST_F(RPCLedgerEntryTest, BinaryFalseIncludeDeleteFalse) // Expected Result: return the latest object that is not deleted (latest object in this test) TEST_F(RPCLedgerEntryTest, ObjectUpdateIncludeDelete) { - static constexpr auto kOUT = R"JSON({ + static constexpr auto kOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, "validated": true, @@ -4011,35 +4007,35 @@ TEST_F(RPCLedgerEntryTest, ObjectUpdateIncludeDelete) })JSON"; // return valid ledgerinfo - auto const ledgerinfo = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillRepeatedly(Return(ledgerinfo)); + auto const ledgerinfo = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillRepeatedly(Return(ledgerinfo)); // return valid ledger entry which can be deserialized auto const line1 = createRippleStateLedgerObject( - "USD", kACCOUNT2, 10, kACCOUNT, 100, kACCOUNT2, 200, kTXN_ID, 123 + "USD", kAccount2, 10, kAccount, 100, kAccount2, 200, kTxnId, 123 ); auto const line2 = createRippleStateLedgerObject( - "USD", kACCOUNT, 10, kACCOUNT2, 100, kACCOUNT, 200, kTXN_ID, 123 + "USD", kAccount, 10, kAccount2, 100, kAccount, 200, kTxnId, 123 ); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax, _)) .WillRepeatedly(Return(line1.getSerializer().peekData())); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX - 1, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax - 1, _)) .WillRepeatedly(Return(line2.getSerializer().peekData())); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "index": "{}", "include_deleted": true }})JSON", - kINDEX1 + kIndex1 ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kOUT)); + EXPECT_EQ(*output.result, boost::json::parse(kOut)); }); } @@ -4047,7 +4043,7 @@ TEST_F(RPCLedgerEntryTest, ObjectUpdateIncludeDelete) // Expected Result: return the latest object that is not deleted TEST_F(RPCLedgerEntryTest, ObjectDeletedPreviously) { - static constexpr auto kOUT = R"JSON({ + static constexpr auto kOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, "validated": true, @@ -4066,30 +4062,30 @@ TEST_F(RPCLedgerEntryTest, ObjectDeletedPreviously) "index": "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD" } })JSON"; - auto const ledgerinfo = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillRepeatedly(Return(ledgerinfo)); + auto const ledgerinfo = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillRepeatedly(Return(ledgerinfo)); // return valid ledger entry which can be deserialized - auto const offer = createNftBuyOffer(kNFT_ID, kACCOUNT); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) + auto const offer = createNftBuyOffer(kNftId, kAccount); + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax, _)) .WillOnce(Return(std::optional{})); - EXPECT_CALL(*backend_, doFetchLedgerObjectSeq(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) - .WillOnce(Return(uint32_t{kRANGE_MAX - 4})); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX - 5, _)) + EXPECT_CALL(*backend_, doFetchLedgerObjectSeq(xrpl::uint256{kIndex1}, kRangeMax, _)) + .WillOnce(Return(uint32_t{kRangeMax - 4})); + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax - 5, _)) .WillOnce(Return(offer.getSerializer().peekData())); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "index": "{}", "include_deleted": true }})JSON", - kINDEX1 + kIndex1 ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kOUT)); + EXPECT_EQ(*output.result, boost::json::parse(kOut)); }); } @@ -4097,22 +4093,22 @@ TEST_F(RPCLedgerEntryTest, ObjectDeletedPreviously) // Expected Result: return entryNotFound error TEST_F(RPCLedgerEntryTest, ObjectSeqNotExist) { - auto const ledgerinfo = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillRepeatedly(Return(ledgerinfo)); - EXPECT_CALL(*backend_, doFetchLedgerObject(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) + auto const ledgerinfo = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillRepeatedly(Return(ledgerinfo)); + EXPECT_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kIndex1}, kRangeMax, _)) .WillOnce(Return(std::optional{})); - EXPECT_CALL(*backend_, doFetchLedgerObjectSeq(ripple::uint256{kINDEX1}, kRANGE_MAX, _)) + EXPECT_CALL(*backend_, doFetchLedgerObjectSeq(xrpl::uint256{kIndex1}, kRangeMax, _)) .WillOnce(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "index": "{}", "include_deleted": true }})JSON", - kINDEX1 + kIndex1 ) ); auto const output = handler.process(req, Context{yield}); @@ -4126,7 +4122,7 @@ TEST_F(RPCLedgerEntryTest, ObjectSeqNotExist) // this testcase will test the if response includes synthetic mpt_issuance_id TEST_F(RPCLedgerEntryTest, SyntheticMPTIssuanceID) { - static constexpr auto kOUT = R"JSON({ + static constexpr auto kOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, "validated": true, @@ -4146,31 +4142,31 @@ TEST_F(RPCLedgerEntryTest, SyntheticMPTIssuanceID) } })JSON"; - auto const mptId = ripple::makeMptID(2, getAccountIdWithString(kACCOUNT)); + auto const mptId = xrpl::makeMptID(2, getAccountIdWithString(kAccount)); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) .WillRepeatedly(Return(ledgerHeader)); // return valid ledger entry which can be deserialized - auto const ledgerEntry = createMptIssuanceObject(kACCOUNT, 2, "metadata"); + auto const ledgerEntry = createMptIssuanceObject(kAccount, 2, "metadata"); EXPECT_CALL( - *backend_, doFetchLedgerObject(ripple::keylet::mptIssuance(mptId).key, kRANGE_MAX, _) + *backend_, doFetchLedgerObject(xrpl::keylet::mptokenIssuance(mptId).key, kRangeMax, _) ) .WillRepeatedly(Return(ledgerEntry.getSerializer().peekData())); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance": "{}" }})JSON", - ripple::to_string(mptId) + xrpl::to_string(mptId) ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kOUT)); + EXPECT_EQ(*output.result, boost::json::parse(kOut)); }); } diff --git a/tests/unit/rpc/handlers/LedgerIndexTests.cpp b/tests/unit/rpc/handlers/LedgerIndexTests.cpp index db61458cf..4224dba07 100644 --- a/tests/unit/rpc/handlers/LedgerIndexTests.cpp +++ b/tests/unit/rpc/handlers/LedgerIndexTests.cpp @@ -12,34 +12,32 @@ #include #include -#include #include #include namespace { -constexpr auto kRANGE_MIN = 10; -constexpr auto kRANGE_MAX = 30; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kRangeMin = 10; +constexpr auto kRangeMax = 30; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; } // namespace using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; struct RPCLedgerIndexTest : HandlerBaseTestStrict { RPCLedgerIndexTest() { - backend_->setRange(kRANGE_MIN, kRANGE_MAX); + backend_->setRange(kRangeMin, kRangeMax); } }; TEST_F(RPCLedgerIndexTest, DateStrNotValid) { auto const handler = AnyHandler{LedgerIndexHandler{backend_}}; - auto const req = json::parse(R"JSON({"date": "not_a_number"})JSON"); + auto const req = boost::json::parse(R"JSON({"date": "not_a_number"})JSON"); runSpawn([&](auto yield) { auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); @@ -51,16 +49,16 @@ TEST_F(RPCLedgerIndexTest, DateStrNotValid) TEST_F(RPCLedgerIndexTest, NoDateGiven) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX, 5); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillOnce(Return(ledgerHeader)); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax, 5); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillOnce(Return(ledgerHeader)); auto const handler = AnyHandler{LedgerIndexHandler{backend_}}; - auto const req = json::parse(R"JSON({})JSON"); + auto const req = boost::json::parse(R"JSON({})JSON"); runSpawn([&](auto yield) { auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("ledger_index").as_uint64(), kRANGE_MAX); - EXPECT_EQ(output.result->at("ledger_hash").as_string(), kLEDGER_HASH); + EXPECT_EQ(output.result->at("ledger_index").as_uint64(), kRangeMax); + EXPECT_EQ(output.result->at("ledger_hash").as_string(), kLedgerHash); EXPECT_TRUE(output.result->as_object().contains("closed")); }); } @@ -68,11 +66,11 @@ TEST_F(RPCLedgerIndexTest, NoDateGiven) TEST_F(RPCLedgerIndexTest, EarlierThanMinLedger) { auto const handler = AnyHandler{LedgerIndexHandler{backend_}}; - auto const req = json::parse(R"JSON({"date": "2024-06-25T12:23:05Z"})JSON"); + auto const req = boost::json::parse(R"JSON({"date": "2024-06-25T12:23:05Z"})JSON"); auto const ledgerHeader = createLedgerHeaderWithUnixTime( - kLEDGER_HASH, kRANGE_MIN, 1719318190 + kLedgerHash, kRangeMin, 1719318190 ); //"2024-06-25T12:23:10Z" - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MIN, _)).WillOnce(Return(ledgerHeader)); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMin, _)).WillOnce(Return(ledgerHeader)); runSpawn([&](auto yield) { auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); @@ -86,11 +84,11 @@ TEST_F(RPCLedgerIndexTest, ChangeTimeZone) // Note: setenv/unsetenv are included with but misc-include-cleaner still angry setenv("TZ", "EST+5", 1); // NOLINT(misc-include-cleaner) auto const handler = AnyHandler{LedgerIndexHandler{backend_}}; - auto const req = json::parse(R"JSON({"date": "2024-06-25T12:23:05Z"})JSON"); + auto const req = boost::json::parse(R"JSON({"date": "2024-06-25T12:23:05Z"})JSON"); auto const ledgerHeader = createLedgerHeaderWithUnixTime( - kLEDGER_HASH, kRANGE_MIN, 1719318190 + kLedgerHash, kRangeMin, 1719318190 ); //"2024-06-25T12:23:10Z" - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MIN, _)).WillOnce(Return(ledgerHeader)); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMin, _)).WillOnce(Return(ledgerHeader)); runSpawn([&](auto yield) { auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); @@ -117,19 +115,19 @@ public: return std::vector{ {.testName = "LaterThanMaxLedger", .json = R"JSON({"date": "2024-06-25T12:23:55Z"})JSON", - .expectedLedgerIndex = kRANGE_MAX, + .expectedLedgerIndex = kRangeMax, .closeTimeIso = "2024-06-25T12:23:50Z"}, {.testName = "GreaterThanMinLedger", .json = R"JSON({"date": "2024-06-25T12:23:11Z"})JSON", - .expectedLedgerIndex = kRANGE_MIN, + .expectedLedgerIndex = kRangeMin, .closeTimeIso = "2024-06-25T12:23:10Z"}, {.testName = "IsMinLedger", .json = R"JSON({"date": "2024-06-25T12:23:10Z"})JSON", - .expectedLedgerIndex = kRANGE_MIN, + .expectedLedgerIndex = kRangeMin, .closeTimeIso = "2024-06-25T12:23:10Z"}, {.testName = "IsMaxLedger", .json = R"JSON({"date": "2024-06-25T12:23:50Z"})JSON", - .expectedLedgerIndex = kRANGE_MAX, + .expectedLedgerIndex = kRangeMax, .closeTimeIso = "2024-06-25T12:23:50Z"}, {.testName = "IsMidLedger", .json = R"JSON({"date": "2024-06-25T12:23:30Z"})JSON", @@ -147,32 +145,32 @@ INSTANTIATE_TEST_CASE_P( RPCLedgerIndexTestsGroup, LedgerIndexTests, ValuesIn(LedgerIndexTests::generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(LedgerIndexTests, SearchFromLedgerRange) { auto const testBundle = GetParam(); - auto const jv = json::parse(testBundle.json).as_object(); + auto const jv = boost::json::parse(testBundle.json).as_object(); // start from 1719318190 , which is the unix time for 2024-06-25T12:23:10Z to // 2024-06-25T12:23:50Z with step 2 - for (uint32_t i = kRANGE_MIN; i <= kRANGE_MAX; i++) { + for (uint32_t i = kRangeMin; i <= kRangeMax; i++) { auto const ledgerHeader = - createLedgerHeaderWithUnixTime(kLEDGER_HASH, i, 1719318190 + (2 * (i - kRANGE_MIN))); - auto const exactNumberOfCalls = i == kRANGE_MIN ? Exactly(3) : Exactly(2); + createLedgerHeaderWithUnixTime(kLedgerHash, i, 1719318190 + (2 * (i - kRangeMin))); + auto const exactNumberOfCalls = i == kRangeMin ? Exactly(3) : Exactly(2); EXPECT_CALL(*backend_, fetchLedgerBySequence(i, _)) .Times(i == testBundle.expectedLedgerIndex ? exactNumberOfCalls : AtMost(1)) .WillRepeatedly(Return(ledgerHeader)); } auto const handler = AnyHandler{LedgerIndexHandler{backend_}}; - auto const req = json::parse(testBundle.json); + auto const req = boost::json::parse(testBundle.json); runSpawn([&](auto yield) { auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ(output.result->at("ledger_index").as_uint64(), testBundle.expectedLedgerIndex); - EXPECT_EQ(output.result->at("ledger_hash").as_string(), kLEDGER_HASH); + EXPECT_EQ(output.result->at("ledger_hash").as_string(), kLedgerHash); EXPECT_EQ(output.result->at("closed").as_string(), testBundle.closeTimeIso); }); } diff --git a/tests/unit/rpc/handlers/LedgerRangeTests.cpp b/tests/unit/rpc/handlers/LedgerRangeTests.cpp index a5d57b001..8b9e0ad5c 100644 --- a/tests/unit/rpc/handlers/LedgerRangeTests.cpp +++ b/tests/unit/rpc/handlers/LedgerRangeTests.cpp @@ -8,13 +8,12 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kRANGE_MIN = 10; -constexpr auto kRANGE_MAX = 30; +constexpr auto kRangeMin = 10; +constexpr auto kRangeMax = 30; } // namespace @@ -23,29 +22,29 @@ class RPCLedgerRangeTest : public HandlerBaseTest {}; TEST_F(RPCLedgerRangeTest, LedgerRangeMinMaxSame) { runSpawn([this](auto yield) { - backend_->updateRange(kRANGE_MIN); + backend_->updateRange(kRangeMin); auto const handler = AnyHandler{LedgerRangeHandler{backend_}}; - auto const req = json::parse("{}"); + auto const req = boost::json::parse("{}"); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); auto const json = output.result.value(); - EXPECT_EQ(json.at("ledger_index_min").as_uint64(), kRANGE_MIN); - EXPECT_EQ(json.at("ledger_index_max").as_uint64(), kRANGE_MIN); + EXPECT_EQ(json.at("ledger_index_min").as_uint64(), kRangeMin); + EXPECT_EQ(json.at("ledger_index_max").as_uint64(), kRangeMin); }); } TEST_F(RPCLedgerRangeTest, LedgerRangeFullySet) { runSpawn([this](auto yield) { - backend_->setRange(kRANGE_MIN, kRANGE_MAX); + backend_->setRange(kRangeMin, kRangeMax); auto const handler = AnyHandler{LedgerRangeHandler{backend_}}; - auto const req = json::parse("{}"); + auto const req = boost::json::parse("{}"); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); auto const json = output.result.value(); - EXPECT_EQ(json.at("ledger_index_min").as_uint64(), kRANGE_MIN); - EXPECT_EQ(json.at("ledger_index_max").as_uint64(), kRANGE_MAX); + EXPECT_EQ(json.at("ledger_index_min").as_uint64(), kRangeMin); + EXPECT_EQ(json.at("ledger_index_max").as_uint64(), kRangeMax); }); } diff --git a/tests/unit/rpc/handlers/LedgerTests.cpp b/tests/unit/rpc/handlers/LedgerTests.cpp index 0a40c7322..1b04f60af 100644 --- a/tests/unit/rpc/handlers/LedgerTests.cpp +++ b/tests/unit/rpc/handlers/LedgerTests.cpp @@ -29,28 +29,27 @@ namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kINDEX1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; -constexpr auto kINDEX2 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515B1"; -constexpr auto kCURRENCY = "0158415500000000C1F76FF6ECB0BAC600000000"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kIndex1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; +constexpr auto kIndex2 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515B1"; +constexpr auto kCurrency = "0158415500000000C1F76FF6ECB0BAC600000000"; -constexpr auto kRANGE_MIN = 10; -constexpr auto kRANGE_MAX = 30; -constexpr auto kAPI_VERSION = 2; +constexpr auto kRangeMin = 10; +constexpr auto kRangeMax = 30; +constexpr auto kApiVersion = 2; } // namespace using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; struct RPCLedgerHandlerTest : HandlerBaseTest { RPCLedgerHandlerTest() { - backend_->setRange(kRANGE_MIN, kRANGE_MAX); + backend_->setRange(kRangeMin, kRangeMax); } protected: @@ -166,7 +165,7 @@ INSTANTIATE_TEST_CASE_P( RPCLedgerGroup1, LedgerParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(LedgerParameterTest, InvalidParams) @@ -174,7 +173,7 @@ TEST_P(LedgerParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -186,16 +185,16 @@ TEST_P(LedgerParameterTest, InvalidParams) TEST_F(RPCLedgerHandlerTest, LedgerNotExistViaIntSequence) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(std::nullopt)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "ledger_index": {} }})JSON", - kRANGE_MAX + kRangeMax ) ); auto const output = handler.process(req, Context{yield}); @@ -209,16 +208,16 @@ TEST_F(RPCLedgerHandlerTest, LedgerNotExistViaIntSequence) TEST_F(RPCLedgerHandlerTest, LedgerNotExistViaStringSequence) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(std::nullopt)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "ledger_index": "{}" }})JSON", - kRANGE_MAX + kRangeMax ) ); auto const output = handler.process(req, Context{yield}); @@ -232,17 +231,17 @@ TEST_F(RPCLedgerHandlerTest, LedgerNotExistViaStringSequence) TEST_F(RPCLedgerHandlerTest, LedgerNotExistViaHash) { EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "ledger_hash": "{}" }})JSON", - kLEDGER_HASH + kLedgerHash ) ); auto const output = handler.process(req, Context{yield}); @@ -255,7 +254,7 @@ TEST_F(RPCLedgerHandlerTest, LedgerNotExistViaHash) TEST_F(RPCLedgerHandlerTest, Default) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -276,31 +275,31 @@ TEST_F(RPCLedgerHandlerTest, Default) } })JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(ledgerHeader)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse("{}"); + auto const req = boost::json::parse("{}"); auto output = handler.process(req, Context{yield}); ASSERT_TRUE(output); // remove human readable time, it is slightly different cross the platform EXPECT_EQ(output.result->as_object().at("ledger").as_object().erase("close_time_human"), 1); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } // fields not supported for specific value can be set to its default value TEST_F(RPCLedgerHandlerTest, ConditionallyNotSupportedFieldsDefaultValue) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)) + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)) .WillRepeatedly(Return(ledgerHeader)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "full": false, "accounts": false, @@ -314,13 +313,13 @@ TEST_F(RPCLedgerHandlerTest, ConditionallyNotSupportedFieldsDefaultValue) TEST_F(RPCLedgerHandlerTest, QueryViaLedgerIndex) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); ON_CALL(*backend_, fetchLedgerBySequence(15, _)).WillByDefault(Return(ledgerHeader)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse(R"JSON({"ledger_index": 15})JSON"); + auto const req = boost::json::parse(R"JSON({"ledger_index": 15})JSON"); auto output = handler.process(req, Context{yield}); ASSERT_TRUE(output); EXPECT_TRUE(output.result->as_object().contains("ledger")); @@ -329,14 +328,15 @@ TEST_F(RPCLedgerHandlerTest, QueryViaLedgerIndex) TEST_F(RPCLedgerHandlerTest, QueryViaLedgerHash) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kINDEX1}, _)) + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kIndex1}, _)) .WillByDefault(Return(ledgerHeader)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse(fmt::format(R"JSON({{"ledger_hash": "{}" }})JSON", kINDEX1)); + auto const req = + boost::json::parse(fmt::format(R"JSON({{"ledger_hash": "{}" }})JSON", kIndex1)); auto output = handler.process(req, Context{yield}); ASSERT_TRUE(output); EXPECT_TRUE(output.result->as_object().contains("ledger")); @@ -345,7 +345,7 @@ TEST_F(RPCLedgerHandlerTest, QueryViaLedgerHash) TEST_F(RPCLedgerHandlerTest, BinaryTrue) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -356,26 +356,26 @@ TEST_F(RPCLedgerHandlerTest, BinaryTrue) } })JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(ledgerHeader)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "binary": true })JSON" ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCLedgerHandlerTest, TransactionsExpandBinary) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -396,25 +396,25 @@ TEST_F(RPCLedgerHandlerTest, TransactionsExpandBinary) } })JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(ledgerHeader)); TransactionAndMetadata t1; - t1.transaction = createPaymentTransactionObject(kACCOUNT, kACCOUNT2, 100, 3, kRANGE_MAX) + t1.transaction = createPaymentTransactionObject(kAccount, kAccount2, 100, 3, kRangeMax) .getSerializer() .peekData(); t1.metadata = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, 110, 30).getSerializer().peekData(); - t1.ledgerSequence = kRANGE_MAX; + createPaymentTransactionMetaObject(kAccount, kAccount2, 110, 30).getSerializer().peekData(); + t1.ledgerSequence = kRangeMax; EXPECT_CALL(*backend_, fetchAllTransactionsInLedger).Times(1); - ON_CALL(*backend_, fetchAllTransactionsInLedger(kRANGE_MAX, _)) + ON_CALL(*backend_, fetchAllTransactionsInLedger(kRangeMax, _)) .WillByDefault(Return(std::vector{t1, t1})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "binary": true, "expand": true, @@ -423,13 +423,13 @@ TEST_F(RPCLedgerHandlerTest, TransactionsExpandBinary) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCLedgerHandlerTest, TransactionsExpandBinaryV2) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -452,23 +452,23 @@ TEST_F(RPCLedgerHandlerTest, TransactionsExpandBinaryV2) } })JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillOnce(Return(ledgerHeader)); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillOnce(Return(ledgerHeader)); TransactionAndMetadata t1; - t1.transaction = createPaymentTransactionObject(kACCOUNT, kACCOUNT2, 100, 3, kRANGE_MAX) + t1.transaction = createPaymentTransactionObject(kAccount, kAccount2, 100, 3, kRangeMax) .getSerializer() .peekData(); t1.metadata = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, 110, 30).getSerializer().peekData(); - t1.ledgerSequence = kRANGE_MAX; + createPaymentTransactionMetaObject(kAccount, kAccount2, 110, 30).getSerializer().peekData(); + t1.ledgerSequence = kRangeMax; - EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kRANGE_MAX, _)) + EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kRangeMax, _)) .WillOnce(Return(std::vector{t1, t1})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "binary": true, "expand": true, @@ -476,15 +476,15 @@ TEST_F(RPCLedgerHandlerTest, TransactionsExpandBinaryV2) })JSON" ); auto const output = - handler.process(req, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + handler.process(req, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCLedgerHandlerTest, TransactionsExpandNotBinary) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -543,25 +543,25 @@ TEST_F(RPCLedgerHandlerTest, TransactionsExpandNotBinary) } })JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(ledgerHeader)); TransactionAndMetadata t1; - t1.transaction = createPaymentTransactionObject(kACCOUNT, kACCOUNT2, 100, 3, kRANGE_MAX) + t1.transaction = createPaymentTransactionObject(kAccount, kAccount2, 100, 3, kRangeMax) .getSerializer() .peekData(); t1.metadata = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, 110, 30).getSerializer().peekData(); - t1.ledgerSequence = kRANGE_MAX; + createPaymentTransactionMetaObject(kAccount, kAccount2, 110, 30).getSerializer().peekData(); + t1.ledgerSequence = kRangeMax; EXPECT_CALL(*backend_, fetchAllTransactionsInLedger).Times(1); - ON_CALL(*backend_, fetchAllTransactionsInLedger(kRANGE_MAX, _)) + ON_CALL(*backend_, fetchAllTransactionsInLedger(kRangeMax, _)) .WillByDefault(Return(std::vector{t1})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "binary": false, "expand": true, @@ -572,13 +572,13 @@ TEST_F(RPCLedgerHandlerTest, TransactionsExpandNotBinary) ASSERT_TRUE(output); // remove human readable time, it is slightly different cross the platform EXPECT_EQ(output.result->as_object().at("ledger").as_object().erase("close_time_human"), 1); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCLedgerHandlerTest, TransactionsExpandNotBinaryV2) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -642,72 +642,71 @@ TEST_F(RPCLedgerHandlerTest, TransactionsExpandNotBinaryV2) } })JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillOnce(Return(ledgerHeader)); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillOnce(Return(ledgerHeader)); TransactionAndMetadata t1; - t1.transaction = createPaymentTransactionObject(kACCOUNT, kACCOUNT2, 100, 3, kRANGE_MAX) + t1.transaction = createPaymentTransactionObject(kAccount, kAccount2, 100, 3, kRangeMax) .getSerializer() .peekData(); t1.metadata = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, 110, 30).getSerializer().peekData(); - t1.ledgerSequence = kRANGE_MAX; + createPaymentTransactionMetaObject(kAccount, kAccount2, 110, 30).getSerializer().peekData(); + t1.ledgerSequence = kRangeMax; - EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kRANGE_MAX, _)) + EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kRangeMax, _)) .WillOnce(Return(std::vector{t1})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "binary": false, "expand": true, "transactions": true })JSON" ); - auto output = handler.process(req, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + auto output = handler.process(req, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_TRUE(output); // remove human readable time, it is slightly different cross the platform EXPECT_EQ(output.result->as_object().at("ledger").as_object().erase("close_time_human"), 1); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCLedgerHandlerTest, TwoRequestInARowTransactionsExpandNotBinaryV2) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillOnce(Return(ledgerHeader)); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillOnce(Return(ledgerHeader)); - auto const ledgerHeader2 = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX - 1, 10); - EXPECT_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX - 1, _)) - .WillOnce(Return(ledgerHeader2)); + auto const ledgerHeader2 = createLedgerHeader(kLedgerHash, kRangeMax - 1, 10); + EXPECT_CALL(*backend_, fetchLedgerBySequence(kRangeMax - 1, _)).WillOnce(Return(ledgerHeader2)); TransactionAndMetadata t1; - t1.transaction = createPaymentTransactionObject(kACCOUNT, kACCOUNT2, 100, 3, kRANGE_MAX) + t1.transaction = createPaymentTransactionObject(kAccount, kAccount2, 100, 3, kRangeMax) .getSerializer() .peekData(); t1.metadata = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, 110, 30).getSerializer().peekData(); - t1.ledgerSequence = kRANGE_MAX; + createPaymentTransactionMetaObject(kAccount, kAccount2, 110, 30).getSerializer().peekData(); + t1.ledgerSequence = kRangeMax; - EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kRANGE_MAX, _)) + EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kRangeMax, _)) .WillOnce(Return(std::vector{t1})); - EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kRANGE_MAX - 1, _)) + EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kRangeMax - 1, _)) .WillOnce(Return(std::vector{t1})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "binary": false, "expand": true, "transactions": true })JSON" ); - auto output = handler.process(req, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + auto output = handler.process(req, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_TRUE(output); - auto const req2 = json::parse( + auto const req2 = boost::json::parse( fmt::format( R"JSON({{ "binary": false, @@ -715,10 +714,10 @@ TEST_F(RPCLedgerHandlerTest, TwoRequestInARowTransactionsExpandNotBinaryV2) "transactions": true, "ledger_index": {} }})JSON", - kRANGE_MAX - 1 + kRangeMax - 1 ) ); - auto output2 = handler.process(req2, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + auto output2 = handler.process(req2, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_TRUE(output2); EXPECT_NE( output.result->at("ledger").at("transactions").as_array()[0].at("close_time_iso"), @@ -729,17 +728,17 @@ TEST_F(RPCLedgerHandlerTest, TwoRequestInARowTransactionsExpandNotBinaryV2) TEST_F(RPCLedgerHandlerTest, TransactionsNotExpand) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchAllTransactionHashesInLedger).Times(1); - ON_CALL(*backend_, fetchAllTransactionHashesInLedger(kRANGE_MAX, _)) - .WillByDefault(Return(std::vector{ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}})); + ON_CALL(*backend_, fetchAllTransactionHashesInLedger(kRangeMax, _)) + .WillByDefault(Return(std::vector{xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "transactions": true })JSON" @@ -748,14 +747,14 @@ TEST_F(RPCLedgerHandlerTest, TransactionsNotExpand) ASSERT_TRUE(output); EXPECT_EQ( output.result->as_object().at("ledger").at("transactions"), - json::parse(fmt::format(R"JSON(["{}", "{}"])JSON", kINDEX1, kINDEX2)) + boost::json::parse(fmt::format(R"JSON(["{}", "{}"])JSON", kIndex1, kIndex2)) ); }); } TEST_F(RPCLedgerHandlerTest, DiffNotBinary) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON([ { "object_id": "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515B1", @@ -778,44 +777,44 @@ TEST_F(RPCLedgerHandlerTest, DiffNotBinary) } ])JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(ledgerHeader)); std::vector los; EXPECT_CALL(*backend_, fetchLedgerDiff).Times(1); los.push_back( - LedgerObject{.key = ripple::uint256{kINDEX2}, .blob = Blob{}} + LedgerObject{.key = xrpl::uint256{kIndex2}, .blob = Blob{}} ); // NOLINT(modernize-use-emplace) los.push_back( LedgerObject{ - .key = ripple::uint256{kINDEX1}, - .blob = createAccountRootObject(kACCOUNT, ripple::lsfGlobalFreeze, 1, 10, 2, kINDEX1, 3) + .key = xrpl::uint256{kIndex1}, + .blob = createAccountRootObject(kAccount, xrpl::lsfGlobalFreeze, 1, 10, 2, kIndex1, 3) .getSerializer() .peekData() } ); - ON_CALL(*backend_, fetchLedgerDiff(kRANGE_MAX, _)).WillByDefault(Return(los)); + ON_CALL(*backend_, fetchLedgerDiff(kRangeMax, _)).WillByDefault(Return(los)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "diff": true })JSON" ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("ledger").at("diff"), json::parse(kEXPECTED_OUT)); + EXPECT_EQ(output.result->at("ledger").at("diff"), boost::json::parse(kExpectedOut)); }); } TEST_F(RPCLedgerHandlerTest, DiffBinary) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON([ { "object_id": "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515B1", @@ -827,31 +826,31 @@ TEST_F(RPCLedgerHandlerTest, DiffBinary) } ])JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(ledgerHeader)); std::vector los; EXPECT_CALL(*backend_, fetchLedgerDiff).Times(1); los.push_back( - LedgerObject{.key = ripple::uint256{kINDEX2}, .blob = Blob{}} + LedgerObject{.key = xrpl::uint256{kIndex2}, .blob = Blob{}} ); // NOLINT(modernize-use-emplace) los.push_back( LedgerObject{ - .key = ripple::uint256{kINDEX1}, - .blob = createAccountRootObject(kACCOUNT, ripple::lsfGlobalFreeze, 1, 10, 2, kINDEX1, 3) + .key = xrpl::uint256{kIndex1}, + .blob = createAccountRootObject(kAccount, xrpl::lsfGlobalFreeze, 1, 10, 2, kIndex1, 3) .getSerializer() .peekData() } ); - ON_CALL(*backend_, fetchLedgerDiff(kRANGE_MAX, _)).WillByDefault(Return(los)); + ON_CALL(*backend_, fetchLedgerDiff(kRangeMax, _)).WillByDefault(Return(los)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "diff": true, "binary": true @@ -859,13 +858,13 @@ TEST_F(RPCLedgerHandlerTest, DiffBinary) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("ledger").at("diff"), json::parse(kEXPECTED_OUT)); + EXPECT_EQ(output.result->at("ledger").at("diff"), boost::json::parse(kExpectedOut)); }); } TEST_F(RPCLedgerHandlerTest, OwnerFundsEmpty) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -924,25 +923,25 @@ TEST_F(RPCLedgerHandlerTest, OwnerFundsEmpty) } })JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(ledgerHeader)); TransactionAndMetadata t1; - t1.transaction = createPaymentTransactionObject(kACCOUNT, kACCOUNT2, 100, 3, kRANGE_MAX) + t1.transaction = createPaymentTransactionObject(kAccount, kAccount2, 100, 3, kRangeMax) .getSerializer() .peekData(); t1.metadata = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, 110, 30).getSerializer().peekData(); - t1.ledgerSequence = kRANGE_MAX; + createPaymentTransactionMetaObject(kAccount, kAccount2, 110, 30).getSerializer().peekData(); + t1.ledgerSequence = kRangeMax; EXPECT_CALL(*backend_, fetchAllTransactionsInLedger).Times(1); - ON_CALL(*backend_, fetchAllTransactionsInLedger(kRANGE_MAX, _)) + ON_CALL(*backend_, fetchAllTransactionsInLedger(kRangeMax, _)) .WillByDefault(Return(std::vector{t1})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "binary": false, "expand": true, @@ -954,13 +953,13 @@ TEST_F(RPCLedgerHandlerTest, OwnerFundsEmpty) ASSERT_TRUE(output); // remove human readable time, it is slightly different cross the platform EXPECT_EQ(output.result->as_object().at("ledger").as_object().erase("close_time_human"), 1); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCLedgerHandlerTest, OwnerFundsTrueBinaryFalse) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "ledger": { "account_hash": "0000000000000000000000000000000000000000000000000000000000000000", @@ -1017,46 +1016,46 @@ TEST_F(RPCLedgerHandlerTest, OwnerFundsTrueBinaryFalse) "validated": true })JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(ledgerHeader)); // account doFetchLedgerObject - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; auto const accountObject = createAccountRootObject( - kACCOUNT, 0, kRANGE_MAX, 200 /*balance*/, 2 /*owner object*/, kINDEX1, kRANGE_MAX - 1, 0 + kAccount, 0, kRangeMax, 200 /*balance*/, 2 /*owner object*/, kIndex1, kRangeMax - 1, 0 ) .getSerializer() .peekData(); - ON_CALL(*backend_, doFetchLedgerObject(accountKk, kRANGE_MAX, _)) + ON_CALL(*backend_, doFetchLedgerObject(accountKk, kRangeMax, _)) .WillByDefault(Return(accountObject)); // fee object 2*2+3->7 ; balance 200 - 7 -> 193 auto feeBlob = createLegacyFeeSettingBlob(1, 2 /*reserve inc*/, 3 /*reserve base*/, 4, 0); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, kRANGE_MAX, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, kRangeMax, _)) .WillByDefault(Return(feeBlob)); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); TransactionAndMetadata tx; - tx.metadata = createMetaDataForCreateOffer(kCURRENCY, kACCOUNT2, 100, 300, 200) + tx.metadata = createMetaDataForCreateOffer(kCurrency, kAccount2, 100, 300, 200) .getSerializer() .peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300, true) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300, true) .getSerializer() .peekData(); tx.date = 123456; - tx.ledgerSequence = kRANGE_MAX; + tx.ledgerSequence = kRangeMax; EXPECT_CALL(*backend_, fetchAllTransactionsInLedger).Times(1); - ON_CALL(*backend_, fetchAllTransactionsInLedger(kRANGE_MAX, _)) + ON_CALL(*backend_, fetchAllTransactionsInLedger(kRangeMax, _)) .WillByDefault(Return(std::vector{tx})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "binary": false, "expand": true, @@ -1068,13 +1067,13 @@ TEST_F(RPCLedgerHandlerTest, OwnerFundsTrueBinaryFalse) ASSERT_TRUE(output); // remove human readable time, it is slightly different cross the platform EXPECT_EQ(output.result->as_object().at("ledger").as_object().erase("close_time_human"), 1); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCLedgerHandlerTest, OwnerFundsTrueBinaryTrue) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "ledger": { "closed": true, @@ -1092,46 +1091,46 @@ TEST_F(RPCLedgerHandlerTest, OwnerFundsTrueBinaryTrue) "validated": true })JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(ledgerHeader)); // account doFetchLedgerObject - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; auto const accountObject = createAccountRootObject( - kACCOUNT, 0, kRANGE_MAX, 200 /*balance*/, 2 /*owner object*/, kINDEX1, kRANGE_MAX - 1, 0 + kAccount, 0, kRangeMax, 200 /*balance*/, 2 /*owner object*/, kIndex1, kRangeMax - 1, 0 ) .getSerializer() .peekData(); - ON_CALL(*backend_, doFetchLedgerObject(accountKk, kRANGE_MAX, _)) + ON_CALL(*backend_, doFetchLedgerObject(accountKk, kRangeMax, _)) .WillByDefault(Return(accountObject)); // fee object 2*2+3->7 ; balance 200 - 7 -> 193 auto feeBlob = createLegacyFeeSettingBlob(1, 2 /*reserve inc*/, 3 /*reserve base*/, 4, 0); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, kRANGE_MAX, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, kRangeMax, _)) .WillByDefault(Return(feeBlob)); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); TransactionAndMetadata tx; - tx.metadata = createMetaDataForCreateOffer(kCURRENCY, kACCOUNT2, 100, 300, 200) + tx.metadata = createMetaDataForCreateOffer(kCurrency, kAccount2, 100, 300, 200) .getSerializer() .peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300, true) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300, true) .getSerializer() .peekData(); tx.date = 123456; - tx.ledgerSequence = kRANGE_MAX; + tx.ledgerSequence = kRangeMax; EXPECT_CALL(*backend_, fetchAllTransactionsInLedger).Times(1); - ON_CALL(*backend_, fetchAllTransactionsInLedger(kRANGE_MAX, _)) + ON_CALL(*backend_, fetchAllTransactionsInLedger(kRangeMax, _)) .WillByDefault(Return(std::vector{tx})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "binary": true, "expand": true, @@ -1141,34 +1140,34 @@ TEST_F(RPCLedgerHandlerTest, OwnerFundsTrueBinaryTrue) ); auto output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCLedgerHandlerTest, OwnerFundsIssuerIsSelf) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(ledgerHeader)); // issuer is self TransactionAndMetadata tx; tx.metadata = - createMetaDataForCreateOffer(kCURRENCY, kACCOUNT, 100, 300, 200).getSerializer().peekData(); + createMetaDataForCreateOffer(kCurrency, kAccount, 100, 300, 200).getSerializer().peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount, 200, 300) .getSerializer() .peekData(); tx.date = 123456; - tx.ledgerSequence = kRANGE_MAX; + tx.ledgerSequence = kRangeMax; EXPECT_CALL(*backend_, fetchAllTransactionsInLedger).Times(1); - ON_CALL(*backend_, fetchAllTransactionsInLedger(kRANGE_MAX, _)) + ON_CALL(*backend_, fetchAllTransactionsInLedger(kRangeMax, _)) .WillByDefault(Return(std::vector{tx})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "binary": true, "expand": true, @@ -1188,7 +1187,7 @@ TEST_F(RPCLedgerHandlerTest, OwnerFundsIssuerIsSelf) TEST_F(RPCLedgerHandlerTest, OwnerFundsNotEnoughForReserve) { - static constexpr auto kEXPECTED_OUT = + static constexpr auto kExpectedOut = R"JSON({ "ledger": { "closed": true, @@ -1206,46 +1205,46 @@ TEST_F(RPCLedgerHandlerTest, OwnerFundsNotEnoughForReserve) "validated": true })JSON"; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(ledgerHeader)); // account doFetchLedgerObject - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; auto const accountObject = createAccountRootObject( - kACCOUNT, 0, kRANGE_MAX, 6 /*balance*/, 2 /*owner object*/, kINDEX1, kRANGE_MAX - 1, 0 + kAccount, 0, kRangeMax, 6 /*balance*/, 2 /*owner object*/, kIndex1, kRangeMax - 1, 0 ) .getSerializer() .peekData(); - ON_CALL(*backend_, doFetchLedgerObject(accountKk, kRANGE_MAX, _)) + ON_CALL(*backend_, doFetchLedgerObject(accountKk, kRangeMax, _)) .WillByDefault(Return(accountObject)); // fee object 2*2+3->7 ; balance 6 - 7 -> -1 auto feeBlob = createLegacyFeeSettingBlob(1, 2 /*reserve inc*/, 3 /*reserve base*/, 4, 0); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, kRANGE_MAX, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, kRangeMax, _)) .WillByDefault(Return(feeBlob)); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); TransactionAndMetadata tx; - tx.metadata = createMetaDataForCreateOffer(kCURRENCY, kACCOUNT2, 100, 300, 200) + tx.metadata = createMetaDataForCreateOffer(kCurrency, kAccount2, 100, 300, 200) .getSerializer() .peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300, true) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300, true) .getSerializer() .peekData(); tx.date = 123456; - tx.ledgerSequence = kRANGE_MAX; + tx.ledgerSequence = kRangeMax; EXPECT_CALL(*backend_, fetchAllTransactionsInLedger).Times(1); - ON_CALL(*backend_, fetchAllTransactionsInLedger(kRANGE_MAX, _)) + ON_CALL(*backend_, fetchAllTransactionsInLedger(kRangeMax, _)) .WillByDefault(Return(std::vector{tx})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "binary": true, "expand": true, @@ -1255,49 +1254,49 @@ TEST_F(RPCLedgerHandlerTest, OwnerFundsNotEnoughForReserve) ); auto output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOut)); }); } TEST_F(RPCLedgerHandlerTest, OwnerFundsNotXRP) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(ledgerHeader)); // mock line auto const line = createRippleStateLedgerObject( - kCURRENCY, kACCOUNT2, 50 /*balance*/, kACCOUNT, 10, kACCOUNT2, 20, kINDEX1, 123 + kCurrency, kAccount2, 50 /*balance*/, kAccount, 10, kAccount2, 20, kIndex1, 123 ); - auto lineKey = ripple::keylet::line( - getAccountIdWithString(kACCOUNT), - getAccountIdWithString(kACCOUNT2), - ripple::to_currency(std::string(kCURRENCY)) + auto lineKey = xrpl::keylet::trustLine( + getAccountIdWithString(kAccount), + getAccountIdWithString(kAccount2), + xrpl::toCurrency(std::string(kCurrency)) ) .key; - ON_CALL(*backend_, doFetchLedgerObject(lineKey, kRANGE_MAX, _)) + ON_CALL(*backend_, doFetchLedgerObject(lineKey, kRangeMax, _)) .WillByDefault(Return(line.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); TransactionAndMetadata tx; - tx.metadata = createMetaDataForCreateOffer(kCURRENCY, kACCOUNT2, 100, 300, 200, true) + tx.metadata = createMetaDataForCreateOffer(kCurrency, kAccount2, 100, 300, 200, true) .getSerializer() .peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300) .getSerializer() .peekData(); tx.date = 123456; - tx.ledgerSequence = kRANGE_MAX; + tx.ledgerSequence = kRangeMax; EXPECT_CALL(*backend_, fetchAllTransactionsInLedger).Times(1); - ON_CALL(*backend_, fetchAllTransactionsInLedger(kRANGE_MAX, _)) + ON_CALL(*backend_, fetchAllTransactionsInLedger(kRangeMax, _)) .WillByDefault(Return(std::vector{tx})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "binary": true, "expand": true, @@ -1320,52 +1319,52 @@ TEST_F(RPCLedgerHandlerTest, OwnerFundsNotXRP) TEST_F(RPCLedgerHandlerTest, OwnerFundsIgnoreFreezeLine) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kRANGE_MAX); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kRangeMax); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kRANGE_MAX, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kRangeMax, _)).WillByDefault(Return(ledgerHeader)); // mock line freeze auto const line = createRippleStateLedgerObject( - kCURRENCY, - kACCOUNT2, + kCurrency, + kAccount2, 50 /*balance*/, - kACCOUNT, + kAccount, 10, - kACCOUNT2, + kAccount2, 20, - kINDEX1, + kIndex1, 123, - ripple::lsfLowFreeze | ripple::lsfHighFreeze + xrpl::lsfLowFreeze | xrpl::lsfHighFreeze ); - auto lineKey = ripple::keylet::line( - getAccountIdWithString(kACCOUNT), - getAccountIdWithString(kACCOUNT2), - ripple::to_currency(std::string(kCURRENCY)) + auto lineKey = xrpl::keylet::trustLine( + getAccountIdWithString(kAccount), + getAccountIdWithString(kAccount2), + xrpl::toCurrency(std::string(kCurrency)) ) .key; - ON_CALL(*backend_, doFetchLedgerObject(lineKey, kRANGE_MAX, _)) + ON_CALL(*backend_, doFetchLedgerObject(lineKey, kRangeMax, _)) .WillByDefault(Return(line.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); TransactionAndMetadata tx; - tx.metadata = createMetaDataForCreateOffer(kCURRENCY, kACCOUNT2, 100, 300, 200, true) + tx.metadata = createMetaDataForCreateOffer(kCurrency, kAccount2, 100, 300, 200, true) .getSerializer() .peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300) .getSerializer() .peekData(); tx.date = 123456; - tx.ledgerSequence = kRANGE_MAX; + tx.ledgerSequence = kRangeMax; EXPECT_CALL(*backend_, fetchAllTransactionsInLedger).Times(1); - ON_CALL(*backend_, fetchAllTransactionsInLedger(kRANGE_MAX, _)) + ON_CALL(*backend_, fetchAllTransactionsInLedger(kRangeMax, _)) .WillByDefault(Return(std::vector{tx})); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{LedgerHandler{backend_, mockAmendmentCenterPtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( R"JSON({ "binary": true, "expand": true, diff --git a/tests/unit/rpc/handlers/MPTHoldersTests.cpp b/tests/unit/rpc/handlers/MPTHoldersTests.cpp index 86bbd9464..48f1ee958 100644 --- a/tests/unit/rpc/handlers/MPTHoldersTests.cpp +++ b/tests/unit/rpc/handlers/MPTHoldersTests.cpp @@ -11,10 +11,10 @@ #include #include #include -#include -#include -#include +#include #include +#include +#include #include #include @@ -23,17 +23,16 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kHOLDE_R1_ACCOUNT = "rrnAZCqMahreZrKMcZU3t2DZ6yUndT4ubN"; -constexpr auto kHOLDE_R2_ACCOUNT = "rEiNkzogdHEzUxPfsri5XSMqtXUixf2Yx"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kMPT_ID = "000004C463C52827307480341125DA0577DEFC38405B0E3E"; +constexpr auto kHoldeR1Account = "rrnAZCqMahreZrKMcZU3t2DZ6yUndT4ubN"; +constexpr auto kHoldeR2Account = "rEiNkzogdHEzUxPfsri5XSMqtXUixf2Yx"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kMptId = "000004C463C52827307480341125DA0577DEFC38405B0E3E"; -std::string const kMPT_OUT1 = +std::string const kMptOuT1 = R"JSON({ "account": "rrnAZCqMahreZrKMcZU3t2DZ6yUndT4ubN", "flags": 0, @@ -41,7 +40,7 @@ std::string const kMPT_OUT1 = "mptoken_index": "D137F2E5A5767A06CB7A8F060ADE442A30CFF95028E1AF4B8767E3A56877205A" })JSON"; -std::string const kMPT_OUT2 = +std::string const kMptOuT2 = R"JSON({ "account": "rEiNkzogdHEzUxPfsri5XSMqtXUixf2Yx", "flags": 0, @@ -62,13 +61,13 @@ TEST_F(RPCMPTHoldersHandlerTest, NonHexLedgerHash) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{MPTHoldersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "ledger_hash": "xxx" }})JSON", - kMPT_ID + kMptId ) ); auto const output = handler.process(input, Context{.yield = std::ref(yield)}); @@ -84,13 +83,13 @@ TEST_F(RPCMPTHoldersHandlerTest, NonStringLedgerHash) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{MPTHoldersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "ledger_hash": 123 }})JSON", - kMPT_ID + kMptId ) ); auto const output = handler.process(input, Context{.yield = std::ref(yield)}); @@ -106,13 +105,13 @@ TEST_F(RPCMPTHoldersHandlerTest, InvalidLedgerIndexString) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{MPTHoldersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "ledger_index": "notvalidated" }})JSON", - kMPT_ID + kMptId ) ); auto const output = handler.process(input, Context{.yield = std::ref(yield)}); @@ -129,7 +128,7 @@ TEST_F(RPCMPTHoldersHandlerTest, MPTIDInvalidFormat) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{MPTHoldersHandler{backend_}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "mpt_issuance_id": "xxx" })JSON"); auto const output = handler.process(input, Context{.yield = std::ref(yield)}); @@ -145,7 +144,7 @@ TEST_F(RPCMPTHoldersHandlerTest, MPTIDMissing) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{MPTHoldersHandler{backend_}}; - auto const input = json::parse(R"JSON({})JSON"); + auto const input = boost::json::parse(R"JSON({})JSON"); auto const output = handler.process(input, Context{.yield = std::ref(yield)}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -159,7 +158,7 @@ TEST_F(RPCMPTHoldersHandlerTest, MPTIDNotString) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{MPTHoldersHandler{backend_}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "mpt_issuance_id": 12 })JSON"); auto const output = handler.process(input, Context{.yield = std::ref(yield)}); @@ -176,13 +175,13 @@ TEST_F(RPCMPTHoldersHandlerTest, MarkerInvalidFormat) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{MPTHoldersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "marker": "xxx" }})JSON", - kMPT_ID + kMptId ) ); auto const output = handler.process(input, Context{.yield = std::ref(yield)}); @@ -198,13 +197,13 @@ TEST_F(RPCMPTHoldersHandlerTest, MarkerNotString) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{MPTHoldersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "marker": 1 }})JSON", - kMPT_ID + kMptId ) ); auto const output = handler.process(input, Context{.yield = std::ref(yield)}); @@ -220,17 +219,17 @@ TEST_F(RPCMPTHoldersHandlerTest, NonExistLedgerViaLedgerHash) { // mock fetchLedgerByHash return empty EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillByDefault(Return(std::optional{})); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "ledger_hash": "{}" }})JSON", - kMPT_ID, - kLEDGER_HASH + kMptId, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -249,14 +248,14 @@ TEST_F(RPCMPTHoldersHandlerTest, NonExistLedgerViaLedgerStringIndex) { // mock fetchLedgerBySequence return empty EXPECT_CALL(*backend_, fetchLedgerBySequence) - .WillOnce(Return(std::optional{})); - auto const input = json::parse( + .WillOnce(Return(std::optional{})); + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "ledger_index": "4" }})JSON", - kMPT_ID + kMptId ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -273,14 +272,14 @@ TEST_F(RPCMPTHoldersHandlerTest, NonExistLedgerViaLedgerIntIndex) { // mock fetchLedgerBySequence return empty EXPECT_CALL(*backend_, fetchLedgerBySequence) - .WillOnce(Return(std::optional{})); - auto const input = json::parse( + .WillOnce(Return(std::optional{})); + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "ledger_index": 4 }})JSON", - kMPT_ID + kMptId ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -298,18 +297,18 @@ TEST_F(RPCMPTHoldersHandlerTest, NonExistLedgerViaLedgerIntIndex) TEST_F(RPCMPTHoldersHandlerTest, NonExistLedgerViaLedgerHash2) { // mock fetchLedgerByHash return ledger but seq is 31 > 30 - auto ledgerinfo = createLedgerHeader(kLEDGER_HASH, 31); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerinfo = createLedgerHeader(kLedgerHash, 31); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerinfo)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "ledger_hash": "{}" }})JSON", - kMPT_ID, - kLEDGER_HASH + kMptId, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -328,13 +327,13 @@ TEST_F(RPCMPTHoldersHandlerTest, NonExistLedgerViaLedgerIndex2) // no need to check from db,call fetchLedgerBySequence 0 time // differ from previous logic EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(0); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "ledger_index": "31" }})JSON", - kMPT_ID + kMptId ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -350,21 +349,21 @@ TEST_F(RPCMPTHoldersHandlerTest, NonExistLedgerViaLedgerIndex2) // normal case when MPT does not exist TEST_F(RPCMPTHoldersHandlerTest, MPTNotFound) { - auto ledgerinfo = createLedgerHeader(kLEDGER_HASH, 30); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerinfo = createLedgerHeader(kLedgerHash, 30); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerinfo)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); ON_CALL(*backend_, doFetchLedgerObject).WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "ledger_hash": "{}" }})JSON", - kMPT_ID, - kLEDGER_HASH + kMptId, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -388,41 +387,41 @@ TEST_F(RPCMPTHoldersHandlerTest, DefaultParameters) "mptokens": [{}], "validated": true }})JSON", - kMPT_ID, - kMPT_OUT1 + kMptId, + kMptOuT1 ); - auto ledgerInfo = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerInfo = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerInfo)); - auto const issuanceKk = ripple::keylet::mptIssuance(ripple::uint192(kMPT_ID)).key; + auto const issuanceKk = xrpl::keylet::mptokenIssuance(xrpl::uint192(kMptId)).key; ON_CALL(*backend_, doFetchLedgerObject(issuanceKk, 30, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - auto const mptoken = createMpTokenObject(kHOLDE_R1_ACCOUNT, ripple::uint192(kMPT_ID)); + auto const mptoken = createMpTokenObject(kHoldeR1Account, xrpl::uint192(kMptId)); std::vector const mpts = {mptoken.getSerializer().peekData()}; ON_CALL(*backend_, fetchMPTHolders) .WillByDefault(Return(MPTHoldersAndCursor{.mptokens = mpts, .cursor = {}})); EXPECT_CALL( *backend_, fetchMPTHolders( - ripple::uint192(kMPT_ID), testing::_, testing::Eq(std::nullopt), Const(30), testing::_ + xrpl::uint192(kMptId), testing::_, testing::Eq(std::nullopt), Const(30), testing::_ ) ) .Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}" }})JSON", - kMPT_ID + kMptId ) ); runSpawn([&, this](auto& yield) { auto handler = AnyHandler{MPTHoldersHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(currentOutput), *output.result); + EXPECT_EQ(boost::json::parse(currentOutput), *output.result); }); } @@ -443,40 +442,40 @@ TEST_F(RPCMPTHoldersHandlerTest, CustomAmounts) }}], "validated": true }})JSON", - kMPT_ID + kMptId ); - auto ledgerInfo = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerInfo = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerInfo)); - auto const issuanceKk = ripple::keylet::mptIssuance(ripple::uint192(kMPT_ID)).key; + auto const issuanceKk = xrpl::keylet::mptokenIssuance(xrpl::uint192(kMptId)).key; ON_CALL(*backend_, doFetchLedgerObject(issuanceKk, 30, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - auto const mptoken = createMpTokenObject(kHOLDE_R1_ACCOUNT, ripple::uint192(kMPT_ID), 0); + auto const mptoken = createMpTokenObject(kHoldeR1Account, xrpl::uint192(kMptId), 0); std::vector const mpts = {mptoken.getSerializer().peekData()}; ON_CALL(*backend_, fetchMPTHolders) .WillByDefault(Return(MPTHoldersAndCursor{.mptokens = mpts, .cursor = {}})); EXPECT_CALL( *backend_, fetchMPTHolders( - ripple::uint192(kMPT_ID), testing::_, testing::Eq(std::nullopt), Const(30), testing::_ + xrpl::uint192(kMptId), testing::_, testing::Eq(std::nullopt), Const(30), testing::_ ) ) .Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}" }})JSON", - kMPT_ID + kMptId ) ); runSpawn([&, this](auto& yield) { auto handler = AnyHandler{MPTHoldersHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(currentOutput), *output.result); + EXPECT_EQ(boost::json::parse(currentOutput), *output.result); }); } @@ -491,26 +490,26 @@ TEST_F(RPCMPTHoldersHandlerTest, SpecificLedgerIndex) "mptokens": [{}], "validated": true }})JSON", - kMPT_ID, + kMptId, specificLedger, - kMPT_OUT1 + kMptOuT1 ); - auto ledgerInfo = createLedgerHeader(kLEDGER_HASH, specificLedger); + auto ledgerInfo = createLedgerHeader(kLedgerHash, specificLedger); ON_CALL(*backend_, fetchLedgerBySequence(specificLedger, _)).WillByDefault(Return(ledgerInfo)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - auto const issuanceKk = ripple::keylet::mptIssuance(ripple::uint192(kMPT_ID)).key; + auto const issuanceKk = xrpl::keylet::mptokenIssuance(xrpl::uint192(kMptId)).key; ON_CALL(*backend_, doFetchLedgerObject(issuanceKk, specificLedger, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - auto const mptoken = createMpTokenObject(kHOLDE_R1_ACCOUNT, ripple::uint192(kMPT_ID)); + auto const mptoken = createMpTokenObject(kHoldeR1Account, xrpl::uint192(kMptId)); std::vector const mpts = {mptoken.getSerializer().peekData()}; ON_CALL(*backend_, fetchMPTHolders) .WillByDefault(Return(MPTHoldersAndCursor{.mptokens = mpts, .cursor = {}})); EXPECT_CALL( *backend_, fetchMPTHolders( - ripple::uint192(kMPT_ID), + xrpl::uint192(kMptId), testing::_, testing::Eq(std::nullopt), Const(specificLedger), @@ -519,13 +518,13 @@ TEST_F(RPCMPTHoldersHandlerTest, SpecificLedgerIndex) ) .Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "ledger_index": {} }})JSON", - kMPT_ID, + kMptId, specificLedger ) ); @@ -533,7 +532,7 @@ TEST_F(RPCMPTHoldersHandlerTest, SpecificLedgerIndex) auto handler = AnyHandler{MPTHoldersHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(currentOutput), *output.result); + EXPECT_EQ(boost::json::parse(currentOutput), *output.result); }); } @@ -548,38 +547,38 @@ TEST_F(RPCMPTHoldersHandlerTest, MarkerParameter) "validated": true, "marker": "{}" }})JSON", - kMPT_ID, - kMPT_OUT2, - ripple::strHex(getAccountIdWithString(kHOLDE_R1_ACCOUNT)) + kMptId, + kMptOuT2, + xrpl::strHex(getAccountIdWithString(kHoldeR1Account)) ); - auto ledgerInfo = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerInfo = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerInfo)); - auto const issuanceKk = ripple::keylet::mptIssuance(ripple::uint192(kMPT_ID)).key; + auto const issuanceKk = xrpl::keylet::mptokenIssuance(xrpl::uint192(kMptId)).key; ON_CALL(*backend_, doFetchLedgerObject(issuanceKk, 30, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - auto const mptoken = createMpTokenObject(kHOLDE_R2_ACCOUNT, ripple::uint192(kMPT_ID)); + auto const mptoken = createMpTokenObject(kHoldeR2Account, xrpl::uint192(kMptId)); std::vector const mpts = {mptoken.getSerializer().peekData()}; - auto const marker = getAccountIdWithString(kHOLDE_R1_ACCOUNT); + auto const marker = getAccountIdWithString(kHoldeR1Account); ON_CALL(*backend_, fetchMPTHolders) .WillByDefault(Return(MPTHoldersAndCursor{.mptokens = mpts, .cursor = marker})); EXPECT_CALL( *backend_, fetchMPTHolders( - ripple::uint192(kMPT_ID), testing::_, testing::Eq(marker), Const(30), testing::_ + xrpl::uint192(kMptId), testing::_, testing::Eq(marker), Const(30), testing::_ ) ) .Times(1); - auto const holder1AccountId = ripple::strHex(getAccountIdWithString(kHOLDE_R1_ACCOUNT)); - auto const input = json::parse( + auto const holder1AccountId = xrpl::strHex(getAccountIdWithString(kHoldeR1Account)); + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "marker": "{}" }})JSON", - kMPT_ID, + kMptId, holder1AccountId ) ); @@ -587,7 +586,7 @@ TEST_F(RPCMPTHoldersHandlerTest, MarkerParameter) auto handler = AnyHandler{MPTHoldersHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(currentOutput), *output.result); + EXPECT_EQ(boost::json::parse(currentOutput), *output.result); }); } @@ -601,19 +600,19 @@ TEST_F(RPCMPTHoldersHandlerTest, MultipleMPTs) "mptokens": [{}, {}], "validated": true }})JSON", - kMPT_ID, - kMPT_OUT1, - kMPT_OUT2 + kMptId, + kMptOuT1, + kMptOuT2 ); - auto ledgerInfo = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerInfo = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerInfo)); - auto const issuanceKk = ripple::keylet::mptIssuance(ripple::uint192(kMPT_ID)).key; + auto const issuanceKk = xrpl::keylet::mptokenIssuance(xrpl::uint192(kMptId)).key; ON_CALL(*backend_, doFetchLedgerObject(issuanceKk, 30, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - auto const mptoken1 = createMpTokenObject(kHOLDE_R1_ACCOUNT, ripple::uint192(kMPT_ID)); - auto const mptoken2 = createMpTokenObject(kHOLDE_R2_ACCOUNT, ripple::uint192(kMPT_ID)); + auto const mptoken1 = createMpTokenObject(kHoldeR1Account, xrpl::uint192(kMptId)); + auto const mptoken2 = createMpTokenObject(kHoldeR2Account, xrpl::uint192(kMptId)); std::vector const mpts = { mptoken1.getSerializer().peekData(), mptoken2.getSerializer().peekData() }; @@ -622,24 +621,24 @@ TEST_F(RPCMPTHoldersHandlerTest, MultipleMPTs) EXPECT_CALL( *backend_, fetchMPTHolders( - ripple::uint192(kMPT_ID), testing::_, testing::Eq(std::nullopt), Const(30), testing::_ + xrpl::uint192(kMptId), testing::_, testing::Eq(std::nullopt), Const(30), testing::_ ) ) .Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}" }})JSON", - kMPT_ID + kMptId ) ); runSpawn([&, this](auto& yield) { auto handler = AnyHandler{MPTHoldersHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(currentOutput), *output.result); + EXPECT_EQ(boost::json::parse(currentOutput), *output.result); }); } @@ -653,25 +652,25 @@ TEST_F(RPCMPTHoldersHandlerTest, LimitMoreThanMAx) "mptokens": [{}], "validated": true }})JSON", - kMPT_ID, - kMPT_OUT1 + kMptId, + kMptOuT1 ); - auto ledgerInfo = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerInfo = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerInfo)); - auto const issuanceKk = ripple::keylet::mptIssuance(ripple::uint192(kMPT_ID)).key; + auto const issuanceKk = xrpl::keylet::mptokenIssuance(xrpl::uint192(kMptId)).key; ON_CALL(*backend_, doFetchLedgerObject(issuanceKk, 30, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - auto const mptoken = createMpTokenObject(kHOLDE_R1_ACCOUNT, ripple::uint192(kMPT_ID)); + auto const mptoken = createMpTokenObject(kHoldeR1Account, xrpl::uint192(kMptId)); std::vector const mpts = {mptoken.getSerializer().peekData()}; ON_CALL(*backend_, fetchMPTHolders) .WillByDefault(Return(MPTHoldersAndCursor{.mptokens = mpts, .cursor = {}})); EXPECT_CALL( *backend_, fetchMPTHolders( - ripple::uint192(kMPT_ID), - Const(MPTHoldersHandler::kLIMIT_MAX), + xrpl::uint192(kMptId), + Const(MPTHoldersHandler::kLimitMax), testing::Eq(std::nullopt), Const(30), testing::_ @@ -679,20 +678,20 @@ TEST_F(RPCMPTHoldersHandlerTest, LimitMoreThanMAx) ) .Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "mpt_issuance_id": "{}", "limit": {} }})JSON", - kMPT_ID, - MPTHoldersHandler::kLIMIT_MAX + 1 + kMptId, + MPTHoldersHandler::kLimitMax + 1 ) ); runSpawn([&, this](auto& yield) { auto handler = AnyHandler{MPTHoldersHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(currentOutput), *output.result); + EXPECT_EQ(boost::json::parse(currentOutput), *output.result); }); } diff --git a/tests/unit/rpc/handlers/NFTBuyOffersTests.cpp b/tests/unit/rpc/handlers/NFTBuyOffersTests.cpp index 756983d09..6a1f600b1 100644 --- a/tests/unit/rpc/handlers/NFTBuyOffersTests.cpp +++ b/tests/unit/rpc/handlers/NFTBuyOffersTests.cpp @@ -23,16 +23,15 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kNFT_ID = "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004"; -constexpr auto kINDEX1 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kINDEX2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kNftId = "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004"; +constexpr auto kIndex1 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kIndex2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; } // namespace @@ -47,13 +46,13 @@ TEST_F(RPCNFTBuyOffersHandlerTest, NonHexLedgerHash) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTBuyOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": "xxx" }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -69,13 +68,13 @@ TEST_F(RPCNFTBuyOffersHandlerTest, LimitNotInt) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTBuyOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": "xxx" }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -90,13 +89,13 @@ TEST_F(RPCNFTBuyOffersHandlerTest, LimitNegative) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTBuyOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": -1 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -111,13 +110,13 @@ TEST_F(RPCNFTBuyOffersHandlerTest, LimitZero) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTBuyOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": 0 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -132,13 +131,13 @@ TEST_F(RPCNFTBuyOffersHandlerTest, NonStringLedgerHash) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTBuyOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": 123 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -154,13 +153,13 @@ TEST_F(RPCNFTBuyOffersHandlerTest, InvalidLedgerIndexString) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTBuyOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_index": "notvalidated" }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -177,7 +176,7 @@ TEST_F(RPCNFTBuyOffersHandlerTest, NFTIDInvalidFormat) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTBuyOffersHandler{backend_}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "nft_id": "00080000B4F4AFC5FBCBD76873F18006173D2193467D3EE7" })JSON"); auto const output = handler.process(input, Context{.yield = yield}); @@ -193,7 +192,7 @@ TEST_F(RPCNFTBuyOffersHandlerTest, NFTIDNotString) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTBuyOffersHandler{backend_}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "nft_id": 12 })JSON"); auto const output = handler.process(input, Context{.yield = yield}); @@ -209,18 +208,18 @@ TEST_F(RPCNFTBuyOffersHandlerTest, NFTIDNotString) TEST_F(RPCNFTBuyOffersHandlerTest, NonExistLedgerViaLedgerHash) { // mock fetchLedgerByHash return empty - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": "{}" }})JSON", - kNFT_ID, - kLEDGER_HASH + kNftId, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -239,15 +238,15 @@ TEST_F(RPCNFTBuyOffersHandlerTest, NonExistLedgerViaLedgerIndex) { // mock fetchLedgerBySequence return empty ON_CALL(*backend_, fetchLedgerBySequence) - .WillByDefault(Return(std::optional{})); + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_index": "4" }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -265,18 +264,18 @@ TEST_F(RPCNFTBuyOffersHandlerTest, NonExistLedgerViaLedgerIndex) TEST_F(RPCNFTBuyOffersHandlerTest, NonExistLedgerViaLedgerHash2) { // mock fetchLedgerByHash return ledger but seq is 31 > 30 - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 31); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, 31); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": "{}" }})JSON", - kNFT_ID, - kLEDGER_HASH + kNftId, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -295,13 +294,13 @@ TEST_F(RPCNFTBuyOffersHandlerTest, NonExistLedgerViaLedgerIndex2) // no need to check from db, call fetchLedgerBySequence 0 time // differ from previous logic EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(0); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_index": "31" }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -317,20 +316,20 @@ TEST_F(RPCNFTBuyOffersHandlerTest, NonExistLedgerViaLedgerIndex2) // error case when nft is not found TEST_F(RPCNFTBuyOffersHandlerTest, NoNFT) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); ON_CALL(*backend_, doFetchLedgerObject).WillByDefault(Return(std::nullopt)); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": "{}" }})JSON", - kNFT_ID, - kLEDGER_HASH + kNftId, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -347,13 +346,13 @@ TEST_F(RPCNFTBuyOffersHandlerTest, MarkerNotString) { runSpawn([this](auto yield) { auto const handler = AnyHandler{NFTBuyOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "marker": 9 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{yield}); @@ -366,18 +365,18 @@ TEST_F(RPCNFTBuyOffersHandlerTest, MarkerNotString) } // error case : invalid marker -// marker format in this RPC is a hex-string of a ripple::uint256. +// marker format in this RPC is a hex-string of a xrpl::uint256. TEST_F(RPCNFTBuyOffersHandlerTest, InvalidMarker) { runSpawn([this](auto yield) { auto const handler = AnyHandler{NFTBuyOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "marker": "123invalid" }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{yield}); @@ -389,13 +388,13 @@ TEST_F(RPCNFTBuyOffersHandlerTest, InvalidMarker) }); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTBuyOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "marker": 250 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{yield}); @@ -409,7 +408,7 @@ TEST_F(RPCNFTBuyOffersHandlerTest, InvalidMarker) // normal case when only provide nft_id TEST_F(RPCNFTBuyOffersHandlerTest, DefaultParameters) { - static constexpr auto kCORRECT_OUTPUT = R"JSON({ + static constexpr auto kCorrectOutput = R"JSON({ "nft_id": "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004", "validated": true, "offers": [ @@ -428,14 +427,14 @@ TEST_F(RPCNFTBuyOffersHandlerTest, DefaultParameters) ] })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return owner index containing 2 indexes - auto const directory = ripple::keylet::nft_buys(ripple::uint256{kNFT_ID}); + auto const directory = xrpl::keylet::nftBuys(xrpl::uint256{kNftId}); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(directory.key, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -443,18 +442,18 @@ TEST_F(RPCNFTBuyOffersHandlerTest, DefaultParameters) // return two nft buy offers std::vector bbs; - auto const offer = createNftBuyOffer(kNFT_ID, kACCOUNT); + auto const offer = createNftBuyOffer(kNftId, kAccount); bbs.push_back(offer.getSerializer().peekData()); bbs.push_back(offer.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}" }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](auto yield) { @@ -462,28 +461,28 @@ TEST_F(RPCNFTBuyOffersHandlerTest, DefaultParameters) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(kCORRECT_OUTPUT), *output.result); + EXPECT_EQ(boost::json::parse(kCorrectOutput), *output.result); }); } // normal case when provided with nft_id and limit TEST_F(RPCNFTBuyOffersHandlerTest, MultipleResultsWithMarkerAndLimitOutput) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return owner index - std::vector indexes; + std::vector indexes; std::vector bbs; auto repetitions = 500; - auto const offer = createNftBuyOffer(kNFT_ID, kACCOUNT); - auto idx = ripple::uint256{kINDEX1}; + auto const offer = createNftBuyOffer(kNftId, kAccount); + auto idx = xrpl::uint256{kIndex1}; while ((repetitions--) != 0) { indexes.push_back(idx++); bbs.push_back(offer.getSerializer().peekData()); } - ripple::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); + xrpl::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); ON_CALL(*backend_, doFetchLedgerObject) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -492,13 +491,13 @@ TEST_F(RPCNFTBuyOffersHandlerTest, MultipleResultsWithMarkerAndLimitOutput) ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": 50 }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](auto yield) { @@ -518,34 +517,34 @@ TEST_F(RPCNFTBuyOffersHandlerTest, MultipleResultsWithMarkerAndLimitOutput) // normal case when provided with nft_id, limit and marker TEST_F(RPCNFTBuyOffersHandlerTest, ResultsForInputWithMarkerAndLimit) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return owner index - std::vector indexes; + std::vector indexes; std::vector bbs; auto repetitions = 500; - auto const offer = createNftBuyOffer(kNFT_ID, kACCOUNT); - auto idx = ripple::uint256{kINDEX1}; + auto const offer = createNftBuyOffer(kNftId, kAccount); + auto idx = xrpl::uint256{kIndex1}; while ((repetitions--) != 0) { indexes.push_back(idx++); bbs.push_back(offer.getSerializer().peekData()); } - ripple::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); - auto const cursorBuyOffer = createNftBuyOffer(kNFT_ID, kACCOUNT); + xrpl::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); + auto const cursorBuyOffer = createNftBuyOffer(kNftId, kAccount); // first is nft offer object auto const cursor = - ripple::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC353"}; - auto const first = ripple::keylet::nftoffer(cursor); + xrpl::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC353"}; + auto const first = xrpl::keylet::nftokenOffer(cursor); ON_CALL(*backend_, doFetchLedgerObject(first.key, testing::_, testing::_)) .WillByDefault(Return(cursorBuyOffer.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject(first.key, testing::_, testing::_)).Times(1); - auto const directory = ripple::keylet::nft_buys(ripple::uint256{kNFT_ID}); + auto const directory = xrpl::keylet::nftBuys(xrpl::uint256{kNftId}); auto const startHint = 0ul; // offer node is hardcoded to 0ul - auto const secondKey = ripple::keylet::page(directory, startHint).key; + auto const secondKey = xrpl::keylet::page(directory, startHint).key; ON_CALL(*backend_, doFetchLedgerObject(secondKey, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject(secondKey, testing::_, testing::_)).Times(3); @@ -553,14 +552,14 @@ TEST_F(RPCNFTBuyOffersHandlerTest, ResultsForInputWithMarkerAndLimit) ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "marker": "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC353", "limit": 50 }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](auto yield) { @@ -582,34 +581,34 @@ TEST_F(RPCNFTBuyOffersHandlerTest, ResultsForInputWithMarkerAndLimit) // nothing left after reading remaining 50 entries TEST_F(RPCNFTBuyOffersHandlerTest, ResultsWithoutMarkerForInputWithMarkerAndLimit) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(3); // return owner index - std::vector indexes; + std::vector indexes; std::vector bbs; auto repetitions = 100; - auto const offer = createNftBuyOffer(kNFT_ID, kACCOUNT); - auto idx = ripple::uint256{kINDEX1}; + auto const offer = createNftBuyOffer(kNftId, kAccount); + auto idx = xrpl::uint256{kIndex1}; while ((repetitions--) != 0) { indexes.push_back(idx++); bbs.push_back(offer.getSerializer().peekData()); } - ripple::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); - auto const cursorBuyOffer = createNftBuyOffer(kNFT_ID, kACCOUNT); + xrpl::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); + auto const cursorBuyOffer = createNftBuyOffer(kNftId, kAccount); // first is nft offer object auto const cursor = - ripple::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC353"}; - auto const first = ripple::keylet::nftoffer(cursor); + xrpl::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC353"}; + auto const first = xrpl::keylet::nftokenOffer(cursor); ON_CALL(*backend_, doFetchLedgerObject(first.key, testing::_, testing::_)) .WillByDefault(Return(cursorBuyOffer.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject(first.key, testing::_, testing::_)).Times(1); - auto const directory = ripple::keylet::nft_buys(ripple::uint256{kNFT_ID}); + auto const directory = xrpl::keylet::nftBuys(xrpl::uint256{kNftId}); auto const startHint = 0ul; // offer node is hardcoded to 0ul - auto const secondKey = ripple::keylet::page(directory, startHint).key; + auto const secondKey = xrpl::keylet::page(directory, startHint).key; ON_CALL(*backend_, doFetchLedgerObject(secondKey, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject(secondKey, testing::_, testing::_)).Times(7); @@ -619,14 +618,14 @@ TEST_F(RPCNFTBuyOffersHandlerTest, ResultsWithoutMarkerForInputWithMarkerAndLimi runSpawn([&, this](auto yield) { auto handler = AnyHandler{NFTBuyOffersHandler{this->backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "marker": "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC353", "limit": 50 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{yield}); @@ -640,13 +639,13 @@ TEST_F(RPCNFTBuyOffersHandlerTest, ResultsWithoutMarkerForInputWithMarkerAndLimi runSpawn([this](auto yield) { auto const handler = AnyHandler{NFTBuyOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": 49 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{yield}); @@ -655,13 +654,13 @@ TEST_F(RPCNFTBuyOffersHandlerTest, ResultsWithoutMarkerForInputWithMarkerAndLimi runSpawn([this](auto yield) { auto const handler = AnyHandler{NFTBuyOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": 501 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{yield}); @@ -671,14 +670,14 @@ TEST_F(RPCNFTBuyOffersHandlerTest, ResultsWithoutMarkerForInputWithMarkerAndLimi TEST_F(RPCNFTBuyOffersHandlerTest, LimitLessThanMin) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return owner index containing 2 indexes - auto const directory = ripple::keylet::nft_buys(ripple::uint256{kNFT_ID}); + auto const directory = xrpl::keylet::nftBuys(xrpl::uint256{kNftId}); auto const ownerDir = createOwnerDirLedgerObject( - std::vector{NFTBuyOffersHandler::kLIMIT_MIN + 1, ripple::uint256{kINDEX1}}, kINDEX1 + std::vector{NFTBuyOffersHandler::kLimitMin + 1, xrpl::uint256{kIndex1}}, kIndex1 ); ON_CALL(*backend_, doFetchLedgerObject(directory.key, testing::_, testing::_)) @@ -687,21 +686,21 @@ TEST_F(RPCNFTBuyOffersHandlerTest, LimitLessThanMin) // return two nft buy offers std::vector bbs; - auto const offer = createNftBuyOffer(kNFT_ID, kACCOUNT); - bbs.reserve(NFTBuyOffersHandler::kLIMIT_MIN + 1); - for (auto i = 0; i < NFTBuyOffersHandler::kLIMIT_MIN + 1; i++) + auto const offer = createNftBuyOffer(kNftId, kAccount); + bbs.reserve(NFTBuyOffersHandler::kLimitMin + 1); + for (auto i = 0; i < NFTBuyOffersHandler::kLimitMin + 1; i++) bbs.push_back(offer.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": {} }})JSON", - kNFT_ID, - NFTBuyOffersHandler::kLIMIT_MIN - 1 + kNftId, + NFTBuyOffersHandler::kLimitMin - 1 ) ); runSpawn([&, this](auto yield) { @@ -709,21 +708,21 @@ TEST_F(RPCNFTBuyOffersHandlerTest, LimitLessThanMin) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("offers").as_array().size(), NFTBuyOffersHandler::kLIMIT_MIN); - EXPECT_EQ(output.result->at("limit").as_uint64(), NFTBuyOffersHandler::kLIMIT_MIN); + EXPECT_EQ(output.result->at("offers").as_array().size(), NFTBuyOffersHandler::kLimitMin); + EXPECT_EQ(output.result->at("limit").as_uint64(), NFTBuyOffersHandler::kLimitMin); }); } TEST_F(RPCNFTBuyOffersHandlerTest, LimitMoreThanMax) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return owner index containing 2 indexes - auto const directory = ripple::keylet::nft_buys(ripple::uint256{kNFT_ID}); + auto const directory = xrpl::keylet::nftBuys(xrpl::uint256{kNftId}); auto const ownerDir = createOwnerDirLedgerObject( - std::vector{NFTBuyOffersHandler::kLIMIT_MAX + 1, ripple::uint256{kINDEX1}}, kINDEX1 + std::vector{NFTBuyOffersHandler::kLimitMax + 1, xrpl::uint256{kIndex1}}, kIndex1 ); ON_CALL(*backend_, doFetchLedgerObject(directory.key, testing::_, testing::_)) @@ -732,21 +731,21 @@ TEST_F(RPCNFTBuyOffersHandlerTest, LimitMoreThanMax) // return two nft buy offers std::vector bbs; - auto const offer = createNftBuyOffer(kNFT_ID, kACCOUNT); - bbs.reserve(NFTBuyOffersHandler::kLIMIT_MAX + 1); - for (auto i = 0; i < NFTBuyOffersHandler::kLIMIT_MAX + 1; i++) + auto const offer = createNftBuyOffer(kNftId, kAccount); + bbs.reserve(NFTBuyOffersHandler::kLimitMax + 1); + for (auto i = 0; i < NFTBuyOffersHandler::kLimitMax + 1; i++) bbs.push_back(offer.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": {} }})JSON", - kNFT_ID, - NFTBuyOffersHandler::kLIMIT_MAX + 1 + kNftId, + NFTBuyOffersHandler::kLimitMax + 1 ) ); runSpawn([&, this](auto yield) { @@ -754,7 +753,7 @@ TEST_F(RPCNFTBuyOffersHandlerTest, LimitMoreThanMax) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("offers").as_array().size(), NFTBuyOffersHandler::kLIMIT_MAX); - EXPECT_EQ(output.result->at("limit").as_uint64(), NFTBuyOffersHandler::kLIMIT_MAX); + EXPECT_EQ(output.result->at("offers").as_array().size(), NFTBuyOffersHandler::kLimitMax); + EXPECT_EQ(output.result->at("limit").as_uint64(), NFTBuyOffersHandler::kLimitMax); }); } diff --git a/tests/unit/rpc/handlers/NFTHistoryTests.cpp b/tests/unit/rpc/handlers/NFTHistoryTests.cpp index 003da307a..e0d9f271f 100644 --- a/tests/unit/rpc/handlers/NFTHistoryTests.cpp +++ b/tests/unit/rpc/handlers/NFTHistoryTests.cpp @@ -21,25 +21,24 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kMIN_SEQ = 10; -constexpr auto kMAX_SEQ = 30; -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kNFT_ID = "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004"; -constexpr auto kAPI_VERSION = 2; +constexpr auto kMinSeq = 10; +constexpr auto kMaxSeq = 30; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kNftId = "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004"; +constexpr auto kApiVersion = 2; } // namespace struct RPCNFTHistoryHandlerTest : HandlerBaseTest { RPCNFTHistoryHandlerTest() { - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); } }; @@ -229,7 +228,7 @@ INSTANTIATE_TEST_CASE_P( RPCNFTHistoryGroup1, NFTHistoryParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(NFTHistoryParameterTest, InvalidParams) @@ -237,7 +236,7 @@ TEST_P(NFTHistoryParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); @@ -252,21 +251,19 @@ genTransactions(uint32_t seq1, uint32_t seq2) { auto transactions = std::vector{}; auto trans1 = TransactionAndMetadata(); - ripple::STObject const obj = createPaymentTransactionObject(kACCOUNT, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj = createPaymentTransactionObject(kAccount, kAccount2, 1, 1, 32); trans1.transaction = obj.getSerializer().peekData(); trans1.ledgerSequence = seq1; - ripple::STObject const metaObj = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, 22, 23); + xrpl::STObject const metaObj = createPaymentTransactionMetaObject(kAccount, kAccount2, 22, 23); trans1.metadata = metaObj.getSerializer().peekData(); trans1.date = 1; transactions.push_back(trans1); auto trans2 = TransactionAndMetadata(); - ripple::STObject const obj2 = createPaymentTransactionObject(kACCOUNT, kACCOUNT2, 1, 1, 32); + xrpl::STObject const obj2 = createPaymentTransactionObject(kAccount, kAccount2, 1, 1, 32); trans2.transaction = obj.getSerializer().peekData(); trans2.ledgerSequence = seq2; - ripple::STObject const metaObj2 = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, 22, 23); + xrpl::STObject const metaObj2 = createPaymentTransactionMetaObject(kAccount, kAccount2, 22, 23); trans2.metadata = metaObj2.getSerializer().peekData(); trans2.date = 2; transactions.push_back(trans2); @@ -275,7 +272,7 @@ genTransactions(uint32_t seq1, uint32_t seq2) TEST_F(RPCNFTHistoryHandlerTest, IndexSpecificForwardTrue) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchNFTTransactions).WillByDefault(Return(transCursor)); @@ -285,7 +282,7 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexSpecificForwardTrue) testing::_, testing::_, true, - testing::Optional(testing::Eq(TransactionsCursor{kMIN_SEQ + 1, 0})), + testing::Optional(testing::Eq(TransactionsCursor{kMinSeq + 1, 0})), testing::_ ) ) @@ -293,7 +290,7 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexSpecificForwardTrue) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", @@ -301,19 +298,19 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexSpecificForwardTrue) "ledger_index_max": {}, "forward": true }})JSON", - kNFT_ID, - kMIN_SEQ + 1, - kMAX_SEQ - 1 + kNftId, + kMinSeq + 1, + kMaxSeq - 1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("nft_id").as_string(), kNFT_ID); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ + 1); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ - 1); + EXPECT_EQ(output.result->at("nft_id").as_string(), kNftId); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq + 1); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq - 1); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); EXPECT_FALSE(output.result->as_object().contains("limit")); @@ -322,7 +319,7 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexSpecificForwardTrue) TEST_F(RPCNFTHistoryHandlerTest, IndexSpecificForwardFalseV1) { - constexpr auto kOUTPUT = R"JSON({ + constexpr auto kOutput = R"JSON({ "nft_id": "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004", "ledger_index_min": 11, "ledger_index_max": 29, @@ -417,7 +414,7 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexSpecificForwardFalseV1) } })JSON"; - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchNFTTransactions).WillByDefault(Return(transCursor)); @@ -427,7 +424,7 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexSpecificForwardFalseV1) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ - 1, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq - 1, INT32_MAX})), testing::_ ) ) @@ -435,7 +432,7 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexSpecificForwardFalseV1) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", @@ -443,20 +440,20 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexSpecificForwardFalseV1) "ledger_index_max": {}, "forward": false }})JSON", - kNFT_ID, - kMIN_SEQ + 1, - kMAX_SEQ - 1 + kNftId, + kMinSeq + 1, + kMaxSeq - 1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result.value(), boost::json::parse(kOUTPUT)); + EXPECT_EQ(output.result.value(), boost::json::parse(kOutput)); }); } TEST_F(RPCNFTHistoryHandlerTest, IndexSpecificForwardFalseV2) { - constexpr auto kOUTPUT = R"JSON({ + constexpr auto kOutput = R"JSON({ "nft_id": "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004", "ledger_index_min": 11, "ledger_index_max": 29, @@ -555,7 +552,7 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexSpecificForwardFalseV2) } })JSON"; - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; EXPECT_CALL( @@ -564,19 +561,19 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexSpecificForwardFalseV2) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ - 1, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq - 1, INT32_MAX})), testing::_ ) ) .WillOnce(Return(transCursor)); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(2); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", @@ -584,21 +581,21 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexSpecificForwardFalseV2) "ledger_index_max": {}, "forward": false }})JSON", - kNFT_ID, - kMIN_SEQ + 1, - kMAX_SEQ - 1 + kNftId, + kMinSeq + 1, + kMaxSeq - 1 ) ); auto const output = - handler.process(kINPUT, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + handler.process(kInput, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_TRUE(output); - EXPECT_EQ(output.result.value(), boost::json::parse(kOUTPUT)); + EXPECT_EQ(output.result.value(), boost::json::parse(kOutput)); }); } TEST_F(RPCNFTHistoryHandlerTest, IndexNotSpecificForwardTrue) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchNFTTransactions).WillByDefault(Return(transCursor)); @@ -608,7 +605,7 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexNotSpecificForwardTrue) testing::_, testing::_, true, - testing::Optional(testing::Eq(TransactionsCursor{kMIN_SEQ, 0})), + testing::Optional(testing::Eq(TransactionsCursor{kMinSeq, 0})), testing::_ ) ) @@ -616,7 +613,7 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexNotSpecificForwardTrue) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", @@ -624,19 +621,19 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexNotSpecificForwardTrue) "ledger_index_max": {}, "forward": true }})JSON", - kNFT_ID, + kNftId, -1, -1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("nft_id").as_string(), kNFT_ID); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ); + EXPECT_EQ(output.result->at("nft_id").as_string(), kNftId); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); EXPECT_FALSE(output.result->as_object().contains("limit")); @@ -645,7 +642,7 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexNotSpecificForwardTrue) TEST_F(RPCNFTHistoryHandlerTest, IndexNotSpecificForwardFalse) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchNFTTransactions).WillByDefault(Return(transCursor)); @@ -655,7 +652,7 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexNotSpecificForwardFalse) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq, INT32_MAX})), testing::_ ) ) @@ -663,7 +660,7 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexNotSpecificForwardFalse) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", @@ -671,19 +668,19 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexNotSpecificForwardFalse) "ledger_index_max": {}, "forward": false }})JSON", - kNFT_ID, + kNftId, -1, -1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("nft_id").as_string(), kNFT_ID); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ); + EXPECT_EQ(output.result->at("nft_id").as_string(), kNftId); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); EXPECT_FALSE(output.result->as_object().contains("limit")); @@ -692,7 +689,7 @@ TEST_F(RPCNFTHistoryHandlerTest, IndexNotSpecificForwardFalse) TEST_F(RPCNFTHistoryHandlerTest, BinaryTrueV1) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchNFTTransactions).WillByDefault(Return(transCursor)); @@ -702,7 +699,7 @@ TEST_F(RPCNFTHistoryHandlerTest, BinaryTrueV1) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq, INT32_MAX})), testing::_ ) ) @@ -710,7 +707,7 @@ TEST_F(RPCNFTHistoryHandlerTest, BinaryTrueV1) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", @@ -718,19 +715,19 @@ TEST_F(RPCNFTHistoryHandlerTest, BinaryTrueV1) "ledger_index_max": {}, "binary": true }})JSON", - kNFT_ID, + kNftId, -1, -1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("nft_id").as_string(), kNFT_ID); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ); + EXPECT_EQ(output.result->at("nft_id").as_string(), kNftId); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); EXPECT_EQ( @@ -755,7 +752,7 @@ TEST_F(RPCNFTHistoryHandlerTest, BinaryTrueV1) TEST_F(RPCNFTHistoryHandlerTest, BinaryTrueV2) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; EXPECT_CALL( @@ -764,7 +761,7 @@ TEST_F(RPCNFTHistoryHandlerTest, BinaryTrueV2) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq, INT32_MAX})), testing::_ ) ) @@ -772,7 +769,7 @@ TEST_F(RPCNFTHistoryHandlerTest, BinaryTrueV2) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", @@ -780,20 +777,20 @@ TEST_F(RPCNFTHistoryHandlerTest, BinaryTrueV2) "ledger_index_max": {}, "binary": true }})JSON", - kNFT_ID, + kNftId, -1, -1 ) ); auto const output = - handler.process(kINPUT, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + handler.process(kInput, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("nft_id").as_string(), kNFT_ID); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ); + EXPECT_EQ(output.result->at("nft_id").as_string(), kNftId); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); EXPECT_EQ( @@ -818,7 +815,7 @@ TEST_F(RPCNFTHistoryHandlerTest, BinaryTrueV2) TEST_F(RPCNFTHistoryHandlerTest, LimitAndMarker) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchNFTTransactions).WillByDefault(Return(transCursor)); @@ -836,7 +833,7 @@ TEST_F(RPCNFTHistoryHandlerTest, LimitAndMarker) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", @@ -846,20 +843,20 @@ TEST_F(RPCNFTHistoryHandlerTest, LimitAndMarker) "forward": false, "marker": {{"ledger": 10, "seq": 11}} }})JSON", - kNFT_ID, + kNftId, -1, -1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("nft_id").as_string(), kNFT_ID); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ); + EXPECT_EQ(output.result->at("nft_id").as_string(), kNftId); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq); EXPECT_EQ(output.result->at("limit").as_uint64(), 2); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); }); @@ -868,7 +865,7 @@ TEST_F(RPCNFTHistoryHandlerTest, LimitAndMarker) TEST_F(RPCNFTHistoryHandlerTest, SpecificLedgerIndex) { // adjust the order for forward->false - auto const transactions = genTransactions(kMAX_SEQ - 1, kMIN_SEQ + 1); + auto const transactions = genTransactions(kMaxSeq - 1, kMinSeq + 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchNFTTransactions).WillByDefault(Return(transCursor)); @@ -878,33 +875,33 @@ TEST_F(RPCNFTHistoryHandlerTest, SpecificLedgerIndex) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ - 1, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq - 1, INT32_MAX})), testing::_ ) ) .Times(1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ - 1); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq - 1); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ - 1, _)).WillByDefault(Return(ledgerHeader)); + ON_CALL(*backend_, fetchLedgerBySequence(kMaxSeq - 1, _)).WillByDefault(Return(ledgerHeader)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_index": {} }})JSON", - kNFT_ID, - kMAX_SEQ - 1 + kNftId, + kMaxSeq - 1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("nft_id").as_string(), kNFT_ID); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMAX_SEQ - 1); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ - 1); + EXPECT_EQ(output.result->at("nft_id").as_string(), kNftId); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMaxSeq - 1); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq - 1); EXPECT_FALSE(output.result->as_object().contains("limit")); EXPECT_FALSE(output.result->as_object().contains("marker")); EXPECT_EQ(output.result->at("transactions").as_array().size(), 1); @@ -914,21 +911,21 @@ TEST_F(RPCNFTHistoryHandlerTest, SpecificLedgerIndex) TEST_F(RPCNFTHistoryHandlerTest, SpecificNonexistLedgerIntIndex) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ - 1, _)).WillByDefault(Return(std::nullopt)); + ON_CALL(*backend_, fetchLedgerBySequence(kMaxSeq - 1, _)).WillByDefault(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_index": {} }})JSON", - kNFT_ID, - kMAX_SEQ - 1 + kNftId, + kMaxSeq - 1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -939,21 +936,21 @@ TEST_F(RPCNFTHistoryHandlerTest, SpecificNonexistLedgerIntIndex) TEST_F(RPCNFTHistoryHandlerTest, SpecificNonexistLedgerStringIndex) { EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence(kMAX_SEQ - 1, _)).WillByDefault(Return(std::nullopt)); + ON_CALL(*backend_, fetchLedgerBySequence(kMaxSeq - 1, _)).WillByDefault(Return(std::nullopt)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_index": "{}" }})JSON", - kNFT_ID, - kMAX_SEQ - 1 + kNftId, + kMaxSeq - 1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -964,7 +961,7 @@ TEST_F(RPCNFTHistoryHandlerTest, SpecificNonexistLedgerStringIndex) TEST_F(RPCNFTHistoryHandlerTest, SpecificLedgerHash) { // adjust the order for forward->false - auto const transactions = genTransactions(kMAX_SEQ - 1, kMIN_SEQ + 1); + auto const transactions = genTransactions(kMaxSeq - 1, kMinSeq + 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchNFTTransactions).WillByDefault(Return(transCursor)); @@ -974,34 +971,34 @@ TEST_F(RPCNFTHistoryHandlerTest, SpecificLedgerHash) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ - 1, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq - 1, INT32_MAX})), testing::_ ) ) .Times(1); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, kMAX_SEQ - 1); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, kMaxSeq - 1); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": "{}" }})JSON", - kNFT_ID, - kLEDGER_HASH + kNftId, + kLedgerHash ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("nft_id").as_string(), kNFT_ID); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMAX_SEQ - 1); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ - 1); + EXPECT_EQ(output.result->at("nft_id").as_string(), kNftId); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMaxSeq - 1); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq - 1); EXPECT_FALSE(output.result->as_object().contains("limit")); EXPECT_FALSE(output.result->as_object().contains("marker")); EXPECT_EQ(output.result->at("transactions").as_array().size(), 1); @@ -1010,7 +1007,7 @@ TEST_F(RPCNFTHistoryHandlerTest, SpecificLedgerHash) TEST_F(RPCNFTHistoryHandlerTest, TxLessThanMinSeq) { - auto const transactions = genTransactions(kMAX_SEQ - 1, kMIN_SEQ + 1); + auto const transactions = genTransactions(kMaxSeq - 1, kMinSeq + 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchNFTTransactions).WillByDefault(Return(transCursor)); @@ -1020,7 +1017,7 @@ TEST_F(RPCNFTHistoryHandlerTest, TxLessThanMinSeq) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ - 1, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq - 1, INT32_MAX})), testing::_ ) ) @@ -1028,7 +1025,7 @@ TEST_F(RPCNFTHistoryHandlerTest, TxLessThanMinSeq) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", @@ -1036,16 +1033,16 @@ TEST_F(RPCNFTHistoryHandlerTest, TxLessThanMinSeq) "ledger_index_max": {}, "forward": false }})JSON", - kNFT_ID, - kMIN_SEQ + 2, - kMAX_SEQ - 1 + kNftId, + kMinSeq + 2, + kMaxSeq - 1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("nft_id").as_string(), kNFT_ID); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ + 2); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ - 1); + EXPECT_EQ(output.result->at("nft_id").as_string(), kNftId); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq + 2); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq - 1); EXPECT_EQ(output.result->at("transactions").as_array().size(), 1); EXPECT_FALSE(output.result->as_object().contains("limit")); EXPECT_FALSE(output.result->as_object().contains("marker")); @@ -1054,7 +1051,7 @@ TEST_F(RPCNFTHistoryHandlerTest, TxLessThanMinSeq) TEST_F(RPCNFTHistoryHandlerTest, TxLargerThanMaxSeq) { - auto const transactions = genTransactions(kMAX_SEQ - 1, kMIN_SEQ + 1); + auto const transactions = genTransactions(kMaxSeq - 1, kMinSeq + 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchNFTTransactions).WillByDefault(Return(transCursor)); @@ -1064,7 +1061,7 @@ TEST_F(RPCNFTHistoryHandlerTest, TxLargerThanMaxSeq) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ - 2, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq - 2, INT32_MAX})), testing::_ ) ) @@ -1072,7 +1069,7 @@ TEST_F(RPCNFTHistoryHandlerTest, TxLargerThanMaxSeq) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", @@ -1080,28 +1077,28 @@ TEST_F(RPCNFTHistoryHandlerTest, TxLargerThanMaxSeq) "ledger_index_max": {}, "forward": false }})JSON", - kNFT_ID, - kMIN_SEQ + 1, - kMAX_SEQ - 2 + kNftId, + kMinSeq + 1, + kMaxSeq - 2 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("nft_id").as_string(), kNFT_ID); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ + 1); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ - 2); + EXPECT_EQ(output.result->at("nft_id").as_string(), kNftId); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq + 1); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq - 2); EXPECT_EQ(output.result->at("transactions").as_array().size(), 1); EXPECT_FALSE(output.result->as_object().contains("limit")); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); }); } TEST_F(RPCNFTHistoryHandlerTest, LimitMoreThanMax) { - auto const transactions = genTransactions(kMIN_SEQ + 1, kMAX_SEQ - 1); + auto const transactions = genTransactions(kMinSeq + 1, kMaxSeq - 1); auto const transCursor = TransactionsAndCursor{.txns = transactions, .cursor = TransactionsCursor{12, 34}}; ON_CALL(*backend_, fetchNFTTransactions).WillByDefault(Return(transCursor)); @@ -1111,7 +1108,7 @@ TEST_F(RPCNFTHistoryHandlerTest, LimitMoreThanMax) testing::_, testing::_, false, - testing::Optional(testing::Eq(TransactionsCursor{kMAX_SEQ - 1, INT32_MAX})), + testing::Optional(testing::Eq(TransactionsCursor{kMaxSeq - 1, INT32_MAX})), testing::_ ) ) @@ -1119,7 +1116,7 @@ TEST_F(RPCNFTHistoryHandlerTest, LimitMoreThanMax) runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTHistoryHandler{backend_}}; - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", @@ -1128,24 +1125,22 @@ TEST_F(RPCNFTHistoryHandlerTest, LimitMoreThanMax) "forward": false, "limit": {} }})JSON", - kNFT_ID, - kMIN_SEQ + 1, - kMAX_SEQ - 1, - NFTHistoryHandler::kLIMIT_MAX + 1 + kNftId, + kMinSeq + 1, + kMaxSeq - 1, + NFTHistoryHandler::kLimitMax + 1 ) ); - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("nft_id").as_string(), kNFT_ID); - EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMIN_SEQ + 1); - EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMAX_SEQ - 1); + EXPECT_EQ(output.result->at("nft_id").as_string(), kNftId); + EXPECT_EQ(output.result->at("ledger_index_min").as_uint64(), kMinSeq + 1); + EXPECT_EQ(output.result->at("ledger_index_max").as_uint64(), kMaxSeq - 1); EXPECT_EQ( output.result->at("marker").as_object(), - json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") + boost::json::parse(R"JSON({"ledger": 12, "seq": 34})JSON") ); EXPECT_EQ(output.result->at("transactions").as_array().size(), 2); - EXPECT_EQ( - output.result->as_object().at("limit").as_uint64(), NFTHistoryHandler::kLIMIT_MAX - ); + EXPECT_EQ(output.result->as_object().at("limit").as_uint64(), NFTHistoryHandler::kLimitMax); }); } diff --git a/tests/unit/rpc/handlers/NFTInfoTests.cpp b/tests/unit/rpc/handlers/NFTInfoTests.cpp index 55b0999c0..443199e03 100644 --- a/tests/unit/rpc/handlers/NFTInfoTests.cpp +++ b/tests/unit/rpc/handlers/NFTInfoTests.cpp @@ -19,15 +19,14 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kNFT_ID = "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004"; -constexpr auto kNFT_ID2 = "00081388319F12E15BCA13E1B933BF4C99C8E1BBC36BD4910A85D52F00000022"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kNftId = "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004"; +constexpr auto kNftID2 = "00081388319F12E15BCA13E1B933BF4C99C8E1BBC36BD4910A85D52F00000022"; } // namespace @@ -42,13 +41,13 @@ TEST_F(RPCNFTInfoHandlerTest, NonHexLedgerHash) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTInfoHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": "xxx" }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -64,13 +63,13 @@ TEST_F(RPCNFTInfoHandlerTest, NonStringLedgerHash) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTInfoHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": 123 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -86,13 +85,13 @@ TEST_F(RPCNFTInfoHandlerTest, InvalidLedgerIndexString) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTInfoHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_index": "notvalidated" }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -109,7 +108,7 @@ TEST_F(RPCNFTInfoHandlerTest, NFTIDInvalidFormat) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTInfoHandler{backend_}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "nft_id": "00080000B4F4AFC5FBCBD76873F18006173D2193467D3EE7" })JSON"); auto const output = handler.process(input, Context{.yield = yield}); @@ -125,7 +124,7 @@ TEST_F(RPCNFTInfoHandlerTest, NFTIDNotString) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTInfoHandler{backend_}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "nft_id": 12 })JSON"); auto const output = handler.process(input, Context{.yield = yield}); @@ -141,18 +140,18 @@ TEST_F(RPCNFTInfoHandlerTest, NFTIDNotString) TEST_F(RPCNFTInfoHandlerTest, NonExistLedgerViaLedgerHash) { // mock fetchLedgerByHash return empty - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": "{}" }})JSON", - kNFT_ID, - kLEDGER_HASH + kNftId, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -171,15 +170,15 @@ TEST_F(RPCNFTInfoHandlerTest, NonExistLedgerViaLedgerStringIndex) { // mock fetchLedgerBySequence return empty ON_CALL(*backend_, fetchLedgerBySequence) - .WillByDefault(Return(std::optional{})); + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_index": "4" }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -196,15 +195,15 @@ TEST_F(RPCNFTInfoHandlerTest, NonExistLedgerViaLedgerIntIndex) { // mock fetchLedgerBySequence return empty ON_CALL(*backend_, fetchLedgerBySequence) - .WillByDefault(Return(std::optional{})); + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_index": 4 }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -222,18 +221,18 @@ TEST_F(RPCNFTInfoHandlerTest, NonExistLedgerViaLedgerIntIndex) TEST_F(RPCNFTInfoHandlerTest, NonExistLedgerViaLedgerHash2) { // mock fetchLedgerByHash return ledger but seq is 31 > 30 - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 31); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, 31); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": "{}" }})JSON", - kNFT_ID, - kLEDGER_HASH + kNftId, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -252,13 +251,13 @@ TEST_F(RPCNFTInfoHandlerTest, NonExistLedgerViaLedgerIndex2) // no need to check from db,call fetchLedgerBySequence 0 time // differ from previous logic EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(0); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_index": "31" }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -274,21 +273,21 @@ TEST_F(RPCNFTInfoHandlerTest, NonExistLedgerViaLedgerIndex2) // error case nft does not exist TEST_F(RPCNFTInfoHandlerTest, NonExistNFT) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // fetch nft return empty ON_CALL(*backend_, fetchNFT).WillByDefault(Return(std::optional{})); - EXPECT_CALL(*backend_, fetchNFT(ripple::uint256{kNFT_ID}, 30, _)).Times(1); - auto const input = json::parse( + EXPECT_CALL(*backend_, fetchNFT(xrpl::uint256{kNftId}, 30, _)).Times(1); + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": "{}" }})JSON", - kNFT_ID, - kLEDGER_HASH + kNftId, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -304,7 +303,7 @@ TEST_F(RPCNFTInfoHandlerTest, NonExistNFT) // normal case when only provide nft_id TEST_F(RPCNFTInfoHandlerTest, DefaultParameters) { - static constexpr auto kCURRENT_OUTPUT = R"JSON({ + static constexpr auto kCurrentOutput = R"JSON({ "nft_id": "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004", "ledger_index": 30, "owner": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -318,35 +317,35 @@ TEST_F(RPCNFTInfoHandlerTest, DefaultParameters) "validated": true })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch nft return something - auto const nft = std::make_optional(createNft(kNFT_ID, kACCOUNT, ledgerHeader.seq)); + auto const nft = std::make_optional(createNft(kNftId, kAccount, ledgerHeader.seq)); ON_CALL(*backend_, fetchNFT).WillByDefault(Return(nft)); - EXPECT_CALL(*backend_, fetchNFT(ripple::uint256{kNFT_ID}, 30, _)).Times(1); + EXPECT_CALL(*backend_, fetchNFT(xrpl::uint256{kNftId}, 30, _)).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}" }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](auto yield) { auto handler = AnyHandler{NFTInfoHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(kCURRENT_OUTPUT), *output.result); + EXPECT_EQ(boost::json::parse(kCurrentOutput), *output.result); }); } // nft is burned -> should not omit uri TEST_F(RPCNFTInfoHandlerTest, BurnedNFT) { - static constexpr auto kCURRENT_OUTPUT = R"JSON({ + static constexpr auto kCurrentOutput = R"JSON({ "nft_id": "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004", "ledger_index": 30, "owner": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -360,37 +359,37 @@ TEST_F(RPCNFTInfoHandlerTest, BurnedNFT) "validated": true })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch nft return something auto const nft = std::make_optional( - createNft(kNFT_ID, kACCOUNT, ledgerHeader.seq, ripple::Blob{'u', 'r', 'i'}, true) + createNft(kNftId, kAccount, ledgerHeader.seq, xrpl::Blob{'u', 'r', 'i'}, true) ); ON_CALL(*backend_, fetchNFT).WillByDefault(Return(nft)); - EXPECT_CALL(*backend_, fetchNFT(ripple::uint256{kNFT_ID}, 30, _)).Times(1); + EXPECT_CALL(*backend_, fetchNFT(xrpl::uint256{kNftId}, 30, _)).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}" }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](auto yield) { auto handler = AnyHandler{NFTInfoHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(kCURRENT_OUTPUT), *output.result); + EXPECT_EQ(boost::json::parse(kCurrentOutput), *output.result); }); } // uri is not available -> should specify an empty string TEST_F(RPCNFTInfoHandlerTest, NotBurnedNFTWithoutURI) { - static constexpr auto kCURRENT_OUTPUT = R"JSON({ + static constexpr auto kCurrentOutput = R"JSON({ "nft_id": "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004", "ledger_index": 30, "owner": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -404,36 +403,36 @@ TEST_F(RPCNFTInfoHandlerTest, NotBurnedNFTWithoutURI) "validated": true })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch nft return something auto const nft = - std::make_optional(createNft(kNFT_ID, kACCOUNT, ledgerHeader.seq, ripple::Blob{})); + std::make_optional(createNft(kNftId, kAccount, ledgerHeader.seq, xrpl::Blob{})); ON_CALL(*backend_, fetchNFT).WillByDefault(Return(nft)); - EXPECT_CALL(*backend_, fetchNFT(ripple::uint256{kNFT_ID}, 30, _)).Times(1); + EXPECT_CALL(*backend_, fetchNFT(xrpl::uint256{kNftId}, 30, _)).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}" }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](auto yield) { auto handler = AnyHandler{NFTInfoHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(kCURRENT_OUTPUT), *output.result); + EXPECT_EQ(boost::json::parse(kCurrentOutput), *output.result); }); } // check taxon field, transfer fee and serial TEST_F(RPCNFTInfoHandlerTest, NFTWithExtraFieldsSet) { - static constexpr auto kCURRENT_OUTPUT = R"JSON({ + static constexpr auto kCurrentOutput = R"JSON({ "nft_id": "00081388319F12E15BCA13E1B933BF4C99C8E1BBC36BD4910A85D52F00000022", "ledger_index": 30, "owner": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", @@ -447,27 +446,27 @@ TEST_F(RPCNFTInfoHandlerTest, NFTWithExtraFieldsSet) "validated": true })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // fetch nft return something - auto const nft = std::make_optional(createNft(kNFT_ID2, kACCOUNT, ledgerHeader.seq)); + auto const nft = std::make_optional(createNft(kNftID2, kAccount, ledgerHeader.seq)); ON_CALL(*backend_, fetchNFT).WillByDefault(Return(nft)); - EXPECT_CALL(*backend_, fetchNFT(ripple::uint256{kNFT_ID2}, 30, _)).Times(1); + EXPECT_CALL(*backend_, fetchNFT(xrpl::uint256{kNftID2}, 30, _)).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}" }})JSON", - kNFT_ID2 + kNftID2 ) ); runSpawn([&, this](auto yield) { auto handler = AnyHandler{NFTInfoHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(kCURRENT_OUTPUT), *output.result); + EXPECT_EQ(boost::json::parse(kCurrentOutput), *output.result); }); } diff --git a/tests/unit/rpc/handlers/NFTSellOffersTests.cpp b/tests/unit/rpc/handlers/NFTSellOffersTests.cpp index 488187965..e793316be 100644 --- a/tests/unit/rpc/handlers/NFTSellOffersTests.cpp +++ b/tests/unit/rpc/handlers/NFTSellOffersTests.cpp @@ -23,16 +23,15 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kNFT_ID = "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004"; -constexpr auto kINDEX1 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kINDEX2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kNftId = "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004"; +constexpr auto kIndex1 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kIndex2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; } // namespace @@ -47,13 +46,13 @@ TEST_F(RPCNFTSellOffersHandlerTest, LimitNotInt) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTSellOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": "xxx" }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -68,13 +67,13 @@ TEST_F(RPCNFTSellOffersHandlerTest, LimitNegative) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTSellOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": -1 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -89,13 +88,13 @@ TEST_F(RPCNFTSellOffersHandlerTest, LimitZero) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTSellOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": 0 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -110,13 +109,13 @@ TEST_F(RPCNFTSellOffersHandlerTest, NonHexLedgerHash) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTSellOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": "xxx" }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -132,13 +131,13 @@ TEST_F(RPCNFTSellOffersHandlerTest, NonStringLedgerHash) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTSellOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": 123 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -154,13 +153,13 @@ TEST_F(RPCNFTSellOffersHandlerTest, InvalidLedgerIndexString) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTSellOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_index": "notvalidated" }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{.yield = yield}); @@ -177,7 +176,7 @@ TEST_F(RPCNFTSellOffersHandlerTest, NFTIDInvalidFormat) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTSellOffersHandler{backend_}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "nft_id": "00080000B4F4AFC5FBCBD76873F18006173D2193467D3EE7" })JSON"); auto const output = handler.process(input, Context{.yield = yield}); @@ -193,7 +192,7 @@ TEST_F(RPCNFTSellOffersHandlerTest, NFTIDNotString) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTSellOffersHandler{backend_}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "nft_id": 12 })JSON"); auto const output = handler.process(input, Context{.yield = yield}); @@ -209,18 +208,18 @@ TEST_F(RPCNFTSellOffersHandlerTest, NFTIDNotString) TEST_F(RPCNFTSellOffersHandlerTest, NonExistLedgerViaLedgerHash) { // mock fetchLedgerByHash return empty - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": "{}" }})JSON", - kNFT_ID, - kLEDGER_HASH + kNftId, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -239,15 +238,15 @@ TEST_F(RPCNFTSellOffersHandlerTest, NonExistLedgerViaLedgerIndex) { // mock fetchLedgerBySequence return empty ON_CALL(*backend_, fetchLedgerBySequence) - .WillByDefault(Return(std::optional{})); + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_index": "4" }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -265,18 +264,18 @@ TEST_F(RPCNFTSellOffersHandlerTest, NonExistLedgerViaLedgerIndex) TEST_F(RPCNFTSellOffersHandlerTest, NonExistLedgerViaLedgerHash2) { // mock fetchLedgerByHash return ledger but seq is 31 > 30 - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 31); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, 31); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": "{}" }})JSON", - kNFT_ID, - kLEDGER_HASH + kNftId, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -295,13 +294,13 @@ TEST_F(RPCNFTSellOffersHandlerTest, NonExistLedgerViaLedgerIndex2) // no need to check from db, call fetchLedgerBySequence 0 time // differ from previous logic EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(0); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_index": "31" }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -317,20 +316,20 @@ TEST_F(RPCNFTSellOffersHandlerTest, NonExistLedgerViaLedgerIndex2) // error case when nft is not found TEST_F(RPCNFTSellOffersHandlerTest, NoNFT) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); ON_CALL(*backend_, doFetchLedgerObject).WillByDefault(Return(std::nullopt)); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "ledger_hash": "{}" }})JSON", - kNFT_ID, - kLEDGER_HASH + kNftId, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -347,13 +346,13 @@ TEST_F(RPCNFTSellOffersHandlerTest, MarkerNotString) { runSpawn([this](auto yield) { auto const handler = AnyHandler{NFTSellOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "marker": 9 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{yield}); @@ -366,18 +365,18 @@ TEST_F(RPCNFTSellOffersHandlerTest, MarkerNotString) } // error case : invalid marker -// marker format in this RPC is a hex-string of a ripple::uint256. +// marker format in this RPC is a hex-string of a xrpl::uint256. TEST_F(RPCNFTSellOffersHandlerTest, InvalidMarker) { runSpawn([this](auto yield) { auto const handler = AnyHandler{NFTSellOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "marker": "123invalid" }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{yield}); @@ -389,13 +388,13 @@ TEST_F(RPCNFTSellOffersHandlerTest, InvalidMarker) }); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NFTSellOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "marker": 250 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{yield}); @@ -409,7 +408,7 @@ TEST_F(RPCNFTSellOffersHandlerTest, InvalidMarker) // normal case when only provide nft_id TEST_F(RPCNFTSellOffersHandlerTest, DefaultParameters) { - static constexpr auto kCORRECT_OUTPUT = R"JSON({ + static constexpr auto kCorrectOutput = R"JSON({ "nft_id": "00010000A7CAD27B688D14BA1A9FA5366554D6ADCF9CE0875B974D9F00000004", "validated": true, "offers": [ @@ -428,14 +427,14 @@ TEST_F(RPCNFTSellOffersHandlerTest, DefaultParameters) ] })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return owner index containing 2 indexes - auto const directory = ripple::keylet::nft_sells(ripple::uint256{kNFT_ID}); + auto const directory = xrpl::keylet::nftSells(xrpl::uint256{kNftId}); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); ON_CALL(*backend_, doFetchLedgerObject(directory.key, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -443,18 +442,18 @@ TEST_F(RPCNFTSellOffersHandlerTest, DefaultParameters) // return two nft sell offers std::vector bbs; - auto const offer = createNftSellOffer(kNFT_ID, kACCOUNT); + auto const offer = createNftSellOffer(kNftId, kAccount); bbs.push_back(offer.getSerializer().peekData()); bbs.push_back(offer.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}" }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](auto yield) { @@ -462,28 +461,28 @@ TEST_F(RPCNFTSellOffersHandlerTest, DefaultParameters) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(kCORRECT_OUTPUT), *output.result); + EXPECT_EQ(boost::json::parse(kCorrectOutput), *output.result); }); } // normal case when provided with nft_id and limit TEST_F(RPCNFTSellOffersHandlerTest, MultipleResultsWithMarkerAndLimitOutput) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return owner index - std::vector indexes; + std::vector indexes; std::vector bbs; auto repetitions = 500; - auto const offer = createNftSellOffer(kNFT_ID, kACCOUNT); - auto idx = ripple::uint256{kINDEX1}; + auto const offer = createNftSellOffer(kNftId, kAccount); + auto idx = xrpl::uint256{kIndex1}; while ((repetitions--) != 0) { indexes.push_back(idx++); bbs.push_back(offer.getSerializer().peekData()); } - ripple::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); + xrpl::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); ON_CALL(*backend_, doFetchLedgerObject) .WillByDefault(Return(ownerDir.getSerializer().peekData())); @@ -492,13 +491,13 @@ TEST_F(RPCNFTSellOffersHandlerTest, MultipleResultsWithMarkerAndLimitOutput) ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": 50 }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](auto yield) { @@ -518,34 +517,34 @@ TEST_F(RPCNFTSellOffersHandlerTest, MultipleResultsWithMarkerAndLimitOutput) // normal case when provided with nft_id, limit and marker TEST_F(RPCNFTSellOffersHandlerTest, ResultsForInputWithMarkerAndLimit) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return owner index - std::vector indexes; + std::vector indexes; std::vector bbs; auto repetitions = 500; - auto const offer = createNftSellOffer(kNFT_ID, kACCOUNT); - auto idx = ripple::uint256{kINDEX1}; + auto const offer = createNftSellOffer(kNftId, kAccount); + auto idx = xrpl::uint256{kIndex1}; while ((repetitions--) != 0) { indexes.push_back(idx++); bbs.push_back(offer.getSerializer().peekData()); } - ripple::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); - auto const cursorSellOffer = createNftSellOffer(kNFT_ID, kACCOUNT); + xrpl::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); + auto const cursorSellOffer = createNftSellOffer(kNftId, kAccount); // first is nft offer object auto const cursor = - ripple::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC353"}; - auto const first = ripple::keylet::nftoffer(cursor); + xrpl::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC353"}; + auto const first = xrpl::keylet::nftokenOffer(cursor); ON_CALL(*backend_, doFetchLedgerObject(first.key, testing::_, testing::_)) .WillByDefault(Return(cursorSellOffer.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject(first.key, testing::_, testing::_)).Times(1); - auto const directory = ripple::keylet::nft_sells(ripple::uint256{kNFT_ID}); + auto const directory = xrpl::keylet::nftSells(xrpl::uint256{kNftId}); auto const startHint = 0ul; // offer node is hardcoded to 0ul - auto const secondKey = ripple::keylet::page(directory, startHint).key; + auto const secondKey = xrpl::keylet::page(directory, startHint).key; ON_CALL(*backend_, doFetchLedgerObject(secondKey, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject(secondKey, testing::_, testing::_)).Times(3); @@ -553,14 +552,14 @@ TEST_F(RPCNFTSellOffersHandlerTest, ResultsForInputWithMarkerAndLimit) ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "marker": "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC353", "limit": 50 }})JSON", - kNFT_ID + kNftId ) ); runSpawn([&, this](auto yield) { @@ -582,34 +581,34 @@ TEST_F(RPCNFTSellOffersHandlerTest, ResultsForInputWithMarkerAndLimit) // nothing left after reading remaining 50 entries TEST_F(RPCNFTSellOffersHandlerTest, ResultsWithoutMarkerForInputWithMarkerAndLimit) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(3); // return owner index - std::vector indexes; + std::vector indexes; std::vector bbs; auto repetitions = 100; - auto const offer = createNftSellOffer(kNFT_ID, kACCOUNT); - auto idx = ripple::uint256{kINDEX1}; + auto const offer = createNftSellOffer(kNftId, kAccount); + auto idx = xrpl::uint256{kIndex1}; while ((repetitions--) != 0) { indexes.push_back(idx++); bbs.push_back(offer.getSerializer().peekData()); } - ripple::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kINDEX1); - auto const cursorSellOffer = createNftSellOffer(kNFT_ID, kACCOUNT); + xrpl::STObject const ownerDir = createOwnerDirLedgerObject(indexes, kIndex1); + auto const cursorSellOffer = createNftSellOffer(kNftId, kAccount); // first is nft offer object auto const cursor = - ripple::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC353"}; - auto const first = ripple::keylet::nftoffer(cursor); + xrpl::uint256{"E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC353"}; + auto const first = xrpl::keylet::nftokenOffer(cursor); ON_CALL(*backend_, doFetchLedgerObject(first.key, testing::_, testing::_)) .WillByDefault(Return(cursorSellOffer.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject(first.key, testing::_, testing::_)).Times(1); - auto const directory = ripple::keylet::nft_sells(ripple::uint256{kNFT_ID}); + auto const directory = xrpl::keylet::nftSells(xrpl::uint256{kNftId}); auto const startHint = 0ul; // offer node is hardcoded to 0ul - auto const secondKey = ripple::keylet::page(directory, startHint).key; + auto const secondKey = xrpl::keylet::page(directory, startHint).key; ON_CALL(*backend_, doFetchLedgerObject(secondKey, testing::_, testing::_)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject(secondKey, testing::_, testing::_)).Times(7); @@ -619,14 +618,14 @@ TEST_F(RPCNFTSellOffersHandlerTest, ResultsWithoutMarkerForInputWithMarkerAndLim runSpawn([&, this](auto yield) { auto handler = AnyHandler{NFTSellOffersHandler{this->backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "marker": "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC353", "limit": 50 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{yield}); @@ -640,13 +639,13 @@ TEST_F(RPCNFTSellOffersHandlerTest, ResultsWithoutMarkerForInputWithMarkerAndLim runSpawn([this](auto yield) { auto const handler = AnyHandler{NFTSellOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": 49 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{yield}); @@ -655,13 +654,13 @@ TEST_F(RPCNFTSellOffersHandlerTest, ResultsWithoutMarkerForInputWithMarkerAndLim runSpawn([this](auto yield) { auto const handler = AnyHandler{NFTSellOffersHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": 501 }})JSON", - kNFT_ID + kNftId ) ); auto const output = handler.process(input, Context{yield}); @@ -671,14 +670,14 @@ TEST_F(RPCNFTSellOffersHandlerTest, ResultsWithoutMarkerForInputWithMarkerAndLim TEST_F(RPCNFTSellOffersHandlerTest, LimitLessThanMin) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return owner index containing 2 indexes - auto const directory = ripple::keylet::nft_sells(ripple::uint256{kNFT_ID}); + auto const directory = xrpl::keylet::nftSells(xrpl::uint256{kNftId}); auto const ownerDir = createOwnerDirLedgerObject( - std::vector{NFTSellOffersHandler::kLIMIT_MIN + 1, ripple::uint256{kINDEX1}}, kINDEX1 + std::vector{NFTSellOffersHandler::kLimitMin + 1, xrpl::uint256{kIndex1}}, kIndex1 ); ON_CALL(*backend_, doFetchLedgerObject(directory.key, testing::_, testing::_)) @@ -687,21 +686,21 @@ TEST_F(RPCNFTSellOffersHandlerTest, LimitLessThanMin) // return two nft buy offers std::vector bbs; - auto const offer = createNftSellOffer(kNFT_ID, kACCOUNT); - bbs.reserve(NFTSellOffersHandler::kLIMIT_MIN + 1); - for (auto i = 0; i < NFTSellOffersHandler::kLIMIT_MIN + 1; i++) + auto const offer = createNftSellOffer(kNftId, kAccount); + bbs.reserve(NFTSellOffersHandler::kLimitMin + 1); + for (auto i = 0; i < NFTSellOffersHandler::kLimitMin + 1; i++) bbs.push_back(offer.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": {} }})JSON", - kNFT_ID, - NFTSellOffersHandler::kLIMIT_MIN - 1 + kNftId, + NFTSellOffersHandler::kLimitMin - 1 ) ); runSpawn([&, this](auto yield) { @@ -709,21 +708,21 @@ TEST_F(RPCNFTSellOffersHandlerTest, LimitLessThanMin) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("offers").as_array().size(), NFTSellOffersHandler::kLIMIT_MIN); - EXPECT_EQ(output.result->at("limit").as_uint64(), NFTSellOffersHandler::kLIMIT_MIN); + EXPECT_EQ(output.result->at("offers").as_array().size(), NFTSellOffersHandler::kLimitMin); + EXPECT_EQ(output.result->at("limit").as_uint64(), NFTSellOffersHandler::kLimitMin); }); } TEST_F(RPCNFTSellOffersHandlerTest, LimitMoreThanMax) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return owner index containing 2 indexes - auto const directory = ripple::keylet::nft_sells(ripple::uint256{kNFT_ID}); + auto const directory = xrpl::keylet::nftSells(xrpl::uint256{kNftId}); auto const ownerDir = createOwnerDirLedgerObject( - std::vector{NFTSellOffersHandler::kLIMIT_MAX + 1, ripple::uint256{kINDEX1}}, kINDEX1 + std::vector{NFTSellOffersHandler::kLimitMax + 1, xrpl::uint256{kIndex1}}, kIndex1 ); ON_CALL(*backend_, doFetchLedgerObject(directory.key, testing::_, testing::_)) @@ -732,21 +731,21 @@ TEST_F(RPCNFTSellOffersHandlerTest, LimitMoreThanMax) // return two nft buy offers std::vector bbs; - auto const offer = createNftSellOffer(kNFT_ID, kACCOUNT); - bbs.reserve(NFTSellOffersHandler::kLIMIT_MAX + 1); - for (auto i = 0; i < NFTSellOffersHandler::kLIMIT_MAX + 1; i++) + auto const offer = createNftSellOffer(kNftId, kAccount); + bbs.reserve(NFTSellOffersHandler::kLimitMax + 1); + for (auto i = 0; i < NFTSellOffersHandler::kLimitMax + 1; i++) bbs.push_back(offer.getSerializer().peekData()); ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "nft_id": "{}", "limit": {} }})JSON", - kNFT_ID, - NFTSellOffersHandler::kLIMIT_MAX + 1 + kNftId, + NFTSellOffersHandler::kLimitMax + 1 ) ); runSpawn([&, this](auto yield) { @@ -754,7 +753,7 @@ TEST_F(RPCNFTSellOffersHandlerTest, LimitMoreThanMax) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("offers").as_array().size(), NFTSellOffersHandler::kLIMIT_MAX); - EXPECT_EQ(output.result->at("limit").as_uint64(), NFTSellOffersHandler::kLIMIT_MAX); + EXPECT_EQ(output.result->at("offers").as_array().size(), NFTSellOffersHandler::kLimitMax); + EXPECT_EQ(output.result->at("limit").as_uint64(), NFTSellOffersHandler::kLimitMax); }); } diff --git a/tests/unit/rpc/handlers/NFTsByIssuerTest.cpp b/tests/unit/rpc/handlers/NFTsByIssuerTest.cpp index 520bf7632..1d90427e4 100644 --- a/tests/unit/rpc/handlers/NFTsByIssuerTest.cpp +++ b/tests/unit/rpc/handlers/NFTsByIssuerTest.cpp @@ -22,21 +22,20 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kACCOUNT = "r4X6JLsBfhNK4UnquNkCxhVHKPkvbQff67"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kNFT_ID1 = +constexpr auto kAccount = "r4X6JLsBfhNK4UnquNkCxhVHKPkvbQff67"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kNftID1 = "00080000EC28C2910FD1C454A51598AAB91C8876286B2E7F0000099B00000000"; // taxon 0 -constexpr auto kNFT_ID2 = +constexpr auto kNftID2 = "00080000EC28C2910FD1C454A51598AAB91C8876286B2E7F16E5DA9C00000001"; // taxon 0 -constexpr auto kNFT_ID3 = +constexpr auto kNftID3 = "00080000EC28C2910FD1C454A51598AAB91C8876286B2E7F5B974D9E00000004"; // taxon 1 -std::string const kNFT1_OUT = +std::string const kNfT1Out = R"JSON({ "nft_id": "00080000EC28C2910FD1C454A51598AAB91C8876286B2E7F0000099B00000000", "ledger_index": 29, @@ -49,7 +48,7 @@ std::string const kNFT1_OUT = "nft_taxon": 0, "nft_serial": 0 })JSON"; -std::string const kNFT2_OUT = +std::string const kNfT2Out = R"JSON({ "nft_id": "00080000EC28C2910FD1C454A51598AAB91C8876286B2E7F16E5DA9C00000001", "ledger_index": 29, @@ -62,7 +61,7 @@ std::string const kNFT2_OUT = "nft_taxon": 0, "nft_serial": 1 })JSON"; -std::string const kNFT3_OUT = +std::string const kNfT3Out = R"JSON({ "nft_id": "00080000EC28C2910FD1C454A51598AAB91C8876286B2E7F5B974D9E00000004", "ledger_index": 29, @@ -89,13 +88,13 @@ TEST_F(RPCNFTsByIssuerHandlerTest, NonHexLedgerHash) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTsByIssuerHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}", "ledger_hash": "xxx" }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{.yield = std::ref(yield)}); @@ -111,13 +110,13 @@ TEST_F(RPCNFTsByIssuerHandlerTest, NonStringLedgerHash) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTsByIssuerHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}", "ledger_hash": 123 }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{.yield = std::ref(yield)}); @@ -133,13 +132,13 @@ TEST_F(RPCNFTsByIssuerHandlerTest, InvalidLedgerIndexString) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTsByIssuerHandler{backend_}}; - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}", "ledger_index": "notvalidated" }})JSON", - kACCOUNT + kAccount ) ); auto const output = handler.process(input, Context{.yield = std::ref(yield)}); @@ -156,7 +155,7 @@ TEST_F(RPCNFTsByIssuerHandlerTest, NFTIssuerInvalidFormat) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTsByIssuerHandler{backend_}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "issuer": "xxx" })JSON"); auto const output = handler.process(input, Context{.yield = std::ref(yield)}); @@ -172,7 +171,7 @@ TEST_F(RPCNFTsByIssuerHandlerTest, NFTIssuerMissing) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTsByIssuerHandler{backend_}}; - auto const input = json::parse(R"JSON({})JSON"); + auto const input = boost::json::parse(R"JSON({})JSON"); auto const output = handler.process(input, Context{.yield = std::ref(yield)}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -186,7 +185,7 @@ TEST_F(RPCNFTsByIssuerHandlerTest, NFTIssuerNotString) { runSpawn([this](boost::asio::yield_context yield) { auto const handler = AnyHandler{NFTsByIssuerHandler{backend_}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "issuer": 12 })JSON"); auto const output = handler.process(input, Context{.yield = std::ref(yield)}); @@ -203,17 +202,17 @@ TEST_F(RPCNFTsByIssuerHandlerTest, NonExistLedgerViaLedgerHash) { // mock fetchLedgerByHash return empty EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) + .WillByDefault(Return(std::optional{})); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -232,14 +231,14 @@ TEST_F(RPCNFTsByIssuerHandlerTest, NonExistLedgerViaLedgerStringIndex) { // mock fetchLedgerBySequence return empty EXPECT_CALL(*backend_, fetchLedgerBySequence) - .WillOnce(Return(std::optional{})); - auto const input = json::parse( + .WillOnce(Return(std::optional{})); + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}", "ledger_index": "4" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -256,14 +255,14 @@ TEST_F(RPCNFTsByIssuerHandlerTest, NonExistLedgerViaLedgerIntIndex) { // mock fetchLedgerBySequence return empty EXPECT_CALL(*backend_, fetchLedgerBySequence) - .WillOnce(Return(std::optional{})); - auto const input = json::parse( + .WillOnce(Return(std::optional{})); + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}", "ledger_index": 4 }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -281,18 +280,18 @@ TEST_F(RPCNFTsByIssuerHandlerTest, NonExistLedgerViaLedgerIntIndex) TEST_F(RPCNFTsByIssuerHandlerTest, NonExistLedgerViaLedgerHash2) { // mock fetchLedgerByHash return ledger but seq is 31 > 30 - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 31); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, 31); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -311,13 +310,13 @@ TEST_F(RPCNFTsByIssuerHandlerTest, NonExistLedgerViaLedgerIndex2) // no need to check from db,call fetchLedgerBySequence 0 time // differ from previous logic EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(0); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}", "ledger_index": "31" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -333,21 +332,21 @@ TEST_F(RPCNFTsByIssuerHandlerTest, NonExistLedgerViaLedgerIndex2) // normal case when issuer does not exist or has no NFTs TEST_F(RPCNFTsByIssuerHandlerTest, AccountNotFound) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); ON_CALL(*backend_, doFetchLedgerObject).WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](boost::asio::yield_context yield) { @@ -371,18 +370,18 @@ TEST_F(RPCNFTsByIssuerHandlerTest, DefaultParameters) "nfts": [{}], "validated": true }})JSON", - kACCOUNT, - kNFT1_OUT + kAccount, + kNfT1Out ); - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - std::vector const nfts = {createNft(kNFT_ID1, kACCOUNT, 29)}; - auto const account = getAccountIdWithString(kACCOUNT); + std::vector const nfts = {createNft(kNftID1, kAccount, 29)}; + auto const account = getAccountIdWithString(kAccount); ON_CALL(*backend_, fetchNFTsByIssuer) .WillByDefault(Return(NFTsAndCursor{.nfts = nfts, .cursor = {}})); EXPECT_CALL( @@ -390,19 +389,19 @@ TEST_F(RPCNFTsByIssuerHandlerTest, DefaultParameters) ) .Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto& yield) { auto handler = AnyHandler{NFTsByIssuerHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(currentOutput), *output.result); + EXPECT_EQ(boost::json::parse(currentOutput), *output.result); }); } @@ -428,20 +427,20 @@ TEST_F(RPCNFTsByIssuerHandlerTest, SpecificLedgerIndex) }}], "validated": true }})JSON", - kACCOUNT, + kAccount, specificLedger ); - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, specificLedger); + auto ledgerHeader = createLedgerHeader(kLedgerHash, specificLedger); ON_CALL(*backend_, fetchLedgerBySequence(specificLedger, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, specificLedger, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - std::vector const nfts = {createNft(kNFT_ID1, kACCOUNT, specificLedger)}; - auto const account = getAccountIdWithString(kACCOUNT); + std::vector const nfts = {createNft(kNftID1, kAccount, specificLedger)}; + auto const account = getAccountIdWithString(kAccount); ON_CALL(*backend_, fetchNFTsByIssuer) .WillByDefault(Return(NFTsAndCursor{.nfts = nfts, .cursor = {}})); EXPECT_CALL( @@ -450,13 +449,13 @@ TEST_F(RPCNFTsByIssuerHandlerTest, SpecificLedgerIndex) ) .Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}", "ledger_index": {} }})JSON", - kACCOUNT, + kAccount, specificLedger ) ); @@ -464,7 +463,7 @@ TEST_F(RPCNFTsByIssuerHandlerTest, SpecificLedgerIndex) auto handler = AnyHandler{NFTsByIssuerHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(currentOutput), *output.result); + EXPECT_EQ(boost::json::parse(currentOutput), *output.result); }); } @@ -479,18 +478,18 @@ TEST_F(RPCNFTsByIssuerHandlerTest, TaxonParameter) "validated": true, "nft_taxon": 0 }})JSON", - kACCOUNT, - kNFT1_OUT + kAccount, + kNfT1Out ); - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - std::vector const nfts = {createNft(kNFT_ID1, kACCOUNT, 29)}; - auto const account = getAccountIdWithString(kACCOUNT); + std::vector const nfts = {createNft(kNftID1, kAccount, 29)}; + auto const account = getAccountIdWithString(kAccount); ON_CALL(*backend_, fetchNFTsByIssuer) .WillByDefault(Return(NFTsAndCursor{.nfts = nfts, .cursor = {}})); EXPECT_CALL( @@ -498,20 +497,20 @@ TEST_F(RPCNFTsByIssuerHandlerTest, TaxonParameter) ) .Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}", "nft_taxon": 0 }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto& yield) { auto handler = AnyHandler{NFTsByIssuerHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(currentOutput), *output.result); + EXPECT_EQ(boost::json::parse(currentOutput), *output.result); }); } @@ -526,40 +525,40 @@ TEST_F(RPCNFTsByIssuerHandlerTest, MarkerParameter) "validated": true, "marker": "00080000EC28C2910FD1C454A51598AAB91C8876286B2E7F5B974D9E00000004" }})JSON", - kACCOUNT, - kNFT3_OUT + kAccount, + kNfT3Out ); - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - std::vector const nfts = {createNft(kNFT_ID3, kACCOUNT, 29)}; - auto const account = getAccountIdWithString(kACCOUNT); + std::vector const nfts = {createNft(kNftID3, kAccount, 29)}; + auto const account = getAccountIdWithString(kAccount); ON_CALL(*backend_, fetchNFTsByIssuer) - .WillByDefault(Return(NFTsAndCursor{.nfts = nfts, .cursor = ripple::uint256{kNFT_ID3}})); + .WillByDefault(Return(NFTsAndCursor{.nfts = nfts, .cursor = xrpl::uint256{kNftID3}})); EXPECT_CALL( - *backend_, fetchNFTsByIssuer(account, _, Const(30), _, Eq(ripple::uint256{kNFT_ID1}), _) + *backend_, fetchNFTsByIssuer(account, _, Const(30), _, Eq(xrpl::uint256{kNftID1}), _) ) .Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}", "marker": "{}" }})JSON", - kACCOUNT, - kNFT_ID1 + kAccount, + kNftID1 ) ); runSpawn([&, this](auto& yield) { auto handler = AnyHandler{NFTsByIssuerHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(currentOutput), *output.result); + EXPECT_EQ(boost::json::parse(currentOutput), *output.result); }); } @@ -573,24 +572,24 @@ TEST_F(RPCNFTsByIssuerHandlerTest, MultipleNFTs) "nfts": [{}, {}, {}], "validated": true }})JSON", - kACCOUNT, - kNFT1_OUT, - kNFT2_OUT, - kNFT3_OUT + kAccount, + kNfT1Out, + kNfT2Out, + kNfT3Out ); - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); std::vector const nfts = { - createNft(kNFT_ID1, kACCOUNT, 29), - createNft(kNFT_ID2, kACCOUNT, 29), - createNft(kNFT_ID3, kACCOUNT, 29) + createNft(kNftID1, kAccount, 29), + createNft(kNftID2, kAccount, 29), + createNft(kNftID3, kAccount, 29) }; - auto const account = getAccountIdWithString(kACCOUNT); + auto const account = getAccountIdWithString(kAccount); ON_CALL(*backend_, fetchNFTsByIssuer) .WillByDefault(Return(NFTsAndCursor{.nfts = nfts, .cursor = {}})); EXPECT_CALL( @@ -598,19 +597,19 @@ TEST_F(RPCNFTsByIssuerHandlerTest, MultipleNFTs) ) .Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}" }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto& yield) { auto handler = AnyHandler{NFTsByIssuerHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(currentOutput), *output.result); + EXPECT_EQ(boost::json::parse(currentOutput), *output.result); }); } @@ -624,18 +623,18 @@ TEST_F(RPCNFTsByIssuerHandlerTest, LimitMoreThanMax) "nfts": [{}], "validated": true }})JSON", - kACCOUNT, - kNFT1_OUT + kAccount, + kNfT1Out ); - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - auto const accountKk = ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key; + auto const accountKk = xrpl::keylet::account(getAccountIdWithString(kAccount)).key; ON_CALL(*backend_, doFetchLedgerObject(accountKk, 30, _)) .WillByDefault(Return(Blob{'f', 'a', 'k', 'e'})); - std::vector const nfts = {createNft(kNFT_ID1, kACCOUNT, 29)}; - auto const account = getAccountIdWithString(kACCOUNT); + std::vector const nfts = {createNft(kNftID1, kAccount, 29)}; + auto const account = getAccountIdWithString(kAccount); ON_CALL(*backend_, fetchNFTsByIssuer) .WillByDefault(Return(NFTsAndCursor{.nfts = nfts, .cursor = {}})); EXPECT_CALL( @@ -644,27 +643,27 @@ TEST_F(RPCNFTsByIssuerHandlerTest, LimitMoreThanMax) account, Eq(std::nullopt), Const(30), - NFTsByIssuerHandler::kLIMIT_MAX, + NFTsByIssuerHandler::kLimitMax, Eq(std::nullopt), _ ) ) .Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "issuer": "{}", "limit": {} }})JSON", - kACCOUNT, - NFTsByIssuerHandler::kLIMIT_MAX + 1 + kAccount, + NFTsByIssuerHandler::kLimitMax + 1 ) ); runSpawn([&, this](auto& yield) { auto handler = AnyHandler{NFTsByIssuerHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(currentOutput), *output.result); + EXPECT_EQ(boost::json::parse(currentOutput), *output.result); }); } diff --git a/tests/unit/rpc/handlers/NoRippleCheckTests.cpp b/tests/unit/rpc/handlers/NoRippleCheckTests.cpp index c5edf43c7..279e195b8 100644 --- a/tests/unit/rpc/handlers/NoRippleCheckTests.cpp +++ b/tests/unit/rpc/handlers/NoRippleCheckTests.cpp @@ -22,18 +22,17 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kINDEX1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; -constexpr auto kINDEX2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; -constexpr auto kISSUER = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; -constexpr auto kTXN_ID = "E3FE6EA3D48F0C2B639448020EA4F03D4F4F8FFDB243A852A0F59177921B4879"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kIndex1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; +constexpr auto kIndex2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kIssuer = "rK9DrarGKnVEo2nYp5MfVRXRYf5yRX3mwD"; +constexpr auto kTxnId = "E3FE6EA3D48F0C2B639448020EA4F03D4F4F8FFDB243A852A0F59177921B4879"; } // namespace @@ -149,7 +148,7 @@ INSTANTIATE_TEST_CASE_P( RPCNoRippleCheckGroup1, NoRippleCheckParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(NoRippleCheckParameterTest, InvalidParams) @@ -157,7 +156,7 @@ TEST_P(NoRippleCheckParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NoRippleCheckHandler{backend_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{.yield = yield, .apiVersion = 2}); ASSERT_FALSE(output); @@ -169,7 +168,7 @@ TEST_P(NoRippleCheckParameterTest, InvalidParams) TEST_F(NoRippleCheckParameterTest, V1ApiTransactionsIsNotBool) { - static constexpr auto kREQ_JSON = R"JSON( + static constexpr auto kReqJson = R"JSON( { "account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "role": "gateway", @@ -180,7 +179,7 @@ TEST_F(NoRippleCheckParameterTest, V1ApiTransactionsIsNotBool) EXPECT_CALL(*backend_, fetchLedgerBySequence); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NoRippleCheckHandler{backend_}}; - auto const req = json::parse(kREQ_JSON); + auto const req = boost::json::parse(kReqJson); auto const output = handler.process(req, Context{.yield = yield, .apiVersion = 1}); ASSERT_FALSE(output); @@ -194,23 +193,23 @@ TEST_F(RPCNoRippleCheckTest, LedgerNotExistViaHash) { EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // return empty ledgerHeader - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(std::nullopt)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "role": "gateway", "ledger_hash": "{}" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); auto const handler = AnyHandler{NoRippleCheckHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -220,26 +219,26 @@ TEST_F(RPCNoRippleCheckTest, LedgerNotExistViaHash) TEST_F(RPCNoRippleCheckTest, LedgerNotExistViaIntIndex) { - constexpr auto kSEQ = 12; + constexpr auto kSeq = 12; EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return empty ledgerHeader - ON_CALL(*backend_, fetchLedgerBySequence(kSEQ, _)).WillByDefault(Return(std::nullopt)); + ON_CALL(*backend_, fetchLedgerBySequence(kSeq, _)).WillByDefault(Return(std::nullopt)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "role": "gateway", "ledger_index": {} }})JSON", - kACCOUNT, - kSEQ + kAccount, + kSeq ) ); auto const handler = AnyHandler{NoRippleCheckHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -249,26 +248,26 @@ TEST_F(RPCNoRippleCheckTest, LedgerNotExistViaIntIndex) TEST_F(RPCNoRippleCheckTest, LedgerNotExistViaStringIndex) { - constexpr auto kSEQ = 12; + constexpr auto kSeq = 12; EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); // return empty ledgerHeader - ON_CALL(*backend_, fetchLedgerBySequence(kSEQ, _)).WillByDefault(Return(std::nullopt)); + ON_CALL(*backend_, fetchLedgerBySequence(kSeq, _)).WillByDefault(Return(std::nullopt)); - static auto const kINPUT = json::parse( + static auto const kInput = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "role": "gateway", "ledger_index": "{}" }})JSON", - kACCOUNT, - kSEQ + kAccount, + kSeq ) ); auto const handler = AnyHandler{NoRippleCheckHandler{backend_}}; runSpawn([&](auto yield) { - auto const output = handler.process(kINPUT, Context{yield}); + auto const output = handler.process(kInput, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "lgrNotFound"); @@ -278,22 +277,22 @@ TEST_F(RPCNoRippleCheckTest, LedgerNotExistViaStringIndex) TEST_F(RPCNoRippleCheckTest, AccountNotExist) { - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, 30); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // fetch account object return empty ON_CALL(*backend_, doFetchLedgerObject).WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}", "role": "gateway" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { @@ -308,8 +307,8 @@ TEST_F(RPCNoRippleCheckTest, AccountNotExist) TEST_F(RPCNoRippleCheckTest, NormalPathRoleUserDefaultRippleSetTrustLineNoRippleSet) { - static constexpr auto kSEQ = 30; - static constexpr auto kEXPECTED_OUTPUT = + static constexpr auto kSeq = 30; + static constexpr auto kExpectedOutput = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -319,31 +318,31 @@ TEST_F(RPCNoRippleCheckTest, NormalPathRoleUserDefaultRippleSetTrustLineNoRipple "validated": true })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, kSeq); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // fetch account object return valid account with DefaultRippleSet flag ON_CALL(*backend_, doFetchLedgerObject) - .WillByDefault(Return( - createAccountRootObject(kACCOUNT, ripple::lsfDefaultRipple, 2, 200, 2, kINDEX1, 2) - .getSerializer() - .peekData() - )); + .WillByDefault( + Return(createAccountRootObject(kAccount, xrpl::lsfDefaultRipple, 2, 200, 2, kIndex1, 2) + .getSerializer() + .peekData()) + ); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSEQ, _)) + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSeq, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, ripple::lsfLowNoRipple + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, xrpl::lsfLowNoRipple ); auto const line2 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, ripple::lsfLowNoRipple + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, xrpl::lsfLowNoRipple ); std::vector bbs; @@ -353,29 +352,29 @@ TEST_F(RPCNoRippleCheckTest, NormalPathRoleUserDefaultRippleSetTrustLineNoRipple ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}", "role": "user" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NoRippleCheckHandler{backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUTPUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOutput)); }); } TEST_F(RPCNoRippleCheckTest, NormalPathRoleUserDefaultRippleUnsetTrustLineNoRippleUnSet) { - static constexpr auto kSEQ = 30; - static constexpr auto kEXPECTED_OUTPUT = + static constexpr auto kSeq = 30; + static constexpr auto kExpectedOutput = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -386,29 +385,29 @@ TEST_F(RPCNoRippleCheckTest, NormalPathRoleUserDefaultRippleUnsetTrustLineNoRipp "validated": true })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, kSeq); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // fetch account object return valid account with DefaultRippleSet flag ON_CALL(*backend_, doFetchLedgerObject) .WillByDefault(Return( - createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2).getSerializer().peekData() + createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2).getSerializer().peekData() )); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSEQ, _)) + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSeq, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); auto const line2 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); std::vector bbs; @@ -418,29 +417,29 @@ TEST_F(RPCNoRippleCheckTest, NormalPathRoleUserDefaultRippleUnsetTrustLineNoRipp ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}", "role": "user" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NoRippleCheckHandler{backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUTPUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOutput)); }); } TEST_F(RPCNoRippleCheckTest, NormalPathRoleGatewayDefaultRippleSetTrustLineNoRippleSet) { - static constexpr auto kSEQ = 30; - static constexpr auto kEXPECTED_OUTPUT = + static constexpr auto kSeq = 30; + static constexpr auto kExpectedOutput = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -451,31 +450,31 @@ TEST_F(RPCNoRippleCheckTest, NormalPathRoleGatewayDefaultRippleSetTrustLineNoRip "validated": true })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, kSeq); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // fetch account object return valid account with DefaultRippleSet flag ON_CALL(*backend_, doFetchLedgerObject) - .WillByDefault(Return( - createAccountRootObject(kACCOUNT, ripple::lsfDefaultRipple, 2, 200, 2, kINDEX1, 2) - .getSerializer() - .peekData() - )); + .WillByDefault( + Return(createAccountRootObject(kAccount, xrpl::lsfDefaultRipple, 2, 200, 2, kIndex1, 2) + .getSerializer() + .peekData()) + ); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSEQ, _)) + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSeq, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, ripple::lsfLowNoRipple + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, xrpl::lsfLowNoRipple ); auto const line2 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, ripple::lsfLowNoRipple + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, xrpl::lsfLowNoRipple ); std::vector bbs; @@ -485,29 +484,29 @@ TEST_F(RPCNoRippleCheckTest, NormalPathRoleGatewayDefaultRippleSetTrustLineNoRip ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}", "role": "gateway" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NoRippleCheckHandler{backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUTPUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOutput)); }); } TEST_F(RPCNoRippleCheckTest, NormalPathRoleGatewayDefaultRippleUnsetTrustLineNoRippleUnset) { - static constexpr auto kSEQ = 30; - static constexpr auto kEXPECTED_OUTPUT = + static constexpr auto kSeq = 30; + static constexpr auto kExpectedOutput = R"JSON({ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 30, @@ -517,29 +516,29 @@ TEST_F(RPCNoRippleCheckTest, NormalPathRoleGatewayDefaultRippleUnsetTrustLineNoR "validated": true })JSON"; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, kSeq); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // fetch account object return valid account with DefaultRippleSet flag ON_CALL(*backend_, doFetchLedgerObject) .WillByDefault(Return( - createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2).getSerializer().peekData() + createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2).getSerializer().peekData() )); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSEQ, _)) + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSeq, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); auto const line2 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, 0 ); std::vector bbs; @@ -549,22 +548,22 @@ TEST_F(RPCNoRippleCheckTest, NormalPathRoleGatewayDefaultRippleUnsetTrustLineNoR ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", "ledger_hash": "{}", "role": "gateway" }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NoRippleCheckHandler{backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUTPUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOutput)); }); } @@ -573,33 +572,33 @@ TEST_F( NormalPathRoleGatewayDefaultRippleUnsetTrustLineNoRippleUnsetHighAccount ) { - static constexpr auto kSEQ = 30; + static constexpr auto kSeq = 30; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, kSeq); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // fetch account object return valid account with DefaultRippleSet flag ON_CALL(*backend_, doFetchLedgerObject) .WillByDefault(Return( - createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2).getSerializer().peekData() + createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2).getSerializer().peekData() )); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSEQ, _)) + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSeq, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, kSEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, kSeq, _)) .WillByDefault(Return(createLegacyFeeSettingBlob(1, 2, 3, 4, 0))); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT2, 10, kACCOUNT, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount2, 10, kAccount, 20, kTxnId, 123, 0 ); auto const line2 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT2, 10, kACCOUNT, 20, kTXN_ID, 123, 0 + "USD", kIssuer, 100, kAccount2, 10, kAccount, 20, kTxnId, 123, 0 ); std::vector bbs; @@ -609,7 +608,7 @@ TEST_F( ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -617,8 +616,8 @@ TEST_F( "role": "gateway", "transactions": true }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { @@ -632,33 +631,33 @@ TEST_F( TEST_F(RPCNoRippleCheckTest, NormalPathLimit) { - constexpr auto kSEQ = 30; + constexpr auto kSeq = 30; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, kSeq); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // fetch account object return valid account with DefaultRippleSet flag ON_CALL(*backend_, doFetchLedgerObject) - .WillByDefault(Return( - createAccountRootObject(kACCOUNT, ripple::lsfDefaultRipple, 2, 200, 2, kINDEX1, 2) - .getSerializer() - .peekData() - )); + .WillByDefault( + Return(createAccountRootObject(kAccount, xrpl::lsfDefaultRipple, 2, 200, 2, kIndex1, 2) + .getSerializer() + .peekData()) + ); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSEQ, _)) + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSeq, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, ripple::lsfLowNoRipple + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, xrpl::lsfLowNoRipple ); auto const line2 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, ripple::lsfLowNoRipple + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, xrpl::lsfLowNoRipple ); std::vector bbs; @@ -668,7 +667,7 @@ TEST_F(RPCNoRippleCheckTest, NormalPathLimit) ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -676,8 +675,8 @@ TEST_F(RPCNoRippleCheckTest, NormalPathLimit) "role": "gateway", "limit": 1 }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { @@ -690,8 +689,8 @@ TEST_F(RPCNoRippleCheckTest, NormalPathLimit) TEST_F(RPCNoRippleCheckTest, NormalPathTransactions) { - constexpr auto kSEQ = 30; - constexpr auto kTRANSACTION_SEQ = 123; + constexpr auto kSeq = 30; + constexpr auto kTransactionSeq = 123; auto const expectedOutput = fmt::format( R"JSON({{ "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", @@ -736,40 +735,40 @@ TEST_F(RPCNoRippleCheckTest, NormalPathTransactions) ], "validated": true }})JSON", - kTRANSACTION_SEQ, - kTRANSACTION_SEQ + 1, - ripple::tfClearNoRipple, - kTRANSACTION_SEQ + 2, - ripple::tfClearNoRipple + kTransactionSeq, + kTransactionSeq + 1, + xrpl::tfClearNoRipple, + kTransactionSeq + 2, + xrpl::tfClearNoRipple ); - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, kSeq); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // fetch account object return valid account with DefaultRippleSet flag ON_CALL(*backend_, doFetchLedgerObject) .WillByDefault( - Return(createAccountRootObject(kACCOUNT, 0, kTRANSACTION_SEQ, 200, 2, kINDEX1, 2) + Return(createAccountRootObject(kAccount, 0, kTransactionSeq, 200, 2, kIndex1, 2) .getSerializer() .peekData()) ); auto const ownerDir = - createOwnerDirLedgerObject({ripple::uint256{kINDEX1}, ripple::uint256{kINDEX2}}, kINDEX1); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSEQ, _)) + createOwnerDirLedgerObject({xrpl::uint256{kIndex1}, xrpl::uint256{kIndex2}}, kIndex1); + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSeq, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, kSEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, kSeq, _)) .WillByDefault(Return(createLegacyFeeSettingBlob(1, 2, 3, 4, 0))); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(3); auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, ripple::lsfLowNoRipple + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, xrpl::lsfLowNoRipple ); auto const line2 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, ripple::lsfLowNoRipple + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, xrpl::lsfLowNoRipple ); std::vector bbs; @@ -779,7 +778,7 @@ TEST_F(RPCNoRippleCheckTest, NormalPathTransactions) ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -787,56 +786,56 @@ TEST_F(RPCNoRippleCheckTest, NormalPathTransactions) "role": "gateway", "transactions": true }})JSON", - kACCOUNT, - kLEDGER_HASH + kAccount, + kLedgerHash ) ); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{NoRippleCheckHandler{backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(expectedOutput)); + EXPECT_EQ(*output.result, boost::json::parse(expectedOutput)); }); } TEST_F(RPCNoRippleCheckTest, LimitMoreThanMax) { - constexpr auto kSEQ = 30; + constexpr auto kSeq = 30; - auto ledgerHeader = createLedgerHeader(kLEDGER_HASH, kSEQ); - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kLEDGER_HASH}, _)) + auto ledgerHeader = createLedgerHeader(kLedgerHash, kSeq); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kLedgerHash}, _)) .WillByDefault(Return(ledgerHeader)); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); // fetch account object return valid account with DefaultRippleSet flag ON_CALL(*backend_, doFetchLedgerObject) - .WillByDefault(Return( - createAccountRootObject(kACCOUNT, ripple::lsfDefaultRipple, 2, 200, 2, kINDEX1, 2) - .getSerializer() - .peekData() - )); + .WillByDefault( + Return(createAccountRootObject(kAccount, xrpl::lsfDefaultRipple, 2, 200, 2, kIndex1, 2) + .getSerializer() + .peekData()) + ); auto const ownerDir = createOwnerDirLedgerObject( - std::vector{NoRippleCheckHandler::kLIMIT_MAX + 1, ripple::uint256{kINDEX1}}, kINDEX1 + std::vector{NoRippleCheckHandler::kLimitMax + 1, xrpl::uint256{kIndex1}}, kIndex1 ); - auto const ownerDirKk = ripple::keylet::ownerDir(getAccountIdWithString(kACCOUNT)).key; - ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSEQ, _)) + auto const ownerDirKk = xrpl::keylet::ownerDir(getAccountIdWithString(kAccount)).key; + ON_CALL(*backend_, doFetchLedgerObject(ownerDirKk, kSeq, _)) .WillByDefault(Return(ownerDir.getSerializer().peekData())); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2); auto const line1 = createRippleStateLedgerObject( - "USD", kISSUER, 100, kACCOUNT, 10, kACCOUNT2, 20, kTXN_ID, 123, ripple::lsfLowNoRipple + "USD", kIssuer, 100, kAccount, 10, kAccount2, 20, kTxnId, 123, xrpl::lsfLowNoRipple ); std::vector bbs; - bbs.reserve(NoRippleCheckHandler::kLIMIT_MAX + 1); - for (auto i = 0; i < NoRippleCheckHandler::kLIMIT_MAX + 1; i++) { + bbs.reserve(NoRippleCheckHandler::kLimitMax + 1); + for (auto i = 0; i < NoRippleCheckHandler::kLimitMax + 1; i++) { bbs.push_back(line1.getSerializer().peekData()); } ON_CALL(*backend_, doFetchLedgerObjects).WillByDefault(Return(bbs)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "account": "{}", @@ -844,9 +843,9 @@ TEST_F(RPCNoRippleCheckTest, LimitMoreThanMax) "role": "gateway", "limit": {} }})JSON", - kACCOUNT, - kLEDGER_HASH, - NoRippleCheckHandler::kLIMIT_MAX + 1 + kAccount, + kLedgerHash, + NoRippleCheckHandler::kLimitMax + 1 ) ); runSpawn([&, this](auto yield) { @@ -855,7 +854,7 @@ TEST_F(RPCNoRippleCheckTest, LimitMoreThanMax) ASSERT_TRUE(output); EXPECT_EQ( output.result->as_object().at("problems").as_array().size(), - NoRippleCheckHandler::kLIMIT_MAX + NoRippleCheckHandler::kLimitMax ); }); } diff --git a/tests/unit/rpc/handlers/ServerInfoTests.cpp b/tests/unit/rpc/handlers/ServerInfoTests.cpp index c35e5a4cb..c1e7cbdfc 100644 --- a/tests/unit/rpc/handlers/ServerInfoTests.cpp +++ b/tests/unit/rpc/handlers/ServerInfoTests.cpp @@ -24,15 +24,14 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; using TestServerInfoHandler = BaseServerInfoHandler; namespace { -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kCLIENT_IP = "1.1.1.1"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kClientIp = "1.1.1.1"; } // namespace @@ -63,7 +62,7 @@ struct RPCServerInfoHandlerTest : HandlerBaseTest, MockLoadBalancerTest, MockCou EXPECT_TRUE(validated.contains("age")); EXPECT_EQ(validated.at("age").as_uint64(), 3u); EXPECT_TRUE(validated.contains("hash")); - EXPECT_EQ(boost::json::value_to(validated.at("hash")), kLEDGER_HASH); + EXPECT_EQ(boost::json::value_to(validated.at("hash")), kLedgerHash); EXPECT_TRUE(validated.contains("seq")); EXPECT_EQ(validated.at("seq").as_uint64(), 30u); EXPECT_TRUE(validated.contains("base_fee_xrp")); @@ -128,7 +127,7 @@ TEST_F(RPCServerInfoHandlerTest, NoLedgerHeaderErrorsOutWithInternal) }}; runSpawn([&](auto yield) { - auto const req = json::parse("{}"); + auto const req = boost::json::parse("{}"); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); @@ -140,7 +139,7 @@ TEST_F(RPCServerInfoHandlerTest, NoLedgerHeaderErrorsOutWithInternal) TEST_F(RPCServerInfoHandlerTest, NoFeesErrorsOutWithInternal) { - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); EXPECT_CALL(*backend_, doFetchLedgerObject).WillOnce(Return(std::nullopt)); @@ -153,7 +152,7 @@ TEST_F(RPCServerInfoHandlerTest, NoFeesErrorsOutWithInternal) }}; runSpawn([&](auto yield) { - auto const req = json::parse("{}"); + auto const req = boost::json::parse("{}"); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); @@ -169,14 +168,14 @@ TEST_F(RPCServerInfoHandlerTest, DefaultOutputIsPresent) MockCounters const* rawCountersPtr = mockCountersPtr_.get(); MockETLService const* rawETLServicePtr = mockETLServicePtr_.get(); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30, 3); // 3 seconds old EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); auto const feeBlob = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); EXPECT_CALL(*backend_, doFetchLedgerObject).WillOnce(Return(feeBlob)); EXPECT_CALL( - *rawBalancerPtr, forwardToRippled(testing::_, testing::Eq(kCLIENT_IP), false, testing::_) + *rawBalancerPtr, forwardToRippled(testing::_, testing::Eq(kClientIp), false, testing::_) ) .WillOnce(Return(std::unexpected{rpc::ClioError::EtlInvalidResponse})); @@ -193,8 +192,8 @@ TEST_F(RPCServerInfoHandlerTest, DefaultOutputIsPresent) }}; runSpawn([&](auto yield) { - auto const req = json::parse("{}"); - auto const output = handler.process(req, Context{yield, {}, false, kCLIENT_IP}); + auto const req = boost::json::parse("{}"); + auto const output = handler.process(req, Context{yield, {}, false, kClientIp}); validateNormalOutput(output); @@ -212,14 +211,14 @@ TEST_F(RPCServerInfoHandlerTest, AmendmentBlockedIsPresentIfSet) MockCounters const* rawCountersPtr = mockCountersPtr_.get(); MockETLService const* rawETLServicePtr = mockETLServicePtr_.get(); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30, 3); // 3 seconds old EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); auto const feeBlob = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); EXPECT_CALL(*backend_, doFetchLedgerObject).WillOnce(Return(feeBlob)); EXPECT_CALL( - *rawBalancerPtr, forwardToRippled(testing::_, testing::Eq(kCLIENT_IP), false, testing::_) + *rawBalancerPtr, forwardToRippled(testing::_, testing::Eq(kClientIp), false, testing::_) ) .WillOnce(Return(std::unexpected{rpc::ClioError::EtlInvalidResponse})); @@ -236,8 +235,8 @@ TEST_F(RPCServerInfoHandlerTest, AmendmentBlockedIsPresentIfSet) }}; runSpawn([&](auto yield) { - auto const req = json::parse("{}"); - auto const output = handler.process(req, Context{yield, {}, false, kCLIENT_IP}); + auto const req = boost::json::parse("{}"); + auto const output = handler.process(req, Context{yield, {}, false, kClientIp}); validateNormalOutput(output); @@ -253,14 +252,14 @@ TEST_F(RPCServerInfoHandlerTest, CorruptionDetectedIsPresentIfSet) MockCounters const* rawCountersPtr = mockCountersPtr_.get(); MockETLService const* rawETLServicePtr = mockETLServicePtr_.get(); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30, 3); // 3 seconds old EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); auto const feeBlob = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); EXPECT_CALL(*backend_, doFetchLedgerObject).WillOnce(Return(feeBlob)); EXPECT_CALL( - *rawBalancerPtr, forwardToRippled(testing::_, testing::Eq(kCLIENT_IP), false, testing::_) + *rawBalancerPtr, forwardToRippled(testing::_, testing::Eq(kClientIp), false, testing::_) ) .WillOnce(Return(std::unexpected{rpc::ClioError::EtlInvalidResponse})); @@ -277,8 +276,8 @@ TEST_F(RPCServerInfoHandlerTest, CorruptionDetectedIsPresentIfSet) }}; runSpawn([&](auto yield) { - auto const req = json::parse("{}"); - auto const output = handler.process(req, Context{yield, {}, false, kCLIENT_IP}); + auto const req = boost::json::parse("{}"); + auto const output = handler.process(req, Context{yield, {}, false, kClientIp}); validateNormalOutput(output); @@ -293,14 +292,14 @@ TEST_F(RPCServerInfoHandlerTest, CacheReportsEnabledFlagCorrectly) MockLoadBalancer* rawBalancerPtr = mockLoadBalancerPtr_.get(); MockCounters const* rawCountersPtr = mockCountersPtr_.get(); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30, 3); // 3 seconds old EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(2).WillRepeatedly(Return(ledgerHeader)); auto const feeBlob = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(2).WillRepeatedly(Return(feeBlob)); EXPECT_CALL( - *rawBalancerPtr, forwardToRippled(testing::_, testing::Eq(kCLIENT_IP), false, testing::_) + *rawBalancerPtr, forwardToRippled(testing::_, testing::Eq(kClientIp), false, testing::_) ) .Times(2) .WillRepeatedly(Return(std::unexpected{rpc::ClioError::EtlInvalidResponse})); @@ -318,8 +317,8 @@ TEST_F(RPCServerInfoHandlerTest, CacheReportsEnabledFlagCorrectly) }}; runSpawn([&](auto yield) { - auto const req = json::parse("{}"); - auto const output = handler.process(req, Context{yield, {}, false, kCLIENT_IP}); + auto const req = boost::json::parse("{}"); + auto const output = handler.process(req, Context{yield, {}, false, kClientIp}); validateNormalOutput(output); @@ -332,8 +331,8 @@ TEST_F(RPCServerInfoHandlerTest, CacheReportsEnabledFlagCorrectly) backend_->cache().setDisabled(); runSpawn([&](auto yield) { - auto const req = json::parse("{}"); - auto const output = handler.process(req, Context{yield, {}, false, kCLIENT_IP}); + auto const req = boost::json::parse("{}"); + auto const output = handler.process(req, Context{yield, {}, false, kClientIp}); validateNormalOutput(output); @@ -350,8 +349,8 @@ TEST_F(RPCServerInfoHandlerTest, AdminSectionPresentWhenAdminFlagIsSet) MockCounters const* rawCountersPtr = mockCountersPtr_.get(); MockETLService const* rawETLServicePtr = mockETLServicePtr_.get(); - auto const empty = json::object{}; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old + auto const empty = boost::json::object{}; + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30, 3); // 3 seconds old EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); auto const feeBlob = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); @@ -379,7 +378,7 @@ TEST_F(RPCServerInfoHandlerTest, AdminSectionPresentWhenAdminFlagIsSet) }}; runSpawn([&](auto yield) { - auto const req = json::parse("{}"); + auto const req = boost::json::parse("{}"); auto const output = handler.process(req, Context{yield, {}, true}); validateNormalOutput(output); @@ -393,8 +392,8 @@ TEST_F(RPCServerInfoHandlerTest, BackendCountersPresentWhenRequestWithParam) MockCounters const* rawCountersPtr = mockCountersPtr_.get(); MockETLService const* rawETLServicePtr = mockETLServicePtr_.get(); - auto const empty = json::object{}; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old + auto const empty = boost::json::object{}; + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30, 3); // 3 seconds old EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); auto const feeBlob = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); @@ -425,7 +424,7 @@ TEST_F(RPCServerInfoHandlerTest, BackendCountersPresentWhenRequestWithParam) }}; runSpawn([&](auto yield) { - auto const req = json::parse(R"JSON( + auto const req = boost::json::parse(R"JSON( { "backend_counters": true } @@ -443,8 +442,8 @@ TEST_F(RPCServerInfoHandlerTest, RippledForwardedValuesPresent) MockCounters const* rawCountersPtr = mockCountersPtr_.get(); MockETLService const* rawETLServicePtr = mockETLServicePtr_.get(); - auto const empty = json::object{}; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old + auto const empty = boost::json::object{}; + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30, 3); // 3 seconds old EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); auto const feeBlob = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); @@ -454,7 +453,7 @@ TEST_F(RPCServerInfoHandlerTest, RippledForwardedValuesPresent) EXPECT_CALL(*rawETLServicePtr, isAmendmentBlocked).WillOnce(Return(false)); - auto const rippledObj = json::parse(R"JSON({ + auto const rippledObj = boost::json::parse(R"JSON({ "result": { "info": { "build_version": "1234", @@ -482,7 +481,7 @@ TEST_F(RPCServerInfoHandlerTest, RippledForwardedValuesPresent) }}; runSpawn([&](auto yield) { - auto const req = json::parse("{}"); + auto const req = boost::json::parse("{}"); auto const output = handler.process(req, Context{yield, {}, true}); validateNormalOutput(output); @@ -497,8 +496,8 @@ TEST_F(RPCServerInfoHandlerTest, RippledForwardedValuesMissingNoExceptionThrown) MockCounters const* rawCountersPtr = mockCountersPtr_.get(); MockETLService const* rawETLServicePtr = mockETLServicePtr_.get(); - auto const empty = json::object{}; - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old + auto const empty = boost::json::object{}; + auto const ledgerHeader = createLedgerHeader(kLedgerHash, 30, 3); // 3 seconds old EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); auto const feeBlob = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); @@ -508,7 +507,7 @@ TEST_F(RPCServerInfoHandlerTest, RippledForwardedValuesMissingNoExceptionThrown) EXPECT_CALL(*rawETLServicePtr, isAmendmentBlocked).WillOnce(Return(false)); - auto const rippledObj = json::parse(R"JSON({ + auto const rippledObj = boost::json::parse(R"JSON({ "result": { "info": {} } @@ -531,7 +530,7 @@ TEST_F(RPCServerInfoHandlerTest, RippledForwardedValuesMissingNoExceptionThrown) }}; runSpawn([&](auto yield) { - auto const req = json::parse("{}"); + auto const req = boost::json::parse("{}"); auto const output = handler.process(req, Context{yield, {}, true}); validateNormalOutput(output); diff --git a/tests/unit/rpc/handlers/SubscribeTests.cpp b/tests/unit/rpc/handlers/SubscribeTests.cpp index 2e3e78acf..28e77e729 100644 --- a/tests/unit/rpc/handlers/SubscribeTests.cpp +++ b/tests/unit/rpc/handlers/SubscribeTests.cpp @@ -32,22 +32,21 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; using std::chrono::milliseconds; namespace { -constexpr auto kMIN_SEQ = 10; -constexpr auto kMAX_SEQ = 30; -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kPAYS20_USD_GETS10_XRP_BOOK_DIR = +constexpr auto kMinSeq = 10; +constexpr auto kMaxSeq = 30; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kPayS20UsdGetS10XrpBookDir = "43B83ADC452B85FCBADA6CAEAC5181C255A213630D58FFD455071AFD498D0000"; -constexpr auto kPAYS20_XRP_GETS10_USD_BOOK_DIR = +constexpr auto kPayS20XrpGetS10UsdBookDir = "7B1767D41DBCE79D9585CF9D0262A5FEC45E5206FF524F8B55071AFD498D0000"; -constexpr auto kINDEX1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; -constexpr auto kINDEX2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; +constexpr auto kIndex1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"; +constexpr auto kIndex2 = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC321"; } // namespace @@ -560,7 +559,7 @@ INSTANTIATE_TEST_CASE_P( RPCSubscribe, SubscribeParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(SubscribeParameterTest, InvalidParams) @@ -570,7 +569,7 @@ TEST_P(SubscribeParameterTest, InvalidParams) auto const handler = AnyHandler{ SubscribeHandler{backend_, mockAmendmentCenterPtr_, mockSubscriptionManagerPtr_} }; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -586,7 +585,8 @@ TEST_F(RPCSubscribeHandlerTest, EmptyResponse) SubscribeHandler{backend_, mockAmendmentCenterPtr_, mockSubscriptionManagerPtr_} }; EXPECT_CALL(*mockSession_, setApiSubversion(0)); - auto const output = handler.process(json::parse(R"JSON({})JSON"), Context{yield, session_}); + auto const output = + handler.process(boost::json::parse(R"JSON({})JSON"), Context{yield, session_}); ASSERT_TRUE(output); EXPECT_TRUE(output.result->as_object().empty()); }); @@ -595,7 +595,7 @@ TEST_F(RPCSubscribeHandlerTest, EmptyResponse) TEST_F(RPCSubscribeHandlerTest, StreamsWithoutLedger) { // these streams don't return response - auto const input = json::parse( + auto const input = boost::json::parse( R"JSON({ "streams": ["transactions_proposed", "transactions", "validations", "manifests", "book_changes"] })JSON" @@ -619,7 +619,7 @@ TEST_F(RPCSubscribeHandlerTest, StreamsWithoutLedger) TEST_F(RPCSubscribeHandlerTest, StreamsLedger) { - static constexpr auto kEXPECTED_OUTPUT = + static constexpr auto kExpectedOutput = R"JSON({ "validated_ledgers": "10-30", "ledger_index": 30, @@ -630,7 +630,7 @@ TEST_F(RPCSubscribeHandlerTest, StreamsLedger) "reserve_inc": 2 })JSON"; - auto const input = json::parse( + auto const input = boost::json::parse( R"JSON({ "streams": ["ledger"] })JSON" @@ -641,25 +641,25 @@ TEST_F(RPCSubscribeHandlerTest, StreamsLedger) }; EXPECT_CALL(*mockSubscriptionManagerPtr_, subLedger) - .WillOnce(testing::Return(boost::json::parse(kEXPECTED_OUTPUT).as_object())); + .WillOnce(testing::Return(boost::json::parse(kExpectedOutput).as_object())); EXPECT_CALL(*mockSession_, setApiSubversion(0)); auto const output = handler.process(input, Context{yield, session_}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->as_object(), json::parse(kEXPECTED_OUTPUT)); + EXPECT_EQ(output.result->as_object(), boost::json::parse(kExpectedOutput)); }); } TEST_F(RPCSubscribeHandlerTest, Accounts) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "accounts": ["{}", "{}", "{}"] }})JSON", - kACCOUNT, - kACCOUNT2, - kACCOUNT2 + kAccount, + kAccount2, + kAccount2 ) ); runSpawn([&, this](auto yield) { @@ -668,10 +668,10 @@ TEST_F(RPCSubscribeHandlerTest, Accounts) }; EXPECT_CALL( - *mockSubscriptionManagerPtr_, subAccount(getAccountIdWithString(kACCOUNT), session_) + *mockSubscriptionManagerPtr_, subAccount(getAccountIdWithString(kAccount), session_) ); EXPECT_CALL( - *mockSubscriptionManagerPtr_, subAccount(getAccountIdWithString(kACCOUNT2), session_) + *mockSubscriptionManagerPtr_, subAccount(getAccountIdWithString(kAccount2), session_) ) .Times(2); EXPECT_CALL(*mockSession_, setApiSubversion(0)); @@ -683,14 +683,14 @@ TEST_F(RPCSubscribeHandlerTest, Accounts) TEST_F(RPCSubscribeHandlerTest, AccountsProposed) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "accounts_proposed": ["{}", "{}", "{}"] }})JSON", - kACCOUNT, - kACCOUNT2, - kACCOUNT2 + kAccount, + kAccount2, + kAccount2 ) ); runSpawn([&, this](auto yield) { @@ -700,11 +700,11 @@ TEST_F(RPCSubscribeHandlerTest, AccountsProposed) EXPECT_CALL( *mockSubscriptionManagerPtr_, - subProposedAccount(getAccountIdWithString(kACCOUNT), session_) + subProposedAccount(getAccountIdWithString(kAccount), session_) ); EXPECT_CALL( *mockSubscriptionManagerPtr_, - subProposedAccount(getAccountIdWithString(kACCOUNT2), session_) + subProposedAccount(getAccountIdWithString(kAccount2), session_) ) .Times(2); EXPECT_CALL(*mockSession_, setApiSubversion(0)); @@ -716,7 +716,7 @@ TEST_F(RPCSubscribeHandlerTest, AccountsProposed) TEST_F(RPCSubscribeHandlerTest, JustBooks) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "books": [ @@ -731,7 +731,7 @@ TEST_F(RPCSubscribeHandlerTest, JustBooks) }} ] }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -748,7 +748,7 @@ TEST_F(RPCSubscribeHandlerTest, JustBooks) TEST_F(RPCSubscribeHandlerTest, BooksBothSet) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "books": [ @@ -764,7 +764,7 @@ TEST_F(RPCSubscribeHandlerTest, BooksBothSet) }} ] }})JSON", - kACCOUNT + kAccount ) ); runSpawn([&, this](auto yield) { @@ -781,7 +781,7 @@ TEST_F(RPCSubscribeHandlerTest, BooksBothSet) TEST_F(RPCSubscribeHandlerTest, BooksBothSnapshotSet) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "books": [ @@ -798,132 +798,113 @@ TEST_F(RPCSubscribeHandlerTest, BooksBothSnapshotSet) }} ] }})JSON", - kACCOUNT + kAccount ) ); - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - auto const issuer = getAccountIdWithString(kACCOUNT); + auto const issuer = getAccountIdWithString(kAccount); auto const getsXRPPaysUSDBook = getBookBase( rpc::parseBook( - ripple::to_currency("USD"), - issuer, - ripple::xrpCurrency(), - ripple::xrpAccount(), - std::nullopt + xrpl::toCurrency("USD"), issuer, xrpl::xrpCurrency(), xrpl::xrpAccount(), std::nullopt ) .value() ); auto const reversedBook = getBookBase( rpc::parseBook( - ripple::xrpCurrency(), - ripple::xrpAccount(), - ripple::to_currency("USD"), - issuer, - std::nullopt + xrpl::xrpCurrency(), xrpl::xrpAccount(), xrpl::toCurrency("USD"), issuer, std::nullopt ) .value() ); - ON_CALL(*backend_, doFetchSuccessorKey(getsXRPPaysUSDBook, kMAX_SEQ, _)) - .WillByDefault(Return(ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR})); + ON_CALL(*backend_, doFetchSuccessorKey(getsXRPPaysUSDBook, kMaxSeq, _)) + .WillByDefault(Return(xrpl::uint256{kPayS20UsdGetS10XrpBookDir})); - ON_CALL( - *backend_, - doFetchSuccessorKey(ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}, kMAX_SEQ, _) - ) + ON_CALL(*backend_, doFetchSuccessorKey(xrpl::uint256{kPayS20UsdGetS10XrpBookDir}, kMaxSeq, _)) .WillByDefault(Return(std::nullopt)); - ON_CALL(*backend_, doFetchSuccessorKey(reversedBook, kMAX_SEQ, _)) - .WillByDefault(Return(ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR})); + ON_CALL(*backend_, doFetchSuccessorKey(reversedBook, kMaxSeq, _)) + .WillByDefault(Return(xrpl::uint256{kPayS20XrpGetS10UsdBookDir})); EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(4); // 2 book dirs + 2 issuer global freeze + 2 transferRate + 1 owner root + 1 fee EXPECT_CALL(*backend_, doFetchLedgerObject).Times(8); - auto const indexes = std::vector(10, ripple::uint256{kINDEX2}); - ON_CALL( - *backend_, - doFetchLedgerObject(ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}, kMAX_SEQ, _) - ) + auto const indexes = std::vector(10, xrpl::uint256{kIndex2}); + ON_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kPayS20UsdGetS10XrpBookDir}, kMaxSeq, _)) .WillByDefault( - Return(createOwnerDirLedgerObject(indexes, kINDEX1).getSerializer().peekData()) + Return(createOwnerDirLedgerObject(indexes, kIndex1).getSerializer().peekData()) ); // for reverse - auto const indexes2 = std::vector(10, ripple::uint256{kINDEX1}); - ON_CALL( - *backend_, - doFetchLedgerObject(ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, kMAX_SEQ, _) - ) + auto const indexes2 = std::vector(10, xrpl::uint256{kIndex1}); + ON_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, kMaxSeq, _)) .WillByDefault( - Return(createOwnerDirLedgerObject(indexes2, kINDEX2).getSerializer().peekData()) + Return(createOwnerDirLedgerObject(indexes2, kIndex2).getSerializer().peekData()) ); // offer owner account root ON_CALL( *backend_, doFetchLedgerObject( - ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, kMAX_SEQ, _ + xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, kMaxSeq, _ ) ) .WillByDefault(Return( - createAccountRootObject(kACCOUNT2, 0, 2, 200, 2, kINDEX1, 2).getSerializer().peekData() + createAccountRootObject(kAccount2, 0, 2, 200, 2, kIndex1, 2).getSerializer().peekData() )); // issuer account root ON_CALL( *backend_, - doFetchLedgerObject( - ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key, kMAX_SEQ, _ - ) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount)).key, kMaxSeq, _) ) .WillByDefault(Return( - createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2).getSerializer().peekData() + createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2).getSerializer().peekData() )); // fee auto feeBlob = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, kMAX_SEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, kMaxSeq, _)) .WillByDefault(Return(feeBlob)); auto const gets10XRPPays20USDOffer = createOfferLedgerObject( - kACCOUNT2, + kAccount2, 10, 20, - ripple::to_string(ripple::xrpCurrency()), - ripple::to_string(ripple::to_currency("USD")), - toBase58(ripple::xrpAccount()), - kACCOUNT, - kPAYS20_USD_GETS10_XRP_BOOK_DIR + xrpl::to_string(xrpl::xrpCurrency()), + xrpl::to_string(xrpl::toCurrency("USD")), + toBase58(xrpl::xrpAccount()), + kAccount, + kPayS20UsdGetS10XrpBookDir ); // for reverse // offer owner is USD issuer auto const gets10USDPays20XRPOffer = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT, - toBase58(ripple::xrpAccount()), - kPAYS20_XRP_GETS10_USD_BOOK_DIR + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount, + toBase58(xrpl::xrpAccount()), + kPayS20XrpGetS10UsdBookDir ); std::vector const bbs(10, gets10XRPPays20USDOffer.getSerializer().peekData()); - ON_CALL(*backend_, doFetchLedgerObjects(indexes, kMAX_SEQ, _)).WillByDefault(Return(bbs)); + ON_CALL(*backend_, doFetchLedgerObjects(indexes, kMaxSeq, _)).WillByDefault(Return(bbs)); // for reverse std::vector const bbs2(10, gets10USDPays20XRPOffer.getSerializer().peekData()); - ON_CALL(*backend_, doFetchLedgerObjects(indexes2, kMAX_SEQ, _)).WillByDefault(Return(bbs2)); + ON_CALL(*backend_, doFetchLedgerObjects(indexes2, kMaxSeq, _)).WillByDefault(Return(bbs2)); EXPECT_CALL(*backend_, doFetchLedgerObjects).Times(2); - static auto const kEXPECTED_OFFER = fmt::format( + static auto const kExpectedOffer = fmt::format( R"JSON({{ "Account": "{}", "BookDirectory": "{}", @@ -944,11 +925,11 @@ TEST_F(RPCSubscribeHandlerTest, BooksBothSnapshotSet) "owner_funds": "193", "quality": "2" }})JSON", - kACCOUNT2, - kPAYS20_USD_GETS10_XRP_BOOK_DIR, - kACCOUNT + kAccount2, + kPayS20UsdGetS10XrpBookDir, + kAccount ); - static auto const kEXPECTED_REVERSED_OFFER = fmt::format( + static auto const kExpectedReversedOffer = fmt::format( R"JSON({{ "Account": "{}", "BookDirectory": "{}", @@ -969,9 +950,9 @@ TEST_F(RPCSubscribeHandlerTest, BooksBothSnapshotSet) "owner_funds": "10", "quality": "2" }})JSON", - kACCOUNT, - kPAYS20_XRP_GETS10_USD_BOOK_DIR, - kACCOUNT + kAccount, + kPayS20XrpGetS10UsdBookDir, + kAccount ); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{ @@ -985,18 +966,18 @@ TEST_F(RPCSubscribeHandlerTest, BooksBothSnapshotSet) EXPECT_EQ(output.result->as_object().at("asks").as_array().size(), 10); EXPECT_EQ( output.result->as_object().at("bids").as_array()[0].as_object(), - json::parse(kEXPECTED_OFFER) + boost::json::parse(kExpectedOffer) ); EXPECT_EQ( output.result->as_object().at("asks").as_array()[0].as_object(), - json::parse(kEXPECTED_REVERSED_OFFER) + boost::json::parse(kExpectedReversedOffer) ); }); } TEST_F(RPCSubscribeHandlerTest, BooksBothUnsetSnapshotSet) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "books": [ @@ -1012,131 +993,112 @@ TEST_F(RPCSubscribeHandlerTest, BooksBothUnsetSnapshotSet) }} ] }})JSON", - kACCOUNT + kAccount ) ); - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - auto const issuer = getAccountIdWithString(kACCOUNT); + auto const issuer = getAccountIdWithString(kAccount); auto const getsXRPPaysUSDBook = getBookBase( rpc::parseBook( - ripple::to_currency("USD"), - issuer, - ripple::xrpCurrency(), - ripple::xrpAccount(), - std::nullopt + xrpl::toCurrency("USD"), issuer, xrpl::xrpCurrency(), xrpl::xrpAccount(), std::nullopt ) .value() ); auto const reversedBook = getBookBase( rpc::parseBook( - ripple::xrpCurrency(), - ripple::xrpAccount(), - ripple::to_currency("USD"), - issuer, - std::nullopt + xrpl::xrpCurrency(), xrpl::xrpAccount(), xrpl::toCurrency("USD"), issuer, std::nullopt ) .value() ); - ON_CALL(*backend_, doFetchSuccessorKey(getsXRPPaysUSDBook, kMAX_SEQ, _)) - .WillByDefault(Return(ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR})); + ON_CALL(*backend_, doFetchSuccessorKey(getsXRPPaysUSDBook, kMaxSeq, _)) + .WillByDefault(Return(xrpl::uint256{kPayS20UsdGetS10XrpBookDir})); - ON_CALL( - *backend_, - doFetchSuccessorKey(ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}, kMAX_SEQ, _) - ) + ON_CALL(*backend_, doFetchSuccessorKey(xrpl::uint256{kPayS20UsdGetS10XrpBookDir}, kMaxSeq, _)) .WillByDefault(Return(std::nullopt)); - ON_CALL(*backend_, doFetchSuccessorKey(reversedBook, kMAX_SEQ, _)) - .WillByDefault(Return(ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR})); + ON_CALL(*backend_, doFetchSuccessorKey(reversedBook, kMaxSeq, _)) + .WillByDefault(Return(xrpl::uint256{kPayS20XrpGetS10UsdBookDir})); EXPECT_CALL(*backend_, doFetchSuccessorKey).Times(2); EXPECT_CALL(*backend_, doFetchLedgerObject).Times(5); - auto const indexes = std::vector(10, ripple::uint256{kINDEX2}); - ON_CALL( - *backend_, - doFetchLedgerObject(ripple::uint256{kPAYS20_USD_GETS10_XRP_BOOK_DIR}, kMAX_SEQ, _) - ) + auto const indexes = std::vector(10, xrpl::uint256{kIndex2}); + ON_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kPayS20UsdGetS10XrpBookDir}, kMaxSeq, _)) .WillByDefault( - Return(createOwnerDirLedgerObject(indexes, kINDEX1).getSerializer().peekData()) + Return(createOwnerDirLedgerObject(indexes, kIndex1).getSerializer().peekData()) ); // for reverse - auto const indexes2 = std::vector(10, ripple::uint256{kINDEX1}); - ON_CALL( - *backend_, - doFetchLedgerObject(ripple::uint256{kPAYS20_XRP_GETS10_USD_BOOK_DIR}, kMAX_SEQ, _) - ) + auto const indexes2 = std::vector(10, xrpl::uint256{kIndex1}); + ON_CALL(*backend_, doFetchLedgerObject(xrpl::uint256{kPayS20XrpGetS10UsdBookDir}, kMaxSeq, _)) .WillByDefault( - Return(createOwnerDirLedgerObject(indexes2, kINDEX2).getSerializer().peekData()) + Return(createOwnerDirLedgerObject(indexes2, kIndex2).getSerializer().peekData()) ); // offer owner account root ON_CALL( *backend_, doFetchLedgerObject( - ripple::keylet::account(getAccountIdWithString(kACCOUNT2)).key, kMAX_SEQ, _ + xrpl::keylet::account(getAccountIdWithString(kAccount2)).key, kMaxSeq, _ ) ) .WillByDefault(Return( - createAccountRootObject(kACCOUNT2, 0, 2, 200, 2, kINDEX1, 2).getSerializer().peekData() + createAccountRootObject(kAccount2, 0, 2, 200, 2, kIndex1, 2).getSerializer().peekData() )); // issuer account root ON_CALL( *backend_, - doFetchLedgerObject( - ripple::keylet::account(getAccountIdWithString(kACCOUNT)).key, kMAX_SEQ, _ - ) + doFetchLedgerObject(xrpl::keylet::account(getAccountIdWithString(kAccount)).key, kMaxSeq, _) ) .WillByDefault(Return( - createAccountRootObject(kACCOUNT, 0, 2, 200, 2, kINDEX1, 2).getSerializer().peekData() + createAccountRootObject(kAccount, 0, 2, 200, 2, kIndex1, 2).getSerializer().peekData() )); // fee auto feeBlob = createLegacyFeeSettingBlob(1, 2, 3, 4, 0); - ON_CALL(*backend_, doFetchLedgerObject(ripple::keylet::fees().key, kMAX_SEQ, _)) + ON_CALL(*backend_, doFetchLedgerObject(xrpl::keylet::feeSettings().key, kMaxSeq, _)) .WillByDefault(Return(feeBlob)); auto const gets10XRPPays20USDOffer = createOfferLedgerObject( - kACCOUNT2, + kAccount2, 10, 20, - ripple::to_string(ripple::xrpCurrency()), - ripple::to_string(ripple::to_currency("USD")), - toBase58(ripple::xrpAccount()), - kACCOUNT, - kPAYS20_USD_GETS10_XRP_BOOK_DIR + xrpl::to_string(xrpl::xrpCurrency()), + xrpl::to_string(xrpl::toCurrency("USD")), + toBase58(xrpl::xrpAccount()), + kAccount, + kPayS20UsdGetS10XrpBookDir ); // for reverse // offer owner is USD issuer auto const gets10USDPays20XRPOffer = createOfferLedgerObject( - kACCOUNT, + kAccount, 10, 20, - ripple::to_string(ripple::to_currency("USD")), - ripple::to_string(ripple::xrpCurrency()), - kACCOUNT, - toBase58(ripple::xrpAccount()), - kPAYS20_XRP_GETS10_USD_BOOK_DIR + xrpl::to_string(xrpl::toCurrency("USD")), + xrpl::to_string(xrpl::xrpCurrency()), + kAccount, + toBase58(xrpl::xrpAccount()), + kPayS20XrpGetS10UsdBookDir ); std::vector const bbs(10, gets10XRPPays20USDOffer.getSerializer().peekData()); - ON_CALL(*backend_, doFetchLedgerObjects(indexes, kMAX_SEQ, _)).WillByDefault(Return(bbs)); + ON_CALL(*backend_, doFetchLedgerObjects(indexes, kMaxSeq, _)).WillByDefault(Return(bbs)); // for reverse std::vector const bbs2(10, gets10USDPays20XRPOffer.getSerializer().peekData()); - ON_CALL(*backend_, doFetchLedgerObjects(indexes2, kMAX_SEQ, _)).WillByDefault(Return(bbs2)); + ON_CALL(*backend_, doFetchLedgerObjects(indexes2, kMaxSeq, _)).WillByDefault(Return(bbs2)); EXPECT_CALL(*backend_, doFetchLedgerObjects); - static auto const kEXPECTED_OFFER = fmt::format( + static auto const kExpectedOffer = fmt::format( R"JSON({{ "Account": "{}", "BookDirectory": "{}", @@ -1157,9 +1119,9 @@ TEST_F(RPCSubscribeHandlerTest, BooksBothUnsetSnapshotSet) "owner_funds": "193", "quality": "2" }})JSON", - kACCOUNT2, - kPAYS20_USD_GETS10_XRP_BOOK_DIR, - kACCOUNT + kAccount2, + kPayS20UsdGetS10XrpBookDir, + kAccount ); runSpawn([&, this](auto yield) { @@ -1173,14 +1135,14 @@ TEST_F(RPCSubscribeHandlerTest, BooksBothUnsetSnapshotSet) EXPECT_EQ(output.result->as_object().at("offers").as_array().size(), 10); EXPECT_EQ( output.result->as_object().at("offers").as_array()[0].as_object(), - json::parse(kEXPECTED_OFFER) + boost::json::parse(kExpectedOffer) ); }); } TEST_F(RPCSubscribeHandlerTest, APIVersion) { - auto const input = json::parse( + auto const input = boost::json::parse( R"JSON({ "streams": ["transactions_proposed"] })JSON" @@ -1203,7 +1165,7 @@ TEST_F(RPCSubscribeHandlerTest, APIVersion) TEST(RPCSubscribeHandlerSpecTest, DeprecatedFields) { boost::json::value const json{ - {"streams", kACCOUNT}, + {"streams", kAccount}, {"accounts", {123}}, {"accounts_proposed", "abc"}, {"books", "1"}, diff --git a/tests/unit/rpc/handlers/TestHandlerTests.cpp b/tests/unit/rpc/handlers/TestHandlerTests.cpp index 4804f7060..c30c39f15 100644 --- a/tests/unit/rpc/handlers/TestHandlerTests.cpp +++ b/tests/unit/rpc/handlers/TestHandlerTests.cpp @@ -12,8 +12,6 @@ using namespace rpc; using namespace rpc::validation; using namespace tests::common; -namespace json = boost::json; - class RPCTestHandlerTest : public HandlerBaseTest {}; // example handler tests @@ -21,7 +19,7 @@ TEST_F(RPCTestHandlerTest, HandlerSuccess) { runSpawn([](auto yield) { auto const handler = AnyHandler{HandlerFake{}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "hello": "world", "limit": 10 })JSON"); @@ -38,7 +36,7 @@ TEST_F(RPCTestHandlerTest, NoInputHandlerSuccess) { runSpawn([](auto yield) { auto const handler = AnyHandler{NoInputHandlerFake{}}; - auto const output = handler.process(json::parse(R"JSON({})JSON"), Context{yield}); + auto const output = handler.process(boost::json::parse(R"JSON({})JSON"), Context{yield}); ASSERT_TRUE(output); auto const val = output.result.value(); @@ -50,7 +48,7 @@ TEST_F(RPCTestHandlerTest, HandlerErrorHandling) { runSpawn([](auto yield) { auto const handler = AnyHandler{HandlerFake{}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "hello": "not world", "limit": 10 })JSON"); @@ -60,7 +58,7 @@ TEST_F(RPCTestHandlerTest, HandlerErrorHandling) auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "invalidParams"); - EXPECT_EQ(err.at("error_code").as_uint64(), rpc::RippledError::rpcINVALID_PARAMS); + EXPECT_EQ(err.at("error_code").as_uint64(), rpc::RippledError::RpcInvalidParams); EXPECT_EQ(err.at("error_message").as_string(), "Invalid parameters."); }); } @@ -69,7 +67,7 @@ TEST_F(RPCTestHandlerTest, HandlerInnerErrorHandling) { runSpawn([](auto yield) { auto const handler = AnyHandler{FailingHandlerFake{}}; - auto const input = json::parse(R"JSON({ + auto const input = boost::json::parse(R"JSON({ "hello": "world", "limit": 10 })JSON"); diff --git a/tests/unit/rpc/handlers/TransactionEntryTests.cpp b/tests/unit/rpc/handlers/TransactionEntryTests.cpp index 6e841a52c..f0970db83 100644 --- a/tests/unit/rpc/handlers/TransactionEntryTests.cpp +++ b/tests/unit/rpc/handlers/TransactionEntryTests.cpp @@ -17,17 +17,16 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; namespace { -constexpr auto kINDEX = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; -constexpr auto kTXN_ID = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kCURRENCY = "0158415500000000C1F76FF6ECB0BAC600000000"; -constexpr auto kAPI_VERSION = 2; +constexpr auto kIndex = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; +constexpr auto kTxnId = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kCurrency = "0158415500000000C1F76FF6ECB0BAC600000000"; +constexpr auto kApiVersion = 2; } // namespace @@ -42,7 +41,7 @@ TEST_F(RPCTransactionEntryHandlerTest, TxHashNotProvide) { runSpawn([this](auto yield) { auto const handler = AnyHandler{TransactionEntryHandler{backend_}}; - auto const output = handler.process(json::parse("{}"), Context{yield}); + auto const output = handler.process(boost::json::parse("{}"), Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "fieldNotFoundTransaction"); @@ -55,7 +54,7 @@ TEST_F(RPCTransactionEntryHandlerTest, TxHashWrongFormat) runSpawn([this](auto yield) { auto const handler = AnyHandler{TransactionEntryHandler{backend_}}; auto const output = - handler.process(json::parse(R"JSON({"tx_hash": "123"})JSON"), Context{yield}); + handler.process(boost::json::parse(R"JSON({"tx_hash": "123"})JSON"), Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "invalidParams"); @@ -66,18 +65,18 @@ TEST_F(RPCTransactionEntryHandlerTest, TxHashWrongFormat) TEST_F(RPCTransactionEntryHandlerTest, NonExistLedgerViaLedgerHash) { // mock fetchLedgerByHash return empty - ON_CALL(*backend_, fetchLedgerByHash(ripple::uint256{kINDEX}, _)) - .WillByDefault(Return(std::optional{})); + ON_CALL(*backend_, fetchLedgerByHash(xrpl::uint256{kIndex}, _)) + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerByHash).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "ledger_hash": "{}", "tx_hash": "{}" }})JSON", - kINDEX, - kTXN_ID + kIndex, + kTxnId ) ); runSpawn([&, this](auto yield) { @@ -95,15 +94,15 @@ TEST_F(RPCTransactionEntryHandlerTest, NonExistLedgerViaLedgerIndex) { // mock fetchLedgerBySequence return empty ON_CALL(*backend_, fetchLedgerBySequence) - .WillByDefault(Return(std::optional{})); + .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "ledger_index": "4", "tx_hash": "{}" }})JSON", - kTXN_ID + kTxnId ) ); runSpawn([&, this](auto yield) { @@ -118,19 +117,19 @@ TEST_F(RPCTransactionEntryHandlerTest, NonExistLedgerViaLedgerIndex) TEST_F(RPCTransactionEntryHandlerTest, TXNotFound) { - ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(createLedgerHeader(kINDEX, 30))); + ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(createLedgerHeader(kIndex, 30))); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); - ON_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)) + ON_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)) .WillByDefault(Return(std::optional{})); EXPECT_CALL(*backend_, fetchTransaction).Times(1); runSpawn([this](auto yield) { auto const handler = AnyHandler{TransactionEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "tx_hash": "{}" }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); @@ -145,28 +144,28 @@ TEST_F(RPCTransactionEntryHandlerTest, LedgerSeqNotMatch) { TransactionAndMetadata tx; tx.metadata = - createMetaDataForCreateOffer(kCURRENCY, kACCOUNT, 100, 200, 300).getSerializer().peekData(); + createMetaDataForCreateOffer(kCurrency, kAccount, 100, 200, 300).getSerializer().peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300) .getSerializer() .peekData(); tx.date = 123456; tx.ledgerSequence = 10; - ON_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillByDefault(Return(tx)); + ON_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillByDefault(Return(tx)); EXPECT_CALL(*backend_, fetchTransaction).Times(1); - ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(createLedgerHeader(kINDEX, 30))); + ON_CALL(*backend_, fetchLedgerBySequence).WillByDefault(Return(createLedgerHeader(kIndex, 30))); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); runSpawn([this](auto yield) { auto const handler = AnyHandler{TransactionEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "tx_hash": "{}", "ledger_index": "30" }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); @@ -179,7 +178,7 @@ TEST_F(RPCTransactionEntryHandlerTest, LedgerSeqNotMatch) TEST_F(RPCTransactionEntryHandlerTest, NormalPath) { - static constexpr auto kOUTPUT = R"JSON({ + static constexpr auto kOutput = R"JSON({ "metadata": { "AffectedNodes": [ { @@ -220,41 +219,41 @@ TEST_F(RPCTransactionEntryHandlerTest, NormalPath) TransactionAndMetadata tx; tx.metadata = - createMetaDataForCreateOffer(kCURRENCY, kACCOUNT, 100, 200, 300).getSerializer().peekData(); + createMetaDataForCreateOffer(kCurrency, kAccount, 100, 200, 300).getSerializer().peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300) .getSerializer() .peekData(); tx.date = 123456; tx.ledgerSequence = 30; - ON_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillByDefault(Return(tx)); + ON_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillByDefault(Return(tx)); EXPECT_CALL(*backend_, fetchTransaction).Times(1); ON_CALL(*backend_, fetchLedgerBySequence) - .WillByDefault(Return(createLedgerHeader(kINDEX, tx.ledgerSequence))); + .WillByDefault(Return(createLedgerHeader(kIndex, tx.ledgerSequence))); EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(1); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{TransactionEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "tx_hash": "{}", "ledger_index": {} }})JSON", - kTXN_ID, + kTxnId, tx.ledgerSequence ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(kOUTPUT), *output.result); + EXPECT_EQ(boost::json::parse(kOutput), *output.result); }); } TEST_F(RPCTransactionEntryHandlerTest, NormalPathV2) { - static constexpr auto kOUTPUT = R"JSON({ + static constexpr auto kOutput = R"JSON({ "meta": { "AffectedNodes": [ { @@ -296,32 +295,32 @@ TEST_F(RPCTransactionEntryHandlerTest, NormalPathV2) TransactionAndMetadata tx; tx.metadata = - createMetaDataForCreateOffer(kCURRENCY, kACCOUNT, 100, 200, 300).getSerializer().peekData(); + createMetaDataForCreateOffer(kCurrency, kAccount, 100, 200, 300).getSerializer().peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300) .getSerializer() .peekData(); tx.date = 123456; tx.ledgerSequence = 30; - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillOnce(Return(tx)); + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillOnce(Return(tx)); EXPECT_CALL(*backend_, fetchLedgerBySequence) - .WillOnce(Return(createLedgerHeader(kINDEX, tx.ledgerSequence))); + .WillOnce(Return(createLedgerHeader(kIndex, tx.ledgerSequence))); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{TransactionEntryHandler{backend_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "tx_hash": "{}", "ledger_index": {} }})JSON", - kTXN_ID, + kTxnId, tx.ledgerSequence ) ); auto const output = - handler.process(req, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + handler.process(req, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_TRUE(output); - EXPECT_EQ(json::parse(kOUTPUT), *output.result); + EXPECT_EQ(boost::json::parse(kOutput), *output.result); }); } diff --git a/tests/unit/rpc/handlers/TxTests.cpp b/tests/unit/rpc/handlers/TxTests.cpp index fae08efc0..b8acacc69 100644 --- a/tests/unit/rpc/handlers/TxTests.cpp +++ b/tests/unit/rpc/handlers/TxTests.cpp @@ -22,24 +22,23 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; using TestTxHandler = TxHandler; namespace { -constexpr auto kTXN_ID = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; -constexpr auto kNFT_ID = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DF"; -constexpr auto kNFT_ID2 = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DA"; -constexpr auto kLEDGER_HASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kCURRENCY = "0158415500000000C1F76FF6ECB0BAC600000000"; -constexpr auto kCTID = "C002807000010002"; // seq 163952 txindex 1 netid 2 -constexpr auto kSEQ_FROM_CTID = 163952; +constexpr auto kTxnId = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DD"; +constexpr auto kNftId = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DF"; +constexpr auto kNftID2 = "05FB0EB4B899F056FA095537C5817163801F544BAFCEA39C995D76DB4D16F9DA"; +constexpr auto kLedgerHash = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kCurrency = "0158415500000000C1F76FF6ECB0BAC600000000"; +constexpr auto kCtid = "C002807000010002"; // seq 163952 txindex 1 netid 2 +constexpr auto kSeqFromCtid = 163952; -constexpr auto kDEFAULT_OUT1 = R"JSON({ +constexpr auto kDefaultOuT1 = R"JSON({ "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "Fee": "2", "Sequence": 100, @@ -78,7 +77,7 @@ constexpr auto kDEFAULT_OUT1 = R"JSON({ "validated": true })JSON"; -constexpr auto kDEFAULT_OUT2 = R"JSON({ +constexpr auto kDefaultOuT2 = R"JSON({ "hash": "2E2FBAAFF767227FE4381C4BE9855986A6B9F96C62F6E443731AB36F7BBB8A08", "ledger_hash": "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652", "ledger_index": 100, @@ -121,7 +120,7 @@ constexpr auto kDEFAULT_OUT2 = R"JSON({ "close_time_iso": "2000-01-01T00:00:00Z", "validated": true })JSON"; -constexpr auto kINDEX = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; +constexpr auto kIndex = "E6DBAFC99223B42257915A63DFC6B0C032D4070F9A574B255AD97466726FC322"; } // namespace @@ -131,7 +130,7 @@ TEST_F(RPCTxTest, ExcessiveLgrRange) { runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", @@ -139,7 +138,7 @@ TEST_F(RPCTxTest, ExcessiveLgrRange) "min_ledger": 1, "max_ledger": 1002 }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); @@ -155,14 +154,14 @@ TEST_F(RPCTxTest, InvalidBinaryV1) { TransactionAndMetadata tx; tx.metadata = - createMetaDataForCreateOffer(kCURRENCY, kACCOUNT, 100, 200, 300).getSerializer().peekData(); + createMetaDataForCreateOffer(kCurrency, kAccount, 100, 200, 300).getSerializer().peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300) .getSerializer() .peekData(); tx.date = 123456; tx.ledgerSequence = 100; - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillOnce(Return(tx)); + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillOnce(Return(tx)); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); ASSERT_NE(rawETLPtr, nullptr); @@ -170,14 +169,14 @@ TEST_F(RPCTxTest, InvalidBinaryV1) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}", "binary": 12 }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{.yield = yield, .apiVersion = 1u}); @@ -189,14 +188,14 @@ TEST_F(RPCTxTest, InvalidBinaryV2) { runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}", "binary": 12 }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{.yield = yield, .apiVersion = 2u}); @@ -212,7 +211,7 @@ TEST_F(RPCTxTest, InvalidLgrRange) { runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", @@ -220,7 +219,7 @@ TEST_F(RPCTxTest, InvalidLgrRange) "max_ledger": 1, "min_ledger": 10 }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); @@ -234,7 +233,7 @@ TEST_F(RPCTxTest, InvalidLgrRange) TEST_F(RPCTxTest, TxnNotFound) { - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)) + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)) .WillOnce(Return(std::optional{})); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); @@ -243,13 +242,13 @@ TEST_F(RPCTxTest, TxnNotFound) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}" }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); @@ -264,7 +263,7 @@ TEST_F(RPCTxTest, TxnNotFound) TEST_F(RPCTxTest, TxnNotFoundInGivenRangeSearchAllFalse) { backend_->setRange(10, 30); - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)) + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)) .WillOnce(Return(std::optional{})); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); @@ -273,7 +272,7 @@ TEST_F(RPCTxTest, TxnNotFoundInGivenRangeSearchAllFalse) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", @@ -281,7 +280,7 @@ TEST_F(RPCTxTest, TxnNotFoundInGivenRangeSearchAllFalse) "min_ledger": 1, "max_ledger": 1000 }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); @@ -297,7 +296,7 @@ TEST_F(RPCTxTest, TxnNotFoundInGivenRangeSearchAllFalse) TEST_F(RPCTxTest, TxnNotFoundInGivenRangeSearchAllTrue) { backend_->setRange(1, 1000); - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)) + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)) .WillOnce(Return(std::optional{})); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); @@ -306,7 +305,7 @@ TEST_F(RPCTxTest, TxnNotFoundInGivenRangeSearchAllTrue) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", @@ -314,7 +313,7 @@ TEST_F(RPCTxTest, TxnNotFoundInGivenRangeSearchAllTrue) "min_ledger": 1, "max_ledger": 1000 }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); @@ -332,7 +331,7 @@ TEST_F(RPCTxTest, TxnNotFoundInGivenRangeSearchAllTrue) TEST_F(RPCTxTest, CtidNotFoundSearchAllFalse) { backend_->setRange(1, 1000); - EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSEQ_FROM_CTID, _)) + EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSeqFromCtid, _)) .WillOnce(Return(std::vector{})); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); @@ -341,14 +340,14 @@ TEST_F(RPCTxTest, CtidNotFoundSearchAllFalse) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "ctid": "{}", "min_ledger": 1, "max_ledger": 1000 }})JSON", - kCTID + kCtid ) ); auto const output = handler.process(req, Context{yield}); @@ -365,15 +364,15 @@ TEST_F(RPCTxTest, DefaultParameter_API_v1) { TransactionAndMetadata tx; tx.metadata = - createMetaDataForCreateOffer(kCURRENCY, kACCOUNT, 100, 200, 300).getSerializer().peekData(); + createMetaDataForCreateOffer(kCurrency, kAccount, 100, 200, 300).getSerializer().peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300) .getSerializer() .peekData(); tx.date = 123456; tx.ledgerSequence = 100; - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillOnce(Return(tx)); + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillOnce(Return(tx)); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); ASSERT_NE(rawETLPtr, nullptr); @@ -381,19 +380,19 @@ TEST_F(RPCTxTest, DefaultParameter_API_v1) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}" }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{.yield = yield, .apiVersion = 1u}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kDEFAULT_OUT1)); + EXPECT_EQ(*output.result, boost::json::parse(kDefaultOuT1)); }); } @@ -401,13 +400,13 @@ TEST_F(RPCTxTest, PaymentTx_API_v1) { TransactionAndMetadata tx; tx.transaction = - createPaymentTransactionObject(kACCOUNT, kACCOUNT2, 2, 3, 300).getSerializer().peekData(); + createPaymentTransactionObject(kAccount, kAccount2, 2, 3, 300).getSerializer().peekData(); tx.metadata = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, 110, 30).getSerializer().peekData(); + createPaymentTransactionMetaObject(kAccount, kAccount2, 110, 30).getSerializer().peekData(); tx.date = 123456; tx.ledgerSequence = 100; - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillOnce(Return(tx)); + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillOnce(Return(tx)); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); ASSERT_NE(rawETLPtr, nullptr); @@ -415,13 +414,13 @@ TEST_F(RPCTxTest, PaymentTx_API_v1) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}" }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{.yield = yield, .apiVersion = 1u}); @@ -435,13 +434,13 @@ TEST_F(RPCTxTest, PaymentTx_API_v2) { TransactionAndMetadata tx; tx.transaction = - createPaymentTransactionObject(kACCOUNT, kACCOUNT2, 2, 3, 300).getSerializer().peekData(); + createPaymentTransactionObject(kAccount, kAccount2, 2, 3, 300).getSerializer().peekData(); tx.metadata = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, 110, 30).getSerializer().peekData(); + createPaymentTransactionMetaObject(kAccount, kAccount2, 110, 30).getSerializer().peekData(); tx.date = 123456; tx.ledgerSequence = 100; - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillOnce(Return(tx)); + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillOnce(Return(tx)); EXPECT_CALL(*backend_, fetchLedgerBySequence(tx.ledgerSequence, _)) .WillOnce(Return(std::nullopt)); @@ -451,13 +450,13 @@ TEST_F(RPCTxTest, PaymentTx_API_v2) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}" }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{.yield = yield, .apiVersion = 2u}); @@ -472,16 +471,16 @@ TEST_F(RPCTxTest, DefaultParameter_API_v2) { TransactionAndMetadata tx; tx.metadata = - createMetaDataForCreateOffer(kCURRENCY, kACCOUNT, 100, 200, 300).getSerializer().peekData(); + createMetaDataForCreateOffer(kCurrency, kAccount, 100, 200, 300).getSerializer().peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300) .getSerializer() .peekData(); tx.date = 123456; tx.ledgerSequence = 100; - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillOnce(Return(tx)); - auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, tx.ledgerSequence); + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillOnce(Return(tx)); + auto const ledgerHeader = createLedgerHeader(kLedgerHash, tx.ledgerSequence); EXPECT_CALL(*backend_, fetchLedgerBySequence(tx.ledgerSequence, _)) .WillOnce(Return(ledgerHeader)); @@ -491,25 +490,25 @@ TEST_F(RPCTxTest, DefaultParameter_API_v2) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}" }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{.yield = yield, .apiVersion = 2u}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kDEFAULT_OUT2)); + EXPECT_EQ(*output.result, boost::json::parse(kDefaultOuT2)); }); } TEST_F(RPCTxTest, ReturnBinary) { // Note: `inLedger` is API v1 only. See DefaultOutput_* - static constexpr auto kOUT = R"JSON({ + static constexpr auto kOut = R"JSON({ "meta": "201C00000064F8E311006FE864D50AA87BEE5380000158415500000000C1F76FF6ECB0BAC6000000004B4E9C06F24296074F7BC48F92A97916C6DC5EA96540000000000000C8E1E1F1031000", "tx": "120007240000006464400000000000012C65D5071AFD498D00000158415500000000C1F76FF6ECB0BAC600000000D31252CF902EF8DD8451243869B38667CBD89DF368400000000000000273047465737481144B4E9C06F24296074F7BC48F92A97916C6DC5EA9", "hash": "2E2FBAAFF767227FE4381C4BE9855986A6B9F96C62F6E443731AB36F7BBB8A08", @@ -522,14 +521,14 @@ TEST_F(RPCTxTest, ReturnBinary) TransactionAndMetadata tx; tx.metadata = - createMetaDataForCreateOffer(kCURRENCY, kACCOUNT, 100, 200, 300).getSerializer().peekData(); + createMetaDataForCreateOffer(kCurrency, kAccount, 100, 200, 300).getSerializer().peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300) .getSerializer() .peekData(); tx.date = 123456; tx.ledgerSequence = 100; - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillOnce(Return(tx)); + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillOnce(Return(tx)); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); ASSERT_NE(rawETLPtr, nullptr); @@ -537,19 +536,19 @@ TEST_F(RPCTxTest, ReturnBinary) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}", "binary": true }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kOUT)); + EXPECT_EQ(*output.result, boost::json::parse(kOut)); }); } @@ -557,7 +556,7 @@ TEST_F(RPCTxTest, ReturnBinary) TEST_F(RPCTxTest, ReturnBinaryWithCTID) { // Note: `inLedger` is API v1 only. See DefaultOutput_* - static constexpr auto kOUT = R"JSON({ + static constexpr auto kOut = R"JSON({ "meta": "201C00000064F8E311006FE864D50AA87BEE5380000158415500000000C1F76FF6ECB0BAC6000000004B4E9C06F24296074F7BC48F92A97916C6DC5EA96540000000000000C8E1E1F1031000", "tx": "120007240000006464400000000000012C65D5071AFD498D00000158415500000000C1F76FF6ECB0BAC600000000D31252CF902EF8DD8451243869B38667CBD89DF368400000000000000273047465737481144B4E9C06F24296074F7BC48F92A97916C6DC5EA9", "hash": "2E2FBAAFF767227FE4381C4BE9855986A6B9F96C62F6E443731AB36F7BBB8A08", @@ -570,14 +569,14 @@ TEST_F(RPCTxTest, ReturnBinaryWithCTID) TransactionAndMetadata tx; tx.metadata = - createMetaDataForCreateOffer(kCURRENCY, kACCOUNT, 100, 200, 300).getSerializer().peekData(); + createMetaDataForCreateOffer(kCurrency, kAccount, 100, 200, 300).getSerializer().peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300) .getSerializer() .peekData(); tx.date = 123456; tx.ledgerSequence = 100; - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillOnce(Return(tx)); + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillOnce(Return(tx)); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); ASSERT_NE(rawETLPtr, nullptr); @@ -585,26 +584,26 @@ TEST_F(RPCTxTest, ReturnBinaryWithCTID) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}", "binary": true }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kOUT)); + EXPECT_EQ(*output.result, boost::json::parse(kOut)); }); } TEST_F(RPCTxTest, MintNFT) { // Note: `inLedger` is API v1 only. See DefaultOutput_* - static auto const kOUT = fmt::format( + static auto const kOut = fmt::format( R"JSON({{ "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "Fee": "50", @@ -657,14 +656,14 @@ TEST_F(RPCTxTest, MintNFT) "inLedger": 100, "validated": true }})JSON", - kNFT_ID, - kNFT_ID + kNftId, + kNftId ); - TransactionAndMetadata tx = createMintNftTxWithMetadata(kACCOUNT, 1, 50, 123, kNFT_ID); + TransactionAndMetadata tx = createMintNftTxWithMetadata(kAccount, 1, 50, 123, kNftId); tx.date = 123456; tx.ledgerSequence = 100; - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillOnce(Return(tx)); + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillOnce(Return(tx)); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); ASSERT_NE(rawETLPtr, nullptr); @@ -672,29 +671,29 @@ TEST_F(RPCTxTest, MintNFT) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}" }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kOUT)); + EXPECT_EQ(*output.result, boost::json::parse(kOut)); }); } TEST_F(RPCTxTest, NFTAcceptOffer) { TransactionAndMetadata tx = - createAcceptNftBuyerOfferTxWithMetadata(kACCOUNT, 1, 50, kNFT_ID, kINDEX); + createAcceptNftBuyerOfferTxWithMetadata(kAccount, 1, 50, kNftId, kIndex); tx.date = 123456; tx.ledgerSequence = 100; - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillOnce(Return(tx)); + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillOnce(Return(tx)); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); ASSERT_NE(rawETLPtr, nullptr); @@ -702,29 +701,29 @@ TEST_F(RPCTxTest, NFTAcceptOffer) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}" }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("meta").at("nftoken_id").as_string(), kNFT_ID); + EXPECT_EQ(output.result->at("meta").at("nftoken_id").as_string(), kNftId); }); } TEST_F(RPCTxTest, NFTCancelOffer) { - std::vector ids{kNFT_ID, kNFT_ID2}; - TransactionAndMetadata tx = createCancelNftOffersTxWithMetadata(kACCOUNT, 1, 50, ids); + std::vector ids{kNftId, kNftID2}; + TransactionAndMetadata tx = createCancelNftOffersTxWithMetadata(kAccount, 1, 50, ids); tx.date = 123456; tx.ledgerSequence = 100; - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillOnce(Return(tx)); + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillOnce(Return(tx)); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); ASSERT_NE(rawETLPtr, nullptr); @@ -732,13 +731,13 @@ TEST_F(RPCTxTest, NFTCancelOffer) runSpawn([this, &ids](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}" }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); @@ -759,11 +758,11 @@ TEST_F(RPCTxTest, NFTCancelOffer) TEST_F(RPCTxTest, NFTCreateOffer) { TransactionAndMetadata tx = - createCreateNftOfferTxWithMetadata(kACCOUNT, 1, 50, kNFT_ID, 123, kNFT_ID2); + createCreateNftOfferTxWithMetadata(kAccount, 1, 50, kNftId, 123, kNftID2); tx.date = 123456; tx.ledgerSequence = 100; - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillOnce(Return(tx)); + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillOnce(Return(tx)); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); ASSERT_NE(rawETLPtr, nullptr); @@ -771,18 +770,18 @@ TEST_F(RPCTxTest, NFTCreateOffer) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}" }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_TRUE(output.result->at("meta").at("offer_id").as_string() == kNFT_ID2); + EXPECT_TRUE(output.result->at("meta").at("offer_id").as_string() == kNftID2); }); } @@ -790,15 +789,15 @@ TEST_F(RPCTxTest, CTIDAndTransactionBothProvided) { runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}", "ctid": "{}" }})JSON", - kTXN_ID, - kCTID + kTxnId, + kCtid ) ); auto const output = handler.process(req, Context{yield}); @@ -814,7 +813,7 @@ TEST_F(RPCTxTest, CTIDAndTransactionBothNotProvided) { runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse(R"JSON({ "command": "tx"})JSON"); + auto const req = boost::json::parse(R"JSON({ "command": "tx"})JSON"); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); @@ -828,7 +827,7 @@ TEST_F(RPCTxTest, CTIDInvalidType) { runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse(R"JSON({ "command": "tx", "ctid": 123})JSON"); + auto const req = boost::json::parse(R"JSON({ "command": "tx", "ctid": 123})JSON"); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); @@ -846,7 +845,8 @@ TEST_F(RPCTxTest, CTIDInvalidString) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse(R"JSON({ "command": "tx", "ctid": "B002807000010002"})JSON"); + auto const req = + boost::json::parse(R"JSON({ "command": "tx", "ctid": "B002807000010002"})JSON"); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); @@ -864,13 +864,13 @@ TEST_F(RPCTxTest, CTIDNotMatch) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "ctid": "{}" }})JSON", - kCTID + kCtid ) ); auto const output = handler.process(req, Context{yield}); @@ -878,7 +878,7 @@ TEST_F(RPCTxTest, CTIDNotMatch) auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "wrongNetwork"); - EXPECT_EQ(err.at("error_code").as_uint64(), rpc::RippledError::rpcWRONG_NETWORK); + EXPECT_EQ(err.at("error_code").as_uint64(), rpc::RippledError::RpcWrongNetwork); EXPECT_EQ( err.at("error_message").as_string(), "Wrong network. You should submit this request to a node running on NetworkID: 2" @@ -888,7 +888,7 @@ TEST_F(RPCTxTest, CTIDNotMatch) TEST_F(RPCTxTest, ReturnCTIDForTxInput) { - static constexpr auto kOUT = R"JSON({ + static constexpr auto kOut = R"JSON({ "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "Fee": "2", "Sequence": 100, @@ -929,14 +929,14 @@ TEST_F(RPCTxTest, ReturnCTIDForTxInput) TransactionAndMetadata tx; tx.metadata = - createMetaDataForCreateOffer(kCURRENCY, kACCOUNT, 100, 200, 300).getSerializer().peekData(); + createMetaDataForCreateOffer(kCurrency, kAccount, 100, 200, 300).getSerializer().peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300) .getSerializer() .peekData(); tx.date = 123456; tx.ledgerSequence = 100; - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillOnce(Return(tx)); + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillOnce(Return(tx)); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); ASSERT_NE(rawETLPtr, nullptr); @@ -944,24 +944,24 @@ TEST_F(RPCTxTest, ReturnCTIDForTxInput) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}" }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kOUT)); + EXPECT_EQ(*output.result, boost::json::parse(kOut)); }); } TEST_F(RPCTxTest, NotReturnCTIDIfETLNotAvailable) { - static constexpr auto kOUT = R"JSON({ + static constexpr auto kOut = R"JSON({ "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "Fee": "2", "Sequence": 100, @@ -1001,14 +1001,14 @@ TEST_F(RPCTxTest, NotReturnCTIDIfETLNotAvailable) TransactionAndMetadata tx; tx.metadata = - createMetaDataForCreateOffer(kCURRENCY, kACCOUNT, 100, 200, 300).getSerializer().peekData(); + createMetaDataForCreateOffer(kCurrency, kAccount, 100, 200, 300).getSerializer().peekData(); tx.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300) .getSerializer() .peekData(); tx.date = 123456; tx.ledgerSequence = 100; - EXPECT_CALL(*backend_, fetchTransaction(ripple::uint256{kTXN_ID}, _)).WillOnce(Return(tx)); + EXPECT_CALL(*backend_, fetchTransaction(xrpl::uint256{kTxnId}, _)).WillOnce(Return(tx)); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); ASSERT_NE(rawETLPtr, nullptr); @@ -1016,24 +1016,24 @@ TEST_F(RPCTxTest, NotReturnCTIDIfETLNotAvailable) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "transaction": "{}" }})JSON", - kTXN_ID + kTxnId ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kOUT)); + EXPECT_EQ(*output.result, boost::json::parse(kOut)); }); } TEST_F(RPCTxTest, ViaCTID) { - static auto const kOUT = fmt::format( + static auto const kOut = fmt::format( R"JSON({{ "Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "Fee": "2", @@ -1072,29 +1072,29 @@ TEST_F(RPCTxTest, ViaCTID) "inLedger": {}, "validated": true }})JSON", - kCTID, - kSEQ_FROM_CTID, - kSEQ_FROM_CTID + kCtid, + kSeqFromCtid, + kSeqFromCtid ); TransactionAndMetadata tx1; tx1.metadata = - createMetaDataForCreateOffer(kCURRENCY, kACCOUNT, 1, 200, 300).getSerializer().peekData(); + createMetaDataForCreateOffer(kCurrency, kAccount, 1, 200, 300).getSerializer().peekData(); tx1.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300) .getSerializer() .peekData(); tx1.date = 123456; - tx1.ledgerSequence = kSEQ_FROM_CTID; + tx1.ledgerSequence = kSeqFromCtid; TransactionAndMetadata tx2; tx2.transaction = - createPaymentTransactionObject(kACCOUNT, kACCOUNT2, 2, 3, 300).getSerializer().peekData(); + createPaymentTransactionObject(kAccount, kAccount2, 2, 3, 300).getSerializer().peekData(); tx2.metadata = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, 110, 30).getSerializer().peekData(); - tx2.ledgerSequence = kSEQ_FROM_CTID; + createPaymentTransactionMetaObject(kAccount, kAccount2, 110, 30).getSerializer().peekData(); + tx2.ledgerSequence = kSeqFromCtid; - EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSEQ_FROM_CTID, _)) + EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSeqFromCtid, _)) .WillOnce(Return(std::vector{tx1, tx2})); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); @@ -1103,18 +1103,18 @@ TEST_F(RPCTxTest, ViaCTID) runSpawn([this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", "ctid": "{}" }})JSON", - kCTID + kCtid ) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kOUT)); + EXPECT_EQ(*output.result, boost::json::parse(kOut)); }); } @@ -1122,34 +1122,34 @@ TEST_F(RPCTxTest, ViaLowercaseCTID) { TransactionAndMetadata tx1; tx1.metadata = - createMetaDataForCreateOffer(kCURRENCY, kACCOUNT, 1, 200, 300).getSerializer().peekData(); + createMetaDataForCreateOffer(kCurrency, kAccount, 1, 200, 300).getSerializer().peekData(); tx1.transaction = - createCreateOfferTransactionObject(kACCOUNT, 2, 100, kCURRENCY, kACCOUNT2, 200, 300) + createCreateOfferTransactionObject(kAccount, 2, 100, kCurrency, kAccount2, 200, 300) .getSerializer() .peekData(); tx1.date = 123456; - tx1.ledgerSequence = kSEQ_FROM_CTID; + tx1.ledgerSequence = kSeqFromCtid; TransactionAndMetadata tx2; tx2.transaction = - createPaymentTransactionObject(kACCOUNT, kACCOUNT2, 2, 3, 300).getSerializer().peekData(); + createPaymentTransactionObject(kAccount, kAccount2, 2, 3, 300).getSerializer().peekData(); tx2.metadata = - createPaymentTransactionMetaObject(kACCOUNT, kACCOUNT2, 110, 30).getSerializer().peekData(); - tx2.ledgerSequence = kSEQ_FROM_CTID; + createPaymentTransactionMetaObject(kAccount, kAccount2, 110, 30).getSerializer().peekData(); + tx2.ledgerSequence = kSeqFromCtid; - EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSEQ_FROM_CTID, _)) + EXPECT_CALL(*backend_, fetchAllTransactionsInLedger(kSeqFromCtid, _)) .WillOnce(Return(std::vector{tx1, tx2})); auto const rawETLPtr = dynamic_cast(mockETLServicePtr_.get()); ASSERT_NE(rawETLPtr, nullptr); EXPECT_CALL(*rawETLPtr, getETLState).WillOnce(Return(etl::ETLState{.networkID = 2})); - std::string ctid(kCTID); + std::string ctid(kCtid); std::ranges::transform(ctid, ctid.begin(), ::tolower); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{TestTxHandler{backend_, mockETLServicePtr_}}; - auto const req = json::parse( + auto const req = boost::json::parse( fmt::format( R"JSON({{ "command": "tx", @@ -1160,6 +1160,6 @@ TEST_F(RPCTxTest, ViaLowercaseCTID) ); auto const output = handler.process(req, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ(output.result->at("ctid").as_string(), kCTID); + EXPECT_EQ(output.result->at("ctid").as_string(), kCtid); }); } diff --git a/tests/unit/rpc/handlers/UnsubscribeTests.cpp b/tests/unit/rpc/handlers/UnsubscribeTests.cpp index 281b75079..c515bf775 100644 --- a/tests/unit/rpc/handlers/UnsubscribeTests.cpp +++ b/tests/unit/rpc/handlers/UnsubscribeTests.cpp @@ -23,14 +23,13 @@ using namespace rpc; using namespace data; -namespace json = boost::json; using namespace testing; using namespace feed; namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; } // namespace @@ -484,7 +483,7 @@ INSTANTIATE_TEST_CASE_P( RPCUnsubscribe, UnsubscribeParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(UnsubscribeParameterTest, InvalidParams) @@ -492,7 +491,7 @@ TEST_P(UnsubscribeParameterTest, InvalidParams) auto const testBundle = GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{UnsubscribeHandler{mockSubscriptionManagerPtr_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = handler.process(req, Context{yield}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -505,7 +504,8 @@ TEST_F(RPCUnsubscribeTest, EmptyResponse) { runSpawn([&, this](auto yield) { auto const handler = AnyHandler{UnsubscribeHandler{mockSubscriptionManagerPtr_}}; - auto const output = handler.process(json::parse(R"JSON({})JSON"), Context{yield, session_}); + auto const output = + handler.process(boost::json::parse(R"JSON({})JSON"), Context{yield, session_}); ASSERT_TRUE(output); EXPECT_TRUE(output.result->as_object().empty()); }); @@ -513,7 +513,7 @@ TEST_F(RPCUnsubscribeTest, EmptyResponse) TEST_F(RPCUnsubscribeTest, Streams) { - auto const input = json::parse( + auto const input = boost::json::parse( R"JSON({ "streams": ["transactions_proposed", "transactions", "validations", "manifests", "book_changes", "ledger"] })JSON" @@ -536,26 +536,26 @@ TEST_F(RPCUnsubscribeTest, Streams) TEST_F(RPCUnsubscribeTest, Accounts) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "accounts": ["{}", "{}"] }})JSON", - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount2 ) ); EXPECT_CALL( *mockSubscriptionManagerPtr_, // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - unsubAccount(*rpc::accountFromStringStrict(kACCOUNT), _) + unsubAccount(*rpc::accountFromStringStrict(kAccount), _) ) .Times(1); EXPECT_CALL( *mockSubscriptionManagerPtr_, // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - unsubAccount(*rpc::accountFromStringStrict(kACCOUNT2), _) + unsubAccount(*rpc::accountFromStringStrict(kAccount2), _) ) .Times(1); @@ -569,26 +569,26 @@ TEST_F(RPCUnsubscribeTest, Accounts) TEST_F(RPCUnsubscribeTest, AccountsProposed) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "accounts_proposed": ["{}", "{}"] }})JSON", - kACCOUNT, - kACCOUNT2 + kAccount, + kAccount2 ) ); EXPECT_CALL( *mockSubscriptionManagerPtr_, // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - unsubProposedAccount(*rpc::accountFromStringStrict(kACCOUNT), _) + unsubProposedAccount(*rpc::accountFromStringStrict(kAccount), _) ) .Times(1); EXPECT_CALL( *mockSubscriptionManagerPtr_, // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - unsubProposedAccount(*rpc::accountFromStringStrict(kACCOUNT2), _) + unsubProposedAccount(*rpc::accountFromStringStrict(kAccount2), _) ) .Times(1); @@ -602,7 +602,7 @@ TEST_F(RPCUnsubscribeTest, AccountsProposed) TEST_F(RPCUnsubscribeTest, Books) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "books": [ @@ -618,7 +618,7 @@ TEST_F(RPCUnsubscribeTest, Books) }} ] }})JSON", - kACCOUNT + kAccount ) ); @@ -627,7 +627,7 @@ TEST_F(RPCUnsubscribeTest, Books) auto const book = *parsedBookMaybe; EXPECT_CALL(*mockSubscriptionManagerPtr_, unsubBook(book, _)).Times(1); - EXPECT_CALL(*mockSubscriptionManagerPtr_, unsubBook(ripple::reversed(book), _)).Times(1); + EXPECT_CALL(*mockSubscriptionManagerPtr_, unsubBook(xrpl::reversed(book), _)).Times(1); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{UnsubscribeHandler{mockSubscriptionManagerPtr_}}; @@ -639,7 +639,7 @@ TEST_F(RPCUnsubscribeTest, Books) TEST_F(RPCUnsubscribeTest, SingleBooks) { - auto const input = json::parse( + auto const input = boost::json::parse( fmt::format( R"JSON({{ "books": [ @@ -654,7 +654,7 @@ TEST_F(RPCUnsubscribeTest, SingleBooks) }} ] }})JSON", - kACCOUNT + kAccount ) ); diff --git a/tests/unit/rpc/handlers/VaultInfoTests.cpp b/tests/unit/rpc/handlers/VaultInfoTests.cpp index 326fe69cb..f1fc0afb0 100644 --- a/tests/unit/rpc/handlers/VaultInfoTests.cpp +++ b/tests/unit/rpc/handlers/VaultInfoTests.cpp @@ -24,25 +24,24 @@ using namespace rpc; using namespace data; using namespace testing; -namespace json = boost::json; namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; -constexpr auto kACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; -constexpr auto kINDEX1 = "ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890"; -constexpr auto kSEQ = 30; -constexpr auto kASSET_CURRENCY = "XRP"; -constexpr auto kASSET_ISSUER = "rrrrrrrrrrrrrrrrrrrrrhoLvTp"; -constexpr auto kVAULT_ID = "61B03A6F8CEBD3AF9D8F696C3D0A9A9F0493B34BF6B5D93CF0BC009E6BA75303"; -constexpr auto kAPI_VERSION = 2; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun"; +constexpr auto kIndex1 = "ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890"; +constexpr auto kSeq = 30; +constexpr auto kAssetCurrency = "XRP"; +constexpr auto kAssetIssuer = "rrrrrrrrrrrrrrrrrrrrrhoLvTp"; +constexpr auto kVaultId = "61B03A6F8CEBD3AF9D8F696C3D0A9A9F0493B34BF6B5D93CF0BC009E6BA75303"; +constexpr auto kApiVersion = 2; } // namespace struct RPCVaultInfoHandlerTest : HandlerBaseTest { RPCVaultInfoHandlerTest() { - backend_->setRange(10, kSEQ); + backend_->setRange(10, kSeq); } protected: @@ -146,8 +145,8 @@ generateTestValuesForParametersTest() "vault_id": "{}", "owner": "{}" }})JSON", - kVAULT_ID, - kACCOUNT + kVaultId, + kAccount ), .expectedError = "malformedRequest", .expectedErrorCode = ClioError::RpcMalformedRequest, @@ -160,7 +159,7 @@ INSTANTIATE_TEST_CASE_P( RPCVaultInfoGroup, VaultInfoParameterTest, ValuesIn(generateTestValuesForParametersTest()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(VaultInfoParameterTest, InvalidParams) @@ -168,9 +167,9 @@ TEST_P(VaultInfoParameterTest, InvalidParams) auto const testBundle = VaultInfoParameterTest::GetParam(); runSpawn([&, this](auto yield) { auto const handler = AnyHandler{VaultInfoHandler{backend_}}; - auto const req = json::parse(testBundle.testJson); + auto const req = boost::json::parse(testBundle.testJson); auto const output = - handler.process(req, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + handler.process(req, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); @@ -187,17 +186,17 @@ TEST_P(VaultInfoParameterTest, InvalidParams) TEST_F(RPCVaultInfoHandlerTest, InputHasOwnerButNotFoundResultsInError) { - auto const ledgerHeader = createLedgerHeader(kINDEX1, kSEQ); + auto const ledgerHeader = createLedgerHeader(kIndex1, kSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); // Input JSON using vault object - auto static const kINPUT = boost::json::parse( + auto static const kInput = boost::json::parse( fmt::format( R"JSON({{ "owner": "{}", "seq": 3 }})JSON", - kACCOUNT + kAccount ) ); @@ -205,101 +204,101 @@ TEST_F(RPCVaultInfoHandlerTest, InputHasOwnerButNotFoundResultsInError) auto const handler = AnyHandler{VaultInfoHandler{backend_}}; runSpawn([&](auto yield) { auto const output = - handler.process(kINPUT, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + handler.process(kInput, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "entryNotFound"); - EXPECT_EQ(err.at("error_code").as_uint64(), rpc::RippledError::rpcENTRY_NOT_FOUND); + EXPECT_EQ(err.at("error_code").as_uint64(), rpc::RippledError::RpcEntryNotFound); EXPECT_EQ(err.at("error_message").as_string(), "Entry not found."); }); } TEST_F(RPCVaultInfoHandlerTest, VaultIDFailsVaultDeserializationReturnsEntryNotFound) { - auto const ledgerHeader = createLedgerHeader(kINDEX1, kSEQ); + auto const ledgerHeader = createLedgerHeader(kIndex1, kSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); // Mock: vault_id exists, but data is not a valid vault object - ripple::uint256 const vaultKey = ripple::uint256{kVAULT_ID}; - EXPECT_CALL(*backend_, doFetchLedgerObject(vaultKey, kSEQ, _)) + xrpl::uint256 const vaultKey = xrpl::uint256{kVaultId}; + EXPECT_CALL(*backend_, doFetchLedgerObject(vaultKey, kSeq, _)) .WillOnce(Return(std::nullopt)); // intentionally invalid vault - auto const kINPUT = boost::json::parse( + auto const kInput = boost::json::parse( fmt::format( R"({{ "vault_id": "{}" }})", - kVAULT_ID + kVaultId ) ); auto const handler = AnyHandler{VaultInfoHandler{backend_}}; runSpawn([&](auto yield) { auto const output = - handler.process(kINPUT, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + handler.process(kInput, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "entryNotFound"); - EXPECT_EQ(err.at("error_code").as_uint64(), rpc::RippledError::rpcENTRY_NOT_FOUND); + EXPECT_EQ(err.at("error_code").as_uint64(), rpc::RippledError::RpcEntryNotFound); EXPECT_EQ(err.at("error_message").as_string(), "vault object not found."); }); } TEST_F(RPCVaultInfoHandlerTest, MissingIssuanceObject) { - auto const ledgerHeader = createLedgerHeader(kINDEX1, kSEQ); + auto const ledgerHeader = createLedgerHeader(kIndex1, kSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); - ripple::uint192 const mptSharesID{123}; - ripple::uint256 const prevTxId{2}; + xrpl::uint192 const mptSharesID{123}; + xrpl::uint256 const prevTxId{2}; uint32_t const prevTxSeq = 3; uint64_t const ownerNode = 4; auto const vault = createVault( - kACCOUNT, - kACCOUNT2, - kSEQ, - kASSET_CURRENCY, - kASSET_ISSUER, + kAccount, + kAccount2, + kSeq, + kAssetCurrency, + kAssetIssuer, mptSharesID, ownerNode, prevTxId, prevTxSeq ); - auto const vaultKeylet = ripple::keylet::vault(ripple::uint256{kVAULT_ID}).key; - auto const mptIssuance = ripple::keylet::mptIssuance(mptSharesID).key; + auto const vaultKeylet = xrpl::keylet::vault(xrpl::uint256{kVaultId}).key; + auto const mptIssuance = xrpl::keylet::mptokenIssuance(mptSharesID).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(vaultKeylet, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(vaultKeylet, kSeq, _)) .WillOnce(Return(vault.getSerializer().peekData())); - EXPECT_CALL(*backend_, doFetchLedgerObject(mptIssuance, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(mptIssuance, kSeq, _)) .WillOnce(Return(std::nullopt)); // Missing issuance - auto static const kINPUT = boost::json::parse( + auto static const kInput = boost::json::parse( fmt::format( R"({{ "vault_id": "{}" }})", - kVAULT_ID + kVaultId ) ); auto const handler = AnyHandler{VaultInfoHandler{backend_}}; runSpawn([&](auto yield) { auto const output = - handler.process(kINPUT, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + handler.process(kInput, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_FALSE(output); auto const err = rpc::makeError(output.result.error()); EXPECT_EQ(err.at("error").as_string(), "entryNotFound"); - EXPECT_EQ(err.at("error_code").as_uint64(), rpc::RippledError::rpcENTRY_NOT_FOUND); + EXPECT_EQ(err.at("error_code").as_uint64(), rpc::RippledError::RpcEntryNotFound); EXPECT_EQ(err.at("error_message").as_string(), "issuance object not found."); }); } TEST_F(RPCVaultInfoHandlerTest, ValidVaultObjectQueryByVaultID) { - constexpr auto kEXPECTED_OUTPUT = + constexpr auto kExpectedOutput = R"JSON({ "ledger_index": 30, "validated": true, @@ -337,22 +336,22 @@ TEST_F(RPCVaultInfoHandlerTest, ValidVaultObjectQueryByVaultID) } })JSON"; - auto const ledgerHeader = createLedgerHeader(kINDEX1, kSEQ); + auto const ledgerHeader = createLedgerHeader(kIndex1, kSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); // Vault params - ripple::uint192 const mptSharesID{123}; - ripple::uint256 const prevTxId{2}; + xrpl::uint192 const mptSharesID{123}; + xrpl::uint256 const prevTxId{2}; uint32_t const prevTxSeq = 3; uint64_t const ownerNode = 4; // Mock vault object auto const vault = createVault( - kACCOUNT, - kACCOUNT2, - kSEQ, - kASSET_CURRENCY, - kASSET_ISSUER, + kAccount, + kAccount2, + kSeq, + kAssetCurrency, + kAssetIssuer, mptSharesID, ownerNode, prevTxId, @@ -360,22 +359,22 @@ TEST_F(RPCVaultInfoHandlerTest, ValidVaultObjectQueryByVaultID) ); // Set up keylet based on vaultID - auto const issuance = createMptIssuanceObject(kACCOUNT, kSEQ, "metadata"); - auto const vaultKeylet = ripple::keylet::vault(ripple::uint256{kVAULT_ID}).key; - auto const mptIssuance = ripple::keylet::mptIssuance(mptSharesID).key; + auto const issuance = createMptIssuanceObject(kAccount, kSeq, "metadata"); + auto const vaultKeylet = xrpl::keylet::vault(xrpl::uint256{kVaultId}).key; + auto const mptIssuance = xrpl::keylet::mptokenIssuance(mptSharesID).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(vaultKeylet, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(vaultKeylet, kSeq, _)) .WillOnce(Return(vault.getSerializer().peekData())); - EXPECT_CALL(*backend_, doFetchLedgerObject(mptIssuance, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(mptIssuance, kSeq, _)) .WillOnce(Return(issuance.getSerializer().peekData())); // Input JSON using vault_id - auto static const kINPUT = boost::json::parse( + auto static const kInput = boost::json::parse( fmt::format( R"({{ "vault_id": "{}" }})", - kVAULT_ID + kVaultId ) ); @@ -383,15 +382,15 @@ TEST_F(RPCVaultInfoHandlerTest, ValidVaultObjectQueryByVaultID) auto const handler = AnyHandler{VaultInfoHandler{backend_}}; runSpawn([&](auto yield) { auto const output = - handler.process(kINPUT, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + handler.process(kInput, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUTPUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOutput)); }); } TEST_F(RPCVaultInfoHandlerTest, ValidVaultObjectQueryByOwnerAndSeq) { - constexpr auto kEXPECTED_OUTPUT = + constexpr auto kExpectedOutput = R"JSON({ "ledger_index": 30, "validated": true, @@ -429,53 +428,53 @@ TEST_F(RPCVaultInfoHandlerTest, ValidVaultObjectQueryByOwnerAndSeq) } })JSON"; - auto const ledgerHeader = createLedgerHeader(kINDEX1, kSEQ); + auto const ledgerHeader = createLedgerHeader(kIndex1, kSeq); EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); // Vault params - ripple::uint192 const mptSharesID{123}; - ripple::uint256 const prevTxId{2}; + xrpl::uint192 const mptSharesID{123}; + xrpl::uint256 const prevTxId{2}; uint32_t const prevTxSeq = 3; uint64_t const ownerNode = 4; // Mock vault object auto const vault = createVault( - kACCOUNT, - kACCOUNT2, - kSEQ, - kASSET_CURRENCY, - kASSET_ISSUER, + kAccount, + kAccount2, + kSeq, + kAssetCurrency, + kAssetIssuer, mptSharesID, ownerNode, prevTxId, prevTxSeq ); - auto const issuance = createMptIssuanceObject(kACCOUNT, kSEQ, "metadata"); + auto const issuance = createMptIssuanceObject(kAccount, kSeq, "metadata"); - auto const accountRoot = createAccountRootObject(kACCOUNT, 0, kSEQ, 200, 2, kINDEX1, 2); - auto const account = getAccountIdWithString(kACCOUNT); - auto const accountKeylet = ripple::keylet::account(account).key; - auto const vaultKeylet = ripple::keylet::vault(account, kSEQ).key; - auto const mptIssuance = ripple::keylet::mptIssuance(mptSharesID).key; + auto const accountRoot = createAccountRootObject(kAccount, 0, kSeq, 200, 2, kIndex1, 2); + auto const account = getAccountIdWithString(kAccount); + auto const accountKeylet = xrpl::keylet::account(account).key; + auto const vaultKeylet = xrpl::keylet::vault(account, kSeq).key; + auto const mptIssuance = xrpl::keylet::mptokenIssuance(mptSharesID).key; - EXPECT_CALL(*backend_, doFetchLedgerObject(accountKeylet, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(accountKeylet, kSeq, _)) .WillOnce(Return(accountRoot.getSerializer().peekData())); - EXPECT_CALL(*backend_, doFetchLedgerObject(vaultKeylet, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(vaultKeylet, kSeq, _)) .WillOnce(Return(vault.getSerializer().peekData())); - EXPECT_CALL(*backend_, doFetchLedgerObject(mptIssuance, kSEQ, _)) + EXPECT_CALL(*backend_, doFetchLedgerObject(mptIssuance, kSeq, _)) .WillOnce(Return(issuance.getSerializer().peekData())); // Input JSON using vault object - auto static const kINPUT = boost::json::parse( + auto static const kInput = boost::json::parse( fmt::format( R"JSON({{ "owner": "{}", "seq": {}, "ledger_index": 30 }})JSON", - kACCOUNT, - kSEQ + kAccount, + kSeq ) ); @@ -483,8 +482,8 @@ TEST_F(RPCVaultInfoHandlerTest, ValidVaultObjectQueryByOwnerAndSeq) auto const handler = AnyHandler{VaultInfoHandler{backend_}}; runSpawn([&](auto yield) { auto const output = - handler.process(kINPUT, Context{.yield = yield, .apiVersion = kAPI_VERSION}); + handler.process(kInput, Context{.yield = yield, .apiVersion = kApiVersion}); ASSERT_TRUE(output); - EXPECT_EQ(*output.result, json::parse(kEXPECTED_OUTPUT)); + EXPECT_EQ(*output.result, boost::json::parse(kExpectedOutput)); }); } diff --git a/tests/unit/rpc/handlers/VersionHandlerTests.cpp b/tests/unit/rpc/handlers/VersionHandlerTests.cpp index feb623978..c22dc82d3 100644 --- a/tests/unit/rpc/handlers/VersionHandlerTests.cpp +++ b/tests/unit/rpc/handlers/VersionHandlerTests.cpp @@ -14,9 +14,9 @@ namespace { -constexpr auto kDEFAULT_API_VERSION = 3u; -constexpr auto kMIN_API_VERSION = 2u; -constexpr auto kMAX_API_VERSION = 10u; +constexpr auto kDefaultApiVersion = 3u; +constexpr auto kMinApiVersion = 2u; +constexpr auto kMaxApiVersion = 10u; } // namespace @@ -28,9 +28,9 @@ class RPCVersionHandlerTest : public HandlerBaseTest {}; TEST_F(RPCVersionHandlerTest, Default) { ClioConfigDefinition cfg{ - {"api_version.min", ConfigValue{ConfigType::Integer}.defaultValue(kMIN_API_VERSION)}, - {"api_version.max", ConfigValue{ConfigType::Integer}.defaultValue(kMAX_API_VERSION)}, - {"api_version.default", ConfigValue{ConfigType::Integer}.defaultValue(kDEFAULT_API_VERSION)} + {"api_version.min", ConfigValue{ConfigType::Integer}.defaultValue(kMinApiVersion)}, + {"api_version.max", ConfigValue{ConfigType::Integer}.defaultValue(kMaxApiVersion)}, + {"api_version.default", ConfigValue{ConfigType::Integer}.defaultValue(kDefaultApiVersion)} }; boost::json::value jsonData = boost::json::parse( @@ -40,9 +40,9 @@ TEST_F(RPCVersionHandlerTest, Default) "api_version.max": {}, "api_version.default": {} }})JSON", - kMIN_API_VERSION, - kMAX_API_VERSION, - kDEFAULT_API_VERSION + kMinApiVersion, + kMaxApiVersion, + kDefaultApiVersion ) ); diff --git a/tests/unit/test_data/SslCert.cpp b/tests/unit/test_data/SslCert.cpp index bfeb1b64d..7fa8fc6c7 100644 --- a/tests/unit/test_data/SslCert.cpp +++ b/tests/unit/test_data/SslCert.cpp @@ -9,7 +9,7 @@ namespace tests { std::string_view sslCert() { - static constexpr auto kCERT = R"( + static constexpr auto kCert = R"( -----BEGIN CERTIFICATE----- MIIDrjCCApagAwIBAgIJAOE4Hv/P8CO3MA0GCSqGSIb3DQEBCwUAMDkxEjAQBgNV BAMMCTEyNy4wLjAuMTELMAkGA1UEBhMCVVMxFjAUBgNVBAcMDVNhbiBGcmFuc2lz @@ -33,7 +33,7 @@ LLuOOuPuy2d+HqjKE7z00j28Uf7gZK29bGx1rK+xH6veAr4plKBavBr8WWpAoUG+ PAMNb1i80cMsjK98xXDdr+7Uvy5M4COMwA5XHmMZDEW8Jw== -----END CERTIFICATE----- )"; - return kCERT; + return kCert; } TmpFile @@ -45,7 +45,7 @@ sslCertFile() std::string_view sslKey() { - static constexpr auto kKEY = R"( + static constexpr auto kKey = R"( -----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAqP3K4WDIhk63zbxSoN8tJqRZD3W0IWFMwCluZchUwsHPxEC4 32sPk58YonynY5nGtTeSGhedSqHD0gFBLcU/su4dSsj+kgGgJwKmiPmoQiTpzEmd @@ -74,7 +74,7 @@ O2R4tGOOkGAX/0/actRXptFk23ucHnSIwcW6HYgDM3tDBP7n3GYdu5CSE1eiR5k7 Zl3fuvbMYcmYKgutFcRj+8NvzRWT2suzGU2x4PiPX+fh5kpvmMdvLA== -----END RSA PRIVATE KEY----- )"; - return kKEY; + return kKey; } TmpFile diff --git a/tests/unit/util/AccountUtilsTests.cpp b/tests/unit/util/AccountUtilsTests.cpp index 2e13e9948..f02583998 100644 --- a/tests/unit/util/AccountUtilsTests.cpp +++ b/tests/unit/util/AccountUtilsTests.cpp @@ -6,22 +6,22 @@ #include namespace { -constexpr auto kACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; +constexpr auto kAccount = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; } // namespace TEST(AccountUtils, parseBase58Wrapper) { - EXPECT_FALSE(util::parseBase58Wrapper("rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jp!")); - EXPECT_TRUE(util::parseBase58Wrapper(kACCOUNT)); + EXPECT_FALSE(util::parseBase58Wrapper("rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jp!")); + EXPECT_TRUE(util::parseBase58Wrapper(kAccount)); EXPECT_TRUE( - util::parseBase58Wrapper( - ripple::TokenType::NodePrivate, "paQmjZ37pKKPMrgadBLsuf9ab7Y7EUNzh27LQrZqoexpAs31nJi" + util::parseBase58Wrapper( + xrpl::TokenType::NodePrivate, "paQmjZ37pKKPMrgadBLsuf9ab7Y7EUNzh27LQrZqoexpAs31nJi" ) ); EXPECT_FALSE( - util::parseBase58Wrapper( - ripple::TokenType::NodePrivate, "??paQmjZ37pKKPMrgadBLsuf9ab7Y7EUNzh27LQrZqoexpAs31n" + util::parseBase58Wrapper( + xrpl::TokenType::NodePrivate, "??paQmjZ37pKKPMrgadBLsuf9ab7Y7EUNzh27LQrZqoexpAs31n" ) ); } diff --git a/tests/unit/util/BlockingCacheTests.cpp b/tests/unit/util/BlockingCacheTests.cpp index 093f4c751..8f2118cff 100644 --- a/tests/unit/util/BlockingCacheTests.cpp +++ b/tests/unit/util/BlockingCacheTests.cpp @@ -184,7 +184,7 @@ INSTANTIATE_TEST_SUITE_P( .testName = "UpdateFails" } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_F(BlockingCacheTest, InvalidateWhenStateIsNoValue) diff --git a/tests/unit/util/ChannelTests.cpp b/tests/unit/util/ChannelTests.cpp index 14380fcaf..1bd3453e6 100644 --- a/tests/unit/util/ChannelTests.cpp +++ b/tests/unit/util/ChannelTests.cpp @@ -28,13 +28,13 @@ using namespace testing; namespace { -constexpr auto kDEFAULT_THREAD_POOL_SIZE = 4; -constexpr auto kTEST_TIMEOUT = std::chrono::seconds{10}; +constexpr auto kDefaultThreadPoolSize = 4; +constexpr auto kTestTimeout = std::chrono::seconds{10}; -constexpr auto kNUM_SENDERS = 3uz; -constexpr auto kNUM_RECEIVERS = 3uz; -constexpr auto kVALUES_PER_SENDER = 500uz; -constexpr auto kTOTAL_EXPECTED = kNUM_SENDERS * kVALUES_PER_SENDER; +constexpr auto kNumSenders = 3uz; +constexpr auto kNumReceivers = 3uz; +constexpr auto kValuesPerSender = 500uz; +constexpr auto kTotalExpected = kNumSenders * kValuesPerSender; enum class ContextType { IOContext, ThreadPool }; @@ -48,9 +48,9 @@ std::vector generateExpectedValues() { std::vector expectedValues; - expectedValues.reserve(kTOTAL_EXPECTED); - for (auto senderId = 0uz; senderId < kNUM_SENDERS; ++senderId) { - for (auto i = 0uz; i < kVALUES_PER_SENDER; ++i) { + expectedValues.reserve(kTotalExpected); + for (auto senderId = 0uz; senderId < kNumSenders; ++senderId) { + for (auto i = 0uz; i < kValuesPerSender; ++i) { expectedValues.push_back(generateValue(senderId, i)); } } @@ -58,7 +58,7 @@ generateExpectedValues() return expectedValues; } -std::vector const kEXPECTED_VALUES = generateExpectedValues(); +std::vector const kExpectedValues = generateExpectedValues(); std::string contextTypeToString(ContextType type) @@ -77,7 +77,7 @@ public: if (type == ContextType::ThreadPool) { return ContextVariant( - std::in_place_type_t(), kDEFAULT_THREAD_POOL_SIZE + std::in_place_type_t(), kDefaultThreadPoolSize ); } @@ -99,7 +99,7 @@ public: { std::visit( util::OverloadSet{ - [](boost::asio::io_context& context) { context.run_for(kTEST_TIMEOUT); }, + [](boost::asio::io_context& context) { context.run_for(kTestTimeout); }, [](boost::asio::thread_pool& context) { context.join(); }, }, context_ @@ -149,11 +149,11 @@ TEST_P(ChannelSpawnTest, MultipleSendersOneReceiver) { auto localSender = std::move(sender); - for (auto senderId = 0uz; senderId < kNUM_SENDERS; ++senderId) { + for (auto senderId = 0uz; senderId < kNumSenders; ++senderId) { util::spawn( executor, [senderCopy = localSender, senderId](boost::asio::yield_context yield) mutable { - for (auto i = 0uz; i < kVALUES_PER_SENDER; ++i) { + for (auto i = 0uz; i < kValuesPerSender; ++i) { if (not senderCopy.asyncSend(generateValue(senderId, i), yield)) break; } @@ -164,10 +164,10 @@ TEST_P(ChannelSpawnTest, MultipleSendersOneReceiver) context_.run(); - EXPECT_EQ(receivedValues.lock()->size(), kTOTAL_EXPECTED); + EXPECT_EQ(receivedValues.lock()->size(), kTotalExpected); std::ranges::sort(receivedValues.lock().get()); - EXPECT_EQ(receivedValues.lock().get(), kEXPECTED_VALUES); + EXPECT_EQ(receivedValues.lock().get(), kExpectedValues); }); } @@ -176,9 +176,9 @@ TEST_P(ChannelSpawnTest, MultipleSendersMultipleReceivers) context_.withExecutor([this](auto& executor) { auto [sender, receiver] = util::Channel::create(executor, 10); util::Mutex> receivedValues; - std::vector receivers(kNUM_RECEIVERS, receiver); + std::vector receivers(kNumReceivers, receiver); - for (auto receiverId = 0uz; receiverId < kNUM_RECEIVERS; ++receiverId) { + for (auto receiverId = 0uz; receiverId < kNumReceivers; ++receiverId) { util::spawn( executor, [&receiverRef = receivers[receiverId], @@ -195,11 +195,11 @@ TEST_P(ChannelSpawnTest, MultipleSendersMultipleReceivers) { auto localSender = std::move(sender); - for (auto senderId = 0uz; senderId < kNUM_SENDERS; ++senderId) { + for (auto senderId = 0uz; senderId < kNumSenders; ++senderId) { util::spawn( executor, [senderCopy = localSender, senderId](boost::asio::yield_context yield) mutable { - for (auto i = 0uz; i < kVALUES_PER_SENDER; ++i) { + for (auto i = 0uz; i < kValuesPerSender; ++i) { auto const value = generateValue(senderId, i); if (not senderCopy.asyncSend(value, yield)) break; @@ -211,10 +211,10 @@ TEST_P(ChannelSpawnTest, MultipleSendersMultipleReceivers) context_.run(); - EXPECT_EQ(receivedValues.lock()->size(), kTOTAL_EXPECTED); + EXPECT_EQ(receivedValues.lock()->size(), kTotalExpected); std::ranges::sort(receivedValues.lock().get()); - EXPECT_EQ(receivedValues.lock().get(), kEXPECTED_VALUES); + EXPECT_EQ(receivedValues.lock().get(), kExpectedValues); }); } @@ -346,7 +346,7 @@ TEST_P(ChannelCallbackTest, MultipleSendersOneReceiver) util::Mutex> receivedValues; auto receiveNext = [&receiver, &receivedValues](this auto&& self) -> void { - if (receivedValues.lock()->size() >= kTOTAL_EXPECTED) + if (receivedValues.lock()->size() >= kTotalExpected) return; receiver.asyncReceive([&receivedValues, @@ -362,14 +362,14 @@ TEST_P(ChannelCallbackTest, MultipleSendersOneReceiver) { auto localSender = std::move(sender); - for (auto senderId = 0uz; senderId < kNUM_SENDERS; ++senderId) { + for (auto senderId = 0uz; senderId < kNumSenders; ++senderId) { auto senderCopy = localSender; boost::asio::post( executor, [senderCopy = std::move(senderCopy), senderId, &executor]() mutable { auto sendNext = [senderCopy = std::move(senderCopy), senderId, &executor](this auto&& self, std::size_t i) -> void { - if (i >= kVALUES_PER_SENDER) + if (i >= kValuesPerSender) return; senderCopy.asyncSend( @@ -394,10 +394,10 @@ TEST_P(ChannelCallbackTest, MultipleSendersOneReceiver) context_.run(); - EXPECT_EQ(receivedValues.lock()->size(), kTOTAL_EXPECTED); + EXPECT_EQ(receivedValues.lock()->size(), kTotalExpected); std::ranges::sort(receivedValues.lock().get()); - EXPECT_EQ(receivedValues.lock().get(), kEXPECTED_VALUES); + EXPECT_EQ(receivedValues.lock().get(), kExpectedValues); }); } @@ -406,9 +406,9 @@ TEST_P(ChannelCallbackTest, MultipleSendersMultipleReceivers) context_.withExecutor([this](auto& executor) { auto [sender, receiver] = util::Channel::create(executor, 10); util::Mutex> receivedValues; - std::vector receivers(kNUM_RECEIVERS, receiver); + std::vector receivers(kNumReceivers, receiver); - for (auto receiverId = 0uz; receiverId < kNUM_RECEIVERS; ++receiverId) { + for (auto receiverId = 0uz; receiverId < kNumReceivers; ++receiverId) { auto& receiverRef = receivers[receiverId]; auto receiveNext = [&receiverRef, &receivedValues](this auto&& self) -> void { receiverRef.asyncReceive([&receivedValues, @@ -424,14 +424,14 @@ TEST_P(ChannelCallbackTest, MultipleSendersMultipleReceivers) { auto localSender = std::move(sender); - for (auto senderId = 0uz; senderId < kNUM_SENDERS; ++senderId) { + for (auto senderId = 0uz; senderId < kNumSenders; ++senderId) { auto senderCopy = localSender; boost::asio::post( executor, [senderCopy = std::move(senderCopy), senderId, &executor]() mutable { auto sendNext = [senderCopy = std::move(senderCopy), senderId, &executor](this auto&& self, std::size_t i) -> void { - if (i >= kVALUES_PER_SENDER) + if (i >= kValuesPerSender) return; senderCopy.asyncSend( @@ -456,10 +456,10 @@ TEST_P(ChannelCallbackTest, MultipleSendersMultipleReceivers) context_.run(); - EXPECT_EQ(receivedValues.lock()->size(), kTOTAL_EXPECTED); + EXPECT_EQ(receivedValues.lock()->size(), kTotalExpected); std::ranges::sort(receivedValues.lock().get()); - EXPECT_EQ(receivedValues.lock().get(), kEXPECTED_VALUES); + EXPECT_EQ(receivedValues.lock().get(), kExpectedValues); }); } @@ -620,7 +620,7 @@ TEST(ChannelTest, MultipleSenderCopiesErrorHandling) testCompleted = true; }); - executor.run_for(kTEST_TIMEOUT); + executor.run_for(kTestTimeout); EXPECT_TRUE(testCompleted); } @@ -706,7 +706,7 @@ TEST(ChannelTest, ChannelPreservesOrderFIFO) } ); - executor.run_for(kTEST_TIMEOUT); + executor.run_for(kTestTimeout); EXPECT_TRUE(testCompleted); } @@ -735,7 +735,7 @@ TEST(ChannelTest, AsyncReceiveWakesUpWhenSenderDestroyed) } ); - executor.run_for(kTEST_TIMEOUT); + executor.run_for(kTestTimeout); EXPECT_TRUE(testCompleted); } @@ -746,16 +746,16 @@ TEST(ChannelTest, AsyncReceiveWakesUpWhenSenderDestroyed) TEST(ChannelTest, PendingAsyncSendsAreCancelledOnClose) { boost::asio::thread_pool pool{4}; - static constexpr auto kPENDING_NUM_SENDERS = 10uz; + static constexpr auto kPendingNumSenders = 10uz; // Channel with capacity 0 - all sends will block waiting for a receiver auto [sender, receiver] = util::Channel::create(pool, 0); std::atomic completedSends{0}; - std::counting_semaphore semaphore{kPENDING_NUM_SENDERS}; + std::counting_semaphore semaphore{kPendingNumSenders}; // Spawn multiple senders that will all block (no receiver is consuming) - for (auto i = 0uz; i < kPENDING_NUM_SENDERS; ++i) { + for (auto i = 0uz; i < kPendingNumSenders; ++i) { util::spawn( pool, [senderCopy = sender, i, &completedSends, &semaphore]( @@ -780,7 +780,7 @@ TEST(ChannelTest, PendingAsyncSendsAreCancelledOnClose) pool.join(); // All sends should have completed (returned false due to closed channel) - EXPECT_EQ(completedSends, kPENDING_NUM_SENDERS); + EXPECT_EQ(completedSends, kPendingNumSenders); } INSTANTIATE_CHANNEL_FOR_CLANG(int); diff --git a/tests/unit/util/ConceptsTests.cpp b/tests/unit/util/ConceptsTests.cpp index 7cf032a64..d1b58e4f7 100644 --- a/tests/unit/util/ConceptsTests.cpp +++ b/tests/unit/util/ConceptsTests.cpp @@ -17,15 +17,15 @@ TEST(ConceptTests, hasNoDuplicates) } struct TestA { - static constexpr auto kNAME = "TestA"; + static constexpr auto kName = "TestA"; }; struct AnotherA { - static constexpr auto kNAME = "TestA"; + static constexpr auto kName = "TestA"; }; struct TestB { - static constexpr auto kNAME = "TestB"; + static constexpr auto kName = "TestB"; }; TEST(ConceptTests, hasNoDuplicateNames) diff --git a/tests/unit/util/LedgerUtilsTests.cpp b/tests/unit/util/LedgerUtilsTests.cpp index 42c1cfe5e..7e6938890 100644 --- a/tests/unit/util/LedgerUtilsTests.cpp +++ b/tests/unit/util/LedgerUtilsTests.cpp @@ -13,8 +13,8 @@ TEST(LedgerUtilsTests, LedgerObjectTypeList) { - constexpr auto kTYPES = util::LedgerTypes::getLedgerEntryTypeStrList(); - static constexpr char const* kTYPES_LIST[] = { + constexpr auto kTypes = util::LedgerTypes::getLedgerEntryTypeStrList(); + static constexpr char const* kTypesList[] = { JS(account), JS(amendments), JS(check), @@ -41,144 +41,151 @@ TEST(LedgerUtilsTests, LedgerObjectTypeList) JS(oracle), JS(credential), JS(vault), + JS(loan_broker), + JS(loan), JS(nunl), JS(delegate) }; - static_assert(std::size(kTYPES_LIST) == kTYPES.size()); - static_assert(std::ranges::all_of(kTYPES_LIST, [&kTYPES](std::string_view type) { - return std::ranges::find(kTYPES, type) != std::cend(kTYPES); + static_assert(std::size(kTypesList) == kTypes.size()); + static_assert(std::ranges::all_of(kTypesList, [&kTypes](std::string_view type) { + return std::ranges::find(kTypes, type) != std::cend(kTypes); })); } TEST(LedgerUtilsTests, StrToType) { - EXPECT_EQ(util::LedgerTypes::getLedgerEntryTypeFromStr("mess"), ripple::ltANY); - EXPECT_EQ(util::LedgerTypes::getLedgerEntryTypeFromStr("tomato"), ripple::ltANY); - EXPECT_EQ(util::LedgerTypes::getLedgerEntryTypeFromStr("account"), ripple::ltACCOUNT_ROOT); - EXPECT_EQ(util::LedgerTypes::getLedgerEntryTypeFromStr("AccoUnt"), ripple::ltANY); - EXPECT_EQ(util::LedgerTypes::getLedgerEntryTypeFromStr("AccountRoot"), ripple::ltACCOUNT_ROOT); - EXPECT_EQ(util::LedgerTypes::getLedgerEntryTypeFromStr("ACCOUNTRoot"), ripple::ltACCOUNT_ROOT); + EXPECT_EQ(util::LedgerTypes::getLedgerEntryTypeFromStr("mess"), xrpl::ltANY); + EXPECT_EQ(util::LedgerTypes::getLedgerEntryTypeFromStr("tomato"), xrpl::ltANY); + EXPECT_EQ(util::LedgerTypes::getLedgerEntryTypeFromStr("account"), xrpl::ltACCOUNT_ROOT); + EXPECT_EQ(util::LedgerTypes::getLedgerEntryTypeFromStr("AccoUnt"), xrpl::ltANY); + EXPECT_EQ(util::LedgerTypes::getLedgerEntryTypeFromStr("AccountRoot"), xrpl::ltACCOUNT_ROOT); + EXPECT_EQ(util::LedgerTypes::getLedgerEntryTypeFromStr("ACCOUNTRoot"), xrpl::ltACCOUNT_ROOT); - constexpr auto kTYPES = util::LedgerTypes::getLedgerEntryTypeStrList(); - std::ranges::for_each(kTYPES, [](auto const& typeStr) { - EXPECT_NE(util::LedgerTypes::getLedgerEntryTypeFromStr(typeStr), ripple::ltANY); + constexpr auto kTypes = util::LedgerTypes::getLedgerEntryTypeStrList(); + std::ranges::for_each(kTypes, [](auto const& typeStr) { + EXPECT_NE(util::LedgerTypes::getLedgerEntryTypeFromStr(typeStr), xrpl::ltANY); }); } TEST(LedgerUtilsTests, DeletionBlockerTypes) { - constexpr auto kTESTED_TYPES = util::LedgerTypes::getDeletionBlockerLedgerTypes(); + constexpr auto kTestedTypes = util::LedgerTypes::getDeletionBlockerLedgerTypes(); - static constexpr ripple::LedgerEntryType kDELETION_BLOCKERS[] = { - ripple::ltCHECK, - ripple::ltESCROW, - ripple::ltNFTOKEN_PAGE, - ripple::ltPAYCHAN, - ripple::ltRIPPLE_STATE, - ripple::ltXCHAIN_OWNED_CLAIM_ID, - ripple::ltXCHAIN_OWNED_CREATE_ACCOUNT_CLAIM_ID, - ripple::ltBRIDGE, - ripple::ltMPTOKEN_ISSUANCE, - ripple::ltMPTOKEN, - ripple::ltPERMISSIONED_DOMAIN + static constexpr xrpl::LedgerEntryType kDeletionBlockers[] = { + xrpl::ltCHECK, + xrpl::ltESCROW, + xrpl::ltNFTOKEN_PAGE, + xrpl::ltPAYCHAN, + xrpl::ltRIPPLE_STATE, + xrpl::ltXCHAIN_OWNED_CLAIM_ID, + xrpl::ltXCHAIN_OWNED_CREATE_ACCOUNT_CLAIM_ID, + xrpl::ltBRIDGE, + xrpl::ltMPTOKEN_ISSUANCE, + xrpl::ltMPTOKEN, + xrpl::ltPERMISSIONED_DOMAIN, + xrpl::ltLOAN }; - static_assert(std::size(kDELETION_BLOCKERS) == kTESTED_TYPES.size()); - static_assert(std::ranges::any_of(kTESTED_TYPES, [](auto const& type) { - return std::find(std::cbegin(kDELETION_BLOCKERS), std::cend(kDELETION_BLOCKERS), type) != - std::cend(kDELETION_BLOCKERS); + static_assert(std::size(kDeletionBlockers) == kTestedTypes.size()); + static_assert(std::ranges::any_of(kTestedTypes, [](auto const& type) { + return std::find(std::cbegin(kDeletionBlockers), std::cend(kDeletionBlockers), type) != + std::cend(kDeletionBlockers); })); } struct LedgerEntryTypeParam { std::string input; - ripple::LedgerEntryType expected; + xrpl::LedgerEntryType expected; }; -static LedgerEntryTypeParam const kCHAIN_TEST_CASES[] = { +static LedgerEntryTypeParam const kChainTestCases[] = { // Using RPC name with exact match - {.input = "amendments", .expected = ripple::ltAMENDMENTS}, - {.input = "directory", .expected = ripple::ltDIR_NODE}, - {.input = "fee", .expected = ripple::ltFEE_SETTINGS}, - {.input = "hashes", .expected = ripple::ltLEDGER_HASHES}, - {.input = "nunl", .expected = ripple::ltNEGATIVE_UNL}, + {.input = "amendments", .expected = xrpl::ltAMENDMENTS}, + {.input = "directory", .expected = xrpl::ltDIR_NODE}, + {.input = "fee", .expected = xrpl::ltFEE_SETTINGS}, + {.input = "hashes", .expected = xrpl::ltLEDGER_HASHES}, + {.input = "nunl", .expected = xrpl::ltNEGATIVE_UNL}, // Using canonical name with exact match - {.input = "Amendments", .expected = ripple::ltAMENDMENTS}, - {.input = "DirectoryNode", .expected = ripple::ltDIR_NODE}, - {.input = "FeeSettings", .expected = ripple::ltFEE_SETTINGS}, - {.input = "LedgerHashes", .expected = ripple::ltLEDGER_HASHES}, - {.input = "NegativeUNL", .expected = ripple::ltNEGATIVE_UNL} + {.input = "Amendments", .expected = xrpl::ltAMENDMENTS}, + {.input = "DirectoryNode", .expected = xrpl::ltDIR_NODE}, + {.input = "FeeSettings", .expected = xrpl::ltFEE_SETTINGS}, + {.input = "LedgerHashes", .expected = xrpl::ltLEDGER_HASHES}, + {.input = "NegativeUNL", .expected = xrpl::ltNEGATIVE_UNL} }; -static LedgerEntryTypeParam const kACCOUNT_OWNED_TEST_CASES[] = { +static LedgerEntryTypeParam const kAccountOwnedTestCases[] = { // Using RPC name with exact match - {.input = "account", .expected = ripple::ltACCOUNT_ROOT}, - {.input = "check", .expected = ripple::ltCHECK}, - {.input = "deposit_preauth", .expected = ripple::ltDEPOSIT_PREAUTH}, - {.input = "escrow", .expected = ripple::ltESCROW}, - {.input = "offer", .expected = ripple::ltOFFER}, - {.input = "payment_channel", .expected = ripple::ltPAYCHAN}, - {.input = "signer_list", .expected = ripple::ltSIGNER_LIST}, - {.input = "state", .expected = ripple::ltRIPPLE_STATE}, - {.input = "ticket", .expected = ripple::ltTICKET}, - {.input = "nft_offer", .expected = ripple::ltNFTOKEN_OFFER}, - {.input = "nft_page", .expected = ripple::ltNFTOKEN_PAGE}, - {.input = "amm", .expected = ripple::ltAMM}, - {.input = "bridge", .expected = ripple::ltBRIDGE}, - {.input = "xchain_owned_claim_id", .expected = ripple::ltXCHAIN_OWNED_CLAIM_ID}, + {.input = "account", .expected = xrpl::ltACCOUNT_ROOT}, + {.input = "check", .expected = xrpl::ltCHECK}, + {.input = "deposit_preauth", .expected = xrpl::ltDEPOSIT_PREAUTH}, + {.input = "escrow", .expected = xrpl::ltESCROW}, + {.input = "offer", .expected = xrpl::ltOFFER}, + {.input = "payment_channel", .expected = xrpl::ltPAYCHAN}, + {.input = "signer_list", .expected = xrpl::ltSIGNER_LIST}, + {.input = "state", .expected = xrpl::ltRIPPLE_STATE}, + {.input = "ticket", .expected = xrpl::ltTICKET}, + {.input = "nft_offer", .expected = xrpl::ltNFTOKEN_OFFER}, + {.input = "nft_page", .expected = xrpl::ltNFTOKEN_PAGE}, + {.input = "amm", .expected = xrpl::ltAMM}, + {.input = "bridge", .expected = xrpl::ltBRIDGE}, + {.input = "xchain_owned_claim_id", .expected = xrpl::ltXCHAIN_OWNED_CLAIM_ID}, {.input = "xchain_owned_create_account_claim_id", - .expected = ripple::ltXCHAIN_OWNED_CREATE_ACCOUNT_CLAIM_ID}, - {.input = "did", .expected = ripple::ltDID}, - {.input = "oracle", .expected = ripple::ltORACLE}, - {.input = "credential", .expected = ripple::ltCREDENTIAL}, - {.input = "mpt_issuance", .expected = ripple::ltMPTOKEN_ISSUANCE}, - {.input = "mptoken", .expected = ripple::ltMPTOKEN}, - {.input = "permissioned_domain", .expected = ripple::ltPERMISSIONED_DOMAIN}, - {.input = "vault", .expected = ripple::ltVAULT}, - {.input = "delegate", .expected = ripple::ltDELEGATE}, + .expected = xrpl::ltXCHAIN_OWNED_CREATE_ACCOUNT_CLAIM_ID}, + {.input = "did", .expected = xrpl::ltDID}, + {.input = "oracle", .expected = xrpl::ltORACLE}, + {.input = "credential", .expected = xrpl::ltCREDENTIAL}, + {.input = "mpt_issuance", .expected = xrpl::ltMPTOKEN_ISSUANCE}, + {.input = "mptoken", .expected = xrpl::ltMPTOKEN}, + {.input = "permissioned_domain", .expected = xrpl::ltPERMISSIONED_DOMAIN}, + {.input = "vault", .expected = xrpl::ltVAULT}, + {.input = "loan_broker", .expected = xrpl::ltLOAN_BROKER}, + {.input = "loan", .expected = xrpl::ltLOAN}, + {.input = "delegate", .expected = xrpl::ltDELEGATE}, // Using canonical name with exact match - {.input = "AccountRoot", .expected = ripple::ltACCOUNT_ROOT}, - {.input = "Check", .expected = ripple::ltCHECK}, - {.input = "DepositPreauth", .expected = ripple::ltDEPOSIT_PREAUTH}, - {.input = "Escrow", .expected = ripple::ltESCROW}, - {.input = "Offer", .expected = ripple::ltOFFER}, - {.input = "PayChannel", .expected = ripple::ltPAYCHAN}, - {.input = "SignerList", .expected = ripple::ltSIGNER_LIST}, - {.input = "RippleState", .expected = ripple::ltRIPPLE_STATE}, - {.input = "Ticket", .expected = ripple::ltTICKET}, - {.input = "NFTokenOffer", .expected = ripple::ltNFTOKEN_OFFER}, - {.input = "NFTokenPage", .expected = ripple::ltNFTOKEN_PAGE}, - {.input = "AMM", .expected = ripple::ltAMM}, - {.input = "Bridge", .expected = ripple::ltBRIDGE}, - {.input = "XChainOwnedClaimID", .expected = ripple::ltXCHAIN_OWNED_CLAIM_ID}, + {.input = "AccountRoot", .expected = xrpl::ltACCOUNT_ROOT}, + {.input = "Check", .expected = xrpl::ltCHECK}, + {.input = "DepositPreauth", .expected = xrpl::ltDEPOSIT_PREAUTH}, + {.input = "Escrow", .expected = xrpl::ltESCROW}, + {.input = "Offer", .expected = xrpl::ltOFFER}, + {.input = "PayChannel", .expected = xrpl::ltPAYCHAN}, + {.input = "SignerList", .expected = xrpl::ltSIGNER_LIST}, + {.input = "RippleState", .expected = xrpl::ltRIPPLE_STATE}, + {.input = "Ticket", .expected = xrpl::ltTICKET}, + {.input = "NFTokenOffer", .expected = xrpl::ltNFTOKEN_OFFER}, + {.input = "NFTokenPage", .expected = xrpl::ltNFTOKEN_PAGE}, + {.input = "AMM", .expected = xrpl::ltAMM}, + {.input = "Bridge", .expected = xrpl::ltBRIDGE}, + {.input = "XChainOwnedClaimID", .expected = xrpl::ltXCHAIN_OWNED_CLAIM_ID}, {.input = "XChainOwnedCreateAccountClaimID", - .expected = ripple::ltXCHAIN_OWNED_CREATE_ACCOUNT_CLAIM_ID}, - {.input = "DID", .expected = ripple::ltDID}, - {.input = "Oracle", .expected = ripple::ltORACLE}, - {.input = "Credential", .expected = ripple::ltCREDENTIAL}, - {.input = "MPTokenIssuance", .expected = ripple::ltMPTOKEN_ISSUANCE}, - {.input = "MPToken", .expected = ripple::ltMPTOKEN}, - {.input = "PermissionedDomain", .expected = ripple::ltPERMISSIONED_DOMAIN}, - {.input = "Vault", .expected = ripple::ltVAULT}, - {.input = "Delegate", .expected = ripple::ltDELEGATE} + .expected = xrpl::ltXCHAIN_OWNED_CREATE_ACCOUNT_CLAIM_ID}, + {.input = "DID", .expected = xrpl::ltDID}, + {.input = "Oracle", .expected = xrpl::ltORACLE}, + {.input = "Credential", .expected = xrpl::ltCREDENTIAL}, + {.input = "MPTokenIssuance", .expected = xrpl::ltMPTOKEN_ISSUANCE}, + {.input = "MPToken", .expected = xrpl::ltMPTOKEN}, + {.input = "PermissionedDomain", .expected = xrpl::ltPERMISSIONED_DOMAIN}, + {.input = "Vault", .expected = xrpl::ltVAULT}, + {.input = "LoanBroker", .expected = xrpl::ltLOAN_BROKER}, + {.input = "Loan", .expected = xrpl::ltLOAN}, + {.input = "Delegate", .expected = xrpl::ltDELEGATE} }; -static LedgerEntryTypeParam const kCASE_INSENSITIVE_TEST_CASES[] = { +static LedgerEntryTypeParam const kCaseInsensitiveTestCases[] = { // With canonical name in mixedcase - {.input = "mPtOKenIssuance", .expected = ripple::ltMPTOKEN_ISSUANCE}, + {.input = "mPtOKenIssuance", .expected = xrpl::ltMPTOKEN_ISSUANCE}, // With canonical name in lowercase - {.input = "mptokenissuance", .expected = ripple::ltMPTOKEN_ISSUANCE}, + {.input = "mptokenissuance", .expected = xrpl::ltMPTOKEN_ISSUANCE}, }; -static LedgerEntryTypeParam const kINVALID_TEST_CASES[] = { - {.input = "", .expected = ripple::ltANY}, - {.input = "1234", .expected = ripple::ltANY}, - {.input = "unknown", .expected = ripple::ltANY}, +static LedgerEntryTypeParam const kInvalidTestCases[] = { + {.input = "", .expected = xrpl::ltANY}, + {.input = "1234", .expected = xrpl::ltANY}, + {.input = "unknown", .expected = xrpl::ltANY}, // With RPC name with inexact match - {.input = "MPT_Issuance", .expected = ripple::ltANY} + {.input = "MPT_Issuance", .expected = xrpl::ltANY} }; class LedgerEntryTypeFromStrTest : public ::testing::TestWithParam {}; @@ -195,16 +202,12 @@ INSTANTIATE_TEST_SUITE_P( LedgerEntryTypeFromStrTest, ::testing::ValuesIn([]() { std::vector v; - v.insert(v.end(), std::begin(kCHAIN_TEST_CASES), std::end(kCHAIN_TEST_CASES)); + v.insert(v.end(), std::begin(kChainTestCases), std::end(kChainTestCases)); + v.insert(v.end(), std::begin(kAccountOwnedTestCases), std::end(kAccountOwnedTestCases)); v.insert( - v.end(), std::begin(kACCOUNT_OWNED_TEST_CASES), std::end(kACCOUNT_OWNED_TEST_CASES) + v.end(), std::begin(kCaseInsensitiveTestCases), std::end(kCaseInsensitiveTestCases) ); - v.insert( - v.end(), - std::begin(kCASE_INSENSITIVE_TEST_CASES), - std::end(kCASE_INSENSITIVE_TEST_CASES) - ); - v.insert(v.end(), std::begin(kINVALID_TEST_CASES), std::end(kINVALID_TEST_CASES)); + v.insert(v.end(), std::begin(kInvalidTestCases), std::end(kInvalidTestCases)); return v; }()) ); @@ -223,16 +226,12 @@ INSTANTIATE_TEST_SUITE_P( AccountOwnedLedgerTypeFromStrTest, ::testing::ValuesIn([]() { std::vector v; + v.insert(v.end(), std::begin(kAccountOwnedTestCases), std::end(kAccountOwnedTestCases)); v.insert( - v.end(), std::begin(kACCOUNT_OWNED_TEST_CASES), std::end(kACCOUNT_OWNED_TEST_CASES) + v.end(), std::begin(kCaseInsensitiveTestCases), std::end(kCaseInsensitiveTestCases) ); - v.insert( - v.end(), - std::begin(kCASE_INSENSITIVE_TEST_CASES), - std::end(kCASE_INSENSITIVE_TEST_CASES) - ); - v.insert(v.end(), std::begin(kINVALID_TEST_CASES), std::end(kINVALID_TEST_CASES)); - v.push_back({"amendments", ripple::ltANY}); // chain type should return ltANY + v.insert(v.end(), std::begin(kInvalidTestCases), std::end(kInvalidTestCases)); + v.push_back({"amendments", xrpl::ltANY}); // chain type should return ltANY return v; }()) ); diff --git a/tests/unit/util/ObservableValueAtomicTest.cpp b/tests/unit/util/ObservableValueAtomicTest.cpp index 4837fb4ae..05cf9a5a0 100644 --- a/tests/unit/util/ObservableValueAtomicTest.cpp +++ b/tests/unit/util/ObservableValueAtomicTest.cpp @@ -157,15 +157,15 @@ TEST_F(ObservableValueAtomicTest, ThreadSafetyBasic) values.push_back(value); }); - static constexpr auto kNUM_THREADS = 4; - static constexpr auto kINCREMENTS_PER_THREAD = 100; + static constexpr auto kNumThreads = 4; + static constexpr auto kIncrementsPerThread = 100; std::vector threads; - threads.reserve(kNUM_THREADS); + threads.reserve(kNumThreads); - for (int i = 0; i < kNUM_THREADS; ++i) { + for (int i = 0; i < kNumThreads; ++i) { threads.emplace_back([&obs]() { - for (int j = 0; j < kINCREMENTS_PER_THREAD; ++j) { + for (int j = 0; j < kIncrementsPerThread; ++j) { int const expected = obs.get(); int const newValue = expected + 1; obs.set(newValue); @@ -194,15 +194,15 @@ TEST_F(ObservableValueAtomicTest, ThreadSafetyWithDirectAccess) auto connection = obs.observe([&](int const&) { notificationCount.fetch_add(1); }); - static constexpr auto kNUM_THREADS = 4; - static constexpr auto kOPERATIONS_PER_THREAD = 50; + static constexpr auto kNumThreads = 4; + static constexpr auto kOperationsPerThread = 50; std::vector threads; - threads.reserve(kNUM_THREADS); + threads.reserve(kNumThreads); - for (int i = 0; i < kNUM_THREADS; ++i) { + for (int i = 0; i < kNumThreads; ++i) { threads.emplace_back([&obs]() { - for (int j = 0; j < kOPERATIONS_PER_THREAD; ++j) { + for (int j = 0; j < kOperationsPerThread; ++j) { int const current = obs.get(); obs.set(current + 1); std::this_thread::sleep_for(std::chrono::microseconds(1)); @@ -262,15 +262,15 @@ TEST_F(ObservableValueAtomicTest, RaceConditionNotificationIntegrity) values.push_back(value); }); - static constexpr auto kNUM_THREADS = 10; - static constexpr auto kOPERATIONS_PER_THREAD = 20; + static constexpr auto kNumThreads = 10; + static constexpr auto kOperationsPerThread = 20; std::vector threads; - threads.reserve(kNUM_THREADS); + threads.reserve(kNumThreads); - for (int i = 0; i < kNUM_THREADS; ++i) { + for (int i = 0; i < kNumThreads; ++i) { threads.emplace_back([&obs]() { - for (int j = 0; j < kOPERATIONS_PER_THREAD; ++j) { + for (int j = 0; j < kOperationsPerThread; ++j) { obs.set(j % 3); std::this_thread::sleep_for(std::chrono::microseconds(1)); } @@ -306,12 +306,12 @@ TEST_F(ObservableValueAtomicTest, DeterministicNotificationTest) values.push_back(value); }); - static constexpr auto kNUM_THREADS = 5; + static constexpr auto kNumThreads = 5; std::vector threads; - threads.reserve(kNUM_THREADS); + threads.reserve(kNumThreads); - for (int i = 0; i < kNUM_THREADS; ++i) { + for (int i = 0; i < kNumThreads; ++i) { threads.emplace_back([&obs, i]() { obs.set(i + 1); }); } @@ -319,19 +319,19 @@ TEST_F(ObservableValueAtomicTest, DeterministicNotificationTest) thread.join(); // Each thread sets a unique value, so expect exactly kNumThreads notifications - EXPECT_EQ(notificationCount.load(), kNUM_THREADS); + EXPECT_EQ(notificationCount.load(), kNumThreads); std::scoped_lock const lock(valuesMutex); - EXPECT_EQ(values.size(), kNUM_THREADS); + EXPECT_EQ(values.size(), kNumThreads); for (auto const& value : values) { EXPECT_GE(value, 1); - EXPECT_LE(value, kNUM_THREADS); + EXPECT_LE(value, kNumThreads); } int const finalValue = obs.get(); EXPECT_GE(finalValue, 1); - EXPECT_LE(finalValue, kNUM_THREADS); + EXPECT_LE(finalValue, kNumThreads); } TEST_F(ObservableValueAtomicTest, NoNotificationForSameValue) @@ -341,12 +341,12 @@ TEST_F(ObservableValueAtomicTest, NoNotificationForSameValue) auto connection = obs.observe([&](int const&) { notificationCount.fetch_add(1); }); - static constexpr auto kNUM_THREADS = 10; + static constexpr auto kNumThreads = 10; std::vector threads; - threads.reserve(kNUM_THREADS); + threads.reserve(kNumThreads); - for (int i = 0; i < kNUM_THREADS; ++i) { + for (int i = 0; i < kNumThreads; ++i) { threads.emplace_back([&obs]() { obs.set(42); }); } @@ -370,14 +370,14 @@ TEST_F(ObservableValueAtomicTest, AtomicRaceConditionCorrectness) values.push_back(value); }); - static constexpr auto kNUM_THREADS = 3; + static constexpr auto kNumThreads = 3; std::vector threads; - threads.reserve(kNUM_THREADS); + threads.reserve(kNumThreads); // Test that direct access properly notifies for all value changes // Each thread will make unique changes to avoid race condition conflicts - for (int i = 0; i < kNUM_THREADS; ++i) { + for (int i = 0; i < kNumThreads; ++i) { threads.emplace_back([&obs, i]() { int const baseValue = (i + 1) * 10; // 10, 20, 30 obs.set(baseValue); // Store unique values @@ -390,10 +390,10 @@ TEST_F(ObservableValueAtomicTest, AtomicRaceConditionCorrectness) // We should get some notifications (exact count depends on race conditions) // but at least one per thread since they use unique base values - EXPECT_GE(notificationCount.load(), kNUM_THREADS); + EXPECT_GE(notificationCount.load(), kNumThreads); std::scoped_lock const lock(valuesMutex); - EXPECT_GE(values.size(), kNUM_THREADS); + EXPECT_GE(values.size(), kNumThreads); for (auto const& value : values) EXPECT_GT(value, 0); diff --git a/tests/unit/util/ObservableValueTest.cpp b/tests/unit/util/ObservableValueTest.cpp index d8f3eccd2..22d3dc2fb 100644 --- a/tests/unit/util/ObservableValueTest.cpp +++ b/tests/unit/util/ObservableValueTest.cpp @@ -531,8 +531,8 @@ TEST_F(ObservableValueTest, ManyObservers) mockObservers; std::vector connections; - constexpr int kNUM_OBSERVERS = 100; - for (int i = 0; i < kNUM_OBSERVERS; ++i) { + constexpr int kNumObservers = 100; + for (int i = 0; i < kNumObservers; ++i) { mockObservers.push_back( std::make_unique>>() ); diff --git a/tests/unit/util/ResponseExpirationCacheTests.cpp b/tests/unit/util/ResponseExpirationCacheTests.cpp index 23a187574..9ba3fbdd6 100644 --- a/tests/unit/util/ResponseExpirationCacheTests.cpp +++ b/tests/unit/util/ResponseExpirationCacheTests.cpp @@ -11,40 +11,104 @@ using namespace util; struct ResponseExpirationCacheTests : public ::testing::Test { protected: ResponseExpirationCache cache_{std::chrono::seconds{100}, {"key"}}; + boost::json::object bareRequest_{{"command", "key"}}; boost::json::object object_{{"key", "value"}}; }; TEST_F(ResponseExpirationCacheTests, PutAndGetNotExpired) { - EXPECT_FALSE(cache_.get("key").has_value()); + EXPECT_FALSE(cache_.get("key", bareRequest_).has_value()); - cache_.put("key", object_); - auto result = cache_.get("key"); + cache_.put("key", bareRequest_, object_); + auto result = cache_.get("key", bareRequest_); ASSERT_TRUE(result.has_value()); EXPECT_EQ(*result, object_); // NOLINT(bugprone-unchecked-optional-access) - result = cache_.get("key2"); + result = cache_.get("key2", bareRequest_); ASSERT_FALSE(result.has_value()); - cache_.put("key2", object_); - result = cache_.get("key2"); + cache_.put("key2", bareRequest_, object_); + result = cache_.get("key2", bareRequest_); ASSERT_FALSE(result.has_value()); } TEST_F(ResponseExpirationCacheTests, Invalidate) { - cache_.put("key", object_); + cache_.put("key", bareRequest_, object_); cache_.invalidate(); - EXPECT_FALSE(cache_.get("key").has_value()); + EXPECT_FALSE(cache_.get("key", bareRequest_).has_value()); } TEST_F(ResponseExpirationCacheTests, GetExpired) { ResponseExpirationCache cache{std::chrono::milliseconds{1}, {"key"}}; auto const response = boost::json::object{{"key", "value"}}; + auto const req = boost::json::object{{"command", "key"}}; - cache.put("key", response); + cache.put("key", req, response); std::this_thread::sleep_for(std::chrono::milliseconds{2}); - auto const result = cache.get("key"); + auto const result = cache.get("key", req); EXPECT_FALSE(result); } + +TEST_F(ResponseExpirationCacheTests, BareRequestCommandOnlyIsCached) +{ + boost::json::object const req{{"command", "key"}}; + cache_.put("key", req, object_); + auto const result = cache_.get("key", req); + ASSERT_TRUE(result.has_value()); + EXPECT_EQ(*result, object_); // NOLINT(bugprone-unchecked-optional-access) +} + +TEST_F(ResponseExpirationCacheTests, BareRequestWithIdIsCached) +{ + boost::json::object const req{{"command", "key"}, {"id", 42}}; + cache_.put("key", req, object_); + auto const result = cache_.get("key", req); + ASSERT_TRUE(result.has_value()); + EXPECT_EQ(*result, object_); // NOLINT(bugprone-unchecked-optional-access) +} + +TEST_F(ResponseExpirationCacheTests, BareRequestMethodAndIdIsCached) +{ + boost::json::object const req{{"method", "key"}, {"id", "req-1"}}; + cache_.put("key", req, object_); + auto const result = cache_.get("key", req); + ASSERT_TRUE(result.has_value()); + EXPECT_EQ(*result, object_); // NOLINT(bugprone-unchecked-optional-access) +} + +TEST_F(ResponseExpirationCacheTests, NonBareGetReturnNulloptAfterBarePut) +{ + boost::json::object const bareReq{{"command", "key"}}; + boost::json::object const nonBareReq{{"command", "key"}, {"limit", 50}}; + + cache_.put("key", bareReq, object_); + ASSERT_TRUE(cache_.get("key", bareReq).has_value()); + EXPECT_FALSE(cache_.get("key", nonBareReq).has_value()); +} + +TEST_F(ResponseExpirationCacheTests, NonBarePutDoesNotStore) +{ + boost::json::object const nonBareReq{{"command", "key"}, {"limit", 50}}; + boost::json::object const bareReq{{"command", "key"}}; + + cache_.put("key", nonBareReq, object_); + EXPECT_FALSE(cache_.get("key", bareReq).has_value()); +} + +TEST_F(ResponseExpirationCacheTests, ApiVersionMakesRequestNonBare) +{ + boost::json::object const req{{"command", "key"}, {"api_version", 1}}; + cache_.put("key", req, object_); + EXPECT_FALSE(cache_.get("key", req).has_value()); +} + +TEST_F(ResponseExpirationCacheTests, BareRequestIdOnlyIsCached) +{ + boost::json::object const req{{"id", 7}}; + cache_.put("key", req, object_); + auto const result = cache_.get("key", req); + ASSERT_TRUE(result.has_value()); + EXPECT_EQ(*result, object_); // NOLINT(bugprone-unchecked-optional-access) +} diff --git a/tests/unit/util/ShasumTests.cpp b/tests/unit/util/ShasumTests.cpp index deadc655e..f32d05493 100644 --- a/tests/unit/util/ShasumTests.cpp +++ b/tests/unit/util/ShasumTests.cpp @@ -10,27 +10,27 @@ using namespace util; struct ShasumTest : testing::Test { - static constexpr auto kEMPTY_HASH = + static constexpr auto kEmptyHash = "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855"; - static constexpr auto kHELLO_WORLD_HASH = + static constexpr auto kHelloWorldHash = "B94D27B9934D3E08A52E52D7DA7DABFAC484EFE37A5380EE9088F7ACE2EFCDE9"; }; TEST_F(ShasumTest, sha256sum) { - ripple::uint256 expected; + xrpl::uint256 expected; - ASSERT_TRUE(expected.parseHex(kEMPTY_HASH)); + ASSERT_TRUE(expected.parseHex(kEmptyHash)); EXPECT_EQ(sha256sum(""), expected); - ASSERT_TRUE(expected.parseHex(kHELLO_WORLD_HASH)); + ASSERT_TRUE(expected.parseHex(kHelloWorldHash)); EXPECT_EQ(sha256sum("hello world"), expected); } TEST_F(ShasumTest, sha256sumString) { - EXPECT_EQ(sha256sumString(""), kEMPTY_HASH); - EXPECT_EQ(sha256sumString("hello world"), kHELLO_WORLD_HASH); + EXPECT_EQ(sha256sumString(""), kEmptyHash); + EXPECT_EQ(sha256sumString("hello world"), kHelloWorldHash); } TEST_F(ShasumTest, Sha256sumStreamingEmpty) @@ -38,8 +38,8 @@ TEST_F(ShasumTest, Sha256sumStreamingEmpty) Sha256sum hasher; auto result = std::move(hasher).finalize(); - ripple::uint256 expected; - ASSERT_TRUE(expected.parseHex(kEMPTY_HASH)); + xrpl::uint256 expected; + ASSERT_TRUE(expected.parseHex(kEmptyHash)); EXPECT_EQ(result, expected); } @@ -50,8 +50,8 @@ TEST_F(ShasumTest, Sha256sumStreamingSingleUpdate) hasher.update(data.data(), data.size()); auto result = std::move(hasher).finalize(); - ripple::uint256 expected; - ASSERT_TRUE(expected.parseHex(kHELLO_WORLD_HASH)); + xrpl::uint256 expected; + ASSERT_TRUE(expected.parseHex(kHelloWorldHash)); EXPECT_EQ(result, expected); } @@ -63,8 +63,8 @@ TEST_F(ShasumTest, Sha256sumStreamingMultipleUpdates) hasher.update("world", 5); auto result = std::move(hasher).finalize(); - ripple::uint256 expected; - ASSERT_TRUE(expected.parseHex(kHELLO_WORLD_HASH)); + xrpl::uint256 expected; + ASSERT_TRUE(expected.parseHex(kHelloWorldHash)); EXPECT_EQ(result, expected); } diff --git a/tests/unit/util/TimeUtilsTests.cpp b/tests/unit/util/TimeUtilsTests.cpp index 18b65cf7c..a36e2504d 100644 --- a/tests/unit/util/TimeUtilsTests.cpp +++ b/tests/unit/util/TimeUtilsTests.cpp @@ -76,6 +76,6 @@ TEST(TimeUtilTests, SystemTpFromLedgerCloseTime) { using namespace std::chrono; - auto const tp = util::systemTpFromLedgerCloseTime(ripple::NetClock::time_point{seconds{0}}); - EXPECT_EQ(tp.time_since_epoch(), ripple::epoch_offset); + auto const tp = util::systemTpFromLedgerCloseTime(xrpl::NetClock::time_point{seconds{0}}); + EXPECT_EQ(tp.time_since_epoch(), xrpl::kEpochOffset); } diff --git a/tests/unit/util/TxUtilTests.cpp b/tests/unit/util/TxUtilTests.cpp index aea48de00..6dc976cee 100644 --- a/tests/unit/util/TxUtilTests.cpp +++ b/tests/unit/util/TxUtilTests.cpp @@ -14,14 +14,14 @@ TEST(TxUtilTests, txTypesInLowercase) ASSERT_TRUE( std::size_t( std::distance( - ripple::TxFormats::getInstance().begin(), ripple::TxFormats::getInstance().end() + xrpl::TxFormats::getInstance().begin(), xrpl::TxFormats::getInstance().end() ) ) == types.size() ); std::for_each( - ripple::TxFormats::getInstance().begin(), - ripple::TxFormats::getInstance().end(), + xrpl::TxFormats::getInstance().begin(), + xrpl::TxFormats::getInstance().end(), [&](auto const& pair) { EXPECT_TRUE(types.find(util::toLower(pair.getName())) != types.end()); } diff --git a/tests/unit/util/async/AnyExecutionContextTests.cpp b/tests/unit/util/async/AnyExecutionContextTests.cpp index da28002f9..704390c15 100644 --- a/tests/unit/util/async/AnyExecutionContextTests.cpp +++ b/tests/unit/util/async/AnyExecutionContextTests.cpp @@ -10,6 +10,7 @@ #include "util/async/Outcome.hpp" #include "util/async/context/SyncExecutionContext.hpp" #include "util/async/context/impl/Cancellation.hpp" +#include "util/async/impl/Any.hpp" #include "util/async/impl/ErasedOperation.hpp" #include @@ -105,8 +106,8 @@ struct AnyExecutionContextTests : Test { TEST_F(AnyExecutionContextTests, Move) { - auto mockOp = OperationType{}; - EXPECT_CALL(mockExecutionContext, execute(A>())) + auto mockOp = OperationType{}; + EXPECT_CALL(mockExecutionContext, execute(A>())) .WillOnce(ReturnRef(mockOp)); EXPECT_CALL(mockOp, get()); @@ -116,8 +117,8 @@ TEST_F(AnyExecutionContextTests, Move) TEST_F(AnyExecutionContextTests, CopyIsRefCounted) { - auto mockOp = OperationType{}; - EXPECT_CALL(mockExecutionContext, execute(A>())) + auto mockOp = OperationType{}; + EXPECT_CALL(mockExecutionContext, execute(A>())) .WillOnce(ReturnRef(mockOp)); EXPECT_CALL(mockOp, get()); @@ -127,8 +128,8 @@ TEST_F(AnyExecutionContextTests, CopyIsRefCounted) TEST_F(AnyExecutionContextTests, ExecuteWithoutTokenAndVoid) { - auto mockOp = OperationType{}; - EXPECT_CALL(mockExecutionContext, execute(A>())) + auto mockOp = OperationType{}; + EXPECT_CALL(mockExecutionContext, execute(A>())) .WillOnce(ReturnRef(mockOp)); EXPECT_CALL(mockOp, get()); @@ -140,17 +141,17 @@ TEST_F(AnyExecutionContextTests, ExecuteWithoutTokenAndVoid) TEST_F(AnyExecutionContextTests, ExecuteWithoutTokenAndVoidThrowsException) { - auto mockOp = OperationType{}; - EXPECT_CALL(mockExecutionContext, execute(A>())) - .WillOnce([](auto&&) -> OperationType const& { throw 0; }); + auto mockOp = OperationType{}; + EXPECT_CALL(mockExecutionContext, execute(A>())) + .WillOnce([](auto&&) -> OperationType const& { throw 0; }); EXPECT_ANY_THROW([[maybe_unused]] auto unused = ctx.execute([] { throw 0; })); } TEST_F(AnyExecutionContextTests, ExecuteWithStopTokenAndVoid) { - auto mockOp = StoppableOperationType{}; - EXPECT_CALL(mockExecutionContext, execute(A>(), _)) + auto mockOp = StoppableOperationType{}; + EXPECT_CALL(mockExecutionContext, execute(A>(), _)) .WillOnce(ReturnRef(mockOp)); EXPECT_CALL(mockOp, get()); @@ -162,17 +163,17 @@ TEST_F(AnyExecutionContextTests, ExecuteWithStopTokenAndVoid) TEST_F(AnyExecutionContextTests, ExecuteWithStopTokenAndVoidThrowsException) { - EXPECT_CALL(mockExecutionContext, execute(A>(), _)) - .WillOnce([](auto&&, auto) -> StoppableOperationType const& { throw 0; }); + EXPECT_CALL(mockExecutionContext, execute(A>(), _)) + .WillOnce([](auto&&, auto) -> StoppableOperationType const& { throw 0; }); EXPECT_ANY_THROW([[maybe_unused]] auto unused = ctx.execute([](auto) { throw 0; })); } TEST_F(AnyExecutionContextTests, ExecuteWithStopTokenAndReturnValue) { - auto mockOp = StoppableOperationType{}; + auto mockOp = StoppableOperationType{}; EXPECT_CALL(mockOp, get()).WillOnce(Return(std::make_any(42))); - EXPECT_CALL(mockExecutionContext, execute(A>(), _)) + EXPECT_CALL(mockExecutionContext, execute(A>(), _)) .WillOnce(ReturnRef(mockOp)); auto op = ctx.execute([](auto) -> int { throw 0; }); @@ -183,19 +184,19 @@ TEST_F(AnyExecutionContextTests, ExecuteWithStopTokenAndReturnValue) TEST_F(AnyExecutionContextTests, ExecuteWithStopTokenAndReturnValueThrowsException) { - EXPECT_CALL(mockExecutionContext, execute(A>(), _)) - .WillOnce([](auto&&, auto) -> StoppableOperationType const& { throw 0; }); + EXPECT_CALL(mockExecutionContext, execute(A>(), _)) + .WillOnce([](auto&&, auto) -> StoppableOperationType const& { throw 0; }); EXPECT_ANY_THROW([[maybe_unused]] auto unused = ctx.execute([](auto) -> int { throw 0; })); } TEST_F(AnyExecutionContextTests, TimerCancellation) { - auto mockScheduledOp = ScheduledOperationType{}; + auto mockScheduledOp = ScheduledOperationType{}; EXPECT_CALL(mockScheduledOp, cancel()); EXPECT_CALL( mockExecutionContext, - scheduleAfter(std::chrono::milliseconds{12}, A>()) + scheduleAfter(std::chrono::milliseconds{12}, A>()) ) .WillOnce(ReturnRef(mockScheduledOp)); @@ -207,13 +208,13 @@ TEST_F(AnyExecutionContextTests, TimerCancellation) TEST_F(AnyExecutionContextTests, TimerExecuted) { - auto mockScheduledOp = ScheduledOperationType{}; + auto mockScheduledOp = ScheduledOperationType{}; EXPECT_CALL(mockScheduledOp, get()).WillOnce(Return(std::make_any(42))); EXPECT_CALL( mockExecutionContext, - scheduleAfter(std::chrono::milliseconds{12}, A>()) + scheduleAfter(std::chrono::milliseconds{12}, A>()) ) - .WillOnce([&mockScheduledOp](auto, auto&&) -> ScheduledOperationType const& { + .WillOnce([&mockScheduledOp](auto, auto&&) -> ScheduledOperationType const& { return mockScheduledOp; }); @@ -225,12 +226,12 @@ TEST_F(AnyExecutionContextTests, TimerExecuted) TEST_F(AnyExecutionContextTests, TimerWithBoolHandlerCancellation) { - auto mockScheduledOp = ScheduledOperationType{}; + auto mockScheduledOp = ScheduledOperationType{}; EXPECT_CALL(mockScheduledOp, cancel()); EXPECT_CALL( mockExecutionContext, scheduleAfter( - std::chrono::milliseconds{12}, A>() + std::chrono::milliseconds{12}, A>() ) ) .WillOnce(ReturnRef(mockScheduledOp)); @@ -243,15 +244,15 @@ TEST_F(AnyExecutionContextTests, TimerWithBoolHandlerCancellation) TEST_F(AnyExecutionContextTests, TimerWithBoolHandlerExecuted) { - auto mockScheduledOp = ScheduledOperationType{}; + auto mockScheduledOp = ScheduledOperationType{}; EXPECT_CALL(mockScheduledOp, get()).WillOnce(Return(std::make_any(42))); EXPECT_CALL( mockExecutionContext, scheduleAfter( - std::chrono::milliseconds{12}, A>() + std::chrono::milliseconds{12}, A>() ) ) - .WillOnce([&mockScheduledOp](auto, auto&&) -> ScheduledOperationType const& { + .WillOnce([&mockScheduledOp](auto, auto&&) -> ScheduledOperationType const& { return mockScheduledOp; }); @@ -264,13 +265,13 @@ TEST_F(AnyExecutionContextTests, TimerWithBoolHandlerExecuted) TEST_F(AnyExecutionContextTests, RepeatingOperation) { - auto mockRepeatingOp = RepeatingOperationType{}; + auto mockRepeatingOp = RepeatingOperationType{}; EXPECT_CALL(mockRepeatingOp, wait()); EXPECT_CALL( mockExecutionContext, - executeRepeatedly(std::chrono::milliseconds{1}, A>()) + executeRepeatedly(std::chrono::milliseconds{1}, A>()) ) - .WillOnce([&mockRepeatingOp] -> RepeatingOperationType const& { + .WillOnce([&mockRepeatingOp] -> RepeatingOperationType const& { return mockRepeatingOp; }); @@ -281,11 +282,11 @@ TEST_F(AnyExecutionContextTests, RepeatingOperation) TEST_F(AnyExecutionContextTests, StrandExecuteWithVoid) { - auto mockOp = OperationType{}; + auto mockOp = OperationType{}; auto mockStrand = StrandType{}; EXPECT_CALL(mockOp, get()); EXPECT_CALL(mockExecutionContext, makeStrand()).WillOnce(ReturnRef(mockStrand)); - EXPECT_CALL(mockStrand, execute(A>())).WillOnce(ReturnRef(mockOp)); + EXPECT_CALL(mockStrand, execute(A>())).WillOnce(ReturnRef(mockOp)); auto strand = ctx.makeStrand(); static_assert(std::is_same_v); @@ -300,8 +301,8 @@ TEST_F(AnyExecutionContextTests, StrandExecuteWithVoidThrowsException) { auto mockStrand = StrandType{}; EXPECT_CALL(mockExecutionContext, makeStrand()).WillOnce(ReturnRef(mockStrand)); - EXPECT_CALL(mockStrand, execute(A>())) - .WillOnce([](auto&&) -> OperationType const& { throw 0; }); + EXPECT_CALL(mockStrand, execute(A>())) + .WillOnce([](auto&&) -> OperationType const& { throw 0; }); auto strand = ctx.makeStrand(); static_assert(std::is_same_v); @@ -311,11 +312,11 @@ TEST_F(AnyExecutionContextTests, StrandExecuteWithVoidThrowsException) TEST_F(AnyExecutionContextTests, StrandExecuteWithReturnValue) { - auto mockOp = OperationType{}; + auto mockOp = OperationType{}; auto mockStrand = StrandType{}; EXPECT_CALL(mockOp, get()).WillOnce(Return(std::make_any(42))); EXPECT_CALL(mockExecutionContext, makeStrand()).WillOnce(ReturnRef(mockStrand)); - EXPECT_CALL(mockStrand, execute(A>())).WillOnce(ReturnRef(mockOp)); + EXPECT_CALL(mockStrand, execute(A>())).WillOnce(ReturnRef(mockOp)); auto strand = ctx.makeStrand(); static_assert(std::is_same_v); @@ -330,8 +331,8 @@ TEST_F(AnyExecutionContextTests, StrandExecuteWithReturnValueThrowsException) { auto mockStrand = StrandType{}; EXPECT_CALL(mockExecutionContext, makeStrand()).WillOnce(ReturnRef(mockStrand)); - EXPECT_CALL(mockStrand, execute(A>())) - .WillOnce([](auto&&) -> OperationType const& { throw 0; }); + EXPECT_CALL(mockStrand, execute(A>())) + .WillOnce([](auto&&) -> OperationType const& { throw 0; }); auto strand = ctx.makeStrand(); static_assert(std::is_same_v); @@ -341,11 +342,11 @@ TEST_F(AnyExecutionContextTests, StrandExecuteWithReturnValueThrowsException) TEST_F(AnyExecutionContextTests, StrandExecuteWithStopTokenAndVoid) { - auto mockOp = StoppableOperationType{}; + auto mockOp = StoppableOperationType{}; auto mockStrand = StrandType{}; EXPECT_CALL(mockOp, get()); EXPECT_CALL(mockExecutionContext, makeStrand()).WillOnce(ReturnRef(mockStrand)); - EXPECT_CALL(mockStrand, execute(A>(), _)) + EXPECT_CALL(mockStrand, execute(A>(), _)) .WillOnce(ReturnRef(mockOp)); auto strand = ctx.makeStrand(); @@ -361,8 +362,8 @@ TEST_F(AnyExecutionContextTests, StrandExecuteWithStopTokenAndVoidThrowsExceptio { auto mockStrand = StrandType{}; EXPECT_CALL(mockExecutionContext, makeStrand()).WillOnce(ReturnRef(mockStrand)); - EXPECT_CALL(mockStrand, execute(A>(), _)) - .WillOnce([](auto&&, auto) -> StoppableOperationType const& { throw 0; }); + EXPECT_CALL(mockStrand, execute(A>(), _)) + .WillOnce([](auto&&, auto) -> StoppableOperationType const& { throw 0; }); auto strand = ctx.makeStrand(); static_assert(std::is_same_v); @@ -372,11 +373,11 @@ TEST_F(AnyExecutionContextTests, StrandExecuteWithStopTokenAndVoidThrowsExceptio TEST_F(AnyExecutionContextTests, StrandExecuteWithStopTokenAndReturnValue) { - auto mockOp = StoppableOperationType{}; + auto mockOp = StoppableOperationType{}; auto mockStrand = StrandType{}; EXPECT_CALL(mockOp, get()).WillOnce(Return(std::make_any(42))); EXPECT_CALL(mockExecutionContext, makeStrand()).WillOnce(ReturnRef(mockStrand)); - EXPECT_CALL(mockStrand, execute(A>(), _)) + EXPECT_CALL(mockStrand, execute(A>(), _)) .WillOnce(ReturnRef(mockOp)); auto strand = ctx.makeStrand(); @@ -392,8 +393,8 @@ TEST_F(AnyExecutionContextTests, StrandExecuteWithStopTokenAndReturnValueThrowsE { auto mockStrand = StrandType{}; EXPECT_CALL(mockExecutionContext, makeStrand()).WillOnce(ReturnRef(mockStrand)); - EXPECT_CALL(mockStrand, execute(A>(), _)) - .WillOnce([](auto&&, auto) -> StoppableOperationType const& { throw 0; }); + EXPECT_CALL(mockStrand, execute(A>(), _)) + .WillOnce([](auto&&, auto) -> StoppableOperationType const& { throw 0; }); auto strand = ctx.makeStrand(); static_assert(std::is_same_v); diff --git a/tests/unit/util/async/AnyOperationTests.cpp b/tests/unit/util/async/AnyOperationTests.cpp index df4605d87..ce62dec4d 100644 --- a/tests/unit/util/async/AnyOperationTests.cpp +++ b/tests/unit/util/async/AnyOperationTests.cpp @@ -2,6 +2,7 @@ #include "util/MockOperation.hpp" #include "util/async/AnyOperation.hpp" #include "util/async/Error.hpp" +#include "util/async/impl/Any.hpp" #include #include @@ -15,10 +16,10 @@ using namespace util::async; using namespace ::testing; struct AnyOperationTests : virtual Test { - using OperationType = MockOperation>; - using StoppableOperationType = MockStoppableOperation>; - using ScheduledOperationType = MockScheduledOperation>; - using RepeatingOperationType = MockRepeatingOperation>; + using OperationType = MockOperation>; + using StoppableOperationType = MockStoppableOperation>; + using ScheduledOperationType = MockScheduledOperation>; + using RepeatingOperationType = MockRepeatingOperation>; NaggyMock mockOp; NaggyMock mockStoppableOp; @@ -40,7 +41,7 @@ struct AnyOperationTests : virtual Test { TEST_F(AnyOperationTests, Move) { - EXPECT_CALL(mockOp, get()).WillOnce(Return(std::any{})); + EXPECT_CALL(mockOp, get()).WillOnce(Return(impl::Any{})); auto yoink = std::move(voidOp); auto res = yoink.get(); ASSERT_TRUE(res); @@ -48,7 +49,7 @@ TEST_F(AnyOperationTests, Move) TEST_F(AnyOperationTests, VoidDataYieldsNoError) { - EXPECT_CALL(mockOp, get()).WillOnce(Return(std::any{})); + EXPECT_CALL(mockOp, get()).WillOnce(Return(impl::Any{})); auto res = voidOp.get(); ASSERT_TRUE(res); } diff --git a/tests/unit/util/async/AnyStrandTests.cpp b/tests/unit/util/async/AnyStrandTests.cpp index c0a87c31d..b60cb600f 100644 --- a/tests/unit/util/async/AnyStrandTests.cpp +++ b/tests/unit/util/async/AnyStrandTests.cpp @@ -3,6 +3,7 @@ #include "util/async/AnyOperation.hpp" #include "util/async/AnyStopToken.hpp" #include "util/async/AnyStrand.hpp" +#include "util/async/impl/Any.hpp" #include #include @@ -33,8 +34,8 @@ struct AnyStrandTests : ::testing::Test { TEST_F(AnyStrandTests, Move) { - auto mockOp = OperationType{}; - EXPECT_CALL(mockStrand, execute(An>())).WillOnce(ReturnRef(mockOp)); + auto mockOp = OperationType{}; + EXPECT_CALL(mockStrand, execute(An>())).WillOnce(ReturnRef(mockOp)); EXPECT_CALL(mockOp, get()); auto mineNow = std::move(strand); @@ -43,8 +44,8 @@ TEST_F(AnyStrandTests, Move) TEST_F(AnyStrandTests, CopyIsRefCounted) { - auto mockOp = OperationType{}; - EXPECT_CALL(mockStrand, execute(An>())).WillOnce(ReturnRef(mockOp)); + auto mockOp = OperationType{}; + EXPECT_CALL(mockStrand, execute(An>())).WillOnce(ReturnRef(mockOp)); auto yoink = strand; ASSERT_TRUE(yoink.execute([] { throw 0; }).get()); @@ -52,8 +53,8 @@ TEST_F(AnyStrandTests, CopyIsRefCounted) TEST_F(AnyStrandTests, ExecuteWithoutTokenAndVoid) { - auto mockOp = OperationType{}; - EXPECT_CALL(mockStrand, execute(An>())).WillOnce(ReturnRef(mockOp)); + auto mockOp = OperationType{}; + EXPECT_CALL(mockStrand, execute(An>())).WillOnce(ReturnRef(mockOp)); auto op = strand.execute([] {}); static_assert(std::is_same_v>); @@ -63,17 +64,17 @@ TEST_F(AnyStrandTests, ExecuteWithoutTokenAndVoid) TEST_F(AnyStrandTests, ExecuteWithoutTokenAndVoidThrowsException) { - auto mockOp = OperationType{}; - EXPECT_CALL(mockStrand, execute(An>())) - .WillOnce([](auto&&) -> OperationType const& { throw 0; }); + auto mockOp = OperationType{}; + EXPECT_CALL(mockStrand, execute(An>())) + .WillOnce([](auto&&) -> OperationType const& { throw 0; }); EXPECT_ANY_THROW([[maybe_unused]] auto unused = strand.execute([] {})); } TEST_F(AnyStrandTests, ExecuteWithStopTokenAndVoid) { - auto mockOp = StoppableOperationType{}; - EXPECT_CALL(mockStrand, execute(An>(), _)) + auto mockOp = StoppableOperationType{}; + EXPECT_CALL(mockStrand, execute(An>(), _)) .WillOnce(ReturnRef(mockOp)); auto op = strand.execute([](auto) {}); @@ -84,17 +85,17 @@ TEST_F(AnyStrandTests, ExecuteWithStopTokenAndVoid) TEST_F(AnyStrandTests, ExecuteWithStopTokenAndVoidThrowsException) { - EXPECT_CALL(mockStrand, execute(An>(), _)) - .WillOnce([](auto&&, auto) -> StoppableOperationType const& { throw 0; }); + EXPECT_CALL(mockStrand, execute(An>(), _)) + .WillOnce([](auto&&, auto) -> StoppableOperationType const& { throw 0; }); EXPECT_ANY_THROW([[maybe_unused]] auto unused = strand.execute([](auto) {})); } TEST_F(AnyStrandTests, ExecuteWithStopTokenAndReturnValue) { - auto mockOp = StoppableOperationType{}; + auto mockOp = StoppableOperationType{}; EXPECT_CALL(mockOp, get()).WillOnce(Return(std::make_any(42))); - EXPECT_CALL(mockStrand, execute(An>(), _)) + EXPECT_CALL(mockStrand, execute(An>(), _)) .WillOnce(ReturnRef(mockOp)); auto op = strand.execute([](auto) { return 42; }); @@ -105,17 +106,17 @@ TEST_F(AnyStrandTests, ExecuteWithStopTokenAndReturnValue) TEST_F(AnyStrandTests, ExecuteWithStopTokenAndReturnValueThrowsException) { - EXPECT_CALL(mockStrand, execute(An>(), _)) - .WillOnce([](auto&&, auto) -> StoppableOperationType const& { throw 0; }); + EXPECT_CALL(mockStrand, execute(An>(), _)) + .WillOnce([](auto&&, auto) -> StoppableOperationType const& { throw 0; }); EXPECT_ANY_THROW([[maybe_unused]] auto unused = strand.execute([](auto) { return 42; })); } TEST_F(AnyStrandTests, ExecuteWithTimeoutAndStopTokenAndReturnValue) { - auto mockOp = StoppableOperationType{}; + auto mockOp = StoppableOperationType{}; EXPECT_CALL(mockOp, get()).WillOnce(Return(std::make_any(42))); - EXPECT_CALL(mockStrand, execute(An>(), _)) + EXPECT_CALL(mockStrand, execute(An>(), _)) .WillOnce(ReturnRef(mockOp)); auto op = strand.execute([](auto) { return 42; }, std::chrono::milliseconds{1}); @@ -126,8 +127,8 @@ TEST_F(AnyStrandTests, ExecuteWithTimeoutAndStopTokenAndReturnValue) TEST_F(AnyStrandTests, ExecuteWithTimeoutAndStopTokenAndReturnValueThrowsException) { - EXPECT_CALL(mockStrand, execute(An>(), _)) - .WillOnce([](auto&&, auto) -> StoppableOperationType const& { throw 0; }); + EXPECT_CALL(mockStrand, execute(An>(), _)) + .WillOnce([](auto&&, auto) -> StoppableOperationType const& { throw 0; }); EXPECT_ANY_THROW( [[maybe_unused]] auto unused = @@ -137,12 +138,12 @@ TEST_F(AnyStrandTests, ExecuteWithTimeoutAndStopTokenAndReturnValueThrowsExcepti TEST_F(AnyStrandTests, RepeatingOperation) { - auto mockRepeatingOp = RepeatingOperationType{}; + auto mockRepeatingOp = RepeatingOperationType{}; EXPECT_CALL(mockRepeatingOp, wait()); EXPECT_CALL( - mockStrand, executeRepeatedly(std::chrono::milliseconds{1}, A>()) + mockStrand, executeRepeatedly(std::chrono::milliseconds{1}, A>()) ) - .WillOnce([&mockRepeatingOp] -> RepeatingOperationType const& { + .WillOnce([&mockRepeatingOp] -> RepeatingOperationType const& { return mockRepeatingOp; }); diff --git a/tests/unit/util/async/AsyncExecutionContextTests.cpp b/tests/unit/util/async/AsyncExecutionContextTests.cpp index e54f76aec..194f340ee 100644 --- a/tests/unit/util/async/AsyncExecutionContextTests.cpp +++ b/tests/unit/util/async/AsyncExecutionContextTests.cpp @@ -238,10 +238,10 @@ TYPED_TEST(ExecutionContextTests, submit) std::atomic_uint32_t count = 0; std::binary_semaphore sem{0}; - static constexpr auto kNUM_SUBMISSIONS = 1024; + static constexpr auto kNumSubmissions = 1024; - for (auto i = 1; i <= kNUM_SUBMISSIONS; ++i) { - if (i == kNUM_SUBMISSIONS) { + for (auto i = 1; i <= kNumSubmissions; ++i) { + if (i == kNumSubmissions) { this->ctx.submit([&count, &sem] { ++count; sem.release(); @@ -254,7 +254,7 @@ TYPED_TEST(ExecutionContextTests, submit) sem.acquire(); // order is not guaranteed (see `strandSubmit` below) - ASSERT_EQ(count, static_cast(kNUM_SUBMISSIONS)); + ASSERT_EQ(count, static_cast(kNumSubmissions)); } TYPED_TEST(ExecutionContextTests, strandMove) @@ -359,10 +359,10 @@ TYPED_TEST(ExecutionContextTests, strandSubmit) std::vector results; std::binary_semaphore sem{0}; - static constexpr auto kNUM_SUBMISSIONS = 1024; + static constexpr auto kNumSubmissions = 1024; - for (auto i = 1; i <= kNUM_SUBMISSIONS; ++i) { - if (i == kNUM_SUBMISSIONS) { + for (auto i = 1; i <= kNumSubmissions; ++i) { + if (i == kNumSubmissions) { strand.submit([&results, &sem, i] { results.push_back(i); sem.release(); @@ -374,8 +374,8 @@ TYPED_TEST(ExecutionContextTests, strandSubmit) sem.acquire(); - ASSERT_EQ(results.size(), static_cast(kNUM_SUBMISSIONS)); - for (int i = 0; i < kNUM_SUBMISSIONS; ++i) { + ASSERT_EQ(results.size(), static_cast(kNumSubmissions)); + for (int i = 0; i < kNumSubmissions; ++i) { EXPECT_EQ(results[i], i + 1); } } diff --git a/tests/unit/util/config/ArrayViewTests.cpp b/tests/unit/util/config/ArrayViewTests.cpp index 48dbb766b..f144fc443 100644 --- a/tests/unit/util/config/ArrayViewTests.cpp +++ b/tests/unit/util/config/ArrayViewTests.cpp @@ -18,7 +18,7 @@ using namespace util::config; struct ArrayViewTest : virtual testing::Test { ArrayViewTest() { - ConfigFileJson const jsonFileObj{boost::json::parse(kJSON_DATA).as_object()}; + ConfigFileJson const jsonFileObj{boost::json::parse(kJsonData).as_object()}; auto const errors = configData.parse(jsonFileObj); EXPECT_TRUE(!errors.has_value()); } diff --git a/tests/unit/util/config/ClioConfigDefinitionTests.cpp b/tests/unit/util/config/ClioConfigDefinitionTests.cpp index f57814820..9683150f1 100644 --- a/tests/unit/util/config/ClioConfigDefinitionTests.cpp +++ b/tests/unit/util/config/ClioConfigDefinitionTests.cpp @@ -180,11 +180,13 @@ TEST_F(ConfigDescriptionAssertTest, NonExistingKeyTest) EXPECT_CLIO_ASSERT_FAIL({ [[maybe_unused]] auto a = definition.get("etl_sources.[]"); }); } -/** @brief Testing override the default values with the ones in Json */ +/** + * @brief Testing override the default values with the ones in Json + */ struct OverrideConfigVals : testing::Test { OverrideConfigVals() { - ConfigFileJson const jsonFileObj{boost::json::parse(kJSON_DATA).as_object()}; + ConfigFileJson const jsonFileObj{boost::json::parse(kJsonData).as_object()}; auto const errors = configData.parse(jsonFileObj); EXPECT_TRUE(!errors.has_value()); } @@ -298,7 +300,7 @@ struct IncorrectOverrideValues : testing::Test { TEST_F(IncorrectOverrideValues, InvalidJsonErrors) { - ConfigFileJson const jsonFileObj{boost::json::parse(kINVALID_JSON_DATA).as_object()}; + ConfigFileJson const jsonFileObj{boost::json::parse(kInvalidJsonData).as_object()}; auto const errors = configData.parse(jsonFileObj); EXPECT_TRUE(errors.has_value()); diff --git a/tests/unit/util/config/ConfigFileJsonTests.cpp b/tests/unit/util/config/ConfigFileJsonTests.cpp index 973f38ddf..501f86f73 100644 --- a/tests/unit/util/config/ConfigFileJsonTests.cpp +++ b/tests/unit/util/config/ConfigFileJsonTests.cpp @@ -19,7 +19,7 @@ using namespace util::config; namespace { -constexpr auto kEPS = 1e-9; +constexpr auto kEps = 1e-9; } // namespace struct ConfigFileJsonParseTestBundle { @@ -56,7 +56,7 @@ TEST_P(ConfigFileJsonParseTest, parseValues) }, [&flatJson, &key](double const v) { EXPECT_TRUE(flatJson.at(key).is_double()) << key << ": " << v; - EXPECT_NEAR(flatJson.at(key).as_double(), v, kEPS) << key << ": " << v; + EXPECT_NEAR(flatJson.at(key).as_double(), v, kEps) << key << ": " << v; }, [&flatJson, &key](bool const v) { EXPECT_TRUE(flatJson.at(key).is_bool()) << key << ": " << v; @@ -296,7 +296,7 @@ INSTANTIATE_TEST_CASE_P( boost::json::array{boost::json::value{}, "some string"}}} } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); struct ConfigFileJsonTest : public virtual ::testing::Test {}; @@ -325,7 +325,7 @@ TEST_F(ConfigFileJsonTest, getValue) auto const doubleValue = jsonFileObj.getValue("double"); ASSERT_TRUE(std::holds_alternative(doubleValue)); - EXPECT_NEAR(std::get(doubleValue), 123.456, kEPS); + EXPECT_NEAR(std::get(doubleValue), 123.456, kEps); EXPECT_FALSE(jsonFileObj.containsKey("object.int")); } @@ -377,7 +377,7 @@ TEST_F(ConfigFileJsonTest, getArray) auto const value2 = (*array.at(2)); // NOLINT(bugprone-unchecked-optional-access) ASSERT_TRUE(std::holds_alternative(value2)); - EXPECT_NEAR(std::get(value2), 3.14, kEPS); + EXPECT_NEAR(std::get(value2), 3.14, kEps); auto const value3 = (*array.at(3)); // NOLINT(bugprone-unchecked-optional-access) ASSERT_TRUE(std::holds_alternative(value3)); diff --git a/tests/unit/util/config/ObjectViewTests.cpp b/tests/unit/util/config/ObjectViewTests.cpp index 5d9a9a5c9..67e384e9d 100644 --- a/tests/unit/util/config/ObjectViewTests.cpp +++ b/tests/unit/util/config/ObjectViewTests.cpp @@ -16,7 +16,7 @@ using namespace util::config; struct ObjectViewTest : virtual testing::Test { ObjectViewTest() { - ConfigFileJson const jsonFileObj{boost::json::parse(kJSON_DATA).as_object()}; + ConfigFileJson const jsonFileObj{boost::json::parse(kJsonData).as_object()}; auto const errors = configData.parse(jsonFileObj); EXPECT_TRUE(!errors.has_value()); } diff --git a/tests/unit/util/log/LogServiceInitTests.cpp b/tests/unit/util/log/LogServiceInitTests.cpp index eab7a072f..1ea0523ee 100644 --- a/tests/unit/util/log/LogServiceInitTests.cpp +++ b/tests/unit/util/log/LogServiceInitTests.cpp @@ -1,4 +1,3 @@ -#include "util/LoggerBuffer.hpp" #include "util/LoggerFixtures.hpp" #include "util/config/Array.hpp" #include "util/config/ConfigConstraints.hpp" @@ -70,12 +69,6 @@ protected: {"log.tag_style", ConfigValue{ConfigType::String}.defaultValue("none")}, }; - - std::string - getLoggerString() - { - return buffer_.getStrAndReset(); - } }; TEST_F(LogServiceInitTests, DefaultLogLevel) @@ -88,7 +81,7 @@ TEST_F(LogServiceInitTests, DefaultLogLevel) EXPECT_TRUE(LogService::init(config_)); std::string const logString = "some log"; - for (std::string_view const channel : Logger::kCHANNELS) { + for (std::string_view const channel : Logger::kChannels) { Logger const log{channel}; log.trace() << logString; auto loggerStr = getLoggerString(); @@ -131,7 +124,7 @@ TEST_F(LogServiceInitTests, ChannelLogLevel) EXPECT_TRUE(LogService::init(config_)); std::string const logString = "some log"; - for (auto const& channel : Logger::kCHANNELS) { + for (auto const& channel : Logger::kChannels) { Logger const log{channel}; log.trace() << logString; ASSERT_TRUE(getLoggerString().empty()); diff --git a/tests/unit/util/log/LoggerTests.cpp b/tests/unit/util/log/LoggerTests.cpp index 8f523f4a7..031680776 100644 --- a/tests/unit/util/log/LoggerTests.cpp +++ b/tests/unit/util/log/LoggerTests.cpp @@ -84,11 +84,11 @@ TEST_F(LoggerTest, LOGMacro) TEST_F(LoggerTest, ManyDynamicLoggers) { - static constexpr size_t kNUM_LOGGERS = 10'000; + static constexpr size_t kNumLoggers = 10'000; auto initialLoggers = loggersNum(); - for (size_t i = 0; i < kNUM_LOGGERS; ++i) { + for (size_t i = 0; i < kNumLoggers; ++i) { std::string const loggerName = "DynamicLogger" + std::to_string(i); Logger const log{loggerName}; @@ -180,7 +180,9 @@ struct LogFileRotationTests : ::testing::Test { LogServiceState::replaceSinks(LogServiceState::sinks_); } - /** @brief Returns the number of regular files in tmpDir_. */ + /** + * @brief Returns the number of regular files in tmpDir_. + */ [[nodiscard]] std::size_t countLogFiles() const { diff --git a/tests/unit/util/log/PrettyPathTests.cpp b/tests/unit/util/log/PrettyPathTests.cpp index 67cf33304..a79268213 100644 --- a/tests/unit/util/log/PrettyPathTests.cpp +++ b/tests/unit/util/log/PrettyPathTests.cpp @@ -1,46 +1,46 @@ #include "util/MockAssert.hpp" -#include "util/SourceLocation.hpp" #include "util/log/PrettyPath.hpp" #include +#include #include using namespace util; TEST(PrettyPath, CurrentFile) { - auto loc = CURRENT_SRC_LOCATION; + auto loc = std::source_location::current(); auto pretty = prettyPath(loc.file_name()); EXPECT_EQ(pretty, "util/log/PrettyPathTests.cpp"); } struct PrettyPathDepth : public common::util::WithMockAssert { - static constexpr std::string_view kTEST_PATH = "my/awesome/path/to/file.cpp"; + static constexpr std::string_view kTestPath = "my/awesome/path/to/file.cpp"; }; TEST_F(PrettyPathDepth, Zero) { EXPECT_CLIO_ASSERT_FAIL_WITH_MESSAGE( - { [[maybe_unused]] auto unused = prettyPath(kTEST_PATH, 0); }, + { [[maybe_unused]] auto unused = prettyPath(kTestPath, 0); }, "maxDepth must be greater than 0" ); } TEST_F(PrettyPathDepth, Small) { - auto pretty = prettyPath(kTEST_PATH, 1); + auto pretty = prettyPath(kTestPath, 1); EXPECT_EQ(pretty, "file.cpp"); } TEST_F(PrettyPathDepth, Big) { - auto pretty = prettyPath(kTEST_PATH, 4); + auto pretty = prettyPath(kTestPath, 4); EXPECT_EQ(pretty, "awesome/path/to/file.cpp"); } TEST_F(PrettyPathDepth, MoreThanParts) { - auto pretty = prettyPath(kTEST_PATH, 10); + auto pretty = prettyPath(kTestPath, 10); EXPECT_EQ(pretty, "my/awesome/path/to/file.cpp"); } diff --git a/tests/unit/util/prometheus/CounterTests.cpp b/tests/unit/util/prometheus/CounterTests.cpp index 869fbf103..f97f773ae 100644 --- a/tests/unit/util/prometheus/CounterTests.cpp +++ b/tests/unit/util/prometheus/CounterTests.cpp @@ -103,22 +103,22 @@ TEST_F(CounterIntTests, reset) TEST_F(CounterIntTests, multithreadAdd) { - static constexpr auto kNUM_ADDITIONS = 1000; - static constexpr auto kNUM_NUMBER_ADDITIONS = 100; - static constexpr auto kNUMBER_TO_ADD = 11; + static constexpr auto kNumAdditions = 1000; + static constexpr auto kNumNumberAdditions = 100; + static constexpr auto kNumberToAdd = 11; std::thread thread1([&] { - for (int i = 0; i < kNUM_ADDITIONS; ++i) { + for (int i = 0; i < kNumAdditions; ++i) { ++counter; } }); std::thread thread2([&] { - for (int i = 0; i < kNUM_NUMBER_ADDITIONS; ++i) { - counter += kNUMBER_TO_ADD; + for (int i = 0; i < kNumNumberAdditions; ++i) { + counter += kNumberToAdd; } }); thread1.join(); thread2.join(); - EXPECT_EQ(counter.value(), kNUM_ADDITIONS + (kNUM_NUMBER_ADDITIONS * kNUMBER_TO_ADD)); + EXPECT_EQ(counter.value(), kNumAdditions + (kNumNumberAdditions * kNumberToAdd)); } struct CounterDoubleTests : ::testing::Test { @@ -142,20 +142,20 @@ TEST_F(CounterDoubleTests, reset) TEST_F(CounterDoubleTests, multithreadAdd) { - static constexpr auto kNUM_ADDITIONS = 1000; - static constexpr auto kNUM_NUMBER_ADDITIONS = 100; - static constexpr auto kNUMBER_TO_ADD = 11.1234; + static constexpr auto kNumAdditions = 1000; + static constexpr auto kNumNumberAdditions = 100; + static constexpr auto kNumberToAdd = 11.1234; std::thread thread1([&] { - for (int i = 0; i < kNUM_ADDITIONS; ++i) { + for (int i = 0; i < kNumAdditions; ++i) { ++counter; } }); std::thread thread2([&] { - for (int i = 0; i < kNUM_NUMBER_ADDITIONS; ++i) { - counter += kNUMBER_TO_ADD; + for (int i = 0; i < kNumNumberAdditions; ++i) { + counter += kNumberToAdd; } }); thread1.join(); thread2.join(); - EXPECT_NEAR(counter.value(), kNUM_ADDITIONS + (kNUM_NUMBER_ADDITIONS * kNUMBER_TO_ADD), 1e-9); + EXPECT_NEAR(counter.value(), kNumAdditions + (kNumNumberAdditions * kNumberToAdd), 1e-9); } diff --git a/tests/unit/util/prometheus/GaugeTests.cpp b/tests/unit/util/prometheus/GaugeTests.cpp index abf9774b3..1e6416a6f 100644 --- a/tests/unit/util/prometheus/GaugeTests.cpp +++ b/tests/unit/util/prometheus/GaugeTests.cpp @@ -77,30 +77,30 @@ TEST_F(GaugeIntTests, set) TEST_F(GaugeIntTests, multithreadAddAndSubtract) { - static constexpr auto kNUM_ADDITIONS = 1000; - static constexpr auto kNUM_NUMBER_ADDITIONS = 100; - static constexpr auto kNUMBER_TO_ADD = 11; - static constexpr auto kNUM_SUBTRACTIONS = 2000; - static constexpr auto kNUM_NUMBER_SUBTRACTIONS = 300; - static constexpr auto kNUMBER_TO_SUBTRACT = 300; + static constexpr auto kNumAdditions = 1000; + static constexpr auto kNumNumberAdditions = 100; + static constexpr auto kNumberToAdd = 11; + static constexpr auto kNumSubtractions = 2000; + static constexpr auto kNumNumberSubtractions = 300; + static constexpr auto kNumberToSubtract = 300; std::thread thread1([&] { - for (int i = 0; i < kNUM_ADDITIONS; ++i) { + for (int i = 0; i < kNumAdditions; ++i) { ++gauge; } }); std::thread thread2([&] { - for (int i = 0; i < kNUM_NUMBER_ADDITIONS; ++i) { - gauge += kNUMBER_TO_ADD; + for (int i = 0; i < kNumNumberAdditions; ++i) { + gauge += kNumberToAdd; } }); std::thread thread3([&] { - for (int i = 0; i < kNUM_SUBTRACTIONS; ++i) { + for (int i = 0; i < kNumSubtractions; ++i) { --gauge; } }); std::thread thread4([&] { - for (int i = 0; i < kNUM_NUMBER_SUBTRACTIONS; ++i) { - gauge -= kNUMBER_TO_SUBTRACT; + for (int i = 0; i < kNumNumberSubtractions; ++i) { + gauge -= kNumberToSubtract; } }); thread1.join(); @@ -109,8 +109,8 @@ TEST_F(GaugeIntTests, multithreadAddAndSubtract) thread4.join(); EXPECT_EQ( gauge.value(), - kNUM_ADDITIONS + (kNUM_NUMBER_ADDITIONS * kNUMBER_TO_ADD) - kNUM_SUBTRACTIONS - - (kNUM_NUMBER_SUBTRACTIONS * kNUMBER_TO_SUBTRACT) + kNumAdditions + (kNumNumberAdditions * kNumberToAdd) - kNumSubtractions - + (kNumNumberSubtractions * kNumberToSubtract) ); } @@ -151,30 +151,30 @@ TEST_F(GaugeDoubleTests, set) TEST_F(GaugeDoubleTests, multithreadAddAndSubtract) { - static constexpr auto kNUM_ADDITIONS = 1000; - static constexpr auto kNUM_NUMBER_ADDITIONS = 100; - static constexpr auto kNUMBER_TO_ADD = 11.1234; - static constexpr auto kNUM_SUBTRACTIONS = 2000; - static constexpr auto kNUM_NUMBER_SUBTRACTIONS = 300; - static constexpr auto kNUMBER_TO_SUBTRACT = 300.321; + static constexpr auto kNumAdditions = 1000; + static constexpr auto kNumNumberAdditions = 100; + static constexpr auto kNumberToAdd = 11.1234; + static constexpr auto kNumSubtractions = 2000; + static constexpr auto kNumNumberSubtractions = 300; + static constexpr auto kNumberToSubtract = 300.321; std::thread thread1([&] { - for (int i = 0; i < kNUM_ADDITIONS; ++i) { + for (int i = 0; i < kNumAdditions; ++i) { ++gauge; } }); std::thread thread2([&] { - for (int i = 0; i < kNUM_NUMBER_ADDITIONS; ++i) { - gauge += kNUMBER_TO_ADD; + for (int i = 0; i < kNumNumberAdditions; ++i) { + gauge += kNumberToAdd; } }); std::thread thread3([&] { - for (int i = 0; i < kNUM_SUBTRACTIONS; ++i) { + for (int i = 0; i < kNumSubtractions; ++i) { --gauge; } }); std::thread thread4([&] { - for (int i = 0; i < kNUM_NUMBER_SUBTRACTIONS; ++i) { - gauge -= kNUMBER_TO_SUBTRACT; + for (int i = 0; i < kNumNumberSubtractions; ++i) { + gauge -= kNumberToSubtract; } }); thread1.join(); @@ -183,8 +183,8 @@ TEST_F(GaugeDoubleTests, multithreadAddAndSubtract) thread4.join(); EXPECT_NEAR( gauge.value(), - kNUM_ADDITIONS + (kNUM_NUMBER_ADDITIONS * kNUMBER_TO_ADD) - kNUM_SUBTRACTIONS - - (kNUM_NUMBER_SUBTRACTIONS * kNUMBER_TO_SUBTRACT), + kNumAdditions + (kNumNumberAdditions * kNumberToAdd) - kNumSubtractions - + (kNumNumberSubtractions * kNumberToSubtract), 1e-9 ); } diff --git a/tests/unit/util/prometheus/HttpTests.cpp b/tests/unit/util/prometheus/HttpTests.cpp index 811c32714..8ee6636b6 100644 --- a/tests/unit/util/prometheus/HttpTests.cpp +++ b/tests/unit/util/prometheus/HttpTests.cpp @@ -87,7 +87,7 @@ INSTANTIATE_TEST_CASE_P( .expected = false }, }), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); struct PrometheusHandleRequestTestsBase { diff --git a/tests/unit/util/requests/RequestBuilderTests.cpp b/tests/unit/util/requests/RequestBuilderTests.cpp index 1e47f91f4..785856e1c 100644 --- a/tests/unit/util/requests/RequestBuilderTests.cpp +++ b/tests/unit/util/requests/RequestBuilderTests.cpp @@ -6,9 +6,7 @@ #include #include -#include #include -#include #include #include diff --git a/tests/unit/util/requests/SslContextTests.cpp b/tests/unit/util/requests/SslContextTests.cpp index b87d1089e..03ea91849 100644 --- a/tests/unit/util/requests/SslContextTests.cpp +++ b/tests/unit/util/requests/SslContextTests.cpp @@ -1,11 +1,36 @@ #include "util/requests/impl/SslContext.hpp" +#include #include +#include + using namespace util::requests::impl; TEST(SslContext, Create) { - auto ctx = makeClientSslContext(); - EXPECT_TRUE(ctx); + auto& ctx = getClientSslContext(); + EXPECT_NE(ctx.native_handle(), nullptr); +} + +TEST(SslContext, IsCached) +{ + auto& first = getClientSslContext(); + auto& second = getClientSslContext(); + + // Same shared instance is returned on every call + EXPECT_EQ(&first, &second); +} + +TEST(SslContext, InitSucceedsWithSystemCertificates) +{ + EXPECT_TRUE(initClientSslContext().has_value()); +} + +TEST(SslContext, MakeWithoutRootCertificateReturnsError) +{ + auto const ctx = makeClientSslContext(std::nullopt); + + ASSERT_FALSE(ctx.has_value()); + EXPECT_THAT(ctx.error().message(), testing::HasSubstr("could not find root certificate")); } diff --git a/tests/unit/web/AdminVerificationTests.cpp b/tests/unit/web/AdminVerificationTests.cpp index a3af38ab9..7c66ef024 100644 --- a/tests/unit/web/AdminVerificationTests.cpp +++ b/tests/unit/web/AdminVerificationTests.cpp @@ -6,8 +6,6 @@ #include "web/AdminVerificationStrategy.hpp" #include -#include -#include #include #include #include @@ -65,7 +63,7 @@ TEST_F(PasswordAdminVerificationStrategyTest, IsAdminReturnsTrueOnlyForValidPass EXPECT_FALSE(strat_.isAdmin(makeRequest("a"), "127.0.0.1")); // Wrong header - EXPECT_FALSE(strat_.isAdmin(makeRequest(passwordHash_, http::field::authentication_info), "")); + EXPECT_FALSE(strat_.isAdmin(makeRequest(passwordHash_, http::field::accept), "")); } struct MakeAdminVerificationStrategyTestParams { @@ -175,5 +173,5 @@ INSTANTIATE_TEST_SUITE_P( .expectedError = false } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); diff --git a/tests/unit/web/ProxyIpResolverTests.cpp b/tests/unit/web/ProxyIpResolverTests.cpp index 96c5d91d0..2553b9734 100644 --- a/tests/unit/web/ProxyIpResolverTests.cpp +++ b/tests/unit/web/ProxyIpResolverTests.cpp @@ -69,7 +69,7 @@ TEST_F(ProxyIpResolverTest, FromConfig) EXPECT_EQ(proxyIpResolver.resolveClientIp(clientIp, headers), std::nullopt); EXPECT_EQ(proxyIpResolver.resolveClientIp(proxyIp, headers), clientIp); - headers.set(ProxyIpResolver::kPROXY_TOKEN_HEADER, proxyToken); + headers.set(ProxyIpResolver::kProxyTokenHeader, proxyToken); EXPECT_EQ(proxyIpResolver.resolveClientIp(clientIp, headers), clientIp); EXPECT_EQ(proxyIpResolver.resolveClientIp(proxyIp, headers), clientIp); EXPECT_EQ(proxyIpResolver.resolveClientIp("127.0.0.1", headers), clientIp); @@ -127,7 +127,7 @@ INSTANTIATE_TEST_SUITE_P( .proxyIps = {}, .proxyTokens = {"test_token"}, .headers = - {{std::string(ProxyIpResolver::kPROXY_TOKEN_HEADER), "test_token"}, + {{std::string(ProxyIpResolver::kProxyTokenHeader), "test_token"}, {std::string(http::to_string(http::field::forwarded)), "for=1.2.3.4"}}, .connectionIp = "5.6.7.8", .expectedIp = "1.2.3.4" @@ -136,7 +136,7 @@ INSTANTIATE_TEST_SUITE_P( .testName = "TrustedProxyTokenWithoutForwardedHeader", .proxyIps = {}, .proxyTokens = {"test_token"}, - .headers = {{std::string(ProxyIpResolver::kPROXY_TOKEN_HEADER), "test_token"}}, + .headers = {{std::string(ProxyIpResolver::kProxyTokenHeader), "test_token"}}, .connectionIp = "5.6.7.8", .expectedIp = std::nullopt }, @@ -145,7 +145,7 @@ INSTANTIATE_TEST_SUITE_P( .proxyIps = {}, .proxyTokens = {}, .headers = - {{std::string(ProxyIpResolver::kPROXY_TOKEN_HEADER), "test_token"}, + {{std::string(ProxyIpResolver::kProxyTokenHeader), "test_token"}, {std::string(http::to_string(http::field::forwarded)), "for=1.2.3.4"}}, .connectionIp = "5.6.7.8", .expectedIp = std::nullopt @@ -214,5 +214,5 @@ INSTANTIATE_TEST_SUITE_P( .expectedIp = "9.10.11.12" } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); diff --git a/tests/unit/web/RPCServerHandlerTests.cpp b/tests/unit/web/RPCServerHandlerTests.cpp index c815817f5..4b5fb0fdd 100644 --- a/tests/unit/web/RPCServerHandlerTests.cpp +++ b/tests/unit/web/RPCServerHandlerTests.cpp @@ -34,8 +34,8 @@ using namespace util::config; namespace { -constexpr auto kMIN_SEQ = 10; -constexpr auto kMAX_SEQ = 30; +constexpr auto kMinSeq = 10; +constexpr auto kMaxSeq = 30; } // namespace @@ -85,9 +85,9 @@ struct WebRPCServerHandlerTest : util::prometheus::WithPrometheus, util::config::ClioConfigDefinition cfg{ {"log.tag_style", ConfigValue{ConfigType::String}.defaultValue("none")}, {"api_version.default", - ConfigValue{ConfigType::Integer}.defaultValue(rpc::kAPI_VERSION_DEFAULT)}, - {"api_version.min", ConfigValue{ConfigType::Integer}.defaultValue(rpc::kAPI_VERSION_MIN)}, - {"api_version.max", ConfigValue{ConfigType::Integer}.defaultValue(rpc::kAPI_VERSION_MAX)} + ConfigValue{ConfigType::Integer}.defaultValue(rpc::kApiVersionDefault)}, + {"api_version.min", ConfigValue{ConfigType::Integer}.defaultValue(rpc::kApiVersionMin)}, + {"api_version.max", ConfigValue{ConfigType::Integer}.defaultValue(rpc::kApiVersionMax)} }; std::shared_ptr rpcEngine = std::make_shared(); std::shared_ptr etl = std::make_shared(); @@ -107,15 +107,15 @@ struct WebRPCServerHandlerTest : util::prometheus::WithPrometheus, TEST_F(WebRPCServerHandlerTest, HTTPDefaultPath) { - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "method": "server_info", "params": [{}] })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kRESULT = "{}"; - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResult = "{}"; + static constexpr auto kResponse = R"JSON({ "result": { "status": "success" }, @@ -128,35 +128,35 @@ TEST_F(WebRPCServerHandlerTest, HTTPDefaultPath) })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); - EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kREQUEST).as_object())) + EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kRequest).as_object())) .WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, buildResponse(testing::_)) - .WillOnce(testing::Return(rpc::Result{boost::json::parse(kRESULT).as_object()})); + .WillOnce(testing::Return(rpc::Result{boost::json::parse(kResult).as_object()})); EXPECT_CALL(*rpcEngine, notifyComplete("server_info", testing::_)).Times(1); EXPECT_CALL(*etl, lastCloseAgeSeconds()).WillOnce(testing::Return(45)); - (*handler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, HTTPRejectedByDosguard) { - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "method": "server_info", "params": [{}] })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(false)); - (*handler)(kREQUEST, session); + (*handler)(kRequest, session); EXPECT_EQ(session->slowDownCallsCounter, 1); } TEST_F(WebRPCServerHandlerTest, HTTPRejectedByDosguardAfterParsing) { - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "method": "server_info", "params": [{}] })JSON"; @@ -165,23 +165,23 @@ TEST_F(WebRPCServerHandlerTest, HTTPRejectedByDosguardAfterParsing) EXPECT_CALL(dosguard, request(session->clientIp(), testing::_)) .WillOnce(testing::Return(false)); - (*handler)(kREQUEST, session); + (*handler)(kRequest, session); EXPECT_EQ(session->slowDownCallsCounter, 1); } TEST_F(WebRPCServerHandlerTest, WsNormalPath) { session->upgraded = true; - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "command": "server_info", "id": 99, "api_version": 2 })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kRESULT = "{}"; - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResult = "{}"; + static constexpr auto kResponse = R"JSON({ "result": {}, "id": 99, "status": "success", @@ -195,23 +195,23 @@ TEST_F(WebRPCServerHandlerTest, WsNormalPath) ] })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); - EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kREQUEST).as_object())) + EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kRequest).as_object())) .WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, buildResponse(testing::_)) - .WillOnce(testing::Return(rpc::Result{boost::json::parse(kRESULT).as_object()})); + .WillOnce(testing::Return(rpc::Result{boost::json::parse(kResult).as_object()})); EXPECT_CALL(*rpcEngine, notifyComplete("server_info", testing::_)).Times(1); EXPECT_CALL(*etl, lastCloseAgeSeconds()).WillOnce(testing::Return(45)); - (*handler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, WsRejectedByDosguard) { session->upgraded = true; - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "command": "server_info", "id": 99, "api_version": 2 @@ -219,44 +219,44 @@ TEST_F(WebRPCServerHandlerTest, WsRejectedByDosguard) EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(false)); - (*handler)(kREQUEST, session); + (*handler)(kRequest, session); EXPECT_EQ(session->slowDownCallsCounter, 1); } TEST_F(WebRPCServerHandlerTest, WsRejectedByDosguardAfterParsing) { session->upgraded = true; - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "command": "server_info", "id": 99, "api_version": 2 })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); - EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kREQUEST).as_object())) + EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kRequest).as_object())) .WillOnce(testing::Return(false)); - (*handler)(kREQUEST, session); + (*handler)(kRequest, session); EXPECT_EQ(session->slowDownCallsCounter, 1); } TEST_F(WebRPCServerHandlerTest, HTTPForwardedPath) { - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "method": "server_info", "params": [{}] })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); // Note: forwarding always goes thru WS API - static constexpr auto kRESULT = R"JSON({ + static constexpr auto kResult = R"JSON({ "result": { "index": 1 }, "forwarded": true })JSON"; - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResponse = R"JSON({ "result": { "index": 1, "status": "success" @@ -271,30 +271,30 @@ TEST_F(WebRPCServerHandlerTest, HTTPForwardedPath) })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); - EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kREQUEST).as_object())) + EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kRequest).as_object())) .WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, buildResponse(testing::_)) - .WillOnce(testing::Return(rpc::Result{boost::json::parse(kRESULT).as_object()})); + .WillOnce(testing::Return(rpc::Result{boost::json::parse(kResult).as_object()})); EXPECT_CALL(*rpcEngine, notifyComplete("server_info", testing::_)).Times(1); EXPECT_CALL(*etl, lastCloseAgeSeconds()).WillOnce(testing::Return(45)); - (*handler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, HTTPForwardedErrorPath) { - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "method": "server_info", "params": [{}] })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); // Note: forwarding always goes thru WS API - static constexpr auto kRESULT = R"JSON({ + static constexpr auto kResult = R"JSON({ "error": "error", "error_code": 123, "error_message": "error message", @@ -302,7 +302,7 @@ TEST_F(WebRPCServerHandlerTest, HTTPForwardedErrorPath) "type": "response", "forwarded": true })JSON"; - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResponse = R"JSON({ "result": { "error": "error", "error_code": 123, @@ -320,37 +320,37 @@ TEST_F(WebRPCServerHandlerTest, HTTPForwardedErrorPath) })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); - EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kREQUEST).as_object())) + EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kRequest).as_object())) .WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, buildResponse(testing::_)) - .WillOnce(testing::Return(rpc::Result{boost::json::parse(kRESULT).as_object()})); + .WillOnce(testing::Return(rpc::Result{boost::json::parse(kResult).as_object()})); EXPECT_CALL(*rpcEngine, notifyComplete("server_info", testing::_)).Times(1); EXPECT_CALL(*etl, lastCloseAgeSeconds()).WillOnce(testing::Return(45)); - (*handler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, WsForwardedPath) { session->upgraded = true; - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "command": "server_info", "id": 99 })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); // Note: forwarding always goes thru WS API - static constexpr auto kRESULT = R"JSON({ + static constexpr auto kResult = R"JSON({ "result": { "index": 1 }, "forwarded": true })JSON"; - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResponse = R"JSON({ "result": { "index": 1 }, @@ -367,31 +367,31 @@ TEST_F(WebRPCServerHandlerTest, WsForwardedPath) })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); - EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kREQUEST).as_object())) + EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kRequest).as_object())) .WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, buildResponse(testing::_)) - .WillOnce(testing::Return(rpc::Result{boost::json::parse(kRESULT).as_object()})); + .WillOnce(testing::Return(rpc::Result{boost::json::parse(kResult).as_object()})); EXPECT_CALL(*rpcEngine, notifyComplete("server_info", testing::_)).Times(1); EXPECT_CALL(*etl, lastCloseAgeSeconds()).WillOnce(testing::Return(45)); - (*handler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, WsForwardedErrorPath) { session->upgraded = true; - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "command": "server_info", "id": 99 })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); // Note: forwarding always goes thru WS API - static constexpr auto kRESULT = R"JSON({ + static constexpr auto kResult = R"JSON({ "error": "error", "error_code": 123, "error_message": "error message", @@ -401,7 +401,7 @@ TEST_F(WebRPCServerHandlerTest, WsForwardedErrorPath) })JSON"; // WS error responses, unlike their successful counterpart, contain everything on top level // without "result" - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResponse = R"JSON({ "error": "error", "error_code": 123, "error_message": "error message", @@ -418,23 +418,23 @@ TEST_F(WebRPCServerHandlerTest, WsForwardedErrorPath) })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); - EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kREQUEST).as_object())) + EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kRequest).as_object())) .WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, buildResponse(testing::_)) - .WillOnce(testing::Return(rpc::Result{boost::json::parse(kRESULT).as_object()})); + .WillOnce(testing::Return(rpc::Result{boost::json::parse(kResult).as_object()})); // Forwarded errors counted as successful: EXPECT_CALL(*rpcEngine, notifyComplete("server_info", testing::_)).Times(1); EXPECT_CALL(*etl, lastCloseAgeSeconds()).WillOnce(testing::Return(45)); - (*handler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, HTTPErrorPath) { - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResponse = R"JSON({ "result": { "error": "invalidParams", "error_code": 31, @@ -458,9 +458,9 @@ TEST_F(WebRPCServerHandlerTest, HTTPErrorPath) ] })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kREQUEST_JSON = R"JSON({ + static constexpr auto kRequestJson = R"JSON({ "method": "ledger", "params": [ { @@ -471,7 +471,7 @@ TEST_F(WebRPCServerHandlerTest, HTTPErrorPath) EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); EXPECT_CALL( - dosguard, request(session->clientIp(), boost::json::parse(kREQUEST_JSON).as_object()) + dosguard, request(session->clientIp(), boost::json::parse(kRequestJson).as_object()) ) .WillOnce(testing::Return(true)); @@ -479,21 +479,21 @@ TEST_F(WebRPCServerHandlerTest, HTTPErrorPath) .WillOnce( testing::Return( rpc::Result{ - rpc::Status{rpc::RippledError::rpcINVALID_PARAMS, "ledgerIndexMalformed"} + rpc::Status{rpc::RippledError::RpcInvalidParams, "ledgerIndexMalformed"} } ) ); EXPECT_CALL(*etl, lastCloseAgeSeconds()).WillOnce(testing::Return(45)); - (*handler)(kREQUEST_JSON, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequestJson, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, WsErrorPath) { session->upgraded = true; - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResponse = R"JSON({ "id": "123", "error": "invalidParams", "error_code": 31, @@ -515,9 +515,9 @@ TEST_F(WebRPCServerHandlerTest, WsErrorPath) ] })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kREQUEST_JSON = R"JSON({ + static constexpr auto kRequestJson = R"JSON({ "command": "ledger", "ledger_index": "xx", "id": "123", @@ -526,7 +526,7 @@ TEST_F(WebRPCServerHandlerTest, WsErrorPath) EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); EXPECT_CALL( - dosguard, request(session->clientIp(), boost::json::parse(kREQUEST_JSON).as_object()) + dosguard, request(session->clientIp(), boost::json::parse(kRequestJson).as_object()) ) .WillOnce(testing::Return(true)); @@ -534,25 +534,25 @@ TEST_F(WebRPCServerHandlerTest, WsErrorPath) .WillOnce( testing::Return( rpc::Result{ - rpc::Status{rpc::RippledError::rpcINVALID_PARAMS, "ledgerIndexMalformed"} + rpc::Status{rpc::RippledError::RpcInvalidParams, "ledgerIndexMalformed"} } ) ); EXPECT_CALL(*etl, lastCloseAgeSeconds()).WillOnce(testing::Return(45)); - (*handler)(kREQUEST_JSON, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequestJson, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, HTTPNotReady) { - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "method": "server_info", "params": [{}] })JSON"; - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResponse = R"JSON({ "result": { "error": "notReady", "error_code": 13, @@ -567,25 +567,25 @@ TEST_F(WebRPCServerHandlerTest, HTTPNotReady) })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); - EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kREQUEST).as_object())) + EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kRequest).as_object())) .WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, notifyNotReady).Times(1); - (*handler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, WsNotReady) { session->upgraded = true; - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "command": "server_info", "id": 99 })JSON"; - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResponse = R"JSON({ "error": "notReady", "error_code": 13, "error_message": "Not ready to handle this request.", @@ -599,22 +599,22 @@ TEST_F(WebRPCServerHandlerTest, WsNotReady) })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); - EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kREQUEST).as_object())) + EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kRequest).as_object())) .WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, notifyNotReady).Times(1); - (*handler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, HTTPBadSyntaxWhenRequestSubscribe) { - static constexpr auto kREQUEST = R"JSON({"method": "subscribe"})JSON"; + static constexpr auto kRequest = R"JSON({"method": "subscribe"})JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResponse = R"JSON({ "result": { "error": "badSyntax", "error_code": 1, @@ -633,75 +633,75 @@ TEST_F(WebRPCServerHandlerTest, HTTPBadSyntaxWhenRequestSubscribe) EXPECT_CALL(*rpcEngine, notifyBadSyntax).Times(1); - (*handler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, HTTPMissingCommand) { - static constexpr auto kREQUEST = R"JSON({"method2": "server_info"})JSON"; + static constexpr auto kRequest = R"JSON({"method2": "server_info"})JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kRESPONSE = "Null method"; + static constexpr auto kResponse = "Null method"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); EXPECT_CALL(dosguard, request(session->clientIp(), testing::_)).WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, notifyBadSyntax).Times(1); - (*handler)(kREQUEST, session); - EXPECT_EQ(session->message, kRESPONSE); + (*handler)(kRequest, session); + EXPECT_EQ(session->message, kResponse); EXPECT_EQ(session->lastStatus, boost::beast::http::status::bad_request); } TEST_F(WebRPCServerHandlerTest, HTTPCommandNotString) { - static constexpr auto kREQUEST = R"JSON({"method": 1})JSON"; + static constexpr auto kRequest = R"JSON({"method": 1})JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kRESPONSE = "method is not string"; + static constexpr auto kResponse = "method is not string"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); EXPECT_CALL(dosguard, request(session->clientIp(), testing::_)).WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, notifyBadSyntax).Times(1); - (*handler)(kREQUEST, session); - EXPECT_EQ(session->message, kRESPONSE); + (*handler)(kRequest, session); + EXPECT_EQ(session->message, kResponse); EXPECT_EQ(session->lastStatus, boost::beast::http::status::bad_request); } TEST_F(WebRPCServerHandlerTest, HTTPCommandIsEmpty) { - static constexpr auto kREQUEST = R"JSON({"method": ""})JSON"; + static constexpr auto kRequest = R"JSON({"method": ""})JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kRESPONSE = "method is empty"; + static constexpr auto kResponse = "method is empty"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); EXPECT_CALL(dosguard, request(session->clientIp(), testing::_)).WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, notifyBadSyntax).Times(1); - (*handler)(kREQUEST, session); - EXPECT_EQ(session->message, kRESPONSE); + (*handler)(kRequest, session); + EXPECT_EQ(session->message, kResponse); EXPECT_EQ(session->lastStatus, boost::beast::http::status::bad_request); } TEST_F(WebRPCServerHandlerTest, WsMissingCommand) { session->upgraded = true; - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "command2": "server_info", "id": 99 })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResponse = R"JSON({ "error": "missingCommand", "error_code": 6001, "error_message": "Method/Command is not specified or is not a string.", @@ -715,22 +715,22 @@ TEST_F(WebRPCServerHandlerTest, WsMissingCommand) })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); - EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kREQUEST).as_object())) + EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kRequest).as_object())) .WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, notifyBadSyntax).Times(1); - (*handler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, HTTPParamsUnparsableNotArray) { - static constexpr auto kRESPONSE = "params unparsable"; + static constexpr auto kResponse = "params unparsable"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kREQUEST_JSON = R"JSON({ + static constexpr auto kRequestJson = R"JSON({ "method": "ledger", "params": "wrong" })JSON"; @@ -740,18 +740,18 @@ TEST_F(WebRPCServerHandlerTest, HTTPParamsUnparsableNotArray) EXPECT_CALL(*rpcEngine, notifyBadSyntax).Times(1); - (*handler)(kREQUEST_JSON, session); - EXPECT_EQ(session->message, kRESPONSE); + (*handler)(kRequestJson, session); + EXPECT_EQ(session->message, kResponse); EXPECT_EQ(session->lastStatus, boost::beast::http::status::bad_request); } TEST_F(WebRPCServerHandlerTest, HTTPParamsUnparsableArrayWithDigit) { - static constexpr auto kRESPONSE = "params unparsable"; + static constexpr auto kResponse = "params unparsable"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kREQUEST_JSON = R"JSON({ + static constexpr auto kRequestJson = R"JSON({ "method": "ledger", "params": [1] })JSON"; @@ -761,14 +761,14 @@ TEST_F(WebRPCServerHandlerTest, HTTPParamsUnparsableArrayWithDigit) EXPECT_CALL(*rpcEngine, notifyBadSyntax).Times(1); - (*handler)(kREQUEST_JSON, session); - EXPECT_EQ(session->message, kRESPONSE); + (*handler)(kRequestJson, session); + EXPECT_EQ(session->message, kResponse); EXPECT_EQ(session->lastStatus, boost::beast::http::status::bad_request); } TEST_F(WebRPCServerHandlerTest, HTTPInternalError) { - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResponse = R"JSON({ "result": { "error": "internal", "error_code": 73, @@ -782,16 +782,16 @@ TEST_F(WebRPCServerHandlerTest, HTTPInternalError) } })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kREQUEST_JSON = R"JSON({ + static constexpr auto kRequestJson = R"JSON({ "method": "ledger", "params": [{}] })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); EXPECT_CALL( - dosguard, request(session->clientIp(), boost::json::parse(kREQUEST_JSON).as_object()) + dosguard, request(session->clientIp(), boost::json::parse(kRequestJson).as_object()) ) .WillOnce(testing::Return(true)); @@ -800,15 +800,15 @@ TEST_F(WebRPCServerHandlerTest, HTTPInternalError) .Times(1) .WillOnce(testing::Throw(std::runtime_error("MyError"))); - (*handler)(kREQUEST_JSON, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequestJson, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, WsInternalError) { session->upgraded = true; - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResponse = R"JSON({ "error": "internal", "error_code": 73, "error_message": "Internal error.", @@ -821,16 +821,16 @@ TEST_F(WebRPCServerHandlerTest, WsInternalError) } })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kREQUEST_JSON = R"JSON({ + static constexpr auto kRequestJson = R"JSON({ "command": "ledger", "id": "123" })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); EXPECT_CALL( - dosguard, request(session->clientIp(), boost::json::parse(kREQUEST_JSON).as_object()) + dosguard, request(session->clientIp(), boost::json::parse(kRequestJson).as_object()) ) .WillOnce(testing::Return(true)); @@ -839,21 +839,21 @@ TEST_F(WebRPCServerHandlerTest, WsInternalError) .Times(1) .WillOnce(testing::Throw(std::runtime_error("MyError"))); - (*handler)(kREQUEST_JSON, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequestJson, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, HTTPOutDated) { - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "method": "server_info", "params": [{}] })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kRESULT = "{}"; - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResult = "{}"; + static constexpr auto kResponse = R"JSON({ "result": { "status": "success" }, @@ -870,32 +870,32 @@ TEST_F(WebRPCServerHandlerTest, HTTPOutDated) })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); - EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kREQUEST).as_object())) + EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kRequest).as_object())) .WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, buildResponse(testing::_)) - .WillOnce(testing::Return(rpc::Result{boost::json::parse(kRESULT).as_object()})); + .WillOnce(testing::Return(rpc::Result{boost::json::parse(kResult).as_object()})); EXPECT_CALL(*rpcEngine, notifyComplete("server_info", testing::_)).Times(1); EXPECT_CALL(*etl, lastCloseAgeSeconds()).WillOnce(testing::Return(61)); - (*handler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, WsOutdated) { session->upgraded = true; - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "command": "server_info", "id": 99 })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kRESULT = "{}"; - static constexpr auto kRESPONSE = R"JSON({ + static constexpr auto kResult = "{}"; + static constexpr auto kResponse = R"JSON({ "result": {}, "id": 99, "status": "success", @@ -913,17 +913,17 @@ TEST_F(WebRPCServerHandlerTest, WsOutdated) })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); - EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kREQUEST).as_object())) + EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kRequest).as_object())) .WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, buildResponse(testing::_)) - .WillOnce(testing::Return(rpc::Result{boost::json::parse(kRESULT).as_object()})); + .WillOnce(testing::Return(rpc::Result{boost::json::parse(kResult).as_object()})); EXPECT_CALL(*rpcEngine, notifyComplete("server_info", testing::_)).Times(1); EXPECT_CALL(*etl, lastCloseAgeSeconds()).WillOnce(testing::Return(61)); - (*handler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, WsTooBusy) @@ -934,14 +934,14 @@ TEST_F(WebRPCServerHandlerTest, WsTooBusy) auto localHandler = std::make_shared>( cfg, backend_, localRpcEngine, etl, dosguard ); - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "command": "server_info", "id": 99 })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kRESPONSE = + static constexpr auto kResponse = R"JSON({ "error": "tooBusy", "error_code": 9, @@ -951,14 +951,14 @@ TEST_F(WebRPCServerHandlerTest, WsTooBusy) })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); - EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kREQUEST).as_object())) + EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kRequest).as_object())) .WillOnce(testing::Return(true)); EXPECT_CALL(*localRpcEngine, notifyTooBusy).Times(1); EXPECT_CALL(*localRpcEngine, post).WillOnce(testing::Return(false)); - (*localHandler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*localHandler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, HTTPTooBusy) @@ -967,14 +967,14 @@ TEST_F(WebRPCServerHandlerTest, HTTPTooBusy) auto localHandler = std::make_shared>( cfg, backend_, localRpcEngine, etl, dosguard ); - static constexpr auto kREQUEST = R"JSON({ + static constexpr auto kRequest = R"JSON({ "method": "server_info", "params": [{}] })JSON"; - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); - static constexpr auto kRESPONSE = + static constexpr auto kResponse = R"JSON({ "error": "tooBusy", "error_code": 9, @@ -984,35 +984,35 @@ TEST_F(WebRPCServerHandlerTest, HTTPTooBusy) })JSON"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); - EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kREQUEST).as_object())) + EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(kRequest).as_object())) .WillOnce(testing::Return(true)); EXPECT_CALL(*localRpcEngine, notifyTooBusy).Times(1); EXPECT_CALL(*localRpcEngine, post).WillOnce(testing::Return(false)); - (*localHandler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*localHandler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } TEST_F(WebRPCServerHandlerTest, HTTPRequestNotJson) { - static constexpr auto kREQUEST = "not json"; - static constexpr auto kRESPONSE_PREFIX = "Unable to parse JSON from the request"; + static constexpr auto kRequest = "not json"; + static constexpr auto kResponsePrefix = "Unable to parse JSON from the request"; EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); EXPECT_CALL(*rpcEngine, notifyBadSyntax).Times(1); - (*handler)(kREQUEST, session); - EXPECT_THAT(session->message, testing::StartsWith(kRESPONSE_PREFIX)); + (*handler)(kRequest, session); + EXPECT_THAT(session->message, testing::StartsWith(kResponsePrefix)); EXPECT_EQ(session->lastStatus, boost::beast::http::status::bad_request); } TEST_F(WebRPCServerHandlerTest, WsRequestNotJson) { session->upgraded = true; - static constexpr auto kREQUEST = "not json"; - static constexpr auto kRESPONSE = + static constexpr auto kRequest = "not json"; + static constexpr auto kResponse = R"JSON({ "error": "badSyntax", "error_code": 1, @@ -1025,8 +1025,8 @@ TEST_F(WebRPCServerHandlerTest, WsRequestNotJson) EXPECT_CALL(*rpcEngine, notifyBadSyntax).Times(1); - (*handler)(kREQUEST, session); - EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kRESPONSE)); + (*handler)(kRequest, session); + EXPECT_EQ(boost::json::parse(session->message), boost::json::parse(kResponse)); } struct InvalidAPIVersionTestBundle { @@ -1047,12 +1047,12 @@ generateInvalidVersions() {.testName = "v0", .version = "0", .wsMessage = fmt::format( - "Requested API version is lower than minimum supported ({})", rpc::kAPI_VERSION_MIN + "Requested API version is lower than minimum supported ({})", rpc::kApiVersionMin )}, {.testName = "v4", .version = "4", .wsMessage = fmt::format( - "Requested API version is higher than maximum supported ({})", rpc::kAPI_VERSION_MAX + "Requested API version is higher than maximum supported ({})", rpc::kApiVersionMax )}, {.testName = "null", .version = "null", .wsMessage = "API version must be an integer"}, {.testName = "str", .version = "\"bogus\"", .wsMessage = "API version must be an integer"}, @@ -1065,7 +1065,7 @@ INSTANTIATE_TEST_CASE_P( WebRPCServerHandlerAPIVersionGroup, WebRPCServerHandlerInvalidAPIVersionParamTest, testing::ValuesIn(generateInvalidVersions()), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_P(WebRPCServerHandlerInvalidAPIVersionParamTest, HTTPInvalidAPIVersion) @@ -1080,7 +1080,7 @@ TEST_P(WebRPCServerHandlerInvalidAPIVersionParamTest, HTTPInvalidAPIVersion) GetParam().version ); - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(request).as_object())) @@ -1104,7 +1104,7 @@ TEST_P(WebRPCServerHandlerInvalidAPIVersionParamTest, WSInvalidAPIVersion) GetParam().version ); - backend_->setRange(kMIN_SEQ, kMAX_SEQ); + backend_->setRange(kMinSeq, kMaxSeq); EXPECT_CALL(dosguard, isOk(session->clientIp())).WillOnce(testing::Return(true)); EXPECT_CALL(dosguard, request(session->clientIp(), boost::json::parse(request).as_object())) diff --git a/tests/unit/web/ServerTests.cpp b/tests/unit/web/ServerTests.cpp index ad389502f..d3a9aef60 100644 --- a/tests/unit/web/ServerTests.cpp +++ b/tests/unit/web/ServerTests.cpp @@ -518,7 +518,7 @@ jsonServerConfigWithNoSpecifiedAdmin(uint32_t const port) } // get this value from online sha256 generator -constexpr auto kSECRET_SHA256 = "2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b"; +constexpr auto kSecretShA256 = "2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b"; } // namespace @@ -630,7 +630,7 @@ INSTANTIATE_TEST_CASE_P( }, WebServerAdminTestParams{ .config = jsonServerConfigWithAdminPassword(tests::util::generateFreePort()), - .headers = {WebHeader(http::field::authorization, kSECRET_SHA256)}, + .headers = {WebHeader(http::field::authorization, kSecretShA256)}, .expectedResponse = "user" }, WebServerAdminTestParams{ @@ -639,8 +639,8 @@ INSTANTIATE_TEST_CASE_P( http::field::authorization, fmt::format( "{}{}", - PasswordAdminVerificationStrategy::kPASSWORD_PREFIX, - kSECRET_SHA256 + PasswordAdminVerificationStrategy::kPasswordPrefix, + kSecretShA256 ) )}, .expectedResponse = "admin" @@ -649,7 +649,7 @@ INSTANTIATE_TEST_CASE_P( .config = jsonServerConfigWithBothAdminPasswordAndLocalAdminFalse( tests::util::generateFreePort() ), - .headers = {WebHeader(http::field::authorization, kSECRET_SHA256)}, + .headers = {WebHeader(http::field::authorization, kSecretShA256)}, .expectedResponse = "user" }, WebServerAdminTestParams{ @@ -660,8 +660,8 @@ INSTANTIATE_TEST_CASE_P( http::field::authorization, fmt::format( "{}{}", - PasswordAdminVerificationStrategy::kPASSWORD_PREFIX, - kSECRET_SHA256 + PasswordAdminVerificationStrategy::kPasswordPrefix, + kSecretShA256 ) )}, .expectedResponse = "admin" @@ -669,11 +669,11 @@ INSTANTIATE_TEST_CASE_P( WebServerAdminTestParams{ .config = jsonServerConfigWithAdminPassword(tests::util::generateFreePort()), .headers = {WebHeader( - http::field::authentication_info, + http::field::accept, fmt::format( "{}{}", - PasswordAdminVerificationStrategy::kPASSWORD_PREFIX, - kSECRET_SHA256 + PasswordAdminVerificationStrategy::kPasswordPrefix, + kSecretShA256 ) )}, .expectedResponse = "user" @@ -712,7 +712,7 @@ TEST_F(WebServerTest, AdminErrorCfgTestBothAdminPasswordAndLocalAdminSet) boost::json::parse(jsonServerConfigWithBothAdminPasswordAndLocalAdmin) )}; - MockLedgerCache cache; + MockLedgerCache const cache; auto const result = web::makeHttpServer(serverConfig, ctx, dosGuardOverload, e, cache); EXPECT_FALSE(result.has_value()); } @@ -736,7 +736,7 @@ TEST_F(WebServerTest, AdminErrorCfgTestBothAdminPasswordAndLocalAdminFalse) boost::json::parse(jsonServerConfigWithNoAdminPasswordAndLocalAdminFalse) )}; - MockLedgerCache cache; + MockLedgerCache const cache; auto const result = web::makeHttpServer(serverConfig, ctx, dosGuardOverload, e, cache); EXPECT_FALSE(result.has_value()); } @@ -789,7 +789,7 @@ TEST_F(WebServerPrometheusDisabledTest, rejectedIfPrometheusIsDisabled) "/metrics", {WebHeader( http::field::authorization, - fmt::format("{}{}", PasswordAdminVerificationStrategy::kPASSWORD_PREFIX, kSECRET_SHA256) + fmt::format("{}{}", PasswordAdminVerificationStrategy::kPasswordPrefix, kSecretShA256) )} ); EXPECT_EQ(res, "Prometheus is disabled in clio config"); @@ -814,7 +814,7 @@ TEST_F(WebServerPrometheusTest, validResponse) "/metrics", {WebHeader( http::field::authorization, - fmt::format("{}{}", PasswordAdminVerificationStrategy::kPASSWORD_PREFIX, kSECRET_SHA256) + fmt::format("{}{}", PasswordAdminVerificationStrategy::kPasswordPrefix, kSecretShA256) )} ); EXPECT_EQ(res, "# TYPE test_counter counter\ntest_counter 1\n\n"); diff --git a/tests/unit/web/dosguard/DOSGuardTests.cpp b/tests/unit/web/dosguard/DOSGuardTests.cpp index edf362051..d1586edaf 100644 --- a/tests/unit/web/dosguard/DOSGuardTests.cpp +++ b/tests/unit/web/dosguard/DOSGuardTests.cpp @@ -21,7 +21,7 @@ using namespace util::config; using namespace web::dosguard; struct DOSGuardTest : public virtual ::testing::Test { - static constexpr auto kJSON_DATA = R"JSON({ + static constexpr auto kJsonData = R"JSON({ "dos_guard": { "max_fetches": 100, "max_connections": 2, diff --git a/tests/unit/web/dosguard/IntervalSweepHandlerTests.cpp b/tests/unit/web/dosguard/IntervalSweepHandlerTests.cpp index 714834c93..15f770286 100644 --- a/tests/unit/web/dosguard/IntervalSweepHandlerTests.cpp +++ b/tests/unit/web/dosguard/IntervalSweepHandlerTests.cpp @@ -15,7 +15,7 @@ using namespace util::config; struct IntervalSweepHandlerTest : SyncAsioContextTest { protected: - static constexpr auto kJSON_DATA = R"JSON( + static constexpr auto kJsonData = R"JSON( { "dos_guard": { "sweep_interval": 0 diff --git a/tests/unit/web/dosguard/WhitelistHandlerTests.cpp b/tests/unit/web/dosguard/WhitelistHandlerTests.cpp index c3d3e8ed7..5a56c6d8a 100644 --- a/tests/unit/web/dosguard/WhitelistHandlerTests.cpp +++ b/tests/unit/web/dosguard/WhitelistHandlerTests.cpp @@ -42,7 +42,7 @@ TEST_F(WhitelistHandlerTest, TestWhiteListIPV4) testing::StrictMock mockResolver; - static constexpr auto kJSON_DATA_IP_V4 = R"JSON( + static constexpr auto kJsonDataIpV4 = R"JSON( { "dos_guard": { "whitelist": [ @@ -61,7 +61,7 @@ TEST_F(WhitelistHandlerTest, TestWhiteListIPV4) }); ClioConfigDefinition const cfg{ - getParseWhitelistHandlerConfig(boost::json::parse(kJSON_DATA_IP_V4)) + getParseWhitelistHandlerConfig(boost::json::parse(kJsonDataIpV4)) }; auto const result = WhitelistHandler::create(cfg, mockResolver); ASSERT_TRUE(result.has_value()); @@ -75,7 +75,7 @@ TEST_F(WhitelistHandlerTest, TestWhiteListIPV4) TEST_F(WhitelistHandlerTest, TestWhiteListResolvesHostname) { - static constexpr auto kJSON_DATA_IP_V4 = R"JSON( + static constexpr auto kJsonDataIpV4 = R"JSON( { "dos_guard": { "whitelist": [ @@ -87,7 +87,7 @@ TEST_F(WhitelistHandlerTest, TestWhiteListResolvesHostname) )JSON"; ClioConfigDefinition const cfg{ - getParseWhitelistHandlerConfig(boost::json::parse(kJSON_DATA_IP_V4)) + getParseWhitelistHandlerConfig(boost::json::parse(kJsonDataIpV4)) }; auto const result = WhitelistHandler::create(cfg); ASSERT_TRUE(result.has_value()); @@ -101,7 +101,7 @@ TEST_F(WhitelistHandlerTest, TestWhiteListResolvesHostname) TEST_F(WhitelistHandlerTest, TestWhiteListIPV6) { - static constexpr auto kJSON_DATA_IP_V6 = R"JSON( + static constexpr auto kJsonDataIpV6 = R"JSON( { "dos_guard": { "whitelist": [ @@ -113,7 +113,7 @@ TEST_F(WhitelistHandlerTest, TestWhiteListIPV6) )JSON"; ClioConfigDefinition const cfg{ - getParseWhitelistHandlerConfig(boost::json::parse(kJSON_DATA_IP_V6)) + getParseWhitelistHandlerConfig(boost::json::parse(kJsonDataIpV6)) }; auto const result = WhitelistHandler::create(cfg); ASSERT_TRUE(result.has_value()); @@ -162,7 +162,7 @@ TEST_F(WhitelistHandlerTest, CreateWithInvalidIPFails) MOCK_METHOD(std::vector, resolve, (std::string_view)); }; - static constexpr auto kJSON = R"JSON( + static constexpr auto kJson = R"JSON( { "dos_guard": { "whitelist": ["not-an-ip"] @@ -176,7 +176,7 @@ TEST_F(WhitelistHandlerTest, CreateWithInvalidIPFails) return {std::string{hostname}}; }); - ClioConfigDefinition const cfg{getParseWhitelistHandlerConfig(boost::json::parse(kJSON))}; + ClioConfigDefinition const cfg{getParseWhitelistHandlerConfig(boost::json::parse(kJson))}; auto const result = WhitelistHandler::create(cfg, mockResolver); ASSERT_FALSE(result.has_value()); EXPECT_THAT(result.error(), testing::HasSubstr("not-an-ip")); diff --git a/tests/unit/web/impl/ErrorHandlingTests.cpp b/tests/unit/web/impl/ErrorHandlingTests.cpp index b85b8754f..6b36c4cee 100644 --- a/tests/unit/web/impl/ErrorHandlingTests.cpp +++ b/tests/unit/web/impl/ErrorHandlingTests.cpp @@ -46,7 +46,7 @@ TEST_P(ErrorHandlingComposeErrorTest, composeError) { connection_->upgraded = GetParam().connectionUpgraded; ErrorHelper const errorHelper{connection_, GetParam().request}; - auto const result = errorHelper.composeError(rpc::RippledError::rpcNOT_READY); + auto const result = errorHelper.composeError(rpc::RippledError::RpcNotReady); EXPECT_EQ(boost::json::serialize(result), boost::json::serialize(GetParam().expectedResult)); } @@ -102,7 +102,7 @@ INSTANTIATE_TEST_CASE_P( {"request", {{"id", 1}, {"api_version", 2}}}}}} }} ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); struct ErrorHandlingSendErrorTestBundle { @@ -135,7 +135,7 @@ INSTANTIATE_TEST_CASE_P( ErrorHandlingSendErrorTestBundle{ "UpgradedConnection", true, - rpc::Status{rpc::RippledError::rpcTOO_BUSY}, + rpc::Status{rpc::RippledError::RpcTooBusy}, R"JSON({"error":"tooBusy","error_code":9,"error_message":"The server is too busy to help you now.","status":"error","type":"response"})JSON", boost::beast::http::status::ok }, @@ -177,12 +177,12 @@ INSTANTIATE_TEST_CASE_P( ErrorHandlingSendErrorTestBundle{ "NotUpgradedConnection_RippledError", false, - rpc::Status{rpc::RippledError::rpcTOO_BUSY}, + rpc::Status{rpc::RippledError::RpcTooBusy}, R"JSON({"result":{"error":"tooBusy","error_code":9,"error_message":"The server is too busy to help you now.","status":"error","type":"response"}})JSON", boost::beast::http::status::bad_request }, }), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_F(ErrorHandlingTests, sendInternalError) diff --git a/tests/unit/web/ng/RPCServerHandlerTests.cpp b/tests/unit/web/ng/RPCServerHandlerTests.cpp index ee06d0e59..3a0f9c79a 100644 --- a/tests/unit/web/ng/RPCServerHandlerTests.cpp +++ b/tests/unit/web/ng/RPCServerHandlerTests.cpp @@ -20,7 +20,6 @@ #include #include #include -#include #include #include #include @@ -93,7 +92,7 @@ TEST_F(NgRpcServerHandlerTest, DosguardRejectedHttpRequest) EXPECT_EQ(responseHttp.result(), http::status::service_unavailable); auto const responseJson = boost::json::parse(responseHttp.body()).as_object(); - EXPECT_EQ(responseJson.at("error_code").as_int64(), rpc::RippledError::rpcSLOW_DOWN); + EXPECT_EQ(responseJson.at("error_code").as_int64(), rpc::RippledError::RpcSlowDown); }); } @@ -109,7 +108,7 @@ TEST_F(NgRpcServerHandlerTest, DosguardRejectedWsRequest) auto const responseWs = boost::beast::buffers_to_string(response.asWsResponse()); auto const responseJson = boost::json::parse(responseWs).as_object(); - EXPECT_EQ(responseJson.at("error_code").as_int64(), rpc::RippledError::rpcSLOW_DOWN); + EXPECT_EQ(responseJson.at("error_code").as_int64(), rpc::RippledError::RpcSlowDown); EXPECT_EQ(responseJson.at("request").as_string(), requestStr); }); } @@ -126,7 +125,7 @@ TEST_F(NgRpcServerHandlerTest, DosguardRejectedWsJsonRequest) auto const responseWs = boost::beast::buffers_to_string(response.asWsResponse()); auto const responseJson = boost::json::parse(responseWs).as_object(); - EXPECT_EQ(responseJson.at("error_code").as_int64(), rpc::RippledError::rpcSLOW_DOWN); + EXPECT_EQ(responseJson.at("error_code").as_int64(), rpc::RippledError::RpcSlowDown); EXPECT_EQ(responseJson.at("request").as_string(), requestStr); EXPECT_EQ(responseJson.at("id").as_string(), "some id"); }); @@ -218,7 +217,7 @@ TEST_F(NgRpcServerHandlerTest, DosguardRejectedParsedRequest) EXPECT_EQ(responseHttp.result(), http::status::service_unavailable); auto const responseJson = boost::json::parse(responseHttp.body()).as_object(); - EXPECT_EQ(responseJson.at("error_code").as_int64(), rpc::RippledError::rpcSLOW_DOWN); + EXPECT_EQ(responseJson.at("error_code").as_int64(), rpc::RippledError::RpcSlowDown); }); } @@ -242,7 +241,7 @@ TEST_F(NgRpcServerHandlerTest, DosguardAddsLoadWarning) EXPECT_EQ(responseHttp.result(), http::status::service_unavailable); auto const responseJson = boost::json::parse(responseHttp.body()).as_object(); - EXPECT_EQ(responseJson.at("error_code").as_int64(), rpc::RippledError::rpcSLOW_DOWN); + EXPECT_EQ(responseJson.at("error_code").as_int64(), rpc::RippledError::RpcSlowDown); EXPECT_EQ(responseJson.at("warning").as_string(), "load"); EXPECT_EQ( diff --git a/tests/unit/web/ng/RequestTests.cpp b/tests/unit/web/ng/RequestTests.cpp index 7bce2bd36..a19c88578 100644 --- a/tests/unit/web/ng/RequestTests.cpp +++ b/tests/unit/web/ng/RequestTests.cpp @@ -3,7 +3,6 @@ #include #include -#include #include #include @@ -16,9 +15,9 @@ using namespace web::ng; namespace http = boost::beast::http; struct RequestTest : public ::testing::Test { - static Request::HttpHeaders const kHEADERS; + static Request::HttpHeaders const kHeaders; }; -Request::HttpHeaders const RequestTest::kHEADERS = {}; +Request::HttpHeaders const RequestTest::kHeaders = {}; struct RequestMethodTestBundle { std::string testName; @@ -49,7 +48,7 @@ INSTANTIATE_TEST_SUITE_P( }, RequestMethodTestBundle{ .testName = "WebSocket", - .request = Request{"websocket message", RequestTest::kHEADERS}, + .request = Request{"websocket message", RequestTest::kHeaders}, .expectedMethod = Request::Method::Websocket, }, RequestMethodTestBundle{ @@ -58,7 +57,7 @@ INSTANTIATE_TEST_SUITE_P( .expectedMethod = Request::Method::Unsupported, } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); struct RequestIsHttpTestBundle { @@ -85,11 +84,11 @@ INSTANTIATE_TEST_SUITE_P( }, RequestIsHttpTestBundle{ .testName = "WebSocketRequest", - .request = Request{"websocket message", RequestTest::kHEADERS}, + .request = Request{"websocket message", RequestTest::kHeaders}, .expectedIsHttp = false, } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); struct RequestAsHttpRequestTest : RequestTest {}; @@ -109,7 +108,7 @@ TEST_F(RequestAsHttpRequestTest, HttpRequest) TEST_F(RequestAsHttpRequestTest, WebSocketRequest) { - Request const request{"websocket message", RequestTest::kHEADERS}; + Request const request{"websocket message", RequestTest::kHeaders}; auto const maybeHttpRequest = request.asHttpRequest(); EXPECT_FALSE(maybeHttpRequest.has_value()); } @@ -127,7 +126,7 @@ TEST_F(RequestMessageTest, HttpRequest) TEST_F(RequestMessageTest, WebSocketRequest) { std::string const message = "websocket message"; - Request const request{message, RequestTest::kHEADERS}; + Request const request{message, RequestTest::kHeaders}; EXPECT_EQ(request.message(), message); } @@ -156,11 +155,11 @@ INSTANTIATE_TEST_SUITE_P( }, RequestTargetTestBundle{ .testName = "WebSocketRequest", - .request = Request{"websocket message", RequestTest::kHEADERS}, + .request = Request{"websocket message", RequestTest::kHeaders}, .expectedTarget = std::nullopt, } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); struct RequestHttpHeadersTest : RequestTest { diff --git a/tests/unit/web/ng/ResponseTests.cpp b/tests/unit/web/ng/ResponseTests.cpp index 368a19720..038ccaf27 100644 --- a/tests/unit/web/ng/ResponseTests.cpp +++ b/tests/unit/web/ng/ResponseTests.cpp @@ -12,7 +12,6 @@ #include #include #include -#include #include #include #include diff --git a/tests/unit/web/ng/ServerTests.cpp b/tests/unit/web/ng/ServerTests.cpp index 36cd6a260..21faffebd 100644 --- a/tests/unit/web/ng/ServerTests.cpp +++ b/tests/unit/web/ng/ServerTests.cpp @@ -27,7 +27,6 @@ #include #include #include -#include #include #include #include @@ -140,7 +139,7 @@ INSTANTIATE_TEST_CASE_P( true } ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); struct ServerTest : util::prometheus::WithPrometheus, SyncAsioContextTest { @@ -567,7 +566,7 @@ INSTANTIATE_TEST_SUITE_P( ServerHttpTestBundle{"GET", http::verb::get}, ServerHttpTestBundle{"POST", http::verb::post} ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_F(ServerTest, WsClientDisconnects) diff --git a/tests/unit/web/ng/impl/ConnectionHandlerTests.cpp b/tests/unit/web/ng/impl/ConnectionHandlerTests.cpp index 31d8f5b4f..28d4cb155 100644 --- a/tests/unit/web/ng/impl/ConnectionHandlerTests.cpp +++ b/tests/unit/web/ng/impl/ConnectionHandlerTests.cpp @@ -25,7 +25,6 @@ #include #include #include -#include #include #include #include @@ -149,9 +148,7 @@ TEST_F(ConnectionHandlerSequentialProcessingTest, ReceiveError_CloseConnection) .WillOnce(Return(makeError(boost::asio::error::timed_out))); EXPECT_CALL( *mockHttpConnection, - setTimeout( - std::chrono::steady_clock::duration{ConnectionHandler::kCLOSE_CONNECTION_TIMEOUT} - ) + setTimeout(std::chrono::steady_clock::duration{ConnectionHandler::kCloseConnectionTimeout}) ); EXPECT_CALL(*mockHttpConnection, close); EXPECT_CALL(onDisconnectMock, Call) @@ -424,9 +421,7 @@ TEST_F(ConnectionHandlerSequentialProcessingTest, SubscriptionContextIsNullForHt EXPECT_CALL( *mockHttpConnection, - setTimeout( - std::chrono::steady_clock::duration{ConnectionHandler::kCLOSE_CONNECTION_TIMEOUT} - ) + setTimeout(std::chrono::steady_clock::duration{ConnectionHandler::kCloseConnectionTimeout}) ); EXPECT_CALL(*mockHttpConnection, close); @@ -484,9 +479,7 @@ TEST_F(ConnectionHandlerSequentialProcessingTest, Receive_Handle_Send_Loop) EXPECT_CALL( *mockHttpConnection, - setTimeout( - std::chrono::steady_clock::duration{ConnectionHandler::kCLOSE_CONNECTION_TIMEOUT} - ) + setTimeout(std::chrono::steady_clock::duration{ConnectionHandler::kCloseConnectionTimeout}) ); EXPECT_CALL(*mockHttpConnection, close); @@ -759,9 +752,7 @@ TEST_F(ConnectionHandlerSequentialProcessingTest, Stop) EXPECT_CALL( *mockWsConnection, - setTimeout( - std::chrono::steady_clock::duration{ConnectionHandler::kCLOSE_CONNECTION_TIMEOUT} - ) + setTimeout(std::chrono::steady_clock::duration{ConnectionHandler::kCloseConnectionTimeout}) ); EXPECT_CALL(*mockWsConnection, close).WillOnce([&connectionClosed]() { connectionClosed = true; @@ -804,9 +795,7 @@ TEST_F(ConnectionHandlerSequentialProcessingTest, ProcessCalledAfterStop) EXPECT_CALL( *mockWsConnection, - setTimeout( - std::chrono::steady_clock::duration{ConnectionHandler::kCLOSE_CONNECTION_TIMEOUT} - ) + setTimeout(std::chrono::steady_clock::duration{ConnectionHandler::kCloseConnectionTimeout}) ); EXPECT_CALL(*mockWsConnection, close); @@ -816,12 +805,12 @@ TEST_F(ConnectionHandlerSequentialProcessingTest, ProcessCalledAfterStop) } struct ConnectionHandlerParallelProcessingTest : ConnectionHandlerTest { - static constexpr size_t kMAX_PARALLEL_REQUESTS = 3; + static constexpr size_t kMaxParallelRequests = 3; ConnectionHandlerParallelProcessingTest() : ConnectionHandlerTest( ProcessingPolicy::Parallel, - ConnectionHandlerParallelProcessingTest::kMAX_PARALLEL_REQUESTS + ConnectionHandlerParallelProcessingTest::kMaxParallelRequests ) { } diff --git a/tests/unit/web/ng/impl/ErrorHandlingTests.cpp b/tests/unit/web/ng/impl/ErrorHandlingTests.cpp index b01ff2d98..f40721c35 100644 --- a/tests/unit/web/ng/impl/ErrorHandlingTests.cpp +++ b/tests/unit/web/ng/impl/ErrorHandlingTests.cpp @@ -6,7 +6,6 @@ #include #include #include -#include #include #include #include @@ -32,8 +31,8 @@ struct NgErrorHandlingTests : public virtual ::testing::Test { http::request{http::verb::post, "/", 11, body.value_or("")} }; } - static Request::HttpHeaders const kHEADERS; - return Request{body.value_or(""), kHEADERS}; + static Request::HttpHeaders const kHeaders; + return Request{body.value_or(""), kHeaders}; } }; @@ -75,7 +74,7 @@ INSTANTIATE_TEST_CASE_P( NgErrorHandlingMakeErrorTestBundle{ "WsRequest", false, - rpc::Status{rpc::RippledError::rpcTOO_BUSY}, + rpc::Status{rpc::RippledError::RpcTooBusy}, R"JSON({"error":"tooBusy","error_code":9,"error_message":"The server is too busy to help you now.","status":"error","type":"response"})JSON", boost::beast::http::status::ok }, @@ -117,12 +116,12 @@ INSTANTIATE_TEST_CASE_P( NgErrorHandlingMakeErrorTestBundle{ "HttpRequest_RippledError", true, - rpc::Status{rpc::RippledError::rpcTOO_BUSY}, + rpc::Status{rpc::RippledError::RpcTooBusy}, R"JSON({"result":{"error":"tooBusy","error_code":9,"error_message":"The server is too busy to help you now.","status":"error","type":"response"}})JSON", boost::beast::http::status::bad_request }, }), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); struct NgErrorHandlingMakeInternalErrorTestBundle { @@ -219,7 +218,7 @@ INSTANTIATE_TEST_CASE_P( {"request", {{"id", 1}, {"api_version", 2}}}}}} }} ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); TEST_F(NgErrorHandlingTests, MakeNotReadyError) @@ -301,7 +300,7 @@ TEST_P(NgErrorHandlingComposeErrorTest, ComposeError) { auto const request = makeRequest(GetParam().isHttp); ErrorHelper const errorHelper{request, GetParam().request}; - auto const response = errorHelper.composeError(rpc::Status{rpc::RippledError::rpcINTERNAL}); + auto const response = errorHelper.composeError(rpc::Status{rpc::RippledError::RpcInternal}); EXPECT_EQ(boost::json::serialize(response), GetParam().expectedMessage); } @@ -340,5 +339,5 @@ INSTANTIATE_TEST_CASE_P( R"JSON({"result":{"error":"internal","error_code":73,"error_message":"Internal error.","status":"error","type":"response","id":1,"request":{"id":1,"api_version":2}}})JSON" }} ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); diff --git a/tests/unit/web/ng/impl/HttpConnectionTests.cpp b/tests/unit/web/ng/impl/HttpConnectionTests.cpp index bbe8e7728..c573f9473 100644 --- a/tests/unit/web/ng/impl/HttpConnectionTests.cpp +++ b/tests/unit/web/ng/impl/HttpConnectionTests.cpp @@ -17,7 +17,6 @@ #include #include #include -#include #include #include #include diff --git a/tests/unit/web/ng/impl/ServerSslContextTests.cpp b/tests/unit/web/ng/impl/ServerSslContextTests.cpp index fb324c563..78fe4b479 100644 --- a/tests/unit/web/ng/impl/ServerSslContextTests.cpp +++ b/tests/unit/web/ng/impl/ServerSslContextTests.cpp @@ -101,7 +101,7 @@ INSTANTIATE_TEST_SUITE_P( .expectContext = false }} ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator ); struct MakeServerSslContextFromConfigRealFilesTest : testing::Test {}; @@ -178,5 +178,5 @@ INSTANTIATE_TEST_SUITE_P( .expectedSuccess = true }} ), - tests::util::kNAME_GENERATOR + tests::util::kNameGenerator );